lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
76ea6e213607bf82f8b8215300f709e664e35546
0
jeluard/semantic-versioning,sgothel/semantic-versioning
/** * Copyright 2012-2014 Julien Eluard and contributors * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osjava.jardiff; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeSet; import java.util.TreeMap; import java.util.jar.JarEntry; import java.util.jar.JarFile; /* import javax.xml.transform.ErrorListener; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; */ import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; /** * A class to perform a diff between two jar files. * * @author <a href="mailto:[email protected]">Antony Riley</a> */ public class JarDiff { /** * A map containing information about classes which are dependencies. * Keys are internal class names. * Values are instances of ClassInfo. */ protected Map depClassInfo = new HashMap(); /** * A map containing information about classes in the old jar file. * Keys are internal class names. * Values are instances of ClassInfo. */ protected Map oldClassInfo = new TreeMap(); /** * A map containing information about classes in the new jar file. * Keys are internal class names. * Values are instances of ClassInfo. */ protected Map newClassInfo = new TreeMap(); /** * An array of dependencies which are jar files, or urls. */ private URL[] deps; /** * A class loader used for loading dependency classes. */ private URLClassLoader depLoader; /** * The name of the old version. */ private String oldVersion; /** * The name of the new version. */ private String newVersion; /** * Class info visitor, used to load information about classes. */ private ClassInfoVisitor infoVisitor = new ClassInfoVisitor(); /** * Create a new JarDiff object. */ public JarDiff() { } /** * Set the name of the old version. * * @param oldVersion the name */ public void setOldVersion(String oldVersion) { this.oldVersion = oldVersion; } /** * Get the name of the old version. * * @return the name */ public String getOldVersion() { return oldVersion; } /** * Set the name of the new version. * * @param newVersion the version */ public void setNewVersion(String newVersion) { this.newVersion = newVersion; } /** * Get the name of the new version. * * @return the name */ public String getNewVersion() { return newVersion; } /** * Set the dependencies. * * @param deps an array of urls pointing to jar files or directories * containing classes which are required dependencies. */ public void setDependencies(URL[] deps) { this.deps = deps; } /** * Get the dependencies. * * @return the dependencies as an array of URLs */ public URL[] getDependencies() { return deps; } /** * Load classinfo given a ClassReader. * * @param reader the ClassReader * @return the ClassInfo */ private synchronized ClassInfo loadClassInfo(ClassReader reader) throws IOException { infoVisitor.reset(); reader.accept(infoVisitor, 0); return infoVisitor.getClassInfo(); } /** * Load all the classes from the specified URL and store information * about them in the specified map. * This currently only works for jar files, <b>not</b> directories * which contain classes in subdirectories or in the current directory. * * @param infoMap the map to store the ClassInfo in. * @throws DiffException if there is an exception reading info about a * class. */ private void loadClasses(Map infoMap, URL path) throws DiffException { try { File jarFile = null; if(!"file".equals(path.getProtocol()) || path.getHost() != null) { // If it's not a local file, store it as a temporary jar file. // java.util.jar.JarFile requires a local file handle. jarFile = File.createTempFile("jardiff","jar"); // Mark it to be deleted on exit. jarFile.deleteOnExit(); InputStream in = path.openStream(); OutputStream out = new FileOutputStream(jarFile); byte[] buffer = new byte[4096]; int i; while( (i = in.read(buffer,0,buffer.length)) != -1) { out.write(buffer, 0, i); } in.close(); out.close(); } else { // Else it's a local file, nothing special to do. jarFile = new File(path.getPath()); } loadClasses(infoMap, jarFile); } catch (IOException ioe) { throw new DiffException(ioe); } } /** * Load all the classes from the specified URL and store information * about them in the specified map. * This currently only works for jar files, <b>not</b> directories * which contain classes in subdirectories or in the current directory. * * @param infoMap the map to store the ClassInfo in. * @param file the jarfile to load classes from. * @throws IOException if there is an IOException reading info about a * class. */ private void loadClasses(Map infoMap, File file) throws DiffException { try { JarFile jar = new JarFile(file); Enumeration e = jar.entries(); while (e.hasMoreElements()) { JarEntry entry = (JarEntry) e.nextElement(); String name = entry.getName(); if (!entry.isDirectory() && name.endsWith(".class")) { ClassReader reader = new ClassReader(jar.getInputStream(entry)); ClassInfo ci = loadClassInfo(reader); infoMap.put(ci.getName(), ci); } } } catch (IOException ioe) { throw new DiffException(ioe); } } /** * Load old classes from the specified URL. * * @param loc The location of a jar file to load classes from. * @throws DiffException if there is an IOException. */ public void loadOldClasses(URL loc) throws DiffException { loadClasses(oldClassInfo, loc); } /** * Load new classes from the specified URL. * * @param loc The location of a jar file to load classes from. * @throws DiffException if there is an IOException. */ public void loadNewClasses(URL loc) throws DiffException { loadClasses(newClassInfo, loc); } /** * Load old classes from the specified File. * * @param file The location of a jar file to load classes from. * @throws DiffException if there is an IOException */ public void loadOldClasses(File file) throws DiffException { loadClasses(oldClassInfo, file); } /** * Load new classes from the specified File. * * @param file The location of a jar file to load classes from. * @throws DiffException if there is an IOException */ public void loadNewClasses(File file) throws DiffException { loadClasses(newClassInfo, file); } /** * Perform a diff sending the output to the specified handler, using * the specified criteria to select diffs. * * @param handler The handler to receive and handle differences. * @param criteria The criteria we use to select differences. * @throws DiffException when there is an underlying exception, e.g. * writing to a file caused an IOException */ public void diff(DiffHandler handler, DiffCriteria criteria) throws DiffException { diff(handler, criteria, oldVersion, newVersion, oldClassInfo, newClassInfo); } private void diff(DiffHandler handler, DiffCriteria criteria, String oldVersion, String newVersion, Map oldClassInfo, Map newClassInfo) throws DiffException { // TODO: Build the name from the MANIFEST rather than the filename handler.startDiff(oldVersion, newVersion); Iterator i; handler.startOldContents(); i = oldClassInfo.entrySet().iterator(); while(i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); ClassInfo ci = (ClassInfo) entry.getValue(); if(criteria.validClass(ci)) { handler.contains(ci); } } handler.endOldContents(); handler.startNewContents(); i = newClassInfo.entrySet().iterator(); while(i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); ClassInfo ci = (ClassInfo) entry.getValue(); if(criteria.validClass(ci)) { handler.contains(ci); } } handler.endNewContents(); java.util.Set onlyOld = new TreeSet(oldClassInfo.keySet()); java.util.Set onlyNew = new TreeSet(newClassInfo.keySet()); java.util.Set both = new TreeSet(oldClassInfo.keySet()); onlyOld.removeAll(newClassInfo.keySet()); onlyNew.removeAll(oldClassInfo.keySet()); both.retainAll(newClassInfo.keySet()); handler.startRemoved(); i = onlyOld.iterator(); while (i.hasNext()) { String s = (String) i.next(); ClassInfo ci = (ClassInfo) oldClassInfo.get(s); if (criteria.validClass(ci)) handler.classRemoved(ci); } handler.endRemoved(); handler.startAdded(); i = onlyNew.iterator(); while (i.hasNext()) { String s = (String) i.next(); ClassInfo ci = (ClassInfo) newClassInfo.get(s); if (criteria.validClass(ci)) handler.classAdded(ci); } handler.endAdded(); java.util.Set removedMethods = new TreeSet(); java.util.Set removedFields = new TreeSet(); java.util.Set addedMethods = new TreeSet(); java.util.Set addedFields = new TreeSet(); java.util.Set changedMethods = new TreeSet(); java.util.Set changedFields = new TreeSet(); handler.startChanged(); i = both.iterator(); while (i.hasNext()) { String s = (String) i.next(); ClassInfo oci = (ClassInfo) oldClassInfo.get(s); ClassInfo nci = (ClassInfo) newClassInfo.get(s); if (criteria.validClass(oci) || criteria.validClass(nci)) { Map oldMethods = oci.getMethodMap(); Map oldFields = oci.getFieldMap(); Map extOldMethods = new HashMap(oldMethods); Map extOldFields = new HashMap(oldFields); String superClass = oci.getSupername(); while (superClass != null && oldClassInfo.containsKey(superClass)) { ClassInfo sci = (ClassInfo) oldClassInfo.get(superClass); Iterator j = sci.getFieldMap().entrySet().iterator(); while (j.hasNext()) { Map.Entry entry = (Map.Entry) j.next(); if (!((FieldInfo)entry.getValue()).isPrivate() && !extOldFields.containsKey(entry.getKey())) { extOldFields.put(entry.getKey(), entry.getValue()); } } j = sci.getMethodMap().entrySet().iterator(); while (j.hasNext()) { Map.Entry entry = (Map.Entry) j.next(); if (!((MethodInfo)entry.getValue()).isPrivate() && !extOldMethods.containsKey(entry.getKey())) { extOldMethods.put(entry.getKey(), entry.getValue()); } } superClass = sci.getSupername(); } Map newMethods = nci.getMethodMap(); Map newFields = nci.getFieldMap(); Iterator j = oldMethods.entrySet().iterator(); while (j.hasNext()) { Map.Entry entry = (Map.Entry) j.next(); if (criteria.validMethod((MethodInfo) entry.getValue())) removedMethods.add(entry.getKey()); } j = oldFields.entrySet().iterator(); while (j.hasNext()) { Map.Entry entry = (Map.Entry) j.next(); if (criteria.validField((FieldInfo) entry.getValue())) removedFields.add(entry.getKey()); } j = newMethods.entrySet().iterator(); while (j.hasNext()) { Map.Entry entry = (Map.Entry) j.next(); if (criteria.validMethod((MethodInfo) entry.getValue())) addedMethods.add(entry.getKey()); } j = newFields.entrySet().iterator(); while (j.hasNext()) { Map.Entry entry = (Map.Entry) j.next(); if (criteria.validField((FieldInfo) entry.getValue())) addedFields.add(entry.getKey()); } changedMethods.addAll(removedMethods); changedMethods.retainAll(addedMethods); removedMethods.removeAll(changedMethods); removedMethods.removeAll(extOldMethods.keySet()); addedMethods.removeAll(changedMethods); changedFields.addAll(removedFields); changedFields.retainAll(addedFields); removedFields.removeAll(changedFields); removedFields.removeAll(extOldFields.keySet()); addedFields.removeAll(changedFields); j = changedMethods.iterator(); while (j.hasNext()) { String desc = (String) j.next(); MethodInfo oldInfo = (MethodInfo) oldMethods.get(desc); MethodInfo newInfo = (MethodInfo) newMethods.get(desc); if (!criteria.differs(oldInfo, newInfo)) j.remove(); } j = changedFields.iterator(); while (j.hasNext()) { String desc = (String) j.next(); FieldInfo oldInfo = (FieldInfo) oldFields.get(desc); FieldInfo newInfo = (FieldInfo) newFields.get(desc); if (!criteria.differs(oldInfo, newInfo)) j.remove(); } boolean classchanged = criteria.differs(oci, nci); if (classchanged || !removedMethods.isEmpty() || !removedFields.isEmpty() || !addedMethods.isEmpty() || !addedFields.isEmpty() || !changedMethods.isEmpty() || !changedFields.isEmpty()) { handler.startClassChanged(s); handler.startRemoved(); j = removedFields.iterator(); while (j.hasNext()) handler .fieldRemoved((FieldInfo) oldFields.get(j.next())); j = removedMethods.iterator(); while (j.hasNext()) handler.methodRemoved((MethodInfo) oldMethods.get(j.next())); handler.endRemoved(); handler.startAdded(); j = addedFields.iterator(); while (j.hasNext()) handler .fieldAdded((FieldInfo) newFields.get(j.next())); j = addedMethods.iterator(); while (j.hasNext()) handler.methodAdded((MethodInfo) newMethods.get(j.next())); handler.endAdded(); handler.startChanged(); if (classchanged) { // Was only deprecated? if (wasDeprecated(oci, nci) && !criteria.differs(cloneDeprecated(oci), nci)) handler.classDeprecated(oci, nci); else handler.classChanged(oci, nci); } j = changedFields.iterator(); while (j.hasNext()) { Object tmp = j.next(); FieldInfo oldFieldInfo = (FieldInfo) oldFields.get(tmp); FieldInfo newFieldInfo = (FieldInfo) newFields.get(tmp); // Was only deprecated? if (wasDeprecated(oldFieldInfo, newFieldInfo) && !criteria.differs( cloneDeprecated(oldFieldInfo), newFieldInfo)) handler.fieldDeprecated(oldFieldInfo, newFieldInfo); else handler.fieldChanged(oldFieldInfo, newFieldInfo); } j = changedMethods.iterator(); while (j.hasNext()) { Object tmp = j.next(); MethodInfo oldMethodInfo = (MethodInfo) oldMethods .get(tmp); MethodInfo newMethodInfo = (MethodInfo) newMethods .get(tmp); // Was only deprecated? if (wasDeprecated(oldMethodInfo, newMethodInfo) && !criteria.differs( cloneDeprecated(oldMethodInfo), newMethodInfo)) handler.methodDeprecated(oldMethodInfo, newMethodInfo); else handler.methodChanged(oldMethodInfo, newMethodInfo); } handler.endChanged(); handler.endClassChanged(); removedMethods.clear(); removedFields.clear(); addedMethods.clear(); addedFields.clear(); changedMethods.clear(); changedFields.clear(); } } } handler.endChanged(); handler.endDiff(); } /** * Determines if an {@link AbstractInfo} was deprecated. (Shortcut to avoid * creating cloned deprecated infos). */ private static boolean wasDeprecated(AbstractInfo oldInfo, AbstractInfo newInfo) { return !oldInfo.isDeprecated() && newInfo.isDeprecated(); } /** * Clones the class info, but changes access, setting deprecated flag. * * @param classInfo * the original class info * @return the cloned and deprecated info. */ private static ClassInfo cloneDeprecated(ClassInfo classInfo) { return new ClassInfo(classInfo.getVersion(), classInfo.getAccess() | Opcodes.ACC_DEPRECATED, classInfo.getName(), classInfo.getSignature(), classInfo.getSupername(), classInfo.getInterfaces(), classInfo.getMethodMap(), classInfo.getFieldMap()); } /** * Clones the method, but changes access, setting deprecated flag. * * @param methodInfo * the original method info * @return the cloned and deprecated method info. */ private static MethodInfo cloneDeprecated(MethodInfo methodInfo) { return new MethodInfo(methodInfo.getAccess() | Opcodes.ACC_DEPRECATED, methodInfo.getName(), methodInfo.getDesc(), methodInfo.getSignature(), methodInfo.getExceptions()); } /** * Clones the field info, but changes access, setting deprecated flag. * * @param fieldInfo * the original field info * @return the cloned and deprecated field info. */ private static FieldInfo cloneDeprecated(FieldInfo fieldInfo) { return new FieldInfo(fieldInfo.getAccess() | Opcodes.ACC_DEPRECATED, fieldInfo.getName(), fieldInfo.getDesc(), fieldInfo.getSignature(), fieldInfo.getValue()); } }
api/src/main/java/org/osjava/jardiff/JarDiff.java
/** * Copyright 2012-2014 Julien Eluard and contributors * This project includes software developed by Julien Eluard: https://github.com/jeluard/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osjava.jardiff; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeSet; import java.util.TreeMap; import java.util.jar.JarEntry; import java.util.jar.JarFile; /* import javax.xml.transform.ErrorListener; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; */ import org.objectweb.asm.ClassReader; import org.objectweb.asm.Opcodes; /** * A class to perform a diff between two jar files. * * @author <a href="mailto:[email protected]">Antony Riley</a> */ public class JarDiff { /** * A map containing information about classes which are dependencies. * Keys are internal class names. * Values are instances of ClassInfo. */ protected Map depClassInfo = new HashMap(); /** * A map containing information about classes in the old jar file. * Keys are internal class names. * Values are instances of ClassInfo. */ protected Map oldClassInfo = new TreeMap(); /** * A map containing information about classes in the new jar file. * Keys are internal class names. * Values are instances of ClassInfo. */ protected Map newClassInfo = new TreeMap(); /** * An array of dependencies which are jar files, or urls. */ private URL[] deps; /** * A class loader used for loading dependency classes. */ private URLClassLoader depLoader; /** * The name of the old version. */ private String oldVersion; /** * The name of the new version. */ private String newVersion; /** * Class info visitor, used to load information about classes. */ private ClassInfoVisitor infoVisitor = new ClassInfoVisitor(); /** * Create a new JarDiff object. */ public JarDiff() { } /** * Set the name of the old version. * * @param oldVersion the name */ public void setOldVersion(String oldVersion) { this.oldVersion = oldVersion; } /** * Get the name of the old version. * * @return the name */ public String getOldVersion() { return oldVersion; } /** * Set the name of the new version. * * @param newVersion the version */ public void setNewVersion(String newVersion) { this.newVersion = newVersion; } /** * Get the name of the new version. * * @return the name */ public String getNewVersion() { return newVersion; } /** * Set the dependencies. * * @param deps an array of urls pointing to jar files or directories * containing classes which are required dependencies. */ public void setDependencies(URL[] deps) { this.deps = deps; } /** * Get the dependencies. * * @return the dependencies as an array of URLs */ public URL[] getDependencies() { return deps; } /** * Load classinfo given a ClassReader. * * @param reader the ClassReader * @return the ClassInfo */ private synchronized ClassInfo loadClassInfo(ClassReader reader) throws IOException { infoVisitor.reset(); reader.accept(infoVisitor, 0); return infoVisitor.getClassInfo(); } /** * Load all the classes from the specified URL and store information * about them in the specified map. * This currently only works for jar files, <b>not</b> directories * which contain classes in subdirectories or in the current directory. * * @param infoMap the map to store the ClassInfo in. * @throws DiffException if there is an exception reading info about a * class. */ private void loadClasses(Map infoMap, URL path) throws DiffException { try { File jarFile = null; if(!"file".equals(path.getProtocol()) || path.getHost() != null) { // If it's not a local file, store it as a temporary jar file. // java.util.jar.JarFile requires a local file handle. jarFile = File.createTempFile("jardiff","jar"); // Mark it to be deleted on exit. jarFile.deleteOnExit(); InputStream in = path.openStream(); OutputStream out = new FileOutputStream(jarFile); byte[] buffer = new byte[4096]; int i; while( (i = in.read(buffer,0,buffer.length)) != -1) { out.write(buffer, 0, i); } in.close(); out.close(); } else { // Else it's a local file, nothing special to do. jarFile = new File(path.getPath()); } loadClasses(infoMap, jarFile); } catch (IOException ioe) { throw new DiffException(ioe); } } /** * Load all the classes from the specified URL and store information * about them in the specified map. * This currently only works for jar files, <b>not</b> directories * which contain classes in subdirectories or in the current directory. * * @param infoMap the map to store the ClassInfo in. * @param file the jarfile to load classes from. * @throws IOException if there is an IOException reading info about a * class. */ private void loadClasses(Map infoMap, File file) throws DiffException { try { JarFile jar = new JarFile(file); Enumeration e = jar.entries(); while (e.hasMoreElements()) { JarEntry entry = (JarEntry) e.nextElement(); String name = entry.getName(); if (!entry.isDirectory() && name.endsWith(".class")) { ClassReader reader = new ClassReader(jar.getInputStream(entry)); ClassInfo ci = loadClassInfo(reader); infoMap.put(ci.getName(), ci); } } } catch (IOException ioe) { throw new DiffException(ioe); } } /** * Load old classes from the specified URL. * * @param loc The location of a jar file to load classes from. * @throws DiffException if there is an IOException. */ public void loadOldClasses(URL loc) throws DiffException { loadClasses(oldClassInfo, loc); } /** * Load new classes from the specified URL. * * @param loc The location of a jar file to load classes from. * @throws DiffException if there is an IOException. */ public void loadNewClasses(URL loc) throws DiffException { loadClasses(newClassInfo, loc); } /** * Load old classes from the specified File. * * @param file The location of a jar file to load classes from. * @throws DiffException if there is an IOException */ public void loadOldClasses(File file) throws DiffException { loadClasses(oldClassInfo, file); } /** * Load new classes from the specified File. * * @param file The location of a jar file to load classes from. * @throws DiffException if there is an IOException */ public void loadNewClasses(File file) throws DiffException { loadClasses(newClassInfo, file); } /** * Perform a diff sending the output to the specified handler, using * the specified criteria to select diffs. * * @param handler The handler to receive and handle differences. * @param criteria The criteria we use to select differences. * @throws DiffException when there is an underlying exception, e.g. * writing to a file caused an IOException */ public void diff(DiffHandler handler, DiffCriteria criteria) throws DiffException { diff(handler, criteria, oldVersion, newVersion, oldClassInfo, newClassInfo); } private void diff(DiffHandler handler, DiffCriteria criteria, String oldVersion, String newVersion, Map oldClassInfo, Map newClassInfo) throws DiffException { // TODO: Build the name from the MANIFEST rather than the filename handler.startDiff(oldVersion, newVersion); Iterator i; handler.startOldContents(); i = oldClassInfo.entrySet().iterator(); while(i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); ClassInfo ci = (ClassInfo) entry.getValue(); if(criteria.validClass(ci)) { handler.contains(ci); } } handler.endOldContents(); handler.startNewContents(); i = newClassInfo.entrySet().iterator(); while(i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); ClassInfo ci = (ClassInfo) entry.getValue(); if(criteria.validClass(ci)) { handler.contains(ci); } } handler.endNewContents(); java.util.Set onlyOld = new TreeSet(oldClassInfo.keySet()); java.util.Set onlyNew = new TreeSet(newClassInfo.keySet()); java.util.Set both = new TreeSet(oldClassInfo.keySet()); onlyOld.removeAll(newClassInfo.keySet()); onlyNew.removeAll(oldClassInfo.keySet()); both.retainAll(newClassInfo.keySet()); handler.startRemoved(); i = onlyOld.iterator(); while (i.hasNext()) { String s = (String) i.next(); ClassInfo ci = (ClassInfo) oldClassInfo.get(s); if (criteria.validClass(ci)) handler.classRemoved(ci); } handler.endRemoved(); handler.startAdded(); i = onlyNew.iterator(); while (i.hasNext()) { String s = (String) i.next(); ClassInfo ci = (ClassInfo) newClassInfo.get(s); if (criteria.validClass(ci)) handler.classAdded(ci); } handler.endAdded(); java.util.Set removedMethods = new TreeSet(); java.util.Set removedFields = new TreeSet(); java.util.Set addedMethods = new TreeSet(); java.util.Set addedFields = new TreeSet(); java.util.Set changedMethods = new TreeSet(); java.util.Set changedFields = new TreeSet(); handler.startChanged(); i = both.iterator(); while (i.hasNext()) { String s = (String) i.next(); ClassInfo oci = (ClassInfo) oldClassInfo.get(s); ClassInfo nci = (ClassInfo) newClassInfo.get(s); if (criteria.validClass(oci) || criteria.validClass(nci)) { Map oldMethods = oci.getMethodMap(); Map oldFields = oci.getFieldMap(); Map newMethods = nci.getMethodMap(); Map newFields = nci.getFieldMap(); Iterator j = oldMethods.entrySet().iterator(); while (j.hasNext()) { Map.Entry entry = (Map.Entry) j.next(); if (criteria.validMethod((MethodInfo) entry.getValue())) removedMethods.add(entry.getKey()); } j = oldFields.entrySet().iterator(); while (j.hasNext()) { Map.Entry entry = (Map.Entry) j.next(); if (criteria.validField((FieldInfo) entry.getValue())) removedFields.add(entry.getKey()); } j = newMethods.entrySet().iterator(); while (j.hasNext()) { Map.Entry entry = (Map.Entry) j.next(); if (criteria.validMethod((MethodInfo) entry.getValue())) addedMethods.add(entry.getKey()); } j = newFields.entrySet().iterator(); while (j.hasNext()) { Map.Entry entry = (Map.Entry) j.next(); if (criteria.validField((FieldInfo) entry.getValue())) addedFields.add(entry.getKey()); } changedMethods.addAll(removedMethods); changedMethods.retainAll(addedMethods); removedMethods.removeAll(changedMethods); addedMethods.removeAll(changedMethods); changedFields.addAll(removedFields); changedFields.retainAll(addedFields); removedFields.removeAll(changedFields); addedFields.removeAll(changedFields); j = changedMethods.iterator(); while (j.hasNext()) { String desc = (String) j.next(); MethodInfo oldInfo = (MethodInfo) oldMethods.get(desc); MethodInfo newInfo = (MethodInfo) newMethods.get(desc); if (!criteria.differs(oldInfo, newInfo)) j.remove(); } j = changedFields.iterator(); while (j.hasNext()) { String desc = (String) j.next(); FieldInfo oldInfo = (FieldInfo) oldFields.get(desc); FieldInfo newInfo = (FieldInfo) newFields.get(desc); if (!criteria.differs(oldInfo, newInfo)) j.remove(); } boolean classchanged = criteria.differs(oci, nci); if (classchanged || !removedMethods.isEmpty() || !removedFields.isEmpty() || !addedMethods.isEmpty() || !addedFields.isEmpty() || !changedMethods.isEmpty() || !changedFields.isEmpty()) { handler.startClassChanged(s); handler.startRemoved(); j = removedFields.iterator(); while (j.hasNext()) handler .fieldRemoved((FieldInfo) oldFields.get(j.next())); j = removedMethods.iterator(); while (j.hasNext()) handler.methodRemoved((MethodInfo) oldMethods.get(j.next())); handler.endRemoved(); handler.startAdded(); j = addedFields.iterator(); while (j.hasNext()) handler .fieldAdded((FieldInfo) newFields.get(j.next())); j = addedMethods.iterator(); while (j.hasNext()) handler.methodAdded((MethodInfo) newMethods.get(j.next())); handler.endAdded(); handler.startChanged(); if (classchanged) { // Was only deprecated? if (wasDeprecated(oci, nci) && !criteria.differs(cloneDeprecated(oci), nci)) handler.classDeprecated(oci, nci); else handler.classChanged(oci, nci); } j = changedFields.iterator(); while (j.hasNext()) { Object tmp = j.next(); FieldInfo oldFieldInfo = (FieldInfo) oldFields.get(tmp); FieldInfo newFieldInfo = (FieldInfo) newFields.get(tmp); // Was only deprecated? if (wasDeprecated(oldFieldInfo, newFieldInfo) && !criteria.differs( cloneDeprecated(oldFieldInfo), newFieldInfo)) handler.fieldDeprecated(oldFieldInfo, newFieldInfo); else handler.fieldChanged(oldFieldInfo, newFieldInfo); } j = changedMethods.iterator(); while (j.hasNext()) { Object tmp = j.next(); MethodInfo oldMethodInfo = (MethodInfo) oldMethods .get(tmp); MethodInfo newMethodInfo = (MethodInfo) newMethods .get(tmp); // Was only deprecated? if (wasDeprecated(oldMethodInfo, newMethodInfo) && !criteria.differs( cloneDeprecated(oldMethodInfo), newMethodInfo)) handler.methodDeprecated(oldMethodInfo, newMethodInfo); else handler.methodChanged(oldMethodInfo, newMethodInfo); } handler.endChanged(); handler.endClassChanged(); removedMethods.clear(); removedFields.clear(); addedMethods.clear(); addedFields.clear(); changedMethods.clear(); changedFields.clear(); } } } handler.endChanged(); handler.endDiff(); } /** * Determines if an {@link AbstractInfo} was deprecated. (Shortcut to avoid * creating cloned deprecated infos). */ private static boolean wasDeprecated(AbstractInfo oldInfo, AbstractInfo newInfo) { return !oldInfo.isDeprecated() && newInfo.isDeprecated(); } /** * Clones the class info, but changes access, setting deprecated flag. * * @param classInfo * the original class info * @return the cloned and deprecated info. */ private static ClassInfo cloneDeprecated(ClassInfo classInfo) { return new ClassInfo(classInfo.getVersion(), classInfo.getAccess() | Opcodes.ACC_DEPRECATED, classInfo.getName(), classInfo.getSignature(), classInfo.getSupername(), classInfo.getInterfaces(), classInfo.getMethodMap(), classInfo.getFieldMap()); } /** * Clones the method, but changes access, setting deprecated flag. * * @param methodInfo * the original method info * @return the cloned and deprecated method info. */ private static MethodInfo cloneDeprecated(MethodInfo methodInfo) { return new MethodInfo(methodInfo.getAccess() | Opcodes.ACC_DEPRECATED, methodInfo.getName(), methodInfo.getDesc(), methodInfo.getSignature(), methodInfo.getExceptions()); } /** * Clones the field info, but changes access, setting deprecated flag. * * @param fieldInfo * the original field info * @return the cloned and deprecated field info. */ private static FieldInfo cloneDeprecated(FieldInfo fieldInfo) { return new FieldInfo(fieldInfo.getAccess() | Opcodes.ACC_DEPRECATED, fieldInfo.getName(), fieldInfo.getDesc(), fieldInfo.getSignature(), fieldInfo.getValue()); } }
Add superclass handling
api/src/main/java/org/osjava/jardiff/JarDiff.java
Add superclass handling
<ide><path>pi/src/main/java/org/osjava/jardiff/JarDiff.java <ide> if (criteria.validClass(oci) || criteria.validClass(nci)) { <ide> Map oldMethods = oci.getMethodMap(); <ide> Map oldFields = oci.getFieldMap(); <add> Map extOldMethods = new HashMap(oldMethods); <add> Map extOldFields = new HashMap(oldFields); <add> <add> String superClass = oci.getSupername(); <add> while (superClass != null && oldClassInfo.containsKey(superClass)) { <add> ClassInfo sci = (ClassInfo) oldClassInfo.get(superClass); <add> Iterator j = sci.getFieldMap().entrySet().iterator(); <add> while (j.hasNext()) { <add> Map.Entry entry = (Map.Entry) j.next(); <add> if (!((FieldInfo)entry.getValue()).isPrivate() <add> && !extOldFields.containsKey(entry.getKey())) { <add> extOldFields.put(entry.getKey(), entry.getValue()); <add> } <add> } <add> j = sci.getMethodMap().entrySet().iterator(); <add> while (j.hasNext()) { <add> Map.Entry entry = (Map.Entry) j.next(); <add> if (!((MethodInfo)entry.getValue()).isPrivate() <add> && !extOldMethods.containsKey(entry.getKey())) { <add> extOldMethods.put(entry.getKey(), entry.getValue()); <add> } <add> } <add> superClass = sci.getSupername(); <add> } <add> <ide> Map newMethods = nci.getMethodMap(); <ide> Map newFields = nci.getFieldMap(); <ide> Iterator j = oldMethods.entrySet().iterator(); <ide> if (criteria.validField((FieldInfo) entry.getValue())) <ide> addedFields.add(entry.getKey()); <ide> } <add> <ide> changedMethods.addAll(removedMethods); <ide> changedMethods.retainAll(addedMethods); <ide> removedMethods.removeAll(changedMethods); <add> removedMethods.removeAll(extOldMethods.keySet()); <ide> addedMethods.removeAll(changedMethods); <ide> changedFields.addAll(removedFields); <ide> changedFields.retainAll(addedFields); <ide> removedFields.removeAll(changedFields); <add> removedFields.removeAll(extOldFields.keySet()); <ide> addedFields.removeAll(changedFields); <ide> j = changedMethods.iterator(); <ide> while (j.hasNext()) {
JavaScript
mit
f575cdac81b153d3a095f16787f7f049a4deb4df
0
semmypurewal/spotter.js,semmypurewal/spotter.js,semmypurewal/spotter.js
/** * spotter.js * Copyright (C) 2010 Semmy Purewal * * @version .1 * * TODO: modify it so that the modules can better handle timing (big change) * TODO: generate documentation * TODO: create a definite namespace for this library */ spotter = {} /** * Spotter is an object * @class */ Spotter = spotter; /** * spotterFactory * * Creates a new Spotter object with the specified module and options. * * @param m string representing the module that this spotter will use * @param options Object containing options that can be sent to that module */ spotter.spotterFactory = function(m, options) { /** * private constructor * * @private * @constructor * @param {String} v the name of the variable associated with this Spotter object */ var Spotter = function(v) { var varName = v; var lastCallReturned = true; var lastScriptTag = null; var observers = []; var intervalTimer = null; var modFunc; var module; window["spotter"][varName] = this; try { modFunc = window["spotter"]["modules"][m.split(".")[0]][m.split(".")[1]]; if(modFunc === undefined) throw new Exception(); } catch(e) { throw new Error("Spotter: Module " + m + " not found! (Did you remember to include it via a script tag?)"); } module = modFunc(options); //yay no eval! if(!module.url || !module.process) { throw new Error("Spotter: spotter.modules."+m+" is invalid. (Does it return an object with url and process methods?)"); } /** * spot * * Execute the ajax request at the specified time intervals. Note that * this function does not execute if the object is waiting on another * response. * * * @member Spotter * @param {Number} optional parameter represeting the number of seconds * between each request. If this parameter is not provided, the * function performs a single request. * * TODO: set up a time out so that if the last request doesn't return * the remaining requests are not blocked * * TODO: get rid of the number of seconds between requests, let that be * handled by the appropriate module * */ this.spot = function(seconds) { var url; if((!seconds || seconds < 1) && lastCallReturned) { url = module.url(); if(url instanceof Object && url.callbackParam !== undefined) { url = url.url+'&'+url.callbackParam+'=spotter.'+varName+'.callback'; } else { url += '&callback=spotter.'+varName+'.callback'; } url += '&random='+Math.floor(Math.random()*10000); request(url); } else { this.spot(); var obj = this; intervalTimer = setInterval(function() { obj.spot(); }, seconds*1000); } } /** * callback * * Receive the response from the ajax request and send it * to the appropriate module for processing. Removes the * defunct script tag from the DOM * * @member Spotter * @param {Object} result from the API */ this.callback = function(rawData) { var processedData = module.process(rawData); //send the raw data to the module for processing //now the processedData has an 'update' attribute and a 'data' attribute if(processedData.update) this.notifyObservers(processedData.data); lastCallReturned = true; } /** * stop * * Stops this spotter if it is currently spotting. * @member Spotter * @throws Error if you try to stop a stopped spotter */ this.stop = function() { if(intervalTimer == null) { throw new Error("Spotter: You can't stop a stopped spotter!"); } else { var head = document.getElementsByTagName("head"); if(lastScriptTag != null) head[0].removeChild(lastScriptTag); clearInterval(intervalTimer); } } /** * Function that actually makes the request. * * @private * @param {String} url the json request URL */ function request(url) { var head = document.getElementsByTagName("head"); var script = document.createElement('script'); script.id = 'spotter_request'+varName; script.type = 'text/javascript'; script.src = url; if(lastScriptTag != null) head[0].removeChild(lastScriptTag); head[0].appendChild(script); lastScriptTag = script; } /********** OBSERVABLE INTERFACE ***************/ /** * Register an observer with this Spotter * * @member Spotter * @param {Object} observer this method verifies that the notify method is present * @throws TypeError a TypeError is thrown if the parameter does not implement notify */ this.registerObserver = function(observer) { if(observer.notify !== undefined && typeof observer.notify === 'function') observers.push(observer); else throw new TypeError('Spotter: observer must implement a notify method.'); } /** * Notify this Spotter's observers * * @member Spotter * @param {Object} data that will be sent to the observers */ this.notifyObservers = function(data) { for(var i in observers) observers[i].notify(data); } /********** END OBSERVABLE INTERFACE ***************/ }//end spotter constructor this.instanceCount = (this.instanceCount === undefined)?1:this.instanceCount+1; var variableName = "so"+this.instanceCount+Math.floor(Math.random()*100); //window["spotter"][variableName] = new Spotter(variableName); //return window["spotter"][variableName]; return new Spotter(variableName); }
src/spotter.js
/** * spotter.js * Copyright (C) 2010 Semmy Purewal * * @version .1 * * TODO: modify it so that the modules can better handle timing (big change) * TODO: generate documentation * TODO: create a definite namespace for this library */ spotter = {} Spotter = spotter; /** * spotterFactory * * Creates a new Spotter object with the specified module and options. * * @param m string representing the module that this spotter will use * @param options Object containing options that can be sent to that module */ spotter.spotterFactory = function(m, options) { /** * private constructor * * @private * @constructor * @param {String} v the name of the variable associated with this Spotter object */ var _spotter = function(v) { var varName = v; var lastCallReturned = true; var lastScriptTag = null; var observers = new Array(); var intervalTimer = null; var modFunc; var module; try { modFunc = window["spotter"]["modules"][m.split(".")[0]][m.split(".")[1]]; if(modFunc === undefined) throw new Exception(); } catch(Exception) { throw new Error("Spotter: Module " + m + " not found! (Did you remember to include it via a script tag?)"); } module = modFunc(options); //yay no eval! if(!module.url || !module.process) { throw new Error("Spotter: spotter.modules."+m+" is invalid. (Does it return an object with url and process methods?)"); } /** * spot * * Execute the ajax request at the specified time intervals. Note that * this function does not execute if the object is waiting on another * response. * * * @member Spotter * @param {Number} optional parameter represeting the number of seconds * between each request. If this parameter is not provided, the * function performs a single request. * * TODO: set up a time out so that if the last request doesn't return * the remaining requests are not blocked * * TODO: get rid of the number of seconds between requests, let that be * handled by the appropriate module * */ this.spot = function(seconds) { var url; if((!seconds || seconds < 1) && lastCallReturned) { url = module.url(); if(url instanceof Object && url.callbackParam !== undefined) { url = url.url+'&'+url.callbackParam+'=spotter.'+varName+'.callback'; } else { url += '&callback=spotter.'+varName+'.callback'; } url += '&random='+Math.floor(Math.random()*10000); request(url); } else { this.spot(); var obj = this; intervalTimer = setInterval(function() { obj.spot(); }, seconds*1000); } } /** * callback * * Receive the response from the ajax request and send it * to the appropriate module for processing. Removes the * defunct script tag from the DOM * * @member Spotter * @param {Object} result from the API */ this.callback = function(rawData) { var processedData = module.process(rawData); //send the raw data to the module for processing //now the processedData has an 'update' attribute and a 'data' attribute if(processedData.update) this.notifyObservers(processedData.data); lastCallReturned = true; } /** * stop * * Stops this spotter if it is currently spotting. * @member Spotter * @throws Error if you try to stop a stopped spotter */ this.stop = function() { if(intervalTimer == null) { throw new Error("Spotter: You can't stop a stopped spotter!"); } else { var head = document.getElementsByTagName("head"); if(lastScriptTag != null) head[0].removeChild(lastScriptTag); clearInterval(intervalTimer); } } /** * Function that actually makes the request. * * @private * @param {String} url the json request URL */ function request(url) { var head = document.getElementsByTagName("head"); var script = document.createElement('script'); script.id = 'spotter_request'+varName; script.type = 'text/javascript'; script.src = url; if(lastScriptTag != null) head[0].removeChild(lastScriptTag); head[0].appendChild(script); lastScriptTag = script; } /********** OBSERVABLE INTERFACE ***************/ /** * Register an observer with this Spotter * * @member Spotter * @param {Object} observer this method verifies that the notify method is present * @throws TypeError a TypeError is thrown if the parameter does not implement notify */ this.registerObserver = function(observer) { if(observer.notify !== undefined && typeof observer.notify === 'function') observers.push(observer); else throw new TypeError('Spotter: observer must implement a notify method.'); } /** * Notify this Spotter's observers * * @param {Object} data that will be sent to the observers */ this.notifyObservers = function(data) { for(var i in observers) observers[i].notify(data); } /********** END OBSERVABLE INTERFACE ***************/ }//end spotter constructor this.instanceCount = Spotter.instanceCount == null?1:Spotter.instanceCount++; var variableName = "so"+Spotter.instanceCount+Math.floor(Math.random()*100); window["spotter"][variableName] = new _spotter(variableName); return window["spotter"][variableName]; }
finally, major refactor has begun
src/spotter.js
finally, major refactor has begun
<ide><path>rc/spotter.js <ide> <ide> spotter = {} <ide> <add>/** <add> * Spotter is an object <add> * @class <add> */ <ide> Spotter = spotter; <ide> <ide> /** <ide> * @constructor <ide> * @param {String} v the name of the variable associated with this Spotter object <ide> */ <del> var _spotter = function(v) { <add> var Spotter = function(v) { <ide> var varName = v; <ide> var lastCallReturned = true; <ide> var lastScriptTag = null; <del> var observers = new Array(); <add> var observers = []; <ide> var intervalTimer = null; <ide> var modFunc; <ide> var module; <ide> <add> window["spotter"][varName] = this; <ide> <ide> try { <ide> modFunc = window["spotter"]["modules"][m.split(".")[0]][m.split(".")[1]]; <ide> if(modFunc === undefined) throw new Exception(); <del> } catch(Exception) { <add> } catch(e) { <ide> throw new Error("Spotter: Module " + m + " not found! (Did you remember to include it via a script tag?)"); <ide> } <ide> module = modFunc(options); //yay no eval! <ide> /** <ide> * Notify this Spotter's observers <ide> * <add> * @member Spotter <ide> * @param {Object} data that will be sent to the observers <ide> */ <ide> this.notifyObservers = function(data) { <ide> /********** END OBSERVABLE INTERFACE ***************/ <ide> }//end spotter constructor <ide> <del> this.instanceCount = Spotter.instanceCount == null?1:Spotter.instanceCount++; <del> var variableName = "so"+Spotter.instanceCount+Math.floor(Math.random()*100); <del> window["spotter"][variableName] = new _spotter(variableName); <del> return window["spotter"][variableName]; <add> this.instanceCount = (this.instanceCount === undefined)?1:this.instanceCount+1; <add> var variableName = "so"+this.instanceCount+Math.floor(Math.random()*100); <add> //window["spotter"][variableName] = new Spotter(variableName); <add> //return window["spotter"][variableName]; <add> return new Spotter(variableName); <ide> }
Java
mit
72c77641a33e10cbdd5865e8b64321e4686c8061
0
dheerajarora/sql2o,mugizico/sql2o,aaberg/sql2o,xaled/sql2o,indvd00m/sql2o,trfiladelfo/sql2o,minecrafter/sql2o
package org.sql2o.data; import org.joda.time.DateTime; import org.sql2o.Sql2oException; import org.sql2o.converters.*; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Represents a result set row. */ public class Row { private Map<Integer, Object> values; private Table table; public Row(Table table) { this.table = table; values = new HashMap<Integer, Object>(); } void addValue(int columnIndex, Object value){ values.put(columnIndex, value); } public Object getObject(int columnIndex){ return values.get(columnIndex); } public Object getObject(String columnName){ String col = table.isCaseSensitive() ? columnName : columnName.toLowerCase(); Object obj; try{ obj = getObject(table.getColumnNameToIdxMap().get(col)); } catch (NullPointerException ex){ throw new Sql2oException(String.format("Column with name '%s' does not exist", columnName), ex); } return obj; } public BigDecimal getBigDecimal(int columnIndex){ return new BigDecimalConverter().convert(getObject(columnIndex)); } public BigDecimal getBigDecimal(String columnName){ return new BigDecimalConverter().convert(getObject(columnName)); } public Double getDouble(int columnIndex){ return new DoubleConverter(false).convert(getObject(columnIndex)); } public Double getDouble(String columnName){ return new DoubleConverter(false).convert(getObject(columnName)); } public Float getFloat(int columnIndex){ return new FloatConverter(false).convert(getObject(columnIndex)); } public Float getFloat(String columnName){ return new FloatConverter(false).convert(getObject(columnName)); } public Long getLong(int columnIndex){ return new LongConverter(false).convert(getObject(columnIndex)); } public Long getLong(String columnName){ return new LongConverter(false).convert(getObject(columnName)); } public Integer getInteger(int columnIndex){ return new IntegerConverter(false).convert(getObject(columnIndex)); } public Integer getInteger(String columnName){ return new IntegerConverter(false).convert(getObject(columnName)); } public Short getShort(int columnIndex){ return new ShortConverter(false).convert(getObject(columnIndex)); } public Short getShort(String columnName){ return new ShortConverter(false).convert(getObject(columnName)); } public Byte getByte(int columnIndex){ return new ByteConverter(false).convert(getObject(columnIndex)); } public Byte getByte(String columnName){ return new ByteConverter(false).convert(getObject(columnName)); } public Date getDate(int columnIndex){ try { return new DateConverter().convert(getObject(columnIndex)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with index " + columnIndex + " to " + Date.class.toString()); } } public Date getDate(String columnName){ try { return new DateConverter().convert(getObject(columnName)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with name " + columnName + " to " + Date.class.toString()); } } public DateTime getDateTime(int columnIndex){ try { return new JodaTimeConverter().convert(getObject(columnIndex)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with index " + columnIndex + " to " + DateTime.class.toString()); } } public DateTime getDateTime(String columnName){ try { return new JodaTimeConverter().convert(getObject(columnName)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with name " + columnName + " to " + DateTime.class.toString()); } } public String getString(int columnIndex){ try { return new StringConverter().convert(getObject(columnIndex)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with index " + columnIndex + " to " + String.class.getName()); } } public String getString(String columnName){ try { return new StringConverter().convert(getObject(columnName)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with name " + columnName+ " to " + String.class.getName()); } } }
src/main/java/org/sql2o/data/Row.java
package org.sql2o.data; import org.joda.time.DateTime; import org.sql2o.Sql2oException; import org.sql2o.converters.*; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * Represents a result set row. */ public class Row { private Map<Integer, Object> values; private Table table; public Row(Table table) { this.table = table; values = new HashMap<Integer, Object>(); } void addValue(int columnIndex, Object value){ values.put(columnIndex, value); } public Object getObject(int columnIndex){ return values.get(columnIndex); } public Object getObject(String columnName){ String col = table.isCaseSensitive() ? columnName : columnName.toLowerCase(); Object obj; try{ obj = getObject(table.getColumnNameToIdxMap().get(col)); } catch (NullPointerException ex){ throw new Sql2oException(String.format("Column with name '%s' does not exist", columnName), ex); } return obj; } public BigDecimal getBigDecimal(int columnIndex){ return new BigDecimalConverter().convert(getObject(columnIndex)); } public BigDecimal getBigDecimal(String columnName){ return new BigDecimalConverter().convert(getObject(columnName)); } public Double getDouble(int columnIndex){ return new DoubleConverter(false).convert(getObject(columnIndex)); } public Double getDouble(String columnName){ return new DoubleConverter(false).convert(getObject(columnName)); } public Float getFloat(int columnIndex){ return new FloatConverter(false).convert(getObject(columnIndex)); } public Float getFloat(String columnName){ return new FloatConverter(false).convert(getObject(columnName)); } public Long getLong(int columnIndex){ return new LongConverter(false).convert(getObject(columnIndex)); } public Long getLong(String columnName){ return new LongConverter(false).convert(getObject(columnName)); } public Integer getInteger(int columnIndex){ return new IntegerConverter(false).convert(getObject(columnIndex)); } public Integer getInteger(String columnName){ return new IntegerConverter(false).convert(getObject(columnName)); } public Short getShort(int columnIndex){ return new ShortConverter(false).convert(getObject(columnIndex)); } public Short getShort(String columnName){ return new ShortConverter(false).convert(getObject(columnName)); } public Byte getByte(int columnIndex){ return new ByteConverter(false).convert(getObject(columnIndex)); } public Byte getByte(String columnName){ return new ByteConverter(false).convert(getObject(columnName)); } public Date getDate(int columnIndex){ try { return new DateConverter().convert(getObject(columnIndex)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with index " + columnIndex + " to " + Date.class.toString()); } } public Date getDate(String columnName){ try { return new DateConverter().convert(getObject(columnName)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with name " + columnName + " to " + Date.class.toString()); } } public DateTime getDateTime(int columnIndex){ try { return new JodaTimeConverter().convert(getObject(columnIndex)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with index " + columnIndex + " to " + DateTime.class.toString()); } } public DateTime getDateTime(String columnName){ try { return new JodaTimeConverter().convert(getObject(columnName)); } catch (ConverterException e) { throw new Sql2oException("Could not convert column with name " + columnName + " to " + DateTime.class.toString()); } } public String getString(int columnIndex){ return new StringConverter().convert(getObject(columnIndex)); } public String getString(String columnName){ return new StringConverter().convert(getObject(columnName)); } }
fixes try-catch in getString method
src/main/java/org/sql2o/data/Row.java
fixes try-catch in getString method
<ide><path>rc/main/java/org/sql2o/data/Row.java <ide> } <ide> <ide> public String getString(int columnIndex){ <del> return new StringConverter().convert(getObject(columnIndex)); <add> try { <add> return new StringConverter().convert(getObject(columnIndex)); <add> } catch (ConverterException e) { <add> throw new Sql2oException("Could not convert column with index " + columnIndex + " to " + String.class.getName()); <add> } <ide> } <ide> <ide> public String getString(String columnName){ <del> return new StringConverter().convert(getObject(columnName)); <add> try { <add> return new StringConverter().convert(getObject(columnName)); <add> } catch (ConverterException e) { <add> throw new Sql2oException("Could not convert column with name " + columnName+ " to " + String.class.getName()); <add> } <ide> } <ide> <ide> }
Java
mit
0fb979a72f4fbfc37d926e2093e7fccfbcdf8ef7
0
j14solutions/jhybridge,j14solutions/jhybridge,j14solutions/jhybridge,telefonicaid/tdigital-hybridge,telefonicaid/tdigital-hybridge,jorgevila/tdigital-hybridge,telefonicaid/tdigital-hybridge,jorgevila/tdigital-hybridge,telefonicaid/tdigital-hybridge,jorgevila/tdigital-hybridge,jorgevila/tdigital-hybridge,j14solutions/jhybridge
/** * Hybridge * (c) Telefonica Digital, 2013 - All rights reserved * License: GNU Affero V3 (see LICENSE file) */ package com.pdi.hybridge; import java.util.HashMap; import java.util.Observable; import java.util.Observer; import org.json.JSONArray; import org.json.JSONObject; import android.annotation.SuppressLint; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.webkit.WebView; import android.webkit.WebView.HitTestResult; import com.pdi.hybridge.HybridgeConst.Event; public class HybridgeBroadcaster extends Observable { private static HybridgeBroadcaster instance; private boolean isInitialized = false; private final String TAG = "HybridgeBroadcaster"; private StringBuffer jsBuffer; private HashMap<Integer, AsyncTask<JSONObject, Void, JSONObject>> currents; @SuppressLint("UseSparseArrays") public HybridgeBroadcaster() { currents = new HashMap<Integer, AsyncTask<JSONObject,Void,JSONObject>>(); jsBuffer = new StringBuffer(""); } public static HybridgeBroadcaster getInstance() { if (instance == null) { instance = new HybridgeBroadcaster(); } return instance; } public void initJs(WebView view, JSONArray actions, JSONArray events) { runJsInWebView(view, "window.HybridgeGlobal || function () {" + "window.HybridgeGlobal = {" + " isReady : true" + ", version : " + HybridgeConst.VERSION + ", actions : " + actions.toString() + ", events : " + events.toString() + "};" + "window.$ && $('#hybridgeTrigger').toggleClass('switch');" + "}()" ); isInitialized = true; } public void firePause(WebView view) { HybridgeConst.Event event = HybridgeConst.Event.PAUSE; notifyObservers(event); fireJavascriptEvent(view, event, null); } public void fireResume(WebView view) { HybridgeConst.Event event = HybridgeConst.Event.RESUME; notifyObservers(event); fireJavascriptEvent(view, event, null); } public void fireMessage (WebView view, JSONObject data) { HybridgeConst.Event event = HybridgeConst.Event.MESSAGE; notifyObservers(event); fireJavascriptEvent(view, event, data); } public void fireReady(WebView view, JSONObject data) { HybridgeConst.Event event = HybridgeConst.Event.READY; notifyObservers(event); fireJavascriptEvent(view, event, data); } public void fireJavascriptEvent(WebView view, Event event, JSONObject data) { if (isInitialized) { WebView.HitTestResult hr = ((WebView)view).getHitTestResult(); String prejs = ""; String json = data != null ? data.toString() : "{}"; StringBuffer js = new StringBuffer("HybridgeGlobal.fireEvent(\""); js.append(event.getJsName()).append("\",").append(json).append(");"); if (hr == null || hr.getType() != HitTestResult.EDIT_TEXT_TYPE) { if(jsBuffer.length() != 0) { prejs = jsBuffer.append(js.toString()).toString(); runJsInWebView(view, prejs); jsBuffer = new StringBuffer(""); } else { runJsInWebView(view, js.toString()); } } else { Log.d(TAG, "Defer javascript message, user is entering text"); jsBuffer.append(js.toString()); } } } public void runJsInWebView(final WebView view, final String js) { new Handler(Looper.getMainLooper()).post( new Runnable() { @Override public void run() { view.loadUrl("javascript:(function(){" + js + "})()"); } }); } public void updateState(JSONObject data) { this.setChanged(); this.notifyObservers(data); Log.d(TAG, data.toString()); } @SuppressWarnings("unchecked") @Override public void addObserver(Observer observer) { super.addObserver(observer); Class<?> clazz = observer.getClass().getSuperclass(); if (clazz != null && clazz == android.os.AsyncTask.class) { int hashCode = observer.hashCode(); AsyncTask<JSONObject, Void, JSONObject> current = currents.get(hashCode); if (current != null) { if (current.cancel(true)) { currents.remove(hashCode); } } currents.put(hashCode, (AsyncTask<JSONObject, Void, JSONObject>) observer); } } @Override public void deleteObserver(Observer observer) { super.deleteObserver(observer); Class<?> clazz = observer.getClass().getSuperclass(); if (clazz != null && clazz == android.os.AsyncTask.class) { int hashCode = observer.hashCode(); currents.remove(hashCode); } } }
android/Hybridge/src/com/pdi/hybridge/HybridgeBroadcaster.java
/** * Hybridge * (c) Telefonica Digital, 2013 - All rights reserved * License: GNU Affero V3 (see LICENSE file) */ package com.pdi.hybridge; import java.util.HashMap; import java.util.Observable; import java.util.Observer; import org.json.JSONArray; import org.json.JSONObject; import android.annotation.SuppressLint; import android.os.AsyncTask; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.webkit.WebView; import android.webkit.WebView.HitTestResult; import com.pdi.hybridge.HybridgeConst.Event; public class HybridgeBroadcaster extends Observable { private static HybridgeBroadcaster instance; private boolean isInitialized = false; private final String TAG = "HybridgeBroadcaster"; private StringBuffer jsBuffer; private HashMap<Integer, AsyncTask<JSONObject, Void, JSONObject>> currents; @SuppressLint("UseSparseArrays") public HybridgeBroadcaster() { currents = new HashMap<Integer, AsyncTask<JSONObject,Void,JSONObject>>(); jsBuffer = new StringBuffer(""); } public static HybridgeBroadcaster getInstance() { if (instance == null) { instance = new HybridgeBroadcaster(); } return instance; } public void initJs(WebView view, JSONArray actions, JSONArray events) { runJsInWebView(view, "window.HybridgeGlobal || function () {" + "window.HybridgeGlobal = {" + " isReady : true" + ", version : " + HybridgeConst.VERSION + ", actions : " + actions.toString() + ", events : " + events.toString() + "};" + "window.$ && $('#hybridgeTrigger').toggleClass('switch');" + "}()" ); isInitialized = true; } public void firePause(WebView view) { HybridgeConst.Event event = HybridgeConst.Event.PAUSE; notifyObservers(event); fireJavascriptEvent(view, event, null); } public void fireResume(WebView view) { HybridgeConst.Event event = HybridgeConst.Event.RESUME; notifyObservers(event); fireJavascriptEvent(view, event, null); } public void fireMessage (WebView view, JSONObject data) { HybridgeConst.Event event = HybridgeConst.Event.MESSAGE; notifyObservers(event); fireJavascriptEvent(view, event, data); } public void fireReady(WebView view, JSONObject data) { HybridgeConst.Event event = HybridgeConst.Event.READY; notifyObservers(event); fireJavascriptEvent(view, event, data); } public void fireJavascriptEvent(WebView view, Event event, JSONObject data) { if (isInitialized) { WebView.HitTestResult hr = ((WebView)view).getHitTestResult(); String prejs = ""; String json = data != null ? data.toString() : "{}"; StringBuffer js = new StringBuffer("HybridgeGlobal.fireEvent(\""); js.append(event.getJsName()).append("\",").append(json).append(");"); if (hr == null || hr.getType() != HitTestResult.EDIT_TEXT_TYPE) { if(jsBuffer.length() != 0) { prejs = jsBuffer.append(js.toString()).toString(); runJsInWebView(view, prejs); jsBuffer = new StringBuffer(); } else { runJsInWebView(view, js.toString()); } } else { Log.d(TAG, "Defer javascript message, user is entering text"); jsBuffer.append(js.toString()); } } } public void runJsInWebView(final WebView view, final String js) { new Handler(Looper.getMainLooper()).post( new Runnable() { @Override public void run() { view.loadUrl("javascript:(function(){" + js + "})()"); } }); } public void updateState(JSONObject data) { this.setChanged(); this.notifyObservers(data); Log.d(TAG, data.toString()); } @SuppressWarnings("unchecked") @Override public void addObserver(Observer observer) { super.addObserver(observer); Class<?> clazz = observer.getClass().getSuperclass(); if (clazz != null && clazz == android.os.AsyncTask.class) { int hashCode = observer.hashCode(); AsyncTask<JSONObject, Void, JSONObject> current = currents.get(hashCode); if (current != null) { if (current.cancel(true)) { currents.remove(hashCode); } } currents.put(hashCode, (AsyncTask<JSONObject, Void, JSONObject>) observer); } } @Override public void deleteObserver(Observer observer) { super.deleteObserver(observer); Class<?> clazz = observer.getClass().getSuperclass(); if (clazz != null && clazz == android.os.AsyncTask.class) { int hashCode = observer.hashCode(); currents.remove(hashCode); } } }
EDIT init jsBuffer already as String length 0
android/Hybridge/src/com/pdi/hybridge/HybridgeBroadcaster.java
EDIT init jsBuffer already as String length 0
<ide><path>ndroid/Hybridge/src/com/pdi/hybridge/HybridgeBroadcaster.java <ide> if(jsBuffer.length() != 0) { <ide> prejs = jsBuffer.append(js.toString()).toString(); <ide> runJsInWebView(view, prejs); <del> jsBuffer = new StringBuffer(); <add> jsBuffer = new StringBuffer(""); <ide> } else { <ide> runJsInWebView(view, js.toString()); <ide> }
Java
apache-2.0
4bb3bafdc7d98ee62a4d9d8ac3662891169d98ba
0
alxdarksage/BridgePF,DwayneJengSage/BridgePF,Sage-Bionetworks/BridgePF,Sage-Bionetworks/BridgePF,DwayneJengSage/BridgePF,Sage-Bionetworks/BridgePF,DwayneJengSage/BridgePF,alxdarksage/BridgePF,alxdarksage/BridgePF
package org.sagebionetworks.bridge.dynamodb; import org.sagebionetworks.bridge.BridgeUtils; import org.sagebionetworks.bridge.json.DateUtils; import org.sagebionetworks.bridge.models.Upload; import org.sagebionetworks.bridge.models.UploadRequest; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; @DynamoDBTable(tableName = "Upload") public class DynamoUpload implements Upload, DynamoTable { private String uploadId; private long timestamp; private String objectId; private String healthCode; private boolean complete; private Long version; private String name; private long contentLength; private String contentType; private String contentMd5; public DynamoUpload() {} public DynamoUpload(UploadRequest uploadRequest, String healthCode) { uploadId = BridgeUtils.generateGuid(); timestamp = DateUtils.getCurrentMillisFromEpoch(); objectId = BridgeUtils.generateGuid(); this.healthCode = healthCode; complete = false; name = uploadRequest.getName(); contentLength = uploadRequest.getContentLength(); contentType = uploadRequest.getContentType(); contentMd5 = uploadRequest.getContentMd5(); } @DynamoDBHashKey @Override public String getUploadId() { return uploadId; } public void setUploadId(String uploadId) { this.uploadId = uploadId; } @DynamoDBAttribute @Override public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } @DynamoDBAttribute @Override public String getObjectId() { return objectId; } public void setObjectId(String objectId) { this.objectId = objectId; } @DynamoDBAttribute @Override public String getHealthCode() { return healthCode; } public void setHealthCode(String healthCode) { this.healthCode = healthCode; } @DynamoDBAttribute @Override public boolean isComplete() { return complete; } public void setComplete(boolean complete) { this.complete = complete; } @DynamoDBVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @DynamoDBAttribute @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @DynamoDBAttribute @Override public long getContentLength() { return contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } @DynamoDBAttribute @Override public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } @DynamoDBAttribute @Override public String getContentMd5() { return contentMd5; } public void setContentMd5(String contentMd5) { this.contentMd5 = contentMd5; } }
app/org/sagebionetworks/bridge/dynamodb/DynamoUpload.java
package org.sagebionetworks.bridge.dynamodb; import java.util.UUID; import org.sagebionetworks.bridge.json.DateUtils; import org.sagebionetworks.bridge.models.Upload; import org.sagebionetworks.bridge.models.UploadRequest; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBVersionAttribute; @DynamoDBTable(tableName = "Upload") public class DynamoUpload implements Upload, DynamoTable { private String uploadId; private long timestamp; private String objectId; private String healthCode; private boolean complete; private Long version; private String name; private long contentLength; private String contentType; private String contentMd5; public DynamoUpload() {} public DynamoUpload(UploadRequest uploadRequest, String healthCode) { uploadId = BridgeUtils.generateGuid(); timestamp = DateUtils.getCurrentMillisFromEpoch(); objectId = BridgeUtils.generateGuid(); this.healthCode = healthCode; complete = false; name = uploadRequest.getName(); contentLength = uploadRequest.getContentLength(); contentType = uploadRequest.getContentType(); contentMd5 = uploadRequest.getContentMd5(); } @DynamoDBHashKey @Override public String getUploadId() { return uploadId; } public void setUploadId(String uploadId) { this.uploadId = uploadId; } @DynamoDBAttribute @Override public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } @DynamoDBAttribute @Override public String getObjectId() { return objectId; } public void setObjectId(String objectId) { this.objectId = objectId; } @DynamoDBAttribute @Override public String getHealthCode() { return healthCode; } public void setHealthCode(String healthCode) { this.healthCode = healthCode; } @DynamoDBAttribute @Override public boolean isComplete() { return complete; } public void setComplete(boolean complete) { this.complete = complete; } @DynamoDBVersionAttribute public Long getVersion() { return version; } public void setVersion(Long version) { this.version = version; } @DynamoDBAttribute @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @DynamoDBAttribute @Override public long getContentLength() { return contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } @DynamoDBAttribute @Override public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } @DynamoDBAttribute @Override public String getContentMd5() { return contentMd5; } public void setContentMd5(String contentMd5) { this.contentMd5 = contentMd5; } }
Fixing build
app/org/sagebionetworks/bridge/dynamodb/DynamoUpload.java
Fixing build
<ide><path>pp/org/sagebionetworks/bridge/dynamodb/DynamoUpload.java <ide> package org.sagebionetworks.bridge.dynamodb; <ide> <del>import java.util.UUID; <del> <add>import org.sagebionetworks.bridge.BridgeUtils; <ide> import org.sagebionetworks.bridge.json.DateUtils; <ide> import org.sagebionetworks.bridge.models.Upload; <ide> import org.sagebionetworks.bridge.models.UploadRequest;
JavaScript
mit
bb59f57dc0db36aad2eb5d85fbe5a4792d330b44
0
futurice/sec-conference-server,futurice/sec-conference-server
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var EventSchema = new Schema({ title: { type: String, default: '' }, start_time: Date, // jshint ignore:line end_time: Date, // jshint ignore:line location: String, description: String, bar_camp: Boolean, day: String, artists: [String], starred_count: Number // jshint ignore:line }); module.exports = mongoose.model('Event', EventSchema);
api/models/event.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var EventSchema = new Schema({ title: { type: String, default: '' }, start_time: Date, // jshint ignore:line end_time: Date, // jshint ignore:line location: String, description: String, bar_camp: Boolean, artists: [String], starred_count: Number // jshint ignore:line }); module.exports = mongoose.model('Event', EventSchema);
Added field `day` to Event model
api/models/event.js
Added field `day` to Event model
<ide><path>pi/models/event.js <ide> location: String, <ide> description: String, <ide> bar_camp: Boolean, <add> day: String, <ide> artists: [String], <ide> starred_count: Number // jshint ignore:line <ide> });
Java
apache-2.0
a6d15d24258e1310a611324052a6d64e55e2571e
0
HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j,HuangLS/neo4j
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.server; import java.io.File; import org.apache.commons.configuration.Configuration; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.helpers.Service; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.server.configuration.Configurator; import org.neo4j.server.configuration.PropertyFileConfigurator; import org.neo4j.server.configuration.validation.DatabaseLocationMustBeSpecifiedRule; import org.neo4j.server.configuration.validation.Validator; import org.neo4j.server.database.GraphDatabaseFactory; import org.neo4j.server.logging.Logger; import org.neo4j.server.modules.ServerModule; import org.neo4j.server.rest.paging.RealClock; import org.neo4j.server.startup.healthcheck.StartupHealthCheck; import org.neo4j.server.startup.healthcheck.StartupHealthCheckRule; import org.neo4j.server.web.Jetty6WebServer; public abstract class Bootstrapper { public static final Integer OK = 0; public static final Integer WEB_SERVER_STARTUP_ERROR_CODE = 1; public static final Integer GRAPH_DATABASE_STARTUP_ERROR_CODE = 2; private static Logger log = Logger.getLogger( NeoServerBootstrapper.class ); protected NeoServerWithEmbeddedWebServer server; public static void main( String[] args ) { Bootstrapper bootstrapper = loadMostDerivedBootstrapper(); bootstrapper.start( args ); } public static Bootstrapper loadMostDerivedBootstrapper() { Bootstrapper winner = new NeoServerBootstrapper(); for ( Bootstrapper candidate : Service.load( Bootstrapper.class ) ) { if ( candidate.isMoreDerivedThan( winner ) ) winner = candidate; } return winner; } public void controlEvent( int arg ) { // Do nothing, required by the WrapperListener interface } public Integer start() { return start( new String[0] ); } public Integer start( String[] args ) { try { StartupHealthCheck startupHealthCheck = new StartupHealthCheck( rules() ); Jetty6WebServer webServer = new Jetty6WebServer(); server = new NeoServerWithEmbeddedWebServer( this, new AddressResolver(), startupHealthCheck, getConfigurator(), webServer, getServerModules(), new RealClock() ); server.start(); addShutdownHook(); return OK; } catch ( TransactionFailureException tfe ) { tfe.printStackTrace(); log.error( String.format( "Failed to start Neo Server on port [%d], because ", server.getWebServerPort() ) + tfe + ". Another process may be using database location " + server.getDatabase().getLocation() ); return GRAPH_DATABASE_STARTUP_ERROR_CODE; } catch ( Exception e ) { e.printStackTrace(); log.error( "Failed to start Neo Server on port [%s]", server.getWebServerPort() ); return WEB_SERVER_STARTUP_ERROR_CODE; } } public void stop() { stop( 0 ); } public int stop( int stopArg ) { String location = "unknown location"; try { if ( server != null ) { server.stop(); } log.info( "Successfully shutdown Neo Server on port [%d], database [%s]", server.getWebServerPort(), location ); return 0; } catch ( Exception e ) { log.error( "Failed to cleanly shutdown Neo Server on port [%d], database [%s]. Reason [%s] ", server.getWebServerPort(), location, e.getMessage() ); return 1; } } public NeoServerWithEmbeddedWebServer getServer() { return server; } protected abstract GraphDatabaseFactory getGraphDatabaseFactory( Configuration configuration ); protected abstract Iterable<StartupHealthCheckRule> getHealthCheckRules(); protected abstract Iterable<Class<? extends ServerModule>> getServerModules(); protected void addShutdownHook() { Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { log.info( "Neo4j Server shutdown initiated by kill signal" ); if ( server != null ) { server.stop(); } } } ); } protected Configurator getConfigurator() { File configFile = new File( System.getProperty( Configurator.NEO_SERVER_CONFIG_FILE_KEY, Configurator.DEFAULT_CONFIG_DIR ) ); return new PropertyFileConfigurator(new Validator(new DatabaseLocationMustBeSpecifiedRule()), configFile); } protected boolean isMoreDerivedThan( Bootstrapper other ) { // Default implementation just checks if this is a subclass of other return other.getClass().isAssignableFrom( getClass() ); } private StartupHealthCheckRule[] rules() { return IteratorUtil.asCollection( getHealthCheckRules() ).toArray( new StartupHealthCheckRule[0] ); } }
community/server/src/main/java/org/neo4j/server/Bootstrapper.java
/** * Copyright (c) 2002-2011 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.server; import java.io.File; import org.apache.commons.configuration.Configuration; import org.neo4j.graphdb.TransactionFailureException; import org.neo4j.helpers.Service; import org.neo4j.helpers.collection.IteratorUtil; import org.neo4j.server.configuration.Configurator; import org.neo4j.server.configuration.PropertyFileConfigurator; import org.neo4j.server.configuration.validation.DatabaseLocationMustBeSpecifiedRule; import org.neo4j.server.configuration.validation.Validator; import org.neo4j.server.database.GraphDatabaseFactory; import org.neo4j.server.logging.Logger; import org.neo4j.server.modules.ServerModule; import org.neo4j.server.startup.healthcheck.StartupHealthCheck; import org.neo4j.server.startup.healthcheck.StartupHealthCheckRule; import org.neo4j.server.web.Jetty6WebServer; public abstract class Bootstrapper { public static final Integer OK = 0; public static final Integer WEB_SERVER_STARTUP_ERROR_CODE = 1; public static final Integer GRAPH_DATABASE_STARTUP_ERROR_CODE = 2; /* public static final String KEY_LOG4J_CONFIG_XML_PATH = "log4j.config.xml.path"; */ private static Logger log = Logger.getLogger( NeoServerBootstrapper.class ); protected NeoServerWithEmbeddedWebServer server; public static void main( String[] args ) { Bootstrapper bootstrapper = loadMostDerivedBootstrapper(); bootstrapper.start( args ); } public static Bootstrapper loadMostDerivedBootstrapper() { Bootstrapper winner = new NeoServerBootstrapper(); for ( Bootstrapper candidate : Service.load( Bootstrapper.class ) ) { if ( candidate.isMoreDerivedThan( winner ) ) winner = candidate; } return winner; } public void controlEvent( int arg ) { // Do nothing, required by the WrapperListener interface } public Integer start() { return start( new String[0] ); } public Integer start( String[] args ) { try { StartupHealthCheck startupHealthCheck = new StartupHealthCheck( rules() ); Jetty6WebServer webServer = new Jetty6WebServer(); server = new NeoServerWithEmbeddedWebServer( this, new AddressResolver(), startupHealthCheck, getConfigurator(), webServer, getServerModules() ); server.start(); addShutdownHook(); return OK; } catch ( TransactionFailureException tfe ) { tfe.printStackTrace(); log.error( String.format( "Failed to start Neo Server on port [%d], because ", server.getWebServerPort() ) + tfe + ". Another process may be using database location " + server.getDatabase().getLocation() ); return GRAPH_DATABASE_STARTUP_ERROR_CODE; } catch ( Exception e ) { e.printStackTrace(); log.error( "Failed to start Neo Server on port [%s]", server.getWebServerPort() ); return WEB_SERVER_STARTUP_ERROR_CODE; } } public void stop() { stop( 0 ); } public int stop( int stopArg ) { String location = "unknown location"; try { if ( server != null ) { server.stop(); } log.info( "Successfully shutdown Neo Server on port [%d], database [%s]", server.getWebServerPort(), location ); return 0; } catch ( Exception e ) { log.error( "Failed to cleanly shutdown Neo Server on port [%d], database [%s]. Reason [%s] ", server.getWebServerPort(), location, e.getMessage() ); return 1; } } public NeoServerWithEmbeddedWebServer getServer() { return server; } protected abstract GraphDatabaseFactory getGraphDatabaseFactory( Configuration configuration ); protected abstract Iterable<StartupHealthCheckRule> getHealthCheckRules(); protected abstract Iterable<Class<? extends ServerModule>> getServerModules(); protected void addShutdownHook() { Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { log.info( "Neo4j Server shutdown initiated by kill signal" ); if ( server != null ) { server.stop(); } } } ); } protected Configurator getConfigurator() { File configFile = new File( System.getProperty( Configurator.NEO_SERVER_CONFIG_FILE_KEY, Configurator.DEFAULT_CONFIG_DIR ) ); return new PropertyFileConfigurator(new Validator(new DatabaseLocationMustBeSpecifiedRule()), configFile); } protected boolean isMoreDerivedThan( Bootstrapper other ) { // Default implementation just checks if this is a subclass of other return other.getClass().isAssignableFrom( getClass() ); } private StartupHealthCheckRule[] rules() { return IteratorUtil.asCollection( getHealthCheckRules() ).toArray( new StartupHealthCheckRule[0] ); } }
Added clocks as a dependency to the NeoServerWithEmbeddedWebServer
community/server/src/main/java/org/neo4j/server/Bootstrapper.java
Added clocks as a dependency to the NeoServerWithEmbeddedWebServer
<ide><path>ommunity/server/src/main/java/org/neo4j/server/Bootstrapper.java <ide> import org.neo4j.server.database.GraphDatabaseFactory; <ide> import org.neo4j.server.logging.Logger; <ide> import org.neo4j.server.modules.ServerModule; <add>import org.neo4j.server.rest.paging.RealClock; <ide> import org.neo4j.server.startup.healthcheck.StartupHealthCheck; <ide> import org.neo4j.server.startup.healthcheck.StartupHealthCheckRule; <ide> import org.neo4j.server.web.Jetty6WebServer; <ide> public static final Integer OK = 0; <ide> public static final Integer WEB_SERVER_STARTUP_ERROR_CODE = 1; <ide> public static final Integer GRAPH_DATABASE_STARTUP_ERROR_CODE = 2; <del> /* <del> public static final String KEY_LOG4J_CONFIG_XML_PATH = "log4j.config.xml.path"; <del> */ <ide> <ide> private static Logger log = Logger.getLogger( NeoServerBootstrapper.class ); <ide> <ide> StartupHealthCheck startupHealthCheck = new StartupHealthCheck( rules() ); <ide> Jetty6WebServer webServer = new Jetty6WebServer(); <ide> server = new NeoServerWithEmbeddedWebServer( this, new AddressResolver(), <del> startupHealthCheck, getConfigurator(), webServer, getServerModules() ); <add> startupHealthCheck, getConfigurator(), webServer, getServerModules(), new RealClock() ); <ide> server.start(); <ide> <ide> addShutdownHook();
Java
mit
4798b595e415b7d6e829ca6bfe825c8032f8fdc8
0
vinnyoodles/algorithms,vinnyoodles/algorithms,vinnyoodles/algorithms
/** * @Company Riot Games * * Given a list of kill events where a kill event is defined as [ timestamp, killerId, victimId ]. * Return a list of the users who have the largest killstreak. A killstreak is defined as a sequence * of kills where each kill is no more than 15 units of time from the next kill. * * If there is a tie of users with the largest killstreak, then return an array of them. * The return format should be a list of all the users with the largest killstreak in the format of a list of their ids. * * Problem Ex. * Input: [ * [ 1, 1, 2 ], * [ 5, 1, 3 ], * [ 3, 1, 4 ], * [ 9, 2, 1 ], * ] * Output: [ 1, 3 ] * * Note: the list of kills are not in any specific order. */ public List<Integer> largestKillstreak(int[][] kills) { Arrays.sort(kills, (a, b) -> a[0] - b[0]); // Mapping of userId -> [ killCount, killTime ]. HashMap<Integer, int[]> map = new HashMap<Integer, int[]>(); int max = Integer.MIN_VALUE; for (int i = 0; i < kills.length; i ++) { int timestamp = kills[i][0]; int killer = kills[i][1]; int pair = map.getOrDefault(killer, new int[] { 0, 0 }); if (pair[1] + 15 < timestmap) { pair[0] = 0; } pair[0] ++; pair[1] = timestamp; max = Math.max(max, pair[0]); map.put(killer, pair); } List<Integer> list = new ArrayList<Integer>(); for (int i : map.keySet()) { int[] pair = map.get(i); if (pair[0] == max) list.add(i); } return list; } /** * Part 2 expands on the definition of killstreak. * Killstreak is now defined as a sequence of kills where each kill is no more than 15 units of time from the next * as well as not dying from the beginning of the sequence to the end of the sequence. * * This is more commonly the actual definition of a multi killstreak found in games. */ public List<Integer> largestKillstreak(int[][] kills) { Arrays.sort(kills, (a, b) -> a[0] - b[0]); // Mapping of userId -> [ killCount, killTime ]. HashMap<Integer, int[]> map = new HashMap<Integer, int[]>(); int max = Integer.MIN_VALUE; for (int i = 0; i < kills.length; i ++) { int timestamp = kills[i][0]; int killer = kills[i][1]; int victim = kils[i][2]; // Reset the victim's kill count. if (map.containsKey(victim)) { int[] victimPair = map.get(victim); victimPair[0] = 0; map.put(victim, victimPair); } int pair = map.getOrDefault(killer, new int[] { 0, 0 }); if (pair[1] + 15 < timestmap) { pair[0] = 0; } pair[0] ++; pair[1] = timestamp; max = Math.max(max, pair[0]); map.put(killer, pair); } List<Integer> list = new ArrayList<Integer>(); for (int i : map.keySet()) { int[] pair = map.get(i); if (pair[0] == max) list.add(i); } return list; }
java/interview/largest-killstreak.java
/** * @Company Riot Games * * Given a list of kill events where a kill event is defined as [ timestamp, killerId, victimId ]. * Return a list of the users who have the largest killstreak. A killstreak is defined as a sequence * of kills where each kill is no more than 15 units of time from the next kill. * * If there is a tie of users with the largest killstreak, then return an array of them. * The return format should be a list of all the users with the largest killstreak in the format of an array. * [ killerId, number of kills ] * * Problem Ex. * Input: [ * [ 1, 1, 2 ], * [ 5, 1, 3 ], * [ 3, 1, 4 ], * [ 9, 2, 1 ], * ] * Output: [ * [ 1, 3 ] * ] * * Note: the list of kills are not in any specific order. */ public int[][] largestKillstreak(int[][] kills) { } /** * Part 2 expands on the definition of killstreak. * Killstreak is now defined as a sequence of kills where each kill is no more than 15 units of time from the next * as well as not dying from the beginning of the sequence to the end of the sequence. * * This is more commonly the actual definition of a multi killstreak found in games. */ public int[][] largestKillstreak(int[][] kills) { }
Add solution for largest killstreak
java/interview/largest-killstreak.java
Add solution for largest killstreak
<ide><path>ava/interview/largest-killstreak.java <ide> * of kills where each kill is no more than 15 units of time from the next kill. <ide> * <ide> * If there is a tie of users with the largest killstreak, then return an array of them. <del> * The return format should be a list of all the users with the largest killstreak in the format of an array. <del> * [ killerId, number of kills ] <add> * The return format should be a list of all the users with the largest killstreak in the format of a list of their ids. <ide> * <ide> * Problem Ex. <ide> * Input: [ <ide> * [ 3, 1, 4 ], <ide> * [ 9, 2, 1 ], <ide> * ] <del> * Output: [ <del> * [ 1, 3 ] <del> * ] <add> * Output: [ 1, 3 ] <ide> * <ide> * Note: the list of kills are not in any specific order. <ide> */ <del>public int[][] largestKillstreak(int[][] kills) { } <add>public List<Integer> largestKillstreak(int[][] kills) { <add> Arrays.sort(kills, (a, b) -> a[0] - b[0]); <add> // Mapping of userId -> [ killCount, killTime ]. <add> HashMap<Integer, int[]> map = new HashMap<Integer, int[]>(); <add> <add> int max = Integer.MIN_VALUE; <add> for (int i = 0; i < kills.length; i ++) { <add> int timestamp = kills[i][0]; <add> int killer = kills[i][1]; <add> int pair = map.getOrDefault(killer, new int[] { 0, 0 }); <add> if (pair[1] + 15 < timestmap) { <add> pair[0] = 0; <add> } <add> pair[0] ++; <add> pair[1] = timestamp; <add> max = Math.max(max, pair[0]); <add> map.put(killer, pair); <add> } <add> <add> List<Integer> list = new ArrayList<Integer>(); <add> <add> for (int i : map.keySet()) { <add> int[] pair = map.get(i); <add> if (pair[0] == max) list.add(i); <add> } <add> <add> return list; <add>} <ide> <ide> /** <ide> * Part 2 expands on the definition of killstreak. <ide> * <ide> * This is more commonly the actual definition of a multi killstreak found in games. <ide> */ <del>public int[][] largestKillstreak(int[][] kills) { } <add>public List<Integer> largestKillstreak(int[][] kills) { <add> Arrays.sort(kills, (a, b) -> a[0] - b[0]); <add> // Mapping of userId -> [ killCount, killTime ]. <add> HashMap<Integer, int[]> map = new HashMap<Integer, int[]>(); <add> <add> int max = Integer.MIN_VALUE; <add> for (int i = 0; i < kills.length; i ++) { <add> int timestamp = kills[i][0]; <add> int killer = kills[i][1]; <add> int victim = kils[i][2]; <add> <add> // Reset the victim's kill count. <add> if (map.containsKey(victim)) { <add> int[] victimPair = map.get(victim); <add> victimPair[0] = 0; <add> map.put(victim, victimPair); <add> } <add> <add> int pair = map.getOrDefault(killer, new int[] { 0, 0 }); <add> if (pair[1] + 15 < timestmap) { <add> pair[0] = 0; <add> } <add> pair[0] ++; <add> pair[1] = timestamp; <add> max = Math.max(max, pair[0]); <add> map.put(killer, pair); <add> } <add> <add> List<Integer> list = new ArrayList<Integer>(); <add> <add> for (int i : map.keySet()) { <add> int[] pair = map.get(i); <add> if (pair[0] == max) list.add(i); <add> } <add> <add> return list; <add>}
Java
mit
b48836c6492a69c6b43519a603ab743a1487cb0a
0
AydenSekey/24hDuCode2016
package fr.soprasteria.jeu; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JComponent; import fr.soprasteria.jeu.moteur.tirlaser.TirLaserControler; import fr.soprasteria.jeu.view.CaseView; import fr.soprasteria.world.Personnage; import fr.soprasteria.world.Position; import fr.soprasteria.world.WorldGrille; import fr.soprasteria.world.cases.Case; import fr.soprasteria.world.cases.Cible; import fr.soprasteria.world.cases.CibleListener; import fr.soprasteria.world.laser.Laser; import fr.soprasteria.world.laser.LaserDirection; public class PanneauJeuGaming extends PanneauJeu implements CibleListener { private TirLaserControler laserControler; public PanneauJeuGaming() { super(); } public PanneauJeuGaming(WorldGrille grille) { super(grille); laserControler = new TirLaserControler(grille); miseCibleEnEcoute(); this.initialiserComportement(); } private void miseCibleEnEcoute() { for(int col = 0; col < grille.getNbColonnes(); col++) { for(int li = 0; li < grille.getNbLignes(); li++) { Case c = grille.getCase(col, li); if(c instanceof Cible) { ((Cible) c).addListener(this); } } } } public void initialiserComportement() { this.setFocusable(true); this.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_RIGHT) { bougerPersonnageADroite(0); repaint(); } if(e.getKeyCode() == KeyEvent.VK_LEFT) { bougerPersonnageAGauche(0); repaint(); } if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { finirNiveau(); } if(e.getKeyCode() == KeyEvent.VK_SPACE) { if(!grille.getPersonnages().isEmpty()) { Personnage perso = grille.getPersonnages().get(0); Laser laser = perso.tirer(); laserControler.calculTirLaserRecursif(laser); dessinerLaser(laser); } } if(e.getKeyCode() == KeyEvent.VK_NUMPAD4) { Personnage perso = grille.getPersonnages().get(0); perso.setDirectionArme(LaserDirection.OUEST); CaseView caseView = (CaseView) getGridButton(perso.getX(), perso.getY()); caseView.changerPersonnage(LaserDirection.OUEST); } if(e.getKeyCode() == KeyEvent.VK_NUMPAD7) { Personnage perso = grille.getPersonnages().get(0); perso.setDirectionArme(LaserDirection.NORD_OUEST); CaseView caseView = (CaseView) getGridButton(perso.getX(), perso.getY()); caseView.changerPersonnage(LaserDirection.NORD_OUEST); } if(e.getKeyCode() == KeyEvent.VK_NUMPAD8) { Personnage perso = grille.getPersonnages().get(0); perso.setDirectionArme(LaserDirection.NORD); CaseView caseView = (CaseView) getGridButton(perso.getX(), perso.getY()); caseView.changerPersonnage(LaserDirection.NORD); } if(e.getKeyCode() == KeyEvent.VK_NUMPAD9) { Personnage perso = grille.getPersonnages().get(0); perso.setDirectionArme(LaserDirection.NORD_EST); CaseView caseView = (CaseView) getGridButton(perso.getX(), perso.getY()); caseView.changerPersonnage(LaserDirection.NORD_EST); } if(e.getKeyCode() == KeyEvent.VK_NUMPAD6) { System.out.println("s"); Personnage perso = grille.getPersonnages().get(0); perso.setDirectionArme(LaserDirection.EST); CaseView caseView = (CaseView) getGridButton(perso.getX(), perso.getY()); caseView.changerPersonnage(LaserDirection.EST); } } }); } public void bougerPersonnageADroite(int persoNumero) { Personnage perso = this.grille.getPersonnages().get(persoNumero); CaseView caseView = (CaseView) this.getGridButton(perso.getX(), perso.getY()); if(perso.getX() < this.grille.getNbColonnes() - 1) { caseView.retirerPersonnage(); CaseView caseViewVoisine = (CaseView) this.getGridButton(perso.getX()+1, perso.getY()); caseViewVoisine.afficherPersonnage(perso); perso.setX(perso.getX()+1); } } public void bougerPersonnageAGauche(int persoNumero) { Personnage perso = this.grille.getPersonnages().get(persoNumero); CaseView caseView = (CaseView) this.getGridButton(perso.getX(), perso.getY()); if(perso.getX() > 0) { caseView.retirerPersonnage(); CaseView caseViewVoisine = (CaseView) this.getGridButton(perso.getX()-1, perso.getY()); caseViewVoisine.afficherPersonnage(perso); perso.setX(perso.getX()-1); perso.setCaseOccupee(caseViewVoisine.getModele()); } } public void finirNiveau() { FenetreJeu.getInstance().changerPanneau(PanneauSelectionNiveau.getInstance()); } public void dessinerLaser(Point pointSrc, Point pointCible, Color couleur) { Graphics g = this.getGraphics(); if(g != null) { Graphics2D g2d = ( Graphics2D ) g; g2d.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); g2d.setPaint (couleur); g2d.drawLine((int)pointSrc.getX(), (int)pointSrc.getY(), (int)pointCible.getX(), (int)pointCible.getY()); } else { System.err.println("WARNING : support de dessin indisponible."); } } private void dessinerLaser(Laser laser) { Position origine = laser.getOrigine(); Position arret = laser.getArret(); JComponent c = getGridButton(origine.getX(), origine.getY()); Point pSrc = middleLocation(c); Point pCible; if(arret == null) { // Laser non interrompu -> doit atteindre le bord de l'écran pCible = determinerBordPan(pSrc, laser.getDirection()); } else { // Laser interrompu par une case pCible = middleLocation(getGridButton(arret.getX(), arret.getY())); } dessinerLaser(pSrc, pCible, laser.getCouleur()); } /** * Détermine un point dans le prolongement de la direction permettant d'avoir un trait finissant au bord ou en dehors de l'écran. * @param origine les coordonnées d'origine du laser * @param direction la direction du laser * @return le point de fin du segmet de laser. */ private Point determinerBordPan(Point origine, LaserDirection direction) { Point bordPoint = null; int xDistanceWithMin; int yDistanceWithMin; int minDistance; switch (direction) { case OUEST: bordPoint = new Point(this.getWidth(), (int) origine.getY()); break; case NORD_OUEST: xDistanceWithMin = (int) origine.getX(); yDistanceWithMin = (int) origine.getY(); minDistance = Math.min(xDistanceWithMin, yDistanceWithMin); bordPoint = new Point((int) origine.getX() - minDistance,(int) origine.getY() - minDistance); break; case NORD: bordPoint = new Point((int) origine.getX(), 0); break; case NORD_EST: xDistanceWithMin = this.getWidth() - (int) origine.getX(); yDistanceWithMin = (int) origine.getY(); minDistance = Math.min(xDistanceWithMin, yDistanceWithMin); bordPoint = new Point((int) origine.getX() + minDistance, (int) origine.getY() - minDistance); break; case EST: bordPoint = new Point(this.getWidth(), (int) origine.getY()); break; case SUD_EST: xDistanceWithMin = this.getWidth() - (int) origine.getX(); yDistanceWithMin = this.getHeight() - (int) origine.getY(); minDistance = Math.min(xDistanceWithMin, yDistanceWithMin); bordPoint = new Point((int) origine.getX() + minDistance, (int) origine.getY() + minDistance); break; case SUD: bordPoint = new Point((int) origine.getX(), this.getHeight()); break; case SUD_OUEST: xDistanceWithMin = (int) origine.getX(); yDistanceWithMin = this.getHeight() - (int) origine.getY(); minDistance = Math.min(xDistanceWithMin, yDistanceWithMin); bordPoint = new Point((int) origine.getX() - minDistance, (int) origine.getY() + minDistance); break; default: break; } return bordPoint; } /** * Donne la position du centre d'un composant par rappord au coin supérieur gauche de son parent. * @param component le composant pour lequel on veut la position du centre * @return la position du centre du composant. */ private Point middleLocation(JComponent component) { Point pos = component.getLocation(); int witdh = component.getWidth(); int height = component.getHeight(); int midX = (int) pos.getX() + witdh / 2; int midY = (int) pos.getY() + height / 2; return new Point(midX, midY); } @Override public void cibleTouchee() { System.out.println("SUCCESS !"); finirNiveau(); } }
src/main/java/fr/soprasteria/jeu/PanneauJeuGaming.java
package fr.soprasteria.jeu; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.JComponent; import fr.soprasteria.jeu.moteur.tirlaser.TirLaserControler; import fr.soprasteria.jeu.view.CaseView; import fr.soprasteria.world.Personnage; import fr.soprasteria.world.Position; import fr.soprasteria.world.WorldGrille; import fr.soprasteria.world.cases.Case; import fr.soprasteria.world.cases.Cible; import fr.soprasteria.world.cases.CibleListener; import fr.soprasteria.world.laser.Laser; import fr.soprasteria.world.laser.LaserDirection; public class PanneauJeuGaming extends PanneauJeu implements CibleListener { private TirLaserControler laserControler; public PanneauJeuGaming() { super(); } public PanneauJeuGaming(WorldGrille grille) { super(grille); laserControler = new TirLaserControler(grille); miseCibleEnEcoute(); this.initialiserComportement(); } private void miseCibleEnEcoute() { for(int col = 0; col < grille.getNbColonnes(); col++) { for(int li = 0; li < grille.getNbLignes(); li++) { Case c = grille.getCase(col, li); if(c instanceof Cible) { ((Cible) c).addListener(this); } } } } public void initialiserComportement() { this.setFocusable(true); this.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_RIGHT) { bougerPersonnageADroite(0); repaint(); } if(e.getKeyCode() == KeyEvent.VK_LEFT) { bougerPersonnageAGauche(0); repaint(); } if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { finirNiveau(); } if(e.getKeyCode() == KeyEvent.VK_SPACE) { if(!grille.getPersonnages().isEmpty()) { Personnage perso = grille.getPersonnages().get(0); Laser laser = perso.tirer(); laserControler.calculTirLaserRecursif(laser); dessinerLaser(laser); } } if(e.getKeyCode() == KeyEvent.VK_NUMPAD4) { Personnage perso = grille.getPersonnages().get(0); perso.setDirectionArme(LaserDirection.OUEST); CaseView caseView = (CaseView) getGridButton(perso.getX(), perso.getY()); caseView.changerPersonnage(LaserDirection.OUEST); } if(e.getKeyCode() == KeyEvent.VK_NUMPAD7) { Personnage perso = grille.getPersonnages().get(0); perso.setDirectionArme(LaserDirection.NORD_OUEST); CaseView caseView = (CaseView) getGridButton(perso.getX(), perso.getY()); caseView.changerPersonnage(LaserDirection.NORD_OUEST); } if(e.getKeyCode() == KeyEvent.VK_NUMPAD8) { Personnage perso = grille.getPersonnages().get(0); perso.setDirectionArme(LaserDirection.NORD); CaseView caseView = (CaseView) getGridButton(perso.getX(), perso.getY()); caseView.changerPersonnage(LaserDirection.NORD); } if(e.getKeyCode() == KeyEvent.VK_NUMPAD9) { Personnage perso = grille.getPersonnages().get(0); perso.setDirectionArme(LaserDirection.NORD_EST); CaseView caseView = (CaseView) getGridButton(perso.getX(), perso.getY()); caseView.changerPersonnage(LaserDirection.NORD_EST); } if(e.getKeyCode() == KeyEvent.VK_NUMPAD6) { System.out.println("s"); Personnage perso = grille.getPersonnages().get(0); perso.setDirectionArme(LaserDirection.EST); CaseView caseView = (CaseView) getGridButton(perso.getX(), perso.getY()); caseView.changerPersonnage(LaserDirection.EST); } } }); } public void bougerPersonnageADroite(int persoNumero) { Personnage perso = this.grille.getPersonnages().get(persoNumero); CaseView caseView = (CaseView) this.getGridButton(perso.getX(), perso.getY()); caseView.retirerPersonnage(); CaseView caseViewVoisine = (CaseView) this.getGridButton(perso.getX()+1, perso.getY()); caseViewVoisine.afficherPersonnage(perso); perso.setX(perso.getX()+1); } public void bougerPersonnageAGauche(int persoNumero) { Personnage perso = this.grille.getPersonnages().get(persoNumero); CaseView caseView = (CaseView) this.getGridButton(perso.getX(), perso.getY()); caseView.retirerPersonnage(); CaseView caseViewVoisine = (CaseView) this.getGridButton(perso.getX()-1, perso.getY()); caseViewVoisine.afficherPersonnage(perso); perso.setX(perso.getX()-1); perso.setCaseOccupee(caseViewVoisine.getModele()); } public void finirNiveau() { FenetreJeu.getInstance().changerPanneau(PanneauSelectionNiveau.getInstance()); } public void dessinerLaser(Point pointSrc, Point pointCible, Color couleur) { Graphics g = this.getGraphics(); if(g != null) { Graphics2D g2d = ( Graphics2D ) g; g2d.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); g2d.setPaint (couleur); g2d.drawLine((int)pointSrc.getX(), (int)pointSrc.getY(), (int)pointCible.getX(), (int)pointCible.getY()); } else { System.err.println("WARNING : support de dessin indisponible."); } } private void dessinerLaser(Laser laser) { Position origine = laser.getOrigine(); Position arret = laser.getArret(); JComponent c = getGridButton(origine.getX(), origine.getY()); Point pSrc = middleLocation(c); Point pCible; if(arret == null) { // Laser non interrompu -> doit atteindre le bord de l'écran pCible = determinerBordPan(pSrc, laser.getDirection()); } else { // Laser interrompu par une case pCible = middleLocation(getGridButton(arret.getX(), arret.getY())); } dessinerLaser(pSrc, pCible, laser.getCouleur()); } /** * Détermine un point dans le prolongement de la direction permettant d'avoir un trait finissant au bord ou en dehors de l'écran. * @param origine les coordonnées d'origine du laser * @param direction la direction du laser * @return le point de fin du segmet de laser. */ private Point determinerBordPan(Point origine, LaserDirection direction) { Point bordPoint = null; int xDistanceWithMin; int yDistanceWithMin; int minDistance; switch (direction) { case OUEST: bordPoint = new Point(this.getWidth(), (int) origine.getY()); break; case NORD_OUEST: xDistanceWithMin = (int) origine.getX(); yDistanceWithMin = (int) origine.getY(); minDistance = Math.min(xDistanceWithMin, yDistanceWithMin); bordPoint = new Point((int) origine.getX() - minDistance,(int) origine.getY() - minDistance); break; case NORD: bordPoint = new Point((int) origine.getX(), 0); break; case NORD_EST: xDistanceWithMin = this.getWidth() - (int) origine.getX(); yDistanceWithMin = (int) origine.getY(); minDistance = Math.min(xDistanceWithMin, yDistanceWithMin); bordPoint = new Point((int) origine.getX() + minDistance, (int) origine.getY() - minDistance); break; case EST: bordPoint = new Point(this.getWidth(), (int) origine.getY()); break; case SUD_EST: xDistanceWithMin = this.getWidth() - (int) origine.getX(); yDistanceWithMin = this.getHeight() - (int) origine.getY(); minDistance = Math.min(xDistanceWithMin, yDistanceWithMin); bordPoint = new Point((int) origine.getX() + minDistance, (int) origine.getY() + minDistance); break; case SUD: bordPoint = new Point((int) origine.getX(), this.getHeight()); break; case SUD_OUEST: xDistanceWithMin = (int) origine.getX(); yDistanceWithMin = this.getHeight() - (int) origine.getY(); minDistance = Math.min(xDistanceWithMin, yDistanceWithMin); bordPoint = new Point((int) origine.getX() - minDistance, (int) origine.getY() + minDistance); break; default: break; } return bordPoint; } /** * Donne la position du centre d'un composant par rappord au coin supérieur gauche de son parent. * @param component le composant pour lequel on veut la position du centre * @return la position du centre du composant. */ private Point middleLocation(JComponent component) { Point pos = component.getLocation(); int witdh = component.getWidth(); int height = component.getHeight(); int midX = (int) pos.getX() + witdh / 2; int midY = (int) pos.getY() + height / 2; return new Point(midX, midY); } @Override public void cibleTouchee() { System.out.println("SUCCESS !"); finirNiveau(); } }
Correction débordement d'écran.
src/main/java/fr/soprasteria/jeu/PanneauJeuGaming.java
Correction débordement d'écran.
<ide><path>rc/main/java/fr/soprasteria/jeu/PanneauJeuGaming.java <ide> { <ide> Personnage perso = this.grille.getPersonnages().get(persoNumero); <ide> CaseView caseView = (CaseView) this.getGridButton(perso.getX(), perso.getY()); <del> caseView.retirerPersonnage(); <del> CaseView caseViewVoisine = (CaseView) this.getGridButton(perso.getX()+1, perso.getY()); <del> caseViewVoisine.afficherPersonnage(perso); <del> perso.setX(perso.getX()+1); <add> if(perso.getX() < this.grille.getNbColonnes() - 1) { <add> caseView.retirerPersonnage(); <add> CaseView caseViewVoisine = (CaseView) this.getGridButton(perso.getX()+1, perso.getY()); <add> caseViewVoisine.afficherPersonnage(perso); <add> perso.setX(perso.getX()+1); <add> } <ide> } <ide> <ide> public void bougerPersonnageAGauche(int persoNumero) <ide> { <ide> Personnage perso = this.grille.getPersonnages().get(persoNumero); <ide> CaseView caseView = (CaseView) this.getGridButton(perso.getX(), perso.getY()); <del> caseView.retirerPersonnage(); <del> CaseView caseViewVoisine = (CaseView) this.getGridButton(perso.getX()-1, perso.getY()); <del> caseViewVoisine.afficherPersonnage(perso); <del> perso.setX(perso.getX()-1); <del> perso.setCaseOccupee(caseViewVoisine.getModele()); <add> if(perso.getX() > 0) { <add> caseView.retirerPersonnage(); <add> CaseView caseViewVoisine = (CaseView) this.getGridButton(perso.getX()-1, perso.getY()); <add> caseViewVoisine.afficherPersonnage(perso); <add> perso.setX(perso.getX()-1); <add> perso.setCaseOccupee(caseViewVoisine.getModele()); <add> } <ide> } <ide> <ide> public void finirNiveau()
Java
apache-2.0
716108f1b88a8d76a402fdf7d0231f3beaaffc87
0
idea4bsd/idea4bsd,fengbaicanhe/intellij-community,asedunov/intellij-community,diorcety/intellij-community,kool79/intellij-community,retomerz/intellij-community,diorcety/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,signed/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,amith01994/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,consulo/consulo,jagguli/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,da1z/intellij-community,orekyuu/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,apixandru/intellij-community,diorcety/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,consulo/consulo,jagguli/intellij-community,wreckJ/intellij-community,consulo/consulo,vladmm/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,holmes/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,ernestp/consulo,holmes/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,slisson/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,robovm/robovm-studio,adedayo/intellij-community,nicolargo/intellij-community,supersven/intellij-community,robovm/robovm-studio,kool79/intellij-community,supersven/intellij-community,ryano144/intellij-community,joewalnes/idea-community,caot/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,izonder/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,FHannes/intellij-community,ernestp/consulo,jexp/idea2,asedunov/intellij-community,nicolargo/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,kdwink/intellij-community,ryano144/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,fitermay/intellij-community,da1z/intellij-community,semonte/intellij-community,suncycheng/intellij-community,izonder/intellij-community,fnouama/intellij-community,ernestp/consulo,xfournet/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,slisson/intellij-community,ernestp/consulo,robovm/robovm-studio,gnuhub/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,holmes/intellij-community,apixandru/intellij-community,izonder/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,jexp/idea2,Distrotech/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,adedayo/intellij-community,caot/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,joewalnes/idea-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,joewalnes/idea-community,blademainer/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,vladmm/intellij-community,fnouama/intellij-community,clumsy/intellij-community,ernestp/consulo,alphafoobar/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,semonte/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,allotria/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,holmes/intellij-community,samthor/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,nicolargo/intellij-community,semonte/intellij-community,consulo/consulo,petteyg/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,samthor/intellij-community,vladmm/intellij-community,kool79/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,jagguli/intellij-community,xfournet/intellij-community,signed/intellij-community,FHannes/intellij-community,holmes/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,diorcety/intellij-community,kdwink/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,signed/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,fitermay/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,lucafavatella/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,slisson/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,signed/intellij-community,nicolargo/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,samthor/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,izonder/intellij-community,fitermay/intellij-community,FHannes/intellij-community,allotria/intellij-community,jagguli/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,kool79/intellij-community,suncycheng/intellij-community,kool79/intellij-community,xfournet/intellij-community,dslomov/intellij-community,semonte/intellij-community,holmes/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,izonder/intellij-community,caot/intellij-community,amith01994/intellij-community,retomerz/intellij-community,blademainer/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,blademainer/intellij-community,petteyg/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,apixandru/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,kool79/intellij-community,xfournet/intellij-community,orekyuu/intellij-community,da1z/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,caot/intellij-community,fitermay/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,izonder/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,Distrotech/intellij-community,consulo/consulo,nicolargo/intellij-community,alphafoobar/intellij-community,allotria/intellij-community,izonder/intellij-community,samthor/intellij-community,vvv1559/intellij-community,holmes/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,asedunov/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,amith01994/intellij-community,kool79/intellij-community,vladmm/intellij-community,vladmm/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,diorcety/intellij-community,kdwink/intellij-community,retomerz/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,suncycheng/intellij-community,clumsy/intellij-community,caot/intellij-community,holmes/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,signed/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,hurricup/intellij-community,amith01994/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,allotria/intellij-community,da1z/intellij-community,da1z/intellij-community,vladmm/intellij-community,amith01994/intellij-community,jagguli/intellij-community,allotria/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,ryano144/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,signed/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,slisson/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,fnouama/intellij-community,jexp/idea2,caot/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,signed/intellij-community,signed/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,ryano144/intellij-community,hurricup/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,joewalnes/idea-community,blademainer/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,supersven/intellij-community,blademainer/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,caot/intellij-community,da1z/intellij-community,retomerz/intellij-community,hurricup/intellij-community,supersven/intellij-community,signed/intellij-community,samthor/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,FHannes/intellij-community,FHannes/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,xfournet/intellij-community,semonte/intellij-community,fitermay/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,joewalnes/idea-community,tmpgit/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,samthor/intellij-community,jagguli/intellij-community,vladmm/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ryano144/intellij-community,semonte/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,caot/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,ernestp/consulo,da1z/intellij-community,jexp/idea2,youdonghai/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,jexp/idea2,salguarnieri/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,allotria/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,semonte/intellij-community,allotria/intellij-community,robovm/robovm-studio,samthor/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,apixandru/intellij-community,semonte/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,joewalnes/idea-community,apixandru/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,supersven/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,adedayo/intellij-community,jexp/idea2,diorcety/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,jexp/idea2,youdonghai/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,amith01994/intellij-community,allotria/intellij-community,nicolargo/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,samthor/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,allotria/intellij-community,signed/intellij-community,jexp/idea2,ryano144/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,joewalnes/idea-community,salguarnieri/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,consulo/consulo,nicolargo/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,samthor/intellij-community,kdwink/intellij-community,allotria/intellij-community,ryano144/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,da1z/intellij-community
package com.intellij.codeInsight.javadoc; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.TargetElementUtil; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.hint.ParameterInfoController; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.ide.BrowserUtil; import com.intellij.ide.DataManager; import com.intellij.ide.util.gotoByName.ChooseByNameBase; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.PopupStep; import com.intellij.openapi.ui.popup.util.BaseListPopupStep; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileSystem; import com.intellij.openapi.vfs.ex.http.HttpFileSystem; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.psi.*; import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.presentation.java.SymbolPresentationUtil; import com.intellij.psi.util.PsiFormatUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlText; import com.intellij.ui.popup.JBPopupImpl; import com.intellij.util.Alarm; import com.intellij.xml.util.documentation.XmlDocumentationProvider; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; public class JavaDocManager implements ProjectComponent { @NonNls public static final String JAVADOC_LOCATION_AND_SIZE = "javadoc.popup"; private final Project myProject; private Editor myEditor = null; private ParameterInfoController myParameterInfoController; private final Alarm myUpdateDocAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD); private WeakReference<JBPopup> myDocInfoHintRef; private Component myPreviouslyFocused = null; public static final Key<SmartPsiElementPointer> ORIGINAL_ELEMENT_KEY = Key.create("Original element"); @NonNls private static final String HTML_EXTENSION = ".html"; @NonNls private static final String PACKAGE_SUMMARY_FILE = "package-summary.html"; @NonNls public static final String PSI_ELEMENT_PROTOCOL = "psi_element://"; @NonNls private static final String DOC_ELEMENT_PROTOCOL = "doc_element://"; private final ActionManagerEx myActionManagerEx; private final AnActionListener myActionListener = new AnActionListener() { public void beforeActionPerformed(AnAction action, DataContext dataContext) { final JBPopup hint = getDocInfoHint(); if (hint != null) { if (action instanceof HintManager.ActionToIgnore) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN)) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP)) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_DOWN)) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_UP)) return; if (action == ActionManagerEx.getInstanceEx().getAction(IdeActions.ACTION_EDITOR_ESCAPE)) return; hint.cancel(); } } public void beforeEditorTyping(char c, DataContext dataContext) { final JBPopup hint = getDocInfoHint(); if (hint != null) { hint.cancel(); } } public void afterActionPerformed(final AnAction action, final DataContext dataContext) { } }; private static final int ourFlagsForTargetElements = TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED | TargetElementUtil.LOOKUP_ITEM_ACCEPTED | TargetElementUtil.NEW_AS_CONSTRUCTOR | TargetElementUtil.THIS_ACCEPTED | TargetElementUtil.SUPER_ACCEPTED; public static JavaDocManager getInstance(Project project) { return project.getComponent(JavaDocManager.class); } public JavaDocManager(Project project, ActionManagerEx managerEx) { myProject = project; myActionManagerEx = managerEx; } @NotNull public String getComponentName() { return "JavaDocManager"; } public void initComponent() { } public void disposeComponent() { } public void projectOpened() { myActionManagerEx.addAnActionListener(myActionListener); } public void projectClosed() { myActionManagerEx.removeAnActionListener(myActionListener); } public JBPopup showJavaDocInfo(@NotNull PsiElement element) { final JavaDocInfoComponent component = new JavaDocInfoComponent(this); final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component) .setRequestFocusIfNotLookupOrSearch(getProject(element)) .setLookupAndSearchUpdater(new Condition<PsiElement>() { public boolean value(final PsiElement element) { showJavaDocInfo(element); return false; } }, getProject(element)) .setForceHeavyweight(true) .setDimensionServiceKey(myProject, JAVADOC_LOCATION_AND_SIZE, false) .setResizable(true) .setMovable(true) .setTitle(getTitle(element)) .setCancelCallback(new Computable<Boolean>() { public Boolean compute() { if (fromQuickSearch()) { ((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).unregisterHint(); } Disposer.dispose(component); myEditor = null; myPreviouslyFocused = null; return Boolean.TRUE; } }) .createPopup(); JBPopupImpl oldHint = (JBPopupImpl)getDocInfoHint(); if (oldHint != null) { JavaDocInfoComponent oldComponent = (JavaDocInfoComponent)oldHint.getComponent(); PsiElement element1 = oldComponent.getElement(); if (Comparing.equal(element, element1)) { return oldHint; } oldHint.cancel(); } component.setHint(hint); fetchDocInfo(getDefaultProvider(element), component); myDocInfoHintRef = new WeakReference<JBPopup>(hint); myPreviouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(getProject(element)); if (fromQuickSearch()) { ((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).registerHint(hint); } return hint; } @Nullable public JBPopup showJavaDocInfo(final Editor editor, @Nullable PsiFile file, boolean requestFocus) { myEditor = editor; final Project project = getProject(file); PsiDocumentManager.getInstance(project).commitAllDocuments(); final PsiElement list = ParameterInfoController.findArgumentList(file, editor.getCaretModel().getOffset(), -1); if (list != null) { myParameterInfoController = ParameterInfoController.findControllerAtOffset(editor, list.getTextRange().getStartOffset()); } PsiElement originalElement = file != null ? file.findElementAt(editor.getCaretModel().getOffset()) : null; PsiElement element = findTargetElement(editor, file, originalElement); if (element instanceof PsiAnonymousClass) { element = ((PsiAnonymousClass)element).getBaseClassType().resolve(); } if (element == null && myParameterInfoController != null) { final Object[] objects = myParameterInfoController.getSelectedElements(); if (objects != null && objects.length > 0) { element = getPsiElementFromParameterInfoObject(objects[0], element); } } if (element == null && file != null) { // look if we are within a javadoc comment element = originalElement; if (element == null) return null; PsiDocComment comment = PsiTreeUtil.getParentOfType(element, PsiDocComment.class); if (comment == null) return null; element = comment.getParent(); if (!(element instanceof PsiDocCommentOwner)) return null; } JBPopupImpl oldHint = (JBPopupImpl)getDocInfoHint(); if (oldHint != null) { JavaDocInfoComponent component = (JavaDocInfoComponent)oldHint.getComponent(); PsiElement element1 = component.getElement(); if (element != null && Comparing.equal(element, element1)) { if (requestFocus) { component.getComponent().requestFocus(); } return oldHint; } oldHint.cancel(); } final JavaDocInfoComponent component = new JavaDocInfoComponent(this); storeOriginalElement(project, originalElement, element); final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component) .setRequestFocusIfNotLookupOrSearch(project) .setLookupAndSearchUpdater(new Condition<PsiElement>() { public boolean value(final PsiElement element) { if (myEditor != null){ final PsiFile file = element.getContainingFile(); if (file != null) { Editor editor = myEditor; showJavaDocInfo(myEditor, file, false); myEditor = editor; } } else { showJavaDocInfo(element); } return false; } }, project) .setForceHeavyweight(false) .setDimensionServiceKey(project, JAVADOC_LOCATION_AND_SIZE, false) .setResizable(true) .setMovable(true) .setTitle(getTitle(element)) .setCancelCallback(new Computable<Boolean>(){ public Boolean compute() { if (fromQuickSearch()) { ((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).unregisterHint(); } Disposer.dispose(component); myEditor = null; myPreviouslyFocused = null; myParameterInfoController = null; return Boolean.TRUE; } }) .createPopup(); component.setHint(hint); fetchDocInfo(getDefaultProvider(element), component); myDocInfoHintRef = new WeakReference<JBPopup>(hint); myPreviouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(project); return hint; } private static String getTitle(final PsiElement element) { final String title = SymbolPresentationUtil.getSymbolPresentableText(element); return CodeInsightBundle.message("javadoc.info.title", title != null ? title : element.getText()); } private static void storeOriginalElement(final Project project, final PsiElement originalElement, final PsiElement element) { if (element == null) return; try { element.putUserData( ORIGINAL_ELEMENT_KEY, SmartPointerManager.getInstance(project).createSmartPsiElementPointer(originalElement) ); } catch (RuntimeException ex) { // PsiPackage does not allow putUserData } } @Nullable public PsiElement findTargetElement(final Editor editor, @Nullable final PsiFile file, PsiElement contextElement) { PsiElement element = editor != null ? TargetElementUtil.findTargetElement(editor, ourFlagsForTargetElements) : null; // Allow context doc over xml tag content if (element == null && contextElement != null) { final PsiElement parent = contextElement.getParent(); if (parent instanceof XmlText) { element = TargetElementUtil.findTargetElement(editor, ourFlagsForTargetElements, parent.getParent().getTextRange().getStartOffset() + 1 ); } else if (parent instanceof XmlTag || parent instanceof XmlAttribute) { element = TargetElementUtil.findTargetElement(editor, ourFlagsForTargetElements, parent.getTextRange().getStartOffset() + 1 ); } else if (parent instanceof XmlAttributeValue) { final PsiElement grandParent = parent.getParent(); element = TargetElementUtil.findTargetElement(editor, ourFlagsForTargetElements, grandParent.getTextRange().getStartOffset() + 1 ); } } if (element == null && editor != null) { final PsiReference ref = TargetElementUtil.findReference(editor, editor.getCaretModel().getOffset()); if (ref != null) { final PsiElement parent = ref.getElement().getParent(); if (parent instanceof PsiMethodCallExpression) { element = parent; } else if (ref instanceof PsiPolyVariantReference) { element = ref.getElement(); } } final Lookup activeLookup = LookupManager.getInstance(myProject).getActiveLookup(); if (activeLookup != null) { LookupItem item = activeLookup.getCurrentItem(); if (item == null) return null; final DocumentationProvider documentationProvider = getProviderFromElement(file); if (documentationProvider!=null) { element = documentationProvider.getDocumentationElementForLookupItem( PsiManager.getInstance(myProject), item.getObject(), ref != null ? ref.getElement():contextElement ); } } } storeOriginalElement(myProject, contextElement, element); return element; } private boolean fromQuickSearch() { return myPreviouslyFocused != null && myPreviouslyFocused.getParent() instanceof ChooseByNameBase.JPanelProvider; } @Nullable private static PsiElement getPsiElementFromParameterInfoObject(final Object o, PsiElement element) { if (o instanceof CandidateInfo) { element = ((CandidateInfo)o).getElement(); } else if (o instanceof PsiElement) { element = (PsiElement)o; } return element; } public JavaDocProvider getDefaultProvider(final PsiElement _element) { return new JavaDocProvider() { private final SmartPsiElementPointer element = SmartPointerManager.getInstance(_element.getProject()).createSmartPsiElementPointer(_element); public String getJavaDoc() throws Exception { return getDocInfo(element.getElement()); } public PsiElement getElement() { return element.getElement(); } }; } @Nullable public static List<String> getExternalJavaDocUrl(final PsiElement element) { List<String> urls = null; if (element instanceof PsiClass) { urls = findUrlForClass((PsiClass)element); } else if (element instanceof PsiField) { PsiField field = (PsiField)element; PsiClass aClass = field.getContainingClass(); if (aClass != null) { urls = findUrlForClass(aClass); if (urls != null) { for (int i = 0; i < urls.size(); i++) { urls.set(i, urls.get(i) +"#" + field.getName()); } } } } else if (element instanceof PsiMethod) { PsiMethod method = (PsiMethod)element; PsiClass aClass = method.getContainingClass(); if (aClass != null) { urls = findUrlForClass(aClass); if (urls != null) { String signature = PsiFormatUtil.formatMethod(method, PsiSubstitutor.EMPTY, PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_PARAMETERS, PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.SHOW_FQ_CLASS_NAMES , 999); for (int i = 0; i < urls.size(); i++) { urls.set(i, urls.get(i) + "#" + signature); } } } } else if (element instanceof PsiPackage) { urls = findUrlForPackage((PsiPackage)element); } else if (element instanceof PsiDirectory) { PsiPackage aPackage = ((PsiDirectory)element).getPackage(); if (aPackage != null) { urls = findUrlForPackage(aPackage); } } else { DocumentationProvider provider = getProviderFromElement(element); if (provider!=null) { final SmartPsiElementPointer originalElementPointer = element.getUserData(ORIGINAL_ELEMENT_KEY); final String url = provider.getUrlFor(element, originalElementPointer != null ? originalElementPointer.getElement() : null); if (url != null) { urls = new ArrayList<String>(); urls.add(url); } } } if (urls == null) { return null; } else { for (int i = 0; i < urls.size(); i++) { urls.set(i, FileUtil.toSystemIndependentName(urls.get(i)).replaceAll("[\\<\\>\\?]", "")); } return urls; } } public void openJavaDoc(final PsiElement element) { FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.javadoc.external"); List<String> urls = getExternalJavaDocUrl(element); if (urls != null && !urls.isEmpty()) { if (urls.size() > 1) { JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<String>("", urls){ public PopupStep onChosen(final String selectedValue, final boolean finalChoice) { BrowserUtil.launchBrowser(selectedValue); return PopupStep.FINAL_CHOICE; } }); } else { BrowserUtil.launchBrowser(urls.get(0)); } } else { final JBPopup docInfoHint = getDocInfoHint(); if (docInfoHint != null && docInfoHint.isVisible()){ docInfoHint.cancel(); } Messages.showMessageDialog(getProject(element), CodeInsightBundle.message("javadoc.documentation.not.found.message"), CodeInsightBundle.message("javadoc.documentation.not.found.title"), Messages.getErrorIcon()); } } @Nullable private JBPopup getDocInfoHint() { if (myDocInfoHintRef == null) return null; JBPopup hint = myDocInfoHintRef.get(); if (hint == null || !hint.isVisible()) { myDocInfoHintRef = null; return null; } return hint; } @Nullable private static List<String> findUrlForClass(PsiClass aClass) { String qName = aClass.getQualifiedName(); if (qName == null) return null; PsiFile file = aClass.getContainingFile(); if (!(file instanceof PsiJavaFile)) return null; String packageName = ((PsiJavaFile)file).getPackageName(); String relPath; if (packageName.length() > 0) { relPath = packageName.replace('.', '/') + '/' + qName.substring(packageName.length() + 1) + HTML_EXTENSION; } else { relPath = qName + HTML_EXTENSION; } final PsiFile containingFile = aClass.getContainingFile(); if (containingFile == null) return null; final VirtualFile virtualFile = containingFile.getVirtualFile(); if (virtualFile == null) return null; return findUrlForVirtualFile(containingFile.getProject(), virtualFile, relPath); } @Nullable private static List<String> findUrlForVirtualFile(final Project project, final VirtualFile virtualFile, final String relPath) { final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); Module module = fileIndex.getModuleForFile(virtualFile); if (module == null) { final VirtualFileSystem fs = virtualFile.getFileSystem(); if (fs instanceof JarFileSystem) { final VirtualFile jar = ((JarFileSystem)fs).getVirtualFileForJar(virtualFile); if (jar != null) { module = fileIndex.getModuleForFile(jar); } } } if (module != null) { VirtualFile[] javadocPaths = ModuleRootManager.getInstance(module).getJavadocPaths(); List<String> httpRoot = getHttpRoots(javadocPaths, relPath); if (httpRoot != null) return httpRoot; } final List<OrderEntry> orderEntries = fileIndex.getOrderEntriesForFile(virtualFile); for (OrderEntry orderEntry : orderEntries) { final VirtualFile[] files = orderEntry.getFiles(OrderRootType.JAVADOC); final List<String> httpRoot = getHttpRoots(files, relPath); if (httpRoot != null) return httpRoot; } return null; } @Nullable private static List<String> getHttpRoots(final VirtualFile[] roots, String relPath) { final ArrayList<String> result = new ArrayList<String>(); for (VirtualFile root : roots) { if (root.getFileSystem() instanceof HttpFileSystem) { result.add(root.getUrl() + relPath); } else { VirtualFile file = root.findFileByRelativePath(relPath); if (file != null) result.add(file.getUrl()); } } return result.isEmpty() ? null : result; } @Nullable private static List<String> findUrlForPackage(PsiPackage aPackage) { String qName = aPackage.getQualifiedName(); qName = qName.replace('.', '/') + '/' + PACKAGE_SUMMARY_FILE; for(PsiDirectory directory: aPackage.getDirectories()) { List<String> url = findUrlForVirtualFile(aPackage.getProject(),directory.getVirtualFile(), qName); if (url != null) { return url; } } return null; } @Nullable private String findUrlForLink(PsiPackage basePackage, String link) { int index = link.indexOf('#'); String tail = ""; if (index >= 0) { tail = link.substring(index); link = link.substring(0, index); } String qName = basePackage.getQualifiedName(); qName = qName.replace('.', File.separatorChar); String[] docPaths = JavaDocUtil.getDocPaths(getProject(basePackage)); for (String docPath : docPaths) { String url = docPath + File.separator + qName + File.separatorChar + link; File file = new File(url); if (file.exists()) return url + tail; } return null; } public void fetchDocInfo(final JavaDocProvider provider, final JavaDocInfoComponent component) { doFetchDocInfo(component, provider, true); } public void queueFetchDocInfo(final JavaDocProvider provider, final JavaDocInfoComponent component) { doFetchDocInfo(component, provider, false); } private void doFetchDocInfo(final JavaDocInfoComponent component, final JavaDocProvider provider, final boolean cancelRequests) { component.startWait(); if (cancelRequests) { myUpdateDocAlarm.cancelAllRequests(); } SwingUtilities.invokeLater(new Runnable() { public void run() { if (component.isEmpty()) { component.setText(CodeInsightBundle.message("javadoc.fetching.progress")); } } }); myUpdateDocAlarm.addRequest(new Runnable() { public void run() { final Exception[] ex = new Exception[1]; final String text = ApplicationManager.getApplication().runReadAction(new Computable<String>() { @Nullable public String compute() { try { return provider.getJavaDoc(); } catch (Exception e) { ex[0] = e; } return null; } }); if (ex[0] != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { component.setText(CodeInsightBundle.message("javadoc.external.fetch.error.message", ex[0].getLocalizedMessage()), true); } }); return; } final PsiElement element = provider.getElement(); SwingUtilities.invokeLater(new Runnable() { public void run() { if (text == null) { component.setText(CodeInsightBundle.message("no.documentation.found"), true); } else if (text.length() == 0) { component.setText(component.getText(), true); } else { component.setData(element, text); } final JBPopupImpl jbPopup = (JBPopupImpl)getDocInfoHint(); if(jbPopup==null){ return; } jbPopup.setCaption(getTitle(element)); final String dimensionServiceKey = jbPopup.getDimensionServiceKey(); Dimension dimension = component.getPreferredSize(); final Dimension storedSize = dimensionServiceKey != null ? DimensionService.getInstance().getSize(dimensionServiceKey, getProject(element)) : null; if (storedSize != null) { dimension = storedSize; } final Window window = SwingUtilities.getWindowAncestor(component); if (window != null) { window.setBounds(window.getX(), window.getY(), dimension.width, dimension.height); window.validate(); window.repaint(); } } }); } }, 10); } @Nullable private String getDocInfo(PsiElement element) throws Exception { if (element instanceof PsiMethodCallExpression) { return getMethodCandidateInfo((PsiMethodCallExpression)element); } else { final DocumentationProvider provider = getProviderFromElement(element); final JavaDocInfoGenerator javaDocInfoGenerator = new JavaDocInfoGenerator(getProject(element), element, provider); if (myParameterInfoController != null) { final Object[] objects = myParameterInfoController.getSelectedElements(); if (objects.length > 0) { @NonNls StringBuffer sb = null; for(Object o:objects) { PsiElement parameter = getPsiElementFromParameterInfoObject(o, null); if (parameter != null) { final String str2 = new JavaDocInfoGenerator(getProject(element), parameter, provider).generateDocInfo(); if (str2 == null) continue; if (sb == null) sb = new StringBuffer(); sb.append(str2); sb.append("<br>"); } else { sb = null; break; } } if (sb != null) return sb.toString(); } } JavaDocExternalFilter docFilter = new JavaDocExternalFilter(getProject(element)); List<String> docURLs = getExternalJavaDocUrl(element); if (docURLs != null) { for (String docURL : docURLs) { if (element instanceof PsiCompiledElement) { try { String externalDoc = docFilter.getExternalDocInfoForElement(docURL, element); if (externalDoc != null) { return externalDoc; } } catch (FileNotFoundException e) { //try to generate some javadoc } } } } return docFilter.filterInternalDocInfo(javaDocInfoGenerator.generateDocInfo(), null); } } @Nullable public static DocumentationProvider getProviderFromElement(final PsiElement element) { SmartPsiElementPointer originalElementPointer = element!=null ? element.getUserData(ORIGINAL_ELEMENT_KEY):null; PsiElement originalElement = originalElementPointer != null ? originalElementPointer.getElement() : null; PsiFile containingFile = originalElement != null ? originalElement.getContainingFile() : element != null ? element.getContainingFile() : null; DocumentationProvider originalProvider = containingFile != null ? containingFile.getLanguage().getDocumentationProvider() : null; DocumentationProvider elementProvider = element == null ? null : element.getLanguage().getDocumentationProvider(); if (elementProvider == null || (elementProvider instanceof XmlDocumentationProvider && originalProvider != null)) { return originalProvider; } return elementProvider; //give priority to the real element } private String getMethodCandidateInfo(PsiMethodCallExpression expr) { final PsiResolveHelper rh = expr.getManager().getResolveHelper(); final CandidateInfo[] candidates = rh.getReferencedMethodCandidates(expr, true); final String text = expr.getText(); if (candidates.length > 0) { @NonNls final StringBuffer sb = new StringBuffer(); for (final CandidateInfo candidate : candidates) { final PsiElement element = candidate.getElement(); if (!(element instanceof PsiMethod)) { continue; } final String str = PsiFormatUtil.formatMethod((PsiMethod)element, candidate.getSubstitutor(), PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.SHOW_PARAMETERS, PsiFormatUtil.SHOW_TYPE); createElementLink(sb, element, str); } return CodeInsightBundle.message("javadoc.candiates", text, sb); } return CodeInsightBundle.message("javadoc.candidates.not.found", text); } private void createElementLink(@NonNls final StringBuffer sb, final PsiElement element, final String str) { sb.append("&nbsp;&nbsp;<a href=\"psi_element://"); sb.append(JavaDocUtil.getReferenceText(getProject(element), element)); sb.append("\">"); sb.append(str); sb.append("</a>"); sb.append("<br>"); } void navigateByLink(final JavaDocInfoComponent component, String url) { component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final PsiManager manager = PsiManager.getInstance(getProject(component.getElement())); if (url.startsWith(PSI_ELEMENT_PROTOCOL)) { final String refText = url.substring(PSI_ELEMENT_PROTOCOL.length()); final PsiElement targetElement = JavaDocUtil.findReferenceTarget(manager, refText, component.getElement()); if (targetElement != null) { fetchDocInfo(getDefaultProvider(targetElement), component); } } else { final String docUrl = url; fetchDocInfo (new JavaDocProvider() { String getElementLocator(String url) { if (url.startsWith(DOC_ELEMENT_PROTOCOL)) { return url.substring(DOC_ELEMENT_PROTOCOL.length()); } return null; } public String getJavaDoc() throws Exception { String url = getElementLocator(docUrl); if (url != null && JavaDocExternalFilter.isJavaDocURL(url)) { String text = new JavaDocExternalFilter(getProject(component.getElement())).getExternalDocInfo(url); if (text != null) { return text; } } if (url == null) { url = docUrl; } PsiElement element = component.getElement(); if (element != null) { PsiElement parent = element; while (true) { if (parent == null || parent instanceof PsiDirectory) break; parent = parent.getParent(); } if (parent != null) { PsiPackage aPackage = ((PsiDirectory)parent).getPackage(); if (aPackage != null) { String url1 = findUrlForLink(aPackage, url); if (url1 != null) { url = url1; } } } } BrowserUtil.launchBrowser(url); return ""; } public PsiElement getElement() { //String loc = getElementLocator(docUrl); // //if (loc != null) { // PsiElement context = component.getElement(); // return JavaDocUtil.findReferenceTarget(context.getManager(), loc, context); //} return component.getElement(); } }, component); } component.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } void showHint(final JBPopup hint) { if (myEditor != null) { hint.showInBestPositionFor(myEditor); } else if (myPreviouslyFocused != null) { hint.showInBestPositionFor(DataManager.getInstance().getDataContext(myPreviouslyFocused)); } } public void requestFocus() { if (fromQuickSearch()) { myPreviouslyFocused.getParent().requestFocus(); } } public Project getProject(@Nullable final PsiElement element) { assert element == null || myProject == element.getProject(); return myProject; } }
codeInsight/impl/com/intellij/codeInsight/javadoc/JavaDocManager.java
package com.intellij.codeInsight.javadoc; import com.intellij.codeInsight.CodeInsightBundle; import com.intellij.codeInsight.TargetElementUtil; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.hint.ParameterInfoController; import com.intellij.codeInsight.lookup.Lookup; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.codeInsight.lookup.LookupManager; import com.intellij.featureStatistics.FeatureUsageTracker; import com.intellij.ide.BrowserUtil; import com.intellij.ide.DataManager; import com.intellij.ide.util.gotoByName.ChooseByNameBase; import com.intellij.lang.documentation.DocumentationProvider; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.*; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.popup.JBPopup; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.ui.popup.PopupStep; import com.intellij.openapi.ui.popup.util.BaseListPopupStep; import com.intellij.openapi.util.*; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.JarFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileSystem; import com.intellij.openapi.vfs.ex.http.HttpFileSystem; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.psi.*; import com.intellij.psi.infos.CandidateInfo; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.presentation.java.SymbolPresentationUtil; import com.intellij.psi.util.PsiFormatUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.xml.XmlAttribute; import com.intellij.psi.xml.XmlAttributeValue; import com.intellij.psi.xml.XmlTag; import com.intellij.psi.xml.XmlText; import com.intellij.ui.popup.JBPopupImpl; import com.intellij.util.Alarm; import com.intellij.xml.util.documentation.XmlDocumentationProvider; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.FileNotFoundException; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; public class JavaDocManager implements ProjectComponent { @NonNls public static final String JAVADOC_LOCATION_AND_SIZE = "javadoc.popup"; private final Project myProject; private Editor myEditor = null; private ParameterInfoController myParameterInfoController; private final Alarm myUpdateDocAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD); private WeakReference<JBPopup> myDocInfoHintRef; private Component myPreviouslyFocused = null; public static final Key<SmartPsiElementPointer> ORIGINAL_ELEMENT_KEY = Key.create("Original element"); @NonNls private static final String HTML_EXTENSION = ".html"; @NonNls private static final String PACKAGE_SUMMARY_FILE = "package-summary.html"; @NonNls public static final String PSI_ELEMENT_PROTOCOL = "psi_element://"; @NonNls private static final String DOC_ELEMENT_PROTOCOL = "doc_element://"; private final ActionManagerEx myActionManagerEx; private final AnActionListener myActionListener = new AnActionListener() { public void beforeActionPerformed(AnAction action, DataContext dataContext) { final JBPopup hint = getDocInfoHint(); if (hint != null) { if (action instanceof HintManager.ActionToIgnore) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_DOWN)) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_UP)) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_DOWN)) return; if (action == myActionManagerEx.getAction(IdeActions.ACTION_EDITOR_MOVE_CARET_PAGE_UP)) return; if (action == ActionManagerEx.getInstanceEx().getAction(IdeActions.ACTION_EDITOR_ESCAPE)) return; hint.cancel(); } } public void beforeEditorTyping(char c, DataContext dataContext) { final JBPopup hint = getDocInfoHint(); if (hint != null) { hint.cancel(); } } public void afterActionPerformed(final AnAction action, final DataContext dataContext) { } }; private static final int ourFlagsForTargetElements = TargetElementUtil.ELEMENT_NAME_ACCEPTED | TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED | TargetElementUtil.LOOKUP_ITEM_ACCEPTED | TargetElementUtil.NEW_AS_CONSTRUCTOR | TargetElementUtil.THIS_ACCEPTED | TargetElementUtil.SUPER_ACCEPTED; public static JavaDocManager getInstance(Project project) { return project.getComponent(JavaDocManager.class); } public JavaDocManager(Project project, ActionManagerEx managerEx) { myProject = project; myActionManagerEx = managerEx; } @NotNull public String getComponentName() { return "JavaDocManager"; } public void initComponent() { } public void disposeComponent() { } public void projectOpened() { myActionManagerEx.addAnActionListener(myActionListener); } public void projectClosed() { myActionManagerEx.removeAnActionListener(myActionListener); } public JBPopup showJavaDocInfo(@NotNull PsiElement element) { final JavaDocInfoComponent component = new JavaDocInfoComponent(this); final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component) .setRequestFocusIfNotLookupOrSearch(getProject(element)) .setLookupAndSearchUpdater(new Condition<PsiElement>() { public boolean value(final PsiElement element) { showJavaDocInfo(element); return false; } }, getProject(element)) .setForceHeavyweight(true) .setDimensionServiceKey(myProject, JAVADOC_LOCATION_AND_SIZE, false) .setResizable(true) .setMovable(true) .setTitle(getTitle(element)) .setCancelCallback(new Computable<Boolean>() { public Boolean compute() { if (fromQuickSearch()) { ((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).unregisterHint(); } Disposer.dispose(component); myEditor = null; myPreviouslyFocused = null; return Boolean.TRUE; } }) .createPopup(); JBPopupImpl oldHint = (JBPopupImpl)getDocInfoHint(); if (oldHint != null) { JavaDocInfoComponent oldComponent = (JavaDocInfoComponent)oldHint.getComponent(); PsiElement element1 = oldComponent.getElement(); if (Comparing.equal(element, element1)) { return oldHint; } oldHint.cancel(); } component.setHint(hint); fetchDocInfo(getDefaultProvider(element), component); myDocInfoHintRef = new WeakReference<JBPopup>(hint); myPreviouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(getProject(element)); if (fromQuickSearch()) { ((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).registerHint(hint); } return hint; } @Nullable public JBPopup showJavaDocInfo(final Editor editor, @Nullable PsiFile file, boolean requestFocus) { myEditor = editor; final Project project = getProject(file); PsiDocumentManager.getInstance(project).commitAllDocuments(); final PsiElement list = ParameterInfoController.findArgumentList(file, editor.getCaretModel().getOffset(), -1); if (list != null) { myParameterInfoController = ParameterInfoController.findControllerAtOffset(editor, list.getTextRange().getStartOffset()); } PsiElement originalElement = file != null ? file.findElementAt(editor.getCaretModel().getOffset()) : null; PsiElement element = findTargetElement(editor, file, originalElement); if (element instanceof PsiAnonymousClass) { element = ((PsiAnonymousClass)element).getBaseClassType().resolve(); } if (element == null && myParameterInfoController != null) { final Object[] objects = myParameterInfoController.getSelectedElements(); if (objects != null && objects.length > 0) { element = getPsiElementFromParameterInfoObject(objects[0], element); } } if (element == null && file != null) { // look if we are within a javadoc comment element = originalElement; if (element == null) return null; PsiDocComment comment = PsiTreeUtil.getParentOfType(element, PsiDocComment.class); if (comment == null) return null; element = comment.getParent(); if (!(element instanceof PsiDocCommentOwner)) return null; } JBPopupImpl oldHint = (JBPopupImpl)getDocInfoHint(); if (oldHint != null) { JavaDocInfoComponent component = (JavaDocInfoComponent)oldHint.getComponent(); PsiElement element1 = component.getElement(); if (element != null && Comparing.equal(element, element1)) { if (requestFocus) { component.getComponent().requestFocus(); } return oldHint; } oldHint.cancel(); } final JavaDocInfoComponent component = new JavaDocInfoComponent(this); storeOriginalElement(project, originalElement, element); final JBPopup hint = JBPopupFactory.getInstance().createComponentPopupBuilder(component, component) .setRequestFocusIfNotLookupOrSearch(project) .setLookupAndSearchUpdater(new Condition<PsiElement>() { public boolean value(final PsiElement element) { if (myEditor != null){ final PsiFile file = element.getContainingFile(); if (file != null) { Editor editor = myEditor; showJavaDocInfo(myEditor, file, false); myEditor = editor; } } else { showJavaDocInfo(element); } return false; } }, project) .setForceHeavyweight(false) .setDimensionServiceKey(project, JAVADOC_LOCATION_AND_SIZE, false) .setResizable(true) .setMovable(true) .setTitle(getTitle(element)) .setCancelCallback(new Computable<Boolean>(){ public Boolean compute() { if (fromQuickSearch()) { ((ChooseByNameBase.JPanelProvider)myPreviouslyFocused.getParent()).unregisterHint(); } Disposer.dispose(component); myEditor = null; myPreviouslyFocused = null; myParameterInfoController = null; return Boolean.TRUE; } }) .createPopup(); component.setHint(hint); fetchDocInfo(getDefaultProvider(element), component); myDocInfoHintRef = new WeakReference<JBPopup>(hint); myPreviouslyFocused = WindowManagerEx.getInstanceEx().getFocusedComponent(project); return hint; } private static String getTitle(final PsiElement element) { final String title = SymbolPresentationUtil.getSymbolPresentableText(element); return CodeInsightBundle.message("javadoc.info.title", title != null ? title : element.getText()); } private static void storeOriginalElement(final Project project, final PsiElement originalElement, final PsiElement element) { if (element == null) return; try { element.putUserData( ORIGINAL_ELEMENT_KEY, SmartPointerManager.getInstance(project).createSmartPsiElementPointer(originalElement) ); } catch (RuntimeException ex) { // PsiPackage does not allow putUserData } } @Nullable public PsiElement findTargetElement(final Editor editor, @Nullable final PsiFile file, PsiElement contextElement) { PsiElement element = editor != null ? TargetElementUtil.findTargetElement(editor, ourFlagsForTargetElements) : null; // Allow context doc over xml tag content if (element == null && contextElement != null) { final PsiElement parent = contextElement.getParent(); if (parent instanceof XmlText) { element = TargetElementUtil.findTargetElement(editor, ourFlagsForTargetElements, parent.getParent().getTextRange().getStartOffset() + 1 ); } else if (parent instanceof XmlTag || parent instanceof XmlAttribute) { element = TargetElementUtil.findTargetElement(editor, ourFlagsForTargetElements, parent.getTextRange().getStartOffset() + 1 ); } else if (parent instanceof XmlAttributeValue) { final PsiElement grandParent = parent.getParent(); element = TargetElementUtil.findTargetElement(editor, ourFlagsForTargetElements, grandParent.getTextRange().getStartOffset() + 1 ); } } if (element == null && editor != null) { final PsiReference ref = TargetElementUtil.findReference(editor, editor.getCaretModel().getOffset()); if (ref != null) { final PsiElement parent = ref.getElement().getParent(); if (parent instanceof PsiMethodCallExpression) { element = parent; } else if (ref instanceof PsiPolyVariantReference) { element = ref.getElement(); } } final Lookup activeLookup = LookupManager.getInstance(myProject).getActiveLookup(); if (activeLookup != null) { LookupItem item = activeLookup.getCurrentItem(); if (item == null) return null; final DocumentationProvider documentationProvider = getProviderFromElement(file); if (documentationProvider!=null) { element = documentationProvider.getDocumentationElementForLookupItem( PsiManager.getInstance(myProject), item.getObject(), ref != null ? ref.getElement():contextElement ); } } } storeOriginalElement(myProject, contextElement, element); return element; } private boolean fromQuickSearch() { return myPreviouslyFocused != null && myPreviouslyFocused.getParent() instanceof ChooseByNameBase.JPanelProvider; } @Nullable private static PsiElement getPsiElementFromParameterInfoObject(final Object o, PsiElement element) { if (o instanceof CandidateInfo) { element = ((CandidateInfo)o).getElement(); } else if (o instanceof PsiElement) { element = (PsiElement)o; } return element; } public JavaDocProvider getDefaultProvider(final PsiElement _element) { return new JavaDocProvider() { private final SmartPsiElementPointer element = SmartPointerManager.getInstance(_element.getProject()).createSmartPsiElementPointer(_element); public String getJavaDoc() throws Exception { return getDocInfo(element.getElement()); } public PsiElement getElement() { return element.getElement(); } }; } @Nullable public static List<String> getExternalJavaDocUrl(final PsiElement element) { List<String> urls = null; if (element instanceof PsiClass) { urls = findUrlForClass((PsiClass)element); } else if (element instanceof PsiField) { PsiField field = (PsiField)element; PsiClass aClass = field.getContainingClass(); if (aClass != null) { urls = findUrlForClass(aClass); if (urls != null) { for (int i = 0; i < urls.size(); i++) { urls.set(i, urls.get(i) +"#" + field.getName()); } } } } else if (element instanceof PsiMethod) { PsiMethod method = (PsiMethod)element; PsiClass aClass = method.getContainingClass(); if (aClass != null) { urls = findUrlForClass(aClass); if (urls != null) { String signature = PsiFormatUtil.formatMethod(method, PsiSubstitutor.EMPTY, PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_PARAMETERS, PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.SHOW_FQ_CLASS_NAMES | PsiFormatUtil.SHOW_RAW_TYPE, 999); for (int i = 0; i < urls.size(); i++) { urls.set(i, urls.get(i) + "#" + signature); } } } } else if (element instanceof PsiPackage) { urls = findUrlForPackage((PsiPackage)element); } else if (element instanceof PsiDirectory) { PsiPackage aPackage = ((PsiDirectory)element).getPackage(); if (aPackage != null) { urls = findUrlForPackage(aPackage); } } else { DocumentationProvider provider = getProviderFromElement(element); if (provider!=null) { final SmartPsiElementPointer originalElementPointer = element.getUserData(ORIGINAL_ELEMENT_KEY); final String url = provider.getUrlFor(element, originalElementPointer != null ? originalElementPointer.getElement() : null); if (url != null) { urls = new ArrayList<String>(); urls.add(url); } } } if (urls == null) { return null; } else { for (int i = 0; i < urls.size(); i++) { urls.set(i, FileUtil.toSystemIndependentName(urls.get(i)).replaceAll("[\\<\\>\\?]", "")); } return urls; } } public void openJavaDoc(final PsiElement element) { FeatureUsageTracker.getInstance().triggerFeatureUsed("codeassists.javadoc.external"); List<String> urls = getExternalJavaDocUrl(element); if (urls != null && !urls.isEmpty()) { if (urls.size() > 1) { JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<String>("", urls){ public PopupStep onChosen(final String selectedValue, final boolean finalChoice) { BrowserUtil.launchBrowser(selectedValue); return PopupStep.FINAL_CHOICE; } }); } else { BrowserUtil.launchBrowser(urls.get(0)); } } else { final JBPopup docInfoHint = getDocInfoHint(); if (docInfoHint != null && docInfoHint.isVisible()){ docInfoHint.cancel(); } Messages.showMessageDialog(getProject(element), CodeInsightBundle.message("javadoc.documentation.not.found.message"), CodeInsightBundle.message("javadoc.documentation.not.found.title"), Messages.getErrorIcon()); } } @Nullable private JBPopup getDocInfoHint() { if (myDocInfoHintRef == null) return null; JBPopup hint = myDocInfoHintRef.get(); if (hint == null || !hint.isVisible()) { myDocInfoHintRef = null; return null; } return hint; } @Nullable private static List<String> findUrlForClass(PsiClass aClass) { String qName = aClass.getQualifiedName(); if (qName == null) return null; PsiFile file = aClass.getContainingFile(); if (!(file instanceof PsiJavaFile)) return null; String packageName = ((PsiJavaFile)file).getPackageName(); String relPath; if (packageName.length() > 0) { relPath = packageName.replace('.', '/') + '/' + qName.substring(packageName.length() + 1) + HTML_EXTENSION; } else { relPath = qName + HTML_EXTENSION; } final PsiFile containingFile = aClass.getContainingFile(); if (containingFile == null) return null; final VirtualFile virtualFile = containingFile.getVirtualFile(); if (virtualFile == null) return null; return findUrlForVirtualFile(containingFile.getProject(), virtualFile, relPath); } @Nullable private static List<String> findUrlForVirtualFile(final Project project, final VirtualFile virtualFile, final String relPath) { final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); Module module = fileIndex.getModuleForFile(virtualFile); if (module == null) { final VirtualFileSystem fs = virtualFile.getFileSystem(); if (fs instanceof JarFileSystem) { final VirtualFile jar = ((JarFileSystem)fs).getVirtualFileForJar(virtualFile); if (jar != null) { module = fileIndex.getModuleForFile(jar); } } } if (module != null) { VirtualFile[] javadocPaths = ModuleRootManager.getInstance(module).getJavadocPaths(); List<String> httpRoot = getHttpRoots(javadocPaths, relPath); if (httpRoot != null) return httpRoot; } final List<OrderEntry> orderEntries = fileIndex.getOrderEntriesForFile(virtualFile); for (OrderEntry orderEntry : orderEntries) { final VirtualFile[] files = orderEntry.getFiles(OrderRootType.JAVADOC); final List<String> httpRoot = getHttpRoots(files, relPath); if (httpRoot != null) return httpRoot; } return null; } @Nullable private static List<String> getHttpRoots(final VirtualFile[] roots, String relPath) { final ArrayList<String> result = new ArrayList<String>(); for (VirtualFile root : roots) { if (root.getFileSystem() instanceof HttpFileSystem) { result.add(root.getUrl() + relPath); } else { VirtualFile file = root.findFileByRelativePath(relPath); if (file != null) result.add(file.getUrl()); } } return result.isEmpty() ? null : result; } @Nullable private static List<String> findUrlForPackage(PsiPackage aPackage) { String qName = aPackage.getQualifiedName(); qName = qName.replace('.', '/') + '/' + PACKAGE_SUMMARY_FILE; for(PsiDirectory directory: aPackage.getDirectories()) { List<String> url = findUrlForVirtualFile(aPackage.getProject(),directory.getVirtualFile(), qName); if (url != null) { return url; } } return null; } @Nullable private String findUrlForLink(PsiPackage basePackage, String link) { int index = link.indexOf('#'); String tail = ""; if (index >= 0) { tail = link.substring(index); link = link.substring(0, index); } String qName = basePackage.getQualifiedName(); qName = qName.replace('.', File.separatorChar); String[] docPaths = JavaDocUtil.getDocPaths(getProject(basePackage)); for (String docPath : docPaths) { String url = docPath + File.separator + qName + File.separatorChar + link; File file = new File(url); if (file.exists()) return url + tail; } return null; } public void fetchDocInfo(final JavaDocProvider provider, final JavaDocInfoComponent component) { doFetchDocInfo(component, provider, true); } public void queueFetchDocInfo(final JavaDocProvider provider, final JavaDocInfoComponent component) { doFetchDocInfo(component, provider, false); } private void doFetchDocInfo(final JavaDocInfoComponent component, final JavaDocProvider provider, final boolean cancelRequests) { component.startWait(); if (cancelRequests) { myUpdateDocAlarm.cancelAllRequests(); } SwingUtilities.invokeLater(new Runnable() { public void run() { if (component.isEmpty()) { component.setText(CodeInsightBundle.message("javadoc.fetching.progress")); } } }); myUpdateDocAlarm.addRequest(new Runnable() { public void run() { final Exception[] ex = new Exception[1]; final String text = ApplicationManager.getApplication().runReadAction(new Computable<String>() { @Nullable public String compute() { try { return provider.getJavaDoc(); } catch (Exception e) { ex[0] = e; } return null; } }); if (ex[0] != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { component.setText(CodeInsightBundle.message("javadoc.external.fetch.error.message", ex[0].getLocalizedMessage()), true); } }); return; } final PsiElement element = provider.getElement(); SwingUtilities.invokeLater(new Runnable() { public void run() { if (text == null) { component.setText(CodeInsightBundle.message("no.documentation.found"), true); } else if (text.length() == 0) { component.setText(component.getText(), true); } else { component.setData(element, text); } final JBPopupImpl jbPopup = (JBPopupImpl)getDocInfoHint(); if(jbPopup==null){ return; } jbPopup.setCaption(getTitle(element)); final String dimensionServiceKey = jbPopup.getDimensionServiceKey(); Dimension dimension = component.getPreferredSize(); final Dimension storedSize = dimensionServiceKey != null ? DimensionService.getInstance().getSize(dimensionServiceKey, getProject(element)) : null; if (storedSize != null) { dimension = storedSize; } final Window window = SwingUtilities.getWindowAncestor(component); if (window != null) { window.setBounds(window.getX(), window.getY(), dimension.width, dimension.height); window.validate(); window.repaint(); } } }); } }, 10); } @Nullable private String getDocInfo(PsiElement element) throws Exception { if (element instanceof PsiMethodCallExpression) { return getMethodCandidateInfo((PsiMethodCallExpression)element); } else { final DocumentationProvider provider = getProviderFromElement(element); final JavaDocInfoGenerator javaDocInfoGenerator = new JavaDocInfoGenerator(getProject(element), element, provider); if (myParameterInfoController != null) { final Object[] objects = myParameterInfoController.getSelectedElements(); if (objects.length > 0) { @NonNls StringBuffer sb = null; for(Object o:objects) { PsiElement parameter = getPsiElementFromParameterInfoObject(o, null); if (parameter != null) { final String str2 = new JavaDocInfoGenerator(getProject(element), parameter, provider).generateDocInfo(); if (str2 == null) continue; if (sb == null) sb = new StringBuffer(); sb.append(str2); sb.append("<br>"); } else { sb = null; break; } } if (sb != null) return sb.toString(); } } JavaDocExternalFilter docFilter = new JavaDocExternalFilter(getProject(element)); List<String> docURLs = getExternalJavaDocUrl(element); if (docURLs != null) { for (String docURL : docURLs) { if (element instanceof PsiCompiledElement) { try { String externalDoc = docFilter.getExternalDocInfoForElement(docURL, element); if (externalDoc != null) { return externalDoc; } } catch (FileNotFoundException e) { //try to generate some javadoc } } } } return docFilter.filterInternalDocInfo(javaDocInfoGenerator.generateDocInfo(), null); } } @Nullable public static DocumentationProvider getProviderFromElement(final PsiElement element) { SmartPsiElementPointer originalElementPointer = element!=null ? element.getUserData(ORIGINAL_ELEMENT_KEY):null; PsiElement originalElement = originalElementPointer != null ? originalElementPointer.getElement() : null; PsiFile containingFile = originalElement != null ? originalElement.getContainingFile() : element != null ? element.getContainingFile() : null; DocumentationProvider originalProvider = containingFile != null ? containingFile.getLanguage().getDocumentationProvider() : null; DocumentationProvider elementProvider = element == null ? null : element.getLanguage().getDocumentationProvider(); if (elementProvider == null || (elementProvider instanceof XmlDocumentationProvider && originalProvider != null)) { return originalProvider; } return elementProvider; //give priority to the real element } private String getMethodCandidateInfo(PsiMethodCallExpression expr) { final PsiResolveHelper rh = expr.getManager().getResolveHelper(); final CandidateInfo[] candidates = rh.getReferencedMethodCandidates(expr, true); final String text = expr.getText(); if (candidates.length > 0) { @NonNls final StringBuffer sb = new StringBuffer(); for (final CandidateInfo candidate : candidates) { final PsiElement element = candidate.getElement(); if (!(element instanceof PsiMethod)) { continue; } final String str = PsiFormatUtil.formatMethod((PsiMethod)element, candidate.getSubstitutor(), PsiFormatUtil.SHOW_NAME | PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.SHOW_PARAMETERS, PsiFormatUtil.SHOW_TYPE); createElementLink(sb, element, str); } return CodeInsightBundle.message("javadoc.candiates", text, sb); } return CodeInsightBundle.message("javadoc.candidates.not.found", text); } private void createElementLink(@NonNls final StringBuffer sb, final PsiElement element, final String str) { sb.append("&nbsp;&nbsp;<a href=\"psi_element://"); sb.append(JavaDocUtil.getReferenceText(getProject(element), element)); sb.append("\">"); sb.append(str); sb.append("</a>"); sb.append("<br>"); } void navigateByLink(final JavaDocInfoComponent component, String url) { component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final PsiManager manager = PsiManager.getInstance(getProject(component.getElement())); if (url.startsWith(PSI_ELEMENT_PROTOCOL)) { final String refText = url.substring(PSI_ELEMENT_PROTOCOL.length()); final PsiElement targetElement = JavaDocUtil.findReferenceTarget(manager, refText, component.getElement()); if (targetElement != null) { fetchDocInfo(getDefaultProvider(targetElement), component); } } else { final String docUrl = url; fetchDocInfo (new JavaDocProvider() { String getElementLocator(String url) { if (url.startsWith(DOC_ELEMENT_PROTOCOL)) { return url.substring(DOC_ELEMENT_PROTOCOL.length()); } return null; } public String getJavaDoc() throws Exception { String url = getElementLocator(docUrl); if (url != null && JavaDocExternalFilter.isJavaDocURL(url)) { String text = new JavaDocExternalFilter(getProject(component.getElement())).getExternalDocInfo(url); if (text != null) { return text; } } if (url == null) { url = docUrl; } PsiElement element = component.getElement(); if (element != null) { PsiElement parent = element; while (true) { if (parent == null || parent instanceof PsiDirectory) break; parent = parent.getParent(); } if (parent != null) { PsiPackage aPackage = ((PsiDirectory)parent).getPackage(); if (aPackage != null) { String url1 = findUrlForLink(aPackage, url); if (url1 != null) { url = url1; } } } } BrowserUtil.launchBrowser(url); return ""; } public PsiElement getElement() { //String loc = getElementLocator(docUrl); // //if (loc != null) { // PsiElement context = component.getElement(); // return JavaDocUtil.findReferenceTarget(context.getManager(), loc, context); //} return component.getElement(); } }, component); } component.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } void showHint(final JBPopup hint) { if (myEditor != null) { hint.showInBestPositionFor(myEditor); } else if (myPreviouslyFocused != null) { hint.showInBestPositionFor(DataManager.getInstance().getDataContext(myPreviouslyFocused)); } } public void requestFocus() { if (fromQuickSearch()) { myPreviouslyFocused.getParent().requestFocus(); } } public Project getProject(@Nullable final PsiElement element) { assert element == null || myProject == element.getProject(); return myProject; } }
revert raw types for javadoc urls (external javadocs compatibility)
codeInsight/impl/com/intellij/codeInsight/javadoc/JavaDocManager.java
revert raw types for javadoc urls (external javadocs compatibility)
<ide><path>odeInsight/impl/com/intellij/codeInsight/javadoc/JavaDocManager.java <ide> String signature = PsiFormatUtil.formatMethod(method, <ide> PsiSubstitutor.EMPTY, PsiFormatUtil.SHOW_NAME | <ide> PsiFormatUtil.SHOW_PARAMETERS, <del> PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.SHOW_FQ_CLASS_NAMES | PsiFormatUtil.SHOW_RAW_TYPE, 999); <add> PsiFormatUtil.SHOW_TYPE | PsiFormatUtil.SHOW_FQ_CLASS_NAMES , 999); <ide> for (int i = 0; i < urls.size(); i++) { <ide> urls.set(i, urls.get(i) + "#" + signature); <ide> }
Java
mit
985794863c580a08aecbfa30ff7334235abc255c
0
seqcode/seqcode-core,seqcode/seqcode-core,seqcode/seqcode-core,seqcode/seqcode-core
package org.seqcode.projects.galaxyexo; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.seqcode.data.io.RegionFileUtilities; import org.seqcode.deepseq.experiments.ExperimentManager; import org.seqcode.deepseq.experiments.ExptConfig; import org.seqcode.deepseq.experiments.Sample; import org.seqcode.genome.Genome; import org.seqcode.genome.GenomeConfig; import org.seqcode.genome.location.Point; import org.seqcode.genome.location.Region; import org.seqcode.genome.location.StrandedPoint; import org.seqcode.genome.location.StrandedRegion; import org.seqcode.gseutils.ArgParser; import org.seqcode.gseutils.Args; /** * Utility to sort locations by tag counts. * If multiple samples are provided, experiments are normalized by total tags and locations are sorted based on average tag counts. * * input : Signal experiment * : Points * : Window size * output: Regions sorted by tag counts * * @author naomi yamada */ public class RegionCountSorter { protected GenomeConfig gconf; protected Genome genome; protected ExperimentManager manager; protected ExptConfig econf; protected List<Point> points; protected List<StrandedPoint> spoints; protected List<Region> regions; protected List<StrandedRegion> strandedReg; protected int window; public RegionCountSorter(GenomeConfig gcon, ExperimentManager man, ExptConfig econ, int win){ gconf = gcon; genome = gconf.getGenome(); manager= man; econf = econ; window = win; } public void setPoint(List<Point> p ){ points = p;} public void setStrandedPoint(List<StrandedPoint> p){spoints=p;} public void setStrandedRegion(List<StrandedRegion> sreg){ strandedReg=sreg; } public void setRegion(List<Region> reg){ regions=reg;} public void execute(){ // get the regions to count reads List<Region> countRegions = new ArrayList<Region>(); if (points != null){ for (Point p : points) countRegions.add(p.expand(window/2)); }else if (spoints !=null){ for (StrandedPoint p : spoints) countRegions.add(p.expand(window/2)); }else if (strandedReg != null){ if(window >0){ for (StrandedRegion sreg : strandedReg) countRegions.add(sreg.resize(window)); }else{ countRegions.addAll(strandedReg); } }else if(regions != null){ if (window>0){ for (Region reg : regions) countRegions.add(reg.resize(window)); }else{ countRegions = regions; } } double sumReads = 0; // summing total tag counts for all experiments for (Sample sample : manager.getSamples()) sumReads += sample.getHitCount(); // get normalization constant for the total tag normalization double normCONST = sumReads/manager.getSamples().size(); RegionCounts[] regionCounts = new RegionCounts[countRegions.size()]; for (int i = 0 ; i < countRegions.size(); i++){ float counts = 0; for (Sample sample : manager.getSamples()) counts += (float) (normCONST*sample.countHits(countRegions.get(i))/sample.getHitCount()); // add counts regionCounts[i] = new RegionCounts(counts); //add peaks or regions if (points !=null) regionCounts[i].setCoord(points.get(i)); else if (spoints !=null) regionCounts[i].setStrandedCoord(spoints.get(i)); else if (strandedReg != null) regionCounts[i].setStrandedRegion(strandedReg.get(i)); else if (regions != null) regionCounts[i].setRegion(regions.get(i)); } Arrays.sort(regionCounts); // outputting the list of regions in descending order of counts for (int i = 0; i < countRegions.size(); i++){ if (regionCounts[i].getCoord()!=null) System.out.println(regionCounts[i].getCoord()); else if (regionCounts[i].getStrandedCoord()!=null) System.out.println(regionCounts[i].getStrandedCoord()); else if (regionCounts[i].getRegion()!=null) System.out.println(regionCounts[i].getRegion()); else System.out.println(regionCounts[i].getStrandedRegion()); } manager.close(); } private class RegionCounts implements Comparable<RegionCounts>{ protected Point coord=null; //Event coordinate protected StrandedPoint spoints=null; protected Region reg=null; // protected StrandedRegion sreg=null; protected float count; public RegionCounts(float count){ this.count=count; } public void setCoord(Point coord){ this.coord=coord;} public void setStrandedCoord(StrandedPoint spoints){this.spoints=spoints;} public void setRegion(Region reg){this.reg=reg;} public void setStrandedRegion(StrandedRegion sreg){this.sreg=sreg;} public Point getCoord(){ return coord;} public StrandedPoint getStrandedCoord(){return spoints;} public Region getRegion(){return reg;} public StrandedRegion getStrandedRegion(){return sreg;} public int compareTo(RegionCounts regcounts){ return Float.compare(count, regcounts.count); } // float compareVal = regcounts.count; // if (compareVal > this.count){ // return 1; // }else{ // return -1; // } // } } public static void main(String[] args){ ArgParser ap = new ArgParser(args); if((!ap.hasKey("peak") && !ap.hasKey("speak") && !ap.hasKey("region") && !ap.hasKey("sregion") )) { System.err.println("Please provide peak, region, sregion file !"); System.err.println("Usage:\n" + "RegionCountSorter\n" + "--species <organism;genome> OR\n" + "--geninfo <genome info file> AND --seq <path to seqs>\n" + "--peak <list of peaks> OR --speak <list of stranded peaks> OR --region <list of regions> OR --sregion <list of stranded regions> \n" + "--expt <experiments> \n" + "\nOPTIONS:\n" + "--win <window size around peaks> \n" + ""); System.exit(0); } GenomeConfig gconf = new GenomeConfig(args); ExptConfig econf = new ExptConfig(gconf.getGenome(), args); econf.setPerBaseReadFiltering(false); ExperimentManager manager = new ExperimentManager(econf); // parsing command line arguments int win = Args.parseInteger(args, "win", -1); RegionCountSorter sorter = new RegionCountSorter(gconf,manager,econf,win); List<Region> reg = new ArrayList<Region>() ; List<StrandedRegion> sreg ; if (ap.hasKey("peak")){ List<Point> points = RegionFileUtilities.loadPointsFromFile(ap.getKeyValue("peak"), gconf.getGenome()); sorter.setPoint(points); }else if (ap.hasKey("speak")){ List<StrandedPoint> points = RegionFileUtilities.loadStrandedPointsFromFile(gconf.getGenome(), ap.getKeyValue("speak")); sorter.setStrandedPoint(points); }else if (ap.hasKey("sregion")){ sreg = RegionFileUtilities.loadStrandedRegionsFromMotifFile(gconf.getGenome(), ap.getKeyValue("sregion"), -1); sorter.setStrandedRegion(sreg); }else if (ap.hasKey("region")){ reg = RegionFileUtilities.loadRegionsFromFile(ap.getKeyValue("region"), gconf.getGenome(), -1); sorter.setRegion(reg); } sorter.execute(); } }
src/org/seqcode/projects/galaxyexo/RegionCountSorter.java
package org.seqcode.projects.galaxyexo; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.seqcode.data.io.RegionFileUtilities; import org.seqcode.deepseq.experiments.ExperimentManager; import org.seqcode.deepseq.experiments.ExptConfig; import org.seqcode.deepseq.experiments.Sample; import org.seqcode.genome.Genome; import org.seqcode.genome.GenomeConfig; import org.seqcode.genome.location.Point; import org.seqcode.genome.location.Region; import org.seqcode.genome.location.StrandedPoint; import org.seqcode.genome.location.StrandedRegion; import org.seqcode.gseutils.ArgParser; import org.seqcode.gseutils.Args; /** * Utility to sort locations by tag counts. * If multiple samples are provided, experiments are normalized by total tags and locations are sorted based on average tag counts. * * input : Signal experiment * : Points * : Window size * output: Regions sorted by tag counts * * @author naomi yamada */ public class RegionCountSorter { protected GenomeConfig gconf; protected Genome genome; protected ExperimentManager manager; protected ExptConfig econf; protected List<Point> points; protected List<StrandedPoint> spoints; protected List<Region> regions; protected List<StrandedRegion> strandedReg; protected int window; public RegionCountSorter(GenomeConfig gcon, ExperimentManager man, ExptConfig econ, int win){ gconf = gcon; genome = gconf.getGenome(); manager= man; econf = econ; window = win; } public void setPoint(List<Point> p ){ points = p;} public void setStrandedPoint(List<StrandedPoint> p){spoints=p;} public void setStrandedRegion(List<StrandedRegion> sreg){ strandedReg=sreg; } public void setRegion(List<Region> reg){ regions=reg;} public void execute(){ // get the regions to count reads List<Region> countRegions = new ArrayList<Region>(); if (points != null){ for (Point p : points) countRegions.add(p.expand(window/2)); }else if (spoints !=null){ for (StrandedPoint p : spoints) countRegions.add(p.expand(window/2)); }else if (strandedReg != null){ if(window >0){ for (StrandedRegion sreg : strandedReg) countRegions.add(sreg.resize(window)); }else{ countRegions.addAll(strandedReg); } }else if(regions != null){ if (window>0){ for (Region reg : regions) countRegions.add(reg.resize(window)); }else{ countRegions = regions; } } double sumReads = 0; // summing total tag counts for all experiments for (Sample sample : manager.getSamples()) sumReads += sample.getHitCount(); // get normalization constant for the total tag normalization double normCONST = sumReads/manager.getSamples().size(); RegionCounts[] regionCounts = new RegionCounts[countRegions.size()]; for (int i = 0 ; i < countRegions.size(); i++){ float counts = 0; for (Sample sample : manager.getSamples()) counts += (float) (normCONST*sample.countHits(countRegions.get(i))/sample.getHitCount()); // add counts regionCounts[i] = new RegionCounts(counts); //add peaks or regions if (points !=null) regionCounts[i].setCoord(points.get(i)); else if (spoints !=null) regionCounts[i].setStrandedCoord(spoints.get(i)); else if (strandedReg != null) regionCounts[i].setStrandedRegion(strandedReg.get(i)); else if (regions != null) regionCounts[i].setRegion(regions.get(i)); } Arrays.sort(regionCounts); // outputting the list of regions in descending order of counts for (int i = 0; i < countRegions.size(); i++){ if (regionCounts[i].getCoord()!=null) System.out.println(regionCounts[i].getCoord()); else if (regionCounts[i].getStrandedCoord()!=null) System.out.println(regionCounts[i].getStrandedCoord()); else if (regionCounts[i].getRegion()!=null) System.out.println(regionCounts[i].getRegion()); else System.out.println(regionCounts[i].getStrandedRegion()); } manager.close(); } private class RegionCounts implements Comparable<RegionCounts>{ protected Point coord=null; //Event coordinate protected StrandedPoint spoints=null; protected Region reg=null; // protected StrandedRegion sreg=null; protected float count; public RegionCounts(float count){ this.count=count; } public void setCoord(Point coord){ this.coord=coord;} public void setStrandedCoord(StrandedPoint spoints){this.spoints=spoints;} public void setRegion(Region reg){this.reg=reg;} public void setStrandedRegion(StrandedRegion sreg){this.sreg=sreg;} public Point getCoord(){ return coord;} public StrandedPoint getStrandedCoord(){return spoints;} public Region getRegion(){return reg;} public StrandedRegion getStrandedRegion(){return sreg;} public int compareTo(RegionCounts regcounts){ float compareVal = regcounts.count; if (compareVal > this.count){ return 1; }else{ return -1; } } } public static void main(String[] args){ ArgParser ap = new ArgParser(args); if((!ap.hasKey("peak") && !ap.hasKey("speak") && !ap.hasKey("region") && !ap.hasKey("sregion") )) { System.err.println("Please provide peak, region, sregion file !"); System.err.println("Usage:\n" + "RegionCountSorter\n" + "--species <organism;genome> OR\n" + "--geninfo <genome info file> AND --seq <path to seqs>\n" + "--peak <list of peaks> OR --speak <list of stranded peaks> OR --region <list of regions> OR --sregion <list of stranded regions> \n" + "--expt <experiments> \n" + "\nOPTIONS:\n" + "--win <window size around peaks> \n" + ""); System.exit(0); } GenomeConfig gconf = new GenomeConfig(args); ExptConfig econf = new ExptConfig(gconf.getGenome(), args); econf.setPerBaseReadFiltering(false); ExperimentManager manager = new ExperimentManager(econf); // parsing command line arguments int win = Args.parseInteger(args, "win", -1); RegionCountSorter sorter = new RegionCountSorter(gconf,manager,econf,win); List<Region> reg = new ArrayList<Region>() ; List<StrandedRegion> sreg ; if (ap.hasKey("peak")){ List<Point> points = RegionFileUtilities.loadPointsFromFile(ap.getKeyValue("peak"), gconf.getGenome()); sorter.setPoint(points); }else if (ap.hasKey("speak")){ List<StrandedPoint> points = RegionFileUtilities.loadStrandedPointsFromFile(gconf.getGenome(), ap.getKeyValue("speak")); sorter.setStrandedPoint(points); }else if (ap.hasKey("sregion")){ sreg = RegionFileUtilities.loadStrandedRegionsFromMotifFile(gconf.getGenome(), ap.getKeyValue("sregion"), -1); sorter.setStrandedRegion(sreg); }else if (ap.hasKey("region")){ reg = RegionFileUtilities.loadRegionsFromFile(ap.getKeyValue("region"), gconf.getGenome(), -1); sorter.setRegion(reg); } sorter.execute(); } }
Minor bug fixes.
src/org/seqcode/projects/galaxyexo/RegionCountSorter.java
Minor bug fixes.
<ide><path>rc/org/seqcode/projects/galaxyexo/RegionCountSorter.java <ide> public StrandedRegion getStrandedRegion(){return sreg;} <ide> <ide> public int compareTo(RegionCounts regcounts){ <del> float compareVal = regcounts.count; <del> if (compareVal > this.count){ <del> return 1; <del> }else{ <del> return -1; <del> } <del> } <add> return Float.compare(count, regcounts.count); <add> } <add> <add>// float compareVal = regcounts.count; <add>// if (compareVal > this.count){ <add>// return 1; <add>// }else{ <add>// return -1; <add>// } <add>// } <ide> } <ide> <ide>
Java
apache-2.0
173550aa000ebee18aa701f49960b5b5bbf7b1ff
0
akashche/disl-mirror,akashche/disl-mirror,akashche/disl-mirror,akashche/disl-mirror
package ch.usi.dag.disl.weaver.pe; import java.util.List; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.IincInsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.analysis.Interpreter; public class ConstInterpreter extends Interpreter<ConstValue> { protected ConstInterpreter() { super(Opcodes.ASM4); } @Override public ConstValue newValue(final Type type) { if (type == Type.VOID_TYPE) { return null; } return new ConstValue(type == null ? 1 : type.getSize()); } @Override public ConstValue newOperation(final AbstractInsnNode insn) { switch (insn.getOpcode()) { case Opcodes.ACONST_NULL: return new ConstValue(1, ConstValue.NULL); case Opcodes.ICONST_M1: return new ConstValue(1, (Integer) (-1)); case Opcodes.ICONST_0: return new ConstValue(1, (Integer) 0); case Opcodes.ICONST_1: return new ConstValue(1, (Integer) 1); case Opcodes.ICONST_2: return new ConstValue(1, (Integer) 2); case Opcodes.ICONST_3: return new ConstValue(1, (Integer) 3); case Opcodes.ICONST_4: return new ConstValue(1, (Integer) 4); case Opcodes.ICONST_5: return new ConstValue(1, (Integer) 5); case Opcodes.LCONST_0: return new ConstValue(2, new Long(0)); case Opcodes.LCONST_1: return new ConstValue(2, new Long(1)); case Opcodes.FCONST_0: return new ConstValue(1, new Float(0)); case Opcodes.FCONST_1: return new ConstValue(1, new Float(1)); case Opcodes.FCONST_2: return new ConstValue(1, new Float(2)); case Opcodes.DCONST_0: return new ConstValue(2, new Double(0)); case Opcodes.DCONST_1: return new ConstValue(2, new Double(1)); case Opcodes.BIPUSH: return new ConstValue(1, (Integer) (((IntInsnNode) insn).operand)); case Opcodes.SIPUSH: return new ConstValue(1, (Integer) (((IntInsnNode) insn).operand)); case Opcodes.LDC: Object cst = ((LdcInsnNode) insn).cst; return new ConstValue( cst instanceof Long || cst instanceof Double ? 2 : 1, cst); case Opcodes.GETSTATIC: return new ConstValue(Type.getType(((FieldInsnNode) insn).desc) .getSize()); default: return new ConstValue(1); } } @Override public ConstValue copyOperation(final AbstractInsnNode insn, final ConstValue value) { return new ConstValue(value.getSize(), value.cst); } @Override public ConstValue unaryOperation(final AbstractInsnNode insn, final ConstValue value) { if (value.cst == null) { switch (insn.getOpcode()) { case Opcodes.LNEG: case Opcodes.DNEG: case Opcodes.I2L: case Opcodes.I2D: case Opcodes.L2D: case Opcodes.F2L: case Opcodes.F2D: case Opcodes.D2L: return new ConstValue(2); case Opcodes.GETFIELD: return new ConstValue(Type.getType(((FieldInsnNode) insn).desc) .getSize()); default: return new ConstValue(1); } } switch (insn.getOpcode()) { case Opcodes.INEG: return new ConstValue(1, (Integer) (-(Integer) value.cst)); case Opcodes.LNEG: return new ConstValue(2, (Long) (-(Long) value.cst)); case Opcodes.FNEG: return new ConstValue(1, (Float) (-(Float) value.cst)); case Opcodes.DNEG: return new ConstValue(2, (Double) (-(Double) value.cst)); case Opcodes.IINC: return new ConstValue( 1, (Integer) ((Integer) value.cst + ((IincInsnNode) insn).incr)); case Opcodes.I2L: return new ConstValue(2, (Long) ((long) ((Integer) value.cst))); case Opcodes.I2F: return new ConstValue(1, (Float) ((float) ((Integer) value.cst))); case Opcodes.I2D: return new ConstValue(2, (Double) ((double) ((Integer) value.cst))); case Opcodes.L2I: return new ConstValue(1, (Integer) ((int) (long) ((Long) value.cst))); case Opcodes.L2F: return new ConstValue(1, (Float) ((float) ((Long) value.cst))); case Opcodes.L2D: return new ConstValue(2, (Double) ((double) ((Long) value.cst))); case Opcodes.F2I: return new ConstValue(1, (Integer) ((int) ((float) ((Float) value.cst)))); case Opcodes.F2L: return new ConstValue(2, (Long) ((long) ((float) ((Float) value.cst)))); case Opcodes.F2D: return new ConstValue(2, (Double) (-(Double) value.cst)); case Opcodes.D2I: return new ConstValue(1, (Integer) ((int) (double) ((Double) value.cst))); case Opcodes.D2L: return new ConstValue(2, (Long) ((long) (double) ((Double) value.cst))); case Opcodes.D2F: return new ConstValue(1, (Float) ((float) (double) ((Double) value.cst))); case Opcodes.I2B: return new ConstValue(1, (Byte) ((byte) (int) ((Integer) value.cst))); case Opcodes.I2C: return new ConstValue(1, (Character) ((char) (int) ((Integer) value.cst))); case Opcodes.I2S: return new ConstValue(1, (Short) ((short) (int) ((Integer) value.cst))); case Opcodes.IFEQ: return new ConstValue(1, (Boolean) ((Integer) value.cst == 0)); case Opcodes.IFNE: return new ConstValue(1, (Boolean) ((Integer) value.cst != 0)); case Opcodes.IFLT: return new ConstValue(1, (Boolean) ((Integer) value.cst < 0)); case Opcodes.IFGE: return new ConstValue(1, (Boolean) ((Integer) value.cst >= 0)); case Opcodes.IFGT: return new ConstValue(1, (Boolean) ((Integer) value.cst > 0)); case Opcodes.IFLE: return new ConstValue(1, (Boolean) ((Integer) value.cst <= 0)); case Opcodes.IFNULL: return new ConstValue(1, (Boolean) (value.cst == ConstValue.NULL)); case Opcodes.IFNONNULL: return new ConstValue(1, (Boolean) (value.cst != ConstValue.NULL)); case Opcodes.CHECKCAST: return new ConstValue(1, value.cst); case Opcodes.INSTANCEOF: Class<? extends Object> clazz = value.cst.getClass(); while (clazz != null) { if (Type.getInternalName(clazz).equals( ((TypeInsnNode) insn).desc)) { return new ConstValue(1, (Integer) 1); } clazz = clazz.getSuperclass(); } return new ConstValue(1, (Integer) 0); default: return new ConstValue(1); } } @Override public ConstValue binaryOperation(final AbstractInsnNode insn, final ConstValue value1, final ConstValue value2) { if (value1 == null || value2 == null) { switch (insn.getOpcode()) { case Opcodes.LALOAD: case Opcodes.DALOAD: case Opcodes.LADD: case Opcodes.DADD: case Opcodes.LSUB: case Opcodes.DSUB: case Opcodes.LMUL: case Opcodes.DMUL: case Opcodes.LDIV: case Opcodes.DDIV: case Opcodes.LREM: case Opcodes.DREM: case Opcodes.LSHL: case Opcodes.LSHR: case Opcodes.LUSHR: case Opcodes.LAND: case Opcodes.LOR: case Opcodes.LXOR: return new ConstValue(2); default: return new ConstValue(1); } } switch (insn.getOpcode()) { case Opcodes.LALOAD: case Opcodes.DALOAD: return new ConstValue(2); case Opcodes.LADD: return new ConstValue(2, (Long) ((Long) value1.cst + (Long) value2.cst)); case Opcodes.LSUB: return new ConstValue(2, (Long) ((Long) value1.cst - (Long) value2.cst)); case Opcodes.LMUL: return new ConstValue(2, (Long) ((Long) value1.cst * (Long) value2.cst)); case Opcodes.LDIV: return new ConstValue(2, (Long) ((Long) value1.cst / (Long) value2.cst)); case Opcodes.LREM: return new ConstValue(2, (Long) ((Long) value1.cst % (Long) value2.cst)); case Opcodes.LSHL: return new ConstValue(2, (Long) ((Long) value1.cst << (Integer) value2.cst)); case Opcodes.LSHR: return new ConstValue(2, (Long) ((Long) value1.cst >> (Integer) value2.cst)); case Opcodes.LUSHR: return new ConstValue(2, (Long) ((Long) value1.cst >>> (Integer) value2.cst)); case Opcodes.LAND: return new ConstValue(2, (Long) ((Long) value1.cst & (Long) value2.cst)); case Opcodes.LOR: return new ConstValue(2, (Long) ((Long) value1.cst | (Long) value2.cst)); case Opcodes.LXOR: return new ConstValue(2, (Long) ((Long) value1.cst ^ (Long) value2.cst)); case Opcodes.DADD: return new ConstValue(2, (Double) ((Double) value1.cst + (Double) value2.cst)); case Opcodes.DSUB: return new ConstValue(2, (Double) ((Double) value1.cst - (Double) value2.cst)); case Opcodes.DMUL: return new ConstValue(2, (Double) ((Double) value1.cst * (Double) value2.cst)); case Opcodes.DDIV: return new ConstValue(2, (Double) ((Double) value1.cst / (Double) value2.cst)); case Opcodes.DREM: return new ConstValue(2, (Double) ((Double) value1.cst % (Double) value2.cst)); case Opcodes.IADD: return new ConstValue(1, (Integer) ((Integer) value1.cst + (Integer) value2.cst)); case Opcodes.ISUB: return new ConstValue(1, (Integer) ((Integer) value1.cst - (Integer) value2.cst)); case Opcodes.IMUL: return new ConstValue(1, (Integer) ((Integer) value1.cst * (Integer) value2.cst)); case Opcodes.IDIV: return new ConstValue(1, (Integer) ((Integer) value1.cst / (Integer) value2.cst)); case Opcodes.IREM: return new ConstValue(1, (Integer) ((Integer) value1.cst % (Integer) value2.cst)); case Opcodes.ISHL: return new ConstValue(1, (Integer) ((Integer) value1.cst << (Integer) value2.cst)); case Opcodes.ISHR: return new ConstValue(1, (Integer) ((Integer) value1.cst >> (Integer) value2.cst)); case Opcodes.IUSHR: return new ConstValue(1, (Integer) ((Integer) value1.cst >>> (Integer) value2.cst)); case Opcodes.IAND: return new ConstValue(1, (Integer) ((Integer) value1.cst & (Integer) value2.cst)); case Opcodes.IOR: return new ConstValue(1, (Integer) ((Integer) value1.cst | (Integer) value2.cst)); case Opcodes.IXOR: return new ConstValue(1, (Integer) ((Integer) value1.cst ^ (Integer) value2.cst)); case Opcodes.FADD: return new ConstValue(1, (Float) ((Float) value1.cst + (Float) value2.cst)); case Opcodes.FSUB: return new ConstValue(1, (Float) ((Float) value1.cst - (Float) value2.cst)); case Opcodes.FMUL: return new ConstValue(1, (Float) ((Float) value1.cst * (Float) value2.cst)); case Opcodes.FDIV: return new ConstValue(1, (Float) ((Float) value1.cst / (Float) value2.cst)); case Opcodes.FREM: return new ConstValue(1, (Float) ((Float) value1.cst % (Float) value2.cst)); case Opcodes.LCMP: if ((Long) value1.cst > (Long) value2.cst) { return new ConstValue(1, (Integer) 1); } else if ((Long) value1.cst < (Long) value2.cst) { return new ConstValue(1, (Integer) (-1)); } else { return new ConstValue(1, (Integer) 0); } case Opcodes.FCMPL: case Opcodes.FCMPG: if ((Float) value1.cst > (Float) value2.cst) { return new ConstValue(1, (Integer) 1); } else if ((Float) value1.cst < (Float) value2.cst) { return new ConstValue(1, (Integer) (-1)); } else { return new ConstValue(1, (Integer) 0); } case Opcodes.DCMPL: case Opcodes.DCMPG: if ((Double) value1.cst > (Double) value2.cst) { return new ConstValue(1, (Integer) 1); } else if ((Double) value1.cst < (Double) value2.cst) { return new ConstValue(1, (Integer) (-1)); } else { return new ConstValue(1, (Integer) 0); } case Opcodes.IF_ICMPEQ: return new ConstValue(1, (Boolean) ((Integer) value1.cst == (Integer) value2.cst)); case Opcodes.IF_ICMPNE: return new ConstValue(1, (Boolean) ((Integer) value1.cst != (Integer) value2.cst)); case Opcodes.IF_ICMPLT: return new ConstValue(1, (Boolean) ((Integer) value1.cst < (Integer) value2.cst)); case Opcodes.IF_ICMPGE: return new ConstValue(1, (Boolean) ((Integer) value1.cst >= (Integer) value2.cst)); case Opcodes.IF_ICMPGT: return new ConstValue(1, (Boolean) ((Integer) value1.cst > (Integer) value2.cst)); case Opcodes.IF_ICMPLE: return new ConstValue(1, (Boolean) ((Integer) value1.cst <= (Integer) value2.cst)); case Opcodes.IF_ACMPEQ: return new ConstValue(1, (Boolean) (value1.cst == value2.cst)); case Opcodes.IF_ACMPNE: return new ConstValue(1, (Boolean) (value1.cst != value2.cst)); default: return new ConstValue(1); } } @Override public ConstValue ternaryOperation(final AbstractInsnNode insn, final ConstValue value1, final ConstValue value2, final ConstValue value3) { return new ConstValue(1); } @Override public ConstValue naryOperation(final AbstractInsnNode insn, final List<? extends ConstValue> values) { int size; int opcode = insn.getOpcode(); if (opcode == Opcodes.MULTIANEWARRAY) { size = 1; } else { String desc = (opcode == Opcodes.INVOKEDYNAMIC) ? ((InvokeDynamicInsnNode) insn).desc : ((MethodInsnNode) insn).desc; size = Type.getReturnType(desc).getSize(); } return new ConstValue(size); } @Override public void returnOperation(final AbstractInsnNode insn, final ConstValue value, final ConstValue expected) { } @Override public ConstValue merge(final ConstValue d, final ConstValue w) { if (d.size == w.size && d.cst != null && d.cst.equals(w.cst)) { return d; } return new ConstValue(Math.min(d.size, w.size)); } }
src/ch/usi/dag/disl/weaver/pe/ConstInterpreter.java
package ch.usi.dag.disl.weaver.pe; import java.util.List; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.IincInsnNode; import org.objectweb.asm.tree.IntInsnNode; import org.objectweb.asm.tree.InvokeDynamicInsnNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.TypeInsnNode; import org.objectweb.asm.tree.analysis.Interpreter; public class ConstInterpreter extends Interpreter<ConstValue> { protected ConstInterpreter() { super(Opcodes.ASM4); } @Override public ConstValue newValue(final Type type) { if (type == Type.VOID_TYPE) { return null; } return new ConstValue(type == null ? 1 : type.getSize()); } /* * ACONST_NULL, ICONST_M1, ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, * ICONST_5, LCONST_0, LCONST_1, FCONST_0, FCONST_1, FCONST_2, DCONST_0, * DCONST_1, BIPUSH, SIPUSH, LDC, JSR, GETSTATIC, NEW */ @Override public ConstValue newOperation(final AbstractInsnNode insn) { switch (insn.getOpcode()) { case Opcodes.ACONST_NULL: return new ConstValue(1, ConstValue.NULL); case Opcodes.ICONST_M1: return new ConstValue(1, (Integer) (-1)); case Opcodes.ICONST_0: return new ConstValue(1, (Integer) 0); case Opcodes.ICONST_1: return new ConstValue(1, (Integer) 1); case Opcodes.ICONST_2: return new ConstValue(1, (Integer) 2); case Opcodes.ICONST_3: return new ConstValue(1, (Integer) 3); case Opcodes.ICONST_4: return new ConstValue(1, (Integer) 4); case Opcodes.ICONST_5: return new ConstValue(1, (Integer) 5); case Opcodes.LCONST_0: return new ConstValue(2, new Long(0)); case Opcodes.LCONST_1: return new ConstValue(2, new Long(1)); case Opcodes.FCONST_0: return new ConstValue(1, new Float(0)); case Opcodes.FCONST_1: return new ConstValue(1, new Float(1)); case Opcodes.FCONST_2: return new ConstValue(1, new Float(2)); case Opcodes.DCONST_0: return new ConstValue(2, new Double(0)); case Opcodes.DCONST_1: return new ConstValue(2, new Double(1)); case Opcodes.BIPUSH: return new ConstValue(2, (Integer) (((IntInsnNode) insn).operand)); case Opcodes.SIPUSH: return new ConstValue(2, (Integer) (((IntInsnNode) insn).operand)); case Opcodes.LDC: Object cst = ((LdcInsnNode) insn).cst; return new ConstValue( cst instanceof Long || cst instanceof Double ? 2 : 1, cst); case Opcodes.GETSTATIC: return new ConstValue(Type.getType(((FieldInsnNode) insn).desc) .getSize()); default: return new ConstValue(1); } } @Override public ConstValue copyOperation(final AbstractInsnNode insn, final ConstValue value) { return new ConstValue(value.getSize(), value.cst); } @Override public ConstValue unaryOperation(final AbstractInsnNode insn, final ConstValue value) { if (value.cst == null) { switch (insn.getOpcode()) { case Opcodes.LNEG: case Opcodes.DNEG: case Opcodes.I2L: case Opcodes.I2D: case Opcodes.L2D: case Opcodes.F2L: case Opcodes.F2D: case Opcodes.D2L: return new ConstValue(2); case Opcodes.GETFIELD: return new ConstValue(Type.getType(((FieldInsnNode) insn).desc) .getSize()); default: return new ConstValue(1); } } switch (insn.getOpcode()) { case Opcodes.INEG: return new ConstValue(1, (Integer) (-(Integer) value.cst)); case Opcodes.LNEG: return new ConstValue(2, (Long) (-(Long) value.cst)); case Opcodes.FNEG: return new ConstValue(1, (Float) (-(Float) value.cst)); case Opcodes.DNEG: return new ConstValue(2, (Double) (-(Double) value.cst)); case Opcodes.IINC: return new ConstValue( 1, (Integer) ((Integer) value.cst + ((IincInsnNode) insn).incr)); case Opcodes.I2L: return new ConstValue(2, (Long) ((long) ((Integer) value.cst))); case Opcodes.I2F: return new ConstValue(1, (Float) ((float) ((Integer) value.cst))); case Opcodes.I2D: return new ConstValue(2, (Double) ((double) ((Integer) value.cst))); case Opcodes.L2I: return new ConstValue(1, (Integer) ((int) (long) ((Long) value.cst))); case Opcodes.L2F: return new ConstValue(1, (Float) ((float) ((Long) value.cst))); case Opcodes.L2D: return new ConstValue(2, (Double) ((double) ((Long) value.cst))); case Opcodes.F2I: return new ConstValue(1, (Integer) ((int) ((float) ((Float) value.cst)))); case Opcodes.F2L: return new ConstValue(2, (Long) ((long) ((float) ((Float) value.cst)))); case Opcodes.F2D: return new ConstValue(2, (Double) (-(Double) value.cst)); case Opcodes.D2I: return new ConstValue(1, (Integer) ((int) (double) ((Double) value.cst))); case Opcodes.D2L: return new ConstValue(2, (Long) ((long) (double) ((Double) value.cst))); case Opcodes.D2F: return new ConstValue(1, (Float) ((float) (double) ((Double) value.cst))); case Opcodes.I2B: return new ConstValue(1, (Byte) ((byte) (int) ((Integer) value.cst))); case Opcodes.I2C: return new ConstValue(1, (Character) ((char) (int) ((Integer) value.cst))); case Opcodes.I2S: return new ConstValue(1, (Short) ((short) (int) ((Integer) value.cst))); case Opcodes.IFEQ: return new ConstValue(1, (Boolean) ((Integer) value.cst == 0)); case Opcodes.IFNE: return new ConstValue(1, (Boolean) ((Integer) value.cst != 0)); case Opcodes.IFLT: return new ConstValue(1, (Boolean) ((Integer) value.cst < 0)); case Opcodes.IFGE: return new ConstValue(1, (Boolean) ((Integer) value.cst >= 0)); case Opcodes.IFGT: return new ConstValue(1, (Boolean) ((Integer) value.cst > 0)); case Opcodes.IFLE: return new ConstValue(1, (Boolean) ((Integer) value.cst <= 0)); case Opcodes.IFNULL: return new ConstValue(1, (Boolean) (value.cst == ConstValue.NULL)); case Opcodes.IFNONNULL: return new ConstValue(1, (Boolean) (value.cst != ConstValue.NULL)); case Opcodes.CHECKCAST: return new ConstValue(1, value.cst); case Opcodes.INSTANCEOF: Class<? extends Object> clazz = value.cst.getClass(); while (clazz != null) { if (Type.getInternalName(clazz).equals( ((TypeInsnNode) insn).desc)) { return new ConstValue(1, (Integer) 1); } clazz = clazz.getSuperclass(); } return new ConstValue(1, (Integer) 0); default: return new ConstValue(1); } } @Override public ConstValue binaryOperation(final AbstractInsnNode insn, final ConstValue value1, final ConstValue value2) { if (value1 == null || value2 == null) { switch (insn.getOpcode()) { case Opcodes.LALOAD: case Opcodes.DALOAD: case Opcodes.LADD: case Opcodes.DADD: case Opcodes.LSUB: case Opcodes.DSUB: case Opcodes.LMUL: case Opcodes.DMUL: case Opcodes.LDIV: case Opcodes.DDIV: case Opcodes.LREM: case Opcodes.DREM: case Opcodes.LSHL: case Opcodes.LSHR: case Opcodes.LUSHR: case Opcodes.LAND: case Opcodes.LOR: case Opcodes.LXOR: return new ConstValue(2); default: return new ConstValue(1); } } switch (insn.getOpcode()) { case Opcodes.LALOAD: case Opcodes.DALOAD: return new ConstValue(2); case Opcodes.LADD: return new ConstValue(2, (Long) ((Long) value1.cst + (Long) value2.cst)); case Opcodes.LSUB: return new ConstValue(2, (Long) ((Long) value1.cst - (Long) value2.cst)); case Opcodes.LMUL: return new ConstValue(2, (Long) ((Long) value1.cst * (Long) value2.cst)); case Opcodes.LDIV: return new ConstValue(2, (Long) ((Long) value1.cst / (Long) value2.cst)); case Opcodes.LREM: return new ConstValue(2, (Long) ((Long) value1.cst % (Long) value2.cst)); case Opcodes.LSHL: return new ConstValue(2, (Long) ((Long) value1.cst << (Integer) value2.cst)); case Opcodes.LSHR: return new ConstValue(2, (Long) ((Long) value1.cst >> (Integer) value2.cst)); case Opcodes.LUSHR: return new ConstValue(2, (Long) ((Long) value1.cst >>> (Integer) value2.cst)); case Opcodes.LAND: return new ConstValue(2, (Long) ((Long) value1.cst & (Long) value2.cst)); case Opcodes.LOR: return new ConstValue(2, (Long) ((Long) value1.cst | (Long) value2.cst)); case Opcodes.LXOR: return new ConstValue(2, (Long) ((Long) value1.cst ^ (Long) value2.cst)); case Opcodes.DADD: return new ConstValue(2, (Double) ((Double) value1.cst + (Double) value2.cst)); case Opcodes.DSUB: return new ConstValue(2, (Double) ((Double) value1.cst - (Double) value2.cst)); case Opcodes.DMUL: return new ConstValue(2, (Double) ((Double) value1.cst * (Double) value2.cst)); case Opcodes.DDIV: return new ConstValue(2, (Double) ((Double) value1.cst / (Double) value2.cst)); case Opcodes.DREM: return new ConstValue(2, (Double) ((Double) value1.cst % (Double) value2.cst)); case Opcodes.IADD: return new ConstValue(1, (Integer) ((Integer) value1.cst + (Integer) value2.cst)); case Opcodes.ISUB: return new ConstValue(1, (Integer) ((Integer) value1.cst - (Integer) value2.cst)); case Opcodes.IMUL: return new ConstValue(1, (Integer) ((Integer) value1.cst * (Integer) value2.cst)); case Opcodes.IDIV: return new ConstValue(1, (Integer) ((Integer) value1.cst / (Integer) value2.cst)); case Opcodes.IREM: return new ConstValue(1, (Integer) ((Integer) value1.cst % (Integer) value2.cst)); case Opcodes.ISHL: return new ConstValue(1, (Integer) ((Integer) value1.cst << (Integer) value2.cst)); case Opcodes.ISHR: return new ConstValue(1, (Integer) ((Integer) value1.cst >> (Integer) value2.cst)); case Opcodes.IUSHR: return new ConstValue(1, (Integer) ((Integer) value1.cst >>> (Integer) value2.cst)); case Opcodes.IAND: return new ConstValue(1, (Integer) ((Integer) value1.cst & (Integer) value2.cst)); case Opcodes.IOR: return new ConstValue(1, (Integer) ((Integer) value1.cst | (Integer) value2.cst)); case Opcodes.IXOR: return new ConstValue(1, (Integer) ((Integer) value1.cst ^ (Integer) value2.cst)); case Opcodes.FADD: return new ConstValue(1, (Float) ((Float) value1.cst + (Float) value2.cst)); case Opcodes.FSUB: return new ConstValue(1, (Float) ((Float) value1.cst - (Float) value2.cst)); case Opcodes.FMUL: return new ConstValue(1, (Float) ((Float) value1.cst * (Float) value2.cst)); case Opcodes.FDIV: return new ConstValue(1, (Float) ((Float) value1.cst / (Float) value2.cst)); case Opcodes.FREM: return new ConstValue(1, (Float) ((Float) value1.cst % (Float) value2.cst)); case Opcodes.LCMP: if ((Long) value1.cst > (Long) value2.cst) { return new ConstValue(1, (Integer) 1); } else if ((Long) value1.cst < (Long) value2.cst) { return new ConstValue(1, (Integer) (-1)); } else { return new ConstValue(1, (Integer) 0); } case Opcodes.FCMPL: case Opcodes.FCMPG: if ((Float) value1.cst > (Float) value2.cst) { return new ConstValue(1, (Integer) 1); } else if ((Float) value1.cst < (Float) value2.cst) { return new ConstValue(1, (Integer) (-1)); } else { return new ConstValue(1, (Integer) 0); } case Opcodes.DCMPL: case Opcodes.DCMPG: if ((Double) value1.cst > (Double) value2.cst) { return new ConstValue(1, (Integer) 1); } else if ((Double) value1.cst < (Double) value2.cst) { return new ConstValue(1, (Integer) (-1)); } else { return new ConstValue(1, (Integer) 0); } case Opcodes.IF_ICMPEQ: return new ConstValue(1, (Boolean) ((Integer) value1.cst == (Integer) value2.cst)); case Opcodes.IF_ICMPNE: return new ConstValue(1, (Boolean) ((Integer) value1.cst != (Integer) value2.cst)); case Opcodes.IF_ICMPLT: return new ConstValue(1, (Boolean) ((Integer) value1.cst < (Integer) value2.cst)); case Opcodes.IF_ICMPGE: return new ConstValue(1, (Boolean) ((Integer) value1.cst >= (Integer) value2.cst)); case Opcodes.IF_ICMPGT: return new ConstValue(1, (Boolean) ((Integer) value1.cst > (Integer) value2.cst)); case Opcodes.IF_ICMPLE: return new ConstValue(1, (Boolean) ((Integer) value1.cst <= (Integer) value2.cst)); case Opcodes.IF_ACMPEQ: return new ConstValue(1, (Boolean) (value1.cst == value2.cst)); case Opcodes.IF_ACMPNE: return new ConstValue(1, (Boolean) (value1.cst != value2.cst)); default: return new ConstValue(1); } } @Override public ConstValue ternaryOperation(final AbstractInsnNode insn, final ConstValue value1, final ConstValue value2, final ConstValue value3) { return new ConstValue(1); } @Override public ConstValue naryOperation(final AbstractInsnNode insn, final List<? extends ConstValue> values) { int size; int opcode = insn.getOpcode(); if (opcode == Opcodes.MULTIANEWARRAY) { size = 1; } else { String desc = (opcode == Opcodes.INVOKEDYNAMIC) ? ((InvokeDynamicInsnNode) insn).desc : ((MethodInsnNode) insn).desc; size = Type.getReturnType(desc).getSize(); } return new ConstValue(size); } @Override public void returnOperation(final AbstractInsnNode insn, final ConstValue value, final ConstValue expected) { } @Override public ConstValue merge(final ConstValue d, final ConstValue w) { if (d.size == w.size && d.cst != null && d.cst.equals(w.cst)) { return d; } return new ConstValue(Math.min(d.size, w.size)); } }
BugFixed: bipush and sipush pushes 1-byte operand onto stack. git-svn-id: 9828a123601097aec97c9db06897c34ab9021696@335 f1b219a8-1381-427d-9730-7f2851dc2a88
src/ch/usi/dag/disl/weaver/pe/ConstInterpreter.java
BugFixed: bipush and sipush pushes 1-byte operand onto stack.
<ide><path>rc/ch/usi/dag/disl/weaver/pe/ConstInterpreter.java <ide> <ide> return new ConstValue(type == null ? 1 : type.getSize()); <ide> } <del> <del> /* <del> * ACONST_NULL, ICONST_M1, ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, <del> * ICONST_5, LCONST_0, LCONST_1, FCONST_0, FCONST_1, FCONST_2, DCONST_0, <del> * DCONST_1, BIPUSH, SIPUSH, LDC, JSR, GETSTATIC, NEW <del> */ <ide> <ide> @Override <ide> public ConstValue newOperation(final AbstractInsnNode insn) { <ide> case Opcodes.DCONST_1: <ide> return new ConstValue(2, new Double(1)); <ide> case Opcodes.BIPUSH: <del> return new ConstValue(2, (Integer) (((IntInsnNode) insn).operand)); <add> return new ConstValue(1, (Integer) (((IntInsnNode) insn).operand)); <ide> case Opcodes.SIPUSH: <del> return new ConstValue(2, (Integer) (((IntInsnNode) insn).operand)); <add> return new ConstValue(1, (Integer) (((IntInsnNode) insn).operand)); <ide> case Opcodes.LDC: <ide> Object cst = ((LdcInsnNode) insn).cst; <ide> return new ConstValue(
Java
mit
3161faa52f86549c14d6191be3cbb40704fcd7a5
0
CS2103AUG2016-W10-C1/main,CS2103AUG2016-W10-C1/TaskMan
package seedu.taskman.logic.logicmanager; import org.junit.Test; import seedu.taskman.model.TaskMan; import seedu.taskman.model.event.Activity; import seedu.taskman.model.event.Task; import java.util.List; import static org.junit.Assert.assertEquals; public class SelectTests extends LogicManagerTestBase { @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { assertIncorrectIndexFormatBehaviorForCommand("select"); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskMan expectedTaskMan = helper.generateTaskMan(threeTasks); helper.addToModel(model, threeTasks); assertCommandStateChange("select 2", expectedTaskMan, expectedTaskMan.getActivityList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredActivityList().get(1), new Activity(threeTasks.get(1))); } }
src/test/java/seedu/taskman/logic/logicmanager/SelectTests.java
package seedu.taskman.logic.logicmanager; import seedu.taskman.model.TaskMan; import seedu.taskman.model.event.Activity; import seedu.taskman.model.event.Task; import java.util.List; import static org.junit.Assert.assertEquals; public class SelectTests extends LogicManagerTestBase { //@Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { assertIncorrectIndexFormatBehaviorForCommand("select"); } //@Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } //@Test public void execute_select_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskMan expectedTaskMan = helper.generateTaskMan(threeTasks); helper.addToModel(model, threeTasks); assertCommandStateChange("select 2", expectedTaskMan, expectedTaskMan.getActivityList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredActivityList().get(1), new Activity(threeTasks.get(1))); } }
Enabled select tests
src/test/java/seedu/taskman/logic/logicmanager/SelectTests.java
Enabled select tests
<ide><path>rc/test/java/seedu/taskman/logic/logicmanager/SelectTests.java <ide> package seedu.taskman.logic.logicmanager; <ide> <add>import org.junit.Test; <ide> import seedu.taskman.model.TaskMan; <ide> import seedu.taskman.model.event.Activity; <ide> import seedu.taskman.model.event.Task; <ide> <ide> public class SelectTests extends LogicManagerTestBase { <ide> <del> //@Test <add> @Test <ide> public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { <ide> assertIncorrectIndexFormatBehaviorForCommand("select"); <ide> } <ide> <del> //@Test <add> @Test <ide> public void execute_selectIndexNotFound_errorMessageShown() throws Exception { <ide> assertIndexNotFoundBehaviorForCommand("select"); <ide> } <ide> <del> //@Test <add> @Test <ide> public void execute_select_jumpsToCorrectTask() throws Exception { <ide> TestDataHelper helper = new TestDataHelper(); <ide> List<Task> threeTasks = helper.generateTaskList(3);
Java
apache-2.0
c4add2b07d1b5e5d6f3d45af055d7f6a44ba63f0
0
fincatto/nfe,eldevanjr/nfe,danieldhp/nfe,isaiastavares/nfe,granella/nfe,fauker/nfe,caiocteodoro/nfe,klutzer/nfe,jefperito/nfe,wmixvideo/nfe
package com.fincatto.nfe310.classes; /** * URls qrCode: http://nfce.encat.org/desenvolvedor/qrcode/ **/ public enum NFUnidadeFederativa { AC("AC", "Acre", "12", "http://hml.sefaznet.ac.gov.br/nfce/qrcode", "http://hml.sefaznet.ac.gov.br/nfce/qrcode"), AL("AL", "Alagoas", "27"), AP("AP", "Amap\u00E1", "16", "https://www.sefaz.ap.gov.br/nfcehml/nfce.php", "https://www.sefaz.ap.gov.br/nfce/nfce.php"), AM("AM", "Amazonas", "13", "homnfce.sefaz.am.gov.br/nfceweb/consultarNFCe.jsp", "sistemas.sefaz.am.gov.br/nfceweb/consultarNFCe.jsp"), BA("BA", "Bahia", "29", "http://hnfe.sefaz.ba.gov.br/servicos/nfce/modulos/geral/NFCEC_consulta_chave_acesso.aspx", "http://nfe.sefaz.ba.gov.br/servicos/nfce/modulos/geral/NFCEC_consulta_chave_acesso.aspx"), CE("CE", "Cear\u00E1", "23"), DF("DF", "Distrito Federal", "53", "http://dec.fazenda.df.gov.br/ConsultarNFCe.aspx", "http://dec.fazenda.df.gov.br/ConsultarNFCe.aspx"), GO("GO", "Goi\u00E1s", "52", "http://homolog.sefaz.go.gov.br/nfeweb/jsp/ConsultaDANFENFCe.jsf", "http://nfe.sefaz.go.gov.br/nfeweb/jsp/ConsultaDANFENFCe.jsf"), ES("ES", "Esp\u00EDrito Santo", "32"), MA("MA", "Maranh\u00E3o", "21"), MT("MT", "Mato Grosso", "51", "http://www.sefaz.mt.gov.br/nfce/consultanfce", "http://www.sefaz.mt.gov.br/nfce/consultanfce"), MS("MS", "Mato Grosso do Sul", "50"), MG("MG", "Minas Gerais", "31"), PA("PA", "Par\u00E1", "15", "https://appnfc.sefa.pa.gov.br/portal-homologacao/view/consultas/nfce/nfceForm.seam", "https://appnfc.sefa.pa.gov.br/portal/view/consultas/nfce/nfceForm.seam"), PB("PB", "Paraiba", "25", "www.receita.pb.gov.br/nfcehom", "www.receita.pb.gov.br/nfce"), PR("PR", "Paran\u00E1", "41", "http://www.dfeportal.fazenda.pr.gov.br/dfe-portal/rest/servico/consultaNFCe", "http://www.dfeportal.fazenda.pr.gov.br/dfe-portal/rest/servico/consultaNFCe"), PE("PE", "Pernambuco", "26", "http://nfcehomolog.sefaz.pe.gov.br/nfce-web/consultarNFCe", "http://nfce.sefaz.pe.gov.br/nfce-web/consultarNFCe"), PI("PI", "Piau\u00ED", "22", "http://webas.sefaz.pi.gov.br/nfceweb-homologacao/consultarNFCe.jsf", "http://webas.sefaz.pi.gov.br/nfceweb/consultarNFCe.jsf"), RJ("RJ", "Rio de Janeiro", "33", "http://www4.fazenda.rj.gov.br/consultaNFCe/QRCode", "http://www4.fazenda.rj.gov.br/consultaNFCe/QRCode?"), RN("RN", "Rio Grande do Norte", "24", "http://hom.nfce.set.rn.gov.br/consultarNFCe.aspx", "http://nfce.set.rn.gov.br/consultarNFCe.aspx"), RS("RS", "Rio Grande do Sul", "43", "https://www.sefaz.rs.gov.br/NFCE/NFCE-COM.aspx", "https://www.sefaz.rs.gov.br/NFCE/NFCE-COM.aspx"), RO("RO", "Rond\u00F4nia", "11", "http://www.nfce.sefin.ro.gov.br/consultanfce/consulta.jsp", "http://www.nfce.sefin.ro.gov.br/consultanfce/consulta.jsp"), RR("RR", "Roraima", "14", "http://200.174.88.103:8080/nfce/servlet/qrcode", "https://www.sefaz.rr.gov.br/nfce/servlet/qrcode"), SP("SP", "S\u00E3o Paulo", "35", "https://www.homologacao.nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaQRCode.aspx", "https://www.nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaQRCode.aspx"), SC("SC", "Santa Catarina", "42"), SE("SE", "Sergipe", "28", "http://www.hom.nfe.se.gov.br/portal/consultarNFCe.jsp", "http://www.nfce.se.gov.br/portal/consultarNFCe.jsp"), TO("TO", "Tocantins", "17"), NACIONAL("NC", "Nacional", "90"), RFB("RFB", "RFB", "91"), EX("EX", "Exterior", "99"); private final String codigo; private final String descricao; private final String codigoIbge; private final String qrCodeHomologacao; private final String qrCodeProducao; NFUnidadeFederativa(final String codigo, final String descricao, final String codigoIbge, String qrCodeHomologacao, String qrCodeProducao) { this.codigo = codigo; this.descricao = descricao; this.codigoIbge = codigoIbge; this.qrCodeHomologacao = qrCodeHomologacao; this.qrCodeProducao = qrCodeProducao; } NFUnidadeFederativa(final String codigo, final String descricao, final String codigoIbge) { this(codigo, descricao, codigoIbge, null, null); } public String getCodigo() { return this.codigo; } public String getDescricao() { return this.descricao; } public String getCodigoIbge() { return this.codigoIbge; } public String getQrCodeHomologacao() { return qrCodeHomologacao; } public String getQrCodeProducao() { return qrCodeProducao; } @Override public String toString() { return this.getDescricao(); } /** * Identifica a UF pela sigla ou pelo codigo IBGE. * @param codigo Sigla ou codigo IBGE da UF. * @return Objeto da UF. */ public static NFUnidadeFederativa valueOfCodigo(final String codigo) { for (final NFUnidadeFederativa uf : NFUnidadeFederativa.values()) { if (uf.getCodigo().equalsIgnoreCase(codigo)) { return uf; } else if (uf.getCodigoIbge().equalsIgnoreCase(codigo)) { return uf; } } throw new IllegalArgumentException(String.format("N\u00e3o existe o c\u00f3digo %s no mapeamento.", codigo)); } }
src/main/java/com/fincatto/nfe310/classes/NFUnidadeFederativa.java
package com.fincatto.nfe310.classes; /** * URls qrCode: http://nfce.encat.org/desenvolvedor/qrcode/ **/ public enum NFUnidadeFederativa { AC("AC", "Acre", "12", "http://hml.sefaznet.ac.gov.br/nfce/qrcode", "http://hml.sefaznet.ac.gov.br/nfce/qrcode"), AL("AL", "Alagoas", "27"), AP("AP", "Amap\u00E1", "16", "https://www.sefaz.ap.gov.br/nfcehml/nfce.php", "https://www.sefaz.ap.gov.br/nfce/nfce.php"), AM("AM", "Amazonas", "13", "homnfce.sefaz.am.gov.br/nfceweb/consultarNFCe.jsp", "sistemas.sefaz.am.gov.br/nfceweb/consultarNFCe.jsp"), BA("BA", "Bahia", "29", "http://hnfe.sefaz.ba.gov.br/servicos/nfce/modulos/geral/NFCEC_consulta_chave_acesso.aspx", "http://nfe.sefaz.ba.gov.br/servicos/nfce/modulos/geral/NFCEC_consulta_chave_acesso.aspx"), CE("CE", "Cear\u00E1", "23"), DF("DF", "Distrito Federal", "53", "http://dec.fazenda.df.gov.br/ConsultarNFCe.aspx", "http://dec.fazenda.df.gov.br/ConsultarNFCe.aspx"), GO("GO", "Goi\u00E1s", "52"), ES("ES", "Esp\u00EDrito Santo", "32"), MA("MA", "Maranh\u00E3o", "21"), MT("MT", "Mato Grosso", "51", "http://www.sefaz.mt.gov.br/nfce/consultanfce", "http://www.sefaz.mt.gov.br/nfce/consultanfce"), MS("MS", "Mato Grosso do Sul", "50"), MG("MG", "Minas Gerais", "31"), PA("PA", "Par\u00E1", "15", "https://appnfc.sefa.pa.gov.br/portal-homologacao/view/consultas/nfce/nfceForm.seam", "https://appnfc.sefa.pa.gov.br/portal/view/consultas/nfce/nfceForm.seam"), PB("PB", "Paraiba", "25", "www.receita.pb.gov.br/nfcehom", "www.receita.pb.gov.br/nfce"), PR("PR", "Paran\u00E1", "41", "http://www.dfeportal.fazenda.pr.gov.br/dfe-portal/rest/servico/consultaNFCe", "http://www.dfeportal.fazenda.pr.gov.br/dfe-portal/rest/servico/consultaNFCe"), PE("PE", "Pernambuco", "26", "http://nfcehomolog.sefaz.pe.gov.br/nfce-web/consultarNFCe", "http://nfce.sefaz.pe.gov.br/nfce-web/consultarNFCe"), PI("PI", "Piau\u00ED", "22", "http://webas.sefaz.pi.gov.br/nfceweb-homologacao/consultarNFCe.jsf", "http://webas.sefaz.pi.gov.br/nfceweb/consultarNFCe.jsf"), RJ("RJ", "Rio de Janeiro", "33", "http://www4.fazenda.rj.gov.br/consultaNFCe/QRCode", "http://www4.fazenda.rj.gov.br/consultaNFCe/QRCode?"), RN("RN", "Rio Grande do Norte", "24", "http://hom.nfce.set.rn.gov.br/consultarNFCe.aspx", "http://nfce.set.rn.gov.br/consultarNFCe.aspx"), RS("RS", "Rio Grande do Sul", "43", "https://www.sefaz.rs.gov.br/NFCE/NFCE-COM.aspx", "https://www.sefaz.rs.gov.br/NFCE/NFCE-COM.aspx"), RO("RO", "Rond\u00F4nia", "11", "http://www.nfce.sefin.ro.gov.br/consultanfce/consulta.jsp", "http://www.nfce.sefin.ro.gov.br/consultanfce/consulta.jsp"), RR("RR", "Roraima", "14", "http://200.174.88.103:8080/nfce/servlet/qrcode", "https://www.sefaz.rr.gov.br/nfce/servlet/qrcode"), SP("SP", "S\u00E3o Paulo", "35", "https://www.homologacao.nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaQRCode.aspx", "https://www.nfce.fazenda.sp.gov.br/NFCeConsultaPublica/Paginas/ConsultaQRCode.aspx"), SC("SC", "Santa Catarina", "42"), SE("SE", "Sergipe", "28", "http://www.hom.nfe.se.gov.br/portal/consultarNFCe.jsp", "http://www.nfce.se.gov.br/portal/consultarNFCe.jsp"), TO("TO", "Tocantins", "17"), NACIONAL("NC", "Nacional", "90"), RFB("RFB", "RFB", "91"), EX("EX", "Exterior", "99"); private final String codigo; private final String descricao; private final String codigoIbge; private final String qrCodeHomologacao; private final String qrCodeProducao; NFUnidadeFederativa(final String codigo, final String descricao, final String codigoIbge, String qrCodeHomologacao, String qrCodeProducao) { this.codigo = codigo; this.descricao = descricao; this.codigoIbge = codigoIbge; this.qrCodeHomologacao = qrCodeHomologacao; this.qrCodeProducao = qrCodeProducao; } NFUnidadeFederativa(final String codigo, final String descricao, final String codigoIbge) { this(codigo, descricao, codigoIbge, null, null); } public String getCodigo() { return this.codigo; } public String getDescricao() { return this.descricao; } public String getCodigoIbge() { return this.codigoIbge; } public String getQrCodeHomologacao() { return qrCodeHomologacao; } public String getQrCodeProducao() { return qrCodeProducao; } @Override public String toString() { return this.getDescricao(); } /** * Identifica a UF pela sigla ou pelo codigo IBGE. * @param codigo Sigla ou codigo IBGE da UF. * @return Objeto da UF. */ public static NFUnidadeFederativa valueOfCodigo(final String codigo) { for (final NFUnidadeFederativa uf : NFUnidadeFederativa.values()) { if (uf.getCodigo().equalsIgnoreCase(codigo)) { return uf; } else if (uf.getCodigoIbge().equalsIgnoreCase(codigo)) { return uf; } } throw new IllegalArgumentException(String.format("N\u00e3o existe o c\u00f3digo %s no mapeamento.", codigo)); } }
URLs consulta QRCode - Goiás
src/main/java/com/fincatto/nfe310/classes/NFUnidadeFederativa.java
URLs consulta QRCode - Goiás
<ide><path>rc/main/java/com/fincatto/nfe310/classes/NFUnidadeFederativa.java <ide> BA("BA", "Bahia", "29", "http://hnfe.sefaz.ba.gov.br/servicos/nfce/modulos/geral/NFCEC_consulta_chave_acesso.aspx", "http://nfe.sefaz.ba.gov.br/servicos/nfce/modulos/geral/NFCEC_consulta_chave_acesso.aspx"), <ide> CE("CE", "Cear\u00E1", "23"), <ide> DF("DF", "Distrito Federal", "53", "http://dec.fazenda.df.gov.br/ConsultarNFCe.aspx", "http://dec.fazenda.df.gov.br/ConsultarNFCe.aspx"), <del> GO("GO", "Goi\u00E1s", "52"), <add> GO("GO", "Goi\u00E1s", "52", "http://homolog.sefaz.go.gov.br/nfeweb/jsp/ConsultaDANFENFCe.jsf", "http://nfe.sefaz.go.gov.br/nfeweb/jsp/ConsultaDANFENFCe.jsf"), <ide> ES("ES", "Esp\u00EDrito Santo", "32"), <ide> MA("MA", "Maranh\u00E3o", "21"), <ide> MT("MT", "Mato Grosso", "51", "http://www.sefaz.mt.gov.br/nfce/consultanfce", "http://www.sefaz.mt.gov.br/nfce/consultanfce"),
Java
apache-2.0
ef85d22ec35702ebd9e7ea4298d493a8e686d97d
0
apache/sis,apache/sis,apache/sis
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sis.test; import java.util.Set; import java.util.HashSet; import java.lang.reflect.Field; import java.lang.reflect.Method; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlSchema; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlRootElement; import org.opengis.util.CodeList; import org.opengis.util.ControlledVocabulary; import org.opengis.annotation.UML; import org.opengis.annotation.Obligation; import org.opengis.annotation.Specification; import org.apache.sis.util.ArraysExt; import org.apache.sis.xml.Namespaces; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; import static org.apache.sis.test.TestUtilities.getSingleton; /** * Base class for validations of {@link UML}, {@link XmlElement} and other annotations. * Some tests performed by this class are: * * <ul> * <li>All implementation classes have {@link XmlRootElement} and {@link XmlType} annotations.</li> * <li>The name declared in the {@code XmlType} annotations matches the * {@link #getExpectedXmlTypeForElement expected value}.</li> * <li>The name declared in the {@code XmlRootElement} (classes) or {@link XmlElement} (methods) * annotations matches the identifier declared in the {@link UML} annotation of the GeoAPI interfaces. * The UML - XML name mapping can be changed by overriding {@link #getExpectedXmlElementName(Class, UML)} and * {@link #getExpectedXmlElementName(Class, UML)}.</li> * <li>The {@code XmlElement.required()} boolean is consistent with the UML {@linkplain Obligation obligation}.</li> * <li>The namespace declared in the {@code XmlRootElement} or {@code XmlElement} annotations * is not redundant with the {@link XmlSchema} annotation in the package.</li> * <li>The prefixes declared in the {@link XmlNs} annotations match the * {@linkplain Namespaces#getPreferredPrefix expected prefixes}.</li> * <li>The {@linkplain #getWrapperFor wrapper}, if any, is consistent.</li> * </ul> * * @author Cédric Briançon (Geomatys) * @author Martin Desruisseaux (Geomatys) * @version 0.5 * @since 0.3 * @module */ public abstract strictfp class AnnotationsTestCase extends TestCase { /** * The {@value} string used in JAXB annotations for default names or namespaces. */ private static final String DEFAULT = "##default"; /** * The GeoAPI interfaces, {@link CodeList} or {@link Enum} types to test. */ protected final Class<?>[] types; /** * The type being tested, or {@code null} if none. In case of test failure, this information * will be used by {@link #printFailureLocation()} for formatting a message giving the name * of class and method where the failure occurred. */ protected String testingClass; /** * The method being tested, or {@code null} if none. In case of test failure, this information * will be used by {@link #printFailureLocation()} for formatting a message giving the name of * class and method where the failure occurred. */ protected String testingMethod; /** * Creates a new test suite for the given types. * * @param types The GeoAPI interfaces, {@link CodeList} or {@link Enum} types to test. */ protected AnnotationsTestCase(final Class<?>... types) { this.types = types; } /** * Returns the SIS implementation class for the given GeoAPI interface. * For example the implementation of the {@link org.opengis.metadata.citation.Citation} * interface is the {@link org.apache.sis.metadata.iso.citation.DefaultCitation} class. * * @param <T> the type represented by the {@code type} argument. * @param type the GeoAPI interface (never a {@link CodeList} or {@link Enum} type). * @return the SIS implementation for the given interface. */ protected abstract <T> Class<? extends T> getImplementation(Class<T> type); /** * If the given GeoAPI type, when marshalled to XML, is wrapped into an other XML element, * returns the class of the wrapper for that XML element. Otherwise returns {@code null}. * Such wrappers are unusual in XML (except for lists), but the ISO 19139 standard do that * systematically for every elements. * * <p><b>Example:</b> when a {@link org.apache.sis.metadata.iso.citation.DefaultContact} * is marshalled to XML inside a {@code ResponsibleParty}, the element is not marshalled * directly inside its parent as we usually do in XML. Instead, we have a {@code <CI_Contact>}. * inside the {@code <contactInfo>} element as below:</p> * * {@preformat xml * <CI_ResponsibleParty> * <contactInfo> * <CI_Contact> * ... * </CI_Contact> * </contactInfo> * </CI_ResponsibleParty> * } * * To reflect that fact, this method shall return the internal {@code CI_Contact} * wrapper class for the {@link org.apache.sis.metadata.iso.citation.DefaultCitation} argument. * If no wrapper is expected for the given class, then this method shall return {@code null}. * * <p>If a wrapper is expected for the given class but was not found, then this method shall throw * {@link ClassNotFoundException}. Note that no wrapper may be defined explicitely for the given type, * while a wrapper is defined for a parent of the given type. This method does not need to care about * such situation, since the caller will automatically searches for a parent class if * {@code ClassNotFoundException} has been thrown.</p> * * <p>In SIS implementation, most wrappers are also {@link javax.xml.bind.annotation.adapters.XmlAdapter}. * But this is not a requirement.</p> * * @param type the GeoAPI interface, {@link CodeList} or {@link Enum} type. * @return the wrapper for the given type, or {@code null} if none. * @throws ClassNotFoundException if a wrapper was expected but not found. */ protected abstract Class<?> getWrapperFor(Class<?> type) throws ClassNotFoundException; /** * The value returned by {@link AnnotationsTestCase#getWrapperFor(Class)}, together with * a boolean telling whether the wrapper has been found in the tested class or in one * of its parent classes. */ private static final class WrapperClass { final Class<?> type; boolean isInherited; WrapperClass(final Class<?> type) { this.type = type; } } /** * Returns the value of {@link #getWrapperFor(Class)} for the given class, or for a parent * of the given class if {@code getWrapperFor(Class)} threw {@code ClassNotFoundException}. * * @param type the GeoAPI interface, {@link CodeList} or {@link Enum} type. * @return the wrapper for the given type. {@link WrapperClass#type} is {@code null} if * no wrapper has been found. * @throws ClassNotFoundException if a wrapper was expected but not found in the * given type neither in any of the parent classes. */ private WrapperClass getWrapperInHierarchy(final Class<?> type) throws ClassNotFoundException { try { return new WrapperClass(getWrapperFor(type)); } catch (ClassNotFoundException e) { for (final Class<?> parent : type.getInterfaces()) { if (ArraysExt.containsIdentity(types, parent)) try { final WrapperClass wrapper = getWrapperInHierarchy(parent); wrapper.isInherited = true; return wrapper; } catch (ClassNotFoundException e2) { e.addSuppressed(e2); } } throw e; } } /** * Returns the XML type for an element of the given type. For example in ISO 19139, * the XML type of {@code CI_Citation} is {@code CI_Citation_Type}. * * @param type the GeoAPI interface. * @param impl the implementation class. * @return the name of the XML type for the given element, or {@code null} if none. * * @see #testImplementationAnnotations() */ protected abstract String getExpectedXmlTypeForElement(Class<?> type, Class<?> impl); /** * Returns the expected namespace for an element defined by the given specification. * For example the namespace of any type defined by {@link Specification#ISO_19115} * is {@code "http://www.isotc211.org/2005/gmd"}. * * <p>The default implementation recognizes the * {@linkplain Specification#ISO_19115 ISO 19115}, * {@linkplain Specification#ISO_19115_2 ISO 19115-2}, * {@linkplain Specification#ISO_19139 ISO 19139} and * {@linkplain Specification#ISO_19108 ISO 19108} specifications. * Subclasses shall override this method if they need to support more namespaces.</p> * * <p>The prefix for the given namespace will be fetched by * {@link Namespaces#getPreferredPrefix(String, String)}.</p> * * @param impl the implementation class, {@link CodeList} or {@link Enum} type. * @param specification the specification that define the type, or {@code null} if unspecified. * @return the expected namespace. * @throws IllegalArgumentException if the given specification is unknown to this method. */ protected String getExpectedNamespace(final Class<?> impl, final Specification specification) { switch (specification) { case ISO_19115: return Namespaces.GMD; case ISO_19115_2: return Namespaces.GMI; case ISO_19115_3: case ISO_19139: return Namespaces.GMX; case ISO_19108: return Namespaces.GMD; default: throw new IllegalArgumentException(specification.toString()); } } /** * Returns the name of the XML element for the given UML element. * This method is invoked in two situations: * * <ul> * <li>For the root XML element name of an interface, in which case {@code enclosing} is {@code null}.</li> * <li>For the XML element name of a property (field or method) defined by an interface, * in which case {@code enclosing} is the interface containing the property.</li> * </ul> * * The default implementation returns {@link UML#identifier()}. Subclasses shall override this method * when mismatches are known to exist between the UML and XML element names. * * @param enclosing the GeoAPI interface which contains the property, or {@code null} if none. * @param uml the UML element for which to get the corresponding XML element name. * @return the XML element name for the given UML element. */ protected String getExpectedXmlElementName(final Class<?> enclosing, final UML uml) { return uml.identifier(); } /** * Replaces {@value #DEFAULT} value by the {@link XmlSchema} namespace if needed, * then performs validity check on the resulting namespace. This method checks that: * * <ul> * <li>The namespace is not redundant with the package-level {@link XmlSchema} namespace.</li> * <li>The namespace is declared in a package-level {@link XmlNs} annotation.</li> * <li>The namespace is equals to the {@linkplain #getExpectedNamespace expected namespace}.</li> * </ul> * * @param namespace the namespace given by the {@code @XmlRootElement} or {@code @XmlElement} annotation. * @param impl the implementation or wrapper class for which to get the package namespace. * @param uml the {@code @UML} annotation, or {@code null} if none. * @return the actual namespace (same as {@code namespace} if it was not {@value #DEFAULT}). */ private String assertExpectedNamespace(String namespace, final Class<?> impl, final UML uml) { assertNotNull("Missing namespace.", namespace); assertFalse("Missing namespace.", namespace.trim().isEmpty()); /* * Get the namespace declared at the package level, and ensure the the * given namespace is not redundant with that package-level namespace. */ final XmlSchema schema = impl.getPackage().getAnnotation(XmlSchema.class); assertNotNull("Missing @XmlSchema package annotation.", schema); final String schemaNamespace = schema.namespace(); assertFalse("Missing namespace in @XmlSchema package annotation.", schemaNamespace.trim().isEmpty()); assertFalse("Namespace declaration is redundant with @XmlSchema.", namespace.equals(schemaNamespace)); /* * Check that the namespace is declared in the package-level @XmlNs annotation. * We do not verify the validity of those @XmlNs annotations, since this is the * purpose of the 'testPackageAnnotations()' method. */ if (!DEFAULT.equals(namespace)) { boolean found = false; for (final XmlNs ns : schema.xmlns()) { if (namespace.equals(ns.namespaceURI())) { found = true; break; } } if (!found) { fail("Namespace for " + impl + " is not declared in the package @XmlSchema.xmlns()."); } } else { namespace = schemaNamespace; } if (uml != null) { assertEquals("Wrong namespace for the ISO specification.", getExpectedNamespace(impl, uml.specification()), namespace); } return namespace; } /** * Returns the namespace declared in the {@link XmlSchema} annotation of the given package, * or {@code null} if none. * * @param p the package, or {@code null}. * @return the namespace, or {@code null} if none. */ private static String getNamespace(final Package p) { if (p != null) { final XmlSchema schema = p.getAnnotation(XmlSchema.class); if (schema != null) { final String namespace = schema.namespace().trim(); if (!namespace.isEmpty() && !DEFAULT.equals(namespace)) { return namespace; } } } return null; } /** * Returns the namespace declared in the {@link XmlRootElement} annotation of the given class, * or the package annotation if none is found in the class. * * @param impl the implementation class, or {@code null}. * @return the namespace, or {@code null} if none. */ private static String getNamespace(final Class<?> impl) { if (impl == null) { return null; } final XmlRootElement root = impl.getAnnotation(XmlRootElement.class); if (root != null) { final String namespace = root.namespace().trim(); if (!namespace.isEmpty() && !DEFAULT.equals(namespace)) { return namespace; } } return getNamespace(impl.getPackage()); } /** * Gets the {@link XmlElement} annotation for the no-argument method of the given name * in the given implementation class. If the method is not annotated, then fallback on * a field having the same name than the UML identifier. If no such field is found or * is annotated, returns {@code null}. * * @param impl the implementation class. * @param method the name of the getter method to search for. * @param uml the UML annotation on the GeoAPI interface, or {@code null} if none. * @return the {@code XmlElement}, or {@code null} if none. */ private static XmlElement getXmlElement(final Class<?> impl, final String method, final UML uml) { XmlElement element = null; try { element = impl.getMethod(method, (Class<?>[]) null).getAnnotation(XmlElement.class); if (element == null && uml != null) { element = impl.getDeclaredField(uml.identifier()).getAnnotation(XmlElement.class); } } catch (NoSuchMethodException ex) { fail("Missing implementation: " + ex); } catch (NoSuchFieldException ex) { // Ignore - we will consider that there is no annotation. } return element; } /** * Returns {@code true} if the given method should be ignored. * This method returns {@code true} for some standard methods from the JDK. */ private static boolean isIgnored(final Method method) { final String name = method.getName(); return name.equals("equals") || name.equals("hashCode") || name.equals("doubleValue"); } /** * Returns {@code true} if the given method is a non-standard extension. * If {@code true}, then {@code method} does not need to have UML annotation. * * @param method the method to verify. * @return {@code true} if the given method is an extension, or {@code false} otherwise. * * @since 0.5 */ protected boolean isExtension(final Method method) { return false; } /** * Tests the annotations on every GeoAPI interfaces and code lists in the {@link #types} array. * More specifically this method tests that: * * <ul> * <li>All elements in {@link #types} except code lists are interfaces.</li> * <li>All elements in {@code types} have a {@link UML} annotation.</li> * <li>All methods expect deprecated methods and methods overriding JDK methods * have a {@link UML} annotation.</li> * </ul> */ @Test public void testInterfaceAnnotations() { for (final Class<?> type : types) { testingMethod = null; testingClass = type.getCanonicalName(); UML uml = type.getAnnotation(UML.class); assertNotNull("Missing @UML annotation.", uml); if (!ControlledVocabulary.class.isAssignableFrom(type)) { for (final Method method : type.getDeclaredMethods()) { testingMethod = method.getName(); if (!isIgnored(method) && !isExtension(method)) { uml = method.getAnnotation(UML.class); if (!method.isAnnotationPresent(Deprecated.class)) { assertNotNull("Missing @UML annotation.", uml); } } } } } done(); } /** * Tests the annotations in the {@code package-info} files of SIS implementations of the * interfaces enumerated in the {@code #types} array. More specifically this method tests that: * * <ul> * <li>The prefixes declared in the {@link XmlNs} annotations match the * {@linkplain Namespaces#getPreferredPrefix expected prefixes}.</li> * </ul> */ @Test public void testPackageAnnotations() { final Set<Package> packages = new HashSet<>(); for (final Class<?> type : types) { if (!ControlledVocabulary.class.isAssignableFrom(type)) { testingClass = type.getCanonicalName(); final Class<?> impl = getImplementation(type); if (impl != null) { testingClass = impl.getCanonicalName(); final Package p = impl.getPackage(); assertNotNull("Missing package information.", p); packages.add(p); } } } for (final Package p : packages) { for (final XmlNs ns : p.getAnnotation(XmlSchema.class).xmlns()) { testingClass = p.getName(); final String namespace = ns.namespaceURI(); assertEquals("Unexpected namespace prefix.", Namespaces.getPreferredPrefix(namespace, null), ns.prefix()); } } done(); } /** * Tests the annotations on every SIS implementations of the interfaces enumerated * in the {@link #types} array. More specifically this method tests that: * * <ul> * <li>All implementation classes have {@link XmlRootElement} and {@link XmlType} annotations.</li> * <li>The name declared in the {@code XmlType} annotations matches the * {@link #getExpectedXmlTypeForElement expected value}.</li> * <li>The name declared in the {@code XmlRootElement} annotations matches the identifier declared * in the {@link UML} annotation of the GeoAPI interfaces.</li> * <li>The namespace declared in the {@code XmlRootElement} annotations is not redundant with * the {@link XmlSchema} annotation in the package.</li> * </ul> * * This method does not check the method annotations, since it is {@link #testMethodAnnotations()} job. */ @Test @DependsOnMethod("testInterfaceAnnotations") public void testImplementationAnnotations() { for (final Class<?> type : types) { if (ControlledVocabulary.class.isAssignableFrom(type)) { // Skip code lists, since they are not the purpose of this test. continue; } testingClass = type.getCanonicalName(); /* * Get the implementation class, which is mandatory (otherwise the * subclass shall not include the interface in the 'types' array). */ final Class<?> impl = getImplementation(type); assertNotNull("No implementation found.", impl); assertNotSame("No implementation found.", type, impl); testingClass = impl.getCanonicalName(); /* * Compare the XmlRootElement with the UML annotation, if any. The UML annotation * is mandatory in the default implementation of the 'testInterfaceAnnotations()' * method, but we don't require the UML to be non-null here since this is not the * job of this test method. This is because subclasses may choose to override the * 'testInterfaceAnnotations()' method. */ final XmlRootElement root = impl.getAnnotation(XmlRootElement.class); assertNotNull("Missing @XmlRootElement annotation.", root); final UML uml = type.getAnnotation(UML.class); if (uml != null) { assertEquals("Wrong @XmlRootElement.name().", getExpectedXmlElementName(null, uml), root.name()); } /* * Check that the namespace is the expected one (according subclass) * and is not redundant with the package @XmlSchema annotation. */ assertExpectedNamespace(root.namespace(), impl, uml); /* * Compare the XmlType annotation with the expected value. */ final XmlType xmlType = impl.getAnnotation(XmlType.class); assertNotNull("Missing @XmlType annotation.", xmlType); String expected = getExpectedXmlTypeForElement(type, impl); if (expected == null) { expected = DEFAULT; } assertEquals("Wrong @XmlType.name().", expected, xmlType.name()); } done(); } /** * Tests the annotations on every methods of SIS classes. * More specifically this method tests that: * * <ul> * <li>The name declared in {@link XmlElement} matches the UML identifier.</li> * <li>The {@code XmlElement.required()} boolean is consistent with the UML {@linkplain Obligation obligation}.</li> * <li>The namespace declared in {@code XmlElement} is not redundant with the one declared in the package.</li> * </ul> */ @Test @DependsOnMethod("testImplementationAnnotations") public void testMethodAnnotations() { for (final Class<?> type : types) { if (ControlledVocabulary.class.isAssignableFrom(type)) { // Skip code lists, since they are not the purpose of this test. continue; } testingMethod = null; testingClass = type.getCanonicalName(); final Class<?> impl = getImplementation(type); if (impl == null) { /* * Implementation existence are tested by 'testImplementationAnnotations()'. * It is not the purpose of this test to verify again their existence. */ continue; } testingClass = impl.getCanonicalName(); for (final Method method : type.getDeclaredMethods()) { if (isIgnored(method)) { continue; } testingMethod = method.getName(); final UML uml = method.getAnnotation(UML.class); final XmlElement element = getXmlElement(impl, testingMethod, uml); /* * Just display the missing @XmlElement annotation for the method, since we know * that some elements are not yet implemented (and consequently can not yet be * annotated). */ if (element == null) { // Note: lines with the "[WARNING]" string are highlighted by Jenkins. warning("[WARNING] Missing @XmlElement annotation for "); continue; } /* * The UML annotation is mandatory in the default implementation of the * 'testInterfaceAnnotations()' method, but we don't require the UML to * be non-null here since this is not the job of this test method. This * is because subclasses may choose to override the above test method. */ if (uml != null && false) { // Disabled until we merged the ISO 19115-3 branch. assertEquals("Wrong @XmlElement.name().", getExpectedXmlElementName(type, uml), element.name()); assertEquals("Wrong @XmlElement.required().", uml.obligation() == Obligation.MANDATORY, element.required()); } /* * Check that the namespace is the expected one (according subclass) * and is not redundant with the package @XmlSchema annotation. */ assertExpectedNamespace(element.namespace(), impl, uml); } } done(); } /** * Tests the annotations on wrappers returned by {@link #getWrapperFor(Class)}. * More specifically this method tests that: * * <ul> * <li>The wrapper have a getter and a setter method declared in the same class.</li> * <li>The getter method is annotated with {@code @XmlElement} or {@code @XmlElementRef}, but not both</li> * <li>{@code @XmlElementRef} is used only in parent classes, not in leaf classes.</li> * <li>The name declared in {@code @XmlElement} matches the {@code @UML} identifier.</li> * </ul> */ @Test public void testWrapperAnnotations() { for (final Class<?> type : types) { testingClass = type.getCanonicalName(); /* * Check the annotation on the wrapper, if there is one. If no wrapper is declared * specifically for the current type, check if a wrapper is defined for the parent * interface. In such case, the getElement() method is required to be annotated by * @XmlElementRef, not @XmlElement, in order to let JAXB infer the name from the * actual subclass. */ final WrapperClass wrapper; try { wrapper = getWrapperInHierarchy(type); } catch (ClassNotFoundException e) { fail(e.toString()); continue; } if (wrapper.type == null) { // If the wrapper is intentionally undefined, skip it. continue; } /* * Now fetch the getter/setter methods, ensure that they are declared in the same class * and verify that exactly one of @XmlElement or @XmlElementRef annotation is declared. */ testingClass = wrapper.type.getCanonicalName(); final XmlElement element; if (type.isEnum()) { final Field field; try { field = wrapper.type.getDeclaredField("value"); } catch (NoSuchFieldException e) { fail(e.toString()); continue; } element = field.getAnnotation(XmlElement.class); } else { final Method getter, setter; try { getter = wrapper.type.getMethod("getElement", (Class<?>[]) null); setter = wrapper.type.getMethod("setElement", getter.getReturnType()); } catch (NoSuchMethodException e) { fail(e.toString()); continue; } assertEquals("The setter method must be declared in the same class than the " + "getter method - not in a parent class, to avoid issues with JAXB.", getter.getDeclaringClass(), setter.getDeclaringClass()); assertEquals("The setter parameter type shall be the same than the getter return type.", getter.getReturnType(), getSingleton(setter.getParameterTypes())); element = getter.getAnnotation(XmlElement.class); assertEquals("Expected @XmlElement XOR @XmlElementRef.", (element == null), getter.isAnnotationPresent(XmlElementRef.class) || getter.isAnnotationPresent(XmlElementRefs.class)); } /* * If the annotation is @XmlElement, ensure that XmlElement.name() is equals to * the UML identifier. Then verify that the */ if (element != null) { assertFalse("Expected @XmlElementRef.", wrapper.isInherited); final UML uml = type.getAnnotation(UML.class); if (uml != null) { // 'assertNotNull' is 'testInterfaceAnnotations()' job. assertEquals("Wrong @XmlElement.", uml.identifier(), element.name()); } final String namespace = assertExpectedNamespace(element.namespace(), wrapper.type, uml); if (!ControlledVocabulary.class.isAssignableFrom(type)) { final String expected = getNamespace(getImplementation(type)); if (expected != null) { // 'assertNotNull' is 'testImplementationAnnotations()' job. assertEquals("Inconsistent @XmlRootElement namespace.", expected, namespace); } } } } done(); } /** * Shall be invoked after every successful test in order * to disable the report of failed class or method. */ protected final void done() { testingClass = null; testingMethod = null; } /** * Prints the given message followed by the name of the class being tested. */ private void warning(String message) { if (testingClass != null) { final StringBuilder buffer = new StringBuilder(message); buffer.append(testingClass); if (testingMethod != null) { buffer.append('.').append(testingMethod).append("()"); } message = buffer.toString(); } out.println(message); } /** * If a test failed, reports the class and method names were the failure occurred. * The message will be written in the {@link #out} printer. * * @see #testingClass * @see #testingMethod */ @After public final void printFailureLocation() { if (testingClass != null) { warning("TEST FAILURE: "); } } }
core/sis-utility/src/test/java/org/apache/sis/test/AnnotationsTestCase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sis.test; import java.util.Set; import java.util.HashSet; import java.lang.reflect.Field; import java.lang.reflect.Method; import javax.xml.bind.annotation.XmlNs; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlSchema; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlRootElement; import org.opengis.util.CodeList; import org.opengis.util.ControlledVocabulary; import org.opengis.annotation.UML; import org.opengis.annotation.Obligation; import org.opengis.annotation.Specification; import org.apache.sis.util.ArraysExt; import org.apache.sis.xml.Namespaces; import org.junit.After; import org.junit.Test; import static org.junit.Assert.*; import static org.apache.sis.test.TestUtilities.getSingleton; /** * Base class for validations of {@link UML}, {@link XmlElement} and other annotations. * Some tests performed by this class are: * * <ul> * <li>All implementation classes have {@link XmlRootElement} and {@link XmlType} annotations.</li> * <li>The name declared in the {@code XmlType} annotations matches the * {@link #getExpectedXmlTypeForElement expected value}.</li> * <li>The name declared in the {@code XmlRootElement} (classes) or {@link XmlElement} (methods) * annotations matches the identifier declared in the {@link UML} annotation of the GeoAPI interfaces. * The UML - XML name mapping can be changed by overriding {@link #getExpectedXmlElementName(Class, UML)} and * {@link #getExpectedXmlElementName(Class, UML)}.</li> * <li>The {@code XmlElement.required()} boolean is consistent with the UML {@linkplain Obligation obligation}.</li> * <li>The namespace declared in the {@code XmlRootElement} or {@code XmlElement} annotations * is not redundant with the {@link XmlSchema} annotation in the package.</li> * <li>The prefixes declared in the {@link XmlNs} annotations match the * {@linkplain Namespaces#getPreferredPrefix expected prefixes}.</li> * <li>The {@linkplain #getWrapperFor wrapper}, if any, is consistent.</li> * </ul> * * @author Cédric Briançon (Geomatys) * @author Martin Desruisseaux (Geomatys) * @version 0.5 * @since 0.3 * @module */ public abstract strictfp class AnnotationsTestCase extends TestCase { /** * The {@value} string used in JAXB annotations for default names or namespaces. */ private static final String DEFAULT = "##default"; /** * The GeoAPI interfaces, {@link CodeList} or {@link Enum} types to test. */ protected final Class<?>[] types; /** * The type being tested, or {@code null} if none. In case of test failure, this information * will be used by {@link #printFailureLocation()} for formatting a message giving the name * of class and method where the failure occurred. */ protected String testingClass; /** * The method being tested, or {@code null} if none. In case of test failure, this information * will be used by {@link #printFailureLocation()} for formatting a message giving the name of * class and method where the failure occurred. */ protected String testingMethod; /** * Creates a new test suite for the given types. * * @param types The GeoAPI interfaces, {@link CodeList} or {@link Enum} types to test. */ protected AnnotationsTestCase(final Class<?>... types) { this.types = types; } /** * Returns the SIS implementation class for the given GeoAPI interface. * For example the implementation of the {@link org.opengis.metadata.citation.Citation} * interface is the {@link org.apache.sis.metadata.iso.citation.DefaultCitation} class. * * @param <T> the type represented by the {@code type} argument. * @param type the GeoAPI interface (never a {@link CodeList} or {@link Enum} type). * @return the SIS implementation for the given interface. */ protected abstract <T> Class<? extends T> getImplementation(Class<T> type); /** * If the given GeoAPI type, when marshalled to XML, is wrapped into an other XML element, * returns the class of the wrapper for that XML element. Otherwise returns {@code null}. * Such wrappers are unusual in XML (except for lists), but the ISO 19139 standard do that * systematically for every elements. * * <p><b>Example:</b> when a {@link org.apache.sis.metadata.iso.citation.DefaultContact} * is marshalled to XML inside a {@code ResponsibleParty}, the element is not marshalled * directly inside its parent as we usually do in XML. Instead, we have a {@code <CI_Contact>}. * inside the {@code <contactInfo>} element as below:</p> * * {@preformat xml * <CI_ResponsibleParty> * <contactInfo> * <CI_Contact> * ... * </CI_Contact> * </contactInfo> * </CI_ResponsibleParty> * } * * To reflect that fact, this method shall return the internal {@code CI_Contact} * wrapper class for the {@link org.apache.sis.metadata.iso.citation.DefaultCitation} argument. * If no wrapper is expected for the given class, then this method shall return {@code null}. * * <p>If a wrapper is expected for the given class but was not found, then this method shall throw * {@link ClassNotFoundException}. Note that no wrapper may be defined explicitely for the given type, * while a wrapper is defined for a parent of the given type. This method does not need to care about * such situation, since the caller will automatically searches for a parent class if * {@code ClassNotFoundException} has been thrown.</p> * * <p>In SIS implementation, most wrappers are also {@link javax.xml.bind.annotation.adapters.XmlAdapter}. * But this is not a requirement.</p> * * @param type the GeoAPI interface, {@link CodeList} or {@link Enum} type. * @return the wrapper for the given type, or {@code null} if none. * @throws ClassNotFoundException if a wrapper was expected but not found. */ protected abstract Class<?> getWrapperFor(Class<?> type) throws ClassNotFoundException; /** * The value returned by {@link AnnotationsTestCase#getWrapperFor(Class)}, together with * a boolean telling whether the wrapper has been found in the tested class or in one * of its parent classes. */ private static final class WrapperClass { final Class<?> type; boolean isInherited; WrapperClass(final Class<?> type) { this.type = type; } } /** * Returns the value of {@link #getWrapperFor(Class)} for the given class, or for a parent * of the given class if {@code getWrapperFor(Class)} threw {@code ClassNotFoundException}. * * @param type the GeoAPI interface, {@link CodeList} or {@link Enum} type. * @return the wrapper for the given type. {@link WrapperClass#type} is {@code null} if * no wrapper has been found. * @throws ClassNotFoundException if a wrapper was expected but not found in the * given type neither in any of the parent classes. */ private WrapperClass getWrapperInHierarchy(final Class<?> type) throws ClassNotFoundException { try { return new WrapperClass(getWrapperFor(type)); } catch (ClassNotFoundException e) { for (final Class<?> parent : type.getInterfaces()) { if (ArraysExt.containsIdentity(types, parent)) try { final WrapperClass wrapper = getWrapperInHierarchy(parent); wrapper.isInherited = true; return wrapper; } catch (ClassNotFoundException e2) { e.addSuppressed(e2); } } throw e; } } /** * Returns the XML type for an element of the given type. For example in ISO 19139, * the XML type of {@code CI_Citation} is {@code CI_Citation_Type}. * * @param type the GeoAPI interface. * @param impl the implementation class. * @return the name of the XML type for the given element, or {@code null} if none. * * @see #testImplementationAnnotations() */ protected abstract String getExpectedXmlTypeForElement(Class<?> type, Class<?> impl); /** * Returns the expected namespace for an element defined by the given specification. * For example the namespace of any type defined by {@link Specification#ISO_19115} * is {@code "http://www.isotc211.org/2005/gmd"}. * * <p>The default implementation recognizes the * {@linkplain Specification#ISO_19115 ISO 19115}, * {@linkplain Specification#ISO_19115_2 ISO 19115-2}, * {@linkplain Specification#ISO_19139 ISO 19139} and * {@linkplain Specification#ISO_19108 ISO 19108} specifications. * Subclasses shall override this method if they need to support more namespaces.</p> * * <p>The prefix for the given namespace will be fetched by * {@link Namespaces#getPreferredPrefix(String, String)}.</p> * * @param impl the implementation class, {@link CodeList} or {@link Enum} type. * @param specification the specification that define the type, or {@code null} if unspecified. * @return the expected namespace. * @throws IllegalArgumentException if the given specification is unknown to this method. */ protected String getExpectedNamespace(final Class<?> impl, final Specification specification) { switch (specification) { case ISO_19115: return Namespaces.GMD; case ISO_19115_2: return Namespaces.GMI; case ISO_19139: return Namespaces.GMX; case ISO_19108: return Namespaces.GMD; default: throw new IllegalArgumentException(specification.toString()); } } /** * Returns the name of the XML element for the given UML element. * This method is invoked in two situations: * * <ul> * <li>For the root XML element name of an interface, in which case {@code enclosing} is {@code null}.</li> * <li>For the XML element name of a property (field or method) defined by an interface, * in which case {@code enclosing} is the interface containing the property.</li> * </ul> * * The default implementation returns {@link UML#identifier()}. Subclasses shall override this method * when mismatches are known to exist between the UML and XML element names. * * @param enclosing the GeoAPI interface which contains the property, or {@code null} if none. * @param uml the UML element for which to get the corresponding XML element name. * @return the XML element name for the given UML element. */ protected String getExpectedXmlElementName(final Class<?> enclosing, final UML uml) { return uml.identifier(); } /** * Replaces {@value #DEFAULT} value by the {@link XmlSchema} namespace if needed, * then performs validity check on the resulting namespace. This method checks that: * * <ul> * <li>The namespace is not redundant with the package-level {@link XmlSchema} namespace.</li> * <li>The namespace is declared in a package-level {@link XmlNs} annotation.</li> * <li>The namespace is equals to the {@linkplain #getExpectedNamespace expected namespace}.</li> * </ul> * * @param namespace the namespace given by the {@code @XmlRootElement} or {@code @XmlElement} annotation. * @param impl the implementation or wrapper class for which to get the package namespace. * @param uml the {@code @UML} annotation, or {@code null} if none. * @return the actual namespace (same as {@code namespace} if it was not {@value #DEFAULT}). */ private String assertExpectedNamespace(String namespace, final Class<?> impl, final UML uml) { assertNotNull("Missing namespace.", namespace); assertFalse("Missing namespace.", namespace.trim().isEmpty()); /* * Get the namespace declared at the package level, and ensure the the * given namespace is not redundant with that package-level namespace. */ final XmlSchema schema = impl.getPackage().getAnnotation(XmlSchema.class); assertNotNull("Missing @XmlSchema package annotation.", schema); final String schemaNamespace = schema.namespace(); assertFalse("Missing namespace in @XmlSchema package annotation.", schemaNamespace.trim().isEmpty()); assertFalse("Namespace declaration is redundant with @XmlSchema.", namespace.equals(schemaNamespace)); /* * Check that the namespace is declared in the package-level @XmlNs annotation. * We do not verify the validity of those @XmlNs annotations, since this is the * purpose of the 'testPackageAnnotations()' method. */ if (!DEFAULT.equals(namespace)) { boolean found = false; for (final XmlNs ns : schema.xmlns()) { if (namespace.equals(ns.namespaceURI())) { found = true; break; } } if (!found) { fail("Namespace for " + impl + " is not declared in the package @XmlSchema.xmlns()."); } } else { namespace = schemaNamespace; } if (uml != null) { assertEquals("Wrong namespace for the ISO specification.", getExpectedNamespace(impl, uml.specification()), namespace); } return namespace; } /** * Returns the namespace declared in the {@link XmlSchema} annotation of the given package, * or {@code null} if none. * * @param p the package, or {@code null}. * @return the namespace, or {@code null} if none. */ private static String getNamespace(final Package p) { if (p != null) { final XmlSchema schema = p.getAnnotation(XmlSchema.class); if (schema != null) { final String namespace = schema.namespace().trim(); if (!namespace.isEmpty() && !DEFAULT.equals(namespace)) { return namespace; } } } return null; } /** * Returns the namespace declared in the {@link XmlRootElement} annotation of the given class, * or the package annotation if none is found in the class. * * @param impl the implementation class, or {@code null}. * @return the namespace, or {@code null} if none. */ private static String getNamespace(final Class<?> impl) { if (impl == null) { return null; } final XmlRootElement root = impl.getAnnotation(XmlRootElement.class); if (root != null) { final String namespace = root.namespace().trim(); if (!namespace.isEmpty() && !DEFAULT.equals(namespace)) { return namespace; } } return getNamespace(impl.getPackage()); } /** * Gets the {@link XmlElement} annotation for the no-argument method of the given name * in the given implementation class. If the method is not annotated, then fallback on * a field having the same name than the UML identifier. If no such field is found or * is annotated, returns {@code null}. * * @param impl the implementation class. * @param method the name of the getter method to search for. * @param uml the UML annotation on the GeoAPI interface, or {@code null} if none. * @return the {@code XmlElement}, or {@code null} if none. */ private static XmlElement getXmlElement(final Class<?> impl, final String method, final UML uml) { XmlElement element = null; try { element = impl.getMethod(method, (Class<?>[]) null).getAnnotation(XmlElement.class); if (element == null && uml != null) { element = impl.getDeclaredField(uml.identifier()).getAnnotation(XmlElement.class); } } catch (NoSuchMethodException ex) { fail("Missing implementation: " + ex); } catch (NoSuchFieldException ex) { // Ignore - we will consider that there is no annotation. } return element; } /** * Returns {@code true} if the given method should be ignored. * This method returns {@code true} for some standard methods from the JDK. */ private static boolean isIgnored(final Method method) { final String name = method.getName(); return name.equals("equals") || name.equals("hashCode") || name.equals("doubleValue"); } /** * Returns {@code true} if the given method is a non-standard extension. * If {@code true}, then {@code method} does not need to have UML annotation. * * @param method the method to verify. * @return {@code true} if the given method is an extension, or {@code false} otherwise. * * @since 0.5 */ protected boolean isExtension(final Method method) { return false; } /** * Tests the annotations on every GeoAPI interfaces and code lists in the {@link #types} array. * More specifically this method tests that: * * <ul> * <li>All elements in {@link #types} except code lists are interfaces.</li> * <li>All elements in {@code types} have a {@link UML} annotation.</li> * <li>All methods expect deprecated methods and methods overriding JDK methods * have a {@link UML} annotation.</li> * </ul> */ @Test public void testInterfaceAnnotations() { for (final Class<?> type : types) { testingMethod = null; testingClass = type.getCanonicalName(); UML uml = type.getAnnotation(UML.class); assertNotNull("Missing @UML annotation.", uml); if (!ControlledVocabulary.class.isAssignableFrom(type)) { for (final Method method : type.getDeclaredMethods()) { testingMethod = method.getName(); if (!isIgnored(method) && !isExtension(method)) { uml = method.getAnnotation(UML.class); if (!method.isAnnotationPresent(Deprecated.class)) { assertNotNull("Missing @UML annotation.", uml); } } } } } done(); } /** * Tests the annotations in the {@code package-info} files of SIS implementations of the * interfaces enumerated in the {@code #types} array. More specifically this method tests that: * * <ul> * <li>The prefixes declared in the {@link XmlNs} annotations match the * {@linkplain Namespaces#getPreferredPrefix expected prefixes}.</li> * </ul> */ @Test public void testPackageAnnotations() { final Set<Package> packages = new HashSet<>(); for (final Class<?> type : types) { if (!ControlledVocabulary.class.isAssignableFrom(type)) { testingClass = type.getCanonicalName(); final Class<?> impl = getImplementation(type); if (impl != null) { testingClass = impl.getCanonicalName(); final Package p = impl.getPackage(); assertNotNull("Missing package information.", p); packages.add(p); } } } for (final Package p : packages) { for (final XmlNs ns : p.getAnnotation(XmlSchema.class).xmlns()) { testingClass = p.getName(); final String namespace = ns.namespaceURI(); assertEquals("Unexpected namespace prefix.", Namespaces.getPreferredPrefix(namespace, null), ns.prefix()); } } done(); } /** * Tests the annotations on every SIS implementations of the interfaces enumerated * in the {@link #types} array. More specifically this method tests that: * * <ul> * <li>All implementation classes have {@link XmlRootElement} and {@link XmlType} annotations.</li> * <li>The name declared in the {@code XmlType} annotations matches the * {@link #getExpectedXmlTypeForElement expected value}.</li> * <li>The name declared in the {@code XmlRootElement} annotations matches the identifier declared * in the {@link UML} annotation of the GeoAPI interfaces.</li> * <li>The namespace declared in the {@code XmlRootElement} annotations is not redundant with * the {@link XmlSchema} annotation in the package.</li> * </ul> * * This method does not check the method annotations, since it is {@link #testMethodAnnotations()} job. */ @Test @DependsOnMethod("testInterfaceAnnotations") public void testImplementationAnnotations() { for (final Class<?> type : types) { if (ControlledVocabulary.class.isAssignableFrom(type)) { // Skip code lists, since they are not the purpose of this test. continue; } testingClass = type.getCanonicalName(); /* * Get the implementation class, which is mandatory (otherwise the * subclass shall not include the interface in the 'types' array). */ final Class<?> impl = getImplementation(type); assertNotNull("No implementation found.", impl); assertNotSame("No implementation found.", type, impl); testingClass = impl.getCanonicalName(); /* * Compare the XmlRootElement with the UML annotation, if any. The UML annotation * is mandatory in the default implementation of the 'testInterfaceAnnotations()' * method, but we don't require the UML to be non-null here since this is not the * job of this test method. This is because subclasses may choose to override the * 'testInterfaceAnnotations()' method. */ final XmlRootElement root = impl.getAnnotation(XmlRootElement.class); assertNotNull("Missing @XmlRootElement annotation.", root); final UML uml = type.getAnnotation(UML.class); if (uml != null) { assertEquals("Wrong @XmlRootElement.name().", getExpectedXmlElementName(null, uml), root.name()); } /* * Check that the namespace is the expected one (according subclass) * and is not redundant with the package @XmlSchema annotation. */ assertExpectedNamespace(root.namespace(), impl, uml); /* * Compare the XmlType annotation with the expected value. */ final XmlType xmlType = impl.getAnnotation(XmlType.class); assertNotNull("Missing @XmlType annotation.", xmlType); String expected = getExpectedXmlTypeForElement(type, impl); if (expected == null) { expected = DEFAULT; } assertEquals("Wrong @XmlType.name().", expected, xmlType.name()); } done(); } /** * Tests the annotations on every methods of SIS classes. * More specifically this method tests that: * * <ul> * <li>The name declared in {@link XmlElement} matches the UML identifier.</li> * <li>The {@code XmlElement.required()} boolean is consistent with the UML {@linkplain Obligation obligation}.</li> * <li>The namespace declared in {@code XmlElement} is not redundant with the one declared in the package.</li> * </ul> */ @Test @DependsOnMethod("testImplementationAnnotations") public void testMethodAnnotations() { for (final Class<?> type : types) { if (ControlledVocabulary.class.isAssignableFrom(type)) { // Skip code lists, since they are not the purpose of this test. continue; } testingMethod = null; testingClass = type.getCanonicalName(); final Class<?> impl = getImplementation(type); if (impl == null) { /* * Implementation existence are tested by 'testImplementationAnnotations()'. * It is not the purpose of this test to verify again their existence. */ continue; } testingClass = impl.getCanonicalName(); for (final Method method : type.getDeclaredMethods()) { if (isIgnored(method)) { continue; } testingMethod = method.getName(); final UML uml = method.getAnnotation(UML.class); final XmlElement element = getXmlElement(impl, testingMethod, uml); /* * Just display the missing @XmlElement annotation for the method, since we know * that some elements are not yet implemented (and consequently can not yet be * annotated). */ if (element == null) { // Note: lines with the "[WARNING]" string are highlighted by Jenkins. warning("[WARNING] Missing @XmlElement annotation for "); continue; } /* * The UML annotation is mandatory in the default implementation of the * 'testInterfaceAnnotations()' method, but we don't require the UML to * be non-null here since this is not the job of this test method. This * is because subclasses may choose to override the above test method. */ if (uml != null) { assertEquals("Wrong @XmlElement.name().", getExpectedXmlElementName(type, uml), element.name()); assertEquals("Wrong @XmlElement.required().", uml.obligation() == Obligation.MANDATORY, element.required()); } /* * Check that the namespace is the expected one (according subclass) * and is not redundant with the package @XmlSchema annotation. */ assertExpectedNamespace(element.namespace(), impl, uml); } } done(); } /** * Tests the annotations on wrappers returned by {@link #getWrapperFor(Class)}. * More specifically this method tests that: * * <ul> * <li>The wrapper have a getter and a setter method declared in the same class.</li> * <li>The getter method is annotated with {@code @XmlElement} or {@code @XmlElementRef}, but not both</li> * <li>{@code @XmlElementRef} is used only in parent classes, not in leaf classes.</li> * <li>The name declared in {@code @XmlElement} matches the {@code @UML} identifier.</li> * </ul> */ @Test public void testWrapperAnnotations() { for (final Class<?> type : types) { testingClass = type.getCanonicalName(); /* * Check the annotation on the wrapper, if there is one. If no wrapper is declared * specifically for the current type, check if a wrapper is defined for the parent * interface. In such case, the getElement() method is required to be annotated by * @XmlElementRef, not @XmlElement, in order to let JAXB infer the name from the * actual subclass. */ final WrapperClass wrapper; try { wrapper = getWrapperInHierarchy(type); } catch (ClassNotFoundException e) { fail(e.toString()); continue; } if (wrapper.type == null) { // If the wrapper is intentionally undefined, skip it. continue; } /* * Now fetch the getter/setter methods, ensure that they are declared in the same class * and verify that exactly one of @XmlElement or @XmlElementRef annotation is declared. */ testingClass = wrapper.type.getCanonicalName(); final XmlElement element; if (type.isEnum()) { final Field field; try { field = wrapper.type.getDeclaredField("value"); } catch (NoSuchFieldException e) { fail(e.toString()); continue; } element = field.getAnnotation(XmlElement.class); } else { final Method getter, setter; try { getter = wrapper.type.getMethod("getElement", (Class<?>[]) null); setter = wrapper.type.getMethod("setElement", getter.getReturnType()); } catch (NoSuchMethodException e) { fail(e.toString()); continue; } assertEquals("The setter method must be declared in the same class than the " + "getter method - not in a parent class, to avoid issues with JAXB.", getter.getDeclaringClass(), setter.getDeclaringClass()); assertEquals("The setter parameter type shall be the same than the getter return type.", getter.getReturnType(), getSingleton(setter.getParameterTypes())); element = getter.getAnnotation(XmlElement.class); assertEquals("Expected @XmlElement XOR @XmlElementRef.", (element == null), getter.isAnnotationPresent(XmlElementRef.class) || getter.isAnnotationPresent(XmlElementRefs.class)); } /* * If the annotation is @XmlElement, ensure that XmlElement.name() is equals to * the UML identifier. Then verify that the */ if (element != null) { assertFalse("Expected @XmlElementRef.", wrapper.isInherited); final UML uml = type.getAnnotation(UML.class); if (uml != null) { // 'assertNotNull' is 'testInterfaceAnnotations()' job. assertEquals("Wrong @XmlElement.", uml.identifier(), element.name()); } final String namespace = assertExpectedNamespace(element.namespace(), wrapper.type, uml); if (!ControlledVocabulary.class.isAssignableFrom(type)) { final String expected = getNamespace(getImplementation(type)); if (expected != null) { // 'assertNotNull' is 'testImplementationAnnotations()' job. assertEquals("Inconsistent @XmlRootElement namespace.", expected, namespace); } } } } done(); } /** * Shall be invoked after every successful test in order * to disable the report of failed class or method. */ protected final void done() { testingClass = null; testingMethod = null; } /** * Prints the given message followed by the name of the class being tested. */ private void warning(String message) { if (testingClass != null) { final StringBuilder buffer = new StringBuilder(message); buffer.append(testingClass); if (testingMethod != null) { buffer.append('.').append(testingMethod).append("()"); } message = buffer.toString(); } out.println(message); } /** * If a test failed, reports the class and method names were the failure occurred. * The message will be written in the {@link #out} printer. * * @see #testingClass * @see #testingMethod */ @After public final void printFailureLocation() { if (testingClass != null) { warning("TEST FAILURE: "); } } }
Temporarily relax some tests because of changs in GeoAPI 4.0-SNAPSHOT. They are corrections in the upgrade to ISO 19115:2014. Those corrections are reflected in the SIS ISO_19115-3 branch, to be merged later. git-svn-id: bd781a9493159d57baabeab2b59de614917f0f5c@1823739 13f79535-47bb-0310-9956-ffa450edef68
core/sis-utility/src/test/java/org/apache/sis/test/AnnotationsTestCase.java
Temporarily relax some tests because of changs in GeoAPI 4.0-SNAPSHOT. They are corrections in the upgrade to ISO 19115:2014. Those corrections are reflected in the SIS ISO_19115-3 branch, to be merged later.
<ide><path>ore/sis-utility/src/test/java/org/apache/sis/test/AnnotationsTestCase.java <ide> switch (specification) { <ide> case ISO_19115: return Namespaces.GMD; <ide> case ISO_19115_2: return Namespaces.GMI; <add> case ISO_19115_3: <ide> case ISO_19139: return Namespaces.GMX; <ide> case ISO_19108: return Namespaces.GMD; <ide> default: throw new IllegalArgumentException(specification.toString()); <ide> * be non-null here since this is not the job of this test method. This <ide> * is because subclasses may choose to override the above test method. <ide> */ <del> if (uml != null) { <add> if (uml != null && false) { // Disabled until we merged the ISO 19115-3 branch. <ide> assertEquals("Wrong @XmlElement.name().", getExpectedXmlElementName(type, uml), element.name()); <ide> assertEquals("Wrong @XmlElement.required().", uml.obligation() == Obligation.MANDATORY, element.required()); <ide> }
JavaScript
mit
bf3a1206e0989b9eebee1eed732d6608f6f4b816
0
Fer0x/Backbone.Safe,Fer0x/Backbone.Safe,orizens/Backbone.Safe
/** * Safe - support for storing Backbone.Model to localstorage * using the 'set' method of Model * * @constructor - use the key 'safe' to define unique storage key for backbone safe * * examples: * * // simple defintion for safe * Backbone.Model.extend({ key: 'my-unique-key' }); * * // advanced defintion for safe with options * Backbone.Model.extend({ * * safe: { * key: 'my-unique-key', * options: { * reload: true * } * } * * }) * * @requires Backbone.js, Underscore.js * @param {string} uniqueID - the name of the storage you'de like to use * @param {object} context - the Backbone.Model instance reference * @param {object} options - (optional) configuration for setting up various features * - {boolean} reload - true to reload (before initialize) data from local sotrage if exists * * @author Oren Farhi, http://orizens.com * * @version 0.3 * */ (function(){ var _ = this._; var Backbone = this.Backbone; // if Underscore or Backbone have not been loaded // exit to prevent js errors if (!_ || !Backbone || !JSON) { return; } // factory for creating extend replacement for Backbone Objects var createExtend = function(extendFn) { return function(config) { var init = config.initialize || function(){}; config.initialize = function() { var storageKey; // create safe if exist as key if (config && config.safe) { // handle key, value safe storageKey = config.safe.key ? config.safe.key : config.safe; Backbone.Safe.create(storageKey, this, config.safe.options || { reload: true }); } //- run init of the model instance init.apply(this, arguments); }; return extendFn.call(this, config); }; }; // extend Model & Collection constructor to handle safe initialization Backbone.Model.extend = createExtend(Backbone.Model.extend); Backbone.Collection.extend = createExtend(Backbone.Collection.extend); Backbone.Safe = function(uniqueID, context, options) { // parsing options settings this._reload = options && options.reload && options.reload === true; this.uid = uniqueID; this.context = context; this.isCollection = !context.set && context.models && context.add; // mixins for collection and model var collection = { // events that Safe is listening in order to // trigger save to local storage events: 'add reset', // the value to be used when cleaning the safe emptyValue: '[]', reload: function() { context.add(this.getData()); }, toJSON: function(collection) { return collection.toJSON(); } }; var model = { events: 'change', emptyValue: '{}', reload: function() { context.set(this.getData()); }, toJSON: function(model) { return model.toJSON(); } }; // attach relevant object to Safe prototype _.extend( this, this.isCollection ? collection : model ); // if the uid doesn't exist, create it this.ensureUID(); // These are the lines that are responsible for // loading the saved data from the local storage to the model // // the data is loaded before the Safe binds to change events // storage exist ? -> save to model // if it's a collection - use add if (this._reload) { this.reload(); } // listen to any change event and cache it context.on(this.events, this.store, this); }; Backbone.Safe.prototype = { /** * creates a local storage item with the provided * UID if not exist */ ensureUID: function() { if (_.isNull(this.getData())){ this.create(); } }, create: function() { this.storage().setItem(this.uid, this.emptyValue); }, store: function(model) { this.storage() .setItem(this.uid, JSON.stringify( this.toJSON( model ))); }, storage: function() { return localStorage; }, /** * returns json object of the local saved data * @return {json} */ getData: function() { // JSON.parse can't be run with an empty string this._current = this.storage().getItem(this.uid); return this._current ? JSON.parse(this._current) : this._current; }, // set the local storage key to the empty value reset: function() { this.create(); }, // removes the key from teh localstorage destroy: function() { this.storage().removeItem( this.uid ); } }; // factory method Backbone.Safe.create = function( uniqueID, context, options) { if (uniqueID && context) { context.safe = new Backbone.Safe(uniqueID, context, options); } }; })();
backbone.safe.js
/** * Safe - support for storing Backbone.Model to localstorage * using the 'set' method of Model * * @constructor - use the key 'safe' to define unique storage key for backbone safe * * examples: * * // simple defintion for safe * Backbone.Model.extend({ key: 'my-unique-key' }); * * // advanced defintion for safe with options * Backbone.Model.extend({ * * safe: { * key: 'my-unique-key', * options: { * reload: true * } * } * * }) * * @requires Backbone.js, Underscore.js * @param {string} uniqueID - the name of the storage you'de like to use * @param {object} context - the Backbone.Model instance reference * @param {object} options - (optional) configuration for setting up various features * - {boolean} reload - true to reload (before initialize) data from local sotrage if exists * * @author Oren Farhi, http://orizens.com * * @version 0.3 * */ (function(){ var _ = this._; var Backbone = this.Backbone; // if Underscore or Backbone have not been loaded // exit to prevent js errors if (!_ || !Backbone || !JSON) { return; } // factory for creating extend replacement for Backbone Objects var createExtend = function(extendFn) { return function(config) { var init = config.initialize || function(){}; config.initialize = function() { var storageKey; // create safe if exist as key if (config && config.safe) { // handle key, value safe storageKey = config.safe.key ? config.safe.key : config.safe; Backbone.Safe.create(storageKey, this, config.safe.options || { reload: true }); } //- run init of the model instance init.apply(this, arguments); }; return extendFn.call(this, config); }; }; // extend Model & Collection constructor to handle safe initialization Backbone.Model.extend = createExtend(Backbone.Model.extend); Backbone.Collection.extend = createExtend(Backbone.Collection.extend); Backbone.Safe = function(uniqueID, context, options) { // parsing options settings this._reload = options && options.reload && options.reload === true; this.uid = uniqueID; this.context = context; this.isCollection = !context.set && context.models && context.add; // mixins for collection and model var collection = { // events that Safe is listening in order to // trigger save to local storage events: 'add reset', // the value to be used when cleaning the safe emptyValue: '[]', reload: function() { context.add(this.getData()); }, toJSON: function(collection) { return collection.toJSON(); } }; var model = { events: 'change', emptyValue: '{}', reload: function() { context.set(this.getData()); }, toJSON: function(model) { return model.toJSON(); } }; // attach relevant object to Safe prototype _.extend( this, this.isCollection ? collection : model ); // if the uid doesn't exist, create it this.ensureUID(); // These are the lines that are responsible for // loading the saved data from the local storage to the model // // the data is loaded before the Safe binds to change events // storage exist ? -> save to model // if it's a collection - use add if (this._reload) { this.reload(); } // listen to any change event and cache it context.on(this.events, this.store, this); }; Backbone.Safe.prototype = { /** * creates a local storage item with the provided * UID if not exist */ ensureUID: function() { if (_.isNull(this.getData())){ this.create(); } }, create: function() { this.storage().setItem(this.uid, this.emptyValue); }, store: function(model) { this.storage() .setItem(this.uid, JSON.stringify( this.toJSON( model ))); }, storage: function() { return localStorage; }, /** * returns json object of the local saved data * @return {json} */ getData: function() { // JSON.parse can't be run with an empty string this._current = this.storage().getItem(this.uid); return this._current ? JSON.parse(this._current) : this._current; }, // set the local storage key to the empty value reset: function() { this.create(); }, // removes the key from teh localstorage destroy: function() { this.storage().removeItem( this.uniqueID ); } }; // factory method Backbone.Safe.create = function( uniqueID, context, options) { if (uniqueID && context) { context.safe = new Backbone.Safe(uniqueID, context, options); } }; })();
closed #5 thanks @codelance
backbone.safe.js
closed #5
<ide><path>ackbone.safe.js <ide> <ide> // removes the key from teh localstorage <ide> destroy: function() { <del> this.storage().removeItem( this.uniqueID ); <add> this.storage().removeItem( this.uid ); <ide> } <ide> }; <ide>
Java
apache-2.0
f8b8055e0d26078627ba53d70bcaf8b328d3b1b1
0
mmanski/sling,klcodanr/sling,tyge68/sling,cleliameneghin/sling,roele/sling,tmaret/sling,dulvac/sling,nleite/sling,roele/sling,Sivaramvt/sling,mmanski/sling,ist-dresden/sling,ist-dresden/sling,klcodanr/sling,cleliameneghin/sling,Nimco/sling,tmaret/sling,plutext/sling,dulvac/sling,nleite/sling,tyge68/sling,roele/sling,ieb/sling,tyge68/sling,mikibrv/sling,sdmcraft/sling,gutsy/sling,JEBailey/sling,labertasch/sling,gutsy/sling,anchela/sling,mcdan/sling,klcodanr/sling,labertasch/sling,plutext/sling,wimsymons/sling,cleliameneghin/sling,vladbailescu/sling,ffromm/sling,mikibrv/sling,headwirecom/sling,klcodanr/sling,mcdan/sling,trekawek/sling,SylvesterAbreu/sling,mikibrv/sling,nleite/sling,roele/sling,sdmcraft/sling,Nimco/sling,Nimco/sling,ffromm/sling,awadheshv/sling,awadheshv/sling,wimsymons/sling,ist-dresden/sling,mmanski/sling,JEBailey/sling,sdmcraft/sling,SylvesterAbreu/sling,plutext/sling,labertasch/sling,cleliameneghin/sling,mcdan/sling,nleite/sling,wimsymons/sling,mmanski/sling,ffromm/sling,SylvesterAbreu/sling,ieb/sling,headwirecom/sling,Sivaramvt/sling,ist-dresden/sling,sdmcraft/sling,vladbailescu/sling,awadheshv/sling,plutext/sling,anchela/sling,dulvac/sling,JEBailey/sling,Nimco/sling,labertasch/sling,mmanski/sling,mikibrv/sling,ist-dresden/sling,tmaret/sling,SylvesterAbreu/sling,mcdan/sling,tyge68/sling,trekawek/sling,gutsy/sling,anchela/sling,Nimco/sling,awadheshv/sling,plutext/sling,ffromm/sling,tmaret/sling,trekawek/sling,gutsy/sling,JEBailey/sling,JEBailey/sling,headwirecom/sling,mikibrv/sling,ieb/sling,cleliameneghin/sling,ffromm/sling,vladbailescu/sling,gutsy/sling,trekawek/sling,Sivaramvt/sling,plutext/sling,trekawek/sling,Sivaramvt/sling,labertasch/sling,dulvac/sling,tteofili/sling,tteofili/sling,nleite/sling,mcdan/sling,trekawek/sling,ieb/sling,ieb/sling,tyge68/sling,roele/sling,awadheshv/sling,mikibrv/sling,wimsymons/sling,tmaret/sling,awadheshv/sling,headwirecom/sling,tyge68/sling,vladbailescu/sling,tteofili/sling,sdmcraft/sling,Nimco/sling,sdmcraft/sling,tteofili/sling,ieb/sling,mcdan/sling,Sivaramvt/sling,anchela/sling,SylvesterAbreu/sling,tteofili/sling,klcodanr/sling,Sivaramvt/sling,wimsymons/sling,dulvac/sling,dulvac/sling,SylvesterAbreu/sling,anchela/sling,tteofili/sling,gutsy/sling,vladbailescu/sling,klcodanr/sling,wimsymons/sling,mmanski/sling,headwirecom/sling,nleite/sling,ffromm/sling
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.apache.sling.hc.webconsole.impl; import static org.apache.sling.hc.util.FormattingResultLog.msHumanReadable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Collection; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.request.ResponseUtil; import org.apache.sling.hc.api.Result; import org.apache.sling.hc.api.ResultLog; import org.apache.sling.hc.api.execution.HealthCheckExecutionOptions; import org.apache.sling.hc.api.execution.HealthCheckExecutionResult; import org.apache.sling.hc.api.execution.HealthCheckExecutor; /** Webconsole plugin to execute health check services */ @Component @Service(Servlet.class) @SuppressWarnings("serial") @Properties({ @Property(name=org.osgi.framework.Constants.SERVICE_DESCRIPTION, value="Apache Sling Health Check Web Console Plugin"), @Property(name="felix.webconsole.label", value=HealthCheckWebconsolePlugin.LABEL), @Property(name="felix.webconsole.title", value=HealthCheckWebconsolePlugin.TITLE), @Property(name="felix.webconsole.category", value=HealthCheckWebconsolePlugin.CATEGORY), @Property(name="felix.webconsole.css", value="/healthcheck/res/ui/healthcheck.css") }) public class HealthCheckWebconsolePlugin extends HttpServlet { public static final String TITLE = "Sling Health Check"; public static final String LABEL = "healthcheck"; public static final String CATEGORY = "Sling"; public static final String PARAM_TAGS = "tags"; public static final String PARAM_DEBUG = "debug"; public static final String PARAM_QUIET = "quiet"; public static final String PARAM_FORCE_INSTANT_EXECUTION = "forceInstantExecution"; public static final String PARAM_COMBINE_TAGS_WITH_OR = "combineTagsWithOr"; public static final String PARAM_OVERRIDE_GLOBAL_TIMEOUT = "overrideGlobalTimeout"; @Reference private HealthCheckExecutor healthCheckExecutor; /** Serve static resource if applicable, and return true in that case */ private boolean getStaticResource(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final String pathInfo = req.getPathInfo(); if (pathInfo!= null && pathInfo.contains("res/ui")) { final String prefix = "/" + LABEL; final InputStream is = getClass().getResourceAsStream(pathInfo.substring(prefix.length())); if (is == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, pathInfo); } else { final OutputStream os = resp.getOutputStream(); try { final byte [] buffer = new byte[16384]; int n=0; while( (n = is.read(buffer, 0, buffer.length)) > 0) { os.write(buffer, 0, n); } } finally { try { is.close(); } catch ( final IOException ignore ) { // ignore } } } return true; } return false; } @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (getStaticResource(req, resp)) { return; } final String tags = getParam(req, PARAM_TAGS, null); final boolean debug = Boolean.valueOf(getParam(req, PARAM_DEBUG, "false")); final boolean quiet = Boolean.valueOf(getParam(req, PARAM_QUIET, "false")); final boolean combineTagsWithOr = Boolean.valueOf(getParam(req, PARAM_COMBINE_TAGS_WITH_OR, "false")); final boolean forceInstantExecution = Boolean.valueOf(getParam(req, PARAM_FORCE_INSTANT_EXECUTION, "false")); final String overrideGlobalTimeoutStr = getParam(req, PARAM_OVERRIDE_GLOBAL_TIMEOUT, ""); final PrintWriter pw = resp.getWriter(); doForm(pw, tags, debug, quiet, combineTagsWithOr, forceInstantExecution, overrideGlobalTimeoutStr); // Execute health checks only if tags are specified (even if empty) if (tags != null) { HealthCheckExecutionOptions options = new HealthCheckExecutionOptions(); options.setCombineTagsWithOr(combineTagsWithOr); options.setForceInstantExecution(forceInstantExecution); try { options.setOverrideGlobalTimeout(Integer.valueOf(overrideGlobalTimeoutStr)); } catch (NumberFormatException nfe) { // override not set in UI } Collection<HealthCheckExecutionResult> results = healthCheckExecutor.execute(options, tags.split(",")); pw.println("<table class='content healthcheck' cellpadding='0' cellspacing='0' width='100%'>"); int total = 0; int failed = 0; for (final HealthCheckExecutionResult exR : results) { final Result r = exR.getHealthCheckResult(); total++; if (!r.isOk()) { failed++; } if (!quiet || !r.isOk()) { renderResult(pw, exR, debug); } } final WebConsoleHelper c = new WebConsoleHelper(resp.getWriter()); c.titleHtml("Summary", total + " HealthCheck executed, " + failed + " failures"); pw.println("</table>"); pw.println("<a href='configMgr/org.apache.sling.hc.core.impl.executor.HealthCheckExecutorImpl'>Configure executor</a><br/><br/>"); } } private void renderResult(final PrintWriter pw, final HealthCheckExecutionResult exResult, final boolean debug) throws IOException { final Result result = exResult.getHealthCheckResult(); final WebConsoleHelper c = new WebConsoleHelper(pw); final StringBuilder status = new StringBuilder(); status.append("Tags: ").append(exResult.getHealthCheckMetadata().getTags()); status.append(" Finished: ").append(new SimpleDateFormat("yyyy-MM-dd mm:ss").format(exResult.getFinishedAt()) + " after " + msHumanReadable(exResult.getElapsedTimeInMs())); c.titleHtml(exResult.getHealthCheckMetadata().getTitle(), null); c.tr(); c.tdContent(); c.writer().print(ResponseUtil.escapeXml(status.toString())); c.writer().print("<br/>Result: <span class='resultOk"); c.writer().print(result.isOk()); c.writer().print("'>"); c.writer().print(result.getStatus().toString()); c.writer().print("</span>"); c.closeTd(); c.closeTr(); c.tr(); c.tdContent(); for(final ResultLog.Entry e : result) { if (!debug && e.getStatus().equals(Result.Status.DEBUG)) { continue; } c.writer().print("<div class='log"); c.writer().print(e.getStatus().toString()); c.writer().print("'>"); c.writer().print(e.getStatus().toString()); c.writer().print(' '); c.writer().print(ResponseUtil.escapeXml(e.getMessage())); if (e.getException() != null) { c.writer().print(" "); c.writer().print(ResponseUtil.escapeXml(e.getException().toString())); } c.writer().println("</div>"); } c.closeTd(); } private void doForm(final PrintWriter pw, final String tags, final boolean debug, final boolean quiet, final boolean combineTagsWithOr, final boolean forceInstantExecution, final String overrideGlobalTimeoutStr) throws IOException { final WebConsoleHelper c = new WebConsoleHelper(pw); pw.print("<form method='get'>"); pw.println("<table class='content' cellpadding='0' cellspacing='0' width='100%'>"); c.titleHtml(TITLE, "To execute health check services, enter " + " an optional list of tags, to select specific health checks, or no tags for all checks." + " Prefix a tag with a minus sign (-) to omit checks having that tag."); c.tr(); c.tdLabel("Health Check tags (comma-separated)"); c.tdContent(); c.writer().print("<input type='text' name='" + PARAM_TAGS + "' value='"); if ( tags != null ) { c.writer().print(ResponseUtil.escapeXml(tags)); } c.writer().println("' class='input' size='80'>"); c.closeTd(); c.closeTr(); c.tr(); c.tdLabel("Combine tags with logical 'OR' instead of the default 'AND'"); c.tdContent(); c.writer().print("<input type='checkbox' name='" + PARAM_COMBINE_TAGS_WITH_OR + "' class='input' value='true'"); if (combineTagsWithOr) { c.writer().print(" checked=true"); } c.writer().println(">"); c.closeTd(); c.closeTr(); c.tr(); c.tdLabel("Show DEBUG logs"); c.tdContent(); c.writer().print("<input type='checkbox' name='" + PARAM_DEBUG + "' class='input' value='true'"); if ( debug ) { c.writer().print(" checked=true"); } c.writer().println(">"); c.closeTd(); c.closeTr(); c.tr(); c.tdLabel("Show failed checks only"); c.tdContent(); c.writer().print("<input type='checkbox' name='" + PARAM_QUIET + "' class='input' value='true'"); if ( quiet ) { c.writer().print(" checked=true"); } c.writer().println(">"); c.closeTd(); c.closeTr(); c.tr(); c.tdLabel("Force instant execution (no cache, async checks are executed)"); c.tdContent(); c.writer().print("<input type='checkbox' name='" + PARAM_FORCE_INSTANT_EXECUTION + "' class='input' value='true'"); if (forceInstantExecution) { c.writer().print(" checked=true"); } c.writer().println(">"); c.closeTd(); c.closeTr(); c.tr(); c.tdLabel("Override global timeout"); c.tdContent(); c.writer().print("<input type='text' name='" + PARAM_OVERRIDE_GLOBAL_TIMEOUT + "' value='"); if (overrideGlobalTimeoutStr != null) { c.writer().print(ResponseUtil.escapeXml(overrideGlobalTimeoutStr)); } c.writer().println("' class='input' size='80'>"); c.closeTd(); c.closeTr(); c.tr(); c.tdContent(); c.writer().println("<input type='submit' value='Execute selected health checks'/>"); c.closeTd(); c.closeTr(); c.writer().println("</table></form>"); } private String getParam(final HttpServletRequest req, final String name, final String defaultValue) { String result = req.getParameter(name); if(result == null) { result = defaultValue; } return result; } }
bundles/extensions/healthcheck/webconsole/src/main/java/org/apache/sling/hc/webconsole/impl/HealthCheckWebconsolePlugin.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.apache.sling.hc.webconsole.impl; import static org.apache.sling.hc.util.FormattingResultLog.msHumanReadable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Collection; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.sling.api.request.ResponseUtil; import org.apache.sling.hc.api.Result; import org.apache.sling.hc.api.ResultLog; import org.apache.sling.hc.api.execution.HealthCheckExecutionOptions; import org.apache.sling.hc.api.execution.HealthCheckExecutionResult; import org.apache.sling.hc.api.execution.HealthCheckExecutor; /** Webconsole plugin to execute health check services */ @Component @Service(Servlet.class) @SuppressWarnings("serial") @Properties({ @Property(name=org.osgi.framework.Constants.SERVICE_DESCRIPTION, value="Sling Health Check Web Console Plugin"), @Property(name="felix.webconsole.label", value=HealthCheckWebconsolePlugin.LABEL), @Property(name="felix.webconsole.title", value=HealthCheckWebconsolePlugin.TITLE), @Property(name="felix.webconsole.category", value=HealthCheckWebconsolePlugin.CATEGORY), @Property(name="felix.webconsole.css", value="/healthcheck/res/ui/healthcheck.css") }) public class HealthCheckWebconsolePlugin extends HttpServlet { public static final String TITLE = "Sling Health Check"; public static final String LABEL = "healthcheck"; public static final String CATEGORY = "Sling"; public static final String PARAM_TAGS = "tags"; public static final String PARAM_DEBUG = "debug"; public static final String PARAM_QUIET = "quiet"; public static final String PARAM_FORCE_INSTANT_EXECUTION = "forceInstantExecution"; public static final String PARAM_COMBINE_TAGS_WITH_OR = "combineTagsWithOr"; public static final String PARAM_OVERRIDE_GLOBAL_TIMEOUT = "overrideGlobalTimeout"; @Reference private HealthCheckExecutor healthCheckExecutor; /** Serve static resource if applicable, and return true in that case */ private boolean getStaticResource(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final String pathInfo = req.getPathInfo(); if (pathInfo!= null && pathInfo.contains("res/ui")) { final String prefix = "/" + LABEL; final InputStream is = getClass().getResourceAsStream(pathInfo.substring(prefix.length())); if (is == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, pathInfo); } else { final OutputStream os = resp.getOutputStream(); try { final byte [] buffer = new byte[16384]; int n=0; while( (n = is.read(buffer, 0, buffer.length)) > 0) { os.write(buffer, 0, n); } } finally { try { is.close(); } catch ( final IOException ignore ) { // ignore } } } return true; } return false; } @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { if (getStaticResource(req, resp)) { return; } final String tags = getParam(req, PARAM_TAGS, null); final boolean debug = Boolean.valueOf(getParam(req, PARAM_DEBUG, "false")); final boolean quiet = Boolean.valueOf(getParam(req, PARAM_QUIET, "false")); final boolean combineTagsWithOr = Boolean.valueOf(getParam(req, PARAM_COMBINE_TAGS_WITH_OR, "false")); final boolean forceInstantExecution = Boolean.valueOf(getParam(req, PARAM_FORCE_INSTANT_EXECUTION, "false")); final String overrideGlobalTimeoutStr = getParam(req, PARAM_OVERRIDE_GLOBAL_TIMEOUT, ""); final PrintWriter pw = resp.getWriter(); doForm(pw, tags, debug, quiet, combineTagsWithOr, forceInstantExecution, overrideGlobalTimeoutStr); // Execute health checks only if tags are specified (even if empty) if (tags != null) { HealthCheckExecutionOptions options = new HealthCheckExecutionOptions(); options.setCombineTagsWithOr(combineTagsWithOr); options.setForceInstantExecution(forceInstantExecution); try { options.setOverrideGlobalTimeout(Integer.valueOf(overrideGlobalTimeoutStr)); } catch (NumberFormatException nfe) { // override not set in UI } Collection<HealthCheckExecutionResult> results = healthCheckExecutor.execute(options, tags.split(",")); pw.println("<table class='content healthcheck' cellpadding='0' cellspacing='0' width='100%'>"); int total = 0; int failed = 0; for (final HealthCheckExecutionResult exR : results) { final Result r = exR.getHealthCheckResult(); total++; if (!r.isOk()) { failed++; } if (!quiet || !r.isOk()) { renderResult(pw, exR, debug); } } final WebConsoleHelper c = new WebConsoleHelper(resp.getWriter()); c.titleHtml("Summary", total + " HealthCheck executed, " + failed + " failures"); pw.println("</table>"); pw.println("<a href='configMgr/org.apache.sling.hc.core.impl.executor.HealthCheckExecutorImpl'>Configure executor</a><br/><br/>"); } } private void renderResult(final PrintWriter pw, final HealthCheckExecutionResult exResult, final boolean debug) throws IOException { final Result result = exResult.getHealthCheckResult(); final WebConsoleHelper c = new WebConsoleHelper(pw); final StringBuilder status = new StringBuilder(); status.append("Tags: ").append(exResult.getHealthCheckMetadata().getTags()); status.append(" Finished: ").append(new SimpleDateFormat("yyyy-MM-dd mm:ss").format(exResult.getFinishedAt()) + " after " + msHumanReadable(exResult.getElapsedTimeInMs())); c.titleHtml(exResult.getHealthCheckMetadata().getTitle(), null); c.tr(); c.tdContent(); c.writer().print(ResponseUtil.escapeXml(status.toString())); c.writer().print("<br/>Result: <span class='resultOk"); c.writer().print(result.isOk()); c.writer().print("'>"); c.writer().print(result.getStatus().toString()); c.writer().print("</span>"); c.closeTd(); c.closeTr(); c.tr(); c.tdContent(); for(final ResultLog.Entry e : result) { if (!debug && e.getStatus().equals(Result.Status.DEBUG)) { continue; } c.writer().print("<div class='log"); c.writer().print(e.getStatus().toString()); c.writer().print("'>"); c.writer().print(e.getStatus().toString()); c.writer().print(' '); c.writer().print(ResponseUtil.escapeXml(e.getMessage())); if (e.getException() != null) { c.writer().print(" "); c.writer().print(ResponseUtil.escapeXml(e.getException().toString())); } c.writer().println("</div>"); } c.closeTd(); } private void doForm(final PrintWriter pw, final String tags, final boolean debug, final boolean quiet, final boolean combineTagsWithOr, final boolean forceInstantExecution, final String overrideGlobalTimeoutStr) throws IOException { final WebConsoleHelper c = new WebConsoleHelper(pw); pw.print("<form method='get'>"); pw.println("<table class='content' cellpadding='0' cellspacing='0' width='100%'>"); c.titleHtml(TITLE, "To execute health check services, enter " + " an optional list of tags, to select specific health checks, or no tags for all checks." + " Prefix a tag with a minus sign (-) to omit checks having that tag."); c.tr(); c.tdLabel("Health Check tags (comma-separated)"); c.tdContent(); c.writer().print("<input type='text' name='" + PARAM_TAGS + "' value='"); if ( tags != null ) { c.writer().print(ResponseUtil.escapeXml(tags)); } c.writer().println("' class='input' size='80'>"); c.closeTd(); c.closeTr(); c.tr(); c.tdLabel("Combine tags with logical 'OR' instead of the default 'AND'"); c.tdContent(); c.writer().print("<input type='checkbox' name='" + PARAM_COMBINE_TAGS_WITH_OR + "' class='input' value='true'"); if (combineTagsWithOr) { c.writer().print(" checked=true"); } c.writer().println(">"); c.closeTd(); c.closeTr(); c.tr(); c.tdLabel("Show DEBUG logs"); c.tdContent(); c.writer().print("<input type='checkbox' name='" + PARAM_DEBUG + "' class='input' value='true'"); if ( debug ) { c.writer().print(" checked=true"); } c.writer().println(">"); c.closeTd(); c.closeTr(); c.tr(); c.tdLabel("Show failed checks only"); c.tdContent(); c.writer().print("<input type='checkbox' name='" + PARAM_QUIET + "' class='input' value='true'"); if ( quiet ) { c.writer().print(" checked=true"); } c.writer().println(">"); c.closeTd(); c.closeTr(); c.tr(); c.tdLabel("Force instant execution (no cache, async checks are executed)"); c.tdContent(); c.writer().print("<input type='checkbox' name='" + PARAM_FORCE_INSTANT_EXECUTION + "' class='input' value='true'"); if (forceInstantExecution) { c.writer().print(" checked=true"); } c.writer().println(">"); c.closeTd(); c.closeTr(); c.tr(); c.tdLabel("Override global timeout"); c.tdContent(); c.writer().print("<input type='text' name='" + PARAM_OVERRIDE_GLOBAL_TIMEOUT + "' value='"); if (overrideGlobalTimeoutStr != null) { c.writer().print(ResponseUtil.escapeXml(overrideGlobalTimeoutStr)); } c.writer().println("' class='input' size='80'>"); c.closeTd(); c.closeTr(); c.tr(); c.tdContent(); c.writer().println("<input type='submit' value='Execute selected health checks'/>"); c.closeTd(); c.closeTr(); c.writer().println("</table></form>"); } private String getParam(final HttpServletRequest req, final String name, final String defaultValue) { String result = req.getParameter(name); if(result == null) { result = defaultValue; } return result; } }
Correct typo in description git-svn-id: 6eed74fe9a15c8da84b9a8d7f2960c0406113ece@1660607 13f79535-47bb-0310-9956-ffa450edef68
bundles/extensions/healthcheck/webconsole/src/main/java/org/apache/sling/hc/webconsole/impl/HealthCheckWebconsolePlugin.java
Correct typo in description
<ide><path>undles/extensions/healthcheck/webconsole/src/main/java/org/apache/sling/hc/webconsole/impl/HealthCheckWebconsolePlugin.java <ide> @Service(Servlet.class) <ide> @SuppressWarnings("serial") <ide> @Properties({ <del> @Property(name=org.osgi.framework.Constants.SERVICE_DESCRIPTION, value="Sling Health Check Web Console Plugin"), <add> @Property(name=org.osgi.framework.Constants.SERVICE_DESCRIPTION, value="Apache Sling Health Check Web Console Plugin"), <ide> @Property(name="felix.webconsole.label", value=HealthCheckWebconsolePlugin.LABEL), <ide> @Property(name="felix.webconsole.title", value=HealthCheckWebconsolePlugin.TITLE), <ide> @Property(name="felix.webconsole.category", value=HealthCheckWebconsolePlugin.CATEGORY),
Java
lgpl-2.1
9d1b19b92bb1877f5a3ad2fe096725667a85ddbb
0
languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool,jimregan/languagetool,jimregan/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,jimregan/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.language; import org.languagetool.Language; import org.languagetool.LanguageMaintainedState; import org.languagetool.rules.*; import org.languagetool.rules.gl.*; import org.languagetool.synthesis.Synthesizer; import org.languagetool.synthesis.gl.GalicianSynthesizer; import org.languagetool.rules.spelling.hunspell.HunspellRule; import org.languagetool.tagging.Tagger; import org.languagetool.tagging.disambiguation.Disambiguator; import org.languagetool.tagging.disambiguation.gl.GalicianHybridDisambiguator; import org.languagetool.tagging.gl.GalicianTagger; import org.languagetool.tokenizers.SRXSentenceTokenizer; import org.languagetool.tokenizers.SentenceTokenizer; import org.languagetool.tokenizers.Tokenizer; import org.languagetool.tokenizers.gl.GalicianWordTokenizer; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; public class Galician extends Language { private Tagger tagger; private Tokenizer wordTokenizer; private SentenceTokenizer sentenceTokenizer; private Synthesizer synthesizer; private Disambiguator disambiguator; @Override public SentenceTokenizer getSentenceTokenizer() { if (sentenceTokenizer == null) { sentenceTokenizer = new SRXSentenceTokenizer(this); } return sentenceTokenizer; } @Override public String getName() { return "Galician"; } @Override public String getShortCode() { return "gl"; } @Override public String[] getCountries() { return new String[]{"ES"}; } @Override public Tagger getTagger() { if (tagger == null) { tagger = new GalicianTagger(); } return tagger; } @Override public Tokenizer getWordTokenizer() { if (wordTokenizer == null) { wordTokenizer = new GalicianWordTokenizer(); } return wordTokenizer; } @Override public Synthesizer getSynthesizer() { if (synthesizer == null) { synthesizer = new GalicianSynthesizer(); } return synthesizer; } @Override public Disambiguator getDisambiguator() { if (disambiguator == null) { disambiguator = new GalicianHybridDisambiguator(); } return disambiguator; } @Override public LanguageMaintainedState getMaintainedState() { return LanguageMaintainedState.ActivelyMaintained; } @Override public Contributor[] getMaintainers() { return new Contributor[] { new Contributor("Susana Sotelo Docío"), new Contributor("Tiago F. Santos (4.0)", "https://github.com/TiagoSantos81") }; } @Override public List<Rule> getRelevantRules(ResourceBundle messages) throws IOException { return Arrays.asList( new CommaWhitespaceRule(messages, Example.wrong("Tomamos café<marker> ,</marker> queixo, bolachas e uvas."), Example.fixed("Tomamos café<marker>,</marker> queixo, bolachas e uvas.")), new DoublePunctuationRule(messages), new GenericUnpairedBracketsRule(messages, Arrays.asList("[", "(", "{", "“", "«", "»", "‘", "\"", "'"), Arrays.asList("]", ")", "}", "”", "»", "«", "’", "\"", "'")), new HunspellRule(messages, this), new UppercaseSentenceStartRule(messages, this, Example.wrong("Esta casa é vella. <marker>foi</marker> construida en 1950."), Example.fixed("Esta casa é vella. <marker>Foi</marker> construida en 1950.")), new MultipleWhitespaceRule(messages, this), new LongSentenceRule(messages, 20, false), new LongSentenceRule(messages, 25, false), new LongSentenceRule(messages, 30, false), new LongSentenceRule(messages, 35, false), new LongSentenceRule(messages, 40, false), new LongSentenceRule(messages, 45, false), new LongSentenceRule(messages, 50, true), new LongSentenceRule(messages, 60, false), new SentenceWhitespaceRule(messages), new WhiteSpaceBeforeParagraphEnd(messages), new WhiteSpaceAtBeginOfParagraph(messages), new EmptyLineRule(messages), // Specific to Galician: new SimpleReplaceRule(messages), new CastWordsRule(messages), new GalicianRedundancyRule(messages), new GalicianWordinessRule(messages), new GalicianBarbarismsRule(messages), new GalicianWikipediaRule(messages) ); } @Override public int getPriorityForId(String id) { switch (id) { // case "FRAGMENT_TWO_ARTICLES": return 50; case "DEGREE_MINUTES_SECONDS": return 30; // case "INTERJECTIONS_PUNTUATION": return 20; // case "CONFUSION_POR": return 10; // case "HOMOPHONE_AS_CARD": return 5; // case "TODOS_FOLLOWED_BY_NOUN_PLURAL": return 3; // case "TODOS_FOLLOWED_BY_NOUN_SINGULAR": return 2; case "UNPAIRED_BRACKETS": return -5; // case "PROFANITY": return -6; case "GL_BARBARISM_REPLACE": return -10; case "GL_SIMPLE_REPLACE": return -11; case "GL_REDUNDANCY_REPLACE": return -12; case "GL_WORDINESS_REPLACE": return -13; // case "GL_CLICHE_REPLACE": return -17; // case "CHILDISH_LANGUAGE": return -25; // case "ARCHAISMS": return -26; // case "INFORMALITIES": return -27; // case "PUFFERY": return -30; // case "BIASED_OPINION_WORDS": return -31; // case "WEAK_WORDS": return -32; // case "PT_AGREEMENT_REPLACE": return -35; case "GL_WIKIPEDIA_COMMON_ERRORS":return -45; case "HUNSPELL_RULE": return -50; // case "NO_VERB": return -52; // case "CRASE_CONFUSION": return -55; // case "FINAL_STOPS": return -75; // case "T-V_DISTINCTION": return -100; // case "T-V_DISTINCTION_ALL": return -101; case "REPEATED_WORDS": return -210; case "REPEATED_WORDS_3X": return -211; case "TOO_LONG_SENTENCE_20": return -997; case "TOO_LONG_SENTENCE_25": return -998; case "TOO_LONG_SENTENCE_30": return -999; case "TOO_LONG_SENTENCE_35": return -1000; case "TOO_LONG_SENTENCE_40": return -1001; case "TOO_LONG_SENTENCE_45": return -1002; case "TOO_LONG_SENTENCE_50": return -1003; case "TOO_LONG_SENTENCE_60": return -1004; // case "CACOPHONY": return -2000; } return 0; } }
languagetool-language-modules/gl/src/main/java/org/languagetool/language/Galician.java
/* LanguageTool, a natural language style checker * Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.language; import org.languagetool.Language; import org.languagetool.LanguageMaintainedState; import org.languagetool.rules.*; import org.languagetool.rules.gl.*; import org.languagetool.synthesis.Synthesizer; import org.languagetool.synthesis.gl.GalicianSynthesizer; import org.languagetool.rules.spelling.hunspell.HunspellRule; import org.languagetool.tagging.Tagger; import org.languagetool.tagging.disambiguation.Disambiguator; import org.languagetool.tagging.disambiguation.gl.GalicianHybridDisambiguator; import org.languagetool.tagging.gl.GalicianTagger; import org.languagetool.tokenizers.SRXSentenceTokenizer; import org.languagetool.tokenizers.SentenceTokenizer; import org.languagetool.tokenizers.Tokenizer; import org.languagetool.tokenizers.gl.GalicianWordTokenizer; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.ResourceBundle; public class Galician extends Language { private Tagger tagger; private Tokenizer wordTokenizer; private SentenceTokenizer sentenceTokenizer; private Synthesizer synthesizer; private Disambiguator disambiguator; @Override public SentenceTokenizer getSentenceTokenizer() { if (sentenceTokenizer == null) { sentenceTokenizer = new SRXSentenceTokenizer(this); } return sentenceTokenizer; } @Override public String getName() { return "Galician"; } @Override public String getShortCode() { return "gl"; } @Override public String[] getCountries() { return new String[]{"ES"}; } @Override public Tagger getTagger() { if (tagger == null) { tagger = new GalicianTagger(); } return tagger; } @Override public Tokenizer getWordTokenizer() { if (wordTokenizer == null) { wordTokenizer = new GalicianWordTokenizer(); } return wordTokenizer; } @Override public Synthesizer getSynthesizer() { if (synthesizer == null) { synthesizer = new GalicianSynthesizer(); } return synthesizer; } @Override public Disambiguator getDisambiguator() { if (disambiguator == null) { disambiguator = new GalicianHybridDisambiguator(); } return disambiguator; } @Override public LanguageMaintainedState getMaintainedState() { return LanguageMaintainedState.ActivelyMaintained; } @Override public Contributor[] getMaintainers() { return new Contributor[] { new Contributor("Susana Sotelo Docío"), new Contributor("Tiago F. Santos (4.0)", "https://github.com/TiagoSantos81") }; } @Override public List<Rule> getRelevantRules(ResourceBundle messages) throws IOException { return Arrays.asList( new CommaWhitespaceRule(messages, Example.wrong("Tomamos café<marker> ,</marker> queixo, bolachas e uvas."), Example.fixed("Tomamos café<marker>,</marker> queixo, bolachas e uvas.")), new DoublePunctuationRule(messages), new GenericUnpairedBracketsRule(messages, Arrays.asList("[", "(", "{", "“", "«", "»", "‘", "\"", "'"), Arrays.asList("]", ")", "}", "”", "»", "«", "’", "\"", "'")), new HunspellRule(messages, this), new UppercaseSentenceStartRule(messages, this, Example.wrong("Esta casa é vella. <marker>foi</marker> construida en 1950."), Example.fixed("Esta casa é vella. <marker>Foi</marker> construida en 1950.")), new MultipleWhitespaceRule(messages, this), new LongSentenceRule(messages, 20, false), new LongSentenceRule(messages, 25, false), new LongSentenceRule(messages, 30, false), new LongSentenceRule(messages, 35, false), new LongSentenceRule(messages, 40, false), new LongSentenceRule(messages, 45, false), new LongSentenceRule(messages, 50, true), new LongSentenceRule(messages, 60, false), new SentenceWhitespaceRule(messages), new WhiteSpaceBeforeParagraphEnd(messages), new WhiteSpaceAtBeginOfParagraph(messages), new EmptyLineRule(messages), // Specific to Galician: new SimpleReplaceRule(messages), new CastWordsRule(messages), new GalicianRedundancyRule(messages), new GalicianWordinessRule(messages), new GalicianBarbarismsRule(messages), new GalicianWikipediaRule(messages) ); } @Override public int getPriorityForId(String id) { switch (id) { // case "FRAGMENT_TWO_ARTICLES": return 50; case "DEGREE_MINUTES_SECONDS": return 30; // case "INTERJECTIONS_PUNTUATION": return 20; // case "CONFUSION_POR": return 10; // case "HOMOPHONE_AS_CARD": return 5; // case "TODOS_FOLLOWED_BY_NOUN_PLURAL": return 3; // case "TODOS_FOLLOWED_BY_NOUN_SINGULAR": return 2; case "UNPAIRED_BRACKETS": return -5; // case "PROFANITY": return -6; case "GL_BARBARISM_REPLACE": return -10; case "GL_SIMPLE_REPLACE": return -11; case "GL_REDUNDANCY_REPLACE": return -12; case "GL_WORDINESS_REPLACE": return -13; // case "GL_CLICHE_REPLACE": return -17; // case "CHILDISH_LANGUAGE": return -25; // case "ARCHAISMS": return -26; // case "INFORMALITIES": return -27; // case "PUFFERY": return -30; // case "BIASED_OPINION_WORDS": return -31; // case "WEAK_WORDS": return -32; // case "PT_AGREEMENT_REPLACE": return -35; case "GL_WIKIPEDIA_COMMON_ERRORS":return -45; case "HUNSPELL_RULE": return -50; // case "NO_VERB": return -52; // case "CRASE_CONFUSION": return -55; // case "FINAL_STOPS": return -75; // case "T-V_DISTINCTION": return -100; // case "T-V_DISTINCTION_ALL": return -101; // case "REPEATED_WORDS": return -210; // case "REPEATED_WORDS_3X": return -211; case "TOO_LONG_SENTENCE_20": return -997; case "TOO_LONG_SENTENCE_25": return -998; case "TOO_LONG_SENTENCE_30": return -999; case "TOO_LONG_SENTENCE_35": return -1000; case "TOO_LONG_SENTENCE_40": return -1001; case "TOO_LONG_SENTENCE_45": return -1002; case "TOO_LONG_SENTENCE_50": return -1003; case "TOO_LONG_SENTENCE_60": return -1004; // case "CACOPHONY": return -2000; } return 0; } }
[gl] add rule priorities
languagetool-language-modules/gl/src/main/java/org/languagetool/language/Galician.java
[gl] add rule priorities
<ide><path>anguagetool-language-modules/gl/src/main/java/org/languagetool/language/Galician.java <ide> // case "FINAL_STOPS": return -75; <ide> // case "T-V_DISTINCTION": return -100; <ide> // case "T-V_DISTINCTION_ALL": return -101; <del> // case "REPEATED_WORDS": return -210; <del> // case "REPEATED_WORDS_3X": return -211; <add> case "REPEATED_WORDS": return -210; <add> case "REPEATED_WORDS_3X": return -211; <ide> case "TOO_LONG_SENTENCE_20": return -997; <ide> case "TOO_LONG_SENTENCE_25": return -998; <ide> case "TOO_LONG_SENTENCE_30": return -999;
JavaScript
mit
43dcbd4d6890c9c86245e7d4ce14980970198652
0
marian42/fishtank,marian42/fishtank,marian42/fishtank
var CONTAINERS = 27; var containerEditor = new Object(); var feeder = new Feeder(CONTAINERS); var feederView = new FeederView(feeder, "svgcontainers", "containerprototype", "indicator", 'target'); var serverStatus = new Status(); var logView = new LogView(); var eventView = new EventView(); var imageView = new ImageView(); var network = new Network(feeder, feederView, eventView, serverStatus, imageView); network.checkForUpdate(); var ledcolor = 'rgb(0,0,255)'; function explodeBinArray(value, length) { result = new Array(); for (var i = 0; i < length; i++) { result[i] = value % 2 == 1; value = Math.floor(value / 2); } return result; } Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; $(".dropdown-menu li a").click( function(event) { var index = $($(this)[0].parentNode.parentNode.children).index($(this)[0].parentNode); if ($(this)[0].parentNode.parentNode.parentNode.id == 'ddfoodtype') { if (index == 7) index = 0; else index++; containerEditor.food = index; if (index != 0) { $('#ddfoodtypecurrentimg')[0].src = 'img/food' + index + '.png'; $('#ddfoodtypecurrentimg')[0].style.display = 'inline'; $('#ddfoodtypecurrent')[0].innerHTML = ''; if (containerEditor.amount == 0) { containerEditor.amount = 1; $('#ddamountcurrent')[0].innerHTML = 1; } } else { $('#ddfoodtypecurrentimg')[0].style.display = 'none'; $('#ddfoodtypecurrent')[0].innerHTML = 'Empty'; containerEditor.amount = 0; $('#ddamountcurrent')[0].innerHTML = '0'; } if (containerEditor.food != -1 || containerEditor.amount != -1 || containerEditor.priority != -1) { $('#diveditcontainer').show() containerEditor.btnsenabled = true; } } if ($(this)[0].parentNode.parentNode.parentNode.id == 'ddamount') { var amounts = [0.1,0.2,0.33,0.5,0.66,1,1.5,2]; containerEditor.amount = amounts[index]; $('#ddamountcurrent')[0].innerHTML = amounts[index]; if (containerEditor.food != -1 || containerEditor.amount != -1 || containerEditor.priority != -1) { $('#diveditcontainer').show() containerEditor.btnsenabled = true; } } if ($(this)[0].parentNode.parentNode.parentNode.id == 'ddpriority') { containerEditor.priority = index; $('#ddprioritycurrent')[0].innerHTML = $(this)[0].innerHTML; if (containerEditor.food != -1 || containerEditor.amount != -1 || containerEditor.priority != -1) { $('#diveditcontainer').show() containerEditor.btnsenabled = true; } } if ($(this)[0].parentNode.parentNode.parentNode.id == 'ddeventtype') { eventEditor.type = index; $('#ddeventtypecurrent')[0].innerHTML = $(this)[0].innerHTML; $('#editeventfeed')[0].style.display = (index == 0 ? 'block' : 'none'); $('#editeventlight')[0].style.display = (index == 1 ? 'block' : 'none'); } if ($(this)[0].parentNode.parentNode.parentNode.id == 'ddledcolor') { ledcolor = $(this)[0].children[0].style.backgroundColor; $('#ledcolorpreview')[0].style.backgroundColor = ledcolor; } event.preventDefault(); }); $('#containerbtncancel').click(function() { if (!containerEditor.btnsenabled) return; feederView.updateSelection(); }); $('#containerbtnsubmit').click(function() { if (!containerEditor.btnsenabled) return; $('#containerbtnsubmitloading').show(); var containers = ''; for (var i = 0; i < feederView.size; i++) if (feederView.c[i].selected) containers += i + ','; $.ajax({ type: "POST", url: 'api/updatecontainers', data: "containers=" + containers + "&food=" + containerEditor.food + "&amount=" + containerEditor.amount + "&priority=" + containerEditor.priority, success: function(data) { $('#containerbtnsubmitloading').hide(); if (data == 'loginrequired') { alert('You need to be logged in to do this.'); return; } for (var i = 0; i < feederView.size; i++) if (feederView.c[i].selected) { if (containerEditor.food != -1) feeder.container[i].food = containerEditor.food; if (containerEditor.amount != -1) feeder.container[i].amount = containerEditor.amount; if (containerEditor.priority != -1) feeder.container[i].priority = containerEditor.priority; } feederView.updateSelection(); }, error: function(){ $('#containerbtnsubmitloading').hide(); } }); }); $('#btnmove').click(function(){ $("#containerloading").show(); $.ajax({ type: "POST", url: 'api/move', data: "to=" + feederView.getFirstSelectedIndex(), success: function(data) { if (data == 'loginrequired') alert('You need to be logged in to do this.'); $("#containerloading").hide(); }, error: function(){ $("#containerloading").hide(); } }); }); $('#btnfeedcontainer').click(function(){ $("#containerloading").show(); $.ajax({ type: "POST", url: 'api/dump', data: "to=" + feederView.getFirstSelectedIndex(), success: function(data) { if (data == 'loginrequired') alert('You need to be logged in to do this.'); $("#containerloading").hide(); }, error: function(){ $("#containerloading").hide(); } }); }); window.addEventListener("mouseup", function() {feederView.onMouseUp();}); function updateTimestamps() { logView.updateTimestamps(); eventView.updateTime(); serverStatus.updateTime(); setTimeout(updateTimestamps, 10000); } $(document).on("click",function () { if ($("#divlogin").is(":visible")){ $("#divlogin").fadeOut(200); } }); $('#btnlogin').on("click",function (event) { if (!$("#divlogin").is(":visible")){ $("#divlogin").fadeIn(200); event.stopPropagation(); if (!$('#navbartoggle').is(':hidden')) $('#navmain').collapse('hide'); $('#inputusername')[0].focus(); } return false; }); $('#btnlogout').on("click",function (event) { $.ajax({ type: "POST", url: 'api/logout', success: function(data) { serverStatus.rawdata.user = null; serverStatus.update() }, error: function(){ } }); return false; }); $('#divlogin').on("click",function (event) { event.stopPropagation(); }); $('#loginform').on('keypress',function(event) { if (event.keyCode == 13) { network.username = $('#inputusername').val(); network.password = $('#inputpassword').val(); $("#loggingin").show(); var username = $('#inputusername').val(); $.ajax({ type: "POST", url: 'api/login', data: "username=" + username + '&password=' + $('#inputpassword').val(), success: function(data) { if (data == 'ok') $("#divlogin").fadeOut(200); $('#inputpassword').val(''); $("#loggingin").hide(); serverStatus.rawdata.user = username; serverStatus.update() }, error: function(){ $("#loggingin").hide(); network.loggedin = false; } }); } }); $('#btnswitchlights').click(function(event) { $("#dashboardloading").show(); $.ajax({ type: "POST", url: 'api/switchlights', success: function(data) { if (data == 'loginrequired') alert('You need to be logged in to do this.'); $("#dashboardloading").hide(); }, error: function(){ $("#dashboardloading").hide(); } }); }); $('#btnflashled').click(function(event) { var parts = ledcolor.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); var val = parseInt(parts[3]) + parseInt(parts[2]) * 256 + parseInt(parts[1]) * 256 * 256; var color = val.toString(16).toUpperCase(); while (color.length < 6) color = '0' + color; $("#dashboardloading").show(); $.ajax({ type: "POST", url: 'api/flashled', data: 'color=' + color, success: function(data) { $("#dashboardloading").hide(); }, error: function(){ $("#dashboardloading").hide(); } }); }); $('#btncalibrate').click(function(event) { $("#containerloading").show(); $.ajax({ type: "POST", url: 'api/calibrate', success: function(data) { if (data == 'loginrequired') alert('You need to be logged in to do this.'); $("#containerloading").hide(); }, error: function(){ $("#containerloading").hide(); } }); }); var offset = 54; $('.nav-sidebar li a').click(function(event) { event.preventDefault(); $($(this).attr('href'))[0].scrollIntoView(); scrollBy(0, -offset); }); updateTimestamps();
js/fishtank.js
var CONTAINERS = 27; var containerEditor = new Object(); var feeder = new Feeder(CONTAINERS); var feederView = new FeederView(feeder, "svgcontainers", "containerprototype", "indicator", 'target'); var serverStatus = new Status(); var logView = new LogView(); var eventView = new EventView(); var imageView = new ImageView(); var network = new Network(feeder, feederView, eventView, serverStatus, imageView); network.checkForUpdate(); var ledcolor = 'rgb(0,0,255)'; function explodeBinArray(value, length) { result = new Array(); for (var i = 0; i < length; i++) { result[i] = value % 2 == 1; value = Math.floor(value / 2); } return result; } Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; $(".dropdown-menu li a").click( function(event) { var index = $($(this)[0].parentNode.parentNode.children).index($(this)[0].parentNode); if ($(this)[0].parentNode.parentNode.parentNode.id == 'ddfoodtype') { if (index == 7) index = 0; else index++; containerEditor.food = index; if (index != 0) { $('#ddfoodtypecurrentimg')[0].src = 'img/food' + index + '.png'; $('#ddfoodtypecurrentimg')[0].style.display = 'inline'; $('#ddfoodtypecurrent')[0].innerHTML = ''; if (containerEditor.amount == 0) { containerEditor.amount = 1; $('#ddamountcurrent')[0].innerHTML = 1; } } else { $('#ddfoodtypecurrentimg')[0].style.display = 'none'; $('#ddfoodtypecurrent')[0].innerHTML = 'Empty'; containerEditor.amount = 0; $('#ddamountcurrent')[0].innerHTML = '0'; } if (containerEditor.food != -1 || containerEditor.amount != -1 || containerEditor.priority != -1) { $('#diveditcontainer').show() containerEditor.btnsenabled = true; } } if ($(this)[0].parentNode.parentNode.parentNode.id == 'ddamount') { var amounts = [0.1,0.2,0.33,0.5,0.66,1,1.5,2]; containerEditor.amount = amounts[index]; $('#ddamountcurrent')[0].innerHTML = amounts[index]; if (containerEditor.food != -1 || containerEditor.amount != -1 || containerEditor.priority != -1) { $('#diveditcontainer').show() containerEditor.btnsenabled = true; } } if ($(this)[0].parentNode.parentNode.parentNode.id == 'ddpriority') { containerEditor.priority = index; $('#ddprioritycurrent')[0].innerHTML = $(this)[0].innerHTML; if (containerEditor.food != -1 || containerEditor.amount != -1 || containerEditor.priority != -1) { $('#diveditcontainer').show() containerEditor.btnsenabled = true; } } if ($(this)[0].parentNode.parentNode.parentNode.id == 'ddeventtype') { eventEditor.type = index; $('#ddeventtypecurrent')[0].innerHTML = $(this)[0].innerHTML; $('#editeventfeed')[0].style.display = (index == 0 ? 'block' : 'none'); $('#editeventlight')[0].style.display = (index == 1 ? 'block' : 'none'); } if ($(this)[0].parentNode.parentNode.parentNode.id == 'ddledcolor') { ledcolor = $(this)[0].children[0].style.backgroundColor; $('#ledcolorpreview')[0].style.backgroundColor = ledcolor; } event.preventDefault(); }); $('#containerbtncancel').click(function() { if (!containerEditor.btnsenabled) return; feederView.updateSelection(); }); $('#containerbtnsubmit').click(function() { if (!containerEditor.btnsenabled) return; $('#containerbtnsubmitloading').show(); var containers = ''; for (var i = 0; i < feederView.size; i++) if (feederView.c[i].selected) containers += i + ','; $.ajax({ type: "POST", url: network.server + 'api/updatecontainers', data: "containers=" + containers + "&food=" + containerEditor.food + "&amount=" + containerEditor.amount + "&priority=" + containerEditor.priority, success: function(data) { $('#containerbtnsubmitloading').hide(); if (data == 'loginrequired') { alert('You need to be logged in to do this.'); return; } for (var i = 0; i < feederView.size; i++) if (feederView.c[i].selected) { if (containerEditor.food != -1) feeder.container[i].food = containerEditor.food; if (containerEditor.amount != -1) feeder.container[i].amount = containerEditor.amount; if (containerEditor.priority != -1) feeder.container[i].priority = containerEditor.priority; } feederView.updateSelection(); }, error: function(){ $('#containerbtnsubmitloading').hide(); } }); }); $('#btnmove').click(function(){ $("#containerloading").show(); $.ajax({ type: "POST", url: network.server + 'api/move', data: "to=" + feederView.getFirstSelectedIndex(), success: function(data) { if (data == 'loginrequired') alert('You need to be logged in to do this.'); $("#containerloading").hide(); }, error: function(){ $("#containerloading").hide(); } }); }); $('#btnfeedcontainer').click(function(){ $("#containerloading").show(); $.ajax({ type: "POST", url: network.server + 'api/dump', data: "to=" + feederView.getFirstSelectedIndex(), success: function(data) { if (data == 'loginrequired') alert('You need to be logged in to do this.'); $("#containerloading").hide(); }, error: function(){ $("#containerloading").hide(); } }); }); window.addEventListener("mouseup", function() {feederView.onMouseUp();}); function updateTimestamps() { logView.updateTimestamps(); eventView.updateTime(); serverStatus.updateTime(); setTimeout(updateTimestamps, 10000); } $(document).on("click",function () { if ($("#divlogin").is(":visible")){ $("#divlogin").fadeOut(200); } }); $('#btnlogin').on("click",function (event) { if (!$("#divlogin").is(":visible")){ $("#divlogin").fadeIn(200); event.stopPropagation(); if (!$('#navbartoggle').is(':hidden')) $('#navmain').collapse('hide'); $('#inputusername')[0].focus(); } return false; }); $('#btnlogout').on("click",function (event) { $.ajax({ type: "POST", url: network.server + 'api/logout', success: function(data) { serverStatus.rawdata.user = null; serverStatus.update() }, error: function(){ } }); return false; }); $('#divlogin').on("click",function (event) { event.stopPropagation(); }); $('#loginform').on('keypress',function(event) { if (event.keyCode == 13) { network.username = $('#inputusername').val(); network.password = $('#inputpassword').val(); $("#loggingin").show(); var username = $('#inputusername').val(); $.ajax({ type: "POST", url: network.server + 'api/login', data: "username=" + username + '&password=' + $('#inputpassword').val(), success: function(data) { if (data == 'ok') $("#divlogin").fadeOut(200); $('#inputpassword').val(''); $("#loggingin").hide(); serverStatus.rawdata.user = username; serverStatus.update() }, error: function(){ $("#loggingin").hide(); network.loggedin = false; } }); } }); $('#btnswitchlights').click(function(event) { $("#dashboardloading").show(); $.ajax({ type: "POST", url: network.server + 'api/switchlights', success: function(data) { if (data == 'loginrequired') alert('You need to be logged in to do this.'); $("#dashboardloading").hide(); }, error: function(){ $("#dashboardloading").hide(); } }); }); $('#btnflashled').click(function(event) { var parts = ledcolor.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); var val = parseInt(parts[3]) + parseInt(parts[2]) * 256 + parseInt(parts[1]) * 256 * 256; var color = val.toString(16).toUpperCase(); while (color.length < 6) color = '0' + color; $("#dashboardloading").show(); $.ajax({ type: "POST", url: network.server + 'api/flashled', data: 'color=' + color, success: function(data) { $("#dashboardloading").hide(); }, error: function(){ $("#dashboardloading").hide(); } }); }); $('#btncalibrate').click(function(event) { $("#containerloading").show(); $.ajax({ type: "POST", url: network.server + 'api/calibrate', success: function(data) { if (data == 'loginrequired') alert('You need to be logged in to do this.'); $("#containerloading").hide(); }, error: function(){ $("#containerloading").hide(); } }); }); var offset = 54; $('.nav-sidebar li a').click(function(event) { event.preventDefault(); $($(this).attr('href'))[0].scrollIntoView(); scrollBy(0, -offset); }); updateTimestamps();
Remove absolute server address
js/fishtank.js
Remove absolute server address
<ide><path>s/fishtank.js <ide> containers += i + ','; <ide> $.ajax({ <ide> type: "POST", <del> url: network.server + 'api/updatecontainers', <add> url: 'api/updatecontainers', <ide> data: "containers=" + containers + "&food=" + containerEditor.food + "&amount=" + containerEditor.amount + "&priority=" + containerEditor.priority, <ide> success: function(data) { <ide> $('#containerbtnsubmitloading').hide(); <ide> $("#containerloading").show(); <ide> $.ajax({ <ide> type: "POST", <del> url: network.server + 'api/move', <add> url: 'api/move', <ide> data: "to=" + feederView.getFirstSelectedIndex(), <ide> success: function(data) { <ide> if (data == 'loginrequired') <ide> $("#containerloading").show(); <ide> $.ajax({ <ide> type: "POST", <del> url: network.server + 'api/dump', <add> url: 'api/dump', <ide> data: "to=" + feederView.getFirstSelectedIndex(), <ide> success: function(data) { <ide> if (data == 'loginrequired') <ide> $('#btnlogout').on("click",function (event) { <ide> $.ajax({ <ide> type: "POST", <del> url: network.server + 'api/logout', <add> url: 'api/logout', <ide> success: function(data) { <ide> serverStatus.rawdata.user = null; <ide> serverStatus.update() <ide> <ide> $.ajax({ <ide> type: "POST", <del> url: network.server + 'api/login', <add> url: 'api/login', <ide> data: "username=" + username + '&password=' + $('#inputpassword').val(), <ide> success: function(data) { <ide> if (data == 'ok') <ide> $("#dashboardloading").show(); <ide> $.ajax({ <ide> type: "POST", <del> url: network.server + 'api/switchlights', <add> url: 'api/switchlights', <ide> success: function(data) { <ide> if (data == 'loginrequired') <ide> alert('You need to be logged in to do this.'); <ide> $("#dashboardloading").show(); <ide> $.ajax({ <ide> type: "POST", <del> url: network.server + 'api/flashled', <add> url: 'api/flashled', <ide> data: 'color=' + color, <ide> success: function(data) { <ide> $("#dashboardloading").hide(); <ide> $("#containerloading").show(); <ide> $.ajax({ <ide> type: "POST", <del> url: network.server + 'api/calibrate', <add> url: 'api/calibrate', <ide> success: function(data) { <ide> if (data == 'loginrequired') <ide> alert('You need to be logged in to do this.');
Java
apache-2.0
29ea21902d7b85a960f27c26ead61909803fd315
0
argv-minus-one/fop,StrategyObject/fop,argv-minus-one/fop,argv-minus-one/fop,StrategyObject/fop,argv-minus-one/fop,StrategyObject/fop,StrategyObject/fop,StrategyObject/fop,argv-minus-one/fop
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.render.pdf; import java.util.LinkedList; import java.util.Locale; import java.util.Map; import javax.xml.XMLConstants; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; import org.apache.fop.accessibility.StructureTreeElement; import org.apache.fop.accessibility.StructureTreeEventHandler; import org.apache.fop.events.EventBroadcaster; import org.apache.fop.fo.extensions.ExtensionElementMapping; import org.apache.fop.fo.extensions.InternalElementMapping; import org.apache.fop.fo.pagination.Flow; import org.apache.fop.pdf.PDFFactory; import org.apache.fop.pdf.PDFParentTree; import org.apache.fop.pdf.PDFStructElem; import org.apache.fop.pdf.PDFStructTreeRoot; import org.apache.fop.pdf.StandardStructureAttributes.Table.Scope; import org.apache.fop.pdf.StandardStructureTypes; import org.apache.fop.pdf.StandardStructureTypes.Grouping; import org.apache.fop.pdf.StandardStructureTypes.Table; import org.apache.fop.pdf.StructureHierarchyMember; import org.apache.fop.pdf.StructureType; import org.apache.fop.util.LanguageTags; import org.apache.fop.util.XMLUtil; class PDFStructureTreeBuilder implements StructureTreeEventHandler { private static final String ROLE = "role"; private static final Map<String, StructureElementBuilder> BUILDERS = new java.util.HashMap<String, StructureElementBuilder>(); private static final StructureElementBuilder DEFAULT_BUILDER = new DefaultStructureElementBuilder(Grouping.NON_STRUCT); static { // Declarations and Pagination and Layout Formatting Objects StructureElementBuilder regionBuilder = new RegionBuilder(); addBuilder("root", StandardStructureTypes.Grouping.DOCUMENT); addBuilder("page-sequence", new PageSequenceBuilder()); addBuilder("static-content", regionBuilder); addBuilder("flow", regionBuilder); // Block-level Formatting Objects addBuilder("block", new LanguageHolderBuilder(StandardStructureTypes.Paragraphlike.P)); addBuilder("block-container", StandardStructureTypes.Grouping.DIV); // Inline-level Formatting Objects addBuilder("character", new LanguageHolderBuilder(StandardStructureTypes.InlineLevelStructure.SPAN)); addBuilder("external-graphic", new ImageBuilder()); addBuilder("instream-foreign-object", new ImageBuilder()); addBuilder("inline", StandardStructureTypes.InlineLevelStructure.SPAN); addBuilder("inline-container", StandardStructureTypes.Grouping.DIV); addBuilder("page-number", StandardStructureTypes.InlineLevelStructure.QUOTE); addBuilder("page-number-citation", StandardStructureTypes.InlineLevelStructure.QUOTE); addBuilder("page-number-citation-last", StandardStructureTypes.InlineLevelStructure.QUOTE); // Formatting Objects for Tables addBuilder("table-and-caption", StandardStructureTypes.Grouping.DIV); addBuilder("table", new TableBuilder()); addBuilder("table-caption", StandardStructureTypes.Grouping.CAPTION); addBuilder("table-header", StandardStructureTypes.Table.THEAD); addBuilder("table-footer", new TableFooterBuilder()); addBuilder("table-body", StandardStructureTypes.Table.TBODY); addBuilder("table-row", StandardStructureTypes.Table.TR); addBuilder("table-cell", new TableCellBuilder()); // Formatting Objects for Lists addBuilder("list-block", StandardStructureTypes.List.L); addBuilder("list-item", StandardStructureTypes.List.LI); addBuilder("list-item-body", StandardStructureTypes.List.LBODY); addBuilder("list-item-label", StandardStructureTypes.List.LBL); // Dynamic Effects: Link and Multi Formatting Objects addBuilder("basic-link", StandardStructureTypes.InlineLevelStructure.LINK); // Out-of-Line Formatting Objects addBuilder("float", StandardStructureTypes.Grouping.DIV); addBuilder("footnote", StandardStructureTypes.InlineLevelStructure.NOTE); addBuilder("footnote-body", StandardStructureTypes.Grouping.SECT); // Other Formatting Objects addBuilder("wrapper", StandardStructureTypes.InlineLevelStructure.SPAN); addBuilder("marker", StandardStructureTypes.Grouping.PRIVATE); addBuilder("retrieve-marker", new PlaceholderBuilder()); addBuilder("retrieve-table-marker", new PlaceholderBuilder()); addBuilder("#PCDATA", new PlaceholderBuilder()); } private static void addBuilder(String fo, StructureType structureType) { addBuilder(fo, new DefaultStructureElementBuilder(structureType)); } private static void addBuilder(String fo, StructureElementBuilder mapper) { BUILDERS.put(fo, mapper); } private interface StructureElementBuilder { PDFStructElem build(StructureHierarchyMember parent, Attributes attributes, PDFFactory pdfFactory, EventBroadcaster eventBroadcaster); } private static class DefaultStructureElementBuilder implements StructureElementBuilder { private final StructureType defaultStructureType; DefaultStructureElementBuilder(StructureType structureType) { this.defaultStructureType = structureType; } public final PDFStructElem build(StructureHierarchyMember parent, Attributes attributes, PDFFactory pdfFactory, EventBroadcaster eventBroadcaster) { String role = attributes.getValue(ROLE); StructureType structureType; if (role == null) { structureType = defaultStructureType; } else { structureType = StandardStructureTypes.get(role); if (structureType == null) { structureType = defaultStructureType; PDFEventProducer.Provider.get(eventBroadcaster).nonStandardStructureType(role, role, structureType.toString()); } } PDFStructElem structElem = createStructureElement(parent, structureType); setAttributes(structElem, attributes); addKidToParent(structElem, parent, attributes); registerStructureElement(structElem, pdfFactory, attributes); return structElem; } protected PDFStructElem createStructureElement(StructureHierarchyMember parent, StructureType structureType) { return new PDFStructElem(parent, structureType); } protected void setAttributes(PDFStructElem structElem, Attributes attributes) { } protected void addKidToParent(PDFStructElem kid, StructureHierarchyMember parent, Attributes attributes) { parent.addKid(kid); } protected void registerStructureElement(PDFStructElem structureElement, PDFFactory pdfFactory, Attributes attributes) { pdfFactory.getDocument().registerStructureElement(structureElement); } } private static class PageSequenceBuilder extends DefaultStructureElementBuilder { PageSequenceBuilder() { super(StandardStructureTypes.Grouping.PART); } @Override protected PDFStructElem createStructureElement(StructureHierarchyMember parent, StructureType structureType) { return new PageSequenceStructElem(parent, structureType); } } private static class RegionBuilder extends DefaultStructureElementBuilder { RegionBuilder() { super(StandardStructureTypes.Grouping.SECT); } @Override protected void addKidToParent(PDFStructElem kid, StructureHierarchyMember parent, Attributes attributes) { String flowName = attributes.getValue(Flow.FLOW_NAME); ((PageSequenceStructElem) parent).addContent(flowName, kid); } } private static class LanguageHolderBuilder extends DefaultStructureElementBuilder { LanguageHolderBuilder(StructureType structureType) { super(structureType); } @Override protected void setAttributes(PDFStructElem structElem, Attributes attributes) { String xmlLang = attributes.getValue(XMLConstants.XML_NS_URI, "lang"); if (xmlLang != null) { Locale locale = LanguageTags.toLocale(xmlLang); structElem.setLanguage(locale); } } } private static class ImageBuilder extends DefaultStructureElementBuilder { ImageBuilder() { super(StandardStructureTypes.Illustration.FIGURE); } @Override protected void setAttributes(PDFStructElem structElem, Attributes attributes) { String altTextNode = attributes.getValue(ExtensionElementMapping.URI, "alt-text"); if (altTextNode == null) { altTextNode = "No alternate text specified"; } structElem.put("Alt", altTextNode); } } private static class TableBuilder extends DefaultStructureElementBuilder { TableBuilder() { super(StandardStructureTypes.Table.TABLE); } @Override protected PDFStructElem createStructureElement(StructureHierarchyMember parent, StructureType structureType) { return new TableStructElem(parent, structureType); } } private static class TableFooterBuilder extends DefaultStructureElementBuilder { public TableFooterBuilder() { super(StandardStructureTypes.Table.TFOOT); } @Override protected void addKidToParent(PDFStructElem kid, StructureHierarchyMember parent, Attributes attributes) { ((TableStructElem) parent).addTableFooter(kid); } } private static class TableCellBuilder extends DefaultStructureElementBuilder { TableCellBuilder() { super(StandardStructureTypes.Table.TD); } @Override protected void registerStructureElement(PDFStructElem structureElement, PDFFactory pdfFactory, Attributes attributes) { if (structureElement.getStructureType() == Table.TH) { String scopeAttribute = attributes.getValue(InternalElementMapping.URI, InternalElementMapping.SCOPE); Scope scope = (scopeAttribute == null) ? Scope.COLUMN : Scope.valueOf(scopeAttribute.toUpperCase(Locale.ENGLISH)); pdfFactory.getDocument().registerStructureElement(structureElement, scope); } else { pdfFactory.getDocument().registerStructureElement(structureElement); } } @Override protected void setAttributes(PDFStructElem structElem, Attributes attributes) { String columnSpan = attributes.getValue("number-columns-spanned"); if (columnSpan != null) { structElem.setTableAttributeColSpan(Integer.parseInt(columnSpan)); } String rowSpan = attributes.getValue("number-rows-spanned"); if (rowSpan != null) { structElem.setTableAttributeRowSpan(Integer.parseInt(rowSpan)); } } } private static class PlaceholderBuilder implements StructureElementBuilder { public PDFStructElem build(StructureHierarchyMember parent, Attributes attributes, PDFFactory pdfFactory, EventBroadcaster eventBroadcaster) { PDFStructElem elem = new PDFStructElem.Placeholder(parent); parent.addKid(elem); return elem; } } private PDFFactory pdfFactory; private EventBroadcaster eventBroadcaster; private LinkedList<PDFStructElem> ancestors = new LinkedList<PDFStructElem>(); private PDFStructElem rootStructureElement; void setPdfFactory(PDFFactory pdfFactory) { this.pdfFactory = pdfFactory; } void setEventBroadcaster(EventBroadcaster eventBroadcaster) { this.eventBroadcaster = eventBroadcaster; } void setLogicalStructureHandler(PDFLogicalStructureHandler logicalStructureHandler) { createRootStructureElement(logicalStructureHandler); } private void createRootStructureElement(PDFLogicalStructureHandler logicalStructureHandler) { assert rootStructureElement == null; PDFParentTree parentTree = logicalStructureHandler.getParentTree(); PDFStructTreeRoot structTreeRoot = pdfFactory.getDocument().makeStructTreeRoot(parentTree); rootStructureElement = createStructureElement("root", structTreeRoot, new AttributesImpl(), pdfFactory, eventBroadcaster); } private static PDFStructElem createStructureElement(String name, StructureHierarchyMember parent, Attributes attributes, PDFFactory pdfFactory, EventBroadcaster eventBroadcaster) { StructureElementBuilder builder = BUILDERS.get(name); if (builder == null) { // TODO is a fallback really necessary? builder = DEFAULT_BUILDER; } return builder.build(parent, attributes, pdfFactory, eventBroadcaster); } public void startPageSequence(Locale language, String role) { ancestors = new LinkedList<PDFStructElem>(); AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute("", ROLE, ROLE, XMLUtil.CDATA, role); PDFStructElem structElem = createStructureElement("page-sequence", rootStructureElement, attributes, pdfFactory, eventBroadcaster); if (language != null) { structElem.setLanguage(language); } ancestors.add(structElem); } public void endPageSequence() { } public StructureTreeElement startNode(String name, Attributes attributes, StructureTreeElement parent) { if (!isPDFA1Safe(name)) { return null; } assert parent == null || parent instanceof PDFStructElem; PDFStructElem parentElem = parent == null ? ancestors.getFirst() : (PDFStructElem) parent; PDFStructElem structElem = createStructureElement(name, parentElem, attributes, pdfFactory, eventBroadcaster); ancestors.addFirst(structElem); return structElem; } public void endNode(String name) { if (isPDFA1Safe(name)) { ancestors.removeFirst(); } } private boolean isPDFA1Safe(String name) { return !(pdfFactory.getDocument().getProfile().getPDFAMode().isPart1() && (name.equals("table-body") || name.equals("table-header") || name.equals("table-footer"))); } public StructureTreeElement startImageNode(String name, Attributes attributes, StructureTreeElement parent) { return startNode(name, attributes, parent); } public StructureTreeElement startReferencedNode(String name, Attributes attributes, StructureTreeElement parent) { return startNode(name, attributes, parent); } }
src/java/org/apache/fop/render/pdf/PDFStructureTreeBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.render.pdf; import java.util.LinkedList; import java.util.Locale; import java.util.Map; import javax.xml.XMLConstants; import org.xml.sax.Attributes; import org.xml.sax.helpers.AttributesImpl; import org.apache.fop.accessibility.StructureTreeElement; import org.apache.fop.accessibility.StructureTreeEventHandler; import org.apache.fop.events.EventBroadcaster; import org.apache.fop.fo.extensions.ExtensionElementMapping; import org.apache.fop.fo.extensions.InternalElementMapping; import org.apache.fop.fo.pagination.Flow; import org.apache.fop.pdf.PDFFactory; import org.apache.fop.pdf.PDFParentTree; import org.apache.fop.pdf.PDFStructElem; import org.apache.fop.pdf.PDFStructTreeRoot; import org.apache.fop.pdf.StandardStructureAttributes.Table.Scope; import org.apache.fop.pdf.StandardStructureTypes; import org.apache.fop.pdf.StandardStructureTypes.Grouping; import org.apache.fop.pdf.StandardStructureTypes.Table; import org.apache.fop.pdf.StructureHierarchyMember; import org.apache.fop.pdf.StructureType; import org.apache.fop.util.LanguageTags; import org.apache.fop.util.XMLUtil; class PDFStructureTreeBuilder implements StructureTreeEventHandler { private static final String ROLE = "role"; private static final Map<String, StructureElementBuilder> BUILDERS = new java.util.HashMap<String, StructureElementBuilder>(); private static final StructureElementBuilder DEFAULT_BUILDER = new DefaultStructureElementBuilder(Grouping.NON_STRUCT); static { // Declarations and Pagination and Layout Formatting Objects StructureElementBuilder regionBuilder = new RegionBuilder(); addBuilder("root", StandardStructureTypes.Grouping.DOCUMENT); addBuilder("page-sequence", new PageSequenceBuilder()); addBuilder("static-content", regionBuilder); addBuilder("flow", regionBuilder); // Block-level Formatting Objects addBuilder("block", new LanguageHolderBuilder(StandardStructureTypes.Paragraphlike.P)); addBuilder("block-container", StandardStructureTypes.Grouping.DIV); // Inline-level Formatting Objects addBuilder("character", new LanguageHolderBuilder(StandardStructureTypes.InlineLevelStructure.SPAN)); addBuilder("external-graphic", new ImageBuilder()); addBuilder("instream-foreign-object", new ImageBuilder()); addBuilder("inline", StandardStructureTypes.InlineLevelStructure.SPAN); addBuilder("inline-container", StandardStructureTypes.Grouping.DIV); addBuilder("page-number", StandardStructureTypes.InlineLevelStructure.QUOTE); addBuilder("page-number-citation", StandardStructureTypes.InlineLevelStructure.QUOTE); addBuilder("page-number-citation-last", StandardStructureTypes.InlineLevelStructure.QUOTE); // Formatting Objects for Tables addBuilder("table-and-caption", StandardStructureTypes.Grouping.DIV); addBuilder("table", new TableBuilder()); addBuilder("table-caption", StandardStructureTypes.Grouping.CAPTION); addBuilder("table-header", StandardStructureTypes.Table.THEAD); addBuilder("table-footer", new TableFooterBuilder()); addBuilder("table-body", StandardStructureTypes.Table.TBODY); addBuilder("table-row", StandardStructureTypes.Table.TR); addBuilder("table-cell", new TableCellBuilder()); // Formatting Objects for Lists addBuilder("list-block", StandardStructureTypes.List.L); addBuilder("list-item", StandardStructureTypes.List.LI); addBuilder("list-item-body", StandardStructureTypes.List.LBODY); addBuilder("list-item-label", StandardStructureTypes.List.LBL); // Dynamic Effects: Link and Multi Formatting Objects addBuilder("basic-link", StandardStructureTypes.InlineLevelStructure.LINK); // Out-of-Line Formatting Objects addBuilder("float", StandardStructureTypes.Grouping.DIV); addBuilder("footnote", StandardStructureTypes.InlineLevelStructure.NOTE); addBuilder("footnote-body", StandardStructureTypes.Grouping.SECT); // Other Formatting Objects addBuilder("wrapper", StandardStructureTypes.InlineLevelStructure.SPAN); addBuilder("marker", StandardStructureTypes.Grouping.PRIVATE); addBuilder("retrieve-marker", new PlaceholderBuilder()); addBuilder("retrieve-table-marker", new PlaceholderBuilder()); addBuilder("#PCDATA", new PlaceholderBuilder()); } private static void addBuilder(String fo, StructureType structureType) { addBuilder(fo, new DefaultStructureElementBuilder(structureType)); } private static void addBuilder(String fo, StructureElementBuilder mapper) { BUILDERS.put(fo, mapper); } private interface StructureElementBuilder { PDFStructElem build(StructureHierarchyMember parent, Attributes attributes, PDFFactory pdfFactory, EventBroadcaster eventBroadcaster); } private static class DefaultStructureElementBuilder implements StructureElementBuilder { private final StructureType defaultStructureType; DefaultStructureElementBuilder(StructureType structureType) { this.defaultStructureType = structureType; } public final PDFStructElem build(StructureHierarchyMember parent, Attributes attributes, PDFFactory pdfFactory, EventBroadcaster eventBroadcaster) { String role = attributes.getValue(ROLE); StructureType structureType; if (role == null) { structureType = defaultStructureType; } else { structureType = StandardStructureTypes.get(role); if (structureType == null) { structureType = defaultStructureType; PDFEventProducer.Provider.get(eventBroadcaster).nonStandardStructureType(role, role, structureType.toString()); } } PDFStructElem structElem = createStructureElement(parent, structureType); setAttributes(structElem, attributes); addKidToParent(structElem, parent, attributes); registerStructureElement(structElem, pdfFactory, attributes); return structElem; } protected PDFStructElem createStructureElement(StructureHierarchyMember parent, StructureType structureType) { return new PDFStructElem(parent, structureType); } protected void setAttributes(PDFStructElem structElem, Attributes attributes) { } protected void addKidToParent(PDFStructElem kid, StructureHierarchyMember parent, Attributes attributes) { parent.addKid(kid); } protected void registerStructureElement(PDFStructElem structureElement, PDFFactory pdfFactory, Attributes attributes) { pdfFactory.getDocument().registerStructureElement(structureElement); } } private static class PageSequenceBuilder extends DefaultStructureElementBuilder { PageSequenceBuilder() { super(StandardStructureTypes.Grouping.PART); } @Override protected PDFStructElem createStructureElement(StructureHierarchyMember parent, StructureType structureType) { return new PageSequenceStructElem(parent, structureType); } } private static class RegionBuilder extends DefaultStructureElementBuilder { RegionBuilder() { super(StandardStructureTypes.Grouping.SECT); } @Override protected void addKidToParent(PDFStructElem kid, StructureHierarchyMember parent, Attributes attributes) { String flowName = attributes.getValue(Flow.FLOW_NAME); ((PageSequenceStructElem) parent).addContent(flowName, kid); } } private static class LanguageHolderBuilder extends DefaultStructureElementBuilder { LanguageHolderBuilder(StructureType structureType) { super(structureType); } @Override protected void setAttributes(PDFStructElem structElem, Attributes attributes) { String xmlLang = attributes.getValue(XMLConstants.XML_NS_URI, "lang"); if (xmlLang != null) { Locale locale = LanguageTags.toLocale(xmlLang); structElem.setLanguage(locale); } } } private static class ImageBuilder extends DefaultStructureElementBuilder { ImageBuilder() { super(StandardStructureTypes.Illustration.FIGURE); } @Override protected void setAttributes(PDFStructElem structElem, Attributes attributes) { String altTextNode = attributes.getValue(ExtensionElementMapping.URI, "alt-text"); if (altTextNode == null) { altTextNode = "No alternate text specified"; } structElem.put("Alt", altTextNode); } } private static class TableBuilder extends DefaultStructureElementBuilder { TableBuilder() { super(StandardStructureTypes.Table.TABLE); } @Override protected PDFStructElem createStructureElement(StructureHierarchyMember parent, StructureType structureType) { return new TableStructElem(parent, structureType); } } private static class TableFooterBuilder extends DefaultStructureElementBuilder { public TableFooterBuilder() { super(StandardStructureTypes.Table.TFOOT); } @Override protected void addKidToParent(PDFStructElem kid, StructureHierarchyMember parent, Attributes attributes) { ((TableStructElem) parent).addTableFooter(kid); } } private static class TableCellBuilder extends DefaultStructureElementBuilder { TableCellBuilder() { super(StandardStructureTypes.Table.TD); } @Override protected void registerStructureElement(PDFStructElem structureElement, PDFFactory pdfFactory, Attributes attributes) { if (structureElement.getStructureType() == Table.TH) { String scopeAttribute = attributes.getValue(InternalElementMapping.URI, InternalElementMapping.SCOPE); Scope scope = (scopeAttribute == null) ? Scope.COLUMN : Scope.valueOf(scopeAttribute.toUpperCase(Locale.ENGLISH)); pdfFactory.getDocument().registerStructureElement(structureElement, scope); } else { pdfFactory.getDocument().registerStructureElement(structureElement); } } @Override protected void setAttributes(PDFStructElem structElem, Attributes attributes) { String columnSpan = attributes.getValue("number-columns-spanned"); if (columnSpan != null) { structElem.setTableAttributeColSpan(Integer.parseInt(columnSpan)); } String rowSpan = attributes.getValue("number-rows-spanned"); if (rowSpan != null) { structElem.setTableAttributeRowSpan(Integer.parseInt(rowSpan)); } } } private static class PlaceholderBuilder implements StructureElementBuilder { public PDFStructElem build(StructureHierarchyMember parent, Attributes attributes, PDFFactory pdfFactory, EventBroadcaster eventBroadcaster) { PDFStructElem elem = new PDFStructElem.Placeholder(parent); parent.addKid(elem); return elem; } } private PDFFactory pdfFactory; private EventBroadcaster eventBroadcaster; private LinkedList<PDFStructElem> ancestors = new LinkedList<PDFStructElem>(); private PDFStructElem rootStructureElement; void setPdfFactory(PDFFactory pdfFactory) { this.pdfFactory = pdfFactory; } void setEventBroadcaster(EventBroadcaster eventBroadcaster) { this.eventBroadcaster = eventBroadcaster; } void setLogicalStructureHandler(PDFLogicalStructureHandler logicalStructureHandler) { createRootStructureElement(logicalStructureHandler); } private void createRootStructureElement(PDFLogicalStructureHandler logicalStructureHandler) { assert rootStructureElement == null; PDFParentTree parentTree = logicalStructureHandler.getParentTree(); PDFStructTreeRoot structTreeRoot = pdfFactory.getDocument().makeStructTreeRoot(parentTree); rootStructureElement = createStructureElement("root", structTreeRoot, new AttributesImpl(), pdfFactory, eventBroadcaster); } private static PDFStructElem createStructureElement(String name, StructureHierarchyMember parent, Attributes attributes, PDFFactory pdfFactory, EventBroadcaster eventBroadcaster) { StructureElementBuilder builder = BUILDERS.get(name); if (builder == null) { // TODO is a fallback really necessary? builder = DEFAULT_BUILDER; } return builder.build(parent, attributes, pdfFactory, eventBroadcaster); } public void startPageSequence(Locale language, String role) { ancestors = new LinkedList<PDFStructElem>(); AttributesImpl attributes = new AttributesImpl(); attributes.addAttribute("", ROLE, ROLE, XMLUtil.CDATA, role); PDFStructElem structElem = createStructureElement("page-sequence", rootStructureElement, attributes, pdfFactory, eventBroadcaster); if (language != null) { structElem.setLanguage(language); } ancestors.add(structElem); } public void endPageSequence() { } public StructureTreeElement startNode(String name, Attributes attributes, StructureTreeElement parent) { if (!isPDFA1Safe(name)) { return null; } assert parent == null || parent instanceof PDFStructElem; PDFStructElem parentElem = parent == null ? ancestors.getFirst() : (PDFStructElem) parent; PDFStructElem structElem = createStructureElement(name, parentElem, attributes, pdfFactory, eventBroadcaster); ancestors.addFirst(structElem); return structElem; } public void endNode(String name) { if (isPDFA1Safe(name)) { ancestors.removeFirst(); } } private boolean isPDFA1Safe(String name) { return !(pdfFactory.getDocument().getProfile().getPDFAMode().isPart1() && (name.equals("table-body") || name.equals("table-header") || name.equals("table-footer"))); } public StructureTreeElement startImageNode(String name, Attributes attributes, StructureTreeElement parent) { return startNode(name, attributes, parent); } public StructureTreeElement startReferencedNode(String name, Attributes attributes, StructureTreeElement parent) { return startNode(name, attributes, parent); } }
Fix checkstyle git-svn-id: 102839466c3b40dd9c7e25c0a1a6d26afc40150a@1619419 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/fop/render/pdf/PDFStructureTreeBuilder.java
Fix checkstyle
<ide><path>rc/java/org/apache/fop/render/pdf/PDFStructureTreeBuilder.java <ide> public StructureTreeElement startNode(String name, Attributes attributes, StructureTreeElement parent) { <ide> if (!isPDFA1Safe(name)) { <ide> return null; <del> } <del> assert parent == null || parent instanceof PDFStructElem; <add> } <add> assert parent == null || parent instanceof PDFStructElem; <ide> PDFStructElem parentElem = parent == null ? ancestors.getFirst() : (PDFStructElem) parent; <ide> PDFStructElem structElem = createStructureElement(name, parentElem, attributes, <ide> pdfFactory, eventBroadcaster);
Java
epl-1.0
6e03009883582c26a01d7ce5dbf340aaa365b909
0
rohitmohan96/ceylon-ide-eclipse,rohitmohan96/ceylon-ide-eclipse
package com.redhat.ceylon.eclipse.core.builder; import static com.redhat.ceylon.eclipse.util.Nodes.getIdentifyingNode; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.util.Locale; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import org.antlr.runtime.Token; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisError; import com.redhat.ceylon.compiler.typechecker.tree.AnalysisMessage; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.UnexpectedError; //This is bullshit. The IDE should have a nice way of converting //compilation units into objects that can be shown in the problems //view, and even a nice way of converting errors in nodes in the //typechecker into errors that can be shown in the problems view. //Right now I'm using this for the js compiler errors but I expect //to see other people wanting this and probably implementing their own //solution again. public class CeylonCompilationError implements Diagnostic<JavaFileObject> { private final AnalysisMessage err; private final IProject project; private final JavaFileObject jf; private final IFile file; public CeylonCompilationError(IProject proj, AnalysisMessage error) { err = error; this.project = proj; file = project.getFile(err.getTreeNode().getUnit().getFullPath()); jf = new JavaFileObject() { @Override public URI toUri() { try { return new URI(file.getFullPath().toString()); } catch (URISyntaxException e) { e.printStackTrace(); } return null; } @Override public Writer openWriter() throws IOException { return null; } @Override public Reader openReader(boolean ignoreEncodingErrors) throws IOException { return null; } @Override public OutputStream openOutputStream() throws IOException { return null; } @Override public InputStream openInputStream() throws IOException { return null; } @Override public String getName() { return file.getLocation().toOSString(); } @Override public long getLastModified() { return file.getModificationStamp(); } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return null; } @Override public boolean delete() { return false; } @Override public boolean isNameCompatible(String simpleName, Kind kind) { return false; } @Override public NestingKind getNestingKind() { return NestingKind.TOP_LEVEL; } @Override public Kind getKind() { return Kind.SOURCE; } @Override public Modifier getAccessLevel() { return Modifier.FINAL; } }; } @Override public javax.tools.Diagnostic.Kind getKind() { return (err instanceof AnalysisError || err instanceof UnexpectedError) ? Diagnostic.Kind.ERROR : Diagnostic.Kind.WARNING; } @Override public JavaFileObject getSource() { return jf; } @Override public long getPosition() { return getStartPosition(); } @Override public long getStartPosition() { int startOffset = 0; Node errorNode = getIdentifyingNode(err.getTreeNode()); if (errorNode == null) { errorNode = err.getTreeNode(); } Token token = errorNode.getToken(); if (token!=null) { startOffset = errorNode.getStartIndex(); } return startOffset; } @Override public long getEndPosition() { int endOffset = 0; Node errorNode = getIdentifyingNode(err.getTreeNode()); if (errorNode == null) { errorNode = err.getTreeNode(); } Token token = errorNode.getToken(); if (token!=null) { endOffset = errorNode.getEndIndex(); } return endOffset - 1; } @Override public long getLineNumber() { int line = err.getLine(); Node node = err.getTreeNode(); Node errorNode = getIdentifyingNode(node); if (errorNode == null) { errorNode = node; } Token token = errorNode.getToken(); if (token!=null) { line = token.getLine(); } return line; } @Override public long getColumnNumber() { int startCol = 0; Node node = err.getTreeNode(); Node errorNode = getIdentifyingNode(node); if (errorNode == null) { errorNode = node; } Token token = errorNode.getToken(); if (token!=null) { startCol = token.getCharPositionInLine(); } return startCol; } @Override public String getCode() { return String.valueOf(err.getCode()); } @Override public String getMessage(Locale locale) { return err.getMessage(); } }
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/builder/CeylonCompilationError.java
package com.redhat.ceylon.eclipse.core.builder; import static com.redhat.ceylon.eclipse.util.Nodes.getIdentifyingNode; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.util.Locale; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import javax.tools.Diagnostic; import javax.tools.JavaFileObject; import org.antlr.runtime.Token; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import com.redhat.ceylon.compiler.typechecker.analyzer.AnalysisError; import com.redhat.ceylon.compiler.typechecker.tree.AnalysisMessage; import com.redhat.ceylon.compiler.typechecker.tree.Node; import com.redhat.ceylon.compiler.typechecker.tree.UnexpectedError; //This is bullshit. The IDE should have a nice way of converting //compilation units into objects that can be shown in the problems //view, and even a nice way of converting errors in nodes in the //typechecker into errors that can be shown in the problems view. //Right now I'm using this for the js compiler errors but I expect //to see other people wanting this and probably implementing their own //solution again. public class CeylonCompilationError implements Diagnostic<JavaFileObject> { private final AnalysisMessage err; private final IProject project; private final JavaFileObject jf; private final IFile file; public CeylonCompilationError(IProject proj, AnalysisMessage error) { err = error; this.project = proj; file = project.getFile(err.getTreeNode().getUnit().getFullPath()); jf = new JavaFileObject() { @Override public URI toUri() { try { return new URI(file.getFullPath().toString()); } catch (URISyntaxException e) { e.printStackTrace(); } return null; } @Override public Writer openWriter() throws IOException { return null; } @Override public Reader openReader(boolean ignoreEncodingErrors) throws IOException { return null; } @Override public OutputStream openOutputStream() throws IOException { return null; } @Override public InputStream openInputStream() throws IOException { return null; } @Override public String getName() { return file.getLocation().toOSString(); } @Override public long getLastModified() { return file.getModificationStamp(); } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException { return null; } @Override public boolean delete() { return false; } @Override public boolean isNameCompatible(String simpleName, Kind kind) { return false; } @Override public NestingKind getNestingKind() { return NestingKind.TOP_LEVEL; } @Override public Kind getKind() { return Kind.SOURCE; } @Override public Modifier getAccessLevel() { return Modifier.FINAL; } }; } @Override public javax.tools.Diagnostic.Kind getKind() { return (err instanceof AnalysisError || err instanceof UnexpectedError) ? Diagnostic.Kind.ERROR : Diagnostic.Kind.WARNING; } @Override public JavaFileObject getSource() { return jf; } @Override public long getPosition() { return getStartPosition(); } @Override public long getStartPosition() { int startOffset = 0; Node errorNode = getIdentifyingNode(err.getTreeNode()); if (errorNode == null) { errorNode = err.getTreeNode(); } Token token = errorNode.getToken(); if (token!=null) { startOffset = errorNode.getStartIndex(); } return startOffset; } @Override public long getEndPosition() { int endOffset = 0; Node errorNode = getIdentifyingNode(err.getTreeNode()); if (errorNode == null) { errorNode = err.getTreeNode(); } Token token = errorNode.getToken(); if (token!=null) { endOffset = errorNode.getEndIndex(); } return endOffset; } @Override public long getLineNumber() { int line = err.getLine(); Node node = err.getTreeNode(); Node errorNode = getIdentifyingNode(node); if (errorNode == null) { errorNode = node; } Token token = errorNode.getToken(); if (token!=null) { line = token.getLine(); } return line; } @Override public long getColumnNumber() { int startCol = 0; Node node = err.getTreeNode(); Node errorNode = getIdentifyingNode(node); if (errorNode == null) { errorNode = node; } Token token = errorNode.getToken(); if (token!=null) { startCol = token.getCharPositionInLine(); } return startCol; } @Override public String getCode() { return String.valueOf(err.getCode()); } @Override public String getMessage(Locale locale) { return err.getMessage(); } }
fix error span for JS backend error
plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/builder/CeylonCompilationError.java
fix error span for JS backend error
<ide><path>lugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/builder/CeylonCompilationError.java <ide> if (token!=null) { <ide> endOffset = errorNode.getEndIndex(); <ide> } <del> return endOffset; <add> return endOffset - 1; <ide> } <ide> <ide> @Override
Java
apache-2.0
4d6dee362a9ea772352fa988eba70bd2f89876f9
0
binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language,taverna-incubator/incubator-taverna-language,binfalse/incubator-taverna-language,binfalse/incubator-taverna-language,taverna-incubator/incubator-taverna-language
package uk.org.taverna.scufl2.api.core; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import uk.org.taverna.scufl2.api.annotation.Revision; import uk.org.taverna.scufl2.api.common.AbstractNamedChild; import uk.org.taverna.scufl2.api.common.Child; import uk.org.taverna.scufl2.api.common.NamedSet; import uk.org.taverna.scufl2.api.common.Ported; import uk.org.taverna.scufl2.api.common.Visitor; import uk.org.taverna.scufl2.api.common.WorkflowBean; import uk.org.taverna.scufl2.api.container.WorkflowBundle; import uk.org.taverna.scufl2.api.port.InputWorkflowPort; import uk.org.taverna.scufl2.api.port.OutputWorkflowPort; /** * A <code>Workflow</code> is a set of {@link Processor}s and {@link DataLink}s * between the <code>Processor</code>s. <code>Workflow</code>s may also have * input and output ports. * * @author Alan R Williams */ public class Workflow extends AbstractNamedChild implements Child<WorkflowBundle>, Ported { public static final URI WORKFLOW_ROOT = URI .create("http://ns.taverna.org.uk/2010/workflow/"); public static URI generateIdentifier() { return WORKFLOW_ROOT.resolve(UUID.randomUUID().toString() + "/"); } private final TreeSet<DataLink> dataLinks = new TreeSet<DataLink>(); private final TreeSet<ControlLink> controlLinks = new TreeSet<ControlLink>(); private final NamedSet<InputWorkflowPort> inputPorts = new NamedSet<InputWorkflowPort>(); private final NamedSet<OutputWorkflowPort> outputPorts = new NamedSet<OutputWorkflowPort>(); private final NamedSet<Processor> processors = new NamedSet<Processor>(); private WorkflowBundle parent; private Revision currentRevision; /** * Constructs a <code>Workflow</code> with a name based on a random UUID. */ public Workflow() { newRevision(); String workflowId = WORKFLOW_ROOT.relativize(getWorkflowIdentifier()) .toASCIIString(); setName("wf-" + workflowId); } @Override public boolean accept(Visitor visitor) { if (visitor.visitEnter(this)) { List<Iterable<? extends WorkflowBean>> children = new ArrayList<Iterable<? extends WorkflowBean>>(); children.add(getInputPorts()); children.add(getOutputPorts()); children.add(getProcessors()); children.add(getDataLinks()); children.add(getControlLinks()); children.add(Collections.singleton(getCurrentRevision())); outer: for (Iterable<? extends WorkflowBean> it : children) { for (WorkflowBean bean : it) { if (!bean.accept(visitor)) { break outer; } } } } return visitor.visitLeave(this); } /** * Returns the <code>ControlLink</code>s. * * If there are no <code>ControlLink</code>s an empty set is returned. * * @return the <code>ControlLink</code>s */ public Set<ControlLink> getControlLinks() { return controlLinks; } public Revision getCurrentRevision() { return currentRevision; } /** * Returns the <code>DataLink</code>s. * * If there are no <code>DataLink</code>s an empty set is returned. * * @return the <code>DataLink</code>s. */ public Set<DataLink> getDataLinks() { return dataLinks; } /** * Returns the <code>InputWorkflowPort</code>s. * * If there are no <code>InputWorkflowPort</code>s an empty set is returned. * * @return the <code>InputWorkflowPort</code>s. */ @Override public NamedSet<InputWorkflowPort> getInputPorts() { return inputPorts; } /** * Returns the <code>OutputWorkflowPort</code>s. * * If there are no <code>OutputWorkflowPort</code>s an empty set is * returned. * * @return the <code>OutputWorkflowPort</code>s. */ @Override public NamedSet<OutputWorkflowPort> getOutputPorts() { return outputPorts; } @Override public WorkflowBundle getParent() { return parent; } /** * Returns the <code>Processor</code>s. * * If there are no <code>Processor</code>s an empty set is returned. * * @return the <code>Processor</code>s. */ public NamedSet<Processor> getProcessors() { return processors; } /** * Returns the workflow identifier. * <p> * The the default identifier is {@value #WORKFLOW_ROOT} plus a random UUID. * * @see {@link #setWorkflowIdentifier(URI)} * * @return the workflow identifier */ public URI getWorkflowIdentifier() { if (getCurrentRevision() == null) { return null; } return getCurrentRevision().getResourceURI(); } /** * Set the <code>ControlLink</code>s to be the contents of the specified * set. * <p> * <code>ControlLink</code>s can be added by using * {@link #getControlLinks()}.add(controlLink). * * @param controlLinks * the <code>ControlLink</code>s. <strong>Must not</strong> be * null */ public void setControlLinks(Set<ControlLink> controlLinks) { this.controlLinks.clear(); this.controlLinks.addAll(controlLinks); } public void setCurrentRevision(Revision currentRevision) { this.currentRevision = currentRevision; if (currentRevision == null) { newRevision(); } } /** * Set the <code>DataLink</code>s to be the contents of the specified set. * <p> * <code>DataLink</code>s can be added by using {@link #getDataLinks()} * .add(dataLink). * * @param dataLinks * the <code>DataLink</code>s. <strong>Must not</strong> be null */ public void setDataLinks(Set<DataLink> dataLinks) { dataLinks.clear(); dataLinks.addAll(dataLinks); } /** * Set the <code>InputWorkflowPort</code>s to be the contents of the * specified set. * <p> * <code>InputWorkflowPort</code>s can be added by using * {@link #getInputWorkflowPorts()}.add(inputPort). * * @param inputPorts * the <code>InputWorkflowPort</code>s. <strong>Must not</strong> * be null */ public void setInputPorts(Set<InputWorkflowPort> inputPorts) { this.inputPorts.clear(); for (InputWorkflowPort inputPort : inputPorts) { inputPort.setParent(this); } } /** * Set the <code>OutputWorkflowPort</code>s to be the contents of the * specified set. * <p> * <code>OutputWorkflowPort</code>s can be added by using * {@link #getOutputWorkflowPorts()}.add(outputPort). * * @param outputPorts * the <code>OutputWorkflowPort</code>s. <strong>Must * not</strong> be null */ public void setOutputPorts(Set<OutputWorkflowPort> outputPorts) { this.outputPorts.clear(); for (OutputWorkflowPort outputPort : outputPorts) { outputPort.setParent(this); } } @Override public void setParent(WorkflowBundle parent) { if (this.parent != null && this.parent != parent) { this.parent.getWorkflows().remove(this); } this.parent = parent; if (parent != null) { parent.getWorkflows().add(this); } } /** * Set the <code>Processor</code>s to be the contents of the specified set. * <p> * <code>Processor</code>s can be added by using {@link #getProcessors()} * .add(processor). * * @param processors * the <code>Processor</code>s. <strong>Must not</strong> be null */ public void setProcessors(Set<Processor> processors) { this.processors.clear(); for (Processor processor : processors) { processor.setParent(this); } } /** * Set the workflow identifier. * <p> * This will delete any previous revisions in getRevision * * @param workflowIdentifier * the workflow identifier */ public void setWorkflowIdentifier(URI workflowIdentifier) { setCurrentRevision(new Revision(workflowIdentifier)); } @Override public String toString() { final int maxLen = 6; return "Workflow [getName()=" + getName() + ", getDatalinks()=" + (getDataLinks() != null ? toString(getDataLinks(), maxLen) : null) + ", getInputPorts()=" + (getInputPorts() != null ? toString(getInputPorts(), maxLen) : null) + ", getOutputPorts()=" + (getOutputPorts() != null ? toString(getOutputPorts(), maxLen) : null) + ", getProcessors()=" + (getProcessors() != null ? toString(getProcessors(), maxLen) : null) + "]"; } /** * Updates the workflow identifier. * <p> * The {@link #getCurrentRevision()} will be replaced using using * {@link #newRevision()}. * */ public void updateWorkflowIdentifier() { newRevision(); } private String toString(Collection<?> collection, int maxLen) { StringBuilder builder = new StringBuilder(); builder.append("["); int i = 0; for (Iterator<?> iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) { if (i > 0) { builder.append(", "); } builder.append(iterator.next()); } builder.append("]"); return builder.toString(); } /** * Make a new Revision to mark structural changes to this {@link Workflow}. * <p> * {@link #getWorkflowIdentifier()} will match the identifier of the new * {@link #getCurrentRevision()}. The new revision will include the previous * revision as {@link Revision#getPreviousRevision()} and * {@link Revision#getCreated()} on the new revision will match the current * {@link GregorianCalendar}. * </p> * * @return The new {@link #getCurrentRevision()}, for setting any * further details. */ public Revision newRevision() { return newRevision(null); } /** * Make a new Revision to mark structural changes to this workflow * with the given identifier. * <p> * {@link #getWorkflowIdentifier()} will match the new identifier. The new * {@link #getCurrentRevision()} will include the previous revision as * {@link Revision#getPreviousRevision()}. * <p> * Note, unlike the convenience method {@link #newRevision()} this method * will not update {@link Revision#getCreated()}. * </p> * * @param revisionIdentifier * The new workflow identifier * @return The new {@link #getCurrentRevision()}, for setting any further * details. */ public Revision newRevision(URI revisionIdentifier) { GregorianCalendar created = null; if (revisionIdentifier == null) { revisionIdentifier = generateIdentifier(); created = new GregorianCalendar(); } Revision newRevision = new Revision(revisionIdentifier, getCurrentRevision()); newRevision.setCreated(created); setCurrentRevision(newRevision); return newRevision; } }
scufl2-api/src/main/java/uk/org/taverna/scufl2/api/core/Workflow.java
package uk.org.taverna.scufl2.api.core; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.UUID; import uk.org.taverna.scufl2.api.annotation.Revision; import uk.org.taverna.scufl2.api.common.AbstractNamedChild; import uk.org.taverna.scufl2.api.common.Child; import uk.org.taverna.scufl2.api.common.NamedSet; import uk.org.taverna.scufl2.api.common.Ported; import uk.org.taverna.scufl2.api.common.Visitor; import uk.org.taverna.scufl2.api.common.WorkflowBean; import uk.org.taverna.scufl2.api.container.WorkflowBundle; import uk.org.taverna.scufl2.api.port.InputWorkflowPort; import uk.org.taverna.scufl2.api.port.OutputWorkflowPort; /** * A <code>Workflow</code> is a set of {@link Processor}s and {@link DataLink}s * between the <code>Processor</code>s. <code>Workflow</code>s may also have * input and output ports. * * @author Alan R Williams */ public class Workflow extends AbstractNamedChild implements Child<WorkflowBundle>, Ported { public static final URI WORKFLOW_ROOT = URI .create("http://ns.taverna.org.uk/2010/workflow/"); public static URI generateIdentifier() { return WORKFLOW_ROOT.resolve(UUID.randomUUID().toString() + "/"); } private final TreeSet<DataLink> dataLinks = new TreeSet<DataLink>(); private final TreeSet<ControlLink> controlLinks = new TreeSet<ControlLink>(); private final NamedSet<InputWorkflowPort> inputPorts = new NamedSet<InputWorkflowPort>(); private final NamedSet<OutputWorkflowPort> outputPorts = new NamedSet<OutputWorkflowPort>(); private final NamedSet<Processor> processors = new NamedSet<Processor>(); private WorkflowBundle parent; private Revision currentRevision; public Revision getCurrentRevision() { return currentRevision; } public void setCurrentRevision(Revision currentRevision) { this.currentRevision = currentRevision; if (currentRevision == null) { newRevision(); } } /** * Constructs a <code>Workflow</code> with a name based on a random UUID. */ public Workflow() { newRevision(); String workflowId = WORKFLOW_ROOT.relativize(getWorkflowIdentifier()) .toASCIIString(); setName("wf-" + workflowId); } @Override public boolean accept(Visitor visitor) { if (visitor.visitEnter(this)) { List<Iterable<? extends WorkflowBean>> children = new ArrayList<Iterable<? extends WorkflowBean>>(); children.add(getInputPorts()); children.add(getOutputPorts()); children.add(getProcessors()); children.add(getDataLinks()); children.add(getControlLinks()); children.add(Collections.singleton(getCurrentRevision())); outer: for (Iterable<? extends WorkflowBean> it : children) { for (WorkflowBean bean : it) { if (!bean.accept(visitor)) { break outer; } } } } return visitor.visitLeave(this); } /** * Returns the <code>ControlLink</code>s. * * If there are no <code>ControlLink</code>s an empty set is returned. * * @return the <code>ControlLink</code>s */ public Set<ControlLink> getControlLinks() { return controlLinks; } /** * Returns the <code>DataLink</code>s. * * If there are no <code>DataLink</code>s an empty set is returned. * * @return the <code>DataLink</code>s. */ public Set<DataLink> getDataLinks() { return dataLinks; } /** * Returns the <code>InputWorkflowPort</code>s. * * If there are no <code>InputWorkflowPort</code>s an empty set is returned. * * @return the <code>InputWorkflowPort</code>s. */ @Override public NamedSet<InputWorkflowPort> getInputPorts() { return inputPorts; } /** * Returns the <code>OutputWorkflowPort</code>s. * * If there are no <code>OutputWorkflowPort</code>s an empty set is * returned. * * @return the <code>OutputWorkflowPort</code>s. */ @Override public NamedSet<OutputWorkflowPort> getOutputPorts() { return outputPorts; } @Override public WorkflowBundle getParent() { return parent; } /** * Returns the <code>Processor</code>s. * * If there are no <code>Processor</code>s an empty set is returned. * * @return the <code>Processor</code>s. */ public NamedSet<Processor> getProcessors() { return processors; } /** * Returns the workflow identifier. * <p> * The the default identifier is {@value #WORKFLOW_ROOT} plus a random UUID. * * @see {@link #setWorkflowIdentifier(URI)} * * @return the workflow identifier */ public URI getWorkflowIdentifier() { return getCurrentRevision().getResourceURI(); } /** * Set the <code>ControlLink</code>s to be the contents of the specified * set. * <p> * <code>ControlLink</code>s can be added by using * {@link #getControlLinks()}.add(controlLink). * * @param controlLinks * the <code>ControlLink</code>s. <strong>Must not</strong> be * null */ public void setControlLinks(Set<ControlLink> controlLinks) { this.controlLinks.clear(); this.controlLinks.addAll(controlLinks); } /** * Set the <code>DataLink</code>s to be the contents of the specified set. * <p> * <code>DataLink</code>s can be added by using {@link #getDataLinks()} * .add(dataLink). * * @param dataLinks * the <code>DataLink</code>s. <strong>Must not</strong> be null */ public void setDataLinks(Set<DataLink> dataLinks) { dataLinks.clear(); dataLinks.addAll(dataLinks); } /** * Set the <code>InputWorkflowPort</code>s to be the contents of the * specified set. * <p> * <code>InputWorkflowPort</code>s can be added by using * {@link #getInputWorkflowPorts()}.add(inputPort). * * @param inputPorts * the <code>InputWorkflowPort</code>s. <strong>Must not</strong> * be null */ public void setInputPorts(Set<InputWorkflowPort> inputPorts) { this.inputPorts.clear(); for (InputWorkflowPort inputPort : inputPorts) { inputPort.setParent(this); } } /** * Set the <code>OutputWorkflowPort</code>s to be the contents of the * specified set. * <p> * <code>OutputWorkflowPort</code>s can be added by using * {@link #getOutputWorkflowPorts()}.add(outputPort). * * @param outputPorts * the <code>OutputWorkflowPort</code>s. <strong>Must * not</strong> be null */ public void setOutputPorts(Set<OutputWorkflowPort> outputPorts) { this.outputPorts.clear(); for (OutputWorkflowPort outputPort : outputPorts) { outputPort.setParent(this); } } @Override public void setParent(WorkflowBundle parent) { if (this.parent != null && this.parent != parent) { this.parent.getWorkflows().remove(this); } this.parent = parent; if (parent != null) { parent.getWorkflows().add(this); } } /** * Set the <code>Processor</code>s to be the contents of the specified set. * <p> * <code>Processor</code>s can be added by using {@link #getProcessors()} * .add(processor). * * @param processors * the <code>Processor</code>s. <strong>Must not</strong> be null */ public void setProcessors(Set<Processor> processors) { this.processors.clear(); for (Processor processor : processors) { processor.setParent(this); } } /** * Set the workflow identifier. * <p> * This will delete any previous revisions in getRevision * * @param workflowIdentifier * the workflow identifier */ public void setWorkflowIdentifier(URI workflowIdentifier) { setCurrentRevision(new Revision(workflowIdentifier)); } @Override public String toString() { final int maxLen = 6; return "Workflow [getName()=" + getName() + ", getDatalinks()=" + (getDataLinks() != null ? toString(getDataLinks(), maxLen) : null) + ", getInputPorts()=" + (getInputPorts() != null ? toString(getInputPorts(), maxLen) : null) + ", getOutputPorts()=" + (getOutputPorts() != null ? toString(getOutputPorts(), maxLen) : null) + ", getProcessors()=" + (getProcessors() != null ? toString(getProcessors(), maxLen) : null) + "]"; } /** * Updates the workflow identifier. * <p> * The {@link #getCurrentRevision()} will be replaced using using * {@link #newRevision()}. * */ public void updateWorkflowIdentifier() { newRevision(); } private String toString(Collection<?> collection, int maxLen) { StringBuilder builder = new StringBuilder(); builder.append("["); int i = 0; for (Iterator<?> iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) { if (i > 0) { builder.append(", "); } builder.append(iterator.next()); } builder.append("]"); return builder.toString(); } /** * Make a new Revision to mark structural changes to this {@link Workflow}. * <p> * {@link #getWorkflowIdentifier()} will match the identifier of the new * {@link #getCurrentRevision()}. The new revision will include the previous * revision as {@link Revision#getPreviousRevision()} and * {@link Revision#getCreated()} on the new revision will match the current * {@link GregorianCalendar}. * </p> * * @return The new {@link #getCurrentRevision()}, for setting any * further details. */ public Revision newRevision() { return newRevision(null); } /** * Make a new Revision to mark structural changes to this workflow * with the given identifier. * <p> * {@link #getWorkflowIdentifier()} will match the new identifier. The new * {@link #getCurrentRevision()} will include the previous revision as * {@link Revision#getPreviousRevision()}. * <p> * Note, unlike the convenience method {@link #newRevision()} this method * will not update {@link Revision#getCreated()}. * </p> * * @param revisionIdentifier * The new workflow identifier * @return The new {@link #getCurrentRevision()}, for setting any further * details. */ public Revision newRevision(URI revisionIdentifier) { GregorianCalendar created = null; if (revisionIdentifier == null) { revisionIdentifier = generateIdentifier(); created = new GregorianCalendar(); } Revision newRevision = new Revision(revisionIdentifier, getCurrentRevision()); newRevision.setCreated(created); setCurrentRevision(newRevision); return newRevision; } }
Double-check for null revision (as DummyWorkflow in scufl2-validation-correctness does that)
scufl2-api/src/main/java/uk/org/taverna/scufl2/api/core/Workflow.java
Double-check for null revision
<ide><path>cufl2-api/src/main/java/uk/org/taverna/scufl2/api/core/Workflow.java <ide> private WorkflowBundle parent; <ide> private Revision currentRevision; <ide> <del> public Revision getCurrentRevision() { <del> return currentRevision; <del> } <del> <del> public void setCurrentRevision(Revision currentRevision) { <del> this.currentRevision = currentRevision; <del> if (currentRevision == null) { <del> newRevision(); <del> } <del> } <ide> <ide> /** <ide> * Constructs a <code>Workflow</code> with a name based on a random UUID. <ide> public Set<ControlLink> getControlLinks() { <ide> return controlLinks; <ide> } <add> <add> <add> public Revision getCurrentRevision() { <add> return currentRevision; <add> } <add> <ide> <ide> /** <ide> * Returns the <code>DataLink</code>s. <ide> * @return the workflow identifier <ide> */ <ide> public URI getWorkflowIdentifier() { <add> if (getCurrentRevision() == null) { <add> return null; <add> } <ide> return getCurrentRevision().getResourceURI(); <ide> } <ide> <ide> public void setControlLinks(Set<ControlLink> controlLinks) { <ide> this.controlLinks.clear(); <ide> this.controlLinks.addAll(controlLinks); <add> } <add> <add> public void setCurrentRevision(Revision currentRevision) { <add> this.currentRevision = currentRevision; <add> if (currentRevision == null) { <add> newRevision(); <add> } <ide> } <ide> <ide> /**
JavaScript
mit
2829935c518c40cadc32c907c7389096dc8362cd
0
lewishenson/Formula1Standings,lewishenson/Formula1Standings
'use strict'; angular.module('F1FeederApp', [ 'F1FeederApp.controllers', 'F1FeederApp.services' ]); angular.module('F1FeederApp.controllers', []).controller('driversController', function($scope, ergastAPIservice) { $scope.driversList = []; ergastAPIservice.getDrivers().success(function (response) { $scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings; }); }); angular.module('F1FeederApp.services', []). factory('ergastAPIservice', function($http) { var ergastAPI = {}; ergastAPI.getDrivers = function() { return $http({ method: 'JSONP', url: 'http://ergast.com/api/f1/2014/driverStandings.json?callback=JSON_CALLBACK' }); } return ergastAPI; });
app/app.js
'use strict'; angular.module('F1FeederApp', [ 'F1FeederApp.controllers' ]); angular.module('F1FeederApp.controllers', []).controller('driversController', function($scope) { $scope.driversList = [ { Driver: { givenName: 'Sebastian', familyName: 'Vettel' }, points: 322, nationality: "German", Constructors: [ {name: "Red Bull"} ] }, { Driver: { givenName: 'Fernando', familyName: 'Alonso' }, points: 207, nationality: "Spanish", Constructors: [ {name: "Ferrari"} ] } ]; });
Show dynamic list of drivers
app/app.js
Show dynamic list of drivers
<ide><path>pp/app.js <ide> 'use strict'; <ide> <ide> angular.module('F1FeederApp', [ <del> 'F1FeederApp.controllers' <add> 'F1FeederApp.controllers', <add> 'F1FeederApp.services' <ide> ]); <ide> <del>angular.module('F1FeederApp.controllers', []).controller('driversController', function($scope) { <del> $scope.driversList = [ <del> { <del> Driver: { <del> givenName: 'Sebastian', <del> familyName: 'Vettel' <del> }, <del> points: 322, <del> nationality: "German", <del> Constructors: [ <del> {name: "Red Bull"} <del> ] <del> }, <del> { <del> Driver: { <del> givenName: 'Fernando', <del> familyName: 'Alonso' <del> }, <del> points: 207, <del> nationality: "Spanish", <del> Constructors: [ <del> {name: "Ferrari"} <del> ] <del> } <del> ]; <add>angular.module('F1FeederApp.controllers', []).controller('driversController', function($scope, ergastAPIservice) { <add> $scope.driversList = []; <add> <add> ergastAPIservice.getDrivers().success(function (response) { <add> $scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings; <add> }); <ide> }); <add> <add>angular.module('F1FeederApp.services', []). factory('ergastAPIservice', function($http) { <add> var ergastAPI = {}; <add> <add> ergastAPI.getDrivers = function() { <add> return $http({ <add> method: 'JSONP', <add> url: 'http://ergast.com/api/f1/2014/driverStandings.json?callback=JSON_CALLBACK' <add> }); <add> } <add> <add> return ergastAPI; <add> });
Java
bsd-3-clause
be46ca8a8ccae949917678cd52125974ae064479
0
VulcanRobotics/Veer
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //test change package Subsystem.Swerve; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.Talon; /** * * @author 1218 */ public class O_TurningMotor { private static final double Kp = 1.0; private static final double Ki = 0.0; private static final double Kd = 0.0; private Talon motor; O_TurningEncoder turningEncoder; PIDController PID; // Initialize your subsystem here public O_TurningMotor(int talonPort, int encoderPortA, int encoderPortB) { motor = new Talon(2 ,talonPort); //turing motors on digital breakout 2 turningEncoder = new O_TurningEncoder(encoderPortA, encoderPortB); PID = new PIDController(Kp, Ki, Kd, turningEncoder, motor); PID.setInputRange(-180, 180); PID.setOutputRange(-3, .3); PID.setContinuous(true); PID.enable(); } public void setAngle(int angle) { PID.setSetpoint(angle); } }
src/Subsystem/Swerve/O_TurningMotor.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //test change package Subsystem.Swerve; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.Talon; /** * * @author 1218 */ public class O_TurningMotor { private static final double Kp = 0.0; private static final double Ki = 0.0; private static final double Kd = 0.0; private Talon motor; O_TurningEncoder turningEncoder; PIDController PID; // Initialize your subsystem here public O_TurningMotor(int talonPort, int encoderPortA, int encoderPortB) { motor = new Talon(2,talonPort); //turing motors on digital breakout 2 turningEncoder = new O_TurningEncoder(encoderPortA, encoderPortB); PID = new PIDController(Kp, Ki, Kd, turningEncoder, motor); PID.setInputRange(-180, 180); PID.setOutputRange(-1, 1); PID.setContinuous(true); PID.enable(); } public void setAngle(int angle) { PID.setSetpoint(angle); } }
set max speed low for testing made kp 1
src/Subsystem/Swerve/O_TurningMotor.java
set max speed low for testing made kp 1
<ide><path>rc/Subsystem/Swerve/O_TurningMotor.java <ide> */ <ide> public class O_TurningMotor { <ide> <del> private static final double Kp = 0.0; <add> private static final double Kp = 1.0; <ide> private static final double Ki = 0.0; <ide> private static final double Kd = 0.0; <ide> <ide> <ide> // Initialize your subsystem here <ide> public O_TurningMotor(int talonPort, int encoderPortA, int encoderPortB) { <del> motor = new Talon(2,talonPort); //turing motors on digital breakout 2 <add> motor = new Talon(2 ,talonPort); //turing motors on digital breakout 2 <ide> turningEncoder = new O_TurningEncoder(encoderPortA, encoderPortB); <ide> PID = new PIDController(Kp, Ki, Kd, turningEncoder, motor); <ide> PID.setInputRange(-180, 180); <del> PID.setOutputRange(-1, 1); <add> PID.setOutputRange(-3, .3); <ide> PID.setContinuous(true); <ide> PID.enable(); <ide> }
JavaScript
mit
11f861e127a418ec59106c8d7fe7431d992c4a4d
0
geoportallux/geoportailv3-gisgr,geoportallux/geoportailv3-gisgr,Geoportail-Luxembourg/geoportailv3,geoportallux/geoportailv3-gisgr,Geoportail-Luxembourg/geoportailv3,geoportallux/geoportailv3-gisgr,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3,Geoportail-Luxembourg/geoportailv3
/** * @fileoverview This file provides a print directive. This directive is used * to create a print form panel in the page. * * Example: * * <app-print app-print-map="::mainCtrl.map" * app-print-open="mainCtrl.printOpen" * app-print-layers="mainCtrl.selectedLayers"> * </app-print> */ goog.provide('app.PrintController'); goog.provide('app.printDirective'); goog.require('app.FeaturePopup'); goog.require('app.GetShorturl'); goog.require('app.Theme'); goog.require('app.Themes'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.string'); goog.require('ngeo.CreatePrint'); goog.require('ngeo.FeatureOverlayMgr'); goog.require('ngeo.Print'); goog.require('ngeo.PrintUtils'); goog.require('ol.animation'); goog.require('ol.easing'); goog.require('ol.events'); goog.require('ol.layer.Layer'); goog.require('ol.layer.Vector'); goog.require('ol.render.Event'); goog.require('ol.render.EventType'); /** * @param {string} appPrintTemplateUrl Url to print template * @return {angular.Directive} The Directive Definition Object. * @ngInject */ app.printDirective = function(appPrintTemplateUrl) { return { restrict: 'E', scope: { 'map': '=appPrintMap', 'open': '=appPrintOpen', 'layers': '=appPrintLayers' }, controller: 'AppPrintController', controllerAs: 'ctrl', bindToController: true, templateUrl: appPrintTemplateUrl }; }; app.module.directive('appPrint', app.printDirective); /** * @param {angular.Scope} $scope Scope. * @param {angular.$timeout} $timeout The Angular $timeout service. * @param {angular.$q} $q The Angular $q service. * @param {angularGettext.Catalog} gettextCatalog * @param {ngeo.CreatePrint} ngeoCreatePrint The ngeoCreatePrint service. * @param {ngeo.FeatureOverlayMgr} ngeoFeatureOverlayMgr Feature overlay * manager. * @param {ngeo.PrintUtils} ngeoPrintUtils The ngeoPrintUtils service. * @param {app.Themes} appThemes Themes service. * @param {app.Theme} appTheme the current theme service. * @param {app.FeaturePopup} appFeaturePopup Feature popup service. * @param {app.GetShorturl} appGetShorturl The getShorturl function. * @param {string} printServiceUrl URL to print service. * @param {string} qrServiceUrl URL to qr generator service. * @constructor * @export * @ngInject */ app.PrintController = function($scope, $timeout, $q, gettextCatalog, ngeoCreatePrint, ngeoFeatureOverlayMgr, ngeoPrintUtils, appThemes, appTheme, appFeaturePopup, appGetShorturl, printServiceUrl, qrServiceUrl) { /** * @type {app.FeaturePopup} * @private */ this.featurePopup_ = appFeaturePopup; /** * @type {ol.Map} * @private */ this.map_ = this['map']; goog.asserts.assert(goog.isDefAndNotNull(this.map_)); /** * @type {angular.$timeout} * @private */ this.$timeout_ = $timeout; /** * @type {?angular.$q.Promise} * @private */ this.statusTimeoutPromise_ = null; /** * @type {angular.$q} * @private */ this.$q_ = $q; /** * @type {?angular.$q.Deferred} * @private */ this.requestCanceler_ = null; /** * @type {ngeo.Print} * @private */ this.print_ = ngeoCreatePrint(printServiceUrl); /** * @type {ngeo.PrintUtils} * @private */ this.printUtils_ = ngeoPrintUtils; /** * @type {app.Themes} * @private */ this.appThemes_ = appThemes; /** * @type {app.Theme} * @private */ this.appTheme_ = appTheme; /** * A reference to the vector layer used by feature overlays. * @type {ol.layer.Vector} * @private */ this.featureOverlayLayer_ = ngeoFeatureOverlayMgr.getLayer(); /** * @type {app.GetShorturl} * @private */ this.getShorturl_ = appGetShorturl; /** * @type {string} * @private */ this.qrServiceUrl_ = qrServiceUrl; /** * @type {angularGettext.Catalog} * @private */ this.gettextCatalog_ = gettextCatalog; /** * Current report reference id. * @type {string} * @private */ this.curRef_ = ''; /** * @type {Array.<string>} */ this['layouts'] = [ gettextCatalog.getString('A4 landscape'), gettextCatalog.getString('A4 portrait'), gettextCatalog.getString('A3 landscape'), gettextCatalog.getString('A3 portrait'), gettextCatalog.getString('A2 landscape'), gettextCatalog.getString('A2 portrait'), gettextCatalog.getString('A1 landscape'), gettextCatalog.getString('A1 portrait'), gettextCatalog.getString('A0 landscape'), gettextCatalog.getString('A0 portrait') ]; /** * @type {string} */ this['layout'] = this['layouts'][0]; /** * @type {Array.<number>} */ this['scales'] = []; /** * @type {number} */ this['scale'] = -1; /** * @type {boolean|undefined} */ this['open'] = undefined; /** * @type {string|undefined} */ this['title'] = ''; /** * @type {boolean} */ this['legend'] = false; /** * @type {boolean} */ this['printing'] = false; /** * @type {ol.events.Key?} */ var postcomposeListenerKey = null; /** * @type {Array.<ol.layer.Layer>} * @private */ this.layers_ = this['layers']; /** * @type {function(ol.render.Event)} */ var postcomposeListener = ngeoPrintUtils.createPrintMaskPostcompose( goog.bind( /** * Return the size in dots of the map to print. Depends on * the selected layout. * @return {ol.Size} Size. */ function() { var layoutIdx = this['layouts'].indexOf(this['layout']); goog.asserts.assert(layoutIdx >= 0); return app.PrintController.MAP_SIZES_[layoutIdx]; }, this), goog.bind( /** * Return the scale of the map to print. * @param {olx.FrameState} frameState Frame state. * @return {number} Scale. */ function(frameState) { return app.PrintController.adjustScale_( this.map_.getView(), this['scale']); }, this)); // Show/hide the print mask based on the value of the "open" property. $scope.$watch(goog.bind(function() { return this['open']; }, this), goog.bind(function(newVal) { if (!goog.isDef(newVal)) { return; } var open = /** @type {boolean} */ (newVal); if (open) { this.featurePopup_.hide(); this.useOptimalScale_(); goog.asserts.assert(goog.isNull(postcomposeListenerKey)); postcomposeListenerKey = ol.events.listen(this.map_, ol.render.EventType.POSTCOMPOSE, postcomposeListener); } else if (!goog.isNull(postcomposeListenerKey)) { ol.Observable.unByKey(postcomposeListenerKey); postcomposeListenerKey = null; } this.map_.render(); }, this)); // Set the possible print scales based on the current theme. $scope.$watch(goog.bind(function() { return this.appTheme_.getCurrentTheme(); }, this), goog.bind(function() { this.setScales_(); }, this)); }; /** * @const * @type {Array.<number>} * @private */ app.PrintController.DEFAULT_MAP_SCALES_ = [1500, 2500, 5000, 10000, 15000, 20000, 25000, 50000, 80000, 100000, 125000, 200000, 250000, 400000]; /** * These values should match those set in the jrxml print templates. * @const * @type {Array.<ol.Size>} * @private */ app.PrintController.MAP_SIZES_ = [ // A4 portrait and landscape [715, 395], [470, 650], // A3 portrait and landscape [1065, 640], [715, 975], // A2 portrait and landscape [1558, 985], [1064, 1475], // A1 portrait and landscape [2255, 1482], [1558, 2175], // A0 portrait and landscape [3241, 2173], [2254, 3155] ]; /** * @const * @type {number} * @private */ app.PrintController.DPI_ = 96; /** * Get the center resolution for the current view state. * @param {ol.View} view The view. * @return {number} The point resolution. * @private */ app.PrintController.getViewCenterResolution_ = function(view) { var viewCenter = view.getCenter(); var viewProjection = view.getProjection(); var viewResolution = view.getResolution(); goog.asserts.assert(goog.isDef(viewCenter)); goog.asserts.assert(!goog.isNull(viewProjection)); goog.asserts.assert(goog.isDef(viewResolution)); return viewProjection.getPointResolution(viewResolution, viewCenter); }; /** * @param {ol.View} view The view. * @param {number} scale The non-adjusted scale. * @return {number} The adjusted scale. * @private */ app.PrintController.adjustScale_ = function(view, scale) { var viewResolution = view.getResolution(); var viewCenterResolution = app.PrintController.getViewCenterResolution_(view); goog.asserts.assert(goog.isDef(viewResolution)); var factor = viewResolution / viewCenterResolution; return scale * factor; }; /** * @param {Array.<number>} scales Sorted array of scales (ascending). * @param {number} scale Current scale. * @return {number} The nearest scale. * @private */ app.PrintController.findNearestScale_ = function(scales, scale) { if (scale <= scales[0]) { scale = scales[0]; } else if (scale >= scales[scales.length - 1]) { scale = scales[scales.length - 1]; } else { for (var i = 1, l = scales.length; i < l; ++i) { if (scales[i] >= scale) { if (scales[i] - scale < scale - scales[i - 1]) { scale = scales[i]; } else { scale = scales[i - 1]; } break; } } goog.asserts.assert(i < l); } return scale; }; /** * @export */ app.PrintController.prototype.cancel = function() { // Cancel the latest request, if it's not finished yet. goog.asserts.assert(!goog.isNull(this.requestCanceler_)); this.requestCanceler_.resolve(); // Cancel the status timeout if there's one set, to make sure no other // status request is sent. if (!goog.isNull(this.statusTimeoutPromise_)) { this.$timeout_.cancel(this.statusTimeoutPromise_); } goog.asserts.assert(this.curRef_.length > 0); this.print_.cancel(this.curRef_); this.resetPrintStates_(); }; /** * @param {string} newLayout The name of the selected layout. * @export */ app.PrintController.prototype.changeLayout = function(newLayout) { this['layout'] = newLayout; this.useOptimalScale_(); this.map_.render(); }; /** * @param {number} newScale The new scale. * @export */ app.PrintController.prototype.changeScale = function(newScale) { this['scale'] = newScale; var map = this.map_; var mapSize = map.getSize(); goog.asserts.assert(goog.isDefAndNotNull(mapSize)); var layoutIdx = this['layouts'].indexOf(this['layout']); goog.asserts.assert(layoutIdx >= 0); var optimalResolution = this.printUtils_.getOptimalResolution( mapSize, app.PrintController.MAP_SIZES_[layoutIdx], newScale); var view = map.getView(); var currentResolution = view.getResolution(); if (currentResolution < optimalResolution) { var newResolution = view.constrainResolution(optimalResolution, 0, 1); goog.asserts.assert(newResolution >= optimalResolution); map.beforeRender(ol.animation.zoom({ duration: 250, easing: ol.easing.easeOut, resolution: currentResolution })); view.setResolution(newResolution); } map.render(); }; /** * @export */ app.PrintController.prototype.print = function() { this.featurePopup_.hide(); var map = this.map_; var dpi = app.PrintController.DPI_; var scale = app.PrintController.adjustScale_(map.getView(), this['scale']); var layout = this['layout']; var legend = []; this.layers_.forEach(function(layer) { var name = layer.get('metadata')['legend_name']; if (goog.isDef(name)) { legend.push({'name': name}); } }); this.getShorturl_().then(goog.bind( /** * @param {string} shorturl The short URL. */ function(shorturl) { this.requestCanceler_ = this.$q_.defer(); this['printing'] = true; // create print spec object var spec = this.print_.createSpec(map, scale, dpi, layout, { 'scale': this['scale'], 'name': this['title'], 'url': shorturl, 'qrimage': this.qrServiceUrl_ + '?url=' + shorturl, 'lang': this.gettextCatalog_.currentLanguage, 'legend': this['legend'] ? legend : null, 'scalebar': {'geodetic': true} }); // add feature overlay layer to print spec var /** @type {Array.<MapFishPrintLayer>} */ layers = []; var resolution = map.getView().getResolution(); goog.asserts.assert(goog.isDef(resolution)); this.print_.encodeLayer(layers, this.featureOverlayLayer_, resolution); if (layers.length > 0) { spec.attributes.map.layers.unshift(layers[0]); } // create print report this.print_.createReport(spec, /** @type {angular.$http.Config} */ ({ timeout: this.requestCanceler_.promise })).then( angular.bind(this, this.handleCreateReportSuccess_), angular.bind(this, this.handleCreateReportError_)); }, this)); }; /** * @param {!angular.$http.Response} resp Response. * @private */ app.PrintController.prototype.handleCreateReportSuccess_ = function(resp) { var mfResp = /** @type {MapFishPrintReportResponse} */ (resp.data); var ref = mfResp.ref; goog.asserts.assert(ref.length > 0); this.curRef_ = ref; this.getStatus_(ref); }; /** * @param {string} ref Ref. * @private */ app.PrintController.prototype.getStatus_ = function(ref) { this.requestCanceler_ = this.$q_.defer(); this.print_.getStatus(ref, /** @type {angular.$http.Config} */ ({ timeout: this.requestCanceler_.promise })).then( angular.bind(this, this.handleGetStatusSuccess_, ref), angular.bind(this, this.handleGetStatusError_)); }; /** * @param {!angular.$http.Response} resp Response. * @private */ app.PrintController.prototype.handleCreateReportError_ = function(resp) { this.resetPrintStates_(); // FIXME display error message? }; /** * @param {string} ref Ref. * @param {!angular.$http.Response} resp Response. * @private */ app.PrintController.prototype.handleGetStatusSuccess_ = function(ref, resp) { var mfResp = /** @type {MapFishPrintStatusResponse} */ (resp.data); var done = mfResp.done; if (done) { // The report is ready. Open it by changing the window location. window.location.href = this.print_.getReportUrl(ref); this.resetPrintStates_(); } else { // The report is not ready yet. Check again in 1s. var that = this; this.statusTimeoutPromise_ = this.$timeout_(function() { that.getStatus_(ref); }, 1000, false); } }; /** * @param {!angular.$http.Response} resp Response. * @private */ app.PrintController.prototype.handleGetStatusError_ = function(resp) { this.resetPrintStates_(); // FIXME display error message? }; /** * @private */ app.PrintController.prototype.resetPrintStates_ = function() { this['printing'] = false; this.curRef_ = ''; }; /** * Set possible print scales based on the current theme. * @private */ app.PrintController.prototype.setScales_ = function() { var currentTheme = this.appTheme_.getCurrentTheme(); this.appThemes_.getThemeObject(currentTheme).then(goog.bind( /** * @param {Object} tree Tree object for the theme. */ function(tree) { if (!goog.isNull(tree)) { goog.asserts.assert('metadata' in tree); var scales; if (!goog.string.isEmptySafe(tree['metadata']['print_scales'])) { var printScalesStr = tree['metadata']['print_scales']; scales = goog.array.map( printScalesStr.trim().split(','), /** * @param {string} scale Scale value as a string. * @return {number} Scale value as a number. */ function(scale) { return +scale; }); goog.array.sort(scales); } else { scales = app.PrintController.DEFAULT_MAP_SCALES_; } this['scales'] = scales; var scale = this['scale']; if (scale != -1) { // find nearest scale to current scale scale = app.PrintController.findNearestScale_(scales, scale); if (scale != this['scale']) { this['scale'] = scale; this.map_.render(); } } } }, this)); }; /** * Get the optimal print scale for the current map size and resolution, * and for the selected print layout. * @private */ app.PrintController.prototype.useOptimalScale_ = function() { var map = this.map_; var mapSize = map.getSize(); goog.asserts.assert(goog.isDefAndNotNull(mapSize)); var viewCenterResolution = app.PrintController.getViewCenterResolution_( map.getView()); var layoutIdx = this['layouts'].indexOf(this['layout']); goog.asserts.assert(layoutIdx >= 0); var scale = this.printUtils_.getOptimalScale(mapSize, viewCenterResolution, app.PrintController.MAP_SIZES_[layoutIdx], this['scales']); this['scale'] = scale != -1 ? scale : this['scales'][0]; }; app.module.controller('AppPrintController', app.PrintController);
geoportailv3/static/js/print/printdirective.js
/** * @fileoverview This file provides a print directive. This directive is used * to create a print form panel in the page. * * Example: * * <app-print app-print-map="::mainCtrl.map" * app-print-open="mainCtrl.printOpen" * app-print-layers="mainCtrl.selectedLayers"> * </app-print> */ goog.provide('app.PrintController'); goog.provide('app.printDirective'); goog.require('app.FeaturePopup'); goog.require('app.GetShorturl'); goog.require('app.Theme'); goog.require('app.Themes'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.string'); goog.require('ngeo.CreatePrint'); goog.require('ngeo.FeatureOverlayMgr'); goog.require('ngeo.Print'); goog.require('ngeo.PrintUtils'); goog.require('ol.animation'); goog.require('ol.easing'); goog.require('ol.events'); goog.require('ol.layer.Layer'); goog.require('ol.layer.Vector'); goog.require('ol.render.Event'); goog.require('ol.render.EventType'); /** * @param {string} appPrintTemplateUrl Url to print template * @return {angular.Directive} The Directive Definition Object. * @ngInject */ app.printDirective = function(appPrintTemplateUrl) { return { restrict: 'E', scope: { 'map': '=appPrintMap', 'open': '=appPrintOpen', 'layers': '=appPrintLayers' }, controller: 'AppPrintController', controllerAs: 'ctrl', bindToController: true, templateUrl: appPrintTemplateUrl }; }; app.module.directive('appPrint', app.printDirective); /** * @param {angular.Scope} $scope Scope. * @param {angular.$timeout} $timeout The Angular $timeout service. * @param {angular.$q} $q The Angular $q service. * @param {angularGettext.Catalog} gettextCatalog * @param {ngeo.CreatePrint} ngeoCreatePrint The ngeoCreatePrint service. * @param {ngeo.FeatureOverlayMgr} ngeoFeatureOverlayMgr Feature overlay * manager. * @param {ngeo.PrintUtils} ngeoPrintUtils The ngeoPrintUtils service. * @param {app.Themes} appThemes Themes service. * @param {app.Theme} appTheme the current theme service. * @param {app.FeaturePopup} appFeaturePopup Feature popup service. * @param {app.GetShorturl} appGetShorturl The getShorturl function. * @param {string} printServiceUrl URL to print service. * @param {string} qrServiceUrl URL to qr generator service. * @constructor * @export * @ngInject */ app.PrintController = function($scope, $timeout, $q, gettextCatalog, ngeoCreatePrint, ngeoFeatureOverlayMgr, ngeoPrintUtils, appThemes, appTheme, appFeaturePopup, appGetShorturl, printServiceUrl, qrServiceUrl) { /** * @type {app.FeaturePopup} * @private */ this.featurePopup_ = appFeaturePopup; /** * @type {ol.Map} * @private */ this.map_ = this['map']; goog.asserts.assert(goog.isDefAndNotNull(this.map_)); /** * @type {angular.$timeout} * @private */ this.$timeout_ = $timeout; /** * @type {?angular.$q.Promise} * @private */ this.statusTimeoutPromise_ = null; /** * @type {angular.$q} * @private */ this.$q_ = $q; /** * @type {?angular.$q.Deferred} * @private */ this.requestCanceler_ = null; /** * @type {ngeo.Print} * @private */ this.print_ = ngeoCreatePrint(printServiceUrl); /** * @type {ngeo.PrintUtils} * @private */ this.printUtils_ = ngeoPrintUtils; /** * @type {app.Themes} * @private */ this.appThemes_ = appThemes; /** * @type {app.Theme} * @private */ this.appTheme_ = appTheme; /** * A reference to the vector layer used by feature overlays. * @type {ol.layer.Vector} * @private */ this.featureOverlayLayer_ = ngeoFeatureOverlayMgr.getLayer(); /** * @type {app.GetShorturl} * @private */ this.getShorturl_ = appGetShorturl; /** * @type {string} * @private */ this.qrServiceUrl_ = qrServiceUrl; /** * @type {angularGettext.Catalog} * @private */ this.gettextCatalog_ = gettextCatalog; /** * Current report reference id. * @type {string} * @private */ this.curRef_ = ''; /** * @type {Array.<string>} */ this['layouts'] = [ gettextCatalog.getString('A4 landscape'), gettextCatalog.getString('A4 portrait'), gettextCatalog.getString('A3 landscape'), gettextCatalog.getString('A3 portrait'), gettextCatalog.getString('A2 landscape'), gettextCatalog.getString('A2 portrait'), gettextCatalog.getString('A1 landscape'), gettextCatalog.getString('A1 portrait'), gettextCatalog.getString('A0 landscape'), gettextCatalog.getString('A0 portrait') ]; /** * @type {string} */ this['layout'] = this['layouts'][0]; /** * @type {Array.<number>} */ this['scales'] = []; /** * @type {number} */ this['scale'] = -1; /** * @type {boolean|undefined} */ this['open'] = undefined; /** * @type {string|undefined} */ this['title'] = ''; /** * @type {boolean} */ this['legend'] = false; /** * @type {boolean} */ this['printing'] = false; /** * @type {ol.events.Key?} */ var postcomposeListenerKey = null; /** * @type {Array.<ol.layer.Layer>} * @private */ this.layers_ = this['layers']; /** * @type {function(ol.render.Event)} */ var postcomposeListener = ngeoPrintUtils.createPrintMaskPostcompose( goog.bind( /** * Return the size in dots of the map to print. Depends on * the selected layout. * @return {ol.Size} Size. */ function() { var layoutIdx = this['layouts'].indexOf(this['layout']); goog.asserts.assert(layoutIdx >= 0); return app.PrintController.MAP_SIZES_[layoutIdx]; }, this), goog.bind( /** * Return the scale of the map to print. * @param {olx.FrameState} frameState Frame state. * @return {number} Scale. */ function(frameState) { return app.PrintController.adjustScale_( this.map_.getView(), this['scale']); }, this)); // Show/hide the print mask based on the value of the "open" property. $scope.$watch(goog.bind(function() { return this['open']; }, this), goog.bind(function(newVal) { if (!goog.isDef(newVal)) { return; } var open = /** @type {boolean} */ (newVal); if (open) { this.featurePopup_.hide(); this.useOptimalScale_(); goog.asserts.assert(goog.isNull(postcomposeListenerKey)); postcomposeListenerKey = ol.events.listen(this.map_, ol.render.EventType.POSTCOMPOSE, postcomposeListener); } else if (!goog.isNull(postcomposeListenerKey)) { ol.Observable.unByKey(postcomposeListenerKey); postcomposeListenerKey = null; } this.map_.render(); }, this)); // Set the possible print scales based on the current theme. $scope.$watch(goog.bind(function() { return this.appTheme_.getCurrentTheme(); }, this), goog.bind(function() { this.setScales_(); }, this)); }; /** * @const * @type {Array.<number>} * @private */ app.PrintController.DEFAULT_MAP_SCALES_ = [1500, 2500, 5000, 10000, 15000, 20000, 25000, 50000, 80000, 100000, 125000, 200000, 250000, 400000]; /** * These values should match those set in the jrxml print templates. * @const * @type {Array.<ol.Size>} * @private */ app.PrintController.MAP_SIZES_ = [ // A4 portrait and landscape [470, 650], [715, 395], // A3 portrait and landscape [715, 975], [1065, 640], // A2 portrait and landscape [1064, 1475], [1558, 985], // A1 portrait and landscape [1558, 2175], [2255, 1482], // A0 portrait and landscape [2254, 3155], [3241, 2173] ]; /** * @const * @type {number} * @private */ app.PrintController.DPI_ = 96; /** * Get the center resolution for the current view state. * @param {ol.View} view The view. * @return {number} The point resolution. * @private */ app.PrintController.getViewCenterResolution_ = function(view) { var viewCenter = view.getCenter(); var viewProjection = view.getProjection(); var viewResolution = view.getResolution(); goog.asserts.assert(goog.isDef(viewCenter)); goog.asserts.assert(!goog.isNull(viewProjection)); goog.asserts.assert(goog.isDef(viewResolution)); return viewProjection.getPointResolution(viewResolution, viewCenter); }; /** * @param {ol.View} view The view. * @param {number} scale The non-adjusted scale. * @return {number} The adjusted scale. * @private */ app.PrintController.adjustScale_ = function(view, scale) { var viewResolution = view.getResolution(); var viewCenterResolution = app.PrintController.getViewCenterResolution_(view); goog.asserts.assert(goog.isDef(viewResolution)); var factor = viewResolution / viewCenterResolution; return scale * factor; }; /** * @param {Array.<number>} scales Sorted array of scales (ascending). * @param {number} scale Current scale. * @return {number} The nearest scale. * @private */ app.PrintController.findNearestScale_ = function(scales, scale) { if (scale <= scales[0]) { scale = scales[0]; } else if (scale >= scales[scales.length - 1]) { scale = scales[scales.length - 1]; } else { for (var i = 1, l = scales.length; i < l; ++i) { if (scales[i] >= scale) { if (scales[i] - scale < scale - scales[i - 1]) { scale = scales[i]; } else { scale = scales[i - 1]; } break; } } goog.asserts.assert(i < l); } return scale; }; /** * @export */ app.PrintController.prototype.cancel = function() { // Cancel the latest request, if it's not finished yet. goog.asserts.assert(!goog.isNull(this.requestCanceler_)); this.requestCanceler_.resolve(); // Cancel the status timeout if there's one set, to make sure no other // status request is sent. if (!goog.isNull(this.statusTimeoutPromise_)) { this.$timeout_.cancel(this.statusTimeoutPromise_); } goog.asserts.assert(this.curRef_.length > 0); this.print_.cancel(this.curRef_); this.resetPrintStates_(); }; /** * @param {string} newLayout The name of the selected layout. * @export */ app.PrintController.prototype.changeLayout = function(newLayout) { this['layout'] = newLayout; this.useOptimalScale_(); this.map_.render(); }; /** * @param {number} newScale The new scale. * @export */ app.PrintController.prototype.changeScale = function(newScale) { this['scale'] = newScale; var map = this.map_; var mapSize = map.getSize(); goog.asserts.assert(goog.isDefAndNotNull(mapSize)); var layoutIdx = this['layouts'].indexOf(this['layout']); goog.asserts.assert(layoutIdx >= 0); var optimalResolution = this.printUtils_.getOptimalResolution( mapSize, app.PrintController.MAP_SIZES_[layoutIdx], newScale); var view = map.getView(); var currentResolution = view.getResolution(); if (currentResolution < optimalResolution) { var newResolution = view.constrainResolution(optimalResolution, 0, 1); goog.asserts.assert(newResolution >= optimalResolution); map.beforeRender(ol.animation.zoom({ duration: 250, easing: ol.easing.easeOut, resolution: currentResolution })); view.setResolution(newResolution); } map.render(); }; /** * @export */ app.PrintController.prototype.print = function() { this.featurePopup_.hide(); var map = this.map_; var dpi = app.PrintController.DPI_; var scale = app.PrintController.adjustScale_(map.getView(), this['scale']); var layout = this['layout']; var legend = []; this.layers_.forEach(function(layer) { var name = layer.get('metadata')['legend_name']; if (goog.isDef(name)) { legend.push({'name': name}); } }); this.getShorturl_().then(goog.bind( /** * @param {string} shorturl The short URL. */ function(shorturl) { this.requestCanceler_ = this.$q_.defer(); this['printing'] = true; // create print spec object var spec = this.print_.createSpec(map, scale, dpi, layout, { 'scale': this['scale'], 'name': this['title'], 'url': shorturl, 'qrimage': this.qrServiceUrl_ + '?url=' + shorturl, 'lang': this.gettextCatalog_.currentLanguage, 'legend': this['legend'] ? legend : null, 'scalebar': {'geodetic': true} }); // add feature overlay layer to print spec var /** @type {Array.<MapFishPrintLayer>} */ layers = []; var resolution = map.getView().getResolution(); goog.asserts.assert(goog.isDef(resolution)); this.print_.encodeLayer(layers, this.featureOverlayLayer_, resolution); if (layers.length > 0) { spec.attributes.map.layers.unshift(layers[0]); } // create print report this.print_.createReport(spec, /** @type {angular.$http.Config} */ ({ timeout: this.requestCanceler_.promise })).then( angular.bind(this, this.handleCreateReportSuccess_), angular.bind(this, this.handleCreateReportError_)); }, this)); }; /** * @param {!angular.$http.Response} resp Response. * @private */ app.PrintController.prototype.handleCreateReportSuccess_ = function(resp) { var mfResp = /** @type {MapFishPrintReportResponse} */ (resp.data); var ref = mfResp.ref; goog.asserts.assert(ref.length > 0); this.curRef_ = ref; this.getStatus_(ref); }; /** * @param {string} ref Ref. * @private */ app.PrintController.prototype.getStatus_ = function(ref) { this.requestCanceler_ = this.$q_.defer(); this.print_.getStatus(ref, /** @type {angular.$http.Config} */ ({ timeout: this.requestCanceler_.promise })).then( angular.bind(this, this.handleGetStatusSuccess_, ref), angular.bind(this, this.handleGetStatusError_)); }; /** * @param {!angular.$http.Response} resp Response. * @private */ app.PrintController.prototype.handleCreateReportError_ = function(resp) { this.resetPrintStates_(); // FIXME display error message? }; /** * @param {string} ref Ref. * @param {!angular.$http.Response} resp Response. * @private */ app.PrintController.prototype.handleGetStatusSuccess_ = function(ref, resp) { var mfResp = /** @type {MapFishPrintStatusResponse} */ (resp.data); var done = mfResp.done; if (done) { // The report is ready. Open it by changing the window location. window.location.href = this.print_.getReportUrl(ref); this.resetPrintStates_(); } else { // The report is not ready yet. Check again in 1s. var that = this; this.statusTimeoutPromise_ = this.$timeout_(function() { that.getStatus_(ref); }, 1000, false); } }; /** * @param {!angular.$http.Response} resp Response. * @private */ app.PrintController.prototype.handleGetStatusError_ = function(resp) { this.resetPrintStates_(); // FIXME display error message? }; /** * @private */ app.PrintController.prototype.resetPrintStates_ = function() { this['printing'] = false; this.curRef_ = ''; }; /** * Set possible print scales based on the current theme. * @private */ app.PrintController.prototype.setScales_ = function() { var currentTheme = this.appTheme_.getCurrentTheme(); this.appThemes_.getThemeObject(currentTheme).then(goog.bind( /** * @param {Object} tree Tree object for the theme. */ function(tree) { if (!goog.isNull(tree)) { goog.asserts.assert('metadata' in tree); var scales; if (!goog.string.isEmptySafe(tree['metadata']['print_scales'])) { var printScalesStr = tree['metadata']['print_scales']; scales = goog.array.map( printScalesStr.trim().split(','), /** * @param {string} scale Scale value as a string. * @return {number} Scale value as a number. */ function(scale) { return +scale; }); goog.array.sort(scales); } else { scales = app.PrintController.DEFAULT_MAP_SCALES_; } this['scales'] = scales; var scale = this['scale']; if (scale != -1) { // find nearest scale to current scale scale = app.PrintController.findNearestScale_(scales, scale); if (scale != this['scale']) { this['scale'] = scale; this.map_.render(); } } } }, this)); }; /** * Get the optimal print scale for the current map size and resolution, * and for the selected print layout. * @private */ app.PrintController.prototype.useOptimalScale_ = function() { var map = this.map_; var mapSize = map.getSize(); goog.asserts.assert(goog.isDefAndNotNull(mapSize)); var viewCenterResolution = app.PrintController.getViewCenterResolution_( map.getView()); var layoutIdx = this['layouts'].indexOf(this['layout']); goog.asserts.assert(layoutIdx >= 0); var scale = this.printUtils_.getOptimalScale(mapSize, viewCenterResolution, app.PrintController.MAP_SIZES_[layoutIdx], this['scales']); this['scale'] = scale != -1 ? scale : this['scales'][0]; }; app.module.controller('AppPrintController', app.PrintController);
Adjust map size with new layout order
geoportailv3/static/js/print/printdirective.js
Adjust map size with new layout order
<ide><path>eoportailv3/static/js/print/printdirective.js <ide> */ <ide> app.PrintController.MAP_SIZES_ = [ <ide> // A4 portrait and landscape <del> [470, 650], [715, 395], <add> [715, 395], [470, 650], <ide> // A3 portrait and landscape <del> [715, 975], [1065, 640], <add> [1065, 640], [715, 975], <ide> // A2 portrait and landscape <del> [1064, 1475], [1558, 985], <add> [1558, 985], [1064, 1475], <ide> // A1 portrait and landscape <del> [1558, 2175], [2255, 1482], <add> [2255, 1482], [1558, 2175], <ide> // A0 portrait and landscape <del> [2254, 3155], [3241, 2173] <add> [3241, 2173], [2254, 3155] <ide> ]; <ide> <ide>
Java
mit
b47f03dc3e8844aa5366e39d5a7f71bdd74d8c50
0
axboot/ax-boot-framework,axboot/ax-boot-framework,axboot/ax-boot-framework,axboot/ax-boot-framework,axboot/ax-boot-framework,axboot/ax-boot-framework
package com.chequer.axboot.admin; import com.chequer.axboot.core.parameter.RequestParams; import com.mangofactory.swagger.configuration.SpringSwaggerConfig; import com.mangofactory.swagger.models.dto.ApiInfo; import com.mangofactory.swagger.plugin.EnableSwagger; import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.annotation.AuthenticationPrincipal; import javax.inject.Inject; @Configuration @EnableSwagger public class AXBootSwaggerConfig { @Inject private SpringSwaggerConfig springSwaggerConfig; @Bean public SwaggerSpringMvcPlugin customImplementation() { return new SwaggerSpringMvcPlugin(this.springSwaggerConfig) .apiInfo(new ApiInfo("AXBoot API Swagger", "API Demonstration", "", "", "", "")) .includePatterns("/api/v1.*") .ignoredParameterTypes(AuthenticationPrincipal.class, RequestParams.class); } }
ax-boot-admin/src/main/java/com/chequer/axboot/admin/AXBootSwaggerConfig.java
package com.chequer.axboot.admin; import com.chequer.axboot.core.parameter.RequestParams; import com.mangofactory.swagger.configuration.SpringSwaggerConfig; import com.mangofactory.swagger.models.dto.ApiInfo; import com.mangofactory.swagger.plugin.EnableSwagger; import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.core.annotation.AuthenticationPrincipal; import javax.inject.Inject; @Configuration @EnableSwagger public class AXBootSwaggerConfig { @Inject private SpringSwaggerConfig springSwaggerConfig; @Bean public SwaggerSpringMvcPlugin customImplementation() { return new SwaggerSpringMvcPlugin(this.springSwaggerConfig) .apiInfo(new ApiInfo("API", "API", "", "", "", "")) .includePatterns("/api/v1.*") .ignoredParameterTypes(AuthenticationPrincipal.class, RequestParams.class); } }
Swagger Update
ax-boot-admin/src/main/java/com/chequer/axboot/admin/AXBootSwaggerConfig.java
Swagger Update
<ide><path>x-boot-admin/src/main/java/com/chequer/axboot/admin/AXBootSwaggerConfig.java <ide> @Bean <ide> public SwaggerSpringMvcPlugin customImplementation() { <ide> return new SwaggerSpringMvcPlugin(this.springSwaggerConfig) <del> .apiInfo(new ApiInfo("API", "API", "", "", "", "")) <add> .apiInfo(new ApiInfo("AXBoot API Swagger", "API Demonstration", "", "", "", "")) <ide> .includePatterns("/api/v1.*") <ide> .ignoredParameterTypes(AuthenticationPrincipal.class, RequestParams.class); <ide> }
Java
mit
664bab193127468d03942e2899f644b55099a5e4
0
kasperisager/kelvin-maps,kasperisager/kelvin-maps
/** * Copyright (C) 2015 The Authors. */ package dk.itu.kelvin.controller; // JavaFX utilities import javafx.scene.input.*; import javafx.util.Duration; // JavaFX application utilities import javafx.application.Platform; // JavaFX scene utilities import javafx.geometry.Pos; // JavaFX events import javafx.event.EventHandler; // JavaFX layout import javafx.scene.layout.GridPane; import javafx.scene.layout.StackPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; // JavaFX shapes import javafx.scene.shape.Path; // JavaFX input // JavaFX transformations import javafx.scene.transform.Affine; // JavaFX controls import javafx.scene.control.Button; import javafx.scene.control.ToggleButton; import javafx.scene.control.TextField; import javafx.scene.control.Label; import javafx.scene.control.CheckBox; // JavaFX geometry import javafx.geometry.Bounds; // FXML utilities import javafx.fxml.FXML; // Controls FX import org.controlsfx.control.PopOver; // Utilities import java.util.ArrayList; import java.util.List; // Parser import dk.itu.kelvin.parser.ChartParser; // Threading import dk.itu.kelvin.thread.TaskQueue; // Layout import dk.itu.kelvin.layout.Chart; // Models import dk.itu.kelvin.model.Address; import dk.itu.kelvin.model.Node; // Stores import dk.itu.kelvin.store.AddressStore; /** * Chart controller class. * * @version 1.0.0 */ public final class ChartController { /** * The input file to show in the map viewer. */ private static final String MAP_INPUT = "small.osm"; /** * Default zoom step factor. */ private static final double ZOOM_STEP = 0.025; /** * Default zoom in factor. */ private static final double ZOOM_IN = 1 + ZOOM_STEP; /** * Default zoom out factor. */ private static final double ZOOM_OUT = 1 / ZOOM_IN; /** * Don't show auto completion when the entered input contains less that this * number of characters. */ private static final int AUTOCOMPLETE_CUTOFF = 2; /** * Max number of items to show in the auto completion menu. */ private static final int AUTOCOMPLETE_MAX_ITEMS = 5; /** * Mouse X coordinate for dragging. */ private double initialMouseDragX; /** * Mouse Y coordinate for dragging. */ private double initialMouseDragY; /** * Mouse X coordinate for scrolling and zooming. */ private double initialMouseScrollX; /** * Mouse Y coordinate for scrolling and zooming. */ private double initialMouseScrollY; /** * Affine transformation for chart compass. */ private Affine compassTransform = new Affine(); /** * The addresses map from the parser. */ private AddressStore addresses; /** * PopOver for the config menu. */ private PopOver popOver; /** * Auto-complete popover for textfields. */ private PopOver autocPopOver; /** * The dynamic autocomplete results. */ private List<String> suggestions = new ArrayList<>(); /** * Vbox containing the suggestion buttons. */ private VBox suggestionVBox; /** * Pointer for highlighting the autocomplete suggestions. */ private int pointer; /** * The Canvas element to add all the Chart elements to. */ @FXML private Chart chart; /** * The compass arrow. */ @FXML private Path compassArrow; /** * The address typed in. */ @FXML private TextField addressFrom; /** * The address to navigate to from addressFrom. */ @FXML private TextField addressTo; /** * The config button. */ @FXML private ToggleButton toggleButton; /** * The checkbox VBox element. */ @FXML private VBox checkboxVBox; /** * The poi elements VBox. */ @FXML private VBox poiVBox; /** * The VBox containing route description. */ @FXML private VBox directionsVBox; /** * The VBox containing a ScrollPane. */ @FXML private VBox directionsScrollPane; /** * The VBox surrounding all compass elements. */ @FXML private HBox compassVBox; /** * Indicator for scale. */ @FXML private Label scaleIndicatorLabel; /** * GridPane surrounding the big properties boxes * containing route description and point of interest. */ @FXML private GridPane propertiesGridPane; /** * The parent element. */ @FXML private StackPane stackPane; /** * Tags for cartographic elements. */ private String[] tags = {"Parking", "Cafe", "Restaurant", "Fast Food", "Toilets", "Pub", "Recycling", "Bar", "Compressed Air", "Post Box", "Taxi", "BBQ", "Solarium", "Telephone"}; /** * Initialize the controller. * @throws Exception In case of an error. Duh. */ public void initialize() throws Exception { // Sets the parent element inactive untill loaded. this.stackPane.setDisable(true); this.propertiesGridPane.getChildren().remove(this.checkboxVBox); this.propertiesGridPane.getChildren().remove(this.directionsScrollPane); this.compassArrow.getTransforms().add(this.compassTransform); TaskQueue.run(() -> { ChartParser parser = new ChartParser(); try { parser.read(MAP_INPUT); } catch (Exception ex) { throw new RuntimeException(ex); } /** * Results doesn't get sorted */ //Collections.sort(this.chart.elements(), Element.COMPARATOR); //Get map of all addresses from parser. this.addresses = parser.addresses(); // Schedule rendering of the chart nodes. Platform.runLater(() -> { this.chart.add(parser.ways().values()); this.chart.add(parser.relations().values()); this.chart.add(parser.land()); this.chart.add(parser.bounds()); // Sets the chart active after load. this.stackPane.setDisable(false); ApplicationController.removeIcon(); }); //Get map of all addresses from parser. this.addresses = parser.addresses(); }); this.createPOI(); this.createPopOver(); Platform.runLater(() -> this.addressFrom.requestFocus()); this.autocPopOver = new PopOver(); this.autocPopOver.setArrowLocation(PopOver.ArrowLocation.TOP_LEFT); this.autocPopOver.setCornerRadius(2); this.autocPopOver.setArrowSize(0); this.autocPopOver.setAutoHide(true); this.autocPopOver.setDetachable(false); this.setAutoComplete(this.addressFrom); this.setAutoComplete(this.addressTo); } /** * sets autocomplete for textfields. * @param tf textfield. */ private void setAutoComplete(final TextField tf) { tf.setOnKeyReleased((event) -> { this.suggestions.clear(); if (tf.getLength() > AUTOCOMPLETE_CUTOFF) { for (Address a: this.addresses.keySet()) { if (a.toString().toLowerCase().contains(tf.getText().toLowerCase())) { this.suggestions.add(a.toString()); } if (this.suggestions.size() > AUTOCOMPLETE_MAX_ITEMS) { break; } } } if (this.suggestions.size() <= 0) { this.autocPopOver.hide(Duration.ONE); return; } Bounds bounds = tf.localToScreen(tf.getBoundsInParent()); this.suggestionVBox = new VBox(this.suggestions.size()); this.suggestionVBox.setOnKeyPressed(new EventHandler<KeyEvent>() { public void handle(final KeyEvent e) { moveHighlight(e); } }); this.suggestionVBox.setPrefWidth(bounds.getWidth() + 27); for (String suggestion : this.suggestions) { Button l = new Button(suggestion); l.setPrefWidth(bounds.getWidth() + 27); l.setOnMouseClicked((event2 -> { tf.setText(l.getText()); this.autocPopOver.hide(Duration.ONE); })); this.suggestionVBox.getChildren().add(l); } if (this.suggestions.size() > 0) { Button s = (Button) this.suggestionVBox.getChildren().get(0); s.getStyleClass().add("highlight"); this.pointer = 0; } this.autocPopOver.setContentNode(this.suggestionVBox); if (!this.autocPopOver.isShowing()) { this.autocPopOver.show( tf, bounds.getMinX() + 14, // 14 = font size bounds.getMinY() + bounds.getHeight(), Duration.ONE ); } }); } /** * To move the highlight up and down in the suggestion popover. * @param e the keyevent. */ public void moveHighlight(final KeyEvent e) { if (e.getCode() == KeyCode.UP && this.pointer > 0) { this.pointer--; e.consume(); System.out.println(this.pointer); } if (e.getCode() == (KeyCode.DOWN) && this.pointer < 5) { this.pointer++; e.consume(); System.out.println(this.pointer); } } /** * Initialises the checkboxes of for Points Of Interest. */ private void createPOI() { for (String s : this.tags) { CheckBox cb = new CheckBox(s); cb.setPrefWidth(200); //add CheckBox event listener and update shown labels this.poiVBox.getChildren().add(cb); } } /** * Creates a PopOver object with buttons, eventhandlers and listeners. */ private void createPopOver() { VBox vbox = new VBox(2); Button blind = new Button("High Contrast"); Button poi = new Button("Points of Interest"); blind.setPrefWidth(140); poi.setPrefWidth(140); vbox.getChildren().addAll(blind, poi); blind.setOnAction((event) -> { ApplicationController.highContrast(); }); poi.setOnAction((event) -> { if (!this.checkboxVBox.isVisible()) { this.checkboxVBox.setVisible(true); this.propertiesGridPane.getChildren().add(this.checkboxVBox); this.moveCompass(200); } else { this.checkboxVBox.setVisible(false); this.propertiesGridPane.getChildren().remove(this.checkboxVBox); this.moveCompass(0); } this.popOver.hide(); }); this.popOver = new PopOver(); this.popOver.setContentNode(vbox); this.popOver.setCornerRadius(2); this.popOver.setArrowSize(6); this.popOver.setArrowLocation(PopOver.ArrowLocation.TOP_LEFT); this.popOver.setAutoHide(true); this.toggleButton.selectedProperty().addListener((ob, ov, nv) -> { if (nv) { this.popOver.show(this.toggleButton); } else { this.popOver.hide(); } }); this.popOver.showingProperty().addListener((ob, ov, nv) -> { if (!nv && this.toggleButton.isSelected()) { this.toggleButton.setSelected(false); } }); } /** * The the initial mouse coordinates for scrolling. * * @param e Mouse event for capturing mouse location. */ private void setInitialMouseScroll(final MouseEvent e) { this.initialMouseScrollX = e.getSceneX(); this.initialMouseScrollY = e.getSceneY(); } /** * The the initial mouse coordinates for dragging. * * @param e Mouse event for capturing mouse location. */ private void setInitialMouseDrag(final MouseEvent e) { this.initialMouseDragX = e.getSceneX(); this.initialMouseDragY = e.getSceneY(); } /** * On mouse entered event. * * @param e The mouse event. */ @FXML private void onMouseEntered(final MouseEvent e) { this.setInitialMouseScroll(e); } /** * On mouse pressed event. * * @param e The mouse event. */ @FXML private void onMousePressed(final MouseEvent e) { this.setInitialMouseDrag(e); this.setInitialMouseScroll(e); this.chart.requestFocus(); } /** * On mouse release event. * * @param e The mouse event. */ @FXML private void onMouseReleased(final MouseEvent e) { this.setInitialMouseScroll(e); } /** * On mouse moved event. * * @param e The mouse event. */ @FXML private void onMouseMoved(final MouseEvent e) { this.setInitialMouseScroll(e); } /** * On mouse clicked event. * * @param e The mouse event. */ @FXML private void onMouseClicked(final MouseEvent e) { this.setInitialMouseScroll(e); if (e.getClickCount() == 2) { this.chart.zoom(Math.pow(ZOOM_IN, 15), e.getSceneX(), e.getSceneY()); } } /** * On mouse dragged event. * * @param e The mouse event. */ @FXML private void onMouseDragged(final MouseEvent e) { double x = e.getSceneX(); double y = e.getSceneY(); this.chart.pan(x - this.initialMouseDragX, y - this.initialMouseDragY); this.setInitialMouseScroll(e); this.setInitialMouseDrag(e); } /** * On scroll event. * * @param e The scroll event. */ @FXML private void onScroll(final ScrollEvent e) { double factor = (e.getDeltaY() < 0) ? ZOOM_IN : ZOOM_OUT; this.chart.zoom( factor, this.initialMouseScrollX, this.initialMouseScrollY ); } /** * On zoom event. * * @param e The zoom event. */ @FXML private void onZoom(final ZoomEvent e) { this.chart.zoom( e.getZoomFactor(), this.initialMouseScrollX, this.initialMouseScrollY ); } /** * On rotate event. * * @param e The rotate event. */ @FXML private void onRotate(final RotateEvent e) { this.chart.rotate( e.getAngle(), this.initialMouseScrollX, this.initialMouseScrollY ); this.compassTransform.prependRotation(e.getAngle(), 4, 40); } /** * On key pressed event. * * @param e The key event. */ @FXML private void onKeyPressed(final KeyEvent e) { switch (e.getCode()) { case UP: case K: case W: this.chart.pan(0, 15); e.consume(); break; case DOWN: case J: case S: this.chart.pan(0, -15); e.consume(); break; case RIGHT: case L: case D: this.chart.pan(-15, 0); e.consume(); break; case LEFT: case H: case A: this.chart.pan(15, 0); e.consume(); break; case PLUS: case EQUALS: this.chart.zoom(Math.pow(ZOOM_IN, 8)); e.consume(); break; case MINUS: case UNDERSCORE: this.chart.zoom(Math.pow(ZOOM_OUT, 8)); e.consume(); break; case Q: this.chart.rotate(-10); this.compassTransform.prependRotation(-10, 4, 40); e.consume(); break; case E: this.chart.rotate(10); this.compassTransform.prependRotation(10, 4, 40); e.consume(); break; default: return; } } /** * Zoom in. */ @FXML private void zoomIn() { this.chart.zoom(Math.pow(ZOOM_IN, 8)); } /** * Zoom out. */ @FXML private void zoomOut() { this.chart.zoom(Math.pow(ZOOM_OUT, 8)); } /** * Is activated through input from the user looking for the address. * Found in textfield addressFrom. */ @FXML private void findAddress() { if (this.autocPopOver.isShowing()) { Button b = (Button) this.suggestionVBox.getChildren().get(this.pointer); String input = b.getText(); this.addressFrom.setText(b.getText()); if (input == null) { return; } input = input.trim(); if (input.isEmpty()) { return; } Address startAddress = Address.parse(input); if (startAddress == null) { return; } Node node = this.addresses.find(startAddress); if (node != null) { this.chart.center(node, 2.5); this.chart.setPointer(node); } this.autocPopOver.hide(); } /*else { // Dialog "The address does not exist." }*/ } /** * Takes the input from addressFrom and addressTo. */ @FXML private void findRoute() { if (!this.addressFrom.getText().trim().equals("") && !this.addressTo.getText().trim().equals("")) { Address startAddress = Address.parse(this.addressFrom.getText()); Address endAddress = Address.parse(this.addressTo.getText()); Node startPosition = this.addresses.find(startAddress); Node endPosition = this.addresses.find(endAddress); System.out.println("X: " + startPosition.x() + " " + "Y: " + startPosition.y()); System.out.println("X: " + endPosition.x() + " " + "Y: " + endPosition.y()); } this.propertiesGridPane.getChildren().add(this.directionsScrollPane); this.moveCompass(400); int stack = 30; for (int i = 0; i < stack; i++) { HBox hbox = new HBox(2); hbox.getStyleClass().add("bottomBorder"); hbox.setPrefWidth(500); Label icon = new Label("\uf10c"); icon.getStyleClass().add("icon"); icon.setPrefWidth(40); icon.setAlignment(Pos.CENTER); Label label = new Label("Turn right at next left"); hbox.getChildren().addAll(icon, label); this.directionsVBox.getChildren().add(hbox); } } /** * Hides the route description VBox. */ public void hideDirections() { this.propertiesGridPane.getChildren().remove(this.directionsScrollPane); this.moveCompass(0); } /** * Hides the Points of Interest VBox. */ public void hidePOI() { this.checkboxVBox.setVisible(false); this.propertiesGridPane.getChildren().remove(this.checkboxVBox); this.moveCompass(0); } /** * Moves the compass VBox relative to BOTTOM_LEFT. * @param x how much to move compass along x-axis [px]. */ public void moveCompass(final double x) { this.compassVBox.setTranslateX(x); } /** * Will reset the compass, so it points north. */ @FXML private void compassReset() { //to be continued } /** * Swap the text of the from and to address inputs. */ @FXML private void swapTextFields() { String from = this.addressFrom.getText(); String to = this.addressTo.getText(); this.addressFrom.setText(to); this.addressTo.setText(from); } /** * Shows the route between a and b by car. */ @FXML private void routeByCar() { System.out.println("Route by car"); } /** * Shows the rout between a and b by foot or bicycle. */ @FXML private void routeByFoot() { System.out.println("Route by foot"); } /** * Sets the text of scaleIndicator. * @param text the text to be set in scale. */ private void setScaleText(final String text) { this.scaleIndicatorLabel.setText(text); } /** * Sets the length of the scaleIndicator. * @param length how wide the scale is [px]. */ private void setScaleLenght(final double length) { this.scaleIndicatorLabel.setPrefWidth(length); } }
src/main/java/dk/itu/kelvin/controller/ChartController.java
/** * Copyright (C) 2015 The Authors. */ package dk.itu.kelvin.controller; // JavaFX utilities import javafx.util.Duration; // JavaFX application utilities import javafx.application.Platform; // JavaFX scene utilities import javafx.geometry.Pos; // JavaFX layout import javafx.scene.layout.GridPane; import javafx.scene.layout.StackPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; // JavaFX shapes import javafx.scene.shape.Path; // JavaFX input import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.input.RotateEvent; import javafx.scene.input.ScrollEvent; import javafx.scene.input.ZoomEvent; // JavaFX transformations import javafx.scene.transform.Affine; // JavaFX controls import javafx.scene.control.Button; import javafx.scene.control.ToggleButton; import javafx.scene.control.TextField; import javafx.scene.control.Label; import javafx.scene.control.CheckBox; // JavaFX geometry import javafx.geometry.Bounds; // FXML utilities import javafx.fxml.FXML; // Controls FX import org.controlsfx.control.PopOver; // Utilities import java.util.ArrayList; import java.util.List; // Parser import dk.itu.kelvin.parser.ChartParser; // Threading import dk.itu.kelvin.thread.TaskQueue; // Layout import dk.itu.kelvin.layout.Chart; // Models import dk.itu.kelvin.model.Address; import dk.itu.kelvin.model.Node; // Stores import dk.itu.kelvin.store.AddressStore; /** * Chart controller class. * * @version 1.0.0 */ public final class ChartController { /** * The input file to show in the map viewer. */ private static final String MAP_INPUT = "small.osm"; /** * Default zoom step factor. */ private static final double ZOOM_STEP = 0.025; /** * Default zoom in factor. */ private static final double ZOOM_IN = 1 + ZOOM_STEP; /** * Default zoom out factor. */ private static final double ZOOM_OUT = 1 / ZOOM_IN; /** * Don't show auto completion when the entered input contains less that this * number of characters. */ private static final int AUTOCOMPLETE_CUTOFF = 2; /** * Max number of items to show in the auto completion menu. */ private static final int AUTOCOMPLETE_MAX_ITEMS = 5; /** * Mouse X coordinate for dragging. */ private double initialMouseDragX; /** * Mouse Y coordinate for dragging. */ private double initialMouseDragY; /** * Mouse X coordinate for scrolling and zooming. */ private double initialMouseScrollX; /** * Mouse Y coordinate for scrolling and zooming. */ private double initialMouseScrollY; /** * Affine transformation for chart compass. */ private Affine compassTransform = new Affine(); /** * The addresses map from the parser. */ private AddressStore addresses; /** * PopOver for the config menu. */ private PopOver popOver; /** * Auto-complete popover for textfields. */ private PopOver autocPopOver; /** * The dynamic autocomplete results. */ private List<String> suggestions = new ArrayList<>(); /** * Vbox containing the suggestion buttons. */ private VBox suggestionVBox; /** * Pointer for highlighting the autocomplete suggestions. */ private int pointer; /** * The Canvas element to add all the Chart elements to. */ @FXML private Chart chart; /** * The compass arrow. */ @FXML private Path compassArrow; /** * The address typed in. */ @FXML private TextField addressFrom; /** * The address to navigate to from addressFrom. */ @FXML private TextField addressTo; /** * The config button. */ @FXML private ToggleButton toggleButton; /** * The checkbox VBox element. */ @FXML private VBox checkboxVBox; /** * The poi elements VBox. */ @FXML private VBox poiVBox; /** * The VBox containing route description. */ @FXML private VBox directionsVBox; /** * The VBox containing a ScrollPane. */ @FXML private VBox directionsScrollPane; /** * The VBox surrounding all compass elements. */ @FXML private HBox compassVBox; /** * Indicator for scale. */ @FXML private Label scaleIndicatorLabel; /** * GridPane surrounding the big properties boxes * containing route description and point of interest. */ @FXML private GridPane propertiesGridPane; /** * The parent element. */ @FXML private StackPane stackPane; /** * Tags for cartographic elements. */ private String[] tags = {"Parking", "Cafe", "Restaurant", "Fast Food", "Toilets", "Pub", "Recycling", "Bar", "Compressed Air", "Post Box", "Taxi", "BBQ", "Solarium", "Telephone"}; /** * Initialize the controller. * @throws Exception In case of an error. Duh. */ public void initialize() throws Exception { // Sets the parent element inactive untill loaded. this.stackPane.setDisable(true); this.propertiesGridPane.getChildren().remove(this.checkboxVBox); this.propertiesGridPane.getChildren().remove(this.directionsScrollPane); this.compassArrow.getTransforms().add(this.compassTransform); TaskQueue.run(() -> { ChartParser parser = new ChartParser(); try { parser.read(MAP_INPUT); } catch (Exception ex) { throw new RuntimeException(ex); } /** * Results doesn't get sorted */ //Collections.sort(this.chart.elements(), Element.COMPARATOR); //Get map of all addresses from parser. this.addresses = parser.addresses(); // Schedule rendering of the chart nodes. Platform.runLater(() -> { this.chart.add(parser.ways().values()); this.chart.add(parser.relations().values()); this.chart.add(parser.land()); this.chart.add(parser.bounds()); // Sets the chart active after load. this.stackPane.setDisable(false); ApplicationController.removeIcon(); }); //Get map of all addresses from parser. this.addresses = parser.addresses(); }); this.createPOI(); this.createPopOver(); Platform.runLater(() -> this.addressFrom.requestFocus()); this.autocPopOver = new PopOver(); this.autocPopOver.setArrowLocation(PopOver.ArrowLocation.TOP_LEFT); this.autocPopOver.setCornerRadius(2); this.autocPopOver.setArrowSize(0); this.autocPopOver.setAutoHide(true); this.autocPopOver.setDetachable(false); this.setAutoComplete(this.addressFrom); this.setAutoComplete(this.addressTo); } /** * sets autocomplete for textfields. * @param tf textfield. */ private void setAutoComplete(final TextField tf) { tf.setOnKeyReleased((event) -> { this.suggestions.clear(); if (tf.getLength() > AUTOCOMPLETE_CUTOFF) { for (Address a: this.addresses.keySet()) { if (a.toString().toLowerCase().contains(tf.getText().toLowerCase())) { this.suggestions.add(a.toString()); } if (this.suggestions.size() > AUTOCOMPLETE_MAX_ITEMS) { break; } } } if (this.suggestions.size() <= 0) { this.autocPopOver.hide(Duration.ONE); return; } Bounds bounds = tf.localToScreen(tf.getBoundsInParent()); this.suggestionVBox = new VBox(this.suggestions.size()); this.suggestionVBox.setPrefWidth(bounds.getWidth() + 27); for (String suggestion : this.suggestions) { Button l = new Button(suggestion); l.setPrefWidth(bounds.getWidth() + 27); l.setOnMouseClicked((event2 -> { tf.setText(l.getText()); this.autocPopOver.hide(Duration.ONE); })); this.suggestionVBox.getChildren().add(l); } if (suggestions.size() > 0) { Button s = (Button) this.suggestionVBox.getChildren().get(0); s.getStyleClass().add("highlight"); this.pointer = 0; } this.autocPopOver.setContentNode(this.suggestionVBox); if (!this.autocPopOver.isShowing()) { this.autocPopOver.show( tf, bounds.getMinX() + 14, // 14 = font size bounds.getMinY() + bounds.getHeight(), Duration.ONE ); } }); } /** * Initialises the checkboxes of for Points Of Interest. */ private void createPOI() { for (String s : this.tags) { CheckBox cb = new CheckBox(s); cb.setPrefWidth(200); //add CheckBox event listener and update shown labels this.poiVBox.getChildren().add(cb); } } /** * Creates a PopOver object with buttons, eventhandlers and listeners. */ private void createPopOver() { VBox vbox = new VBox(2); Button blind = new Button("High Contrast"); Button poi = new Button("Points of Interest"); blind.setPrefWidth(140); poi.setPrefWidth(140); vbox.getChildren().addAll(blind, poi); blind.setOnAction((event) -> { ApplicationController.highContrast(); }); poi.setOnAction((event) -> { if (!this.checkboxVBox.isVisible()) { this.checkboxVBox.setVisible(true); this.propertiesGridPane.getChildren().add(this.checkboxVBox); this.moveCompass(200); } else { this.checkboxVBox.setVisible(false); this.propertiesGridPane.getChildren().remove(this.checkboxVBox); this.moveCompass(0); } this.popOver.hide(); }); this.popOver = new PopOver(); this.popOver.setContentNode(vbox); this.popOver.setCornerRadius(2); this.popOver.setArrowSize(6); this.popOver.setArrowLocation(PopOver.ArrowLocation.TOP_LEFT); this.popOver.setAutoHide(true); this.toggleButton.selectedProperty().addListener((ob, ov, nv) -> { if (nv) { this.popOver.show(this.toggleButton); } else { this.popOver.hide(); } }); this.popOver.showingProperty().addListener((ob, ov, nv) -> { if (!nv && this.toggleButton.isSelected()) { this.toggleButton.setSelected(false); } }); } /** * The the initial mouse coordinates for scrolling. * * @param e Mouse event for capturing mouse location. */ private void setInitialMouseScroll(final MouseEvent e) { this.initialMouseScrollX = e.getSceneX(); this.initialMouseScrollY = e.getSceneY(); } /** * The the initial mouse coordinates for dragging. * * @param e Mouse event for capturing mouse location. */ private void setInitialMouseDrag(final MouseEvent e) { this.initialMouseDragX = e.getSceneX(); this.initialMouseDragY = e.getSceneY(); } /** * On mouse entered event. * * @param e The mouse event. */ @FXML private void onMouseEntered(final MouseEvent e) { this.setInitialMouseScroll(e); } /** * On mouse pressed event. * * @param e The mouse event. */ @FXML private void onMousePressed(final MouseEvent e) { this.setInitialMouseDrag(e); this.setInitialMouseScroll(e); this.chart.requestFocus(); } /** * On mouse release event. * * @param e The mouse event. */ @FXML private void onMouseReleased(final MouseEvent e) { this.setInitialMouseScroll(e); } /** * On mouse moved event. * * @param e The mouse event. */ @FXML private void onMouseMoved(final MouseEvent e) { this.setInitialMouseScroll(e); } /** * On mouse clicked event. * * @param e The mouse event. */ @FXML private void onMouseClicked(final MouseEvent e) { this.setInitialMouseScroll(e); if (e.getClickCount() == 2) { this.chart.zoom(Math.pow(ZOOM_IN, 15), e.getSceneX(), e.getSceneY()); } } /** * On mouse dragged event. * * @param e The mouse event. */ @FXML private void onMouseDragged(final MouseEvent e) { double x = e.getSceneX(); double y = e.getSceneY(); this.chart.pan(x - this.initialMouseDragX, y - this.initialMouseDragY); this.setInitialMouseScroll(e); this.setInitialMouseDrag(e); } /** * On scroll event. * * @param e The scroll event. */ @FXML private void onScroll(final ScrollEvent e) { double factor = (e.getDeltaY() < 0) ? ZOOM_IN : ZOOM_OUT; this.chart.zoom( factor, this.initialMouseScrollX, this.initialMouseScrollY ); } /** * On zoom event. * * @param e The zoom event. */ @FXML private void onZoom(final ZoomEvent e) { this.chart.zoom( e.getZoomFactor(), this.initialMouseScrollX, this.initialMouseScrollY ); } /** * On rotate event. * * @param e The rotate event. */ @FXML private void onRotate(final RotateEvent e) { this.chart.rotate( e.getAngle(), this.initialMouseScrollX, this.initialMouseScrollY ); this.compassTransform.prependRotation(e.getAngle(), 4, 40); } /** * On key pressed event. * * @param e The key event. */ @FXML private void onKeyPressed(final KeyEvent e) { switch (e.getCode()) { case UP: case K: case W: this.pointer++; this.chart.pan(0, 15); e.consume(); break; case DOWN: case J: case S: this.pointer--; this.chart.pan(0, -15); e.consume(); break; case RIGHT: case L: case D: this.chart.pan(-15, 0); e.consume(); break; case LEFT: case H: case A: this.chart.pan(15, 0); e.consume(); break; case PLUS: case EQUALS: this.chart.zoom(Math.pow(ZOOM_IN, 8)); e.consume(); break; case MINUS: case UNDERSCORE: this.chart.zoom(Math.pow(ZOOM_OUT, 8)); e.consume(); break; case Q: this.chart.rotate(-10); this.compassTransform.prependRotation(-10, 4, 40); e.consume(); break; case E: this.chart.rotate(10); this.compassTransform.prependRotation(10, 4, 40); e.consume(); break; default: return; } } /** * Zoom in. */ @FXML private void zoomIn() { this.chart.zoom(Math.pow(ZOOM_IN, 8)); } /** * Zoom out. */ @FXML private void zoomOut() { this.chart.zoom(Math.pow(ZOOM_OUT, 8)); } /** * Is activated through input from the user looking for the address. * Found in textfield addressFrom. */ @FXML private void findAddress() { if (autocPopOver.isShowing()) { Button b = (Button) this.suggestionVBox.getChildren().get(this.pointer); String input = b.getText(); addressFrom.setText(b.getText()); if (input == null) { return; } input = input.trim(); if (input.isEmpty()) { return; } Address startAddress = Address.parse(input); if (startAddress == null) { return; } Node node = this.addresses.find(startAddress); if (node != null) { this.chart.center(node, 2.5); this.chart.setPointer(node); } autocPopOver.hide(); } else { // Dialog "The address does not exist." } } /** * Takes the input from addressFrom and addressTo. */ @FXML private void findRoute() { if (!this.addressFrom.getText().trim().equals("") && !this.addressTo.getText().trim().equals("")) { Address startAddress = Address.parse(this.addressFrom.getText()); Address endAddress = Address.parse(this.addressTo.getText()); Node startPosition = this.addresses.find(startAddress); Node endPosition = this.addresses.find(endAddress); System.out.println("X: " + startPosition.x() + " " + "Y: " + startPosition.y()); System.out.println("X: " + endPosition.x() + " " + "Y: " + endPosition.y()); } this.propertiesGridPane.getChildren().add(this.directionsScrollPane); this.moveCompass(400); int stack = 30; for (int i = 0; i < stack; i++) { HBox hbox = new HBox(2); hbox.getStyleClass().add("bottomBorder"); hbox.setPrefWidth(500); Label icon = new Label("\uf10c"); icon.getStyleClass().add("icon"); icon.setPrefWidth(40); icon.setAlignment(Pos.CENTER); Label label = new Label("Turn right at next left"); hbox.getChildren().addAll(icon, label); this.directionsVBox.getChildren().add(hbox); } } /** * Hides the route description VBox. */ public void hideDirections() { this.propertiesGridPane.getChildren().remove(this.directionsScrollPane); this.moveCompass(0); } /** * Hides the Points of Interest VBox. */ public void hidePOI() { this.checkboxVBox.setVisible(false); this.propertiesGridPane.getChildren().remove(this.checkboxVBox); this.moveCompass(0); } /** * Moves the compass VBox relative to BOTTOM_LEFT. * @param x how much to move compass along x-axis [px]. */ public void moveCompass(final double x) { this.compassVBox.setTranslateX(x); } /** * Will reset the compass, so it points north. */ @FXML private void compassReset() { //to be continued } /** * Swap the text of the from and to address inputs. */ @FXML private void swapTextFields() { String from = this.addressFrom.getText(); String to = this.addressTo.getText(); this.addressFrom.setText(to); this.addressTo.setText(from); } /** * Shows the route between a and b by car. */ @FXML private void routeByCar() { System.out.println("Route by car"); } /** * Shows the rout between a and b by foot or bicycle. */ @FXML private void routeByFoot() { System.out.println("Route by foot"); } /** * Sets the text of scaleIndicator. * @param text the text to be set in scale. */ private void setScaleText(final String text) { this.scaleIndicatorLabel.setText(text); } /** * Sets the length of the scaleIndicator. * @param length how wide the scale is [px]. */ private void setScaleLenght(final double length) { this.scaleIndicatorLabel.setPrefWidth(length); } }
Catching keyevent on the suggestion popover but counter will not increase.
src/main/java/dk/itu/kelvin/controller/ChartController.java
Catching keyevent on the suggestion popover but counter will not increase.
<ide><path>rc/main/java/dk/itu/kelvin/controller/ChartController.java <ide> package dk.itu.kelvin.controller; <ide> <ide> // JavaFX utilities <add>import javafx.scene.input.*; <ide> import javafx.util.Duration; <ide> <ide> // JavaFX application utilities <ide> <ide> // JavaFX scene utilities <ide> import javafx.geometry.Pos; <add> <add>// JavaFX events <add>import javafx.event.EventHandler; <ide> <ide> // JavaFX layout <ide> import javafx.scene.layout.GridPane; <ide> import javafx.scene.shape.Path; <ide> <ide> // JavaFX input <del>import javafx.scene.input.KeyEvent; <del>import javafx.scene.input.MouseEvent; <del>import javafx.scene.input.RotateEvent; <del>import javafx.scene.input.ScrollEvent; <del>import javafx.scene.input.ZoomEvent; <ide> <ide> // JavaFX transformations <ide> import javafx.scene.transform.Affine; <ide> Bounds bounds = tf.localToScreen(tf.getBoundsInParent()); <ide> <ide> this.suggestionVBox = new VBox(this.suggestions.size()); <add> this.suggestionVBox.setOnKeyPressed(new EventHandler<KeyEvent>() { <add> public void handle(final KeyEvent e) { <add> moveHighlight(e); <add> } <add> }); <ide> this.suggestionVBox.setPrefWidth(bounds.getWidth() + 27); <ide> <ide> for (String suggestion : this.suggestions) { <ide> this.suggestionVBox.getChildren().add(l); <ide> } <ide> <del> if (suggestions.size() > 0) { <add> if (this.suggestions.size() > 0) { <ide> Button s = (Button) this.suggestionVBox.getChildren().get(0); <ide> s.getStyleClass().add("highlight"); <ide> this.pointer = 0; <ide> ); <ide> } <ide> }); <add> } <add> <add> /** <add> * To move the highlight up and down in the suggestion popover. <add> * @param e the keyevent. <add> */ <add> public void moveHighlight(final KeyEvent e) { <add> if (e.getCode() == KeyCode.UP && this.pointer > 0) { <add> this.pointer--; <add> e.consume(); <add> System.out.println(this.pointer); <add> } <add> if (e.getCode() == (KeyCode.DOWN) && this.pointer < 5) { <add> this.pointer++; <add> e.consume(); <add> System.out.println(this.pointer); <add> } <ide> } <ide> <ide> /** <ide> case UP: <ide> case K: <ide> case W: <del> this.pointer++; <ide> this.chart.pan(0, 15); <ide> e.consume(); <ide> break; <ide> case DOWN: <ide> case J: <ide> case S: <del> this.pointer--; <ide> this.chart.pan(0, -15); <ide> e.consume(); <ide> break; <ide> */ <ide> @FXML <ide> private void findAddress() { <del> if (autocPopOver.isShowing()) { <add> if (this.autocPopOver.isShowing()) { <ide> Button b = (Button) this.suggestionVBox.getChildren().get(this.pointer); <ide> String input = b.getText(); <del> addressFrom.setText(b.getText()); <add> this.addressFrom.setText(b.getText()); <ide> <ide> if (input == null) { <ide> return; <ide> this.chart.setPointer(node); <ide> } <ide> <del> autocPopOver.hide(); <add> this.autocPopOver.hide(); <ide> } <del> else { <add> /*else { <ide> // Dialog "The address does not exist." <del> } <add> }*/ <ide> } <ide> <ide> /**
JavaScript
mit
339ad9e45347e95efcb45644be04a641634d2405
0
fusioncharts/redraphael,fusioncharts/redraphael,fusioncharts/redraphael
/**! * RedRaphael 1.0.0 - JavaScript Vector Library * Copyright (c) 2012-2013 FusionCharts Technologies <http://www.fusioncharts.com> * * Raphael 2.1.0 * Copyright (c) 2008-2012 Dmitry Baranovskiy <http://raphaeljs.com> * Copyright © 2008-2012 Sencha Labs <http://sencha.com> * * Licensed under the MIT license. */ import eve from './eve/eve'; import extend, {merge, getArrayCopy, BLANK} from './raphael.lib'; var _win = (typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : null); /*\ * Raphael [ method ] ** * Creates a canvas object on which to draw. * You must do this first, as all future calls to drawing methods * from this instance will be bound to this canvas. > Parameters ** - container (HTMLElement|string) DOM element or its ID which is going to be a parent for drawing surface - width (number) - height (number) - callback (function) #optional callback function which is going to be executed in the context of newly created paper * or - x (number) - y (number) - width (number) - height (number) - callback (function) #optional callback function which is going to be executed in the context of newly created paper * or - all (array) (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>}). See @Paper.add. - callback (function) #optional callback function which is going to be executed in the context of newly created paper * or - onReadyCallback (function) function that is going to be called on DOM ready event. You can also subscribe to this event via Eve’s “DOMLoad” event. In this case method returns `undefined`. = (object) @Paper > Usage | // Each of the following examples create a canvas | // that is 320px wide by 200px high. | // Canvas is created at the viewport’s 10,50 coordinate. | var paper = Raphael(10, 50, 320, 200); | // Canvas is created at the top left corner of the #notepad element | // (or its top right corner in dir="rtl" elements) | var paper = Raphael(document.getElementById("notepad"), 320, 200); | // Same as above | var paper = Raphael("notepad", 320, 200); | // Image dump | var set = Raphael(["notepad", 320, 200, { | type: "rect", | x: 10, | y: 10, | width: 25, | height: 25, | stroke: "#f00" | }, { | type: "text", | x: 30, | y: 40, | text: "Dump" | }]); \*/ function R(first) { var args, arg, f; // Code commented as resources will now be referenced using relative URLs. // @todo Remove once we have ascertained that there are no issues in any environment. // if (R._url) { // Reinitialize URLs to be safe from pop state event // R._url = (R._g && R._g.win || _window).location.href.replace(/#.*?$/, ""); // } // If the URL is undefined only then initialize the URL with blank in order to support // both relative as well as absolute URLs // @todo Need to track the URL change and modify the URL for the gradient and other elements dynamically. if (R._url === undefined) { R._url = ""; } if (R.is(first, "function")) { return loaded ? first() : eve.on("raphael.DOMload", first); } else if (R.is(first, array)) { return R._engine.create[apply](R, first.splice(0, 3 + R.is(first[0], nu))).add(first); } else { arg = getArrayCopy(arguments); args = Array.prototype.slice.call(arg, 0); if (R.is(args[args.length - 1], "function")) { f = args.pop(); return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function() { f.call(R._engine.create[apply](R, args)); }); } else { return R._engine.create[apply](R, arguments); } } } R.upgrade = "1.0.0"; R.version = "2.1.0"; R.eve = eve; // RedRaphael = R; var loaded, undef, E = "", S = " ", has = "hasOwnProperty", apply = "apply", concat = "concat", nu = "number", string = "string", array = "array", object = "object", finite = "finite", split = "split", none = "none", black = "#000", arraySlice = Array.prototype.slice, arraySplice = Array.prototype.splice, hasPrototypeBug = (function () { var a = function () {}; return a.hasOwnProperty("prototype"); }()), g = { doc: _win.document, win: _win }, doc = g.doc, win = g.win, supportsTouch = R.supportsTouch = "createTouch" in doc, // The devices which both touch and pointer. supportsOnlyTouch = R.supportsOnlyTouch = (supportsTouch && !(win.navigator.maxTouchPoints || win.navigator.msMaxTouchPoints)), CustomAttributes = function () { /*\ * Raphael.ca [ property (object) ] ** * Shortcut for @Raphael.customAttributes \*/ /*\ * Raphael.customAttributes [ property (object) ] ** * If you have a set of attributes that you would like to represent * as a function of some number across all papers you can do it * easily with custom attributes: > Usage | Raphael.customAttributes.hue = function (num) { | num = num % 1; | return {fill: "hsb(" + num + ", 0.75, 1)"}; | }; | // Custom attribute “hue” will change fill | // to be given hue with fixed saturation and brightness. | // Now you can use it like this: | var c = paper.circle(10, 10, 10).attr({hue: .45}); | // or even like this: | c.animate({hue: 1}, 1e3); | | // You could also create custom attribute | // with multiple parameters: | Raphael.customAttributes.hsb = function (h, s, b) { | return {fill: "hsb(" + [h, s, b].join(",") + ")"}; | }; | c.attr({hsb: "0.5 .8 1"}); | c.animate({hsb: [1, 0, 0.5]}, 1e3); \*/ }, caproto = R.ca = R.customAttributes = CustomAttributes.prototype, Paper = function () { /*\ * Paper.ca [ property (object) ] ** * Shortcut for @Paper.customAttributes \*/ /*\ * Paper.customAttributes [ property (object) ] ** * If you have a set of attributes that you would like to represent * as a function of some number you can do it easily with custom attributes: > Usage | paper.customAttributes.hue = function (num) { | num = num % 1; | return {fill: "hsb(" + num + ", 0.75, 1)"}; | }; | // Custom attribute “hue” will change fill | // to be given hue with fixed saturation and brightness. | // Now you can use it like this: | var c = paper.circle(10, 10, 10).attr({hue: .45}); | // or even like this: | c.animate({hue: 1}, 1e3); | | // You could also create custom attribute | // with multiple parameters: | paper.customAttributes.hsb = function (h, s, b) { | return {fill: "hsb(" + [h, s, b].join(",") + ")"}; | }; | c.attr({hsb: "0.5 .8 1"}); | c.animate({hsb: [1, 0, 0.5]}, 1e3); \*/ this.ca = this.customAttributes = new CustomAttributes(); this._CustomAttributes = function () {}; this._CustomAttributes.prototype = this.ca; this._elementsById = {}; this.id = R._oid++; eve('raphael.new', this); }, /*\ * Raphael.fn [ property (object) ] ** * You can add your own method to the canvas. For example if you want to draw a pie chart, * you can create your own pie chart function and ship it as a Raphaël plugin. To do this * you need to extend the `Raphael.fn` object. You should modify the `fn` object before a * Raphaël instance is created, otherwise it will take no effect. Please note that the * ability for namespaced plugins was removed in Raphael 2.0. It is up to the plugin to * ensure any namespacing ensures proper context. > Usage | Raphael.fn.arrow = function (x1, y1, x2, y2, size) { | return this.path( ... ); | }; | // or create namespace | Raphael.fn.mystuff = { | arrow: function () {…}, | star: function () {…}, | // etc… | }; | var paper = Raphael(10, 10, 630, 480); | // then use it | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"}); | paper.mystuff.arrow(); | paper.mystuff.star(); \*/ paperproto = R.fn = Paper.prototype = R.prototype, // Add new dragstart, dragmove and dragend events in order to support touch drag in both touch and hybrid devices events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel dragstart dragmove dragend"[split](S), touchMap = R._touchMap = { mousedown: "touchstart", mousemove: "touchmove", mouseup: "touchend" }, dragEventMap = R._dragEventMap = { dragstart: "mousedown", dragmove: "mousemove", dragend: "mouseup" }, Str = String, toFloat = win.parseFloat, toInt = win.parseInt, math = Math, mmax = math.max, mmin = math.min, abs = math.abs, pow = math.pow, mathCos = math.cos, mathSin = math.sin, mathSqrt = math.sqrt, round = math.round, PI = math.PI, deg2rad = PI / 180, rad2deg = 180 / PI, lowerCase = Str.prototype.toLowerCase, upperCase = Str.prototype.toUpperCase, objectToString = Object.prototype.toString, separator = /[, ]+/, formatrg = /\{(\d+)\}/g, colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i, bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/, commaSpaces = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/, p2s = /,?([achlmqrstvxz]),?/gi, pathCommand = /([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig, tCommand = /([rstm])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig, pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/ig, isnan = { "NaN": 1, "Infinity": 1, "-Infinity": 1 }, hsrg = { hs: 1, rg: 1 }, availableAttrs = R._availableAttrs = { "arrow-end": none, "arrow-start": none, blur: 0, "clip-rect": "0 0 1e9 1e9", "clip-path": E, cursor: "default", cx: 0, cy: 0, fill: "#fff", "fill-opacity": 1, font: '10px "Arial"', "font-family": '"Arial"', "font-size": "10", "font-style": "normal", "font-weight": 400, gradient: 0, height: 0, href: "about:blank", "letter-spacing": 0, "line-height": 12, "vertical-align": "middle", opacity: 1, path: "M0,0", r: 0, rx: 0, ry: 0, src: E, stroke: "#000", "stroke-dasharray": E, "stroke-linecap": "butt", "stroke-linejoin": "butt", "stroke-miterlimit": 0, "stroke-opacity": 1, "stroke-width": 1, target: "_blank", "text-anchor": "middle", "visibility": E, title: E, transform: E, rotation: 0, width: 0, x: 0, y: 0, "shape-rendering": "auto", alpha: nu }, availableAnimAttrs = R._availableAnimAttrs = { blur: nu, "clip-rect": "csv", "clip-path": "path", cx: nu, cy: nu, fill: "colour", "fill-opacity": nu, "font-size": nu, height: nu, opacity: nu, path: "path", r: nu, rx: nu, ry: nu, stroke: "colour", "stroke-opacity": nu, "stroke-width": nu, transform: "transform", width: nu, x: nu, y: nu, // Required for pie 3d "color": "colour", "borderColor": "colour", "borderWidth": nu, alpha: nu, "text-bound": "text-bound" }, eldata = {}, sortByNumber = function(a, b) { return toFloat(a) - toFloat(b); }, fun = function() { }, pipe = function(x) { return x; }, rectPath = R._rectPath = function(x, y, w, h, r) { if (r) { return [["M", x + r, y], ["l", w - r * 2, 0], ["a", r, r, 0, 0, 1, r, r], ["l", 0, h - r * 2], ["a", r, r, 0, 0, 1, -r, r], ["l", r * 2 - w, 0], ["a", r, r, 0, 0, 1, -r, -r], ["l", 0, r * 2 - h], ["a", r, r, 0, 0, 1, r, -r], ["z"]]; } return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]]; }, ellipsePath = function(x, y, rx, ry) { if (ry == null) { ry = rx; } return [["M", x, y], ["m", 0, -ry], ["a", rx, ry, 0, 1, 1, 0, 2 * ry], ["a", rx, ry, 0, 1, 1, 0, -2 * ry], ["z"]]; }, getPath = R._getPath = { group: function() { return false; }, path: function(el) { return el.attr("path"); }, circle: function(el) { var a = el.attrs; return ellipsePath(a.cx, a.cy, a.r); }, ellipse: function(el) { var a = el.attrs; return ellipsePath(a.cx, a.cy, a.rx, a.ry); }, rect: function(el) { var a = el.attrs; return rectPath(a.x, a.y, a.width, a.height, a.r); }, image: function(el) { var a = el.attrs; return rectPath(a.x, a.y, a.width, a.height); }, text: function(el) { var bbox = el._getBBox(); return rectPath(bbox.x, bbox.y, bbox.width, bbox.height); } }, /*\ * Raphael.mapPath [ method ] ** * Transform the path string with given matrix. > Parameters - path (string) path string - matrix (object) see @Matrix = (string) transformed path string \*/ mapPath = R.mapPath = function(path, matrix) { if (!matrix) { return path; } var x, y, i, j, ii, jj, pathi; path = path2curve(path); for (i = 0, ii = path.length; i < ii; i++) { pathi = path[i]; for (j = 1, jj = pathi.length; j < jj; j += 2) { x = matrix.x(pathi[j], pathi[j + 1]); y = matrix.y(pathi[j], pathi[j + 1]); pathi[j] = x; pathi[j + 1] = y; } } return path; }, lastArgIfGroup = R._lastArgIfGroup = function (args, clear) { var last = args.length - 1, arg = args[last]; if (arg && (arg.constructor === R.el.constructor) && arg.type === 'group') { if (clear) { args[last] = undefined; delete args[last]; arraySplice.call(args, last, 1); } return arg; } }, serializeArgs = R._serializeArgs = function (args) { var arg0 = args[0], pathString, attrs, i, ii; if (R.is(arg0, 'object') && !R.is(arg0, 'array') && arg0.type !== 'group') { attrs = arg0; if (arg0.path) { pathString = arg0.path; pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E); } for (i = 1, ii = arguments.length; i < ii; i += 2) { if (!attrs[arguments[i]]) { attrs[arguments[i]] = arguments[i + 1]; } } } else { attrs = {}; for (i = 1, ii = arguments.length; i < ii; i += 2) { attrs[arguments[i]] = args[(i-1) / 2] || arguments[i+1]; } } return attrs; }, /*\ * Raphael.is [ method ] ** * Handfull replacement for `typeof` operator. > Parameters - o (…) any object or primitive - type (string) name of the type, i.e. “string”, “function”, “number”, etc. = (boolean) is given value is of given type \*/ is = R.is = function(o, type) { type = lowerCase.call(type); if (type == finite) { return !isnan[has](+o); } if (type == array) { return o instanceof Array; } if (type === 'object' && (o === undef || o === null)) { return false; } return (type == "null" && o === null) || (type == typeof o && o !== null) || (type == object && o === Object(o)) || (type == "array" && Array.isArray && Array.isArray(o)) || objectToString.call(o).slice(8, -1).toLowerCase() == type; }, /*\ * Raphael.clone [ method ] ** * Returns a recursively cloned version of an object. \*/ clone = R.clone = hasPrototypeBug ? function (obj) { if (Object(obj) !== obj) { return obj; } var res = new obj.constructor; for (var key in obj) if (key !== "prototype" && obj[has](key)) { res[key] = clone(obj[key]); } return res; } : function (obj) { if (Object(obj) !== obj) { return obj; } var res = new obj.constructor; for (var key in obj) if (obj[has](key)) { res[key] = clone(obj[key]); } return res; }, Node = _win.Node; //Adding pollyfill for IE11 if (Node && !Node.prototype.contains) { Node.prototype.contains = function(el){ while (el = el.parentNode) { if (el === this) return true; } return false; } }; R._g = g; R.merge = merge; R.extend = extend; /* * Raphael.createUUID [ method ] ** * Returns RFC4122, version 4 ID */ R.createUUID = (function(uuidRegEx, uuidReplacer) { return function() { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase(); }; })(/[xy]/g, function(c) { var r = math.random() * 16 | 0, v = c == "x" ? r : (r & 3 | 8); return v.toString(16); }); R._radial_gradient = /^x?r(?:\(([^\)]*?)\))?/; R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i; /* * Raphael.getElementID [ method ] ** * Add 'rr-' prefix before created IDs */ R.getElementID = function (id) { return "rr-" + id; }; // PriorityQueue Function Declaration function PriorityQueue(comparator) { this._comparator = comparator; this._elements = []; } PriorityQueue.prototype.isEmpty = function() { return this.size() === 0; }; PriorityQueue.prototype.peek = function() { if (this.isEmpty()) return null; return this._elements[0]; }; PriorityQueue.prototype.deq = function() { var first = this.peek(); var last = this._elements.pop(); var size = this.size(); if (size === 0) return first; this._elements[0] = last; var current = 0; while (current < size) { var largest = current; var left = (2 * current) + 1; var right = (2 * current) + 2; if (left < size && this._compare(left, largest) >= 0) { largest = left; } if (right < size && this._compare(right, largest) >= 0) { largest = right; } if (largest === current) break; this._swap(largest, current); current = largest; } return first; }; PriorityQueue.prototype.enq = function(element) { var size = this._elements.push(element); var current = size - 1; while (current > 0) { var parent = Math.floor((current - 1) / 2); if (this._compare(current, parent) <= 0) break; this._swap(parent, current); current = parent; } return size; }; PriorityQueue.prototype.size = function() { return this._elements.length; }; PriorityQueue.prototype._compare = function(a, b) { return this._comparator(this._elements[a], this._elements[b]); }; PriorityQueue.prototype._swap = function(a, b) { var aux = this._elements[a]; this._elements[a] = this._elements[b]; this._elements[b] = aux; }; /*\ * Raphael.type [ property (string) ] ** * Can be “SVG”, “VML” or empty, depending on browser support. \*/ R.type = (win.ENABLE_RED_CANVAS && (win.CanvasRenderingContext2D || doc.createElement('canvas').getContext)) ? "CANVAS" : (win.SVGAngle || doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML"); if (R.type == "VML") { var d = doc.createElement("div"), b; d.innerHTML = '<v:shape adj="1"/>'; b = d.firstChild; b.style.behavior = "url(#default#VML)"; if (!(b && typeof b.adj == object)) { R.type = E; // return (R.type = E); } d = null; } /*\ * Raphael.svg [ property (boolean) ] ** * `true` if browser supports SVG. \*/ /*\ * Raphael.vml [ property (boolean) ] ** * `true` if browser supports VML. \*/ R.svg = !((R.vml = R.type == "VML") || (R.canvas = R.type == "CANVAS")); R._Paper = Paper; R._id = 0; R._oid = 0; /*\ * Raphael.angle [ method ] ** * Returns angle between two or three points > Parameters - x1 (number) x coord of first point - y1 (number) y coord of first point - x2 (number) x coord of second point - y2 (number) y coord of second point - x3 (number) #optional x coord of third point - y3 (number) #optional y coord of third point = (number) angle in degrees. \*/ R.angle = function (x1, y1, x2, y2, x3, y3) { if (x3 == null) { var x = x1 - x2, y = y1 - y2; if (!x && !y) { return 0; } return (180 + math.atan2(-y, -x) * rad2deg + 360) % 360; } else { return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3); } }; /*\ * Raphael.rad [ method ] ** * Transform angle to radians > Parameters - deg (number) angle in degrees = (number) angle in radians. \*/ R.rad = function (deg) { return deg % 360 * deg2rad; }; /*\ * Raphael.deg [ method ] ** * Transform angle to degrees > Parameters - deg (number) angle in radians = (number) angle in degrees. \*/ R.deg = function (rad) { return rad * rad2deg % 360; }; var toHex = function (color) { if (R.vml) { // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/ var trim = /^\s+|\s+$/g; var bod; try { var docum = new ActiveXObject("htmlfile"); docum.write("<body>"); docum.close(); bod = docum.body; } catch (e) { bod = createPopup().document.body; } var range = bod.createTextRange(); toHex = cacher(function(color) { try { bod.style.color = Str(color).replace(trim, E); var value = range.queryCommandValue("ForeColor"); value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16); return "#" + ("000000" + value.toString(16)).slice(-6); } catch (e) { return none; } }); } else { var i = g.doc.createElement("i"); i.title = "Rapha\xebl Colour Picker"; i.style.display = none; g.doc.body.appendChild(i); toHex = cacher(function(color) { i.style.color = color; return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color"); }); } return toHex(color); }, hsbtoString = function() { return "hsb(" + [this.h, this.s, this.b] + ")"; }, hsltoString = function() { return "hsl(" + [this.h, this.s, this.l] + ")"; }, rgbtoString = function() { return this.hex; }, prepareRGB = function(r, g, b) { if (g == null && is(r, object) && "r" in r && "g" in r && "b" in r) { b = r.b; g = r.g; r = r.r; } if (g == null && is(r, string)) { var clr = R.getRGB(r); r = clr.r; g = clr.g; b = clr.b; } if (r > 1 || g > 1 || b > 1) { r /= 255; g /= 255; b /= 255; } return [r, g, b]; }, packageRGB = function(r, g, b, o) { var rgb = { r: (r *= 255), g: (g *= 255), b: (b *= 255), hex: R.rgb(r, g, b), toString: rgbtoString }; is(o, "finite") && (rgb.opacity = o); return rgb; }; /*\ * Raphael.color [ method ] ** * Parses the color string and returns object with all values for the given color. > Parameters - clr (string) color string in one of the supported formats (see @Raphael.getRGB) = (object) Combined RGB & HSB object in format: o { o r (number) red, o g (number) green, o b (number) blue, o hex (string) color in HTML/CSS format: #••••••, o error (boolean) `true` if string can’t be parsed, o h (number) hue, o s (number) saturation, o v (number) value (brightness), o l (number) lightness o } \*/ R.color = function(clr) { var rgb; if (R.is(clr, object) && "h" in clr && "s" in clr && "b" in clr) { rgb = R.hsb2rgb(clr); clr.r = rgb.r; clr.g = rgb.g; clr.b = rgb.b; clr.hex = rgb.hex; } else if (R.is(clr, object) && "h" in clr && "s" in clr && "l" in clr) { rgb = R.hsl2rgb(clr); clr.r = rgb.r; clr.g = rgb.g; clr.b = rgb.b; clr.hex = rgb.hex; } else { if (R.is(clr, "string")) { clr = R.getRGB(clr); } if (R.is(clr, object) && "r" in clr && "g" in clr && "b" in clr) { rgb = R.rgb2hsl(clr); clr.h = rgb.h; clr.s = rgb.s; clr.l = rgb.l; rgb = R.rgb2hsb(clr); clr.v = rgb.b; } else { clr = { hex: none }; clr.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1; } } clr.toString = rgbtoString; return clr; }; /*\ * Raphael.hsb2rgb [ method ] ** * Converts HSB values to RGB object. > Parameters - h (number) hue - s (number) saturation - v (number) value or brightness = (object) RGB object in format: o { o r (number) red, o g (number) green, o b (number) blue, o hex (string) color in HTML/CSS format: #•••••• o } \*/ R.hsb2rgb = function(h, s, v, o) { if (this.is(h, object) && "h" in h && "s" in h && "b" in h) { v = h.b; s = h.s; h = h.h; o = h.o; } h *= 360; var R, G, B, X, C; h = (h % 360) / 60; C = v * s; X = C * (1 - abs(h % 2 - 1)); R = G = B = v - C; h = ~~h; R += [C, X, 0, 0, X, C][h]; G += [X, C, C, X, 0, 0][h]; B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; /*\ * Raphael.hsl2rgb [ method ] ** * Converts HSL values to RGB object. > Parameters - h (number) hue - s (number) saturation - l (number) luminosity = (object) RGB object in format: o { o r (number) red, o g (number) green, o b (number) blue, o hex (string) color in HTML/CSS format: #•••••• o } \*/ R.hsl2rgb = function(h, s, l, o) { if (this.is(h, object) && "h" in h && "s" in h && "l" in h) { l = h.l; s = h.s; h = h.h; } if (h > 1 || s > 1 || l > 1) { h /= 360; s /= 100; l /= 100; } h *= 360; var R, G, B, X, C; h = (h % 360) / 60; C = 2 * s * (l < .5 ? l : 1 - l); X = C * (1 - abs(h % 2 - 1)); R = G = B = l - C / 2; h = ~~h; R += [C, X, 0, 0, X, C][h]; G += [X, C, C, X, 0, 0][h]; B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; /*\ * Raphael.rgb2hsb [ method ] ** * Converts RGB values to HSB object. > Parameters - r (number) red - g (number) green - b (number) blue = (object) HSB object in format: o { o h (number) hue o s (number) saturation o b (number) brightness o } \*/ R.rgb2hsb = function(r, g, b) { b = prepareRGB(r, g, b); r = b[0]; g = b[1]; b = b[2]; var H, S, V, C; V = mmax(r, g, b); C = V - mmin(r, g, b); H = (C == 0 ? null : V == r ? (g - b) / C : V == g ? (b - r) / C + 2 : (r - g) / C + 4 ); H = ((H + 360) % 6) * 60 / 360; S = C == 0 ? 0 : C / V; return { h: H, s: S, b: V, toString: hsbtoString }; }; /*\ * Raphael.rgb2hsl [ method ] ** * Converts RGB values to HSL object. > Parameters - r (number) red - g (number) green - b (number) blue = (object) HSL object in format: o { o h (number) hue o s (number) saturation o l (number) luminosity o } \*/ R.rgb2hsl = function(r, g, b) { b = prepareRGB(r, g, b); r = b[0]; g = b[1]; b = b[2]; var H, S, L, M, m, C; M = mmax(r, g, b); m = mmin(r, g, b); C = M - m; H = (C == 0 ? null : M == r ? (g - b) / C : M == g ? (b - r) / C + 2 : (r - g) / C + 4); H = ((H + 360) % 6) * 60 / 360; L = (M + m) / 2; S = (C == 0 ? 0 : L < .5 ? C / (2 * L) : C / (2 - 2 * L)); return { h: H, s: S, l: L, toString: hsltoString }; }; R._path2string = function() { return this.join(",").replace(p2s, "$1"); }; var cacher = R._cacher = function (f, scope, postprocessor) { var start = null, end = null, cache = {}, count = 0; function cachedfunction () { var arg = getArrayCopy(arguments), args = arg.join("\u2400"), newEndStr, newEnd, cur, prev, next, nextStr; args = args === '' ? BLANK : args; /****** Cache hit ******/ // If the following condition is true it is a cache hit. if (cache[has](args)) { // cur is the element due to cache hit cur = cache[args]; nextStr = cur.next; // nextStr is the id of next element of cur. prev = cur.prev; // prev is the previous node of the current hit node next = ((nextStr !== null) && cache[nextStr]) || null; // next is the next node of the current hit node // Scope of error: Always check if the start and cur are not same node. // start and cur can be same when same node has back to back cache hits. if (start === cur) { // do nothing. } else if (cache[end] === cur) { // when the cur element is the last element of cache start.next = end; newEndStr = cache[end].next; // Take Id of the next element of the cur element cache[newEndStr].prev = null; // Make it's previous pointer null so that it doesn't point to cur cur.next = null; // taking cur to the front. make it's next point to null, since there is no element ahead of it cur.prev = start; // make it's prev pointer to the present element at the front. start = cache[end]; // start pointer now point to the first element end = newEndStr; // end holds the ID of the last element } else { // when cur element is any element except start and end start.next = args; // present start node's next pointer should point to the cur node cur.prev = start; // cur node's prev pointer now points to the present start, making the present start to 2nd position cur.next = null; // since cur is in front, no one should be ahead of it. hence next = null prev.next = nextStr; // cur's prev node should point to cur's next node next.prev = prev; // cur's next node should point to cur's prev node start = cur; // start point to the cur node } return start.item; } /******* Cache miss *******/ // Else, it is a cache miss. /* ----- deletion process begins here ----- * deletion takes place if cache is full * */ if (count > 1e3) { // Take the second last element newEndStr = cache[end].next; newEnd = cache[newEndStr]; // prev pointer of the second last element should be deleted.(Beware! Not doing this step will lead to memory leak) newEnd.prev = null; // clear the pointers of the node to be deleted cache[end].next = null; // delete the node delete cache[end]; // update the end pointer end = newEndStr; count--; // decrement the counter } /* ----- insertion process begins here ----- */ // create a new node cache[args] = { next: null, prev: start, // newNode's prev pointer should point to the present start item: postprocessor ? postprocessor(f[apply](scope, arg)) : f[apply](scope, arg) }; // If start is present(start can be null if it is first node), point start.next to the new object if (start !== null) { start.next = args; // The present start node will fall second. } // finally assign start to the new node as start always points to the node at front start = cache[args]; // In case newNode is the first node of the cache end will also be null, but it should point to the start. (end === null) && (end = args); count++; return cache[args].item; } return cachedfunction; }; var preload = R._preload = function(src, f) { var img = doc.createElement("img"); img.style.cssText = "position:absolute;left:-9999em;top:-9999em"; img.onload = function() { f.call(this); this.onload = null; doc.body.removeChild(this); }; img.onerror = function() { doc.body.removeChild(this); }; doc.body.appendChild(img); img.src = src; }; function clrToString() { return this.hex; } /*\ * Raphael.getRGB [ method ] ** * Parses colour string as RGB object > Parameters - colour (string) colour string in one of formats: # <ul> # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li> # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li> # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li> # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200,&nbsp;100,&nbsp;0)</code>”)</li> # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%,&nbsp;175%,&nbsp;0%)</code>”)</li> # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5,&nbsp;0.25,&nbsp;1)</code>”)</li> # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li> # <li>hsl(•••, •••, •••) — same as hsb</li> # <li>hsl(•••%, •••%, •••%) — same as hsb</li> # </ul> = (object) RGB object in format: o { o r (number) red, o g (number) green, o b (number) blue o hex (string) color in HTML/CSS format: #••••••, o error (boolean) true if string can’t be parsed o } \*/ R.getRGB = cacher(function(colour) { var opacity, res, red, green, blue, t, values, rgb; colour && is(colour, 'object') && "opacity" in colour && (opacity = colour.opacity); if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) { return { r: -1, g: -1, b: -1, hex: none, error: 1, toString: clrToString }; } if (colour == none) { return { r: -1, g: -1, b: -1, hex: none, toString: clrToString }; } !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() === "#") && (colour = toHex(colour)); if ((rgb = colour.match(colourRegExp))) { if (rgb[2]) { blue = toInt(rgb[2].substring(5), 16); green = toInt(rgb[2].substring(3, 5), 16); red = toInt(rgb[2].substring(1, 3), 16); } if (rgb[3]) { blue = toInt((t = rgb[3].charAt(3)) + t, 16); green = toInt((t = rgb[3].charAt(2)) + t, 16); red = toInt((t = rgb[3].charAt(1)) + t, 16); } if (rgb[4]) { values = rgb[4][split](commaSpaces); red = toFloat(values[0]); values[0].slice(-1) == "%" && (red *= 2.55); green = toFloat(values[1]); values[1].slice(-1) == "%" && (green *= 2.55); blue = toFloat(values[2]); values[2].slice(-1) == "%" && (blue *= 2.55); rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3])); values[3] && values[3].slice(-1) == "%" && (opacity /= 100); } if (rgb[5]) { values = rgb[5][split](commaSpaces); red = toFloat(values[0]); values[0].slice(-1) == "%" && (red *= 2.55); green = toFloat(values[1]); values[1].slice(-1) == "%" && (green *= 2.55); blue = toFloat(values[2]); values[2].slice(-1) == "%" && (blue *= 2.55); (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360); rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3])); values[3] && values[3].slice(-1) == "%" && (opacity /= 100); return R.hsb2rgb(red, green, blue, opacity); } if (rgb[6]) { values = rgb[6][split](commaSpaces); red = toFloat(values[0]); values[0].slice(-1) == "%" && (red *= 2.55); green = toFloat(values[1]); values[1].slice(-1) == "%" && (green *= 2.55); blue = toFloat(values[2]); values[2].slice(-1) == "%" && (blue *= 2.55); (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360); rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3])); values[3] && values[3].slice(-1) == "%" && (opacity /= 100); return R.hsl2rgb(red, green, blue, opacity); } rgb = { r: red, g: green, b: blue, toString: clrToString }; rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1); R.is(opacity, "finite") && (rgb.opacity = opacity); return rgb; } return { r: -1, g: -1, b: -1, hex: none, error: 1, toString: clrToString }; }, R); R.tintshade = cacher(function(colour, percent) { var rgb = R.getRGB(colour), tint, offset = 255; (percent < 0) && (percent *= -1, offset = 0); (percent > 1) && (percent = 1); tint = percent === 0 ? rgb : { r: offset - (offset - rgb.r) * percent, g: offset - (offset - rgb.g) * percent, b: offset - (offset - rgb.b) * percent, toString: clrToString }; tint.hex = R.rgb(tint.r, tint.g, tint.b); rgb.error && (tint.error = rgb.error); if ("opacity" in rgb) { tint.rgba = 'rgba(' + [tint.r, tint.g, tint.b, rgb.opacity].join(',') + ')'; tint.opacity = rgb.opacity; } else { tint.rgba = 'rgb(' + [tint.r, tint.g, tint.b].join(',') + ')'; } return tint; }, R); /*\ * Raphael.hsb [ method ] ** * Converts HSB values to hex representation of the colour. > Parameters - h (number) hue - s (number) saturation - b (number) value or brightness = (string) hex representation of the colour. \*/ R.hsb = cacher(function(h, s, b) { return R.hsb2rgb(h, s, b).hex; }); /*\ * Raphael.hsl [ method ] ** * Converts HSL values to hex representation of the colour. > Parameters - h (number) hue - s (number) saturation - l (number) luminosity = (string) hex representation of the colour. \*/ R.hsl = cacher(function(h, s, l) { return R.hsl2rgb(h, s, l).hex; }); /*\ * Raphael.rgb [ method ] ** * Converts RGB values to hex representation of the colour. > Parameters - r (number) red - g (number) green - b (number) blue = (string) hex representation of the colour. \*/ R.rgb = cacher(function(r, g, b) { return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1); }); /*\ * Raphael.getColor [ method ] ** * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset > Parameters - value (number) #optional brightness, default is `0.75` = (string) hex representation of the colour. \*/ R.getColor = function(value) { var start = this.getColor.start = this.getColor.start || { h: 0, s: 1, b: value || .75 }, rgb = this.hsb2rgb(start.h, start.s, start.b); start.h += .075; if (start.h > 1) { start.h = 0; start.s -= .2; start.s <= 0 && (this.getColor.start = { h: 0, s: 1, b: start.b }); } return rgb.hex; }; /*\ * Raphael.getColor.reset [ method ] ** * Resets spectrum position for @Raphael.getColor back to red. \*/ R.getColor.reset = function() { delete this.start; }; // http://schepers.cc/getting-to-the-point function catmullRom2bezier(crp, z) { var d = []; for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { var p = [ { x: +crp[i - 2], y: +crp[i - 1] }, { x: +crp[i], y: +crp[i + 1] }, { x: +crp[i + 2], y: +crp[i + 3] }, { x: +crp[i + 4], y: +crp[i + 5] } ]; if (z) { if (!i) { p[0] = { x: +crp[iLen - 2], y: +crp[iLen - 1] }; } else if (iLen - 4 == i) { p[3] = { x: +crp[0], y: +crp[1] }; } else if (iLen - 2 == i) { p[2] = { x: +crp[0], y: +crp[1] }; p[3] = { x: +crp[2], y: +crp[3] }; } } else { if (iLen - 4 == i) { p[3] = p[2]; } else if (!i) { p[0] = { x: +crp[i], y: +crp[i + 1] }; } } d.push(["C", (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y ]); } return d; } /*\ * Raphael.parsePathString [ method ] ** * Utility method ** * Parses given path string into an array of arrays of path segments. > Parameters - pathString (string|array) path string or array of segments (in the last case it will be returned straight away) = (array) array of segments. \*/ R.parsePathString = function(pathString) { if (!pathString) { return null; } var pth = paths(pathString); if (pth.arr) { return pathClone(pth.arr); } var paramCounts = { a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0 }, data = []; if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption data = pathClone(pathString); } if (!data.length) { Str(pathString).replace(pathCommand, function(a, b, c) { var params = [], name = b.toLowerCase(); c.replace(pathValues, function(a, b) { b && params.push(+b); }); if (name == "m" && params.length > 2) { data.push([b][concat](params.splice(0, 2))); name = "l"; b = b == "m" ? "l" : "L"; } if (name == "r") { data.push([b][concat](params)); } else while (params.length >= paramCounts[name]) { data.push([b][concat](params.splice(0, paramCounts[name]))); if (!paramCounts[name]) { break; } } }); } data.toString = R._path2string; pth.arr = pathClone(data); return data; }; /*\ * Raphael.parseTransformString [ method ] ** * Utility method ** * Parses given path string into an array of transformations. > Parameters - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away) = (array) array of transformations. \*/ R.parseTransformString = cacher(function(TString) { if (!TString) { return null; } var paramCounts = { r: 3, s: 4, t: 2, m: 6 }, data = []; if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption data = pathClone(TString); } if (!data.length) { Str(TString).replace(tCommand, function(a, b, c) { var params = [], name = lowerCase.call(b); c.replace(pathValues, function(a, b) { b && params.push(+b); }); data.push([b][concat](params)); }); } data.toString = R._path2string; return data; }); // PATHS var paths = function(ps) { var p = paths.ps = paths.ps || {}; if (p[ps]) { p[ps].sleep = 100; } else { p[ps] = { sleep: 100 }; } setTimeout(function() { for (var key in p) if (p[has](key) && key != ps) { p[key].sleep--; !p[key].sleep && delete p[key]; } }); return p[ps]; }; /*\ * Raphael.findDotsAtSegment [ method ] ** * Utility method ** * Find dot coordinates on the given cubic bezier curve at the given t. > Parameters - p1x (number) x of the first point of the curve - p1y (number) y of the first point of the curve - c1x (number) x of the first anchor of the curve - c1y (number) y of the first anchor of the curve - c2x (number) x of the second anchor of the curve - c2y (number) y of the second anchor of the curve - p2x (number) x of the second point of the curve - p2y (number) y of the second point of the curve - t (number) position on the curve (0..1) = (object) point information in format: o { o x: (number) x coordinate of the point o y: (number) y coordinate of the point o m: { o x: (number) x coordinate of the left anchor o y: (number) y coordinate of the left anchor o } o n: { o x: (number) x coordinate of the right anchor o y: (number) y coordinate of the right anchor o } o start: { o x: (number) x coordinate of the start of the curve o y: (number) y coordinate of the start of the curve o } o end: { o x: (number) x coordinate of the end of the curve o y: (number) y coordinate of the end of the curve o } o alpha: (number) angle of the curve derivative at the point o } \*/ R.findDotsAtSegment = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t, t13 = pow(t1, 3), t12 = pow(t1, 2), t2 = t * t, t3 = t2 * t, x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x, y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y, mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x), my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y), nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x), ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y), ax = t1 * p1x + t * c1x, ay = t1 * p1y + t * c1y, cx = t1 * c2x + t * p2x, cy = t1 * c2y + t * p2y, alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI); (mx > nx || my < ny) && (alpha += 180); return { x: x, y: y, m: { x: mx, y: my }, n: { x: nx, y: ny }, start: { x: ax, y: ay }, end: { x: cx, y: cy }, alpha: alpha }; }; /*\ * Raphael.bezierBBox [ method ] ** * Utility method ** * Return bounding box of a given cubic bezier curve > Parameters - p1x (number) x of the first point of the curve - p1y (number) y of the first point of the curve - c1x (number) x of the first anchor of the curve - c1y (number) y of the first anchor of the curve - c2x (number) x of the second anchor of the curve - c2y (number) y of the second anchor of the curve - p2x (number) x of the second point of the curve - p2y (number) y of the second point of the curve * or - bez (array) array of six points for bezier curve = (object) point information in format: o { o min: { o x: (number) x coordinate of the left point o y: (number) y coordinate of the top point o } o max: { o x: (number) x coordinate of the right point o y: (number) y coordinate of the bottom point o } o } \*/ R.bezierBBox = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { if (!R.is(p1x, "array")) { p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y]; } var bbox = curveDim.apply(null, p1x); return { x: bbox.min.x, y: bbox.min.y, x2: bbox.max.x, y2: bbox.max.y, width: bbox.max.x - bbox.min.x, height: bbox.max.y - bbox.min.y }; }; /*\ * Raphael.isPointInsideBBox [ method ] ** * Utility method ** * Returns `true` if given point is inside bounding boxes. > Parameters - bbox (string) bounding box - x (string) x coordinate of the point - y (string) y coordinate of the point = (boolean) `true` if point inside \*/ R.isPointInsideBBox = function(bbox, x, y) { return x >= bbox.x && x <= bbox.x2 && y >= bbox.y && y <= bbox.y2; }; /*\ * Raphael.isBBoxIntersect [ method ] ** * Utility method ** * Returns `true` if two bounding boxes intersect > Parameters - bbox1 (string) first bounding box - bbox2 (string) second bounding box = (boolean) `true` if they intersect \*/ R.isBBoxIntersect = function(bbox1, bbox2) { var i = R.isPointInsideBBox; return i(bbox2, bbox1.x, bbox1.y) || i(bbox2, bbox1.x2, bbox1.y) || i(bbox2, bbox1.x, bbox1.y2) || i(bbox2, bbox1.x2, bbox1.y2) || i(bbox1, bbox2.x, bbox2.y) || i(bbox1, bbox2.x2, bbox2.y) || i(bbox1, bbox2.x, bbox2.y2) || i(bbox1, bbox2.x2, bbox2.y2) || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); }; function base3(t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; } function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { if (z == null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2, n = 12, Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816], Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472], sum = 0; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2, xbase = base3(ct, x1, x2, x3, x4), ybase = base3(ct, y1, y2, y3, y4), comb = xbase * xbase + ybase * ybase; sum += Cvalues[i] * mathSqrt(comb); } return z2 * sum; } function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { return; } var t = 1, step = t / 2, t2 = t - step, l, e = .01; l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); while (abs(l - ll) > e) { step /= 2; t2 += (l < ll ? 1 : -1) * step; l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); } return t2; } function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { if ( mmax(x1, x2) < mmin(x3, x4) || mmin(x1, x2) > mmax(x3, x4) || mmax(y1, y2) < mmin(y3, y4) || mmin(y1, y2) > mmax(y3, y4) ) { return; } var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4), ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4), denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (!denominator) { return; } var px = nx / denominator, py = ny / denominator, px2 = +px.toFixed(2), py2 = + py.toFixed(2); if ( px2 < +mmin(x1, x2).toFixed(2) || px2 > +mmax(x1, x2).toFixed(2) || px2 < +mmin(x3, x4).toFixed(2) || px2 > +mmax(x3, x4).toFixed(2) || py2 < +mmin(y1, y2).toFixed(2) || py2 > +mmax(y1, y2).toFixed(2) || py2 < +mmin(y3, y4).toFixed(2) || py2 > +mmax(y3, y4).toFixed(2) ) { return; } return { x: px, y: py }; } function inter(bez1, bez2) { return interHelper(bez1, bez2); } function interCount(bez1, bez2) { return interHelper(bez1, bez2, 1); } function interHelper(bez1, bez2, justCount) { var bbox1 = R.bezierBBox(bez1), bbox2 = R.bezierBBox(bez2); if (!R.isBBoxIntersect(bbox1, bbox2)) { return justCount ? 0 : []; } var l1 = bezlen.apply(0, bez1), l2 = bezlen.apply(0, bez2), n1 = mmax(~~(l1 / 5), 1), n2 = mmax(~~(l2 / 5), 1), dots1 = [], dots2 = [], xy = {}, res = justCount ? 0 : []; for (var i = 0; i < n1 + 1; i++) { var p = R.findDotsAtSegment.apply(R, bez1.concat(i / n1)); dots1.push({ x: p.x, y: p.y, t: i / n1 }); } for (i = 0; i < n2 + 1; i++) { p = R.findDotsAtSegment.apply(R, bez2.concat(i / n2)); dots2.push({ x: p.x, y: p.y, t: i / n2 }); } for (i = 0; i < n1; i++) { for (var j = 0; j < n2; j++) { var di = dots1[i], di1 = dots1[i + 1], dj = dots2[j], dj1 = dots2[j + 1], ci = abs(di1.x - di.x) < .001 ? "y" : "x", cj = abs(dj1.x - dj.x) < .001 ? "y" : "x", is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y); if (is) { if (xy[is.x.toFixed(4)] == is.y.toFixed(4)) { continue; } xy[is.x.toFixed(4)] = is.y.toFixed(4); var t1 = di.t + abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t), t2 = dj.t + abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t); if (t1 >= 0 && t1 <= 1.001 && t2 >= 0 && t2 <= 1.001) { if (justCount) { res++; } else { res.push({ x: is.x, y: is.y, t1: mmin(t1, 1), t2: mmin(t2, 1) }); } } } } } return res; } /*\ * Raphael.pathIntersection [ method ] ** * Utility method ** * Finds intersections of two paths > Parameters - path1 (string) path string - path2 (string) path string = (array) dots of intersection o [ o { o x: (number) x coordinate of the point o y: (number) y coordinate of the point o t1: (number) t value for segment of path1 o t2: (number) t value for segment of path2 o segment1: (number) order number for segment of path1 o segment2: (number) order number for segment of path2 o bez1: (array) eight coordinates representing beziér curve for the segment of path1 o bez2: (array) eight coordinates representing beziér curve for the segment of path2 o } o ] \*/ R.pathIntersection = function(path1, path2) { return interPathHelper(path1, path2); }; R.pathIntersectionNumber = function(path1, path2) { return interPathHelper(path1, path2, 1); }; function interPathHelper(path1, path2, justCount) { path1 = R._path2curve(path1); path2 = R._path2curve(path2); var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2, res = justCount ? 0 : []; for (var i = 0, ii = path1.length; i < ii; i++) { var pi = path1[i]; if (pi[0] == "M") { x1 = x1m = pi[1]; y1 = y1m = pi[2]; } else { if (pi[0] == "C") { bez1 = [x1, y1].concat(pi.slice(1)); x1 = bez1[6]; y1 = bez1[7]; } else { bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m]; x1 = x1m; y1 = y1m; } for (var j = 0, jj = path2.length; j < jj; j++) { var pj = path2[j]; if (pj[0] == "M") { x2 = x2m = pj[1]; y2 = y2m = pj[2]; } else { if (pj[0] == "C") { bez2 = [x2, y2].concat(pj.slice(1)); x2 = bez2[6]; y2 = bez2[7]; } else { bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m]; x2 = x2m; y2 = y2m; } var intr = interHelper(bez1, bez2, justCount); if (justCount) { res += intr; } else { for (var k = 0, kk = intr.length; k < kk; k++) { intr[k].segment1 = i; intr[k].segment2 = j; intr[k].bez1 = bez1; intr[k].bez2 = bez2; } res = res.concat(intr); } } } } } return res; } /*\ * Raphael.isPointInsidePath [ method ] ** * Utility method ** * Returns `true` if given point is inside a given closed path. > Parameters - path (string) path string - x (number) x of the point - y (number) y of the point = (boolean) true, if point is inside the path \*/ R.isPointInsidePath = function(path, x, y) { var bbox = R.pathBBox(path); return R.isPointInsideBBox(bbox, x, y) && ((interPathHelper(path, [["M", x, y], ["H", bbox.x2 + 10]], 1) % 2 == 1) || (interPathHelper(path, [["M", x, y], ["V", bbox.y2 + 10]], 1) % 2 == 1)) }; R._removedFactory = function(methodname) { return function() { eve("raphael.log", null, "Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object", methodname); }; }; /*\ * Raphael.pathBBox [ method ] ** * Utility method ** * Return bounding box of a given path > Parameters - path (string) path string = (object) bounding box o { o x: (number) x coordinate of the left top point of the box o y: (number) y coordinate of the left top point of the box o x2: (number) x coordinate of the right bottom point of the box o y2: (number) y coordinate of the right bottom point of the box o width: (number) width of the box o height: (number) height of the box o cx: (number) x coordinate of the center of the box o cy: (number) y coordinate of the center of the box o } \*/ var pathDimensions = R.pathBBox = function(path) { var pth = paths(path); if (!path) { return { x: 0, y: 0, width: 0, height: 0, x2: 0, y2: 0 }; } path = path2curve(path); var x = 0, y = 0, X = [], Y = [], p; for (var i = 0, ii = path.length; i < ii; i++) { p = path[i]; if (p[0] == "M") { x = p[1]; y = p[2]; X.push(x); Y.push(y); } else { var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]); X = X[concat](dim.min.x, dim.max.x); Y = Y[concat](dim.min.y, dim.max.y); x = p[5]; y = p[6]; } } var xmin = mmin[apply](0, X), ymin = mmin[apply](0, Y), xmax = mmax[apply](0, X), ymax = mmax[apply](0, Y), bb = { x: xmin, y: ymin, x2: xmax, y2: ymax, width: xmax - xmin, height: ymax - ymin }; pth.bbox = clone(bb); return bb; }, pathClone = function(pathArray) { var res = clone(pathArray); res.toString = R._path2string; return res; }, pathToRelative = R._pathToRelative = function(pathArray) { var pth = paths(pathArray); if (pth.rel) { return pathClone(pth.rel); } if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption pathArray = R.parsePathString(pathArray); } var res = [], x = 0, y = 0, mx = 0, my = 0, start = 0; if (pathArray[0][0] == "M") { x = pathArray[0][1]; y = pathArray[0][2]; mx = x; my = y; start++; res.push(["M", x, y]); } for (var i = start, ii = pathArray.length; i < ii; i++) { var r = res[i] = [], pa = pathArray[i]; if (pa[0] != lowerCase.call(pa[0])) { r[0] = lowerCase.call(pa[0]); switch (r[0]) { case "a": r[1] = pa[1]; r[2] = pa[2]; r[3] = pa[3]; r[4] = pa[4]; r[5] = pa[5]; r[6] = +(pa[6] - x).toFixed(3); r[7] = +(pa[7] - y).toFixed(3); break; case "v": r[1] = +(pa[1] - y).toFixed(3); break; case "m": mx = pa[1]; my = pa[2]; default: for (var j = 1, jj = pa.length; j < jj; j++) { r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3); } } } else { r = res[i] = []; if (pa[0] == "m") { mx = pa[1] + x; my = pa[2] + y; } for (var k = 0, kk = pa.length; k < kk; k++) { res[i][k] = pa[k]; } } var len = res[i].length; switch (res[i][0]) { case "z": x = mx; y = my; break; case "h": x += +res[i][len - 1]; break; case "v": y += +res[i][len - 1]; break; default: x += +res[i][len - 2]; y += +res[i][len - 1]; } } res.toString = R._path2string; pth.rel = pathClone(res); return res; }, pathToAbsolute = R._pathToAbsolute = function(pathArray) { var pth = paths(pathArray), res; if (pth.abs) { return pathClone(pth.abs); } if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption pathArray = R.parsePathString(pathArray); } if (!pathArray || !pathArray.length) { res = [["M", 0, 0]]; res.toString = R._path2string; return res; } var x = 0, y = 0, mx = 0, my = 0, start = 0; res = []; if (pathArray[0][0] == "M") { x = +pathArray[0][1]; y = +pathArray[0][2]; mx = x; my = y; start++; res[0] = ["M", x, y]; } var crz = pathArray.length == 3 && pathArray[0][0] == "M" && pathArray[1][0].toUpperCase() == "R" && pathArray[2][0].toUpperCase() == "Z"; for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { res.push(r = []); pa = pathArray[i]; if (pa[0] != upperCase.call(pa[0])) { r[0] = upperCase.call(pa[0]); switch (r[0]) { case "A": r[1] = pa[1]; r[2] = pa[2]; r[3] = pa[3]; r[4] = pa[4]; r[5] = pa[5]; r[6] = +(pa[6] + x); r[7] = +(pa[7] + y); break; case "V": r[1] = +pa[1] + y; break; case "H": r[1] = +pa[1] + x; break; case "R": var dots = [x, y][concat](pa.slice(1)); for (var j = 2, jj = dots.length; j < jj; j++) { dots[j] = +dots[j] + x; dots[++j] = +dots[j] + y; } res.pop(); res = res[concat](catmullRom2bezier(dots, crz)); break; case "M": mx = +pa[1] + x; my = +pa[2] + y; default: for (j = 1, jj = pa.length; j < jj; j++) { r[j] = +pa[j] + ((j % 2) ? x : y); } } } else if (pa[0] == "R") { dots = [x, y][concat](pa.slice(1)); res.pop(); res = res[concat](catmullRom2bezier(dots, crz)); r = ["R"][concat](pa.slice(-2)); } else { for (var k = 0, kk = pa.length; k < kk; k++) { r[k] = pa[k]; } } switch (r[0]) { case "Z": x = mx; y = my; break; case "H": x = r[1]; break; case "V": y = r[1]; break; case "M": mx = r[r.length - 2]; my = r[r.length - 1]; default: x = r[r.length - 2]; y = r[r.length - 1]; } } res.toString = R._path2string; pth.abs = pathClone(res); return res; }, l2c = function(x1, y1, x2, y2) { return [x1, y1, x2, y2, x2, y2]; }, q2c = function(x1, y1, ax, ay, x2, y2) { var _13 = 1 / 3, _23 = 2 / 3; return [ _13 * x1 + _23 * ax, _13 * y1 + _23 * ay, _13 * x2 + _23 * ax, _13 * y2 + _23 * ay, x2, y2 ]; }, a2c = function(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { // for more information of where this math came from visit: // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes var _120 = PI * 120 / 180, rad = deg2rad * (+angle || 0), res = [], xy, rotate = cacher(function(x, y, rad) { var X = x * mathCos(rad) - y * mathSin(rad), Y = x * mathSin(rad) + y * mathCos(rad); return { x: X, y: Y }; }); if (!recursive) { xy = rotate(x1, y1, -rad); x1 = xy.x; y1 = xy.y; xy = rotate(x2, y2, -rad); x2 = xy.x; y2 = xy.y; var cos = mathCos(deg2rad * angle), sin = mathSin(deg2rad * angle), x = (x1 - x2) / 2, y = (y1 - y2) / 2; var h = (x * x) / (rx * rx) + (y * y) / (ry * ry); if (h > 1) { h = mathSqrt(h); rx = h * rx; ry = h * ry; } var rx2 = rx * rx, ry2 = ry * ry, k = (large_arc_flag == sweep_flag ? -1 : 1) * mathSqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))), cx = k * rx * y / ry + (x1 + x2) / 2, cy = k * -ry * x / rx + (y1 + y2) / 2, f1 = math.asin(((y1 - cy) / ry).toFixed(9)), f2 = math.asin(((y2 - cy) / ry).toFixed(9)); f1 = x1 < cx ? PI - f1 : f1; f2 = x2 < cx ? PI - f2 : f2; f1 < 0 && (f1 = PI * 2 + f1); f2 < 0 && (f2 = PI * 2 + f2); if (sweep_flag && f1 > f2) { f1 = f1 - PI * 2; } if (!sweep_flag && f2 > f1) { f2 = f2 - PI * 2; } } else { f1 = recursive[0]; f2 = recursive[1]; cx = recursive[2]; cy = recursive[3]; } var df = f2 - f1; if (abs(df) > _120) { var f2old = f2, x2old = x2, y2old = y2; f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); x2 = cx + rx * mathCos(f2); y2 = cy + ry * mathSin(f2); res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); } df = f2 - f1; var c1 = mathCos(f1), s1 = mathSin(f1), c2 = mathCos(f2), s2 = mathSin(f2), t = math.tan(df / 4), hx = 4 / 3 * rx * t, hy = 4 / 3 * ry * t, m1 = [x1, y1], m2 = [x1 + hx * s1, y1 - hy * c1], m3 = [x2 + hx * s2, y2 - hy * c2], m4 = [x2, y2]; m2[0] = 2 * m1[0] - m2[0]; m2[1] = 2 * m1[1] - m2[1]; if (recursive) { return [m2, m3, m4][concat](res); } else { res = [m2, m3, m4][concat](res).join()[split](","); var newres = []; for (var i = 0, ii = res.length; i < ii; i++) { newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; } return newres; } }, findDotAtSegment = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t; return { x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x, y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y }; }, curveDim = cacher(function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x), b = 2 * (c1x - p1x) - 2 * (c2x - c1x), c = p1x - c1x, t1 = (-b + mathSqrt(b * b - 4 * a * c)) / 2 / a, t2 = (-b - mathSqrt(b * b - 4 * a * c)) / 2 / a, y = [p1y, p2y], x = [p1x, p2x], dot; abs(t1) > "1e12" && (t1 = .5); abs(t2) > "1e12" && (t2 = .5); if (t1 > 0 && t1 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1); x.push(dot.x); y.push(dot.y); } if (t2 > 0 && t2 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2); x.push(dot.x); y.push(dot.y); } a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y); b = 2 * (c1y - p1y) - 2 * (c2y - c1y); c = p1y - c1y; t1 = (-b + mathSqrt(b * b - 4 * a * c)) / 2 / a; t2 = (-b - mathSqrt(b * b - 4 * a * c)) / 2 / a; abs(t1) > "1e12" && (t1 = .5); abs(t2) > "1e12" && (t2 = .5); if (t1 > 0 && t1 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1); x.push(dot.x); y.push(dot.y); } if (t2 > 0 && t2 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2); x.push(dot.x); y.push(dot.y); } return { min: { x: mmin[apply](0, x), y: mmin[apply](0, y) }, max: { x: mmax[apply](0, x), y: mmax[apply](0, y) } }; }), path2curve = R._path2curve = cacher(function(path, path2) { var pth = !path2 && paths(path); if (!path2 && pth.curve) { return pathClone(pth.curve); } var p = pathToAbsolute(path), p2 = path2 && pathToAbsolute(path2), attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }, attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }, processPath = function(path, d) { var nx, ny; if (!path) { return ["C", d.x, d.y, d.x, d.y, d.x, d.y]; } !(path[0] in { T: 1, Q: 1 }) && (d.qx = d.qy = null); switch (path[0]) { case "M": d.X = path[1]; d.Y = path[2]; break; case "A": path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1)))); break; case "S": nx = d.x + (d.x - (d.bx || d.x)); ny = d.y + (d.y - (d.by || d.y)); path = ["C", nx, ny][concat](path.slice(1)); break; case "T": d.qx = d.x + (d.x - (d.qx || d.x)); d.qy = d.y + (d.y - (d.qy || d.y)); path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2])); break; case "Q": d.qx = path[1]; d.qy = path[2]; path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4])); break; case "L": path = ["C"][concat](l2c(d.x, d.y, path[1], path[2])); break; case "H": path = ["C"][concat](l2c(d.x, d.y, path[1], d.y)); break; case "V": path = ["C"][concat](l2c(d.x, d.y, d.x, path[1])); break; case "Z": path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y)); break; } return path; }, fixArc = function(pp, i) { if (pp[i].length > 7) { pp[i].shift(); var pi = pp[i]; while (pi.length) { pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6))); } pp.splice(i, 1); ii = mmax(p.length, p2 && p2.length || 0); } }, fixM = function(path1, path2, a1, a2, i) { if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M" && !i) { path2.splice(i, 0, ["M", a2.x, a2.y]); a1.bx = 0; a1.by = 0; a1.x = path1[i][1]; a1.y = path1[i][2]; ii = mmax(p.length, p2 && p2.length || 0); } }; for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) { p[i] = processPath(p[i], attrs); fixArc(p, i); p2 && (p2[i] = processPath(p2[i], attrs2)); p2 && fixArc(p2, i); fixM(p, p2, attrs, attrs2, i); fixM(p2, p, attrs2, attrs, i); var seg = p[i], seg2 = p2 && p2[i], seglen = seg.length, seg2len = p2 && seg2.length; attrs.x = seg[seglen - 2]; attrs.y = seg[seglen - 1]; attrs.bx = toFloat(seg[seglen - 4]) || attrs.x; attrs.by = toFloat(seg[seglen - 3]) || attrs.y; attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x); attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y); attrs2.x = p2 && seg2[seg2len - 2]; attrs2.y = p2 && seg2[seg2len - 1]; } if (!p2) { pth.curve = pathClone(p); } return p2 ? [p, p2] : p; }, null, pathClone), parseDots = R._parseDots = cacher(function(gradient) { var dots = []; for (var i = 0, ii = gradient.length; i < ii; i++) { var dot = {}, par = gradient[i].match(/^([^:]*):?([\d\.]*)/); dot.color = R.getRGB(par[1]); if (dot.color.error) { return null; } //store opacity information dot.opacity = dot.color.opacity; dot.color = dot.color.hex; par[2] && (dot.offset = par[2] + "%"); dots.push(dot); } for (i = 1, ii = dots.length - 1; i < ii; i++) { if (!dots[i].offset) { var start = toFloat(dots[i - 1].offset || 0), end = 0; for (var j = i + 1; j < ii; j++) { if (dots[j].offset) { end = dots[j].offset; break; } } if (!end) { end = 100; j = ii; } end = toFloat(end); var d = (end - start) / (j - i + 1); for (; i < j; i++) { start += d; dots[i].offset = start + "%"; } } } return dots; }), tear = R._tear = function(el, paper) { el == paper.top && (paper.top = el.prev); el == paper.bottom && (paper.bottom = el.next); el.next && (el.next.prev = el.prev); el.prev && (el.prev.next = el.next); }, tofront = R._tofront = function(el, paper) { if (paper.top === el) { return false; } tear(el, paper); el.next = null; el.prev = paper.top; paper.top.next = el; paper.top = el; return true; }, toback = R._toback = function(el, paper) { if (paper.bottom === el) { return false; } tear(el, paper); el.next = paper.bottom; el.prev = null; paper.bottom.prev = el; paper.bottom = el; return true; }, insertafter = R._insertafter = function(el, el2, paper, paper2) { tear(el, paper); el.parent = paper2; el2 === paper2.top && (paper2.top = el); el2.next && (el2.next.prev = el); el.next = el2.next; el.prev = el2; el2.next = el; }, insertbefore = R._insertbefore = function(el, el2, paper, paper2) { tear(el, paper); el.parent = paper2; el2 === paper2.bottom && (paper2.bottom = el); el2.prev && (el2.prev.next = el); el.prev = el2.prev; el2.prev = el; el.next = el2; }, /*\ * Raphael.toMatrix [ method ] ** * Utility method ** * Returns matrix of transformations applied to a given path > Parameters - path (string) path string - transform (string|array) transformation string = (object) @Matrix \*/ toMatrix = R.toMatrix = function(path, transform) { var bb = pathDimensions(path), el = { _: { transform: E }, getBBox: function() { return bb; } }; extractTransform(el, transform); return el.matrix; }, /*\ * Raphael.transformPath [ method ] ** * Utility method ** * Returns path transformed by a given transformation > Parameters - path (string) path string - transform (string|array) transformation string = (string) path \*/ transformPath = R.transformPath = function(path, transform) { return mapPath(path, toMatrix(path, transform)); }, extractTransform = R._extractTransform = function(el, tstr) { if (tstr == null) { return el._.transform; } tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E); var tdata = R.parseTransformString(tstr), deg = 0, dx = 0, dy = 0, sx = 1, sy = 1, _ = el._, m = new Matrix; _.transform = tdata || []; if (tdata) { for (var i = 0, ii = tdata.length; i < ii; i++) { var t = tdata[i], tlen = t.length, command = Str(t[0]).toLowerCase(), absolute = t[0] != command, inver = absolute ? m.invert() : 0, x1, y1, x2, y2, bb; if (command == "t" && tlen == 3) { if (absolute) { x1 = inver.x(0, 0); y1 = inver.y(0, 0); x2 = inver.x(t[1], t[2]); y2 = inver.y(t[1], t[2]); m.translate(x2 - x1, y2 - y1); } else { m.translate(t[1], t[2]); } } else if (command == "r") { if (tlen == 2) { bb = _.bb || (_.bb = el.getBBox(1)); m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2); deg += t[1]; } else if (tlen == 4) { if (absolute) { x2 = inver.x(t[2], t[3]); y2 = inver.y(t[2], t[3]); m.rotate(t[1], x2, y2); } else { m.rotate(t[1], t[2], t[3]); } deg += t[1]; } } else if (command == "s") { if (tlen == 2 || tlen == 3) { bb = _.bb || (_.bb = el.getBBox(1)); m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2); sx *= t[1]; sy *= t[tlen - 1]; } else if (tlen == 5) { if (absolute) { x2 = inver.x(t[3], t[4]); y2 = inver.y(t[3], t[4]); m.scale(t[1], t[2], x2, y2); } else { m.scale(t[1], t[2], t[3], t[4]); } sx *= t[1]; sy *= t[2]; } } else if (command == "m" && tlen == 7) { m.add(t[1], t[2], t[3], t[4], t[5], t[6]); } _.dirtyT = 1; el.matrix = m; } } /*\ * Element.matrix [ property (object) ] ** * Keeps @Matrix object, which represents element transformation \*/ el.matrix = m; _.sx = sx; _.sy = sy; _.deg = deg; _.dx = dx = m.e; _.dy = dy = m.f; if (sx == 1 && sy == 1 && !deg && _.bbox) { _.bbox.x += +dx; _.bbox.y += +dy; } else { _.dirtyT = 1; } }, getEmpty = function(item) { var l = item[0]; switch (l.toLowerCase()) { case "t": return [l, 0, 0]; case "m": return [l, 1, 0, 0, 1, 0, 0]; case "r": if (item.length == 4) { return [l, 0, item[2], item[3]]; } else { return [l, 0]; } case "s": if (item.length == 5) { return [l, 1, 1, item[3], item[4]]; } else if (item.length == 3) { return [l, 1, 1]; } else { return [l, 1]; } } }, equaliseTransform = R._equaliseTransform = function(t1, t2) { t2 = Str(t2).replace(/\.{3}|\u2026/g, t1); t1 = R.parseTransformString(t1) || []; t2 = R.parseTransformString(t2) || []; var maxlength = mmax(t1.length, t2.length), from = [], to = [], i = 0, j, jj, tt1, tt2; for (; i < maxlength; i++) { tt1 = t1[i] || getEmpty(t2[i]); tt2 = t2[i] || getEmpty(tt1); if ((tt1[0] != tt2[0]) || (tt1[0].toLowerCase() == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) || (tt1[0].toLowerCase() == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4])) ) { return; } from[i] = []; to[i] = []; for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) { j in tt1 && (from[i][j] = tt1[j]); j in tt2 && (to[i][j] = tt2[j]); } } return { from: from, to: to }; }; R._getContainer = function(x, y, w, h) { var container; container = h == null && !R.is(x, object) ? g.doc.getElementById(x) : x; if (container == null) { return; } if (container.tagName) { if (y == null) { return { container: container, width: container.style.pixelWidth || container.offsetWidth, height: container.style.pixelHeight || container.offsetHeight }; } else { return { container: container, width: y, height: w }; } } return { container: 1, x: x, y: y, width: w, height: h }; }; /*\ * Raphael.pathToRelative [ method ] ** * Utility method ** * Converts path to relative form > Parameters - pathString (string|array) path string or array of segments = (array) array of segments. \*/ R.pathToRelative = pathToRelative; R._engine = {}; /*\ * Raphael.path2curve [ method ] ** * Utility method ** * Converts path to a new path where all segments are cubic bezier curves. > Parameters - pathString (string|array) path string or array of segments = (array) array of segments. \*/ R.path2curve = path2curve; /*\ * Raphael.matrix [ method ] ** * Utility method ** * Returns matrix based on given parameters. > Parameters - a (number) - b (number) - c (number) - d (number) - e (number) - f (number) = (object) @Matrix \*/ R.matrix = function(a, b, c, d, e, f) { return new Matrix(a, b, c, d, e, f); }; function Matrix(a, b, c, d, e, f) { if (a != null) { this.a = +a; this.b = +b; this.c = +c; this.d = +d; this.e = +e; this.f = +f; } else { this.a = 1; this.b = 0; this.c = 0; this.d = 1; this.e = 0; this.f = 0; } } (function(matrixproto) { /*\ * Matrix.add [ method ] ** * Adds given matrix to existing one. > Parameters - a (number) - b (number) - c (number) - d (number) - e (number) - f (number) or - matrix (object) @Matrix \*/ matrixproto.add = function(a, b, c, d, e, f) { var out = [[], [], []], m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]], matrix = [[a, c, e], [b, d, f], [0, 0, 1]], x, y, z, res; if (a && a instanceof Matrix) { matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]]; } for (x = 0; x < 3; x++) { for (y = 0; y < 3; y++) { res = 0; for (z = 0; z < 3; z++) { res += m[x][z] * matrix[z][y]; } out[x][y] = res; } } this.a = out[0][0]; this.b = out[1][0]; this.c = out[0][1]; this.d = out[1][1]; this.e = out[0][2]; this.f = out[1][2]; }; /*\ * Matrix.invert [ method ] ** * Returns inverted version of the matrix = (object) @Matrix \*/ matrixproto.invert = function() { var me = this, x = me.a * me.d - me.b * me.c; return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x); }; /*\ * Matrix.clone [ method ] ** * Returns copy of the matrix = (object) @Matrix \*/ matrixproto.clone = function() { return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f); }; /*\ * Matrix.translate [ method ] ** * Translate the matrix > Parameters - x (number) - y (number) \*/ matrixproto.translate = function(x, y) { this.add(1, 0, 0, 1, x, y); }; /*\ * Matrix.scale [ method ] ** * Scales the matrix > Parameters - x (number) - y (number) #optional - cx (number) #optional - cy (number) #optional \*/ matrixproto.scale = function(x, y, cx, cy) { y == null && (y = x); (cx || cy) && this.add(1, 0, 0, 1, cx, cy); this.add(x, 0, 0, y, 0, 0); (cx || cy) && this.add(1, 0, 0, 1, -cx, -cy); }; /*\ * Matrix.rotate [ method ] ** * Rotates the matrix > Parameters - a (number) - x (number) - y (number) \*/ matrixproto.rotate = function(a, x, y) { a = R.rad(a); x = x || 0; y = y || 0; var cos = +mathCos(a).toFixed(9), sin = + mathSin(a).toFixed(9); this.add(cos, sin, -sin, cos, x, y); this.add(1, 0, 0, 1, -x, -y); }; /*\ * Matrix.x [ method ] ** * Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y > Parameters - x (number) - y (number) = (number) x \*/ matrixproto.x = function(x, y) { return x * this.a + y * this.c + this.e; }; /*\ * Matrix.y [ method ] ** * Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x > Parameters - x (number) - y (number) = (number) y \*/ matrixproto.y = function(x, y) { return x * this.b + y * this.d + this.f; }; matrixproto.get = function(i) { return +this[Str.fromCharCode(97 + i)].toFixed(4); }; matrixproto.toString = function() { return R.svg ? "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join(); }; matrixproto.toMatrixString = function() { return "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")"; }; matrixproto.toFilter = function() { return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) + ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) + ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')"; }; matrixproto.offset = function() { return [this.e.toFixed(4), this.f.toFixed(4)]; }; function norm(a) { return a[0] * a[0] + a[1] * a[1]; } function normalize(a) { var mag = mathSqrt(norm(a)); a[0] && (a[0] /= mag); a[1] && (a[1] /= mag); } /*\ * Matrix.split [ method ] ** * Splits matrix into primitive transformations = (object) in format: o dx (number) translation by x o dy (number) translation by y o scalex (number) scale by x o scaley (number) scale by y o shear (number) shear o rotate (number) rotation in deg o isSimple (boolean) could it be represented via simple transformations \*/ matrixproto.split = function() { var out = {}; // translation out.dx = this.e; out.dy = this.f; // scale and shear var row = [[this.a, this.c], [this.b, this.d]]; out.scalex = mathSqrt(norm(row[0])); normalize(row[0]); out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1]; row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear]; out.scaley = mathSqrt(norm(row[1])); normalize(row[1]); out.shear /= out.scaley; // rotation var sin = -row[0][1], cos = row[1][1]; if (cos < 0) { out.rotate = R.deg(math.acos(cos)); if (sin < 0) { out.rotate = 360 - out.rotate; } } else { out.rotate = R.deg(math.asin(sin)); } out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate); out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate; out.noRotation = !+out.shear.toFixed(9) && !out.rotate; return out; }; /*\ * Matrix.toTransformString [ method ] ** * Return transform string that represents given matrix = (string) transform string \*/ matrixproto.toTransformString = function(shorter) { var s = shorter || this[split](); if (s.isSimple) { s.scalex = +s.scalex.toFixed(4); s.scaley = +s.scaley.toFixed(4); s.rotate = +s.rotate.toFixed(4); return (s.dx || s.dy ? "t" + [s.dx, s.dy] : E) + (s.scalex != 1 || s.scaley != 1 ? "s" + [s.scalex, s.scaley, 0, 0] : E) + (s.rotate ? "r" + [s.rotate, 0, 0] : E); } else { return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)]; } }; })(Matrix.prototype); // WebKit rendering bug workaround method var navigator = win.navigator, version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/); if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") || (navigator.vendor == "Google Inc." && version && version[1] < 8)) { /*\ * Paper.safari [ method ] ** * There is an inconvenient rendering bug in Safari (WebKit): * sometimes the rendering should be forced. * This method should help with dealing with this bug. \*/ paperproto.safari = function() { var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({ stroke: "none" }); setTimeout(function() { rect.remove(); }); return true; }; } else { paperproto.safari = fun; } var preventDefault = function() { this.returnValue = false; }, preventTouch = function() { return this.originalEvent.preventDefault(); }, stopPropagation = function() { this.cancelBubble = true; }, stopTouch = function() { return this.originalEvent.stopPropagation(); }, eventCopyList = { stopPropagation: 'fn', stopImmediatePropagation: 'fn', preventDefault: 'fn', type: true, clientX: true, clientY: true, pageX: true, pageY: true, bubbles: true, cancelable: true, touches: true, target: true, originalTarget: true, srcElement: true, relatedTarget: true, fromElement: true, changedTouches: true, layerX: true, layerY: true }, makeSelectiveCopy = function (target, source) { for (let eve in eventCopyList) { if (eventCopyList[eve] === 'fn') { target[eve] = (function () { return function () { source[eve](); } })(source); } else { target[eve] = source[eve]; } } target.originalEvent = source; }, addEvent = R.addEvent = (function() { if (g.doc.addEventListener) { return function(obj, type, fn, element) { var realName = supportsOnlyTouch && touchMap[type] || type, f; touchMap[dragEventMap[type]] && (realName = touchMap[dragEventMap[type]]); f = function(e) { var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft, target; if (supportsTouch && touchMap[has](supportsOnlyTouch ? type : dragEventMap[type])) { for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) { target = e.targetTouches[i].target; if (target == obj || (target.nodeName == 'tspan' && target.parentNode == obj)) { var olde = e; e = e.targetTouches[i]; e.originalEvent = olde; e.preventDefault = preventTouch; e.stopPropagation = stopTouch; break; } } } return fn.call(element, e, e.clientX + scrollX, e.clientY + scrollY); }; obj.addEventListener(realName, f, {passive: false, capture:false}); return function() { obj.removeEventListener(realName, f, {passive: false, capture:false}); return true; }; }; } else if (g.doc.attachEvent) { return function(obj, type, fn, element) { var f = function(e) { e = e || g.win.event; var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft, x = e.clientX + scrollX, y = e.clientY + scrollY; e.preventDefault = e.preventDefault || preventDefault; e.stopPropagation = e.stopPropagation || stopPropagation; return fn.call(element, e, x, y); }; obj.attachEvent("on" + type, f); var detacher = function() { obj.detachEvent("on" + type, f); return true; }; return detacher; }; } })(), drag = [], dragMove = function(e) { var x = e.clientX, y = e.clientY, scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft, dragi, data, dummyEve = {}, key, el, j = drag.length; while (j--) { dragi = drag[j]; el = dragi.el; if (supportsTouch && e.type === 'touchmove') { var i = e.touches.length, touch; while (i--) { touch = e.touches[i]; if (touch.identifier == el._drag.id) { x = touch.clientX; y = touch.clientY; (e.originalEvent ? e.originalEvent : e).preventDefault(); break; } } } else { e.preventDefault(); } if (el.removed) { continue; } if (el.dragStartFn) { el.dragStartFn(); el.dragStartFn = undefined; el.dragInfo._dragmove = true; } if (g.win.opera) { var node = R._engine.getNode(el), next = node.nextSibling, parent = node.parentNode, display = node.style.display; parent.removeChild(node); node.style.display = "none"; node.style.display = display; next ? parent.insertBefore(node, next) : parent.appendChild(node); } x += scrollX; y += scrollY; //Function to copy some properties of the actual event into the dummy event makeSelectiveCopy(dummyEve, e); data = dummyEve.data = [x - el._drag.x, y - el._drag.y, x, y]; eve("raphael.drag.move." + el.id, dragi.move_scope || el, dummyEve, data); } }, dragUp = function(e) { R.undragmove(dragMove).undragend(dragUp); R.unmousemove(dragMove).unmouseup(dragUp); var i = drag.length, el, dragi; while (i--) { dragi = drag[i]; el = dragi.el if (!el.dragInfo._dragmove) { continue; } else { el.dragInfo._dragmove = undefined; } dragi.el._drag = {}; eve("raphael.drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e); } drag = []; }, /*\ * Raphael.el [ property (object) ] ** * You can add your own method to elements. This is usefull when you want to hack default functionality or * want to wrap some common transformation or attributes in one method. In difference to canvas methods, * you can redefine element method at any time. Expending element methods wouldn’t affect set. > Usage | Raphael.el.red = function () { | this.attr({fill: "#f00"}); | }; | // then use it | paper.circle(100, 100, 20).red(); \*/ elproto = R.el = {}; /*\ * Element.click [ method ] ** * Adds event handler for click for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unclick [ method ] ** * Removes event handler for click for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.dblclick [ method ] ** * Adds event handler for double click for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.undblclick [ method ] ** * Removes event handler for double click for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.mousedown [ method ] ** * Adds event handler for mousedown for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmousedown [ method ] ** * Removes event handler for mousedown for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.mousemove [ method ] ** * Adds event handler for mousemove for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmousemove [ method ] ** * Removes event handler for mousemove for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.mouseout [ method ] ** * Adds event handler for mouseout for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmouseout [ method ] ** * Removes event handler for mouseout for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.mouseover [ method ] ** * Adds event handler for mouseover for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmouseover [ method ] ** * Removes event handler for mouseover for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.mouseup [ method ] ** * Adds event handler for mouseup for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmouseup [ method ] ** * Removes event handler for mouseup for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.touchstart [ method ] ** * Adds event handler for touchstart for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchstart [ method ] ** * Removes event handler for touchstart for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.touchmove [ method ] ** * Adds event handler for touchmove for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchmove [ method ] ** * Removes event handler for touchmove for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.touchend [ method ] ** * Adds event handler for touchend for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchend [ method ] ** * Removes event handler for touchend for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.touchcancel [ method ] ** * Adds event handler for touchcancel for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchcancel [ method ] ** * Removes event handler for touchcancel for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ for (var i = events.length; i--; ) { (function(eventName) { R[eventName] = elproto[eventName] = function(fn, scope) { if (R.is(fn, "function")) { this.events = this.events || []; this.events.push({ name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this) }); } return this; }; R["un" + eventName] = elproto["un" + eventName] = function(fn) { var events = this.events || [], l = events.length; while (l--) if (events[l].name == eventName && events[l].f == fn) { events[l].unbind(); events.splice(l, 1); !events.length && delete this.events; return this; } return this; }; })(events[i]); } /*\ * Element.data [ method ] ** * Adds or retrieves given value asociated with given key. ** * See also @Element.removeData > Parameters - key (string) key to store data - value (any) #optional value to store = (object) @Element * or, if value is not specified: = (any) value > Usage | for (var i = 0, i < 5, i++) { | paper.circle(10 + 15 * i, 10, 10) | .attr({fill: "#000"}) | .data("i", i) | .click(function () { | alert(this.data("i")); | }); | } \*/ elproto.data = function(key, value) { var data = eldata[this.id] = eldata[this.id] || {}; if (arguments.length == 1) { if (R.is(key, object)) { for (var i in key) if (key[has](i)) { this.data(i, key[i]); } return this; } eve("raphael.data.get." + this.id, this, data[key], key); return data[key]; } data[key] = value; eve("raphael.data.set." + this.id, this, value, key); return this; }; /*\ * Element.removeData [ method ] ** * Removes value associated with an element by given key. * If key is not provided, removes all the data of the element. > Parameters - key (string) #optional key = (object) @Element \*/ elproto.removeData = function (key) { if (key == null) { delete eldata[this.id]; } else { eldata[this.id] && delete eldata[this.id][key]; } return this; }; /*\ * Element.getData [ method ] ** * Retrieves the element data = (object) data \*/ elproto.getData = function () { return clone(eldata[this.id] || {}); }; var downables = [], mouseDown = function () { this.untrack = addEvent(g.doc, 'mouseup', mouseUp, this); }, mouseUp = function () { this.untrack(); this.untrack = null; return this.fn && this.fn.apply(this.scope || this.el, arguments); }; elproto.mouseup = function (fn, scope, track) { if (!track) { return R.mouseup.apply(this, arguments); } downables.push(track = { el: this, fn: fn, scope: scope }); track.unbind = addEvent(this.shape || this.node || g.doc, 'mousedown', mouseDown, track); return this; }; elproto.unmouseup = function (fn) { var i = downables.length, undowned; while (i--) { if (downables[i].el === this && downables[i].fn === fn) { undowned = downables[i]; undowned.unbind(); undowned.untrack && undowned.untrack(); downables.splice(i, 1); } } return undowned ? this : R.unmouseup.apply(this, arguments); }; /*\ * Element.hover [ method ] ** * Adds event handlers for hover for the element. > Parameters - f_in (function) handler for hover in - f_out (function) handler for hover out - icontext (object) #optional context for hover in handler - ocontext (object) #optional context for hover out handler = (object) @Element \*/ elproto.hover = function(f_in, f_out, scope_in, scope_out) { return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in); }; /*\ * Element.unhover [ method ] ** * Removes event handlers for hover for the element. > Parameters - f_in (function) handler for hover in - f_out (function) handler for hover out = (object) @Element \*/ elproto.unhover = function(f_in, f_out) { return this.unmouseover(f_in).unmouseout(f_out); }; var draggable = []; /*\ * Element.drag [ method ] ** * Adds event handlers for drag of the element. > Parameters - onmove (function) handler for moving - onstart (function) handler for drag start - onend (function) handler for drag end - mcontext (object) #optional context for moving handler - scontext (object) #optional context for drag start handler - econtext (object) #optional context for drag end handler * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start, * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element * `drag.over.<id>` will be fired as well. * * Start event and start handler will be called in specified context or in context of the element with following parameters: o x (number) x position of the mouse o y (number) y position of the mouse o event (object) DOM event object * Move event and move handler will be called in specified context or in context of the element with following parameters: o dx (number) shift by x from the start point o dy (number) shift by y from the start point o x (number) x position of the mouse o y (number) y position of the mouse o event (object) DOM event object * End event and end handler will be called in specified context or in context of the element with following parameters: o event (object) DOM event object = (object) @Element \*/ elproto.drag = function(onmove, onstart, onend, move_scope, start_scope, end_scope) { var dragInfo = this.dragInfo || (this.dragInfo = { // Store all the callbacks for various eventListeners on the same element onmove: [], onstart: [], onend: [], move_scope: [], start_scope: [], end_scope: [] }); onmove && (dragInfo.onmove.push(onmove)); onstart && (dragInfo.onstart.push(onstart)); onend && (dragInfo.onend.push(onend)); // Scopes are not stored as when called via element.on, there is no provision for provifing scope this.dragFn = this.dragFn || function (e) { var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft, key, dummyEve = {}, data, i, j, k, ii, jj, kk, dragInfo = this.dragInfo; this._drag.x = e.clientX + scrollX; this._drag.y = e.clientY + scrollY; this._drag.id = e.identifier; // Add the drag events for the browsers that doesn't fire mouse event on touch and drag if (supportsTouch && !supportsOnlyTouch) { !drag.length && R.dragmove(dragMove).dragend(dragUp); } !drag.length && R.mousemove(dragMove).mouseup(dragUp); drag.push({ el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope }); //Function to copy some properties of the actual event into the dummy event makeSelectiveCopy(dummyEve, e); data = dummyEve.data = [e.clientX + scrollX, e.clientY + scrollY]; // Attaching handlers for various events for (i = 0, ii = dragInfo.onstart.length; i < ii; i ++) { eve.on("raphael.drag.start." + this.id, dragInfo.onstart[i]); } for (j = 0, jj = dragInfo.onmove.length; j < jj; j ++) { eve.on("raphael.drag.move." + this.id, dragInfo.onmove[j]); } for (k = 0, kk = dragInfo.onend.length; k < kk; k ++) { eve.on("raphael.drag.end." + this.id, dragInfo.onend[k]); } // Where there is no dragStart but there is dragEnd or dragMove handler if (!ii && (jj || kk) ) { eve.on("raphael.drag.end." + this.id, function() { this.undragmove(); }); } // Queuing up the dragStartFn. It is fired if dragmove is fired after dragStart this.dragStartFn = function () { eve("raphael.drag.start." + this.id, drag.start_scope || drag.move_scope || this, dummyEve, data); } } this._drag = {}; draggable.push({ el: this, start: this.dragFn, onstart: onstart, onmove: onmove, onend: onend }); if (onstart && !this.startHandlerAttached) { // Add the drag events for the browsers that doesn't fire mouse event on touch and drag if (supportsTouch && !supportsOnlyTouch) { this.dragstart(this.dragFn); } this.mousedown(this.dragFn); this.startHandlerAttached = true; } return this; }; /*\ * Element.onDragOver [ method ] ** * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id). > Parameters - f (function) handler for event, first argument would be the element you are dragging over \*/ elproto.onDragOver = function(f) { f ? eve.on("raphael.drag.over." + this.id, f) : eve.unbind("raphael.drag.over." + this.id); }; /*\ * Element.undrag [ method ] ** * Removes all drag event handlers from given element. \*/ elproto.undrag = function() { var i = draggable.length; while (i--) { if (draggable[i].el == this) { this.unmousedown(draggable[i].start); draggable.splice(i, 1); eve.unbind("raphael.drag.*." + this.id); this.dragInfo = undefined; this.dragFn = undefined; this.startHandlerAttached = undefined; } } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); delete this._drag; }; /*\ * Element.undragmove [ method ] ** * Removes all dragmove event handlers from given element. \*/ elproto.undragmove = function() { var i = draggable.length; while (i--) { if (draggable[i].el == this && draggable[i].onmove) { draggable.splice(i, 1); eve.unbind("raphael.drag.move." + this.id); this.dragInfo.onmove = undefined; } } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); }; /*\ * Element.undragend [ method ] ** * Removes all dragend event handlers from given element. \*/ elproto.undragend = function() { var i = draggable.length; while (i--) { if (draggable[i].el == this && draggable[i].onend) { draggable.splice(i, 1); eve.unbind("raphael.drag.end." + this.id); this.dragInfo.onend = undefined; } } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); }; /*\ * Element.undragstart [ method ] ** * Removes all dragstart event handlers from given element. \*/ elproto.undragstart = function() { var i = draggable.length; while (i--) { if (draggable[i].el == this && draggable[i].onstart) { this.unmousedown(draggable[i].start); draggable.splice(i, 1); eve.unbind("raphael.drag.start." + this.id); this._dragstart = false; this.dragInfo.onstart = undefined; this.dragFn = undefined; } } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); }; elproto.follow = function(el, callback, stalk) { if (el.removed || el.constructor !== R.el.constructor) { return this; } el.followers.push({ el: this, stalk: (stalk = {before: 'insertBefore', after: 'insertAfter'}[stalk]), cb: callback }); stalk && this[stalk](el); return this; }; elproto.unfollow = function(el) { if (el.removed || el.constructor !== R.el.constructor) { return this; } for (var i = 0, ii = el.followers.length; i < ii; i++) { if (el.followers[i].el === this) { el.followers.splice(i, 1); break; } } return this; }; /*\ * Paper.hide [ method ] ** * Hides a paper ** > Usage | paper.hide(); \*/ paperproto.hide = function () { var paper = this; paper.canvas.style.visibility = "hidden"; return paper; }; /*\ * Paper.show [ method ] ** * Shows a hidden paper ** > Usage | paper.show(); \*/ paperproto.show = function () { var paper = this; paper.canvas.style.visibility = E; return paper; }; /*\ * Paper.group [ method ] ** * Creates a group ** > Parameters ** - id (number) id of the group = (object) Raphaël element object with type “group” ** > Usage | var g = paper.group(); \*/ paperproto.group = function () { // id var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), out = R._engine.group(paper, args[0], group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.circle [ method ] ** * Draws a circle. ** > Parameters ** - x (number) x coordinate of the centre - y (number) y coordinate of the centre - r (number) radius = (object) Raphaël element object with type “circle” ** > Usage | var c = paper.circle(50, 50, 40); \*/ paperproto.circle = function () { // x, y, r var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), attrs = serializeArgs(args, "cx", 0, "cy", 0, "r", 0, "fill", none, "stroke", black), out = R._engine.circle(paper, attrs, group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.rect [ method ] * * Draws a rectangle. ** > Parameters ** - x (number) x coordinate of the top left corner - y (number) y coordinate of the top left corner - width (number) width - height (number) height - r (number) #optional radius for rounded corners, default is 0 = (object) Raphaël element object with type “rect” ** > Usage | // regular rectangle | var c = paper.rect(10, 10, 50, 50); | // rectangle with rounded corners | var c = paper.rect(40, 40, 50, 50, 10); \*/ paperproto.rect = function () { var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), attrs = serializeArgs(args, "x", 0, "y", 0, "width", 0, "height", 0, "r", 0, "fill", none, "stroke", black), out = R._engine.rect(paper, attrs, group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.ellipse [ method ] ** * Draws an ellipse. ** > Parameters ** - x (number) x coordinate of the centre - y (number) y coordinate of the centre - rx (number) horizontal radius - ry (number) vertical radius = (object) Raphaël element object with type “ellipse” ** > Usage | var c = paper.ellipse(50, 50, 40, 20); \*/ paperproto.ellipse = function () { var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), attrs = serializeArgs(args, "x", 0, "y", 0, "rx", 0, "ry", 0, "fill", none, "stroke", black), out = R._engine.ellipse(this, attrs, group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.path [ method ] ** * Creates a path element by given path data string. > Parameters - pathString (string) #optional path string in SVG format. * Path string consists of one-letter commands, followed by comma seprarated arguments in numercal form. Example: | "M10,20L30,40" * Here we can see two commands: “M”, with arguments `(10, 20)` and “L” with arguments `(30, 40)`. Upper case letter mean command is absolute, lower case—relative. * # <p>Here is short list of commands available, for more details see <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path's data attribute's format are described in the SVG specification.">SVG path string format</a>.</p> # <table><thead><tr><th>Command</th><th>Name</th><th>Parameters</th></tr></thead><tbody> # <tr><td>M</td><td>moveto</td><td>(x y)+</td></tr> # <tr><td>Z</td><td>closepath</td><td>(none)</td></tr> # <tr><td>L</td><td>lineto</td><td>(x y)+</td></tr> # <tr><td>H</td><td>horizontal lineto</td><td>x+</td></tr> # <tr><td>V</td><td>vertical lineto</td><td>y+</td></tr> # <tr><td>C</td><td>curveto</td><td>(x1 y1 x2 y2 x y)+</td></tr> # <tr><td>S</td><td>smooth curveto</td><td>(x2 y2 x y)+</td></tr> # <tr><td>Q</td><td>quadratic Bézier curveto</td><td>(x1 y1 x y)+</td></tr> # <tr><td>T</td><td>smooth quadratic Bézier curveto</td><td>(x y)+</td></tr> # <tr><td>A</td><td>elliptical arc</td><td>(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+</td></tr> # <tr><td>R</td><td><a href="http://en.wikipedia.org/wiki/Catmull–Rom_spline#Catmull.E2.80.93Rom_spline">Catmull-Rom curveto</a>*</td><td>x1 y1 (x y)+</td></tr></tbody></table> * * “Catmull-Rom curveto” is a not standard SVG command and added in 2.0 to make life easier. * Note: there is a special case when path consist of just three commands: “M10,10R…z”. In this case path will smoothly connects to its beginning. > Usage | var c = paper.path("M10 10L90 90"); | // draw a diagonal line: | // move to 10,10, line to 90,90 * For example of path strings, check out these icons: http://raphaeljs.com/icons/ \*/ paperproto.path = function () { var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), paperConfig = paper.config, capStyle = (paperConfig && paperConfig["stroke-linecap"]) || "butt", attrs = serializeArgs(args, "path", E, "fill", none, "stroke", black, "stroke-linecap", capStyle), out = R._engine.path(paper, attrs, group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.image [ method ] ** * Embeds an image into the surface. ** > Parameters ** - src (string) URI of the source image - x (number) x coordinate position - y (number) y coordinate position - width (number) width of the image - height (number) height of the image = (object) Raphaël element object with type “image” ** > Usage | var c = paper.image("apple.png", 10, 10, 80, 80); \*/ paperproto.image = function () { var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), attrs = serializeArgs(args, // "src", "", "x", 0, "y", 0, "width", 0, "height", 0), out = R._engine.image(paper, attrs, group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.text [ method ] ** * Draws a text string. If you need line breaks, put “\n” in the string. ** > Parameters ** - x (number) x coordinate position - y (number) y coordinate position - text (string) The text string to draw = (object) Raphaël element object with type “text” ** > Usage | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!"); \*/ paperproto.text = function() { var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), attrs = serializeArgs(args, "x", 0, "y", 0, "text", E, "stroke", none, "fill", black, "text-anchor", "middle", "vertical-align", "middle"), out = R._engine.text(paper, attrs, group, args[1]); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.setConfig [ method ] ** * If you need to store any configuration in paper, call this method ** > Parameters ** - key (String) key name of the key-value pair - value (String or number) value of the key-value pair \*/ paperproto.setConfig = function (key, value) { var paper = this; if ((key !== undefined) && (value !== undefined)) { paper.config = paper.config || {}; paper.config[key] = value; } return paper.config; }; /*\ * Paper._createDOMNodes [ method ] ** * Create DOM nodes with nested children ** > Parameters ** - parentElem (object) parent element node - elemObj (object) nested input object to create elements - returnObj (object) object reference which will be returned ** > Usage | paper._createDOMNodes(parentElementNode, { | tagName: 'filter', | id: 'filter-0', | width: '200%', | height: '200%', | children: [{ | tagName: 'feOffset', | result: 'offOut', | in: 'SourceGraphic', | dx: '1', | dy: '1' | }, { | tagName: 'feColorMatrix', | result: 'matrixOut', | in: 'offOut', | type: 'matrix', | values: '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0' | }, { | tagName: 'feGaussianBlur', | result: 'blurOut', | in: 'matrixOut', | stdDeviation: '1' | }, { | tagName: 'feComposite', | in: 'SourceGraphic', | in2: 'blurOut', | operator: 'over' | }] | }); \*/ paperproto._createDOMNodes = function(parentElem, elementObj, returnObj) { var paper = this, ele, i, len, attr = {}, attrKey, createNode = R._createNode, tagName = elementObj.tagName, children = elementObj.children || []; !returnObj && (returnObj = {}); for (attrKey in elementObj) { if (attrKey !== 'tagName' && attrKey !== 'children') { attr[attrKey] = elementObj[attrKey]; } } !attr.id && (attr.id = R.getElementID(R.createUUID())); if (!paper.canvas.getElementById(attr.id) && tagName) { ele = parentElem.appendChild(createNode(tagName, attr)); returnObj.element = ele; returnObj.id = attr.id; len = children.length; (len > 0) && (returnObj.children = []); for (i = 0; i < len; i++) { returnObj.children[i] = {}; paper._createDOMNodes(ele, children[i], returnObj.children[i]); } } return returnObj; }; /*\ * Paper.addDefs [ method ] ** * Add definitions in paper ** > Parameters ** - elemObj (object) nested input object to create elements ** > Usage | var ob = paper.addDefs({ | filter0: { // key | tagName: 'filter', | id: 'filter-0', | width: '200%', | height: '200%', | children: [{ | tagName: 'feOffset', | result: 'offOut', | in: 'SourceGraphic', | dx: '1', | dy: '1' | }, { | tagName: 'feColorMatrix', | result: 'matrixOut', | in: 'offOut', | type: 'matrix', | values: '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0' | }, { | tagName: 'feGaussianBlur', | result: 'blurOut', | in: 'matrixOut', | stdDeviation: '1' | }, { | tagName: 'feComposite', | in: 'SourceGraphic', | in2: 'blurOut', | operator: 'over' | }] | } | }); | // Creates a 'filter' definition element of id, 'filter-0', with width, height as it's attributes | // Creates feOffset, feColorMatrix, feGaussianBlur, feComposite as children elements | // under the 'filter' definition element \*/ paperproto.addDefs = function (elemObj) { if (!R.svg) { return; } var paper = this, key, returnObj = {}, defs = paper.defs; for (key in elemObj) { returnObj[key] = {}; paper._createDOMNodes(defs, elemObj[key], returnObj[key]); } return returnObj; }; /*\ * Paper.removeDefs [ method ] ** * Remove a particular definition of given id from paper ** > Parameters ** - id (string) id of the element to remove ** > Usage | paper.removeDefs(id); \*/ paperproto.removeDefs = function (id) { if (!R.svg) { return; } var element = R._g.doc.getElementById(id); element && element.remove(); }; /*\ * Paper.updateDefs [ method ] ** * Update definitions in paper ** > Parameters ** - id (string or object) id of the element or the element node itself - attrObj (object) attribute of the element object with it's children attributes nested - hardUpdateChildren (boolean) determines whether to create new children if child elements are less than the children in attrObj or remove children in same manner ** > Usage | paper.updateDefs(id, { | width: '100%', | height: '100%', | children: [{ | dx: '2' | }] | }, true); | // Updates element of given id | // Updates the child element if present and create new child if found less than the children in attrObj | // and delete a child in same manner according to value of 'hardUpdateChildren' \*/ paperproto.updateDefs = function (id, attrObj, hardUpdateChildren) { if (!R.svg) { return; } var paper = this, element = !(id instanceof Node) ? R._g.doc.getElementById(id) : id, attrKey, i, diff, len, children = attrObj.children || [], elemChildren, childId, attr = {}; (hardUpdateChildren === undefined) && (hardUpdateChildren = true); if (element) { for (attrKey in attrObj) { if (attrKey !== 'tagName' && attrKey !== 'children') { element.setAttribute(attrKey, attrObj[attrKey]); } } elemChildren = element.children; for (i = 0, len = children.length; i < len; i++) { childId = children[i].id; elemChildren[i] ? paper.updateDefs(childId || elemChildren[i], children[i]) : hardUpdateChildren && paper._createDOMNodes(element, children[i]); } if (hardUpdateChildren) { diff = elemChildren.length - i; while (diff > 0) { elemChildren[elemChildren.length - 1].remove(); diff--; } } } }; /*\ * Paper.setSize [ method ] ** * If you need to change dimensions of the canvas call this method ** > Parameters ** - width (number) new width of the canvas - height (number) new height of the canvas \*/ paperproto.setSize = function(width, height) { return R._engine.setSize.call(this, width, height); }; /*\ * paper.setDimension [ method ] ** * If you need to change dimensions of the canvas call this method ** > Parameters ** - paramsObj (Object or number) - paramsObj (Object) ** > Properties of paramsObj - width (number) new width of the canvas - height (number) new height of the canvas ** - paramsObj (number) new width of the canvas ** - height (number) new height of the canvas \*/ paperproto.setDimension = function(paramsObj, height) { var paper = this, width; // Check if the first argument is an object or not if (typeof(paramsObj) === 'object') { width = paramsObj.width; height = paramsObj.height; paper.setSize(paramsObj.width, paramsObj.height); } else { width = paramsObj; paper.setSize(width, height); } }; paperproto.attr = function (name) { var element = this; if (name == null) { return { width : element.width, height : element.height }; } if (R.is(name, "string")) { return element[name]; } element.setDimension(name); return element; }; paperproto.status = function(anim, value) { return elproto.status.call(this, anim, value); }; // Works exactly as paper.animateWith() paperproto.animateWith = function(el, anim, params, ms, easing, callback, configObject) { return elproto.animateWith.call(this, el, anim, params, ms, easing, callback, configObject); }; /*\ * Paper.animate [ method ] ** * If you need to animate dimensions of the canvas call this method ** > Parameters ** - paramsObj (Object) > Properties of paramsObj ** - width (number) new width of the canvas - height (number) new height of the canvas - duration (number) time stretch in milliseconds to complete animation - effect (String) animation style - callback (function reference) method which will execute at end of animation \*/ paperproto.animate = function(params, ms, easing, callback) { return elproto.animate.call(this, params, ms, easing, callback); }; /*\ * Paper.setViewBox [ method ] ** * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by * specifying new boundaries. ** > Parameters ** - x (number) new x position, default is `0` - y (number) new y position, default is `0` - w (number) new width of the canvas - h (number) new height of the canvas - fit (boolean) `true` if you want graphics to fit into new boundary box \*/ paperproto.setViewBox = function(x, y, w, h, fit) { return R._engine.setViewBox.call(this, x, y, w, h, fit); }; paperproto.getById = function (id) { return this._elementsById[id] || null; }; /*\ * Paper.top [ property ] ** * Points to the topmost element on the paper \*/ /*\ * Paper.bottom [ property ] ** * Points to the bottom element on the paper \*/ paperproto.top = paperproto.bottom = null; /*\ * Paper.raphael [ property ] ** * Points to the @Raphael object/function \*/ paperproto.raphael = R; function x_y() { return this.x + S + this.y; }; function x_y_w_h() { return this.x + S + this.y + S + this.width + " \xd7 " + this.height; }; /*\ * Element.getBBox [ method ] ** * Return bounding box for a given element ** > Parameters ** - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`. = (object) Bounding box object: o { o x: (number) top left corner x o y: (number) top left corner y o x2: (number) bottom right corner x o y2: (number) bottom right corner y o width: (number) width o height: (number) height o } \*/ elproto.getBBox = function(isWithoutTransform) { if (this.removed) { return {}; } var _ = this._; if (isWithoutTransform) { if (_.dirty || !_.bboxwt) { this.realPath = getPath[this.type](this); _.bboxwt = pathDimensions(this.realPath); _.bboxwt.toString = x_y_w_h; _.dirty = 0; } return _.bboxwt; } if (_.dirty || _.dirtyT || !_.bbox) { if (_.dirty || !this.realPath) { _.bboxwt = 0; this.realPath = getPath[this.type](this); } _.bbox = pathDimensions(mapPath(this.realPath, this.matrix)); _.bbox.toString = x_y_w_h; _.dirty = _.dirtyT = 0; } return _.bbox; }; /*\ * Element.clone [ method ] ** = (object) clone of a given element ** \*/ // elproto.clone = function() { // if (this.removed) { // return null; // } // var o = this, // out = o.paper[o.type]().attr(o.attr()); // o.__set__ && o.__set__.push(out); // return out; // }; /*\ * Element.clone [ method ] ** > Parameters ** - attrObj (object) set of attributes - group (object) parent node = (object) clone of a given element ** \*/ elproto.clone = function(attrObj, group) { if (this.removed) { return null; } var o = this, attr = o.attr(), key, out; if (!attrObj) { out = o.paper[o.type]().attr(attr); } else { for (key in attrObj) { attr[key] = attrObj[key]; } out = o.paper[o.type](attr, group); } o.__set__ && o.__set__.push(out); return out; }; var curveslengths = {}, getPointAtSegmentLength = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) { if (length == null) { return bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y); } else { return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)); } }, getLengthFactory = function(istotal, subpath) { return function(path, length, onlystart) { path = path2curve(path); var x, y, p, l, sp = "", subpaths = {}, point, len = 0; for (var i = 0, ii = path.length; i < ii; i++) { p = path[i]; if (p[0] == "M") { x = +p[1]; y = +p[2]; } else { l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]); if (len + l > length) { if (subpath && !subpaths.start) { point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len); sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y]; if (onlystart) { return sp; } subpaths.start = sp; sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join(); len += l; x = +p[5]; y = +p[6]; continue; } if (!istotal && !subpath) { point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len); return { x: point.x, y: point.y, alpha: point.alpha }; } } len += l; x = +p[5]; y = +p[6]; } sp += p.shift() + p; } subpaths.end = sp; point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1); point.alpha && (point = { x: point.x, y: point.y, alpha: point.alpha }); return point; }; }, getTotalLength = getLengthFactory(1), getPointAtLength = getLengthFactory(), getSubpathsAtLength = getLengthFactory(0, 1); R.getTotalLength = getTotalLength; R.getPointAtLength = getPointAtLength; R.getSubpath = function(path, from, to) { if (this.getTotalLength(path) - to < 1e-6) { return getSubpathsAtLength(path, from).end; } var a = getSubpathsAtLength(path, to, 1); return from ? getSubpathsAtLength(a, from).end : a; }; /*\ * Raphael.getTotalLength [ method ] ** * Returns length of the given path in pixels. ** > Parameters ** - path (string) SVG path string. ** = (number) length. \*/ elproto.getTotalLength = function() { if (this.type != "path") { return; } if (this.node.getTotalLength) { return this.node.getTotalLength(); } return getTotalLength(this.attrs.path); }; /*\ * Raphael.getPointAtLength [ method ] ** * Return coordinates of the point located at the given length on the given path. ** > Parameters ** - path (string) SVG path string - length (number) ** = (object) representation of the point: o { o x: (number) x coordinate o y: (number) y coordinate o alpha: (number) angle of derivative o } \*/ elproto.getPointAtLength = function(length) { if (this.type != "path") { return; } return getPointAtLength(this.attrs.path, length); }; /*\ * Raphael.getSubpath [ method ] ** * Return subpath of a given path from given length to given length. ** > Parameters ** - path (string) SVG path string - from (number) position of the start of the segment - to (number) position of the end of the segment ** = (string) pathstring for the segment \*/ elproto.getSubpath = function(from, to) { if (this.type != "path") { return; } return R.getSubpath(this.attrs.path, from, to); }; /*\ * Raphael.easing_formulas [ property ] ** * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing: # <ul> # <li>“linear”</li> # <li>“&lt;” or “easeIn” or “ease-in”</li> # <li>“>” or “easeOut” or “ease-out”</li> # <li>“&lt;>” or “easeInOut” or “ease-in-out”</li> # <li>“backIn” or “back-in”</li> # <li>“backOut” or “back-out”</li> # <li>“elastic”</li> # <li>“bounce”</li> # </ul> # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p> \*/ var ef = R.easing_formulas = { linear: function(n) { return n; }, "<": function(n) { return pow(n, 1.7); }, ">": function(n) { return pow(n, .48); }, "<>": function(n) { var q = .48 - n / 1.04, Q = mathSqrt(.1734 + q * q), x = Q - q, X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1), y = -Q - q, Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1), t = X + Y + .5; return (1 - t) * 3 * t * t + t * t * t; }, backIn: function(n) { var s = 1.70158; return n * n * ((s + 1) * n - s); }, backOut: function(n) { n = n - 1; var s = 1.70158; return n * n * ((s + 1) * n + s) + 1; }, elastic: function(n) { if (n == !!n) { return n; } return pow(2, -10 * n) * mathSin((n - .075) * (2 * PI) / .3) + 1; }, bounce: function(n) { var s = 7.5625, p = 2.75, l; if (n < (1 / p)) { l = s * n * n; } else { if (n < (2 / p)) { n -= (1.5 / p); l = s * n * n + .75; } else { if (n < (2.5 / p)) { n -= (2.25 / p); l = s * n * n + .9375; } else { n -= (2.625 / p); l = s * n * n + .984375; } } } return l; }, // used in line chart anchor animation oneBounceOut: function (n) { var top = 120; if (n <= 0.9) { return ef.easeIn(n) * 1.33; } return 1.2 - n / 5; }, // Used in translating bubble plots elasticOnce: function(n) { var p = 0.9; if (n == !!n) { return n; } return Math.pow(2, -10 * n) * Math.sin((n - p / 4) * (2 * Math.PI) / p) + 1; }, // accelerating from zero velocity easeInQuad: function (t) { return t*t }, // decelerating to zero velocity easeOutQuad: function (t) { return t*(2-t) }, // acceleration until halfway, then deceleration easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t }, // accelerating from zero velocity easeInCubic: function (t) { return t*t*t }, // decelerating to zero velocity easeOutCubic: function (t) { return (--t)*t*t+1 }, // acceleration until halfway, then deceleration easeInOutCubic: function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 }, // accelerating from zero velocity easeInQuart: function (t) { return t*t*t*t }, // decelerating to zero velocity easeOutQuart: function (t) { return 1-(--t)*t*t*t }, // acceleration until halfway, then deceleration easeInOutQuart: function (t) { return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t }, // accelerating from zero velocity easeInQuint: function (t) { return t*t*t*t*t }, // decelerating to zero velocity easeOutQuint: function (t) { return 1+(--t)*t*t*t*t }, // acceleration until halfway, then deceleration easeInOutQuint: function (t) { return t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t } }; ef.easeIn = ef["ease-in"] = ef["<"]; ef.easeOut = ef["ease-out"] = ef[">"]; ef.easeInOut = ef["ease-in-out"] = ef["<>"]; ef["back-in"] = ef.backIn; ef["back-out"] = ef.backOut; var animationElements = [], requestAnimFrame, // This a temporary fix so that animation can be handled from the scheduler module. animation = function() { var Now = +new Date, l = 0, deqArr = [], i = 0, ll = 0, tmpOpacity, radial, animFrameFn; for (; l < animationElements.length; l++) { var e = animationElements[l]; if (e.el.removed || e.paused || e.parentEl && e.parentEl.e && e.parentEl.e.paused) { continue; } var time = Now - e.start, ms = e.ms, easing = e.easing, from = e.from, diff = e.diff, to = e.to, t = e.t, that = e.el, set = {}, now, origms, init = {}, executeEvent = !R.stopPartialEventPropagation, key, i = 0, peekVal = e.el && e.el.animElements && e.el.animElements.peek(); // Checking hooks while (peekVal && peekVal.pos <= time / ms) { deqArr.push(e.el.animElements.deq()); peekVal = e.el.animElements.peek(); } if (e.initstatus) { time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms; e.status = e.initstatus; delete e.initstatus; if (e.stop) { delete e.el; animationElements.splice(l--, 1); } } else { e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top; } origms = ms; // If has parentEl if (e.parentEl && e.parentEl.animElements) { ms = e.delayend - e.delaystart; time = e.parentEl.cPos - e.delaystart; } else if (e.el.animElements) { e.el.cPos = time / ms; } if (time < 0) { continue; } if (time < ms) { var pos = easing(time / ms); ms = origms; for (var attr in from) if (from[has](attr)) { switch (availableAnimAttrs[attr]) { case nu: now = +from[attr] + pos * ms * diff[attr]; break; case "colour": if (!diff[attr].length) { tmpOpacity = (from[attr].opacity + pos * ms * diff[attr].opacity); if(isNaN(tmpOpacity)){ tmpOpacity = 1; } now = "rgba(" + [ upto255(round(from[attr].r + pos * ms * diff[attr].r)), upto255(round(from[attr].g + pos * ms * diff[attr].g)), upto255(round(from[attr].b + pos * ms * diff[attr].b)), tmpOpacity ].join(",") + ")"; } else { now = []; for (i = 0, ii = from[attr].length; i < ii; ++i) { if (i === 0) { if(from[attr].isRadial || diff[attr].isRadial){ radial = "xr("; radial += from[attr][0].f1 * (1 - pos) + diff[attr][0].f1 * pos || ''; radial += ','; radial += from[attr][0].f2 * (1 - pos) + diff[attr][0].f2 * pos || ''; radial += ','; radial += (from[attr][0].f3 * (1 - pos) + diff[attr][0].f3 * pos) * 100 || ''; radial += '%,'; radial += from[attr][0].f4 * (1 - pos) + diff[attr][0].f4 * pos || ''; radial += ','; radial += from[attr][0].f5 * (1 - pos) + diff[attr][0].f5 * pos; radial += ','; radial += from[attr][0].f6; radial += ')'; now.push(radial) } else { now.push((from[attr][i] * (1 - pos)) + (pos * diff[attr][i])); if (now[0] <= 0) { now[0] += 360; } } } else { now.push("rgba(" + [ upto255(round(from[attr][i].r + pos * ms * diff[attr][i].r)), upto255(round(from[attr][i].g + pos * ms * diff[attr][i].g)), upto255(round(from[attr][i].b + pos * ms * diff[attr][i].b)), (from[attr][i].opacity + pos * ms * diff[attr][i].opacity) ].join(",") + "):" + from[attr][i].position); } } now = now.join("-"); // If radial focus doesnt have a separator if(from[attr].isRadial || diff[attr].isRadial){ now = now.replace('-', ''); } } break; case "path": now = []; for (var i = 0, ii = from[attr].length; i < ii; i++) { now[i] = [from[attr][i][0]]; var jj; jj = from[attr][i] ? from[attr][i].length : 0; for (var j = 1 ; j < jj; j++) { now[i][j] = (+from[attr][i][j] + pos * ms * diff[attr][i][j]).toFixed(4); } now[i] = now[i].join(S); } now = now.join(S); break; case "transform": if (diff[attr].real) { now = []; for (i = 0, ii = from[attr].length; i < ii; i++) { now[i] = [from[attr][i][0]]; for (j = 1, jj = from[attr][i].length; j < jj; j++) { now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j]; } } } else { var get = function(i) { return +from[attr][i] + pos * ms * diff[attr][i]; }; // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]]; now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]]; } break; case "csv": if (attr == "clip-rect") { now = []; i = 4; while (i--) { now[i] = +from[attr][i] + pos * ms * diff[attr][i]; } } break; case "text-bound": now = [][concat](from[attr]); break; default: var from2 = [][concat](from[attr]); now = []; i = that.ca[attr].length; while (i--) { now[i] = +from2[i] + pos * ms * diff[attr][i]; } break; } set[attr] = now; } that.attr(set); if (executeEvent) { (function(id, that, anim) { setTimeout(function() { eve("raphael.anim.frame." + id, that, anim); }); })(that.id, that, e.anim); } } else { (function(f, el, a) { setTimeout(function() { executeEvent && eve("raphael.anim.frame." + el.id, el, a); executeEvent && eve("raphael.anim.finish." + el.id, el, a); R.is(f, "function") && f.call(el); }); })(e.callback, that, e.anim); that.attr(to); delete e.el; animationElements.splice(l--, 1); if (e.repeat > 1 && !e.next) { for (key in to) if (to[has](key)) { init[key] = e.totalOrigin[key]; } e.el.attr(init); runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1); } if (e.next && !e.stop) { runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat); } } } R.svg && that && that.paper && that.paper.safari(); // Starting animation on timer 0 for (l = 0, ll = deqArr.length; l < ll; ++l) { // lib.schedular.addJob((function (l) { // return function () { // runAnimation.apply(null, deqArr[l].params); // }; // })(l), lib.priorityList.instant); animFrameFn = R.getInstantAnimFrameFn(); animFrameFn((function (l) { return function () { runAnimation.apply(null, deqArr[l].params); }; })(l)); } animationElements.length && (requestAnimFrame || R.getAnimFrameFn())(animation); }, upto255 = function(color) { return color > 255 ? 255 : color < 0 ? 0 : color; }, checkPercentage = function (num) { num > 1 && (num = 1); num < 0 && (num = 0); return num; }; R.getAnimFrameFn = function () { return requestAnimFrame = R.requestAnimFrame || _win.webkitRequestAnimationFrame || _win.mozRequestAnimationFrame || _win.oRequestAnimationFrame || _win.msRequestAnimationFrame || function(callback) { setTimeout(callback, 16); }; }; R.getInstantAnimFrameFn = function () { return R.instantRequestAnimFrame || _win.webkitRequestAnimationFrame || _win.mozRequestAnimationFrame || _win.oRequestAnimationFrame || _win.msRequestAnimationFrame || function(callback) { setTimeout(callback, 16); }; }; /*\ * Element.animateWith [ method ] ** * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element. ** > Parameters ** - el (object) element to sync with - anim (object) animation to sync with - params (object) #optional final attributes for the element, see also @Element.attr - ms (number) #optional number of milliseconds for animation to run - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)` - callback (function) #optional callback function. Will be called at the end of animation. - configObject (object) #optional takes an object with optional properties like start(what percentage to start aniation), end(what percentage to end animation), hookFn(function to be called before applying animation), smartMorph(whether to use smartMorphing in path animation) * or - element (object) element to sync with - anim (object) animation to sync with - animation (object) #optional animation object, see @Raphael.animation ** = (object) original element \*/ elproto.animateWith = function(el, anim, params, ms, easing, callback, configObject) { var element = this, refOb = {}, key; // Copying the reference object configObject = configObject || {}; for (key in configObject) { if (configObject.hasOwnProperty(key)) { refOb[key] = configObject[key]; } } configObject = refOb; if (element.removed) { callback && callback.call(element); return element; } if (ms == 0) { if (R.is(callback, "function")) { setTimeout(function () { callback.call(element); }, 0); } return element.attr (params); } var a = params instanceof Animation ? params : R.animation(params, ms, easing, callback), x, y; configObject.start = checkPercentage(configObject.start || 0); configObject.end = checkPercentage(configObject.end || 1); if (configObject.start >= configObject.end){ configObject.start = configObject.end; } if (!configObject.from && configObject.start > 0.01) { // Initializing new Priority Queue if not present already el.animElements = el.animElements || new PriorityQueue(function comparator (a, b) { return b.pos - a.pos; }); el.animElements.enq({ pos: configObject.start, attr: configObject.start === configObject.end, params: [a, element, a.percents[0], null, element.attr(),undefined, el, { start: configObject.start, end: configObject.end, smartMorph: configObject.smartMorph, hookFn: configObject.hookFn }, params], executeOb: { el: this, attrs: params, callback: callback, hookFn: configObject.hookFn } }); } else { runAnimation(a, element, a.percents[0], null, element.attr(),undefined, el, configObject); } for (var i = 0, ii = animationElements.length; i < ii; i++) { if (animationElements[i].anim == anim && animationElements[i].el == el) { animationElements[ii - 1].start = animationElements[i].start; break; } } return element; // var a = params ? R.animation(params, ms, easing, callback) : anim, // status = element.status(anim); // return this.animate(a).status(a, status * anim.ms / a.ms); }; function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) { var cx = 3 * p1x, bx = 3 * (p2x - p1x) - cx, ax = 1 - cx - bx, cy = 3 * p1y, by = 3 * (p2y - p1y) - cy, ay = 1 - cy - by; function sampleCurveX(t) { return ((ax * t + bx) * t + cx) * t; } function solve(x, epsilon) { var t = solveCurveX(x, epsilon); return ((ay * t + by) * t + cy) * t; } function solveCurveX(x, epsilon) { var t0, t1, t2, x2, d2, i; for (t2 = x, i = 0; i < 8; i++) { x2 = sampleCurveX(t2) - x; if (abs(x2) < epsilon) { return t2; } d2 = (3 * ax * t2 + 2 * bx) * t2 + cx; if (abs(d2) < 1e-6) { break; } t2 = t2 - x2 / d2; } t0 = 0; t1 = 1; t2 = x; if (t2 < t0) { return t0; } if (t2 > t1) { return t1; } while (t0 < t1) { x2 = sampleCurveX(t2); if (abs(x2 - x) < epsilon) { return t2; } if (x > x2) { t0 = t2; } else { t1 = t2; } t2 = (t1 - t0) / 2 + t0; } return t2; } return solve(t, 1 / (200 * duration)); } elproto.onAnimation = function(f) { f ? eve.on("raphael.anim.frame." + this.id, f) : eve.unbind("raphael.anim.frame." + this.id); return this; }; function Animation(anim, ms) { var percents = [], newAnim = {}; this.ms = ms; this.times = 1; if (anim) { for (var attr in anim) if (anim[has](attr)) { newAnim[toFloat(attr)] = anim[attr]; percents.push(toFloat(attr)); } percents.sort(sortByNumber); } this.anim = newAnim; this.top = percents[percents.length - 1]; this.percents = percents; } /*\ * Animation.delay [ method ] ** * Creates a copy of existing animation object with given delay. ** > Parameters ** - delay (number) number of ms to pass between animation start and actual animation ** = (object) new altered Animation object | var anim = Raphael.animation({cx: 10, cy: 20}, 2e3); | circle1.animate(anim); // run the given animation immediately | circle2.animate(anim.delay(500)); // run the given animation after 500 ms \*/ Animation.prototype.delay = function(delay) { var a = new Animation(this.anim, this.ms); a.times = this.times; a.del = +delay || 0; return a; }; /*\ * Animation.repeat [ method ] ** * Creates a copy of existing animation object with given repetition. ** > Parameters ** - repeat (number) number iterations of animation. For infinite animation pass `Infinity` ** = (object) new altered Animation object \*/ Animation.prototype.repeat = function(times) { var a = new Animation(this.anim, this.ms); a.del = this.del; a.times = math.floor(mmax(times, 0)) || 1; return a; }; /* ** Function to convert two color string in array format such that ** it is animatabale ** @param {string} c1 color 1 ** @param {string} c2 color 2 ** @param {function} function to getRGB */ function colorNormalizer(c1, c2, getRGB) { "use strict"; var colorAr1, colorAr2, i = 0, ii = 0, j = 0, newColArr = [], newColArr2 = [], temp = {}, pos = 0, uniqArr = []; c1 = c1.constructor === Array ? c1[0]: c1; c2 = c2.constructor === Array ? c2[0]: c2; colorAr1 = c1.split('-'); colorAr2 = c2.split('-'); if (colorAr1.length === 1 && colorAr2.length === 1) { return [c1, c2]; } // Convert colors to linear format, and mark if any of them is radial // linear to radial animation is not correct colorAr1 = allToLinear(colorAr1); colorAr2 = allToLinear(colorAr2); // Handling if default color was added to one // and not other if (!colorAr1.defaultAngleSet && colorAr2.defaultAngleSet) { colorAr2[0] = colorAr1[0]; } if (!colorAr2.defaultAngleSet && colorAr1.defaultAngleSet) { colorAr1[0] = colorAr2[0]; } // If one is radial convert both to radial converToRadialIfOneRadial(colorAr1, colorAr2); /* Making a unique array to store all unique color positions of both color so that new color can be generated that have same amount of positions added */ for(i = 1, ii = colorAr1.length; i < ii; ++i){ pos = colorAr1[i].position; // if(uniqArr.indexOf(pos) === -1){ uniqArr.push(pos); // } } for(i = 1, ii = colorAr2.length; i < ii; ++i){ pos = colorAr2[i].position; if(uniqArr.indexOf(pos) === -1){ uniqArr.push(pos); } } uniqArr.push(0); // sort the positions uniqArr.sort(function(a,b){return a - b}); // generating new colors from the existing colors newColArr = [colorAr1[0]]; for (i = 1, ii = uniqArr.length; i < ii; ++i) { pos = uniqArr[i]; temp = colorAr1.getColorAtPosition(pos); newColArr.push(temp); } newColArr2 = [colorAr2[0]]; for (i = 1, ii = uniqArr.length; i < ii; ++i) { pos = uniqArr[i]; temp = colorAr2.getColorAtPosition(pos); newColArr2.push(temp); } // copying isRadial property newColArr.isRadial = colorAr1.isRadial; newColArr2.isRadial = colorAr2.isRadial; return [newColArr, newColArr2]; // Getting all unique points function converToRadialIfOneRadial(a, b, end){ var angle = 0; if(a.isRadial && !b.isRadial){ angle += +b[0]; b[0] = { f1: 0, f2: 0, f3: 0, f4: 0, f5: 0, f6: '' } b.isRadial = true; } if(!end){ converToRadialIfOneRadial(b, a, true); } } // Function to convert color to array in linear format // and mark if any one of them is radial function allToLinear(arr) { var i = 0, ii = 0, j = 0, item = {}, temp = [], temp2 = {}, key, prevVal = 0, lastVal = 0, counter = 0, rPos = 0, openBrPos = 0, closedBrPos = 0, radial = { f1 : 0.5, f2 : 0.5 }; // Solid color operation if (arr.length === 1) { if(arr[0] === "none"){ arr[0] = "rgba(0,0,0,0)"; } // Push angle zero to start arr.unshift(0); // Mentioning that a default angle was added arr.defaultAngleSet = true; } // Convert angle to number if (isNaN(arr[0])) { // Check if is radial if(~"rx".indexOf(arr[0].charAt(0))){ arr.isRadial = true; rPos = 1; // check if focus if provided // otherwise use default focus if(arr[0].indexOf(')') !== -1){ rPos = arr[0].indexOf(')'); openBrPos = arr[0].indexOf('(') + 1; closedBrPos = rPos; temp = arr[0].substr(openBrPos, closedBrPos - openBrPos).split(','); radial.f1 = parseFloat(temp[0]) || 0; radial.f2 = parseFloat(temp[1]) || 0; if (~temp[2].indexOf('%')) { temp[2] = parseFloat(temp[2]) / 100; } radial.f3 = parseFloat(temp[2]) || 0; radial.f4 = parseFloat(temp[3]) || 0; radial.f5 = parseFloat(temp[4]) || 0; radial.f6 = temp[5]; } arr[0] = arr[0].substr(closedBrPos + 1); arr.unshift(radial); } else { arr[0] = 0; } } else { arr[0] = +arr[0]; } for (i = 1, ii = arr.length; i < ii; ++i) { temp = arr[i].split(":"); // conver first element to rgb object and store temp2 = getRGB(temp[0]); arr[i] = {}; arr[i].r = temp2.r; arr[i].g = temp2.g; arr[i].b = temp2.b; arr[i].opacity = temp2.opacity; // if opacity not present set to 1 arr[i].opacity = +arr[i].opacity; if (isNaN(arr[i].opacity)) { arr[i].opacity = 1; } // set the position arr[i].position = +temp[1]; } // Sorting array according to position // angle and radial focus should be elemnt 0 arr.sort(function(a, b) { if (typeof a === "number" || a.f1) { return -1; } if (typeof b === "number" || a.f2) { return 1; } if (isNaN(a.position) && isNaN(b.position)) { return 0; } if (isNaN(a.position)) { return -1; } if (isNaN(b.position)) { return 1; } return a.position - b.position; }); // If first position is not zero // add new color with position zero if (+arr[1].position !== 0) { if (isNaN(arr[1].position)) { arr[1].position = 0; } else { temp2 = {}; for (key in arr[1]) { temp2[key] = arr[1][key]; } temp2.position = 0; // Shifting array to add current object // in position 1 arr.push({}); for (i = arr.length - 1; i !== 1; --i) { arr[i] = arr[i - 1]; } arr[1] = temp2; } } // index to last position ii = arr.length - 1; // If last position is not 100 // add new color with position 100 if (arr[ii].position !== 100) { if (isNaN(arr[ii].position)) { arr[ii].position = 100; } else { temp2 = {}; for (key in arr[ii]) { temp2[key] = arr[ii][key]; } temp2.position = 100; // Shifting array to add current object // in position 1 arr.push(temp2); } } // Filling correct position value whereever NaN found for (i = 2, ii = arr.length; i < ii; ++i) { if (!(arr[i].position)) { prevVal = arr[i - 1].position; counter = 1; for (j = i + 1; j < ii; ++j) { ++counter; if (!isNaN(arr[j].position)) { lastVal = +arr[j].position; break; } } arr[i].position = prevVal + ((lastVal - prevVal) / counter); } } arr.getColorAtPosition = function(pos) { var prevPos = -1, nextPos = this.length, i = 1, ii = this.length, item = {}, colPrev, colNext, ratio = 0, key = "", col = { r: 0, g: 0, b: 0 }; // Critical section; check again for (; i < ii - 1; ++i) { if (this[i].position <= pos) { prevPos = i; nextPos = i + 1; } if (!(this[i].position < pos) && this[i].position >= pos) { nextPos = i; break; } } ratio = (pos - this[prevPos].position) / (this[nextPos].position - this[prevPos].position); if (isNaN(ratio)) { ratio = 0; } for (key in col) { col[key] = upto255((1 - ratio) * this[prevPos][key] + ratio * this[nextPos][key]); } col.position = pos; col.opacity = (1 - ratio) * this[prevPos]["opacity"] + ratio * this[nextPos]["opacity"]; return col; } return arr; } } /** * Function to make to uncommon path array to a equal length * of path array and same type (L - lineto) to make it animatable * @param {array} path array 1 * @param {array} path array 2 * @return {object} object containing final 'from' and 'to' path */ function pathNormalizer(p1, p2) { 'use strict'; // Function to convert array to svg path (?) only for curves var finalp1 = [], finalp2 = [], pathArr1 = toSvgPath(p1), pathArr2 = toSvgPath(p2), i = 0, ii = 0, temp, createElementNS = document.createElementNS && document.createElementNS.bind(document), dPath = createElementNS && createElementNS("http://www.w3.org/2000/svg", "path"); // If path invalid or svg not supported return if (!pathArr1 || !pathArr2 || !dPath) { return [p1, p2]; } if (canFallback(p1, p2)) { return [p1, p2]; } // If any of the parameters is // absent return to normal flow if (!p1 || !p2) { return [p1, p2]; } // If svg not available return to normal flow if (!document.createElementNS) { return [p1, p2]; } // Setting path again pathArr1 = toSvgPath(p1); pathArr2 = toSvgPath(p2); // If invalid path return the original path if(pathArr1.join().indexOf('undefined') !== -1) { return [p1, p2]; } if(pathArr2.join().indexOf('undefined') !== -1) { return [p1, p2]; } // If svg functions not available return to normal flow if (!dPath.getTotalLength || !dPath.getPointAtLength) { return [p1, p2]; } /* Function to check if the current environment ** can animate the path, as pathNormalizer pauses ** getTotalLength and getPointAtLength function of svg ** which are not supported by all browsers */ function canFallback (path1, path2) { var str1 = '', str2 = '', testLen, testPoint; // Checking path totoalLength is accurate or not // testing with a known path // this check is for Firefox dPath.setAttribute('d', 'M300 10 L300 300 C50 310,50 640,350 650' + 'C600 640,600 310,400 300 L400 10 L295 10'); testLen = dPath.getTotalLength(); testPoint = dPath.getPointAtLength(10); if (testLen < 1829.1 || testLen > 1829.2) { return true; } if (Math.round(testPoint.x) !== 300 || Math.round(testPoint.y) !== 20) { return true; } // path1 and path2 are in array function trimPathArray (arr) { var i = arr.length; while (i-- - 1) { if (arr[i].join('') === arr[i - 1].join('')) { arr.pop(); } else { break; } } } function getPathFromArray(arr) { var str = '', i = 0, ii = arr.length; for (; i < ii; ++i) { str += arr[i].join(' '); } return str; } trimPathArray(path1); trimPathArray(path2); str1 = getPathFromArray(path1); str2 = getPathFromArray(path2); if (str1.split(/[Mm]/).length > 2 || str2.split(/[Mm]/).length > 2) { return false; } if (path1.length === path2.length) { return true; } return false; } /* Convert svg path array to string, Also removes repeated commands */ function toSvgPath(arr) { var str = [], i = 0, ii = arr.length, item = []; if (typeof arr === 'string') { return arr; } // Converting the array to string; path type for (i = 0; i < ii; ++i) { if (!arr[i].join){ return; } else { // Removing continuous Move commands // Picking up the last one if ( !i || !arr[i + 1] || arr[i + 1][0] !== 'M' || arr[i][0] !== 'M'){ str.push(arr[i].join(' ')); } } } str = str.join(''); str = str.split(/[Mm]/).slice(1); for (i = 0, ii = str.length; i < ii; ++i) { str[i] = 'M' + str[i]; } return str; } ii = Math.max(pathArr1.length, pathArr2.length); for (i = 0; i < ii; ++i) { temp = _pathNormalizer(pathArr1[i], pathArr2[i]); pathArr1[i] = temp[0]; pathArr2[i] = temp[1]; } // Convert line path 2 dimensional array to string function linetopath (arr) { var i = 0, ii = 0, str = []; arr = arr || []; ii = arr.length; for (i = 0; i < ii; ++i) { if (arr[i].length - 1) { str.push(arr[i].join(' ')); } } return str.join(''); } /* path2curve appends repeated last path command, this function removes it or any other repeated path command */ function removeBlanks (arr, pos) { var i = arr.length, j = 0, path; while (i-- - 1) { // Pop if length is zero if (arr[i].slice(1).toString() === arr[i - 1].slice(1).toString()) { arr.pop(); } else { break; } } if (arr.length === 1 && pos){ arr.length = 0; } } /* Divide a path array to number to a given number of times as provided in parameters, All path array should start with M command */ function _divide(arr, times) { var resArr = [], locArr = [], arrLen = arr.length, i = 0, ii = 0, x = 0, prevPos = 0, y = 0, // If array size is smaller than // divisions needed diffTimes = times - arrLen; while (diffTimes >= 0) { i = arr.length - 1; arr.push(arr.slice(i)[0]); --diffTimes; } arrLen = arr.length; for (i = 0; i <= times; ++i) { locArr.push(Math.round((i / times) * arrLen)); } for (i = 0, ii = locArr.length - 1; i < ii; ++i) { resArr.push(arr.slice(locArr[i], locArr[i + 1])); if (resArr[i][0][0] !== 'M' && resArr[i][0][0] !== 'm') { prevPos = resArr[i - 1].length - 1; x = resArr[i - 1][prevPos][1]; y = resArr[i - 1][prevPos][2]; resArr[i].unshift(['M', x, y]); } } return resArr; } /* If two path array have different number of MoveTo commands, divide the smaller number of MoveTo command holder to match the other one */ function divideArray (diff) { var arrToDivide = [], countArr = [], transArr = [], i = 0, ii = 0, isArr1 = true; if (diff === 0) { return; } else if (diff > 0) { arrToDivide = pathArr2; isArr1 = false; } else { diff = -diff; arrToDivide = pathArr1; } // Maintaining a count array to judge number of times a1 // path needs to be divided, 1 means dont divide for (i = 0, ii = arrToDivide.length; i < ii; ++i) { countArr.push(1); } while (diff--) { --i; if (i < 0) { i = ii - 1; } countArr[i]++; } for (i = 0; i < ii; ++i){ if (countArr[i] === 1) { transArr.push(arrToDivide[i]); } else { transArr.push.apply(transArr, _divide(arrToDivide[i], countArr[i])); } } if (isArr1) { pathArr1 = transArr; } else { pathArr2 = transArr; } } for (i = pathArr1.length; i--;) { removeBlanks(pathArr1[i], i); // If last element is blank pop it pathArr1[i].length || pathArr1.pop(); } for (i = pathArr2.length; i--;) { removeBlanks(pathArr2[i], i); pathArr2[i].length || pathArr2.pop(); } // Making number off moveto commands equal in both path divideArray(pathArr1.length - pathArr2.length); ii = Math.max(pathArr1.length, pathArr2.length); for (i = 0; i < ii; ++i) { temp = _pathNormalizer(linetopath(pathArr1[i]), linetopath(pathArr2[i])); pathArr1[i] = temp[0]; pathArr2[i] = temp[1]; } for (i = 0, ii = pathArr1.length; i < ii; ++i) { finalp1 = finalp1.concat(pathArr1[i]); } for (i = 0, ii = pathArr2.length; i < ii; ++i) { finalp2 = finalp2.concat(pathArr2[i]); } return [finalp1, finalp2]; } // A function to calculate common path // in two given paths function commonPathCalculator (p1, p2) { 'use strict'; var i = 0, j = 0, ii = 0, jj = 0, k = 0, kk = 0, uncommon1 = 0, uncommon2 = 0, lim1 = 0, lim2 = 0, nearestPoint1, nearestPoint2, map1 = {}, map2 = {}, groupedPath1 = [], groupedPath2 = [], gpIndex1 = -1, gpIndex2 = -1, isSame = true; // Splitting the string commands to get // particular points later // Will be required while breaking paths // into common and uncommon parts function splitter (path) { var i = 0, ii = 0; path = path.split(/[MCLmcl]/).slice(1); for (i = 0, ii = path.length; i < ii; ++i) { path[i] = path[i].split(' ').slice(1); i || path[i].unshift('M'); if (i) { path[i].length === 2 && path[i].unshift('L') || path[i].unshift('C'); } } return path; } // populate the arr to object in reverse manner // i.e value to key mapping function mapper (arr, ob) { var i = 0, ii = arr.length, val, item; for (i = 0, ii = arr.length; i < ii; ++i) { val = arr[i].join(' '); item = arr[i]; if (item[0] === 'C' && item[3] === item[5] && item[4] === item[6]) { arr[i].stringValue = ['L', item[3], item[4]].join(' '); } else item.stringValue = val; // Creating an array if undefined // pushing otherwise ob[item.stringValue] && ob[item.stringValue].push(i); ob[item.stringValue] || (ob[item.stringValue] = [i]); } } // Function to get nearest point that exist // in the other array function getNearestExistingPoint (arr, map, start, ii, lim) { var i = start, k = 0, kk = 0, item; for (; i < ii; ++i) { item = map[arr[i].stringValue]; if (item) { for (k = 0, kk = item.length; k < kk; ++k) { if (item[k] >= lim) { return { index : i, mapValue : item[k], diff : i - start }; } } } } return -1; } // function to get last coordinate for CurveTo command function getCoordinateAsMove (arr) { var last = arr.length - 1; return ['M', arr[last - 1], arr[last]].join(' '); } // function to conver path array to string function pathToString (arr) { return arr.join(''); } // commonPathCalculator flow here p1 = splitter(p1); p2 = splitter(p2); mapper(p1, map1); mapper(p2, map2); // Setting length ii = p1.length; jj = p2.length; i = 0; j = 0; // Making partitions for common // and uncommon parts // Checking if first is common or uncommon while (i < ii && j < jj) { ++gpIndex1; ++gpIndex2; // initializing blank arrays groupedPath1[gpIndex1] = []; groupedPath2[gpIndex2] = []; isSame = (p1[i].stringValue === p2[j].stringValue); if (i) { // Logic to push prev coordinate as move command groupedPath1[gpIndex1].push(getCoordinateAsMove(p1[i - 1])); groupedPath2[gpIndex2].push(getCoordinateAsMove(p2[j - 1])); } if (isSame) { while (i < ii && j < jj && p1[i].stringValue === p2[j].stringValue) { groupedPath1[gpIndex1].push(p1[i].stringValue); groupedPath2[gpIndex2].push(p2[j].stringValue); ++i; ++j; } } else { nearestPoint1 = getNearestExistingPoint(p1, map2, i, ii, j); nearestPoint2 = getNearestExistingPoint(p2, map1, j, jj, i); // Assuming nearestPoint1 is nearer than nearestPoint2 lim1 = nearestPoint1.index; lim2 = nearestPoint1.mapValue; // If nearestPoint2 is nearer if (!~nearestPoint1 || nearestPoint1.diff > nearestPoint2.diff) { lim1 = nearestPoint2.mapValue; lim2 = nearestPoint2.index; } if (!~nearestPoint1 && !~nearestPoint2) { // If both not found include all as uncommon lim1 = ii - 1; lim2 = jj - 1; } // Pushing uncommon paths while (i <= lim1) { groupedPath1[gpIndex1].push(p1[i].stringValue); ++i; } while (j <= lim2) { groupedPath2[gpIndex2].push(p2[j].stringValue); ++j; } } groupedPath1[gpIndex1] = pathToString(groupedPath1[gpIndex1]); groupedPath2[gpIndex2] = pathToString(groupedPath2[gpIndex2]); } // If Any one is left add them all if (i < ii) { ++gpIndex1; groupedPath1[gpIndex1] = []; groupedPath1[gpIndex1].push(getCoordinateAsMove(p1[i - 1])); ++gpIndex2; groupedPath2[gpIndex2] = []; groupedPath2[gpIndex2].push(getCoordinateAsMove(p2[j - 1])); while(i < ii) { groupedPath1[gpIndex1].push(p1[i].stringValue); ++i; } groupedPath1[gpIndex1] = pathToString(groupedPath1[gpIndex1]); } if (j < jj) { ++gpIndex1; groupedPath1[gpIndex1] = []; groupedPath1[gpIndex1].push(getCoordinateAsMove(p1[i - 1])); ++gpIndex2; groupedPath2[gpIndex2] = []; groupedPath2[gpIndex2].push(getCoordinateAsMove(p2[j - 1])); while(j < jj) { groupedPath2[gpIndex2].push(p2[j].stringValue); ++j; } groupedPath2[gpIndex2] = pathToString(groupedPath2[gpIndex2]); } return [groupedPath1, groupedPath2]; } // function to get equal points for two different path // We set path to an dynamically created svg path node // and get equal number of path commands from two different // paths. Uses getPointAtLength and getTotalLength of svg that // arent supported on every browser function _pathNormalizer(p1, p2) { 'use strict'; var i = 0, j = 0, ii = 0, jj = 0, item = {}, fPath1 = [], fPath2 = [], divisions = 0, commonPath, tmp; // Uncommon path normalizer function normalizeUncommonPaths (p1, p2) { var dPath1, dPath2, i = 0, j = 0, item = {}, pathLen1 = 0, pathLen2 = 0, fPath1 = [], fPath2 = [], divisions = 0, round = Math.round; // Creating path elements to use functions 'getTotalLength' // and 'getPointAtLength' dPath1 = document.createElementNS("http://www.w3.org/2000/svg", "path"); dPath1.setAttribute("d", p1); dPath2 = document.createElementNS("http://www.w3.org/2000/svg", "path"); dPath2.setAttribute("d", p2); // Getting length of the paths pathLen1 = dPath1.getTotalLength(); pathLen2 = dPath2.getTotalLength(); // Number of divisions will depend on larger path divisions = 0.15 * Math.max(pathLen1, pathLen2); divisions = Math.ceil(divisions); if (!divisions || !isFinite(divisions) || divisions < 10) { divisions = 10; } for (i = 0; i <= divisions; ++i) { item = dPath1.getPointAtLength((i / divisions) * pathLen1); fPath1.push([i ? "L" : "M", round(item.x), round(item.y) ]); item = dPath2.getPointAtLength((i / divisions) * pathLen2); fPath2.push([i ? "L" : "M", round(item.x), round(item.y) ]); } return [fPath1, fPath2]; } if (!p1 || p1 === 'M ') { p1 = p2.split(' ').slice(0, 3).join(' ').replace(/[LC]/, ''); } if (!p2 || p2 === 'M ') { p2 = p1.split(' ').slice(0, 3).join(' ').replace(/[LC]/, ''); } commonPath = commonPathCalculator(p1, p2); for (i = 0, ii = commonPath[0].length; i < ii; ++i) { tmp = normalizeUncommonPaths(commonPath[0][i], commonPath[1][i]); if (i) { fPath1 = fPath1.concat(tmp[0].slice(1)); fPath2 = fPath2.concat(tmp[1].slice(1)); } else { fPath1 = fPath1.concat(tmp[0]); fPath2 = fPath2.concat(tmp[1]); } } return [fPath1, fPath2]; } function runAnimation(anim, element, percent, status, totalOrigin, times, parentEl, configObject) { percent = toFloat(percent); var params, isInAnim, isInAnimSet, percents = [], next, prev, temp, timestamp, tempDiff, change, ms = anim.ms, from = {}, to = {}, diff = {}; if (element.type === null) { return; } configObject = configObject || {}; configObject.hookFn && configObject.hookFn.call(element); configObject.from = configObject.from || {}; if (status) { for (i = 0, ii = animationElements.length; i < ii; i++) { var e = animationElements[i]; if (e.el.id == element.id && e.anim == anim) { if (e.percent != percent) { delete e.el.e; delete e.el; animationElements.splice(i, 1); isInAnimSet = 1; } else { isInAnim = e; } element.attr(e.totalOrigin); break; } } } else { status = +to; // NaN } for (var i = 0, ii = anim.percents.length; i < ii; i++) { if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) { percent = anim.percents[i]; prev = anim.percents[i - 1] || 0; ms = ms / anim.top * (percent - prev); next = anim.percents[i + 1]; params = anim.anim[percent]; break; } else if (status) { element.attr(anim.anim[anim.percents[i]]); } } if (!params) { return; } if (!isInAnim) { for (var attr in params) if (params[has](attr)) { if (availableAnimAttrs[has](attr) || element.ca[attr]) { from[attr] = configObject.from[attr] || element.attr(attr); (from[attr] == null) && (from[attr] = availableAttrs[attr]); to[attr] = params[attr]; change = false; switch (availableAnimAttrs[attr]) { case nu: tempDiff = to[attr] - from[attr]; (tempDiff || isNaN(tempDiff)) && (change = true); diff[attr] = tempDiff / ms; break; case "colour": if(from[attr] === to[attr]){ break; } else { change = true; } var colorsNormalized = colorNormalizer(from[attr], to[attr], R.getRGB); from[attr] = colorsNormalized[0]; var toColour = colorsNormalized[1]; if (typeof toColour === "string") { if(from[attr].toLowerCase() !== "none"){ from[attr] = R.getRGB(from[attr]); if(!from[attr].opacity){ from[attr].opacity = 1; } } else { from[attr] = { r : 0, g : 0, b : 0, opacity : 0 } } if(to[attr].toLowerCase() !== "none"){ toColour = R.getRGB(to[attr]); if(!toColour.opacity){ toColour.opacity = 1; } } else { toColour = { r : 0, g : 0, b : 0, opacity : 0 } } diff[attr] = { r: (toColour.r - from[attr].r) / ms, g: (toColour.g - from[attr].g) / ms, b: (toColour.b - from[attr].b) / ms, opacity: ((toColour.opacity - from[attr].opacity) / ms) }; } else { diff[attr] = []; for (i = 0, ii = from[attr].length; i < ii; ++i) { if (i === 0) { diff[attr].push(toColour[0]); } else { diff[attr].push({ r: (toColour[i].r - from[attr][i].r) / ms, g: (toColour[i].g - from[attr][i].g) / ms, b: (toColour[i].b - from[attr][i].b) / ms, opacity: (toColour[i].opacity - from[attr][i].opacity) / ms }); } } } break; case "path": var toPath, pathes = path2curve(from[attr], to[attr]); if (configObject.smartMorph) { pathes = pathNormalizer(pathes[0], pathes[1], configObject); } toPath = pathes[1]; from[attr] = pathes[0]; diff[attr] = []; for (i = 0, ii = from[attr].length; i < ii; i++) { diff[attr][i] = [0]; var jj; jj = from[attr][i] ? from[attr][i].length : 0; for (var j = 1; j < jj; j++) { diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms; (!change) && diff[attr][i][j] && (change = true); } } break; case "transform": var _ = element._, eq = equaliseTransform(_[attr], to[attr]); change = true; if (eq) { from[attr] = eq.from; to[attr] = eq.to; diff[attr] = []; diff[attr].real = true; for (i = 0, ii = from[attr].length; i < ii; i++) { diff[attr][i] = [from[attr][i][0]]; for (j = 1, jj = from[attr][i].length; j < jj; j++) { diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms; } } } else { var m = (element.matrix || new Matrix), to2 = { _: { transform: _.transform }, getBBox: function() { return element.getBBox(1); } }; from[attr] = [ m.a, m.b, m.c, m.d, m.e, m.f ]; extractTransform(to2, to[attr]); to[attr] = to2._.transform; diff[attr] = [ (to2.matrix.a - m.a) / ms, (to2.matrix.b - m.b) / ms, (to2.matrix.c - m.c) / ms, (to2.matrix.d - m.d) / ms, (to2.matrix.e - m.e) / ms, (to2.matrix.f - m.f) / ms ]; // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy]; // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }}; // extractTransform(to2, to[attr]); // diff[attr] = [ // (to2._.sx - _.sx) / ms, // (to2._.sy - _.sy) / ms, // (to2._.deg - _.deg) / ms, // (to2._.dx - _.dx) / ms, // (to2._.dy - _.dy) / ms // ]; } break; case "csv": var values = Str(params[attr])[split](separator), from2 = Str(from[attr])[split](separator); if (attr == "clip-rect") { from[attr] = from2; diff[attr] = []; i = from2.length; while (i--) { tempDiff = values[i] - from[attr][i]; (tempDiff || isNaN(tempDiff)) && (change = true); diff[attr][i] = tempDiff / ms; } } to[attr] = values; break; default: values = [][concat](params[attr]); from2 = [][concat](from[attr]); diff[attr] = []; i = element.ca[attr].length; while (i--) { tempDiff = (values[i] || 0) - (from2[i] || 0); (tempDiff || isNaN(tempDiff)) && (change = true); diff[attr][i] = tempDiff / ms; } break; } if (!change) { delete from[attr]; delete to[attr]; delete params[attr]; delete diff[attr]; } } else if (R._availableAttrs[has](attr) || attr === 'text' || element.ca[attr]) { element.attr(attr, params[attr]); delete params[attr]; } } var easing = params.easing, easyeasy = R.easing_formulas[easing]; if (!easyeasy) { easyeasy = Str(easing).match(bezierrg); if (easyeasy && easyeasy.length == 5) { var curve = easyeasy; easyeasy = function(t) { return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms); }; } else { easyeasy = pipe; } } timestamp = params.start || anim.start || +new Date; element.e = e = { anim: anim, percent: percent, timestamp: timestamp, start: timestamp + (anim.del || 0), status: 0, initstatus: status || 0, stop: false, ms: ms, easing: easyeasy, from: from, diff: diff, to: to, el: element, callback: params.callback, prev: prev, next: next, repeat: times || anim.times, origin: element.attr(), totalOrigin: totalOrigin, parentEl : parentEl, delayend: configObject && configObject.end, delaystart: configObject && configObject.start }; animationElements.push(e); if (status && !isInAnim && !isInAnimSet) { e.stop = true; e.start = new Date - ms * status; if (animationElements.length == 1) { return animation(); } } if (isInAnimSet) { e.start = new Date - e.ms * status; } animationElements.length == 1 && (requestAnimFrame || R.getAnimFrameFn())(animation); } else { isInAnim.initstatus = status; isInAnim.start = new Date - isInAnim.ms * status; } eve("raphael.anim.start." + element.id, element, anim); } /*\ * Raphael.animation [ method ] ** * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods. * See also @Animation.delay and @Animation.repeat methods. ** > Parameters ** - params (object) final attributes for the element, see also @Element.attr - ms (number) number of milliseconds for animation to run - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)` - callback (function) #optional callback function. Will be called at the end of animation. ** = (object) @Animation \*/ R.animation = function(params, ms, easing, callback, stopPartialEventPropagation) { if (params instanceof Animation) { return params; } if (R.is(easing, "function") || !easing) { callback = callback || easing || null; easing = null; } !R.stopPartialEventPropagation && (R.stopPartialEventPropagation = stopPartialEventPropagation); params = Object(params); ms = +ms || 0; var p = {}, json, attr; for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) { json = true; p[attr] = params[attr]; } // Enabling the callback to be called even if attr is not provided callback && (json = true); if (!json) { return new Animation(params, ms); } else { easing && (p.easing = easing); callback && (p.callback = callback); return new Animation({ 100: p }, ms); } }; /*\ * Element.animate [ method ] ** * Creates and starts animation for given element. ** > Parameters ** - params (object) final attributes for the element, see also @Element.attr - ms (number) number of milliseconds for animation to run - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)` - callback (function) #optional callback function. Will be called at the end of animation. * or - animation (object) animation object, see @Raphael.animation ** = (object) original element \*/ elproto.animate = function(params, ms, easing, callback) { var element = this; if (element.removed) { callback && callback.call(element); return element; } var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback); runAnimation(anim, element, anim.percents[0], null, element.attr()); return element; }; /*\ * Element.status [ method ] ** * Gets or sets the status of animation of the element. ** > Parameters ** - anim (object) #optional animation object - value (number) #optional 0 – 1. If specified, method works like a setter and sets the status of a given animation to the value. This will cause animation to jump to the given position. ** = (number) status * or = (array) status if `anim` is not specified. Array of objects in format: o { o anim: (object) animation object o status: (number) status o } * or = (object) original element if `value` is specified \*/ elproto.status = function(anim, value) { var out = [], i = 0, len, e; if (value != null) { runAnimation(anim, this, -1, mmin(value, 1)); return this; } else { len = animationElements.length; for (; i < len; i++) { e = animationElements[i]; if (e.el.id == this.id && (!anim || e.anim == anim)) { if (anim) { return e.status; } out.push({ anim: e.anim, status: e.status }); } } if (anim) { return 0; } return out; } }; /*\ * Element.pause [ method ] ** * Stops animation of the element with ability to resume it later on. ** > Parameters ** - anim (object) #optional animation object - resumeChildAnimation (boolean) #pauses the animation of the elements which are in sync with the current element ** = (object) original element \*/ elproto.pause = function(anim, pauseChildAnimation) { var now = +new Date, e, i; for (i = 0; i < animationElements.length; i++) { e = animationElements[i]; // @todo - need a scope to implement the logic for nested animations. if ((e.el.id === this.id || (pauseChildAnimation && e.parentEl && e.parentEl.e.el && e.parentEl.e.el.id === this.id)) && (!anim || e.anim == anim)) { if (eve("raphael.anim.pause." + this.id, this, e.anim) !== false) { e.paused = true; e.pauseStart = now; } } } return this; }; /*\ * Element.resume [ method ] ** * Resumes animation if it was paused with @Element.pause method. ** > Parameters ** - anim (object) #optional animation object - resumeChildAnimation (boolean) #resumes the animation of the elements which are in sync with the current element ** = (object) original element \*/ elproto.resume = function(anim, resumeChildAnimation) { var now = +new Date, e, i; for (i = 0; i < animationElements.length; i++) { e = animationElements[i]; // @todo - need a scope to implement the logic for nested animations. if ((e.el.id === this.id || (resumeChildAnimation && e.parentEl && e.parentEl.e.el && e.parentEl.e.el.id === this.id)) && (!anim || e.anim == anim)) { if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) { delete e.paused; e.el.status(e.anim, e.status); e.pauseEnd = now; e.start += (((e.parentEl && e.parentEl.e.pauseEnd || e.pauseEnd) - (e.parentEl && e.parentEl.e.pauseStart || e.pauseStart)) || 0); } } } return this; }; /*\ * Element.stop [ method ] ** * Stops animation of the element. ** > Parameters ** - anim (object) #optional animation object - stopChildAnimation (boolean) #optional stops the animation of all the element which are in sync with the current element - jumpToEnd (boolean) #optional takes the current animation to its end value ** = (object) original element \*/ elproto.stop = function(anim, stopChildAnimation, jumpToEnd) { var e, i, ele; if (stopChildAnimation) { for (i = animationElements.length - 1; i >= 0; i--) { e = animationElements[i]; // @todo - need a scope to implement the logic for nested animations. if ((e.el.id === this.id || (e.parentEl && e.parentEl.id === this.id)) && (!anim || animationElements[i].anim == anim)) { ele = e.el; jumpToEnd && ele.attr(e.to); e.callback && e.callback.call(ele); delete ele.e; delete e.el; animationElements.splice(i, 1); } } } else { for (var i = 0; i < animationElements.length; i++){ e = animationElements[i]; if (e.el.id === this.id && (!anim || e.anim === anim)) { if (eve("raphael.anim.stop." + this.id, this, e.anim) !== false) { animationElements.splice(i--, 1); } } } } // In case root object has hooked animation elements // in priority queue execute them all if (this.animElements) { executeAnimQueue(this.animElements); } return this; }; function executeAnimQueue (queue) { var ob; // Looping until all executed while (ob = queue.deq()) { ob = ob.executeOb; ob.hookFn && ob.hookFn.call(ob.el); ob.el.attr(ob.attrs); ob.callback && ob.callback.call(ob.el); } } function stopAnimation(paper) { for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.paper == paper) { animationElements.splice(i--, 1); } } eve.on("raphael.remove", stopAnimation); eve.on("raphael.clear", stopAnimation); elproto.toString = function() { return "Rapha\xebl\u2019s object"; }; elproto.toFront = function() { if (this.removed) { return this; } var o = this, thisNode = R._engine.getNode(o), parent = o.parent, followers = o.followers, follower, i, ii; if (R._tofront(o, parent)) { parent.canvas.appendChild(thisNode); } for (i = 0, ii = followers.length; i < ii; i++) { (follower = followers[i]).stalk && follower.el[follower.stalk](o); } return o; }; elproto.toBack = function() { if (this.removed) { return this; } var o = this, thisNode = R._engine.getNode(o), parent = o.parent, followers = o.followers, follower, i, ii; if (R._toback(o, parent)) { parent.canvas.insertBefore(thisNode, parent.canvas.firstChild); } for (i = 0, ii = followers.length; i < ii; i++) { (follower = followers[i]).stalk && follower.el[follower.stalk](o); } return o; }; elproto.insertAfter = function(element) { if (this.removed) { return this; } var o = this, thisNode = R._engine.getNode(o), thatNode = R._engine.getLastNode(element), parentNode = element.parent.canvas, followers = o.followers, follower, i, ii; if (thatNode.nextSibling) { parentNode.insertBefore(thisNode, thatNode.nextSibling); } else { parentNode.appendChild(thisNode); } R._insertafter(o, element, o.parent, element.parent); for (i = 0, ii = followers.length; i < ii; i++) { (follower = followers[i]).stalk && follower.el[follower.stalk](element); } return o; }; elproto.insertBefore = function(element) { if (this.removed) { return this; } var o = this, thisNode = R._engine.getNode(o), thatNode = R._engine.getNode(element), followers = o.followers, follower, i, ii; element.parent.canvas.insertBefore(thisNode, thatNode); R._insertbefore(o, element, o.parent, element.parent); o.parent = element.parent; for (i = 0, ii = followers.length; i < ii; i++) { (follower = followers[i]).stalk && follower.el[follower.stalk](element); } return this; }; elproto.appendChild = function (element) { if (this.removed || this.type !== 'group') { return this; } var group = this, followers = group.followers, follower, thatNode, i, ii; // If appending in same group, simply perform toFront(). if (element.parent === group) { element.toFront(); return group; } thatNode = R._engine.getNode(element); // first remove from own group R._tear(element, element.parent); group.canvas.appendChild(thatNode); element.parent = group; !group.bottom && (group.bottom = element); element.prev = group.top; element.next = null; group.top && (group.top.next = element); group.top = element; for (i = 0, ii = followers.length; i < ii; i++) { (follower = followers[i]).stalk && follower.el[follower.stalk](element); } return group; }; // Reverse application of appendChild elproto.appendTo = function (group) { return group.appendChild(this); } elproto.removeChild = function (element) { if (this.removed || this.type !== 'group' || element.parent !== this) { return this; } var o = this, thatNode = R._engine.getNode(element), paper = o.paper; R._tear(element, o); paper.canvas.appendChild(thatNode); o.parent = paper; !paper.bottom && (paper.bottom = o); o.prev = paper.top; paper.top && (paper.top.next = o); paper.top = o; o.next = null; return o; }; /*\ * Raphael.format [ method ] ** * Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument. ** > Parameters ** - token (string) string to format - … (string) rest of arguments will be treated as parameters for replacement = (string) formated string > Usage | var x = 10, | y = 20, | width = 40, | height = 50; | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z" | paper.path(Raphael.format("M{0},{1}h{2}v{3}h{4}z", x, y, width, height, -width)); \*/ R.format = function(token, params) { var arg = getArrayCopy(arguments), args = R.is(params, array) ? [0][concat](params) : arg; token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function(str, i) { return args[++i] == null ? E : args[i]; })); return token || E; }; var crispFixer = (R.vml && 0.5 || 0); R.crispBound = cacher(function (x, y, w, h, s) { var at = {}, normalizer; x = x || 0; y = y || 0; w = w || 0; h = h || 0; s = s || 0; normalizer = s % 2 / 2 + crispFixer; // normalize for crisp edges at.x = round(x + normalizer) - normalizer; at.y = round(y + normalizer) - normalizer; at.width = round(x + w + normalizer) - normalizer - at.x; at.height = round(y + h + normalizer) - normalizer - at.y; at['stroke-width'] = s; // adjust to single pixel if resultant dimension is zero. (at.width === 0 && w !== 0) && (at.width = 1); (at.height === 0 && h !== 0) && (at.height = 1); return at; }, R); /*\ * Raphael.define [ method ] ** * Allows a unified definition of composite shapes and other behaviours using * simple directives. ** > Parameters ** - definition (object) the shape definition \*/ R.define = function (name, init, ca, fn, e, data) { var i, ii; // multi definition if (R.is(name, array)) { for (i = 0, ii = name.length; i < ii; i++) { R.define(name[i]); } return; } // object definition else if (R.is(name, object)) { R.define(name.name, name[name.name], name.ca, name.fn, name.e, name.data); return; } // invalid or duplicate definition else if (!name || R.fn[name]) { return; } R.fn[name] = function () { var args = getArrayCopy(arguments), element = init.apply(this, args), key; if (fn && R.is(fn, object)) { for (key in fn) { element[key] = fn[key]; } } if (e && R.is(e, object)) { for (key in e) { element[key] && element[key](e[key]); } } if (ca) { if (R.is(ca, 'function')) { element.ca[name] = ca; } else { for (key in ca) { element.ca[key] = ca[key]; } } // Check if namesake ca exists and apply it if (element.ca[name]) { R._lastArgIfGroup(args, true); // purge group if (args.length) { // If name attribute is present then the received argument is an object with the customAttribute and other // common attributes. Else it is just the customAttributes that is to be applied. args[0][name] ? element.attr.apply(element, args): element.attr(name, args[0]); } } } return element; }; if (ca) { R.fn[name].ca = ca; } if (fn) { R.fn[name].fn = fn; } if (e) { R.fn[name].e = e; } if (data) { R.fn[name].data = data; } return R.fn[name]; }; // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html (function(doc, loaded, f) { if (doc.readyState == null && doc.addEventListener) { doc.addEventListener(loaded, f = function() { doc.removeEventListener(loaded, f, false); doc.readyState = "complete"; }, false); doc.readyState = "loading"; } function isLoaded() { (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("raphael.DOMload"); } isLoaded(); })(doc, "DOMContentLoaded"); eve.on("raphael.DOMload", function() { loaded = true; }); // EXPOSE // SVG and VML are appended just before the EXPOSE line // Even with AMD, Raphael should be defined globally // oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R); export default R;
source/raphael.core.js
/**! * RedRaphael 1.0.0 - JavaScript Vector Library * Copyright (c) 2012-2013 FusionCharts Technologies <http://www.fusioncharts.com> * * Raphael 2.1.0 * Copyright (c) 2008-2012 Dmitry Baranovskiy <http://raphaeljs.com> * Copyright © 2008-2012 Sencha Labs <http://sencha.com> * * Licensed under the MIT license. */ import eve from './eve/eve'; import extend, {merge, getArrayCopy, BLANK} from './raphael.lib'; var _win = (typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : null); /*\ * Raphael [ method ] ** * Creates a canvas object on which to draw. * You must do this first, as all future calls to drawing methods * from this instance will be bound to this canvas. > Parameters ** - container (HTMLElement|string) DOM element or its ID which is going to be a parent for drawing surface - width (number) - height (number) - callback (function) #optional callback function which is going to be executed in the context of newly created paper * or - x (number) - y (number) - width (number) - height (number) - callback (function) #optional callback function which is going to be executed in the context of newly created paper * or - all (array) (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>}). See @Paper.add. - callback (function) #optional callback function which is going to be executed in the context of newly created paper * or - onReadyCallback (function) function that is going to be called on DOM ready event. You can also subscribe to this event via Eve’s “DOMLoad” event. In this case method returns `undefined`. = (object) @Paper > Usage | // Each of the following examples create a canvas | // that is 320px wide by 200px high. | // Canvas is created at the viewport’s 10,50 coordinate. | var paper = Raphael(10, 50, 320, 200); | // Canvas is created at the top left corner of the #notepad element | // (or its top right corner in dir="rtl" elements) | var paper = Raphael(document.getElementById("notepad"), 320, 200); | // Same as above | var paper = Raphael("notepad", 320, 200); | // Image dump | var set = Raphael(["notepad", 320, 200, { | type: "rect", | x: 10, | y: 10, | width: 25, | height: 25, | stroke: "#f00" | }, { | type: "text", | x: 30, | y: 40, | text: "Dump" | }]); \*/ function R(first) { var args, arg, f; // Code commented as resources will now be referenced using relative URLs. // @todo Remove once we have ascertained that there are no issues in any environment. // if (R._url) { // Reinitialize URLs to be safe from pop state event // R._url = (R._g && R._g.win || _window).location.href.replace(/#.*?$/, ""); // } // If the URL is undefined only then initialize the URL with blank in order to support // both relative as well as absolute URLs // @todo Need to track the URL change and modify the URL for the gradient and other elements dynamically. if (R._url === undefined) { R._url = ""; } if (R.is(first, "function")) { return loaded ? first() : eve.on("raphael.DOMload", first); } else if (R.is(first, array)) { return R._engine.create[apply](R, first.splice(0, 3 + R.is(first[0], nu))).add(first); } else { arg = getArrayCopy(arguments); args = Array.prototype.slice.call(arg, 0); if (R.is(args[args.length - 1], "function")) { f = args.pop(); return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function() { f.call(R._engine.create[apply](R, args)); }); } else { return R._engine.create[apply](R, arguments); } } } R.upgrade = "1.0.0"; R.version = "2.1.0"; R.eve = eve; // RedRaphael = R; var loaded, undef, E = "", S = " ", has = "hasOwnProperty", apply = "apply", concat = "concat", nu = "number", string = "string", array = "array", object = "object", finite = "finite", split = "split", none = "none", black = "#000", arraySlice = Array.prototype.slice, arraySplice = Array.prototype.splice, hasPrototypeBug = (function () { var a = function () {}; return a.hasOwnProperty("prototype"); }()), g = { doc: _win.document, win: _win }, doc = g.doc, win = g.win, supportsTouch = R.supportsTouch = "createTouch" in doc, // The devices which both touch and pointer. supportsOnlyTouch = R.supportsOnlyTouch = (supportsTouch && !(win.navigator.maxTouchPoints || win.navigator.msMaxTouchPoints)), CustomAttributes = function () { /*\ * Raphael.ca [ property (object) ] ** * Shortcut for @Raphael.customAttributes \*/ /*\ * Raphael.customAttributes [ property (object) ] ** * If you have a set of attributes that you would like to represent * as a function of some number across all papers you can do it * easily with custom attributes: > Usage | Raphael.customAttributes.hue = function (num) { | num = num % 1; | return {fill: "hsb(" + num + ", 0.75, 1)"}; | }; | // Custom attribute “hue” will change fill | // to be given hue with fixed saturation and brightness. | // Now you can use it like this: | var c = paper.circle(10, 10, 10).attr({hue: .45}); | // or even like this: | c.animate({hue: 1}, 1e3); | | // You could also create custom attribute | // with multiple parameters: | Raphael.customAttributes.hsb = function (h, s, b) { | return {fill: "hsb(" + [h, s, b].join(",") + ")"}; | }; | c.attr({hsb: "0.5 .8 1"}); | c.animate({hsb: [1, 0, 0.5]}, 1e3); \*/ }, caproto = R.ca = R.customAttributes = CustomAttributes.prototype, Paper = function () { /*\ * Paper.ca [ property (object) ] ** * Shortcut for @Paper.customAttributes \*/ /*\ * Paper.customAttributes [ property (object) ] ** * If you have a set of attributes that you would like to represent * as a function of some number you can do it easily with custom attributes: > Usage | paper.customAttributes.hue = function (num) { | num = num % 1; | return {fill: "hsb(" + num + ", 0.75, 1)"}; | }; | // Custom attribute “hue” will change fill | // to be given hue with fixed saturation and brightness. | // Now you can use it like this: | var c = paper.circle(10, 10, 10).attr({hue: .45}); | // or even like this: | c.animate({hue: 1}, 1e3); | | // You could also create custom attribute | // with multiple parameters: | paper.customAttributes.hsb = function (h, s, b) { | return {fill: "hsb(" + [h, s, b].join(",") + ")"}; | }; | c.attr({hsb: "0.5 .8 1"}); | c.animate({hsb: [1, 0, 0.5]}, 1e3); \*/ this.ca = this.customAttributes = new CustomAttributes(); this._CustomAttributes = function () {}; this._CustomAttributes.prototype = this.ca; this._elementsById = {}; this.id = R._oid++; eve('raphael.new', this); }, /*\ * Raphael.fn [ property (object) ] ** * You can add your own method to the canvas. For example if you want to draw a pie chart, * you can create your own pie chart function and ship it as a Raphaël plugin. To do this * you need to extend the `Raphael.fn` object. You should modify the `fn` object before a * Raphaël instance is created, otherwise it will take no effect. Please note that the * ability for namespaced plugins was removed in Raphael 2.0. It is up to the plugin to * ensure any namespacing ensures proper context. > Usage | Raphael.fn.arrow = function (x1, y1, x2, y2, size) { | return this.path( ... ); | }; | // or create namespace | Raphael.fn.mystuff = { | arrow: function () {…}, | star: function () {…}, | // etc… | }; | var paper = Raphael(10, 10, 630, 480); | // then use it | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"}); | paper.mystuff.arrow(); | paper.mystuff.star(); \*/ paperproto = R.fn = Paper.prototype = R.prototype, // Add new dragstart, dragmove and dragend events in order to support touch drag in both touch and hybrid devices events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel dragstart dragmove dragend"[split](S), touchMap = R._touchMap = { mousedown: "touchstart", mousemove: "touchmove", mouseup: "touchend" }, dragEventMap = R._dragEventMap = { dragstart: "mousedown", dragmove: "mousemove", dragend: "mouseup" }, Str = String, toFloat = win.parseFloat, toInt = win.parseInt, math = Math, mmax = math.max, mmin = math.min, abs = math.abs, pow = math.pow, mathCos = math.cos, mathSin = math.sin, mathSqrt = math.sqrt, round = math.round, PI = math.PI, deg2rad = PI / 180, rad2deg = 180 / PI, lowerCase = Str.prototype.toLowerCase, upperCase = Str.prototype.toUpperCase, objectToString = Object.prototype.toString, separator = /[, ]+/, formatrg = /\{(\d+)\}/g, colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i, bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/, commaSpaces = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/, p2s = /,?([achlmqrstvxz]),?/gi, pathCommand = /([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig, tCommand = /([rstm])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig, pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/ig, isnan = { "NaN": 1, "Infinity": 1, "-Infinity": 1 }, hsrg = { hs: 1, rg: 1 }, availableAttrs = R._availableAttrs = { "arrow-end": none, "arrow-start": none, blur: 0, "clip-rect": "0 0 1e9 1e9", "clip-path": E, cursor: "default", cx: 0, cy: 0, fill: "#fff", "fill-opacity": 1, font: '10px "Arial"', "font-family": '"Arial"', "font-size": "10", "font-style": "normal", "font-weight": 400, gradient: 0, height: 0, href: "about:blank", "letter-spacing": 0, "line-height": 12, "vertical-align": "middle", opacity: 1, path: "M0,0", r: 0, rx: 0, ry: 0, src: E, stroke: "#000", "stroke-dasharray": E, "stroke-linecap": "butt", "stroke-linejoin": "butt", "stroke-miterlimit": 0, "stroke-opacity": 1, "stroke-width": 1, target: "_blank", "text-anchor": "middle", "visibility": E, title: E, transform: E, rotation: 0, width: 0, x: 0, y: 0, "shape-rendering": "auto", alpha: nu }, availableAnimAttrs = R._availableAnimAttrs = { blur: nu, "clip-rect": "csv", "clip-path": "path", cx: nu, cy: nu, fill: "colour", "fill-opacity": nu, "font-size": nu, height: nu, opacity: nu, path: "path", r: nu, rx: nu, ry: nu, stroke: "colour", "stroke-opacity": nu, "stroke-width": nu, transform: "transform", width: nu, x: nu, y: nu, // Required for pie 3d "color": "colour", "borderColor": "colour", "borderWidth": nu, alpha: nu, "text-bound": "text-bound" }, eldata = {}, sortByNumber = function(a, b) { return toFloat(a) - toFloat(b); }, fun = function() { }, pipe = function(x) { return x; }, rectPath = R._rectPath = function(x, y, w, h, r) { if (r) { return [["M", x + r, y], ["l", w - r * 2, 0], ["a", r, r, 0, 0, 1, r, r], ["l", 0, h - r * 2], ["a", r, r, 0, 0, 1, -r, r], ["l", r * 2 - w, 0], ["a", r, r, 0, 0, 1, -r, -r], ["l", 0, r * 2 - h], ["a", r, r, 0, 0, 1, r, -r], ["z"]]; } return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]]; }, ellipsePath = function(x, y, rx, ry) { if (ry == null) { ry = rx; } return [["M", x, y], ["m", 0, -ry], ["a", rx, ry, 0, 1, 1, 0, 2 * ry], ["a", rx, ry, 0, 1, 1, 0, -2 * ry], ["z"]]; }, getPath = R._getPath = { group: function() { return false; }, path: function(el) { return el.attr("path"); }, circle: function(el) { var a = el.attrs; return ellipsePath(a.cx, a.cy, a.r); }, ellipse: function(el) { var a = el.attrs; return ellipsePath(a.cx, a.cy, a.rx, a.ry); }, rect: function(el) { var a = el.attrs; return rectPath(a.x, a.y, a.width, a.height, a.r); }, image: function(el) { var a = el.attrs; return rectPath(a.x, a.y, a.width, a.height); }, text: function(el) { var bbox = el._getBBox(); return rectPath(bbox.x, bbox.y, bbox.width, bbox.height); } }, /*\ * Raphael.mapPath [ method ] ** * Transform the path string with given matrix. > Parameters - path (string) path string - matrix (object) see @Matrix = (string) transformed path string \*/ mapPath = R.mapPath = function(path, matrix) { if (!matrix) { return path; } var x, y, i, j, ii, jj, pathi; path = path2curve(path); for (i = 0, ii = path.length; i < ii; i++) { pathi = path[i]; for (j = 1, jj = pathi.length; j < jj; j += 2) { x = matrix.x(pathi[j], pathi[j + 1]); y = matrix.y(pathi[j], pathi[j + 1]); pathi[j] = x; pathi[j + 1] = y; } } return path; }, lastArgIfGroup = R._lastArgIfGroup = function (args, clear) { var last = args.length - 1, arg = args[last]; if (arg && (arg.constructor === R.el.constructor) && arg.type === 'group') { if (clear) { args[last] = undefined; delete args[last]; arraySplice.call(args, last, 1); } return arg; } }, serializeArgs = R._serializeArgs = function (args) { var arg0 = args[0], pathString, attrs, i, ii; if (R.is(arg0, 'object') && !R.is(arg0, 'array') && arg0.type !== 'group') { attrs = arg0; if (arg0.path) { pathString = arg0.path; pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E); } for (i = 1, ii = arguments.length; i < ii; i += 2) { if (!attrs[arguments[i]]) { attrs[arguments[i]] = arguments[i + 1]; } } } else { attrs = {}; for (i = 1, ii = arguments.length; i < ii; i += 2) { attrs[arguments[i]] = args[(i-1) / 2] || arguments[i+1]; } } return attrs; }, /*\ * Raphael.is [ method ] ** * Handfull replacement for `typeof` operator. > Parameters - o (…) any object or primitive - type (string) name of the type, i.e. “string”, “function”, “number”, etc. = (boolean) is given value is of given type \*/ is = R.is = function(o, type) { type = lowerCase.call(type); if (type == finite) { return !isnan[has](+o); } if (type == array) { return o instanceof Array; } if (type === 'object' && (o === undef || o === null)) { return false; } return (type == "null" && o === null) || (type == typeof o && o !== null) || (type == object && o === Object(o)) || (type == "array" && Array.isArray && Array.isArray(o)) || objectToString.call(o).slice(8, -1).toLowerCase() == type; }, /*\ * Raphael.clone [ method ] ** * Returns a recursively cloned version of an object. \*/ clone = R.clone = hasPrototypeBug ? function (obj) { if (Object(obj) !== obj) { return obj; } var res = new obj.constructor; for (var key in obj) if (key !== "prototype" && obj[has](key)) { res[key] = clone(obj[key]); } return res; } : function (obj) { if (Object(obj) !== obj) { return obj; } var res = new obj.constructor; for (var key in obj) if (obj[has](key)) { res[key] = clone(obj[key]); } return res; }, Node = _win.Node; //Adding pollyfill for IE11 if (Node && !Node.prototype.contains) { Node.prototype.contains = function(el){ while (el = el.parentNode) { if (el === this) return true; } return false; } }; R._g = g; R.merge = merge; R.extend = extend; /* * Raphael.createUUID [ method ] ** * Returns RFC4122, version 4 ID */ R.createUUID = (function(uuidRegEx, uuidReplacer) { return function() { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase(); }; })(/[xy]/g, function(c) { var r = math.random() * 16 | 0, v = c == "x" ? r : (r & 3 | 8); return v.toString(16); }); R._radial_gradient = /^x?r(?:\(([^\)]*?)\))?/; R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i; /* * Raphael.getElementID [ method ] ** * Add 'rr-' prefix before created IDs */ R.getElementID = function (id) { return "rr-" + id; }; // PriorityQueue Function Declaration function PriorityQueue(comparator) { this._comparator = comparator; this._elements = []; } PriorityQueue.prototype.isEmpty = function() { return this.size() === 0; }; PriorityQueue.prototype.peek = function() { if (this.isEmpty()) return null; return this._elements[0]; }; PriorityQueue.prototype.deq = function() { var first = this.peek(); var last = this._elements.pop(); var size = this.size(); if (size === 0) return first; this._elements[0] = last; var current = 0; while (current < size) { var largest = current; var left = (2 * current) + 1; var right = (2 * current) + 2; if (left < size && this._compare(left, largest) >= 0) { largest = left; } if (right < size && this._compare(right, largest) >= 0) { largest = right; } if (largest === current) break; this._swap(largest, current); current = largest; } return first; }; PriorityQueue.prototype.enq = function(element) { var size = this._elements.push(element); var current = size - 1; while (current > 0) { var parent = Math.floor((current - 1) / 2); if (this._compare(current, parent) <= 0) break; this._swap(parent, current); current = parent; } return size; }; PriorityQueue.prototype.size = function() { return this._elements.length; }; PriorityQueue.prototype._compare = function(a, b) { return this._comparator(this._elements[a], this._elements[b]); }; PriorityQueue.prototype._swap = function(a, b) { var aux = this._elements[a]; this._elements[a] = this._elements[b]; this._elements[b] = aux; }; /*\ * Raphael.type [ property (string) ] ** * Can be “SVG”, “VML” or empty, depending on browser support. \*/ R.type = (win.ENABLE_RED_CANVAS && (win.CanvasRenderingContext2D || doc.createElement('canvas').getContext)) ? "CANVAS" : (win.SVGAngle || doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML"); if (R.type == "VML") { var d = doc.createElement("div"), b; d.innerHTML = '<v:shape adj="1"/>'; b = d.firstChild; b.style.behavior = "url(#default#VML)"; if (!(b && typeof b.adj == object)) { R.type = E; // return (R.type = E); } d = null; } /*\ * Raphael.svg [ property (boolean) ] ** * `true` if browser supports SVG. \*/ /*\ * Raphael.vml [ property (boolean) ] ** * `true` if browser supports VML. \*/ R.svg = !((R.vml = R.type == "VML") || (R.canvas = R.type == "CANVAS")); R._Paper = Paper; R._id = 0; R._oid = 0; /*\ * Raphael.angle [ method ] ** * Returns angle between two or three points > Parameters - x1 (number) x coord of first point - y1 (number) y coord of first point - x2 (number) x coord of second point - y2 (number) y coord of second point - x3 (number) #optional x coord of third point - y3 (number) #optional y coord of third point = (number) angle in degrees. \*/ R.angle = function (x1, y1, x2, y2, x3, y3) { if (x3 == null) { var x = x1 - x2, y = y1 - y2; if (!x && !y) { return 0; } return (180 + math.atan2(-y, -x) * rad2deg + 360) % 360; } else { return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3); } }; /*\ * Raphael.rad [ method ] ** * Transform angle to radians > Parameters - deg (number) angle in degrees = (number) angle in radians. \*/ R.rad = function (deg) { return deg % 360 * deg2rad; }; /*\ * Raphael.deg [ method ] ** * Transform angle to degrees > Parameters - deg (number) angle in radians = (number) angle in degrees. \*/ R.deg = function (rad) { return rad * rad2deg % 360; }; /*\ * Raphael.setWindow [ method ] ** * Used when you need to draw in `&lt;iframe>`. Switched window to the iframe one. > Parameters - newwin (window) new window object \*/ R.setWindow = function (newwin) { eve("raphael.setWindow", R, g.win, newwin); win = g.win = newwin; doc = g.doc = g.win.document; if (R._engine.initWin) { R._engine.initWin(g.win); } }; var toHex = function (color) { if (R.vml) { // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/ var trim = /^\s+|\s+$/g; var bod; try { var docum = new ActiveXObject("htmlfile"); docum.write("<body>"); docum.close(); bod = docum.body; } catch (e) { bod = createPopup().document.body; } var range = bod.createTextRange(); toHex = cacher(function(color) { try { bod.style.color = Str(color).replace(trim, E); var value = range.queryCommandValue("ForeColor"); value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16); return "#" + ("000000" + value.toString(16)).slice(-6); } catch (e) { return none; } }); } else { var i = g.doc.createElement("i"); i.title = "Rapha\xebl Colour Picker"; i.style.display = none; g.doc.body.appendChild(i); toHex = cacher(function(color) { i.style.color = color; return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color"); }); } return toHex(color); }, hsbtoString = function() { return "hsb(" + [this.h, this.s, this.b] + ")"; }, hsltoString = function() { return "hsl(" + [this.h, this.s, this.l] + ")"; }, rgbtoString = function() { return this.hex; }, prepareRGB = function(r, g, b) { if (g == null && is(r, object) && "r" in r && "g" in r && "b" in r) { b = r.b; g = r.g; r = r.r; } if (g == null && is(r, string)) { var clr = R.getRGB(r); r = clr.r; g = clr.g; b = clr.b; } if (r > 1 || g > 1 || b > 1) { r /= 255; g /= 255; b /= 255; } return [r, g, b]; }, packageRGB = function(r, g, b, o) { var rgb = { r: (r *= 255), g: (g *= 255), b: (b *= 255), hex: R.rgb(r, g, b), toString: rgbtoString }; is(o, "finite") && (rgb.opacity = o); return rgb; }; /*\ * Raphael.color [ method ] ** * Parses the color string and returns object with all values for the given color. > Parameters - clr (string) color string in one of the supported formats (see @Raphael.getRGB) = (object) Combined RGB & HSB object in format: o { o r (number) red, o g (number) green, o b (number) blue, o hex (string) color in HTML/CSS format: #••••••, o error (boolean) `true` if string can’t be parsed, o h (number) hue, o s (number) saturation, o v (number) value (brightness), o l (number) lightness o } \*/ R.color = function(clr) { var rgb; if (R.is(clr, object) && "h" in clr && "s" in clr && "b" in clr) { rgb = R.hsb2rgb(clr); clr.r = rgb.r; clr.g = rgb.g; clr.b = rgb.b; clr.hex = rgb.hex; } else if (R.is(clr, object) && "h" in clr && "s" in clr && "l" in clr) { rgb = R.hsl2rgb(clr); clr.r = rgb.r; clr.g = rgb.g; clr.b = rgb.b; clr.hex = rgb.hex; } else { if (R.is(clr, "string")) { clr = R.getRGB(clr); } if (R.is(clr, object) && "r" in clr && "g" in clr && "b" in clr) { rgb = R.rgb2hsl(clr); clr.h = rgb.h; clr.s = rgb.s; clr.l = rgb.l; rgb = R.rgb2hsb(clr); clr.v = rgb.b; } else { clr = { hex: none }; clr.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1; } } clr.toString = rgbtoString; return clr; }; /*\ * Raphael.hsb2rgb [ method ] ** * Converts HSB values to RGB object. > Parameters - h (number) hue - s (number) saturation - v (number) value or brightness = (object) RGB object in format: o { o r (number) red, o g (number) green, o b (number) blue, o hex (string) color in HTML/CSS format: #•••••• o } \*/ R.hsb2rgb = function(h, s, v, o) { if (this.is(h, object) && "h" in h && "s" in h && "b" in h) { v = h.b; s = h.s; h = h.h; o = h.o; } h *= 360; var R, G, B, X, C; h = (h % 360) / 60; C = v * s; X = C * (1 - abs(h % 2 - 1)); R = G = B = v - C; h = ~~h; R += [C, X, 0, 0, X, C][h]; G += [X, C, C, X, 0, 0][h]; B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; /*\ * Raphael.hsl2rgb [ method ] ** * Converts HSL values to RGB object. > Parameters - h (number) hue - s (number) saturation - l (number) luminosity = (object) RGB object in format: o { o r (number) red, o g (number) green, o b (number) blue, o hex (string) color in HTML/CSS format: #•••••• o } \*/ R.hsl2rgb = function(h, s, l, o) { if (this.is(h, object) && "h" in h && "s" in h && "l" in h) { l = h.l; s = h.s; h = h.h; } if (h > 1 || s > 1 || l > 1) { h /= 360; s /= 100; l /= 100; } h *= 360; var R, G, B, X, C; h = (h % 360) / 60; C = 2 * s * (l < .5 ? l : 1 - l); X = C * (1 - abs(h % 2 - 1)); R = G = B = l - C / 2; h = ~~h; R += [C, X, 0, 0, X, C][h]; G += [X, C, C, X, 0, 0][h]; B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; /*\ * Raphael.rgb2hsb [ method ] ** * Converts RGB values to HSB object. > Parameters - r (number) red - g (number) green - b (number) blue = (object) HSB object in format: o { o h (number) hue o s (number) saturation o b (number) brightness o } \*/ R.rgb2hsb = function(r, g, b) { b = prepareRGB(r, g, b); r = b[0]; g = b[1]; b = b[2]; var H, S, V, C; V = mmax(r, g, b); C = V - mmin(r, g, b); H = (C == 0 ? null : V == r ? (g - b) / C : V == g ? (b - r) / C + 2 : (r - g) / C + 4 ); H = ((H + 360) % 6) * 60 / 360; S = C == 0 ? 0 : C / V; return { h: H, s: S, b: V, toString: hsbtoString }; }; /*\ * Raphael.rgb2hsl [ method ] ** * Converts RGB values to HSL object. > Parameters - r (number) red - g (number) green - b (number) blue = (object) HSL object in format: o { o h (number) hue o s (number) saturation o l (number) luminosity o } \*/ R.rgb2hsl = function(r, g, b) { b = prepareRGB(r, g, b); r = b[0]; g = b[1]; b = b[2]; var H, S, L, M, m, C; M = mmax(r, g, b); m = mmin(r, g, b); C = M - m; H = (C == 0 ? null : M == r ? (g - b) / C : M == g ? (b - r) / C + 2 : (r - g) / C + 4); H = ((H + 360) % 6) * 60 / 360; L = (M + m) / 2; S = (C == 0 ? 0 : L < .5 ? C / (2 * L) : C / (2 - 2 * L)); return { h: H, s: S, l: L, toString: hsltoString }; }; R._path2string = function() { return this.join(",").replace(p2s, "$1"); }; var cacher = R._cacher = function (f, scope, postprocessor) { var start = null, end = null, cache = {}, count = 0; function cachedfunction () { var arg = getArrayCopy(arguments), args = arg.join("\u2400"), newEndStr, newEnd, cur, prev, next, nextStr; args = args === '' ? BLANK : args; /****** Cache hit ******/ // If the following condition is true it is a cache hit. if (cache[has](args)) { // cur is the element due to cache hit cur = cache[args]; nextStr = cur.next; // nextStr is the id of next element of cur. prev = cur.prev; // prev is the previous node of the current hit node next = ((nextStr !== null) && cache[nextStr]) || null; // next is the next node of the current hit node // Scope of error: Always check if the start and cur are not same node. // start and cur can be same when same node has back to back cache hits. if (start === cur) { // do nothing. } else if (cache[end] === cur) { // when the cur element is the last element of cache start.next = end; newEndStr = cache[end].next; // Take Id of the next element of the cur element cache[newEndStr].prev = null; // Make it's previous pointer null so that it doesn't point to cur cur.next = null; // taking cur to the front. make it's next point to null, since there is no element ahead of it cur.prev = start; // make it's prev pointer to the present element at the front. start = cache[end]; // start pointer now point to the first element end = newEndStr; // end holds the ID of the last element } else { // when cur element is any element except start and end start.next = args; // present start node's next pointer should point to the cur node cur.prev = start; // cur node's prev pointer now points to the present start, making the present start to 2nd position cur.next = null; // since cur is in front, no one should be ahead of it. hence next = null prev.next = nextStr; // cur's prev node should point to cur's next node next.prev = prev; // cur's next node should point to cur's prev node start = cur; // start point to the cur node } return start.item; } /******* Cache miss *******/ // Else, it is a cache miss. /* ----- deletion process begins here ----- * deletion takes place if cache is full * */ if (count > 1e3) { // Take the second last element newEndStr = cache[end].next; newEnd = cache[newEndStr]; // prev pointer of the second last element should be deleted.(Beware! Not doing this step will lead to memory leak) newEnd.prev = null; // clear the pointers of the node to be deleted cache[end].next = null; // delete the node delete cache[end]; // update the end pointer end = newEndStr; count--; // decrement the counter } /* ----- insertion process begins here ----- */ // create a new node cache[args] = { next: null, prev: start, // newNode's prev pointer should point to the present start item: postprocessor ? postprocessor(f[apply](scope, arg)) : f[apply](scope, arg) }; // If start is present(start can be null if it is first node), point start.next to the new object if (start !== null) { start.next = args; // The present start node will fall second. } // finally assign start to the new node as start always points to the node at front start = cache[args]; // In case newNode is the first node of the cache end will also be null, but it should point to the start. (end === null) && (end = args); count++; return cache[args].item; } return cachedfunction; }; var preload = R._preload = function(src, f) { var img = doc.createElement("img"); img.style.cssText = "position:absolute;left:-9999em;top:-9999em"; img.onload = function() { f.call(this); this.onload = null; doc.body.removeChild(this); }; img.onerror = function() { doc.body.removeChild(this); }; doc.body.appendChild(img); img.src = src; }; function clrToString() { return this.hex; } /*\ * Raphael.getRGB [ method ] ** * Parses colour string as RGB object > Parameters - colour (string) colour string in one of formats: # <ul> # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li> # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li> # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li> # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200,&nbsp;100,&nbsp;0)</code>”)</li> # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%,&nbsp;175%,&nbsp;0%)</code>”)</li> # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5,&nbsp;0.25,&nbsp;1)</code>”)</li> # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li> # <li>hsl(•••, •••, •••) — same as hsb</li> # <li>hsl(•••%, •••%, •••%) — same as hsb</li> # </ul> = (object) RGB object in format: o { o r (number) red, o g (number) green, o b (number) blue o hex (string) color in HTML/CSS format: #••••••, o error (boolean) true if string can’t be parsed o } \*/ R.getRGB = cacher(function(colour) { var opacity, res, red, green, blue, t, values, rgb; colour && is(colour, 'object') && "opacity" in colour && (opacity = colour.opacity); if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) { return { r: -1, g: -1, b: -1, hex: none, error: 1, toString: clrToString }; } if (colour == none) { return { r: -1, g: -1, b: -1, hex: none, toString: clrToString }; } !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() === "#") && (colour = toHex(colour)); if ((rgb = colour.match(colourRegExp))) { if (rgb[2]) { blue = toInt(rgb[2].substring(5), 16); green = toInt(rgb[2].substring(3, 5), 16); red = toInt(rgb[2].substring(1, 3), 16); } if (rgb[3]) { blue = toInt((t = rgb[3].charAt(3)) + t, 16); green = toInt((t = rgb[3].charAt(2)) + t, 16); red = toInt((t = rgb[3].charAt(1)) + t, 16); } if (rgb[4]) { values = rgb[4][split](commaSpaces); red = toFloat(values[0]); values[0].slice(-1) == "%" && (red *= 2.55); green = toFloat(values[1]); values[1].slice(-1) == "%" && (green *= 2.55); blue = toFloat(values[2]); values[2].slice(-1) == "%" && (blue *= 2.55); rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3])); values[3] && values[3].slice(-1) == "%" && (opacity /= 100); } if (rgb[5]) { values = rgb[5][split](commaSpaces); red = toFloat(values[0]); values[0].slice(-1) == "%" && (red *= 2.55); green = toFloat(values[1]); values[1].slice(-1) == "%" && (green *= 2.55); blue = toFloat(values[2]); values[2].slice(-1) == "%" && (blue *= 2.55); (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360); rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3])); values[3] && values[3].slice(-1) == "%" && (opacity /= 100); return R.hsb2rgb(red, green, blue, opacity); } if (rgb[6]) { values = rgb[6][split](commaSpaces); red = toFloat(values[0]); values[0].slice(-1) == "%" && (red *= 2.55); green = toFloat(values[1]); values[1].slice(-1) == "%" && (green *= 2.55); blue = toFloat(values[2]); values[2].slice(-1) == "%" && (blue *= 2.55); (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360); rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3])); values[3] && values[3].slice(-1) == "%" && (opacity /= 100); return R.hsl2rgb(red, green, blue, opacity); } rgb = { r: red, g: green, b: blue, toString: clrToString }; rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1); R.is(opacity, "finite") && (rgb.opacity = opacity); return rgb; } return { r: -1, g: -1, b: -1, hex: none, error: 1, toString: clrToString }; }, R); R.tintshade = cacher(function(colour, percent) { var rgb = R.getRGB(colour), tint, offset = 255; (percent < 0) && (percent *= -1, offset = 0); (percent > 1) && (percent = 1); tint = percent === 0 ? rgb : { r: offset - (offset - rgb.r) * percent, g: offset - (offset - rgb.g) * percent, b: offset - (offset - rgb.b) * percent, toString: clrToString }; tint.hex = R.rgb(tint.r, tint.g, tint.b); rgb.error && (tint.error = rgb.error); if ("opacity" in rgb) { tint.rgba = 'rgba(' + [tint.r, tint.g, tint.b, rgb.opacity].join(',') + ')'; tint.opacity = rgb.opacity; } else { tint.rgba = 'rgb(' + [tint.r, tint.g, tint.b].join(',') + ')'; } return tint; }, R); /*\ * Raphael.hsb [ method ] ** * Converts HSB values to hex representation of the colour. > Parameters - h (number) hue - s (number) saturation - b (number) value or brightness = (string) hex representation of the colour. \*/ R.hsb = cacher(function(h, s, b) { return R.hsb2rgb(h, s, b).hex; }); /*\ * Raphael.hsl [ method ] ** * Converts HSL values to hex representation of the colour. > Parameters - h (number) hue - s (number) saturation - l (number) luminosity = (string) hex representation of the colour. \*/ R.hsl = cacher(function(h, s, l) { return R.hsl2rgb(h, s, l).hex; }); /*\ * Raphael.rgb [ method ] ** * Converts RGB values to hex representation of the colour. > Parameters - r (number) red - g (number) green - b (number) blue = (string) hex representation of the colour. \*/ R.rgb = cacher(function(r, g, b) { return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1); }); /*\ * Raphael.getColor [ method ] ** * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset > Parameters - value (number) #optional brightness, default is `0.75` = (string) hex representation of the colour. \*/ R.getColor = function(value) { var start = this.getColor.start = this.getColor.start || { h: 0, s: 1, b: value || .75 }, rgb = this.hsb2rgb(start.h, start.s, start.b); start.h += .075; if (start.h > 1) { start.h = 0; start.s -= .2; start.s <= 0 && (this.getColor.start = { h: 0, s: 1, b: start.b }); } return rgb.hex; }; /*\ * Raphael.getColor.reset [ method ] ** * Resets spectrum position for @Raphael.getColor back to red. \*/ R.getColor.reset = function() { delete this.start; }; // http://schepers.cc/getting-to-the-point function catmullRom2bezier(crp, z) { var d = []; for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { var p = [ { x: +crp[i - 2], y: +crp[i - 1] }, { x: +crp[i], y: +crp[i + 1] }, { x: +crp[i + 2], y: +crp[i + 3] }, { x: +crp[i + 4], y: +crp[i + 5] } ]; if (z) { if (!i) { p[0] = { x: +crp[iLen - 2], y: +crp[iLen - 1] }; } else if (iLen - 4 == i) { p[3] = { x: +crp[0], y: +crp[1] }; } else if (iLen - 2 == i) { p[2] = { x: +crp[0], y: +crp[1] }; p[3] = { x: +crp[2], y: +crp[3] }; } } else { if (iLen - 4 == i) { p[3] = p[2]; } else if (!i) { p[0] = { x: +crp[i], y: +crp[i + 1] }; } } d.push(["C", (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y ]); } return d; } /*\ * Raphael.parsePathString [ method ] ** * Utility method ** * Parses given path string into an array of arrays of path segments. > Parameters - pathString (string|array) path string or array of segments (in the last case it will be returned straight away) = (array) array of segments. \*/ R.parsePathString = function(pathString) { if (!pathString) { return null; } var pth = paths(pathString); if (pth.arr) { return pathClone(pth.arr); } var paramCounts = { a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0 }, data = []; if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption data = pathClone(pathString); } if (!data.length) { Str(pathString).replace(pathCommand, function(a, b, c) { var params = [], name = b.toLowerCase(); c.replace(pathValues, function(a, b) { b && params.push(+b); }); if (name == "m" && params.length > 2) { data.push([b][concat](params.splice(0, 2))); name = "l"; b = b == "m" ? "l" : "L"; } if (name == "r") { data.push([b][concat](params)); } else while (params.length >= paramCounts[name]) { data.push([b][concat](params.splice(0, paramCounts[name]))); if (!paramCounts[name]) { break; } } }); } data.toString = R._path2string; pth.arr = pathClone(data); return data; }; /*\ * Raphael.parseTransformString [ method ] ** * Utility method ** * Parses given path string into an array of transformations. > Parameters - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away) = (array) array of transformations. \*/ R.parseTransformString = cacher(function(TString) { if (!TString) { return null; } var paramCounts = { r: 3, s: 4, t: 2, m: 6 }, data = []; if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption data = pathClone(TString); } if (!data.length) { Str(TString).replace(tCommand, function(a, b, c) { var params = [], name = lowerCase.call(b); c.replace(pathValues, function(a, b) { b && params.push(+b); }); data.push([b][concat](params)); }); } data.toString = R._path2string; return data; }); // PATHS var paths = function(ps) { var p = paths.ps = paths.ps || {}; if (p[ps]) { p[ps].sleep = 100; } else { p[ps] = { sleep: 100 }; } setTimeout(function() { for (var key in p) if (p[has](key) && key != ps) { p[key].sleep--; !p[key].sleep && delete p[key]; } }); return p[ps]; }; /*\ * Raphael.findDotsAtSegment [ method ] ** * Utility method ** * Find dot coordinates on the given cubic bezier curve at the given t. > Parameters - p1x (number) x of the first point of the curve - p1y (number) y of the first point of the curve - c1x (number) x of the first anchor of the curve - c1y (number) y of the first anchor of the curve - c2x (number) x of the second anchor of the curve - c2y (number) y of the second anchor of the curve - p2x (number) x of the second point of the curve - p2y (number) y of the second point of the curve - t (number) position on the curve (0..1) = (object) point information in format: o { o x: (number) x coordinate of the point o y: (number) y coordinate of the point o m: { o x: (number) x coordinate of the left anchor o y: (number) y coordinate of the left anchor o } o n: { o x: (number) x coordinate of the right anchor o y: (number) y coordinate of the right anchor o } o start: { o x: (number) x coordinate of the start of the curve o y: (number) y coordinate of the start of the curve o } o end: { o x: (number) x coordinate of the end of the curve o y: (number) y coordinate of the end of the curve o } o alpha: (number) angle of the curve derivative at the point o } \*/ R.findDotsAtSegment = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t, t13 = pow(t1, 3), t12 = pow(t1, 2), t2 = t * t, t3 = t2 * t, x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x, y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y, mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x), my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y), nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x), ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y), ax = t1 * p1x + t * c1x, ay = t1 * p1y + t * c1y, cx = t1 * c2x + t * p2x, cy = t1 * c2y + t * p2y, alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI); (mx > nx || my < ny) && (alpha += 180); return { x: x, y: y, m: { x: mx, y: my }, n: { x: nx, y: ny }, start: { x: ax, y: ay }, end: { x: cx, y: cy }, alpha: alpha }; }; /*\ * Raphael.bezierBBox [ method ] ** * Utility method ** * Return bounding box of a given cubic bezier curve > Parameters - p1x (number) x of the first point of the curve - p1y (number) y of the first point of the curve - c1x (number) x of the first anchor of the curve - c1y (number) y of the first anchor of the curve - c2x (number) x of the second anchor of the curve - c2y (number) y of the second anchor of the curve - p2x (number) x of the second point of the curve - p2y (number) y of the second point of the curve * or - bez (array) array of six points for bezier curve = (object) point information in format: o { o min: { o x: (number) x coordinate of the left point o y: (number) y coordinate of the top point o } o max: { o x: (number) x coordinate of the right point o y: (number) y coordinate of the bottom point o } o } \*/ R.bezierBBox = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { if (!R.is(p1x, "array")) { p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y]; } var bbox = curveDim.apply(null, p1x); return { x: bbox.min.x, y: bbox.min.y, x2: bbox.max.x, y2: bbox.max.y, width: bbox.max.x - bbox.min.x, height: bbox.max.y - bbox.min.y }; }; /*\ * Raphael.isPointInsideBBox [ method ] ** * Utility method ** * Returns `true` if given point is inside bounding boxes. > Parameters - bbox (string) bounding box - x (string) x coordinate of the point - y (string) y coordinate of the point = (boolean) `true` if point inside \*/ R.isPointInsideBBox = function(bbox, x, y) { return x >= bbox.x && x <= bbox.x2 && y >= bbox.y && y <= bbox.y2; }; /*\ * Raphael.isBBoxIntersect [ method ] ** * Utility method ** * Returns `true` if two bounding boxes intersect > Parameters - bbox1 (string) first bounding box - bbox2 (string) second bounding box = (boolean) `true` if they intersect \*/ R.isBBoxIntersect = function(bbox1, bbox2) { var i = R.isPointInsideBBox; return i(bbox2, bbox1.x, bbox1.y) || i(bbox2, bbox1.x2, bbox1.y) || i(bbox2, bbox1.x, bbox1.y2) || i(bbox2, bbox1.x2, bbox1.y2) || i(bbox1, bbox2.x, bbox2.y) || i(bbox1, bbox2.x2, bbox2.y) || i(bbox1, bbox2.x, bbox2.y2) || i(bbox1, bbox2.x2, bbox2.y2) || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); }; function base3(t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; } function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { if (z == null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2, n = 12, Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816], Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472], sum = 0; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2, xbase = base3(ct, x1, x2, x3, x4), ybase = base3(ct, y1, y2, y3, y4), comb = xbase * xbase + ybase * ybase; sum += Cvalues[i] * mathSqrt(comb); } return z2 * sum; } function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { return; } var t = 1, step = t / 2, t2 = t - step, l, e = .01; l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); while (abs(l - ll) > e) { step /= 2; t2 += (l < ll ? 1 : -1) * step; l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); } return t2; } function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { if ( mmax(x1, x2) < mmin(x3, x4) || mmin(x1, x2) > mmax(x3, x4) || mmax(y1, y2) < mmin(y3, y4) || mmin(y1, y2) > mmax(y3, y4) ) { return; } var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4), ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4), denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (!denominator) { return; } var px = nx / denominator, py = ny / denominator, px2 = +px.toFixed(2), py2 = + py.toFixed(2); if ( px2 < +mmin(x1, x2).toFixed(2) || px2 > +mmax(x1, x2).toFixed(2) || px2 < +mmin(x3, x4).toFixed(2) || px2 > +mmax(x3, x4).toFixed(2) || py2 < +mmin(y1, y2).toFixed(2) || py2 > +mmax(y1, y2).toFixed(2) || py2 < +mmin(y3, y4).toFixed(2) || py2 > +mmax(y3, y4).toFixed(2) ) { return; } return { x: px, y: py }; } function inter(bez1, bez2) { return interHelper(bez1, bez2); } function interCount(bez1, bez2) { return interHelper(bez1, bez2, 1); } function interHelper(bez1, bez2, justCount) { var bbox1 = R.bezierBBox(bez1), bbox2 = R.bezierBBox(bez2); if (!R.isBBoxIntersect(bbox1, bbox2)) { return justCount ? 0 : []; } var l1 = bezlen.apply(0, bez1), l2 = bezlen.apply(0, bez2), n1 = mmax(~~(l1 / 5), 1), n2 = mmax(~~(l2 / 5), 1), dots1 = [], dots2 = [], xy = {}, res = justCount ? 0 : []; for (var i = 0; i < n1 + 1; i++) { var p = R.findDotsAtSegment.apply(R, bez1.concat(i / n1)); dots1.push({ x: p.x, y: p.y, t: i / n1 }); } for (i = 0; i < n2 + 1; i++) { p = R.findDotsAtSegment.apply(R, bez2.concat(i / n2)); dots2.push({ x: p.x, y: p.y, t: i / n2 }); } for (i = 0; i < n1; i++) { for (var j = 0; j < n2; j++) { var di = dots1[i], di1 = dots1[i + 1], dj = dots2[j], dj1 = dots2[j + 1], ci = abs(di1.x - di.x) < .001 ? "y" : "x", cj = abs(dj1.x - dj.x) < .001 ? "y" : "x", is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y); if (is) { if (xy[is.x.toFixed(4)] == is.y.toFixed(4)) { continue; } xy[is.x.toFixed(4)] = is.y.toFixed(4); var t1 = di.t + abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t), t2 = dj.t + abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t); if (t1 >= 0 && t1 <= 1.001 && t2 >= 0 && t2 <= 1.001) { if (justCount) { res++; } else { res.push({ x: is.x, y: is.y, t1: mmin(t1, 1), t2: mmin(t2, 1) }); } } } } } return res; } /*\ * Raphael.pathIntersection [ method ] ** * Utility method ** * Finds intersections of two paths > Parameters - path1 (string) path string - path2 (string) path string = (array) dots of intersection o [ o { o x: (number) x coordinate of the point o y: (number) y coordinate of the point o t1: (number) t value for segment of path1 o t2: (number) t value for segment of path2 o segment1: (number) order number for segment of path1 o segment2: (number) order number for segment of path2 o bez1: (array) eight coordinates representing beziér curve for the segment of path1 o bez2: (array) eight coordinates representing beziér curve for the segment of path2 o } o ] \*/ R.pathIntersection = function(path1, path2) { return interPathHelper(path1, path2); }; R.pathIntersectionNumber = function(path1, path2) { return interPathHelper(path1, path2, 1); }; function interPathHelper(path1, path2, justCount) { path1 = R._path2curve(path1); path2 = R._path2curve(path2); var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2, res = justCount ? 0 : []; for (var i = 0, ii = path1.length; i < ii; i++) { var pi = path1[i]; if (pi[0] == "M") { x1 = x1m = pi[1]; y1 = y1m = pi[2]; } else { if (pi[0] == "C") { bez1 = [x1, y1].concat(pi.slice(1)); x1 = bez1[6]; y1 = bez1[7]; } else { bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m]; x1 = x1m; y1 = y1m; } for (var j = 0, jj = path2.length; j < jj; j++) { var pj = path2[j]; if (pj[0] == "M") { x2 = x2m = pj[1]; y2 = y2m = pj[2]; } else { if (pj[0] == "C") { bez2 = [x2, y2].concat(pj.slice(1)); x2 = bez2[6]; y2 = bez2[7]; } else { bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m]; x2 = x2m; y2 = y2m; } var intr = interHelper(bez1, bez2, justCount); if (justCount) { res += intr; } else { for (var k = 0, kk = intr.length; k < kk; k++) { intr[k].segment1 = i; intr[k].segment2 = j; intr[k].bez1 = bez1; intr[k].bez2 = bez2; } res = res.concat(intr); } } } } } return res; } /*\ * Raphael.isPointInsidePath [ method ] ** * Utility method ** * Returns `true` if given point is inside a given closed path. > Parameters - path (string) path string - x (number) x of the point - y (number) y of the point = (boolean) true, if point is inside the path \*/ R.isPointInsidePath = function(path, x, y) { var bbox = R.pathBBox(path); return R.isPointInsideBBox(bbox, x, y) && ((interPathHelper(path, [["M", x, y], ["H", bbox.x2 + 10]], 1) % 2 == 1) || (interPathHelper(path, [["M", x, y], ["V", bbox.y2 + 10]], 1) % 2 == 1)) }; R._removedFactory = function(methodname) { return function() { eve("raphael.log", null, "Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object", methodname); }; }; /*\ * Raphael.pathBBox [ method ] ** * Utility method ** * Return bounding box of a given path > Parameters - path (string) path string = (object) bounding box o { o x: (number) x coordinate of the left top point of the box o y: (number) y coordinate of the left top point of the box o x2: (number) x coordinate of the right bottom point of the box o y2: (number) y coordinate of the right bottom point of the box o width: (number) width of the box o height: (number) height of the box o cx: (number) x coordinate of the center of the box o cy: (number) y coordinate of the center of the box o } \*/ var pathDimensions = R.pathBBox = function(path) { var pth = paths(path); if (!path) { return { x: 0, y: 0, width: 0, height: 0, x2: 0, y2: 0 }; } path = path2curve(path); var x = 0, y = 0, X = [], Y = [], p; for (var i = 0, ii = path.length; i < ii; i++) { p = path[i]; if (p[0] == "M") { x = p[1]; y = p[2]; X.push(x); Y.push(y); } else { var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]); X = X[concat](dim.min.x, dim.max.x); Y = Y[concat](dim.min.y, dim.max.y); x = p[5]; y = p[6]; } } var xmin = mmin[apply](0, X), ymin = mmin[apply](0, Y), xmax = mmax[apply](0, X), ymax = mmax[apply](0, Y), bb = { x: xmin, y: ymin, x2: xmax, y2: ymax, width: xmax - xmin, height: ymax - ymin }; pth.bbox = clone(bb); return bb; }, pathClone = function(pathArray) { var res = clone(pathArray); res.toString = R._path2string; return res; }, pathToRelative = R._pathToRelative = function(pathArray) { var pth = paths(pathArray); if (pth.rel) { return pathClone(pth.rel); } if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption pathArray = R.parsePathString(pathArray); } var res = [], x = 0, y = 0, mx = 0, my = 0, start = 0; if (pathArray[0][0] == "M") { x = pathArray[0][1]; y = pathArray[0][2]; mx = x; my = y; start++; res.push(["M", x, y]); } for (var i = start, ii = pathArray.length; i < ii; i++) { var r = res[i] = [], pa = pathArray[i]; if (pa[0] != lowerCase.call(pa[0])) { r[0] = lowerCase.call(pa[0]); switch (r[0]) { case "a": r[1] = pa[1]; r[2] = pa[2]; r[3] = pa[3]; r[4] = pa[4]; r[5] = pa[5]; r[6] = +(pa[6] - x).toFixed(3); r[7] = +(pa[7] - y).toFixed(3); break; case "v": r[1] = +(pa[1] - y).toFixed(3); break; case "m": mx = pa[1]; my = pa[2]; default: for (var j = 1, jj = pa.length; j < jj; j++) { r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3); } } } else { r = res[i] = []; if (pa[0] == "m") { mx = pa[1] + x; my = pa[2] + y; } for (var k = 0, kk = pa.length; k < kk; k++) { res[i][k] = pa[k]; } } var len = res[i].length; switch (res[i][0]) { case "z": x = mx; y = my; break; case "h": x += +res[i][len - 1]; break; case "v": y += +res[i][len - 1]; break; default: x += +res[i][len - 2]; y += +res[i][len - 1]; } } res.toString = R._path2string; pth.rel = pathClone(res); return res; }, pathToAbsolute = R._pathToAbsolute = function(pathArray) { var pth = paths(pathArray), res; if (pth.abs) { return pathClone(pth.abs); } if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption pathArray = R.parsePathString(pathArray); } if (!pathArray || !pathArray.length) { res = [["M", 0, 0]]; res.toString = R._path2string; return res; } var x = 0, y = 0, mx = 0, my = 0, start = 0; res = []; if (pathArray[0][0] == "M") { x = +pathArray[0][1]; y = +pathArray[0][2]; mx = x; my = y; start++; res[0] = ["M", x, y]; } var crz = pathArray.length == 3 && pathArray[0][0] == "M" && pathArray[1][0].toUpperCase() == "R" && pathArray[2][0].toUpperCase() == "Z"; for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { res.push(r = []); pa = pathArray[i]; if (pa[0] != upperCase.call(pa[0])) { r[0] = upperCase.call(pa[0]); switch (r[0]) { case "A": r[1] = pa[1]; r[2] = pa[2]; r[3] = pa[3]; r[4] = pa[4]; r[5] = pa[5]; r[6] = +(pa[6] + x); r[7] = +(pa[7] + y); break; case "V": r[1] = +pa[1] + y; break; case "H": r[1] = +pa[1] + x; break; case "R": var dots = [x, y][concat](pa.slice(1)); for (var j = 2, jj = dots.length; j < jj; j++) { dots[j] = +dots[j] + x; dots[++j] = +dots[j] + y; } res.pop(); res = res[concat](catmullRom2bezier(dots, crz)); break; case "M": mx = +pa[1] + x; my = +pa[2] + y; default: for (j = 1, jj = pa.length; j < jj; j++) { r[j] = +pa[j] + ((j % 2) ? x : y); } } } else if (pa[0] == "R") { dots = [x, y][concat](pa.slice(1)); res.pop(); res = res[concat](catmullRom2bezier(dots, crz)); r = ["R"][concat](pa.slice(-2)); } else { for (var k = 0, kk = pa.length; k < kk; k++) { r[k] = pa[k]; } } switch (r[0]) { case "Z": x = mx; y = my; break; case "H": x = r[1]; break; case "V": y = r[1]; break; case "M": mx = r[r.length - 2]; my = r[r.length - 1]; default: x = r[r.length - 2]; y = r[r.length - 1]; } } res.toString = R._path2string; pth.abs = pathClone(res); return res; }, l2c = function(x1, y1, x2, y2) { return [x1, y1, x2, y2, x2, y2]; }, q2c = function(x1, y1, ax, ay, x2, y2) { var _13 = 1 / 3, _23 = 2 / 3; return [ _13 * x1 + _23 * ax, _13 * y1 + _23 * ay, _13 * x2 + _23 * ax, _13 * y2 + _23 * ay, x2, y2 ]; }, a2c = function(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { // for more information of where this math came from visit: // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes var _120 = PI * 120 / 180, rad = deg2rad * (+angle || 0), res = [], xy, rotate = cacher(function(x, y, rad) { var X = x * mathCos(rad) - y * mathSin(rad), Y = x * mathSin(rad) + y * mathCos(rad); return { x: X, y: Y }; }); if (!recursive) { xy = rotate(x1, y1, -rad); x1 = xy.x; y1 = xy.y; xy = rotate(x2, y2, -rad); x2 = xy.x; y2 = xy.y; var cos = mathCos(deg2rad * angle), sin = mathSin(deg2rad * angle), x = (x1 - x2) / 2, y = (y1 - y2) / 2; var h = (x * x) / (rx * rx) + (y * y) / (ry * ry); if (h > 1) { h = mathSqrt(h); rx = h * rx; ry = h * ry; } var rx2 = rx * rx, ry2 = ry * ry, k = (large_arc_flag == sweep_flag ? -1 : 1) * mathSqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))), cx = k * rx * y / ry + (x1 + x2) / 2, cy = k * -ry * x / rx + (y1 + y2) / 2, f1 = math.asin(((y1 - cy) / ry).toFixed(9)), f2 = math.asin(((y2 - cy) / ry).toFixed(9)); f1 = x1 < cx ? PI - f1 : f1; f2 = x2 < cx ? PI - f2 : f2; f1 < 0 && (f1 = PI * 2 + f1); f2 < 0 && (f2 = PI * 2 + f2); if (sweep_flag && f1 > f2) { f1 = f1 - PI * 2; } if (!sweep_flag && f2 > f1) { f2 = f2 - PI * 2; } } else { f1 = recursive[0]; f2 = recursive[1]; cx = recursive[2]; cy = recursive[3]; } var df = f2 - f1; if (abs(df) > _120) { var f2old = f2, x2old = x2, y2old = y2; f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); x2 = cx + rx * mathCos(f2); y2 = cy + ry * mathSin(f2); res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); } df = f2 - f1; var c1 = mathCos(f1), s1 = mathSin(f1), c2 = mathCos(f2), s2 = mathSin(f2), t = math.tan(df / 4), hx = 4 / 3 * rx * t, hy = 4 / 3 * ry * t, m1 = [x1, y1], m2 = [x1 + hx * s1, y1 - hy * c1], m3 = [x2 + hx * s2, y2 - hy * c2], m4 = [x2, y2]; m2[0] = 2 * m1[0] - m2[0]; m2[1] = 2 * m1[1] - m2[1]; if (recursive) { return [m2, m3, m4][concat](res); } else { res = [m2, m3, m4][concat](res).join()[split](","); var newres = []; for (var i = 0, ii = res.length; i < ii; i++) { newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; } return newres; } }, findDotAtSegment = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t; return { x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x, y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y }; }, curveDim = cacher(function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x), b = 2 * (c1x - p1x) - 2 * (c2x - c1x), c = p1x - c1x, t1 = (-b + mathSqrt(b * b - 4 * a * c)) / 2 / a, t2 = (-b - mathSqrt(b * b - 4 * a * c)) / 2 / a, y = [p1y, p2y], x = [p1x, p2x], dot; abs(t1) > "1e12" && (t1 = .5); abs(t2) > "1e12" && (t2 = .5); if (t1 > 0 && t1 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1); x.push(dot.x); y.push(dot.y); } if (t2 > 0 && t2 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2); x.push(dot.x); y.push(dot.y); } a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y); b = 2 * (c1y - p1y) - 2 * (c2y - c1y); c = p1y - c1y; t1 = (-b + mathSqrt(b * b - 4 * a * c)) / 2 / a; t2 = (-b - mathSqrt(b * b - 4 * a * c)) / 2 / a; abs(t1) > "1e12" && (t1 = .5); abs(t2) > "1e12" && (t2 = .5); if (t1 > 0 && t1 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1); x.push(dot.x); y.push(dot.y); } if (t2 > 0 && t2 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2); x.push(dot.x); y.push(dot.y); } return { min: { x: mmin[apply](0, x), y: mmin[apply](0, y) }, max: { x: mmax[apply](0, x), y: mmax[apply](0, y) } }; }), path2curve = R._path2curve = cacher(function(path, path2) { var pth = !path2 && paths(path); if (!path2 && pth.curve) { return pathClone(pth.curve); } var p = pathToAbsolute(path), p2 = path2 && pathToAbsolute(path2), attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }, attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }, processPath = function(path, d) { var nx, ny; if (!path) { return ["C", d.x, d.y, d.x, d.y, d.x, d.y]; } !(path[0] in { T: 1, Q: 1 }) && (d.qx = d.qy = null); switch (path[0]) { case "M": d.X = path[1]; d.Y = path[2]; break; case "A": path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1)))); break; case "S": nx = d.x + (d.x - (d.bx || d.x)); ny = d.y + (d.y - (d.by || d.y)); path = ["C", nx, ny][concat](path.slice(1)); break; case "T": d.qx = d.x + (d.x - (d.qx || d.x)); d.qy = d.y + (d.y - (d.qy || d.y)); path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2])); break; case "Q": d.qx = path[1]; d.qy = path[2]; path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4])); break; case "L": path = ["C"][concat](l2c(d.x, d.y, path[1], path[2])); break; case "H": path = ["C"][concat](l2c(d.x, d.y, path[1], d.y)); break; case "V": path = ["C"][concat](l2c(d.x, d.y, d.x, path[1])); break; case "Z": path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y)); break; } return path; }, fixArc = function(pp, i) { if (pp[i].length > 7) { pp[i].shift(); var pi = pp[i]; while (pi.length) { pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6))); } pp.splice(i, 1); ii = mmax(p.length, p2 && p2.length || 0); } }, fixM = function(path1, path2, a1, a2, i) { if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M" && !i) { path2.splice(i, 0, ["M", a2.x, a2.y]); a1.bx = 0; a1.by = 0; a1.x = path1[i][1]; a1.y = path1[i][2]; ii = mmax(p.length, p2 && p2.length || 0); } }; for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) { p[i] = processPath(p[i], attrs); fixArc(p, i); p2 && (p2[i] = processPath(p2[i], attrs2)); p2 && fixArc(p2, i); fixM(p, p2, attrs, attrs2, i); fixM(p2, p, attrs2, attrs, i); var seg = p[i], seg2 = p2 && p2[i], seglen = seg.length, seg2len = p2 && seg2.length; attrs.x = seg[seglen - 2]; attrs.y = seg[seglen - 1]; attrs.bx = toFloat(seg[seglen - 4]) || attrs.x; attrs.by = toFloat(seg[seglen - 3]) || attrs.y; attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x); attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y); attrs2.x = p2 && seg2[seg2len - 2]; attrs2.y = p2 && seg2[seg2len - 1]; } if (!p2) { pth.curve = pathClone(p); } return p2 ? [p, p2] : p; }, null, pathClone), parseDots = R._parseDots = cacher(function(gradient) { var dots = []; for (var i = 0, ii = gradient.length; i < ii; i++) { var dot = {}, par = gradient[i].match(/^([^:]*):?([\d\.]*)/); dot.color = R.getRGB(par[1]); if (dot.color.error) { return null; } //store opacity information dot.opacity = dot.color.opacity; dot.color = dot.color.hex; par[2] && (dot.offset = par[2] + "%"); dots.push(dot); } for (i = 1, ii = dots.length - 1; i < ii; i++) { if (!dots[i].offset) { var start = toFloat(dots[i - 1].offset || 0), end = 0; for (var j = i + 1; j < ii; j++) { if (dots[j].offset) { end = dots[j].offset; break; } } if (!end) { end = 100; j = ii; } end = toFloat(end); var d = (end - start) / (j - i + 1); for (; i < j; i++) { start += d; dots[i].offset = start + "%"; } } } return dots; }), tear = R._tear = function(el, paper) { el == paper.top && (paper.top = el.prev); el == paper.bottom && (paper.bottom = el.next); el.next && (el.next.prev = el.prev); el.prev && (el.prev.next = el.next); }, tofront = R._tofront = function(el, paper) { if (paper.top === el) { return false; } tear(el, paper); el.next = null; el.prev = paper.top; paper.top.next = el; paper.top = el; return true; }, toback = R._toback = function(el, paper) { if (paper.bottom === el) { return false; } tear(el, paper); el.next = paper.bottom; el.prev = null; paper.bottom.prev = el; paper.bottom = el; return true; }, insertafter = R._insertafter = function(el, el2, paper, paper2) { tear(el, paper); el.parent = paper2; el2 === paper2.top && (paper2.top = el); el2.next && (el2.next.prev = el); el.next = el2.next; el.prev = el2; el2.next = el; }, insertbefore = R._insertbefore = function(el, el2, paper, paper2) { tear(el, paper); el.parent = paper2; el2 === paper2.bottom && (paper2.bottom = el); el2.prev && (el2.prev.next = el); el.prev = el2.prev; el2.prev = el; el.next = el2; }, /*\ * Raphael.toMatrix [ method ] ** * Utility method ** * Returns matrix of transformations applied to a given path > Parameters - path (string) path string - transform (string|array) transformation string = (object) @Matrix \*/ toMatrix = R.toMatrix = function(path, transform) { var bb = pathDimensions(path), el = { _: { transform: E }, getBBox: function() { return bb; } }; extractTransform(el, transform); return el.matrix; }, /*\ * Raphael.transformPath [ method ] ** * Utility method ** * Returns path transformed by a given transformation > Parameters - path (string) path string - transform (string|array) transformation string = (string) path \*/ transformPath = R.transformPath = function(path, transform) { return mapPath(path, toMatrix(path, transform)); }, extractTransform = R._extractTransform = function(el, tstr) { if (tstr == null) { return el._.transform; } tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E); var tdata = R.parseTransformString(tstr), deg = 0, dx = 0, dy = 0, sx = 1, sy = 1, _ = el._, m = new Matrix; _.transform = tdata || []; if (tdata) { for (var i = 0, ii = tdata.length; i < ii; i++) { var t = tdata[i], tlen = t.length, command = Str(t[0]).toLowerCase(), absolute = t[0] != command, inver = absolute ? m.invert() : 0, x1, y1, x2, y2, bb; if (command == "t" && tlen == 3) { if (absolute) { x1 = inver.x(0, 0); y1 = inver.y(0, 0); x2 = inver.x(t[1], t[2]); y2 = inver.y(t[1], t[2]); m.translate(x2 - x1, y2 - y1); } else { m.translate(t[1], t[2]); } } else if (command == "r") { if (tlen == 2) { bb = _.bb || (_.bb = el.getBBox(1)); m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2); deg += t[1]; } else if (tlen == 4) { if (absolute) { x2 = inver.x(t[2], t[3]); y2 = inver.y(t[2], t[3]); m.rotate(t[1], x2, y2); } else { m.rotate(t[1], t[2], t[3]); } deg += t[1]; } } else if (command == "s") { if (tlen == 2 || tlen == 3) { bb = _.bb || (_.bb = el.getBBox(1)); m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2); sx *= t[1]; sy *= t[tlen - 1]; } else if (tlen == 5) { if (absolute) { x2 = inver.x(t[3], t[4]); y2 = inver.y(t[3], t[4]); m.scale(t[1], t[2], x2, y2); } else { m.scale(t[1], t[2], t[3], t[4]); } sx *= t[1]; sy *= t[2]; } } else if (command == "m" && tlen == 7) { m.add(t[1], t[2], t[3], t[4], t[5], t[6]); } _.dirtyT = 1; el.matrix = m; } } /*\ * Element.matrix [ property (object) ] ** * Keeps @Matrix object, which represents element transformation \*/ el.matrix = m; _.sx = sx; _.sy = sy; _.deg = deg; _.dx = dx = m.e; _.dy = dy = m.f; if (sx == 1 && sy == 1 && !deg && _.bbox) { _.bbox.x += +dx; _.bbox.y += +dy; } else { _.dirtyT = 1; } }, getEmpty = function(item) { var l = item[0]; switch (l.toLowerCase()) { case "t": return [l, 0, 0]; case "m": return [l, 1, 0, 0, 1, 0, 0]; case "r": if (item.length == 4) { return [l, 0, item[2], item[3]]; } else { return [l, 0]; } case "s": if (item.length == 5) { return [l, 1, 1, item[3], item[4]]; } else if (item.length == 3) { return [l, 1, 1]; } else { return [l, 1]; } } }, equaliseTransform = R._equaliseTransform = function(t1, t2) { t2 = Str(t2).replace(/\.{3}|\u2026/g, t1); t1 = R.parseTransformString(t1) || []; t2 = R.parseTransformString(t2) || []; var maxlength = mmax(t1.length, t2.length), from = [], to = [], i = 0, j, jj, tt1, tt2; for (; i < maxlength; i++) { tt1 = t1[i] || getEmpty(t2[i]); tt2 = t2[i] || getEmpty(tt1); if ((tt1[0] != tt2[0]) || (tt1[0].toLowerCase() == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) || (tt1[0].toLowerCase() == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4])) ) { return; } from[i] = []; to[i] = []; for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) { j in tt1 && (from[i][j] = tt1[j]); j in tt2 && (to[i][j] = tt2[j]); } } return { from: from, to: to }; }; R._getContainer = function(x, y, w, h) { var container; container = h == null && !R.is(x, object) ? g.doc.getElementById(x) : x; if (container == null) { return; } if (container.tagName) { if (y == null) { return { container: container, width: container.style.pixelWidth || container.offsetWidth, height: container.style.pixelHeight || container.offsetHeight }; } else { return { container: container, width: y, height: w }; } } return { container: 1, x: x, y: y, width: w, height: h }; }; /*\ * Raphael.pathToRelative [ method ] ** * Utility method ** * Converts path to relative form > Parameters - pathString (string|array) path string or array of segments = (array) array of segments. \*/ R.pathToRelative = pathToRelative; R._engine = {}; /*\ * Raphael.path2curve [ method ] ** * Utility method ** * Converts path to a new path where all segments are cubic bezier curves. > Parameters - pathString (string|array) path string or array of segments = (array) array of segments. \*/ R.path2curve = path2curve; /*\ * Raphael.matrix [ method ] ** * Utility method ** * Returns matrix based on given parameters. > Parameters - a (number) - b (number) - c (number) - d (number) - e (number) - f (number) = (object) @Matrix \*/ R.matrix = function(a, b, c, d, e, f) { return new Matrix(a, b, c, d, e, f); }; function Matrix(a, b, c, d, e, f) { if (a != null) { this.a = +a; this.b = +b; this.c = +c; this.d = +d; this.e = +e; this.f = +f; } else { this.a = 1; this.b = 0; this.c = 0; this.d = 1; this.e = 0; this.f = 0; } } (function(matrixproto) { /*\ * Matrix.add [ method ] ** * Adds given matrix to existing one. > Parameters - a (number) - b (number) - c (number) - d (number) - e (number) - f (number) or - matrix (object) @Matrix \*/ matrixproto.add = function(a, b, c, d, e, f) { var out = [[], [], []], m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]], matrix = [[a, c, e], [b, d, f], [0, 0, 1]], x, y, z, res; if (a && a instanceof Matrix) { matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]]; } for (x = 0; x < 3; x++) { for (y = 0; y < 3; y++) { res = 0; for (z = 0; z < 3; z++) { res += m[x][z] * matrix[z][y]; } out[x][y] = res; } } this.a = out[0][0]; this.b = out[1][0]; this.c = out[0][1]; this.d = out[1][1]; this.e = out[0][2]; this.f = out[1][2]; }; /*\ * Matrix.invert [ method ] ** * Returns inverted version of the matrix = (object) @Matrix \*/ matrixproto.invert = function() { var me = this, x = me.a * me.d - me.b * me.c; return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x); }; /*\ * Matrix.clone [ method ] ** * Returns copy of the matrix = (object) @Matrix \*/ matrixproto.clone = function() { return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f); }; /*\ * Matrix.translate [ method ] ** * Translate the matrix > Parameters - x (number) - y (number) \*/ matrixproto.translate = function(x, y) { this.add(1, 0, 0, 1, x, y); }; /*\ * Matrix.scale [ method ] ** * Scales the matrix > Parameters - x (number) - y (number) #optional - cx (number) #optional - cy (number) #optional \*/ matrixproto.scale = function(x, y, cx, cy) { y == null && (y = x); (cx || cy) && this.add(1, 0, 0, 1, cx, cy); this.add(x, 0, 0, y, 0, 0); (cx || cy) && this.add(1, 0, 0, 1, -cx, -cy); }; /*\ * Matrix.rotate [ method ] ** * Rotates the matrix > Parameters - a (number) - x (number) - y (number) \*/ matrixproto.rotate = function(a, x, y) { a = R.rad(a); x = x || 0; y = y || 0; var cos = +mathCos(a).toFixed(9), sin = + mathSin(a).toFixed(9); this.add(cos, sin, -sin, cos, x, y); this.add(1, 0, 0, 1, -x, -y); }; /*\ * Matrix.x [ method ] ** * Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y > Parameters - x (number) - y (number) = (number) x \*/ matrixproto.x = function(x, y) { return x * this.a + y * this.c + this.e; }; /*\ * Matrix.y [ method ] ** * Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x > Parameters - x (number) - y (number) = (number) y \*/ matrixproto.y = function(x, y) { return x * this.b + y * this.d + this.f; }; matrixproto.get = function(i) { return +this[Str.fromCharCode(97 + i)].toFixed(4); }; matrixproto.toString = function() { return R.svg ? "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join(); }; matrixproto.toMatrixString = function() { return "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")"; }; matrixproto.toFilter = function() { return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) + ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) + ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')"; }; matrixproto.offset = function() { return [this.e.toFixed(4), this.f.toFixed(4)]; }; function norm(a) { return a[0] * a[0] + a[1] * a[1]; } function normalize(a) { var mag = mathSqrt(norm(a)); a[0] && (a[0] /= mag); a[1] && (a[1] /= mag); } /*\ * Matrix.split [ method ] ** * Splits matrix into primitive transformations = (object) in format: o dx (number) translation by x o dy (number) translation by y o scalex (number) scale by x o scaley (number) scale by y o shear (number) shear o rotate (number) rotation in deg o isSimple (boolean) could it be represented via simple transformations \*/ matrixproto.split = function() { var out = {}; // translation out.dx = this.e; out.dy = this.f; // scale and shear var row = [[this.a, this.c], [this.b, this.d]]; out.scalex = mathSqrt(norm(row[0])); normalize(row[0]); out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1]; row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear]; out.scaley = mathSqrt(norm(row[1])); normalize(row[1]); out.shear /= out.scaley; // rotation var sin = -row[0][1], cos = row[1][1]; if (cos < 0) { out.rotate = R.deg(math.acos(cos)); if (sin < 0) { out.rotate = 360 - out.rotate; } } else { out.rotate = R.deg(math.asin(sin)); } out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate); out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate; out.noRotation = !+out.shear.toFixed(9) && !out.rotate; return out; }; /*\ * Matrix.toTransformString [ method ] ** * Return transform string that represents given matrix = (string) transform string \*/ matrixproto.toTransformString = function(shorter) { var s = shorter || this[split](); if (s.isSimple) { s.scalex = +s.scalex.toFixed(4); s.scaley = +s.scaley.toFixed(4); s.rotate = +s.rotate.toFixed(4); return (s.dx || s.dy ? "t" + [s.dx, s.dy] : E) + (s.scalex != 1 || s.scaley != 1 ? "s" + [s.scalex, s.scaley, 0, 0] : E) + (s.rotate ? "r" + [s.rotate, 0, 0] : E); } else { return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)]; } }; })(Matrix.prototype); // WebKit rendering bug workaround method var navigator = win.navigator, version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/); if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") || (navigator.vendor == "Google Inc." && version && version[1] < 8)) { /*\ * Paper.safari [ method ] ** * There is an inconvenient rendering bug in Safari (WebKit): * sometimes the rendering should be forced. * This method should help with dealing with this bug. \*/ paperproto.safari = function() { var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({ stroke: "none" }); setTimeout(function() { rect.remove(); }); return true; }; } else { paperproto.safari = fun; } var preventDefault = function() { this.returnValue = false; }, preventTouch = function() { return this.originalEvent.preventDefault(); }, stopPropagation = function() { this.cancelBubble = true; }, stopTouch = function() { return this.originalEvent.stopPropagation(); }, eventCopyList = { stopPropagation: 'fn', stopImmediatePropagation: 'fn', preventDefault: 'fn', type: true, clientX: true, clientY: true, pageX: true, pageY: true, bubbles: true, cancelable: true, touches: true, target: true, originalTarget: true, srcElement: true, relatedTarget: true, fromElement: true, changedTouches: true, layerX: true, layerY: true }, makeSelectiveCopy = function (target, source) { for (let eve in eventCopyList) { if (eventCopyList[eve] === 'fn') { target[eve] = (function () { return function () { source[eve](); } })(source); } else { target[eve] = source[eve]; } } target.originalEvent = source; }, addEvent = R.addEvent = (function() { if (g.doc.addEventListener) { return function(obj, type, fn, element) { var realName = supportsOnlyTouch && touchMap[type] || type, f; touchMap[dragEventMap[type]] && (realName = touchMap[dragEventMap[type]]); f = function(e) { var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft, target; if (supportsTouch && touchMap[has](supportsOnlyTouch ? type : dragEventMap[type])) { for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) { target = e.targetTouches[i].target; if (target == obj || (target.nodeName == 'tspan' && target.parentNode == obj)) { var olde = e; e = e.targetTouches[i]; e.originalEvent = olde; e.preventDefault = preventTouch; e.stopPropagation = stopTouch; break; } } } return fn.call(element, e, e.clientX + scrollX, e.clientY + scrollY); }; obj.addEventListener(realName, f, {passive: false, capture:false}); return function() { obj.removeEventListener(realName, f, {passive: false, capture:false}); return true; }; }; } else if (g.doc.attachEvent) { return function(obj, type, fn, element) { var f = function(e) { e = e || g.win.event; var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft, x = e.clientX + scrollX, y = e.clientY + scrollY; e.preventDefault = e.preventDefault || preventDefault; e.stopPropagation = e.stopPropagation || stopPropagation; return fn.call(element, e, x, y); }; obj.attachEvent("on" + type, f); var detacher = function() { obj.detachEvent("on" + type, f); return true; }; return detacher; }; } })(), drag = [], dragMove = function(e) { var x = e.clientX, y = e.clientY, scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft, dragi, data, dummyEve = {}, key, el, j = drag.length; while (j--) { dragi = drag[j]; el = dragi.el; if (supportsTouch && e.type === 'touchmove') { var i = e.touches.length, touch; while (i--) { touch = e.touches[i]; if (touch.identifier == el._drag.id) { x = touch.clientX; y = touch.clientY; (e.originalEvent ? e.originalEvent : e).preventDefault(); break; } } } else { e.preventDefault(); } if (el.removed) { continue; } if (el.dragStartFn) { el.dragStartFn(); el.dragStartFn = undefined; el.dragInfo._dragmove = true; } if (g.win.opera) { var node = R._engine.getNode(el), next = node.nextSibling, parent = node.parentNode, display = node.style.display; parent.removeChild(node); node.style.display = "none"; node.style.display = display; next ? parent.insertBefore(node, next) : parent.appendChild(node); } x += scrollX; y += scrollY; //Function to copy some properties of the actual event into the dummy event makeSelectiveCopy(dummyEve, e); data = dummyEve.data = [x - el._drag.x, y - el._drag.y, x, y]; eve("raphael.drag.move." + el.id, dragi.move_scope || el, dummyEve, data); } }, dragUp = function(e) { R.undragmove(dragMove).undragend(dragUp); R.unmousemove(dragMove).unmouseup(dragUp); var i = drag.length, el, dragi; while (i--) { dragi = drag[i]; el = dragi.el if (!el.dragInfo._dragmove) { continue; } else { el.dragInfo._dragmove = undefined; } dragi.el._drag = {}; eve("raphael.drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e); } drag = []; }, /*\ * Raphael.el [ property (object) ] ** * You can add your own method to elements. This is usefull when you want to hack default functionality or * want to wrap some common transformation or attributes in one method. In difference to canvas methods, * you can redefine element method at any time. Expending element methods wouldn’t affect set. > Usage | Raphael.el.red = function () { | this.attr({fill: "#f00"}); | }; | // then use it | paper.circle(100, 100, 20).red(); \*/ elproto = R.el = {}; /*\ * Element.click [ method ] ** * Adds event handler for click for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unclick [ method ] ** * Removes event handler for click for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.dblclick [ method ] ** * Adds event handler for double click for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.undblclick [ method ] ** * Removes event handler for double click for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.mousedown [ method ] ** * Adds event handler for mousedown for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmousedown [ method ] ** * Removes event handler for mousedown for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.mousemove [ method ] ** * Adds event handler for mousemove for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmousemove [ method ] ** * Removes event handler for mousemove for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.mouseout [ method ] ** * Adds event handler for mouseout for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmouseout [ method ] ** * Removes event handler for mouseout for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.mouseover [ method ] ** * Adds event handler for mouseover for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmouseover [ method ] ** * Removes event handler for mouseover for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.mouseup [ method ] ** * Adds event handler for mouseup for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmouseup [ method ] ** * Removes event handler for mouseup for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.touchstart [ method ] ** * Adds event handler for touchstart for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchstart [ method ] ** * Removes event handler for touchstart for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.touchmove [ method ] ** * Adds event handler for touchmove for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchmove [ method ] ** * Removes event handler for touchmove for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.touchend [ method ] ** * Adds event handler for touchend for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchend [ method ] ** * Removes event handler for touchend for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.touchcancel [ method ] ** * Adds event handler for touchcancel for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchcancel [ method ] ** * Removes event handler for touchcancel for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ for (var i = events.length; i--; ) { (function(eventName) { R[eventName] = elproto[eventName] = function(fn, scope) { if (R.is(fn, "function")) { this.events = this.events || []; this.events.push({ name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this) }); } return this; }; R["un" + eventName] = elproto["un" + eventName] = function(fn) { var events = this.events || [], l = events.length; while (l--) if (events[l].name == eventName && events[l].f == fn) { events[l].unbind(); events.splice(l, 1); !events.length && delete this.events; return this; } return this; }; })(events[i]); } /*\ * Element.data [ method ] ** * Adds or retrieves given value asociated with given key. ** * See also @Element.removeData > Parameters - key (string) key to store data - value (any) #optional value to store = (object) @Element * or, if value is not specified: = (any) value > Usage | for (var i = 0, i < 5, i++) { | paper.circle(10 + 15 * i, 10, 10) | .attr({fill: "#000"}) | .data("i", i) | .click(function () { | alert(this.data("i")); | }); | } \*/ elproto.data = function(key, value) { var data = eldata[this.id] = eldata[this.id] || {}; if (arguments.length == 1) { if (R.is(key, object)) { for (var i in key) if (key[has](i)) { this.data(i, key[i]); } return this; } eve("raphael.data.get." + this.id, this, data[key], key); return data[key]; } data[key] = value; eve("raphael.data.set." + this.id, this, value, key); return this; }; /*\ * Element.removeData [ method ] ** * Removes value associated with an element by given key. * If key is not provided, removes all the data of the element. > Parameters - key (string) #optional key = (object) @Element \*/ elproto.removeData = function (key) { if (key == null) { delete eldata[this.id]; } else { eldata[this.id] && delete eldata[this.id][key]; } return this; }; /*\ * Element.getData [ method ] ** * Retrieves the element data = (object) data \*/ elproto.getData = function () { return clone(eldata[this.id] || {}); }; var downables = [], mouseDown = function () { this.untrack = addEvent(g.doc, 'mouseup', mouseUp, this); }, mouseUp = function () { this.untrack(); this.untrack = null; return this.fn && this.fn.apply(this.scope || this.el, arguments); }; elproto.mouseup = function (fn, scope, track) { if (!track) { return R.mouseup.apply(this, arguments); } downables.push(track = { el: this, fn: fn, scope: scope }); track.unbind = addEvent(this.shape || this.node || g.doc, 'mousedown', mouseDown, track); return this; }; elproto.unmouseup = function (fn) { var i = downables.length, undowned; while (i--) { if (downables[i].el === this && downables[i].fn === fn) { undowned = downables[i]; undowned.unbind(); undowned.untrack && undowned.untrack(); downables.splice(i, 1); } } return undowned ? this : R.unmouseup.apply(this, arguments); }; /*\ * Element.hover [ method ] ** * Adds event handlers for hover for the element. > Parameters - f_in (function) handler for hover in - f_out (function) handler for hover out - icontext (object) #optional context for hover in handler - ocontext (object) #optional context for hover out handler = (object) @Element \*/ elproto.hover = function(f_in, f_out, scope_in, scope_out) { return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in); }; /*\ * Element.unhover [ method ] ** * Removes event handlers for hover for the element. > Parameters - f_in (function) handler for hover in - f_out (function) handler for hover out = (object) @Element \*/ elproto.unhover = function(f_in, f_out) { return this.unmouseover(f_in).unmouseout(f_out); }; var draggable = []; /*\ * Element.drag [ method ] ** * Adds event handlers for drag of the element. > Parameters - onmove (function) handler for moving - onstart (function) handler for drag start - onend (function) handler for drag end - mcontext (object) #optional context for moving handler - scontext (object) #optional context for drag start handler - econtext (object) #optional context for drag end handler * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start, * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element * `drag.over.<id>` will be fired as well. * * Start event and start handler will be called in specified context or in context of the element with following parameters: o x (number) x position of the mouse o y (number) y position of the mouse o event (object) DOM event object * Move event and move handler will be called in specified context or in context of the element with following parameters: o dx (number) shift by x from the start point o dy (number) shift by y from the start point o x (number) x position of the mouse o y (number) y position of the mouse o event (object) DOM event object * End event and end handler will be called in specified context or in context of the element with following parameters: o event (object) DOM event object = (object) @Element \*/ elproto.drag = function(onmove, onstart, onend, move_scope, start_scope, end_scope) { var dragInfo = this.dragInfo || (this.dragInfo = { // Store all the callbacks for various eventListeners on the same element onmove: [], onstart: [], onend: [], move_scope: [], start_scope: [], end_scope: [] }); onmove && (dragInfo.onmove.push(onmove)); onstart && (dragInfo.onstart.push(onstart)); onend && (dragInfo.onend.push(onend)); // Scopes are not stored as when called via element.on, there is no provision for provifing scope this.dragFn = this.dragFn || function (e) { var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft, key, dummyEve = {}, data, i, j, k, ii, jj, kk, dragInfo = this.dragInfo; this._drag.x = e.clientX + scrollX; this._drag.y = e.clientY + scrollY; this._drag.id = e.identifier; // Add the drag events for the browsers that doesn't fire mouse event on touch and drag if (supportsTouch && !supportsOnlyTouch) { !drag.length && R.dragmove(dragMove).dragend(dragUp); } !drag.length && R.mousemove(dragMove).mouseup(dragUp); drag.push({ el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope }); //Function to copy some properties of the actual event into the dummy event makeSelectiveCopy(dummyEve, e); data = dummyEve.data = [e.clientX + scrollX, e.clientY + scrollY]; // Attaching handlers for various events for (i = 0, ii = dragInfo.onstart.length; i < ii; i ++) { eve.on("raphael.drag.start." + this.id, dragInfo.onstart[i]); } for (j = 0, jj = dragInfo.onmove.length; j < jj; j ++) { eve.on("raphael.drag.move." + this.id, dragInfo.onmove[j]); } for (k = 0, kk = dragInfo.onend.length; k < kk; k ++) { eve.on("raphael.drag.end." + this.id, dragInfo.onend[k]); } // Where there is no dragStart but there is dragEnd or dragMove handler if (!ii && (jj || kk) ) { eve.on("raphael.drag.end." + this.id, function() { this.undragmove(); }); } // Queuing up the dragStartFn. It is fired if dragmove is fired after dragStart this.dragStartFn = function () { eve("raphael.drag.start." + this.id, drag.start_scope || drag.move_scope || this, dummyEve, data); } } this._drag = {}; draggable.push({ el: this, start: this.dragFn, onstart: onstart, onmove: onmove, onend: onend }); if (onstart && !this.startHandlerAttached) { // Add the drag events for the browsers that doesn't fire mouse event on touch and drag if (supportsTouch && !supportsOnlyTouch) { this.dragstart(this.dragFn); } this.mousedown(this.dragFn); this.startHandlerAttached = true; } return this; }; /*\ * Element.onDragOver [ method ] ** * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id). > Parameters - f (function) handler for event, first argument would be the element you are dragging over \*/ elproto.onDragOver = function(f) { f ? eve.on("raphael.drag.over." + this.id, f) : eve.unbind("raphael.drag.over." + this.id); }; /*\ * Element.undrag [ method ] ** * Removes all drag event handlers from given element. \*/ elproto.undrag = function() { var i = draggable.length; while (i--) { if (draggable[i].el == this) { this.unmousedown(draggable[i].start); draggable.splice(i, 1); eve.unbind("raphael.drag.*." + this.id); this.dragInfo = undefined; this.dragFn = undefined; this.startHandlerAttached = undefined; } } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); delete this._drag; }; /*\ * Element.undragmove [ method ] ** * Removes all dragmove event handlers from given element. \*/ elproto.undragmove = function() { var i = draggable.length; while (i--) { if (draggable[i].el == this && draggable[i].onmove) { draggable.splice(i, 1); eve.unbind("raphael.drag.move." + this.id); this.dragInfo.onmove = undefined; } } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); }; /*\ * Element.undragend [ method ] ** * Removes all dragend event handlers from given element. \*/ elproto.undragend = function() { var i = draggable.length; while (i--) { if (draggable[i].el == this && draggable[i].onend) { draggable.splice(i, 1); eve.unbind("raphael.drag.end." + this.id); this.dragInfo.onend = undefined; } } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); }; /*\ * Element.undragstart [ method ] ** * Removes all dragstart event handlers from given element. \*/ elproto.undragstart = function() { var i = draggable.length; while (i--) { if (draggable[i].el == this && draggable[i].onstart) { this.unmousedown(draggable[i].start); draggable.splice(i, 1); eve.unbind("raphael.drag.start." + this.id); this._dragstart = false; this.dragInfo.onstart = undefined; this.dragFn = undefined; } } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); }; elproto.follow = function(el, callback, stalk) { if (el.removed || el.constructor !== R.el.constructor) { return this; } el.followers.push({ el: this, stalk: (stalk = {before: 'insertBefore', after: 'insertAfter'}[stalk]), cb: callback }); stalk && this[stalk](el); return this; }; elproto.unfollow = function(el) { if (el.removed || el.constructor !== R.el.constructor) { return this; } for (var i = 0, ii = el.followers.length; i < ii; i++) { if (el.followers[i].el === this) { el.followers.splice(i, 1); break; } } return this; }; /*\ * Paper.hide [ method ] ** * Hides a paper ** > Usage | paper.hide(); \*/ paperproto.hide = function () { var paper = this; paper.canvas.style.visibility = "hidden"; return paper; }; /*\ * Paper.show [ method ] ** * Shows a hidden paper ** > Usage | paper.show(); \*/ paperproto.show = function () { var paper = this; paper.canvas.style.visibility = E; return paper; }; /*\ * Paper.group [ method ] ** * Creates a group ** > Parameters ** - id (number) id of the group = (object) Raphaël element object with type “group” ** > Usage | var g = paper.group(); \*/ paperproto.group = function () { // id var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), out = R._engine.group(paper, args[0], group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.circle [ method ] ** * Draws a circle. ** > Parameters ** - x (number) x coordinate of the centre - y (number) y coordinate of the centre - r (number) radius = (object) Raphaël element object with type “circle” ** > Usage | var c = paper.circle(50, 50, 40); \*/ paperproto.circle = function () { // x, y, r var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), attrs = serializeArgs(args, "cx", 0, "cy", 0, "r", 0, "fill", none, "stroke", black), out = R._engine.circle(paper, attrs, group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.rect [ method ] * * Draws a rectangle. ** > Parameters ** - x (number) x coordinate of the top left corner - y (number) y coordinate of the top left corner - width (number) width - height (number) height - r (number) #optional radius for rounded corners, default is 0 = (object) Raphaël element object with type “rect” ** > Usage | // regular rectangle | var c = paper.rect(10, 10, 50, 50); | // rectangle with rounded corners | var c = paper.rect(40, 40, 50, 50, 10); \*/ paperproto.rect = function () { var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), attrs = serializeArgs(args, "x", 0, "y", 0, "width", 0, "height", 0, "r", 0, "fill", none, "stroke", black), out = R._engine.rect(paper, attrs, group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.ellipse [ method ] ** * Draws an ellipse. ** > Parameters ** - x (number) x coordinate of the centre - y (number) y coordinate of the centre - rx (number) horizontal radius - ry (number) vertical radius = (object) Raphaël element object with type “ellipse” ** > Usage | var c = paper.ellipse(50, 50, 40, 20); \*/ paperproto.ellipse = function () { var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), attrs = serializeArgs(args, "x", 0, "y", 0, "rx", 0, "ry", 0, "fill", none, "stroke", black), out = R._engine.ellipse(this, attrs, group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.path [ method ] ** * Creates a path element by given path data string. > Parameters - pathString (string) #optional path string in SVG format. * Path string consists of one-letter commands, followed by comma seprarated arguments in numercal form. Example: | "M10,20L30,40" * Here we can see two commands: “M”, with arguments `(10, 20)` and “L” with arguments `(30, 40)`. Upper case letter mean command is absolute, lower case—relative. * # <p>Here is short list of commands available, for more details see <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path's data attribute's format are described in the SVG specification.">SVG path string format</a>.</p> # <table><thead><tr><th>Command</th><th>Name</th><th>Parameters</th></tr></thead><tbody> # <tr><td>M</td><td>moveto</td><td>(x y)+</td></tr> # <tr><td>Z</td><td>closepath</td><td>(none)</td></tr> # <tr><td>L</td><td>lineto</td><td>(x y)+</td></tr> # <tr><td>H</td><td>horizontal lineto</td><td>x+</td></tr> # <tr><td>V</td><td>vertical lineto</td><td>y+</td></tr> # <tr><td>C</td><td>curveto</td><td>(x1 y1 x2 y2 x y)+</td></tr> # <tr><td>S</td><td>smooth curveto</td><td>(x2 y2 x y)+</td></tr> # <tr><td>Q</td><td>quadratic Bézier curveto</td><td>(x1 y1 x y)+</td></tr> # <tr><td>T</td><td>smooth quadratic Bézier curveto</td><td>(x y)+</td></tr> # <tr><td>A</td><td>elliptical arc</td><td>(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+</td></tr> # <tr><td>R</td><td><a href="http://en.wikipedia.org/wiki/Catmull–Rom_spline#Catmull.E2.80.93Rom_spline">Catmull-Rom curveto</a>*</td><td>x1 y1 (x y)+</td></tr></tbody></table> * * “Catmull-Rom curveto” is a not standard SVG command and added in 2.0 to make life easier. * Note: there is a special case when path consist of just three commands: “M10,10R…z”. In this case path will smoothly connects to its beginning. > Usage | var c = paper.path("M10 10L90 90"); | // draw a diagonal line: | // move to 10,10, line to 90,90 * For example of path strings, check out these icons: http://raphaeljs.com/icons/ \*/ paperproto.path = function () { var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), paperConfig = paper.config, capStyle = (paperConfig && paperConfig["stroke-linecap"]) || "butt", attrs = serializeArgs(args, "path", E, "fill", none, "stroke", black, "stroke-linecap", capStyle), out = R._engine.path(paper, attrs, group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.image [ method ] ** * Embeds an image into the surface. ** > Parameters ** - src (string) URI of the source image - x (number) x coordinate position - y (number) y coordinate position - width (number) width of the image - height (number) height of the image = (object) Raphaël element object with type “image” ** > Usage | var c = paper.image("apple.png", 10, 10, 80, 80); \*/ paperproto.image = function () { var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), attrs = serializeArgs(args, // "src", "", "x", 0, "y", 0, "width", 0, "height", 0), out = R._engine.image(paper, attrs, group); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.text [ method ] ** * Draws a text string. If you need line breaks, put “\n” in the string. ** > Parameters ** - x (number) x coordinate position - y (number) y coordinate position - text (string) The text string to draw = (object) Raphaël element object with type “text” ** > Usage | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!"); \*/ paperproto.text = function() { var paper = this, args = getArrayCopy(arguments), group = lastArgIfGroup(args, true), attrs = serializeArgs(args, "x", 0, "y", 0, "text", E, "stroke", none, "fill", black, "text-anchor", "middle", "vertical-align", "middle"), out = R._engine.text(paper, attrs, group, args[1]); return (paper.__set__ && paper.__set__.push(out), (paper._elementsById[out.id] = out)); }; /*\ * Paper.setConfig [ method ] ** * If you need to store any configuration in paper, call this method ** > Parameters ** - key (String) key name of the key-value pair - value (String or number) value of the key-value pair \*/ paperproto.setConfig = function (key, value) { var paper = this; if ((key !== undefined) && (value !== undefined)) { paper.config = paper.config || {}; paper.config[key] = value; } return paper.config; }; /*\ * Paper._createDOMNodes [ method ] ** * Create DOM nodes with nested children ** > Parameters ** - parentElem (object) parent element node - elemObj (object) nested input object to create elements - returnObj (object) object reference which will be returned ** > Usage | paper._createDOMNodes(parentElementNode, { | tagName: 'filter', | id: 'filter-0', | width: '200%', | height: '200%', | children: [{ | tagName: 'feOffset', | result: 'offOut', | in: 'SourceGraphic', | dx: '1', | dy: '1' | }, { | tagName: 'feColorMatrix', | result: 'matrixOut', | in: 'offOut', | type: 'matrix', | values: '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0' | }, { | tagName: 'feGaussianBlur', | result: 'blurOut', | in: 'matrixOut', | stdDeviation: '1' | }, { | tagName: 'feComposite', | in: 'SourceGraphic', | in2: 'blurOut', | operator: 'over' | }] | }); \*/ paperproto._createDOMNodes = function(parentElem, elementObj, returnObj) { var paper = this, ele, i, len, attr = {}, attrKey, createNode = R._createNode, tagName = elementObj.tagName, children = elementObj.children || []; !returnObj && (returnObj = {}); for (attrKey in elementObj) { if (attrKey !== 'tagName' && attrKey !== 'children') { attr[attrKey] = elementObj[attrKey]; } } !attr.id && (attr.id = R.getElementID(R.createUUID())); if (!paper.canvas.getElementById(attr.id) && tagName) { ele = parentElem.appendChild(createNode(tagName, attr)); returnObj.element = ele; returnObj.id = attr.id; len = children.length; (len > 0) && (returnObj.children = []); for (i = 0; i < len; i++) { returnObj.children[i] = {}; paper._createDOMNodes(ele, children[i], returnObj.children[i]); } } return returnObj; }; /*\ * Paper.addDefs [ method ] ** * Add definitions in paper ** > Parameters ** - elemObj (object) nested input object to create elements ** > Usage | var ob = paper.addDefs({ | filter0: { // key | tagName: 'filter', | id: 'filter-0', | width: '200%', | height: '200%', | children: [{ | tagName: 'feOffset', | result: 'offOut', | in: 'SourceGraphic', | dx: '1', | dy: '1' | }, { | tagName: 'feColorMatrix', | result: 'matrixOut', | in: 'offOut', | type: 'matrix', | values: '0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0' | }, { | tagName: 'feGaussianBlur', | result: 'blurOut', | in: 'matrixOut', | stdDeviation: '1' | }, { | tagName: 'feComposite', | in: 'SourceGraphic', | in2: 'blurOut', | operator: 'over' | }] | } | }); | // Creates a 'filter' definition element of id, 'filter-0', with width, height as it's attributes | // Creates feOffset, feColorMatrix, feGaussianBlur, feComposite as children elements | // under the 'filter' definition element \*/ paperproto.addDefs = function (elemObj) { if (!R.svg) { return; } var paper = this, key, returnObj = {}, defs = paper.defs; for (key in elemObj) { returnObj[key] = {}; paper._createDOMNodes(defs, elemObj[key], returnObj[key]); } return returnObj; }; /*\ * Paper.removeDefs [ method ] ** * Remove a particular definition of given id from paper ** > Parameters ** - id (string) id of the element to remove ** > Usage | paper.removeDefs(id); \*/ paperproto.removeDefs = function (id) { if (!R.svg) { return; } var element = R._g.doc.getElementById(id); element && element.remove(); }; /*\ * Paper.updateDefs [ method ] ** * Update definitions in paper ** > Parameters ** - id (string or object) id of the element or the element node itself - attrObj (object) attribute of the element object with it's children attributes nested - hardUpdateChildren (boolean) determines whether to create new children if child elements are less than the children in attrObj or remove children in same manner ** > Usage | paper.updateDefs(id, { | width: '100%', | height: '100%', | children: [{ | dx: '2' | }] | }, true); | // Updates element of given id | // Updates the child element if present and create new child if found less than the children in attrObj | // and delete a child in same manner according to value of 'hardUpdateChildren' \*/ paperproto.updateDefs = function (id, attrObj, hardUpdateChildren) { if (!R.svg) { return; } var paper = this, element = !(id instanceof Node) ? R._g.doc.getElementById(id) : id, attrKey, i, diff, len, children = attrObj.children || [], elemChildren, childId, attr = {}; (hardUpdateChildren === undefined) && (hardUpdateChildren = true); if (element) { for (attrKey in attrObj) { if (attrKey !== 'tagName' && attrKey !== 'children') { element.setAttribute(attrKey, attrObj[attrKey]); } } elemChildren = element.children; for (i = 0, len = children.length; i < len; i++) { childId = children[i].id; elemChildren[i] ? paper.updateDefs(childId || elemChildren[i], children[i]) : hardUpdateChildren && paper._createDOMNodes(element, children[i]); } if (hardUpdateChildren) { diff = elemChildren.length - i; while (diff > 0) { elemChildren[elemChildren.length - 1].remove(); diff--; } } } }; /*\ * Paper.setSize [ method ] ** * If you need to change dimensions of the canvas call this method ** > Parameters ** - width (number) new width of the canvas - height (number) new height of the canvas \*/ paperproto.setSize = function(width, height) { return R._engine.setSize.call(this, width, height); }; /*\ * paper.setDimension [ method ] ** * If you need to change dimensions of the canvas call this method ** > Parameters ** - paramsObj (Object or number) - paramsObj (Object) ** > Properties of paramsObj - width (number) new width of the canvas - height (number) new height of the canvas ** - paramsObj (number) new width of the canvas ** - height (number) new height of the canvas \*/ paperproto.setDimension = function(paramsObj, height) { var paper = this, width; // Check if the first argument is an object or not if (typeof(paramsObj) === 'object') { width = paramsObj.width; height = paramsObj.height; paper.setSize(paramsObj.width, paramsObj.height); } else { width = paramsObj; paper.setSize(width, height); } }; paperproto.attr = function (name) { var element = this; if (name == null) { return { width : element.width, height : element.height }; } if (R.is(name, "string")) { return element[name]; } element.setDimension(name); return element; }; paperproto.status = function(anim, value) { return elproto.status.call(this, anim, value); }; // Works exactly as paper.animateWith() paperproto.animateWith = function(el, anim, params, ms, easing, callback, configObject) { return elproto.animateWith.call(this, el, anim, params, ms, easing, callback, configObject); }; /*\ * Paper.animate [ method ] ** * If you need to animate dimensions of the canvas call this method ** > Parameters ** - paramsObj (Object) > Properties of paramsObj ** - width (number) new width of the canvas - height (number) new height of the canvas - duration (number) time stretch in milliseconds to complete animation - effect (String) animation style - callback (function reference) method which will execute at end of animation \*/ paperproto.animate = function(params, ms, easing, callback) { return elproto.animate.call(this, params, ms, easing, callback); }; /*\ * Paper.setViewBox [ method ] ** * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by * specifying new boundaries. ** > Parameters ** - x (number) new x position, default is `0` - y (number) new y position, default is `0` - w (number) new width of the canvas - h (number) new height of the canvas - fit (boolean) `true` if you want graphics to fit into new boundary box \*/ paperproto.setViewBox = function(x, y, w, h, fit) { return R._engine.setViewBox.call(this, x, y, w, h, fit); }; paperproto.getById = function (id) { return this._elementsById[id] || null; }; /*\ * Paper.top [ property ] ** * Points to the topmost element on the paper \*/ /*\ * Paper.bottom [ property ] ** * Points to the bottom element on the paper \*/ paperproto.top = paperproto.bottom = null; /*\ * Paper.raphael [ property ] ** * Points to the @Raphael object/function \*/ paperproto.raphael = R; function x_y() { return this.x + S + this.y; }; function x_y_w_h() { return this.x + S + this.y + S + this.width + " \xd7 " + this.height; }; /*\ * Element.getBBox [ method ] ** * Return bounding box for a given element ** > Parameters ** - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`. = (object) Bounding box object: o { o x: (number) top left corner x o y: (number) top left corner y o x2: (number) bottom right corner x o y2: (number) bottom right corner y o width: (number) width o height: (number) height o } \*/ elproto.getBBox = function(isWithoutTransform) { if (this.removed) { return {}; } var _ = this._; if (isWithoutTransform) { if (_.dirty || !_.bboxwt) { this.realPath = getPath[this.type](this); _.bboxwt = pathDimensions(this.realPath); _.bboxwt.toString = x_y_w_h; _.dirty = 0; } return _.bboxwt; } if (_.dirty || _.dirtyT || !_.bbox) { if (_.dirty || !this.realPath) { _.bboxwt = 0; this.realPath = getPath[this.type](this); } _.bbox = pathDimensions(mapPath(this.realPath, this.matrix)); _.bbox.toString = x_y_w_h; _.dirty = _.dirtyT = 0; } return _.bbox; }; /*\ * Element.clone [ method ] ** = (object) clone of a given element ** \*/ // elproto.clone = function() { // if (this.removed) { // return null; // } // var o = this, // out = o.paper[o.type]().attr(o.attr()); // o.__set__ && o.__set__.push(out); // return out; // }; /*\ * Element.clone [ method ] ** > Parameters ** - attrObj (object) set of attributes - group (object) parent node = (object) clone of a given element ** \*/ elproto.clone = function(attrObj, group) { if (this.removed) { return null; } var o = this, attr = o.attr(), key, out; if (!attrObj) { out = o.paper[o.type]().attr(attr); } else { for (key in attrObj) { attr[key] = attrObj[key]; } out = o.paper[o.type](attr, group); } o.__set__ && o.__set__.push(out); return out; }; var curveslengths = {}, getPointAtSegmentLength = function(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) { if (length == null) { return bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y); } else { return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)); } }, getLengthFactory = function(istotal, subpath) { return function(path, length, onlystart) { path = path2curve(path); var x, y, p, l, sp = "", subpaths = {}, point, len = 0; for (var i = 0, ii = path.length; i < ii; i++) { p = path[i]; if (p[0] == "M") { x = +p[1]; y = +p[2]; } else { l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]); if (len + l > length) { if (subpath && !subpaths.start) { point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len); sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y]; if (onlystart) { return sp; } subpaths.start = sp; sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join(); len += l; x = +p[5]; y = +p[6]; continue; } if (!istotal && !subpath) { point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len); return { x: point.x, y: point.y, alpha: point.alpha }; } } len += l; x = +p[5]; y = +p[6]; } sp += p.shift() + p; } subpaths.end = sp; point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1); point.alpha && (point = { x: point.x, y: point.y, alpha: point.alpha }); return point; }; }, getTotalLength = getLengthFactory(1), getPointAtLength = getLengthFactory(), getSubpathsAtLength = getLengthFactory(0, 1); R.getTotalLength = getTotalLength; R.getPointAtLength = getPointAtLength; R.getSubpath = function(path, from, to) { if (this.getTotalLength(path) - to < 1e-6) { return getSubpathsAtLength(path, from).end; } var a = getSubpathsAtLength(path, to, 1); return from ? getSubpathsAtLength(a, from).end : a; }; /*\ * Raphael.getTotalLength [ method ] ** * Returns length of the given path in pixels. ** > Parameters ** - path (string) SVG path string. ** = (number) length. \*/ elproto.getTotalLength = function() { if (this.type != "path") { return; } if (this.node.getTotalLength) { return this.node.getTotalLength(); } return getTotalLength(this.attrs.path); }; /*\ * Raphael.getPointAtLength [ method ] ** * Return coordinates of the point located at the given length on the given path. ** > Parameters ** - path (string) SVG path string - length (number) ** = (object) representation of the point: o { o x: (number) x coordinate o y: (number) y coordinate o alpha: (number) angle of derivative o } \*/ elproto.getPointAtLength = function(length) { if (this.type != "path") { return; } return getPointAtLength(this.attrs.path, length); }; /*\ * Raphael.getSubpath [ method ] ** * Return subpath of a given path from given length to given length. ** > Parameters ** - path (string) SVG path string - from (number) position of the start of the segment - to (number) position of the end of the segment ** = (string) pathstring for the segment \*/ elproto.getSubpath = function(from, to) { if (this.type != "path") { return; } return R.getSubpath(this.attrs.path, from, to); }; /*\ * Raphael.easing_formulas [ property ] ** * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing: # <ul> # <li>“linear”</li> # <li>“&lt;” or “easeIn” or “ease-in”</li> # <li>“>” or “easeOut” or “ease-out”</li> # <li>“&lt;>” or “easeInOut” or “ease-in-out”</li> # <li>“backIn” or “back-in”</li> # <li>“backOut” or “back-out”</li> # <li>“elastic”</li> # <li>“bounce”</li> # </ul> # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p> \*/ var ef = R.easing_formulas = { linear: function(n) { return n; }, "<": function(n) { return pow(n, 1.7); }, ">": function(n) { return pow(n, .48); }, "<>": function(n) { var q = .48 - n / 1.04, Q = mathSqrt(.1734 + q * q), x = Q - q, X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1), y = -Q - q, Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1), t = X + Y + .5; return (1 - t) * 3 * t * t + t * t * t; }, backIn: function(n) { var s = 1.70158; return n * n * ((s + 1) * n - s); }, backOut: function(n) { n = n - 1; var s = 1.70158; return n * n * ((s + 1) * n + s) + 1; }, elastic: function(n) { if (n == !!n) { return n; } return pow(2, -10 * n) * mathSin((n - .075) * (2 * PI) / .3) + 1; }, bounce: function(n) { var s = 7.5625, p = 2.75, l; if (n < (1 / p)) { l = s * n * n; } else { if (n < (2 / p)) { n -= (1.5 / p); l = s * n * n + .75; } else { if (n < (2.5 / p)) { n -= (2.25 / p); l = s * n * n + .9375; } else { n -= (2.625 / p); l = s * n * n + .984375; } } } return l; }, // used in line chart anchor animation oneBounceOut: function (n) { var top = 120; if (n <= 0.9) { return ef.easeIn(n) * 1.33; } return 1.2 - n / 5; }, // Used in translating bubble plots elasticOnce: function(n) { var p = 0.9; if (n == !!n) { return n; } return Math.pow(2, -10 * n) * Math.sin((n - p / 4) * (2 * Math.PI) / p) + 1; }, // accelerating from zero velocity easeInQuad: function (t) { return t*t }, // decelerating to zero velocity easeOutQuad: function (t) { return t*(2-t) }, // acceleration until halfway, then deceleration easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t }, // accelerating from zero velocity easeInCubic: function (t) { return t*t*t }, // decelerating to zero velocity easeOutCubic: function (t) { return (--t)*t*t+1 }, // acceleration until halfway, then deceleration easeInOutCubic: function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1 }, // accelerating from zero velocity easeInQuart: function (t) { return t*t*t*t }, // decelerating to zero velocity easeOutQuart: function (t) { return 1-(--t)*t*t*t }, // acceleration until halfway, then deceleration easeInOutQuart: function (t) { return t<.5 ? 8*t*t*t*t : 1-8*(--t)*t*t*t }, // accelerating from zero velocity easeInQuint: function (t) { return t*t*t*t*t }, // decelerating to zero velocity easeOutQuint: function (t) { return 1+(--t)*t*t*t*t }, // acceleration until halfway, then deceleration easeInOutQuint: function (t) { return t<.5 ? 16*t*t*t*t*t : 1+16*(--t)*t*t*t*t } }; ef.easeIn = ef["ease-in"] = ef["<"]; ef.easeOut = ef["ease-out"] = ef[">"]; ef.easeInOut = ef["ease-in-out"] = ef["<>"]; ef["back-in"] = ef.backIn; ef["back-out"] = ef.backOut; var animationElements = [], requestAnimFrame, // This a temporary fix so that animation can be handled from the scheduler module. animation = function() { var Now = +new Date, l = 0, deqArr = [], i = 0, ll = 0, tmpOpacity, radial, animFrameFn; for (; l < animationElements.length; l++) { var e = animationElements[l]; if (e.el.removed || e.paused || e.parentEl && e.parentEl.e && e.parentEl.e.paused) { continue; } var time = Now - e.start, ms = e.ms, easing = e.easing, from = e.from, diff = e.diff, to = e.to, t = e.t, that = e.el, set = {}, now, origms, init = {}, executeEvent = !R.stopPartialEventPropagation, key, i = 0, peekVal = e.el && e.el.animElements && e.el.animElements.peek(); // Checking hooks while (peekVal && peekVal.pos <= time / ms) { deqArr.push(e.el.animElements.deq()); peekVal = e.el.animElements.peek(); } if (e.initstatus) { time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms; e.status = e.initstatus; delete e.initstatus; if (e.stop) { delete e.el; animationElements.splice(l--, 1); } } else { e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top; } origms = ms; // If has parentEl if (e.parentEl && e.parentEl.animElements) { ms = e.delayend - e.delaystart; time = e.parentEl.cPos - e.delaystart; } else if (e.el.animElements) { e.el.cPos = time / ms; } if (time < 0) { continue; } if (time < ms) { var pos = easing(time / ms); ms = origms; for (var attr in from) if (from[has](attr)) { switch (availableAnimAttrs[attr]) { case nu: now = +from[attr] + pos * ms * diff[attr]; break; case "colour": if (!diff[attr].length) { tmpOpacity = (from[attr].opacity + pos * ms * diff[attr].opacity); if(isNaN(tmpOpacity)){ tmpOpacity = 1; } now = "rgba(" + [ upto255(round(from[attr].r + pos * ms * diff[attr].r)), upto255(round(from[attr].g + pos * ms * diff[attr].g)), upto255(round(from[attr].b + pos * ms * diff[attr].b)), tmpOpacity ].join(",") + ")"; } else { now = []; for (i = 0, ii = from[attr].length; i < ii; ++i) { if (i === 0) { if(from[attr].isRadial || diff[attr].isRadial){ radial = "xr("; radial += from[attr][0].f1 * (1 - pos) + diff[attr][0].f1 * pos || ''; radial += ','; radial += from[attr][0].f2 * (1 - pos) + diff[attr][0].f2 * pos || ''; radial += ','; radial += (from[attr][0].f3 * (1 - pos) + diff[attr][0].f3 * pos) * 100 || ''; radial += '%,'; radial += from[attr][0].f4 * (1 - pos) + diff[attr][0].f4 * pos || ''; radial += ','; radial += from[attr][0].f5 * (1 - pos) + diff[attr][0].f5 * pos; radial += ','; radial += from[attr][0].f6; radial += ')'; now.push(radial) } else { now.push((from[attr][i] * (1 - pos)) + (pos * diff[attr][i])); if (now[0] <= 0) { now[0] += 360; } } } else { now.push("rgba(" + [ upto255(round(from[attr][i].r + pos * ms * diff[attr][i].r)), upto255(round(from[attr][i].g + pos * ms * diff[attr][i].g)), upto255(round(from[attr][i].b + pos * ms * diff[attr][i].b)), (from[attr][i].opacity + pos * ms * diff[attr][i].opacity) ].join(",") + "):" + from[attr][i].position); } } now = now.join("-"); // If radial focus doesnt have a separator if(from[attr].isRadial || diff[attr].isRadial){ now = now.replace('-', ''); } } break; case "path": now = []; for (var i = 0, ii = from[attr].length; i < ii; i++) { now[i] = [from[attr][i][0]]; var jj; jj = from[attr][i] ? from[attr][i].length : 0; for (var j = 1 ; j < jj; j++) { now[i][j] = (+from[attr][i][j] + pos * ms * diff[attr][i][j]).toFixed(4); } now[i] = now[i].join(S); } now = now.join(S); break; case "transform": if (diff[attr].real) { now = []; for (i = 0, ii = from[attr].length; i < ii; i++) { now[i] = [from[attr][i][0]]; for (j = 1, jj = from[attr][i].length; j < jj; j++) { now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j]; } } } else { var get = function(i) { return +from[attr][i] + pos * ms * diff[attr][i]; }; // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]]; now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]]; } break; case "csv": if (attr == "clip-rect") { now = []; i = 4; while (i--) { now[i] = +from[attr][i] + pos * ms * diff[attr][i]; } } break; case "text-bound": now = [][concat](from[attr]); break; default: var from2 = [][concat](from[attr]); now = []; i = that.ca[attr].length; while (i--) { now[i] = +from2[i] + pos * ms * diff[attr][i]; } break; } set[attr] = now; } that.attr(set); if (executeEvent) { (function(id, that, anim) { setTimeout(function() { eve("raphael.anim.frame." + id, that, anim); }); })(that.id, that, e.anim); } } else { (function(f, el, a) { setTimeout(function() { executeEvent && eve("raphael.anim.frame." + el.id, el, a); executeEvent && eve("raphael.anim.finish." + el.id, el, a); R.is(f, "function") && f.call(el); }); })(e.callback, that, e.anim); that.attr(to); delete e.el; animationElements.splice(l--, 1); if (e.repeat > 1 && !e.next) { for (key in to) if (to[has](key)) { init[key] = e.totalOrigin[key]; } e.el.attr(init); runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1); } if (e.next && !e.stop) { runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat); } } } R.svg && that && that.paper && that.paper.safari(); // Starting animation on timer 0 for (l = 0, ll = deqArr.length; l < ll; ++l) { // lib.schedular.addJob((function (l) { // return function () { // runAnimation.apply(null, deqArr[l].params); // }; // })(l), lib.priorityList.instant); animFrameFn = R.getInstantAnimFrameFn(); animFrameFn((function (l) { return function () { runAnimation.apply(null, deqArr[l].params); }; })(l)); } animationElements.length && (requestAnimFrame || R.getAnimFrameFn())(animation); }, upto255 = function(color) { return color > 255 ? 255 : color < 0 ? 0 : color; }, checkPercentage = function (num) { num > 1 && (num = 1); num < 0 && (num = 0); return num; }; R.getAnimFrameFn = function () { return requestAnimFrame = R.requestAnimFrame || _win.webkitRequestAnimationFrame || _win.mozRequestAnimationFrame || _win.oRequestAnimationFrame || _win.msRequestAnimationFrame || function(callback) { setTimeout(callback, 16); }; }; R.getInstantAnimFrameFn = function () { return R.instantRequestAnimFrame || _win.webkitRequestAnimationFrame || _win.mozRequestAnimationFrame || _win.oRequestAnimationFrame || _win.msRequestAnimationFrame || function(callback) { setTimeout(callback, 16); }; }; /*\ * Element.animateWith [ method ] ** * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element. ** > Parameters ** - el (object) element to sync with - anim (object) animation to sync with - params (object) #optional final attributes for the element, see also @Element.attr - ms (number) #optional number of milliseconds for animation to run - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)` - callback (function) #optional callback function. Will be called at the end of animation. - configObject (object) #optional takes an object with optional properties like start(what percentage to start aniation), end(what percentage to end animation), hookFn(function to be called before applying animation), smartMorph(whether to use smartMorphing in path animation) * or - element (object) element to sync with - anim (object) animation to sync with - animation (object) #optional animation object, see @Raphael.animation ** = (object) original element \*/ elproto.animateWith = function(el, anim, params, ms, easing, callback, configObject) { var element = this, refOb = {}, key; // Copying the reference object configObject = configObject || {}; for (key in configObject) { if (configObject.hasOwnProperty(key)) { refOb[key] = configObject[key]; } } configObject = refOb; if (element.removed) { callback && callback.call(element); return element; } if (ms == 0) { if (R.is(callback, "function")) { setTimeout(function () { callback.call(element); }, 0); } return element.attr (params); } var a = params instanceof Animation ? params : R.animation(params, ms, easing, callback), x, y; configObject.start = checkPercentage(configObject.start || 0); configObject.end = checkPercentage(configObject.end || 1); if (configObject.start >= configObject.end){ configObject.start = configObject.end; } if (!configObject.from && configObject.start > 0.01) { // Initializing new Priority Queue if not present already el.animElements = el.animElements || new PriorityQueue(function comparator (a, b) { return b.pos - a.pos; }); el.animElements.enq({ pos: configObject.start, attr: configObject.start === configObject.end, params: [a, element, a.percents[0], null, element.attr(),undefined, el, { start: configObject.start, end: configObject.end, smartMorph: configObject.smartMorph, hookFn: configObject.hookFn }, params], executeOb: { el: this, attrs: params, callback: callback, hookFn: configObject.hookFn } }); } else { runAnimation(a, element, a.percents[0], null, element.attr(),undefined, el, configObject); } for (var i = 0, ii = animationElements.length; i < ii; i++) { if (animationElements[i].anim == anim && animationElements[i].el == el) { animationElements[ii - 1].start = animationElements[i].start; break; } } return element; // var a = params ? R.animation(params, ms, easing, callback) : anim, // status = element.status(anim); // return this.animate(a).status(a, status * anim.ms / a.ms); }; function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) { var cx = 3 * p1x, bx = 3 * (p2x - p1x) - cx, ax = 1 - cx - bx, cy = 3 * p1y, by = 3 * (p2y - p1y) - cy, ay = 1 - cy - by; function sampleCurveX(t) { return ((ax * t + bx) * t + cx) * t; } function solve(x, epsilon) { var t = solveCurveX(x, epsilon); return ((ay * t + by) * t + cy) * t; } function solveCurveX(x, epsilon) { var t0, t1, t2, x2, d2, i; for (t2 = x, i = 0; i < 8; i++) { x2 = sampleCurveX(t2) - x; if (abs(x2) < epsilon) { return t2; } d2 = (3 * ax * t2 + 2 * bx) * t2 + cx; if (abs(d2) < 1e-6) { break; } t2 = t2 - x2 / d2; } t0 = 0; t1 = 1; t2 = x; if (t2 < t0) { return t0; } if (t2 > t1) { return t1; } while (t0 < t1) { x2 = sampleCurveX(t2); if (abs(x2 - x) < epsilon) { return t2; } if (x > x2) { t0 = t2; } else { t1 = t2; } t2 = (t1 - t0) / 2 + t0; } return t2; } return solve(t, 1 / (200 * duration)); } elproto.onAnimation = function(f) { f ? eve.on("raphael.anim.frame." + this.id, f) : eve.unbind("raphael.anim.frame." + this.id); return this; }; function Animation(anim, ms) { var percents = [], newAnim = {}; this.ms = ms; this.times = 1; if (anim) { for (var attr in anim) if (anim[has](attr)) { newAnim[toFloat(attr)] = anim[attr]; percents.push(toFloat(attr)); } percents.sort(sortByNumber); } this.anim = newAnim; this.top = percents[percents.length - 1]; this.percents = percents; } /*\ * Animation.delay [ method ] ** * Creates a copy of existing animation object with given delay. ** > Parameters ** - delay (number) number of ms to pass between animation start and actual animation ** = (object) new altered Animation object | var anim = Raphael.animation({cx: 10, cy: 20}, 2e3); | circle1.animate(anim); // run the given animation immediately | circle2.animate(anim.delay(500)); // run the given animation after 500 ms \*/ Animation.prototype.delay = function(delay) { var a = new Animation(this.anim, this.ms); a.times = this.times; a.del = +delay || 0; return a; }; /*\ * Animation.repeat [ method ] ** * Creates a copy of existing animation object with given repetition. ** > Parameters ** - repeat (number) number iterations of animation. For infinite animation pass `Infinity` ** = (object) new altered Animation object \*/ Animation.prototype.repeat = function(times) { var a = new Animation(this.anim, this.ms); a.del = this.del; a.times = math.floor(mmax(times, 0)) || 1; return a; }; /* ** Function to convert two color string in array format such that ** it is animatabale ** @param {string} c1 color 1 ** @param {string} c2 color 2 ** @param {function} function to getRGB */ function colorNormalizer(c1, c2, getRGB) { "use strict"; var colorAr1, colorAr2, i = 0, ii = 0, j = 0, newColArr = [], newColArr2 = [], temp = {}, pos = 0, uniqArr = []; c1 = c1.constructor === Array ? c1[0]: c1; c2 = c2.constructor === Array ? c2[0]: c2; colorAr1 = c1.split('-'); colorAr2 = c2.split('-'); if (colorAr1.length === 1 && colorAr2.length === 1) { return [c1, c2]; } // Convert colors to linear format, and mark if any of them is radial // linear to radial animation is not correct colorAr1 = allToLinear(colorAr1); colorAr2 = allToLinear(colorAr2); // Handling if default color was added to one // and not other if (!colorAr1.defaultAngleSet && colorAr2.defaultAngleSet) { colorAr2[0] = colorAr1[0]; } if (!colorAr2.defaultAngleSet && colorAr1.defaultAngleSet) { colorAr1[0] = colorAr2[0]; } // If one is radial convert both to radial converToRadialIfOneRadial(colorAr1, colorAr2); /* Making a unique array to store all unique color positions of both color so that new color can be generated that have same amount of positions added */ for(i = 1, ii = colorAr1.length; i < ii; ++i){ pos = colorAr1[i].position; // if(uniqArr.indexOf(pos) === -1){ uniqArr.push(pos); // } } for(i = 1, ii = colorAr2.length; i < ii; ++i){ pos = colorAr2[i].position; if(uniqArr.indexOf(pos) === -1){ uniqArr.push(pos); } } uniqArr.push(0); // sort the positions uniqArr.sort(function(a,b){return a - b}); // generating new colors from the existing colors newColArr = [colorAr1[0]]; for (i = 1, ii = uniqArr.length; i < ii; ++i) { pos = uniqArr[i]; temp = colorAr1.getColorAtPosition(pos); newColArr.push(temp); } newColArr2 = [colorAr2[0]]; for (i = 1, ii = uniqArr.length; i < ii; ++i) { pos = uniqArr[i]; temp = colorAr2.getColorAtPosition(pos); newColArr2.push(temp); } // copying isRadial property newColArr.isRadial = colorAr1.isRadial; newColArr2.isRadial = colorAr2.isRadial; return [newColArr, newColArr2]; // Getting all unique points function converToRadialIfOneRadial(a, b, end){ var angle = 0; if(a.isRadial && !b.isRadial){ angle += +b[0]; b[0] = { f1: 0, f2: 0, f3: 0, f4: 0, f5: 0, f6: '' } b.isRadial = true; } if(!end){ converToRadialIfOneRadial(b, a, true); } } // Function to convert color to array in linear format // and mark if any one of them is radial function allToLinear(arr) { var i = 0, ii = 0, j = 0, item = {}, temp = [], temp2 = {}, key, prevVal = 0, lastVal = 0, counter = 0, rPos = 0, openBrPos = 0, closedBrPos = 0, radial = { f1 : 0.5, f2 : 0.5 }; // Solid color operation if (arr.length === 1) { if(arr[0] === "none"){ arr[0] = "rgba(0,0,0,0)"; } // Push angle zero to start arr.unshift(0); // Mentioning that a default angle was added arr.defaultAngleSet = true; } // Convert angle to number if (isNaN(arr[0])) { // Check if is radial if(~"rx".indexOf(arr[0].charAt(0))){ arr.isRadial = true; rPos = 1; // check if focus if provided // otherwise use default focus if(arr[0].indexOf(')') !== -1){ rPos = arr[0].indexOf(')'); openBrPos = arr[0].indexOf('(') + 1; closedBrPos = rPos; temp = arr[0].substr(openBrPos, closedBrPos - openBrPos).split(','); radial.f1 = parseFloat(temp[0]) || 0; radial.f2 = parseFloat(temp[1]) || 0; if (~temp[2].indexOf('%')) { temp[2] = parseFloat(temp[2]) / 100; } radial.f3 = parseFloat(temp[2]) || 0; radial.f4 = parseFloat(temp[3]) || 0; radial.f5 = parseFloat(temp[4]) || 0; radial.f6 = temp[5]; } arr[0] = arr[0].substr(closedBrPos + 1); arr.unshift(radial); } else { arr[0] = 0; } } else { arr[0] = +arr[0]; } for (i = 1, ii = arr.length; i < ii; ++i) { temp = arr[i].split(":"); // conver first element to rgb object and store temp2 = getRGB(temp[0]); arr[i] = {}; arr[i].r = temp2.r; arr[i].g = temp2.g; arr[i].b = temp2.b; arr[i].opacity = temp2.opacity; // if opacity not present set to 1 arr[i].opacity = +arr[i].opacity; if (isNaN(arr[i].opacity)) { arr[i].opacity = 1; } // set the position arr[i].position = +temp[1]; } // Sorting array according to position // angle and radial focus should be elemnt 0 arr.sort(function(a, b) { if (typeof a === "number" || a.f1) { return -1; } if (typeof b === "number" || a.f2) { return 1; } if (isNaN(a.position) && isNaN(b.position)) { return 0; } if (isNaN(a.position)) { return -1; } if (isNaN(b.position)) { return 1; } return a.position - b.position; }); // If first position is not zero // add new color with position zero if (+arr[1].position !== 0) { if (isNaN(arr[1].position)) { arr[1].position = 0; } else { temp2 = {}; for (key in arr[1]) { temp2[key] = arr[1][key]; } temp2.position = 0; // Shifting array to add current object // in position 1 arr.push({}); for (i = arr.length - 1; i !== 1; --i) { arr[i] = arr[i - 1]; } arr[1] = temp2; } } // index to last position ii = arr.length - 1; // If last position is not 100 // add new color with position 100 if (arr[ii].position !== 100) { if (isNaN(arr[ii].position)) { arr[ii].position = 100; } else { temp2 = {}; for (key in arr[ii]) { temp2[key] = arr[ii][key]; } temp2.position = 100; // Shifting array to add current object // in position 1 arr.push(temp2); } } // Filling correct position value whereever NaN found for (i = 2, ii = arr.length; i < ii; ++i) { if (!(arr[i].position)) { prevVal = arr[i - 1].position; counter = 1; for (j = i + 1; j < ii; ++j) { ++counter; if (!isNaN(arr[j].position)) { lastVal = +arr[j].position; break; } } arr[i].position = prevVal + ((lastVal - prevVal) / counter); } } arr.getColorAtPosition = function(pos) { var prevPos = -1, nextPos = this.length, i = 1, ii = this.length, item = {}, colPrev, colNext, ratio = 0, key = "", col = { r: 0, g: 0, b: 0 }; // Critical section; check again for (; i < ii - 1; ++i) { if (this[i].position <= pos) { prevPos = i; nextPos = i + 1; } if (!(this[i].position < pos) && this[i].position >= pos) { nextPos = i; break; } } ratio = (pos - this[prevPos].position) / (this[nextPos].position - this[prevPos].position); if (isNaN(ratio)) { ratio = 0; } for (key in col) { col[key] = upto255((1 - ratio) * this[prevPos][key] + ratio * this[nextPos][key]); } col.position = pos; col.opacity = (1 - ratio) * this[prevPos]["opacity"] + ratio * this[nextPos]["opacity"]; return col; } return arr; } } /** * Function to make to uncommon path array to a equal length * of path array and same type (L - lineto) to make it animatable * @param {array} path array 1 * @param {array} path array 2 * @return {object} object containing final 'from' and 'to' path */ function pathNormalizer(p1, p2) { 'use strict'; // Function to convert array to svg path (?) only for curves var finalp1 = [], finalp2 = [], pathArr1 = toSvgPath(p1), pathArr2 = toSvgPath(p2), i = 0, ii = 0, temp, createElementNS = document.createElementNS && document.createElementNS.bind(document), dPath = createElementNS && createElementNS("http://www.w3.org/2000/svg", "path"); // If path invalid or svg not supported return if (!pathArr1 || !pathArr2 || !dPath) { return [p1, p2]; } if (canFallback(p1, p2)) { return [p1, p2]; } // If any of the parameters is // absent return to normal flow if (!p1 || !p2) { return [p1, p2]; } // If svg not available return to normal flow if (!document.createElementNS) { return [p1, p2]; } // Setting path again pathArr1 = toSvgPath(p1); pathArr2 = toSvgPath(p2); // If invalid path return the original path if(pathArr1.join().indexOf('undefined') !== -1) { return [p1, p2]; } if(pathArr2.join().indexOf('undefined') !== -1) { return [p1, p2]; } // If svg functions not available return to normal flow if (!dPath.getTotalLength || !dPath.getPointAtLength) { return [p1, p2]; } /* Function to check if the current environment ** can animate the path, as pathNormalizer pauses ** getTotalLength and getPointAtLength function of svg ** which are not supported by all browsers */ function canFallback (path1, path2) { var str1 = '', str2 = '', testLen, testPoint; // Checking path totoalLength is accurate or not // testing with a known path // this check is for Firefox dPath.setAttribute('d', 'M300 10 L300 300 C50 310,50 640,350 650' + 'C600 640,600 310,400 300 L400 10 L295 10'); testLen = dPath.getTotalLength(); testPoint = dPath.getPointAtLength(10); if (testLen < 1829.1 || testLen > 1829.2) { return true; } if (Math.round(testPoint.x) !== 300 || Math.round(testPoint.y) !== 20) { return true; } // path1 and path2 are in array function trimPathArray (arr) { var i = arr.length; while (i-- - 1) { if (arr[i].join('') === arr[i - 1].join('')) { arr.pop(); } else { break; } } } function getPathFromArray(arr) { var str = '', i = 0, ii = arr.length; for (; i < ii; ++i) { str += arr[i].join(' '); } return str; } trimPathArray(path1); trimPathArray(path2); str1 = getPathFromArray(path1); str2 = getPathFromArray(path2); if (str1.split(/[Mm]/).length > 2 || str2.split(/[Mm]/).length > 2) { return false; } if (path1.length === path2.length) { return true; } return false; } /* Convert svg path array to string, Also removes repeated commands */ function toSvgPath(arr) { var str = [], i = 0, ii = arr.length, item = []; if (typeof arr === 'string') { return arr; } // Converting the array to string; path type for (i = 0; i < ii; ++i) { if (!arr[i].join){ return; } else { // Removing continuous Move commands // Picking up the last one if ( !i || !arr[i + 1] || arr[i + 1][0] !== 'M' || arr[i][0] !== 'M'){ str.push(arr[i].join(' ')); } } } str = str.join(''); str = str.split(/[Mm]/).slice(1); for (i = 0, ii = str.length; i < ii; ++i) { str[i] = 'M' + str[i]; } return str; } ii = Math.max(pathArr1.length, pathArr2.length); for (i = 0; i < ii; ++i) { temp = _pathNormalizer(pathArr1[i], pathArr2[i]); pathArr1[i] = temp[0]; pathArr2[i] = temp[1]; } // Convert line path 2 dimensional array to string function linetopath (arr) { var i = 0, ii = 0, str = []; arr = arr || []; ii = arr.length; for (i = 0; i < ii; ++i) { if (arr[i].length - 1) { str.push(arr[i].join(' ')); } } return str.join(''); } /* path2curve appends repeated last path command, this function removes it or any other repeated path command */ function removeBlanks (arr, pos) { var i = arr.length, j = 0, path; while (i-- - 1) { // Pop if length is zero if (arr[i].slice(1).toString() === arr[i - 1].slice(1).toString()) { arr.pop(); } else { break; } } if (arr.length === 1 && pos){ arr.length = 0; } } /* Divide a path array to number to a given number of times as provided in parameters, All path array should start with M command */ function _divide(arr, times) { var resArr = [], locArr = [], arrLen = arr.length, i = 0, ii = 0, x = 0, prevPos = 0, y = 0, // If array size is smaller than // divisions needed diffTimes = times - arrLen; while (diffTimes >= 0) { i = arr.length - 1; arr.push(arr.slice(i)[0]); --diffTimes; } arrLen = arr.length; for (i = 0; i <= times; ++i) { locArr.push(Math.round((i / times) * arrLen)); } for (i = 0, ii = locArr.length - 1; i < ii; ++i) { resArr.push(arr.slice(locArr[i], locArr[i + 1])); if (resArr[i][0][0] !== 'M' && resArr[i][0][0] !== 'm') { prevPos = resArr[i - 1].length - 1; x = resArr[i - 1][prevPos][1]; y = resArr[i - 1][prevPos][2]; resArr[i].unshift(['M', x, y]); } } return resArr; } /* If two path array have different number of MoveTo commands, divide the smaller number of MoveTo command holder to match the other one */ function divideArray (diff) { var arrToDivide = [], countArr = [], transArr = [], i = 0, ii = 0, isArr1 = true; if (diff === 0) { return; } else if (diff > 0) { arrToDivide = pathArr2; isArr1 = false; } else { diff = -diff; arrToDivide = pathArr1; } // Maintaining a count array to judge number of times a1 // path needs to be divided, 1 means dont divide for (i = 0, ii = arrToDivide.length; i < ii; ++i) { countArr.push(1); } while (diff--) { --i; if (i < 0) { i = ii - 1; } countArr[i]++; } for (i = 0; i < ii; ++i){ if (countArr[i] === 1) { transArr.push(arrToDivide[i]); } else { transArr.push.apply(transArr, _divide(arrToDivide[i], countArr[i])); } } if (isArr1) { pathArr1 = transArr; } else { pathArr2 = transArr; } } for (i = pathArr1.length; i--;) { removeBlanks(pathArr1[i], i); // If last element is blank pop it pathArr1[i].length || pathArr1.pop(); } for (i = pathArr2.length; i--;) { removeBlanks(pathArr2[i], i); pathArr2[i].length || pathArr2.pop(); } // Making number off moveto commands equal in both path divideArray(pathArr1.length - pathArr2.length); ii = Math.max(pathArr1.length, pathArr2.length); for (i = 0; i < ii; ++i) { temp = _pathNormalizer(linetopath(pathArr1[i]), linetopath(pathArr2[i])); pathArr1[i] = temp[0]; pathArr2[i] = temp[1]; } for (i = 0, ii = pathArr1.length; i < ii; ++i) { finalp1 = finalp1.concat(pathArr1[i]); } for (i = 0, ii = pathArr2.length; i < ii; ++i) { finalp2 = finalp2.concat(pathArr2[i]); } return [finalp1, finalp2]; } // A function to calculate common path // in two given paths function commonPathCalculator (p1, p2) { 'use strict'; var i = 0, j = 0, ii = 0, jj = 0, k = 0, kk = 0, uncommon1 = 0, uncommon2 = 0, lim1 = 0, lim2 = 0, nearestPoint1, nearestPoint2, map1 = {}, map2 = {}, groupedPath1 = [], groupedPath2 = [], gpIndex1 = -1, gpIndex2 = -1, isSame = true; // Splitting the string commands to get // particular points later // Will be required while breaking paths // into common and uncommon parts function splitter (path) { var i = 0, ii = 0; path = path.split(/[MCLmcl]/).slice(1); for (i = 0, ii = path.length; i < ii; ++i) { path[i] = path[i].split(' ').slice(1); i || path[i].unshift('M'); if (i) { path[i].length === 2 && path[i].unshift('L') || path[i].unshift('C'); } } return path; } // populate the arr to object in reverse manner // i.e value to key mapping function mapper (arr, ob) { var i = 0, ii = arr.length, val, item; for (i = 0, ii = arr.length; i < ii; ++i) { val = arr[i].join(' '); item = arr[i]; if (item[0] === 'C' && item[3] === item[5] && item[4] === item[6]) { arr[i].stringValue = ['L', item[3], item[4]].join(' '); } else item.stringValue = val; // Creating an array if undefined // pushing otherwise ob[item.stringValue] && ob[item.stringValue].push(i); ob[item.stringValue] || (ob[item.stringValue] = [i]); } } // Function to get nearest point that exist // in the other array function getNearestExistingPoint (arr, map, start, ii, lim) { var i = start, k = 0, kk = 0, item; for (; i < ii; ++i) { item = map[arr[i].stringValue]; if (item) { for (k = 0, kk = item.length; k < kk; ++k) { if (item[k] >= lim) { return { index : i, mapValue : item[k], diff : i - start }; } } } } return -1; } // function to get last coordinate for CurveTo command function getCoordinateAsMove (arr) { var last = arr.length - 1; return ['M', arr[last - 1], arr[last]].join(' '); } // function to conver path array to string function pathToString (arr) { return arr.join(''); } // commonPathCalculator flow here p1 = splitter(p1); p2 = splitter(p2); mapper(p1, map1); mapper(p2, map2); // Setting length ii = p1.length; jj = p2.length; i = 0; j = 0; // Making partitions for common // and uncommon parts // Checking if first is common or uncommon while (i < ii && j < jj) { ++gpIndex1; ++gpIndex2; // initializing blank arrays groupedPath1[gpIndex1] = []; groupedPath2[gpIndex2] = []; isSame = (p1[i].stringValue === p2[j].stringValue); if (i) { // Logic to push prev coordinate as move command groupedPath1[gpIndex1].push(getCoordinateAsMove(p1[i - 1])); groupedPath2[gpIndex2].push(getCoordinateAsMove(p2[j - 1])); } if (isSame) { while (i < ii && j < jj && p1[i].stringValue === p2[j].stringValue) { groupedPath1[gpIndex1].push(p1[i].stringValue); groupedPath2[gpIndex2].push(p2[j].stringValue); ++i; ++j; } } else { nearestPoint1 = getNearestExistingPoint(p1, map2, i, ii, j); nearestPoint2 = getNearestExistingPoint(p2, map1, j, jj, i); // Assuming nearestPoint1 is nearer than nearestPoint2 lim1 = nearestPoint1.index; lim2 = nearestPoint1.mapValue; // If nearestPoint2 is nearer if (!~nearestPoint1 || nearestPoint1.diff > nearestPoint2.diff) { lim1 = nearestPoint2.mapValue; lim2 = nearestPoint2.index; } if (!~nearestPoint1 && !~nearestPoint2) { // If both not found include all as uncommon lim1 = ii - 1; lim2 = jj - 1; } // Pushing uncommon paths while (i <= lim1) { groupedPath1[gpIndex1].push(p1[i].stringValue); ++i; } while (j <= lim2) { groupedPath2[gpIndex2].push(p2[j].stringValue); ++j; } } groupedPath1[gpIndex1] = pathToString(groupedPath1[gpIndex1]); groupedPath2[gpIndex2] = pathToString(groupedPath2[gpIndex2]); } // If Any one is left add them all if (i < ii) { ++gpIndex1; groupedPath1[gpIndex1] = []; groupedPath1[gpIndex1].push(getCoordinateAsMove(p1[i - 1])); ++gpIndex2; groupedPath2[gpIndex2] = []; groupedPath2[gpIndex2].push(getCoordinateAsMove(p2[j - 1])); while(i < ii) { groupedPath1[gpIndex1].push(p1[i].stringValue); ++i; } groupedPath1[gpIndex1] = pathToString(groupedPath1[gpIndex1]); } if (j < jj) { ++gpIndex1; groupedPath1[gpIndex1] = []; groupedPath1[gpIndex1].push(getCoordinateAsMove(p1[i - 1])); ++gpIndex2; groupedPath2[gpIndex2] = []; groupedPath2[gpIndex2].push(getCoordinateAsMove(p2[j - 1])); while(j < jj) { groupedPath2[gpIndex2].push(p2[j].stringValue); ++j; } groupedPath2[gpIndex2] = pathToString(groupedPath2[gpIndex2]); } return [groupedPath1, groupedPath2]; } // function to get equal points for two different path // We set path to an dynamically created svg path node // and get equal number of path commands from two different // paths. Uses getPointAtLength and getTotalLength of svg that // arent supported on every browser function _pathNormalizer(p1, p2) { 'use strict'; var i = 0, j = 0, ii = 0, jj = 0, item = {}, fPath1 = [], fPath2 = [], divisions = 0, commonPath, tmp; // Uncommon path normalizer function normalizeUncommonPaths (p1, p2) { var dPath1, dPath2, i = 0, j = 0, item = {}, pathLen1 = 0, pathLen2 = 0, fPath1 = [], fPath2 = [], divisions = 0, round = Math.round; // Creating path elements to use functions 'getTotalLength' // and 'getPointAtLength' dPath1 = document.createElementNS("http://www.w3.org/2000/svg", "path"); dPath1.setAttribute("d", p1); dPath2 = document.createElementNS("http://www.w3.org/2000/svg", "path"); dPath2.setAttribute("d", p2); // Getting length of the paths pathLen1 = dPath1.getTotalLength(); pathLen2 = dPath2.getTotalLength(); // Number of divisions will depend on larger path divisions = 0.15 * Math.max(pathLen1, pathLen2); divisions = Math.ceil(divisions); if (!divisions || !isFinite(divisions) || divisions < 10) { divisions = 10; } for (i = 0; i <= divisions; ++i) { item = dPath1.getPointAtLength((i / divisions) * pathLen1); fPath1.push([i ? "L" : "M", round(item.x), round(item.y) ]); item = dPath2.getPointAtLength((i / divisions) * pathLen2); fPath2.push([i ? "L" : "M", round(item.x), round(item.y) ]); } return [fPath1, fPath2]; } if (!p1 || p1 === 'M ') { p1 = p2.split(' ').slice(0, 3).join(' ').replace(/[LC]/, ''); } if (!p2 || p2 === 'M ') { p2 = p1.split(' ').slice(0, 3).join(' ').replace(/[LC]/, ''); } commonPath = commonPathCalculator(p1, p2); for (i = 0, ii = commonPath[0].length; i < ii; ++i) { tmp = normalizeUncommonPaths(commonPath[0][i], commonPath[1][i]); if (i) { fPath1 = fPath1.concat(tmp[0].slice(1)); fPath2 = fPath2.concat(tmp[1].slice(1)); } else { fPath1 = fPath1.concat(tmp[0]); fPath2 = fPath2.concat(tmp[1]); } } return [fPath1, fPath2]; } function runAnimation(anim, element, percent, status, totalOrigin, times, parentEl, configObject) { percent = toFloat(percent); var params, isInAnim, isInAnimSet, percents = [], next, prev, temp, timestamp, tempDiff, change, ms = anim.ms, from = {}, to = {}, diff = {}; if (element.type === null) { return; } configObject = configObject || {}; configObject.hookFn && configObject.hookFn.call(element); configObject.from = configObject.from || {}; if (status) { for (i = 0, ii = animationElements.length; i < ii; i++) { var e = animationElements[i]; if (e.el.id == element.id && e.anim == anim) { if (e.percent != percent) { delete e.el.e; delete e.el; animationElements.splice(i, 1); isInAnimSet = 1; } else { isInAnim = e; } element.attr(e.totalOrigin); break; } } } else { status = +to; // NaN } for (var i = 0, ii = anim.percents.length; i < ii; i++) { if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) { percent = anim.percents[i]; prev = anim.percents[i - 1] || 0; ms = ms / anim.top * (percent - prev); next = anim.percents[i + 1]; params = anim.anim[percent]; break; } else if (status) { element.attr(anim.anim[anim.percents[i]]); } } if (!params) { return; } if (!isInAnim) { for (var attr in params) if (params[has](attr)) { if (availableAnimAttrs[has](attr) || element.ca[attr]) { from[attr] = configObject.from[attr] || element.attr(attr); (from[attr] == null) && (from[attr] = availableAttrs[attr]); to[attr] = params[attr]; change = false; switch (availableAnimAttrs[attr]) { case nu: tempDiff = to[attr] - from[attr]; (tempDiff || isNaN(tempDiff)) && (change = true); diff[attr] = tempDiff / ms; break; case "colour": if(from[attr] === to[attr]){ break; } else { change = true; } var colorsNormalized = colorNormalizer(from[attr], to[attr], R.getRGB); from[attr] = colorsNormalized[0]; var toColour = colorsNormalized[1]; if (typeof toColour === "string") { if(from[attr].toLowerCase() !== "none"){ from[attr] = R.getRGB(from[attr]); if(!from[attr].opacity){ from[attr].opacity = 1; } } else { from[attr] = { r : 0, g : 0, b : 0, opacity : 0 } } if(to[attr].toLowerCase() !== "none"){ toColour = R.getRGB(to[attr]); if(!toColour.opacity){ toColour.opacity = 1; } } else { toColour = { r : 0, g : 0, b : 0, opacity : 0 } } diff[attr] = { r: (toColour.r - from[attr].r) / ms, g: (toColour.g - from[attr].g) / ms, b: (toColour.b - from[attr].b) / ms, opacity: ((toColour.opacity - from[attr].opacity) / ms) }; } else { diff[attr] = []; for (i = 0, ii = from[attr].length; i < ii; ++i) { if (i === 0) { diff[attr].push(toColour[0]); } else { diff[attr].push({ r: (toColour[i].r - from[attr][i].r) / ms, g: (toColour[i].g - from[attr][i].g) / ms, b: (toColour[i].b - from[attr][i].b) / ms, opacity: (toColour[i].opacity - from[attr][i].opacity) / ms }); } } } break; case "path": var toPath, pathes = path2curve(from[attr], to[attr]); if (configObject.smartMorph) { pathes = pathNormalizer(pathes[0], pathes[1], configObject); } toPath = pathes[1]; from[attr] = pathes[0]; diff[attr] = []; for (i = 0, ii = from[attr].length; i < ii; i++) { diff[attr][i] = [0]; var jj; jj = from[attr][i] ? from[attr][i].length : 0; for (var j = 1; j < jj; j++) { diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms; (!change) && diff[attr][i][j] && (change = true); } } break; case "transform": var _ = element._, eq = equaliseTransform(_[attr], to[attr]); change = true; if (eq) { from[attr] = eq.from; to[attr] = eq.to; diff[attr] = []; diff[attr].real = true; for (i = 0, ii = from[attr].length; i < ii; i++) { diff[attr][i] = [from[attr][i][0]]; for (j = 1, jj = from[attr][i].length; j < jj; j++) { diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms; } } } else { var m = (element.matrix || new Matrix), to2 = { _: { transform: _.transform }, getBBox: function() { return element.getBBox(1); } }; from[attr] = [ m.a, m.b, m.c, m.d, m.e, m.f ]; extractTransform(to2, to[attr]); to[attr] = to2._.transform; diff[attr] = [ (to2.matrix.a - m.a) / ms, (to2.matrix.b - m.b) / ms, (to2.matrix.c - m.c) / ms, (to2.matrix.d - m.d) / ms, (to2.matrix.e - m.e) / ms, (to2.matrix.f - m.f) / ms ]; // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy]; // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }}; // extractTransform(to2, to[attr]); // diff[attr] = [ // (to2._.sx - _.sx) / ms, // (to2._.sy - _.sy) / ms, // (to2._.deg - _.deg) / ms, // (to2._.dx - _.dx) / ms, // (to2._.dy - _.dy) / ms // ]; } break; case "csv": var values = Str(params[attr])[split](separator), from2 = Str(from[attr])[split](separator); if (attr == "clip-rect") { from[attr] = from2; diff[attr] = []; i = from2.length; while (i--) { tempDiff = values[i] - from[attr][i]; (tempDiff || isNaN(tempDiff)) && (change = true); diff[attr][i] = tempDiff / ms; } } to[attr] = values; break; default: values = [][concat](params[attr]); from2 = [][concat](from[attr]); diff[attr] = []; i = element.ca[attr].length; while (i--) { tempDiff = (values[i] || 0) - (from2[i] || 0); (tempDiff || isNaN(tempDiff)) && (change = true); diff[attr][i] = tempDiff / ms; } break; } if (!change) { delete from[attr]; delete to[attr]; delete params[attr]; delete diff[attr]; } } else if (R._availableAttrs[has](attr) || attr === 'text' || element.ca[attr]) { element.attr(attr, params[attr]); delete params[attr]; } } var easing = params.easing, easyeasy = R.easing_formulas[easing]; if (!easyeasy) { easyeasy = Str(easing).match(bezierrg); if (easyeasy && easyeasy.length == 5) { var curve = easyeasy; easyeasy = function(t) { return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms); }; } else { easyeasy = pipe; } } timestamp = params.start || anim.start || +new Date; element.e = e = { anim: anim, percent: percent, timestamp: timestamp, start: timestamp + (anim.del || 0), status: 0, initstatus: status || 0, stop: false, ms: ms, easing: easyeasy, from: from, diff: diff, to: to, el: element, callback: params.callback, prev: prev, next: next, repeat: times || anim.times, origin: element.attr(), totalOrigin: totalOrigin, parentEl : parentEl, delayend: configObject && configObject.end, delaystart: configObject && configObject.start }; animationElements.push(e); if (status && !isInAnim && !isInAnimSet) { e.stop = true; e.start = new Date - ms * status; if (animationElements.length == 1) { return animation(); } } if (isInAnimSet) { e.start = new Date - e.ms * status; } animationElements.length == 1 && (requestAnimFrame || R.getAnimFrameFn())(animation); } else { isInAnim.initstatus = status; isInAnim.start = new Date - isInAnim.ms * status; } eve("raphael.anim.start." + element.id, element, anim); } /*\ * Raphael.animation [ method ] ** * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods. * See also @Animation.delay and @Animation.repeat methods. ** > Parameters ** - params (object) final attributes for the element, see also @Element.attr - ms (number) number of milliseconds for animation to run - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)` - callback (function) #optional callback function. Will be called at the end of animation. ** = (object) @Animation \*/ R.animation = function(params, ms, easing, callback, stopPartialEventPropagation) { if (params instanceof Animation) { return params; } if (R.is(easing, "function") || !easing) { callback = callback || easing || null; easing = null; } !R.stopPartialEventPropagation && (R.stopPartialEventPropagation = stopPartialEventPropagation); params = Object(params); ms = +ms || 0; var p = {}, json, attr; for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) { json = true; p[attr] = params[attr]; } // Enabling the callback to be called even if attr is not provided callback && (json = true); if (!json) { return new Animation(params, ms); } else { easing && (p.easing = easing); callback && (p.callback = callback); return new Animation({ 100: p }, ms); } }; /*\ * Element.animate [ method ] ** * Creates and starts animation for given element. ** > Parameters ** - params (object) final attributes for the element, see also @Element.attr - ms (number) number of milliseconds for animation to run - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)` - callback (function) #optional callback function. Will be called at the end of animation. * or - animation (object) animation object, see @Raphael.animation ** = (object) original element \*/ elproto.animate = function(params, ms, easing, callback) { var element = this; if (element.removed) { callback && callback.call(element); return element; } var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback); runAnimation(anim, element, anim.percents[0], null, element.attr()); return element; }; /*\ * Element.status [ method ] ** * Gets or sets the status of animation of the element. ** > Parameters ** - anim (object) #optional animation object - value (number) #optional 0 – 1. If specified, method works like a setter and sets the status of a given animation to the value. This will cause animation to jump to the given position. ** = (number) status * or = (array) status if `anim` is not specified. Array of objects in format: o { o anim: (object) animation object o status: (number) status o } * or = (object) original element if `value` is specified \*/ elproto.status = function(anim, value) { var out = [], i = 0, len, e; if (value != null) { runAnimation(anim, this, -1, mmin(value, 1)); return this; } else { len = animationElements.length; for (; i < len; i++) { e = animationElements[i]; if (e.el.id == this.id && (!anim || e.anim == anim)) { if (anim) { return e.status; } out.push({ anim: e.anim, status: e.status }); } } if (anim) { return 0; } return out; } }; /*\ * Element.pause [ method ] ** * Stops animation of the element with ability to resume it later on. ** > Parameters ** - anim (object) #optional animation object - resumeChildAnimation (boolean) #pauses the animation of the elements which are in sync with the current element ** = (object) original element \*/ elproto.pause = function(anim, pauseChildAnimation) { var now = +new Date, e, i; for (i = 0; i < animationElements.length; i++) { e = animationElements[i]; // @todo - need a scope to implement the logic for nested animations. if ((e.el.id === this.id || (pauseChildAnimation && e.parentEl && e.parentEl.e.el && e.parentEl.e.el.id === this.id)) && (!anim || e.anim == anim)) { if (eve("raphael.anim.pause." + this.id, this, e.anim) !== false) { e.paused = true; e.pauseStart = now; } } } return this; }; /*\ * Element.resume [ method ] ** * Resumes animation if it was paused with @Element.pause method. ** > Parameters ** - anim (object) #optional animation object - resumeChildAnimation (boolean) #resumes the animation of the elements which are in sync with the current element ** = (object) original element \*/ elproto.resume = function(anim, resumeChildAnimation) { var now = +new Date, e, i; for (i = 0; i < animationElements.length; i++) { e = animationElements[i]; // @todo - need a scope to implement the logic for nested animations. if ((e.el.id === this.id || (resumeChildAnimation && e.parentEl && e.parentEl.e.el && e.parentEl.e.el.id === this.id)) && (!anim || e.anim == anim)) { if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) { delete e.paused; e.el.status(e.anim, e.status); e.pauseEnd = now; e.start += (((e.parentEl && e.parentEl.e.pauseEnd || e.pauseEnd) - (e.parentEl && e.parentEl.e.pauseStart || e.pauseStart)) || 0); } } } return this; }; /*\ * Element.stop [ method ] ** * Stops animation of the element. ** > Parameters ** - anim (object) #optional animation object - stopChildAnimation (boolean) #optional stops the animation of all the element which are in sync with the current element - jumpToEnd (boolean) #optional takes the current animation to its end value ** = (object) original element \*/ elproto.stop = function(anim, stopChildAnimation, jumpToEnd) { var e, i, ele; if (stopChildAnimation) { for (i = animationElements.length - 1; i >= 0; i--) { e = animationElements[i]; // @todo - need a scope to implement the logic for nested animations. if ((e.el.id === this.id || (e.parentEl && e.parentEl.id === this.id)) && (!anim || animationElements[i].anim == anim)) { ele = e.el; jumpToEnd && ele.attr(e.to); e.callback && e.callback.call(ele); delete ele.e; delete e.el; animationElements.splice(i, 1); } } } else { for (var i = 0; i < animationElements.length; i++){ e = animationElements[i]; if (e.el.id === this.id && (!anim || e.anim === anim)) { if (eve("raphael.anim.stop." + this.id, this, e.anim) !== false) { animationElements.splice(i--, 1); } } } } // In case root object has hooked animation elements // in priority queue execute them all if (this.animElements) { executeAnimQueue(this.animElements); } return this; }; function executeAnimQueue (queue) { var ob; // Looping until all executed while (ob = queue.deq()) { ob = ob.executeOb; ob.hookFn && ob.hookFn.call(ob.el); ob.el.attr(ob.attrs); ob.callback && ob.callback.call(ob.el); } } function stopAnimation(paper) { for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.paper == paper) { animationElements.splice(i--, 1); } } eve.on("raphael.remove", stopAnimation); eve.on("raphael.clear", stopAnimation); elproto.toString = function() { return "Rapha\xebl\u2019s object"; }; elproto.toFront = function() { if (this.removed) { return this; } var o = this, thisNode = R._engine.getNode(o), parent = o.parent, followers = o.followers, follower, i, ii; if (R._tofront(o, parent)) { parent.canvas.appendChild(thisNode); } for (i = 0, ii = followers.length; i < ii; i++) { (follower = followers[i]).stalk && follower.el[follower.stalk](o); } return o; }; elproto.toBack = function() { if (this.removed) { return this; } var o = this, thisNode = R._engine.getNode(o), parent = o.parent, followers = o.followers, follower, i, ii; if (R._toback(o, parent)) { parent.canvas.insertBefore(thisNode, parent.canvas.firstChild); } for (i = 0, ii = followers.length; i < ii; i++) { (follower = followers[i]).stalk && follower.el[follower.stalk](o); } return o; }; elproto.insertAfter = function(element) { if (this.removed) { return this; } var o = this, thisNode = R._engine.getNode(o), thatNode = R._engine.getLastNode(element), parentNode = element.parent.canvas, followers = o.followers, follower, i, ii; if (thatNode.nextSibling) { parentNode.insertBefore(thisNode, thatNode.nextSibling); } else { parentNode.appendChild(thisNode); } R._insertafter(o, element, o.parent, element.parent); for (i = 0, ii = followers.length; i < ii; i++) { (follower = followers[i]).stalk && follower.el[follower.stalk](element); } return o; }; elproto.insertBefore = function(element) { if (this.removed) { return this; } var o = this, thisNode = R._engine.getNode(o), thatNode = R._engine.getNode(element), followers = o.followers, follower, i, ii; element.parent.canvas.insertBefore(thisNode, thatNode); R._insertbefore(o, element, o.parent, element.parent); o.parent = element.parent; for (i = 0, ii = followers.length; i < ii; i++) { (follower = followers[i]).stalk && follower.el[follower.stalk](element); } return this; }; elproto.appendChild = function (element) { if (this.removed || this.type !== 'group') { return this; } var group = this, followers = group.followers, follower, thatNode, i, ii; // If appending in same group, simply perform toFront(). if (element.parent === group) { element.toFront(); return group; } thatNode = R._engine.getNode(element); // first remove from own group R._tear(element, element.parent); group.canvas.appendChild(thatNode); element.parent = group; !group.bottom && (group.bottom = element); element.prev = group.top; element.next = null; group.top && (group.top.next = element); group.top = element; for (i = 0, ii = followers.length; i < ii; i++) { (follower = followers[i]).stalk && follower.el[follower.stalk](element); } return group; }; // Reverse application of appendChild elproto.appendTo = function (group) { return group.appendChild(this); } elproto.removeChild = function (element) { if (this.removed || this.type !== 'group' || element.parent !== this) { return this; } var o = this, thatNode = R._engine.getNode(element), paper = o.paper; R._tear(element, o); paper.canvas.appendChild(thatNode); o.parent = paper; !paper.bottom && (paper.bottom = o); o.prev = paper.top; paper.top && (paper.top.next = o); paper.top = o; o.next = null; return o; }; /*\ * Raphael.format [ method ] ** * Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument. ** > Parameters ** - token (string) string to format - … (string) rest of arguments will be treated as parameters for replacement = (string) formated string > Usage | var x = 10, | y = 20, | width = 40, | height = 50; | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z" | paper.path(Raphael.format("M{0},{1}h{2}v{3}h{4}z", x, y, width, height, -width)); \*/ R.format = function(token, params) { var arg = getArrayCopy(arguments), args = R.is(params, array) ? [0][concat](params) : arg; token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function(str, i) { return args[++i] == null ? E : args[i]; })); return token || E; }; var crispFixer = (R.vml && 0.5 || 0); R.crispBound = cacher(function (x, y, w, h, s) { var at = {}, normalizer; x = x || 0; y = y || 0; w = w || 0; h = h || 0; s = s || 0; normalizer = s % 2 / 2 + crispFixer; // normalize for crisp edges at.x = round(x + normalizer) - normalizer; at.y = round(y + normalizer) - normalizer; at.width = round(x + w + normalizer) - normalizer - at.x; at.height = round(y + h + normalizer) - normalizer - at.y; at['stroke-width'] = s; // adjust to single pixel if resultant dimension is zero. (at.width === 0 && w !== 0) && (at.width = 1); (at.height === 0 && h !== 0) && (at.height = 1); return at; }, R); /*\ * Raphael.define [ method ] ** * Allows a unified definition of composite shapes and other behaviours using * simple directives. ** > Parameters ** - definition (object) the shape definition \*/ R.define = function (name, init, ca, fn, e, data) { var i, ii; // multi definition if (R.is(name, array)) { for (i = 0, ii = name.length; i < ii; i++) { R.define(name[i]); } return; } // object definition else if (R.is(name, object)) { R.define(name.name, name[name.name], name.ca, name.fn, name.e, name.data); return; } // invalid or duplicate definition else if (!name || R.fn[name]) { return; } R.fn[name] = function () { var args = getArrayCopy(arguments), element = init.apply(this, args), key; if (fn && R.is(fn, object)) { for (key in fn) { element[key] = fn[key]; } } if (e && R.is(e, object)) { for (key in e) { element[key] && element[key](e[key]); } } if (ca) { if (R.is(ca, 'function')) { element.ca[name] = ca; } else { for (key in ca) { element.ca[key] = ca[key]; } } // Check if namesake ca exists and apply it if (element.ca[name]) { R._lastArgIfGroup(args, true); // purge group if (args.length) { // If name attribute is present then the received argument is an object with the customAttribute and other // common attributes. Else it is just the customAttributes that is to be applied. args[0][name] ? element.attr.apply(element, args): element.attr(name, args[0]); } } } return element; }; if (ca) { R.fn[name].ca = ca; } if (fn) { R.fn[name].fn = fn; } if (e) { R.fn[name].e = e; } if (data) { R.fn[name].data = data; } return R.fn[name]; }; // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html (function(doc, loaded, f) { if (doc.readyState == null && doc.addEventListener) { doc.addEventListener(loaded, f = function() { doc.removeEventListener(loaded, f, false); doc.readyState = "complete"; }, false); doc.readyState = "loading"; } function isLoaded() { (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("raphael.DOMload"); } isLoaded(); })(doc, "DOMContentLoaded"); eve.on("raphael.DOMload", function() { loaded = true; }); // EXPOSE // SVG and VML are appended just before the EXPOSE line // Even with AMD, Raphael should be defined globally // oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R); export default R;
RED-7444: removed R.setWindow
source/raphael.core.js
RED-7444: removed R.setWindow
<ide><path>ource/raphael.core.js <ide> \*/ <ide> R.deg = function (rad) { <ide> return rad * rad2deg % 360; <del> }; <del> <del> /*\ <del> * Raphael.setWindow <del> [ method ] <del> ** <del> * Used when you need to draw in `&lt;iframe>`. Switched window to the iframe one. <del> > Parameters <del> - newwin (window) new window object <del> \*/ <del> R.setWindow = function (newwin) { <del> eve("raphael.setWindow", R, g.win, newwin); <del> win = g.win = newwin; <del> doc = g.doc = g.win.document; <del> if (R._engine.initWin) { <del> R._engine.initWin(g.win); <del> } <ide> }; <ide> <ide> var toHex = function (color) {
Java
apache-2.0
efe4f5820b8450e62961f6aa4f06a9a0cbcc60cf
0
Sanne/jboss-modules,doctau/jboss-modules,ctomc/jboss-modules,jboss-modules/jboss-modules,jasinner/jboss-modules,rogerchina/jboss-modules,Kast0rTr0y/jboss-modules,ropalka/jboss-modules
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.modules; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.net.URL; import java.security.AccessController; import java.security.SecureClassLoader; import java.util.ArrayDeque; import java.util.Collections; import java.util.Enumeration; import java.util.Queue; import sun.misc.Unsafe; /** * A classloader which can delegate to multiple other classloaders without risk of deadlock. A concurrent class loader * should only ever be delegated to by another concurrent class loader; however a concurrent class loader <i>may</i> * delegate to a standard hierarchical class loader. In other words, holding a lock on another class loader while invoking * a method on this class loader may cause an unexpected deadlock. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public abstract class ConcurrentClassLoader extends SecureClassLoader { private static final boolean LOCKLESS; static { LOCKLESS = Boolean.parseBoolean(AccessController.doPrivileged(new PropertyReadAction("jboss.modules.lockless"))); } /** * An empty enumeration, for subclasses to use if desired. */ protected static final Enumeration<URL> EMPTY_ENUMERATION = Collections.enumeration(Collections.<URL>emptySet()); /** {@inheritDoc} */ @Override public final Class<?> loadClass(final String className) throws ClassNotFoundException { return performLoadClass(className, false, false); } /** * Loads the class with the specified binary name. */ @Override public final Class<?> loadClass(final String className, boolean resolve) throws ClassNotFoundException { return performLoadClass(className, false, resolve); } /** * Same as {@link #loadClass(String)}, except only exported classes will be considered. * * @param className the class name * @return the class * @throws ClassNotFoundException if the class isn't found */ public final Class<?> loadExportedClass(final String className) throws ClassNotFoundException { return performLoadClass(className, true, false); } /** * Same as {@link #loadClass(String,boolean)}, except only exported classes will be considered. * * @param className the class name * @param resolve {@code true} to resolve the class after loading * @return the class * @throws ClassNotFoundException if the class isn't found */ public final Class<?> loadExportedClass(final String className, boolean resolve) throws ClassNotFoundException { return performLoadClass(className, true, resolve); } /** * Find a class, possibly delegating to other loader(s). This method should <b>never</b> synchronize across a * delegation method call of any sort. The default implementation always throws {@code ClassNotFoundException}. * * @param className the class name * @param exportsOnly {@code true} if only exported classes should be considered * @param resolve {@code true} to resolve the loaded class * @return the class * @throws ClassNotFoundException if the class is not found */ protected Class<?> findClass(final String className, final boolean exportsOnly, final boolean resolve) throws ClassNotFoundException { throw new ClassNotFoundException(className); } /** * Implementation of {@link ClassLoader#findClass(String)}. * * @param className the class name * @return the result of {@code findClass(className, false, false)} */ protected final Class<?> findClass(final String className) throws ClassNotFoundException { return findClass(className, false, false); } /** * Finds the resource with the given name. The name of a resource is a {@code '/'}-separated path name that * identifies the resource. If the resource name starts with {@code "java/"} then the parent class loader is used. * Otherwise, this method delegates to {@link #findResource(String, boolean)}. * * @param name the name of the resource * @return the resource URL, or {@code null} if no such resource exists or the invoker does not have adequate * permission to access it */ public final URL getResource(final String name) { for (String s : Module.systemPaths) { if (name.startsWith(s)) { return super.getResource(name); } } return findResource(name, false); } /** * Finds all available resources with the given name. * * @see #getResource(String) * * @param name the resource name * @return an enumeration over all the resource URLs; if no resources could be found, the enumeration will be empty * @throws IOException if an I/O error occurs */ public final Enumeration<URL> getResources(final String name) throws IOException { for (String s : Module.systemPaths) { if (name.startsWith(s)) { return super.getResources(name); } } return findResources(name, false); } /** * Find the resource with the given name and exported status. * * @see #getResource(String) * * @param name the resource name * @param exportsOnly {@code true} to consider only exported resources or {@code false} to consider all resources * @return the resource URL */ protected URL findResource(final String name, final boolean exportsOnly) { return null; } /** * Never used. {@link ClassLoader#getResource(String)} and related methods can cause a loop condition * when this method is implemented; use {@link #findResource(String, boolean)} instead. * * @param name ignored * @return {@code null} always */ protected final URL findResource(final String name) { // Always return null so that we don't go into a loop from super.getResource*(). return null; } /** * Finds the resources with the given name and exported status. * * @see #getResources(String) * * @param name the resource name * @param exportsOnly {@code true} to consider only exported resources or {@code false} to consider all resources * @return the resource enumeration * @throws IOException if an I/O error occurs */ protected Enumeration<URL> findResources(final String name, final boolean exportsOnly) throws IOException { return EMPTY_ENUMERATION; } /** * Never used. {@link ClassLoader#getResources(String)} and related methods can cause a loop condition * when this method is implemented; use {@link #findResources(String, boolean)} instead. By default, returns * an empty enumeration. * * @param name ignored * @return an empty enumeration */ protected final Enumeration<URL> findResources(final String name) { return EMPTY_ENUMERATION; } /** * Finds the resource with the given name and exported status, returning the resource content as a stream. * * @param name the resource name * @param exportsOnly {@code true} to consider only exported resources or {@code false} to consider all resources * @return the resource stream, or {@code null} if the resource is not found */ protected InputStream findResourceAsStream(final String name, final boolean exportsOnly) { final URL url = findResource(name, exportsOnly); try { return url == null ? null : url.openStream(); } catch (IOException e) { return null; } } /** * Returns an input stream for reading the specified resource. If the resource starts with {@code "java/"}, then * this method delegates to the parent class loader. Otherwise, this method delegates to {@link #findResourceAsStream(String, boolean)}. * * @param name the resource name * @return the resource stream, or {@code null} if the resource is not found */ public final InputStream getResourceAsStream(final String name) { for (String s : Module.systemPaths) { if (name.startsWith(s)) { return super.getResourceAsStream(name); } } return findResourceAsStream(name, false); } // Private members /** * Perform a class load operation. If the class is in the package or a subpackage of a package in the system packages list, * the parent class loader is used to load the class. Otherwise, this method checks to see if the class loader * object is locked; if so, it unlocks it and submits the request to the class loader thread. Otherwise, it will * load the class itself by delegating to {@link #findClass(String, boolean, boolean)}. * * @param className the class name * @param exportsOnly {@code true} to consider only exported resources or {@code false} to consider all resources * @param resolve {@code true} to resolve the loaded class * @return the class returned by {@link #findClass(String, boolean, boolean)} * @throws ClassNotFoundException if {@link #findClass(String, boolean, boolean)} throws this exception */ private Class<?> performLoadClass(String className, boolean exportsOnly, final boolean resolve) throws ClassNotFoundException { if (className == null) { throw new IllegalArgumentException("name is null"); } for (String s : Module.systemPackages) { if (className.startsWith(s)) { // always delegate to system return findSystemClass(className); } } return performLoadClassChecked(className, exportsOnly, resolve); } /** * Perform a class load operation. This method checks to see if the class loader object is locked; if so, it * unlocks it and submits the request to the class loader thread. Otherwise, it will load the class itself by * delegating to {@link #findClass(String, boolean, boolean)}. * <p> * If the {@code jboss.modules.unsafe-locks} system property is set to {@code true}, then rather than using the * class loading thread, the lock is forcibly broken and the load retried. * * @param className the class name * @param exportsOnly {@code true} to consider only exported resources or {@code false} to consider all resources * @param resolve {@code true} to resolve the loaded class * @return the class returned by {@link #findClass(String, boolean, boolean)} * @throws ClassNotFoundException if {@link #findClass(String, boolean, boolean)} throws this exception */ private Class<?> performLoadClassChecked(final String className, final boolean exportsOnly, final boolean resolve) throws ClassNotFoundException { if (Thread.holdsLock(this)) { if (LOCKLESS) { final Unsafe unsafe = UnsafeHolder.UNSAFE; unsafe.monitorExit(this); try { return performLoadClassChecked(className, exportsOnly, resolve); } finally { unsafe.monitorEnter(this); } } if (Thread.currentThread() != LoaderThreadHolder.LOADER_THREAD) { // Only the classloader thread may take this lock; use a condition to relinquish it final LoadRequest req = new LoadRequest(className, resolve, exportsOnly, this); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; synchronized (queue) { queue.add(req); queue.notify(); } boolean intr = false; try { while (!req.done) try { wait(); } catch (InterruptedException e) { intr = true; } } finally { if (intr) Thread.currentThread().interrupt(); } return req.result; } } // no deadlock risk! Either the lock isn't held, or we're inside the class loader thread. return findClass(className, exportsOnly, resolve); } static final class LoaderThreadHolder { static final Thread LOADER_THREAD; static final Queue<LoadRequest> REQUEST_QUEUE = new ArrayDeque<LoadRequest>(); static { Thread thr = new LoaderThread(); thr.setName("ClassLoader Thread"); // This thread will always run as long as the VM is alive. thr.setDaemon(true); thr.start(); LOADER_THREAD = thr; } private LoaderThreadHolder() { } } static class LoadRequest { private final String className; private final boolean resolve; private final ConcurrentClassLoader requester; Class<?> result; private boolean exportsOnly; boolean done; LoadRequest(final String className, final boolean resolve, final boolean exportsOnly, final ConcurrentClassLoader requester) { this.className = className; this.resolve = resolve; this.exportsOnly = exportsOnly; this.requester = requester; } } static class LoaderThread extends Thread { @Override public void interrupt() { // no interruption } @Override public void run() { /* This resolves a know deadlock that can occur if one thread is in the process of defining a package as part of defining a class, and another thread is defining the system package that can result in loading a class. One holds the Package.pkgs lock and one holds the Classloader lock. */ Package.getPackages(); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; for (; ;) { try { LoadRequest request; synchronized (queue) { while ((request = queue.poll()) == null) { queue.wait(); } } final ConcurrentClassLoader loader = request.requester; Class<?> result = null; synchronized (loader) { try { result = loader.performLoadClassChecked(request.className, request.exportsOnly, request.resolve); } finally { // no matter what, the requester MUST be notified request.result = result; request.done = true; loader.notifyAll(); } } } catch (Throwable t) { // ignore } } } } private static final class UnsafeHolder { static Unsafe UNSAFE; static { try { final Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); UNSAFE = (Unsafe) field.get(null); } catch (IllegalAccessException e) { throw new IllegalAccessError(e.getMessage()); } catch (NoSuchFieldException e) { throw new NoSuchFieldError(e.getMessage()); } } private UnsafeHolder() { } } }
src/main/java/org/jboss/modules/ConcurrentClassLoader.java
/* * JBoss, Home of Professional Open Source. * Copyright 2010, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.modules; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.net.URL; import java.security.AccessController; import java.security.SecureClassLoader; import java.util.ArrayDeque; import java.util.Collections; import java.util.Enumeration; import java.util.Queue; import sun.misc.Unsafe; /** * A classloader which can delegate to multiple other classloaders without risk of deadlock. A concurrent class loader * should only ever be delegated to by another concurrent class loader; however a concurrent class loader <i>may</i> * delegate to a standard hierarchical class loader. In other words, holding a lock on another class loader while invoking * a method on this class loader may cause an unexpected deadlock. * * @author <a href="mailto:[email protected]">David M. Lloyd</a> */ public abstract class ConcurrentClassLoader extends SecureClassLoader { private static final boolean UNSAFE_LOCKS; static { UNSAFE_LOCKS = Boolean.parseBoolean(AccessController.doPrivileged(new PropertyReadAction("jboss.modules.unsafe-locks"))); } /** * An empty enumeration, for subclasses to use if desired. */ protected static final Enumeration<URL> EMPTY_ENUMERATION = Collections.enumeration(Collections.<URL>emptySet()); /** {@inheritDoc} */ @Override public final Class<?> loadClass(final String className) throws ClassNotFoundException { return performLoadClass(className, false, false); } /** * Loads the class with the specified binary name. */ @Override public final Class<?> loadClass(final String className, boolean resolve) throws ClassNotFoundException { return performLoadClass(className, false, resolve); } /** * Same as {@link #loadClass(String)}, except only exported classes will be considered. * * @param className the class name * @return the class * @throws ClassNotFoundException if the class isn't found */ public final Class<?> loadExportedClass(final String className) throws ClassNotFoundException { return performLoadClass(className, true, false); } /** * Same as {@link #loadClass(String,boolean)}, except only exported classes will be considered. * * @param className the class name * @param resolve {@code true} to resolve the class after loading * @return the class * @throws ClassNotFoundException if the class isn't found */ public final Class<?> loadExportedClass(final String className, boolean resolve) throws ClassNotFoundException { return performLoadClass(className, true, resolve); } /** * Find a class, possibly delegating to other loader(s). This method should <b>never</b> synchronize across a * delegation method call of any sort. The default implementation always throws {@code ClassNotFoundException}. * * @param className the class name * @param exportsOnly {@code true} if only exported classes should be considered * @param resolve {@code true} to resolve the loaded class * @return the class * @throws ClassNotFoundException if the class is not found */ protected Class<?> findClass(final String className, final boolean exportsOnly, final boolean resolve) throws ClassNotFoundException { throw new ClassNotFoundException(className); } /** * Implementation of {@link ClassLoader#findClass(String)}. * * @param className the class name * @return the result of {@code findClass(className, false, false)} */ protected final Class<?> findClass(final String className) throws ClassNotFoundException { return findClass(className, false, false); } /** * Finds the resource with the given name. The name of a resource is a {@code '/'}-separated path name that * identifies the resource. If the resource name starts with {@code "java/"} then the parent class loader is used. * Otherwise, this method delegates to {@link #findResource(String, boolean)}. * * @param name the name of the resource * @return the resource URL, or {@code null} if no such resource exists or the invoker does not have adequate * permission to access it */ public final URL getResource(final String name) { for (String s : Module.systemPaths) { if (name.startsWith(s)) { return super.getResource(name); } } return findResource(name, false); } /** * Finds all available resources with the given name. * * @see #getResource(String) * * @param name the resource name * @return an enumeration over all the resource URLs; if no resources could be found, the enumeration will be empty * @throws IOException if an I/O error occurs */ public final Enumeration<URL> getResources(final String name) throws IOException { for (String s : Module.systemPaths) { if (name.startsWith(s)) { return super.getResources(name); } } return findResources(name, false); } /** * Find the resource with the given name and exported status. * * @see #getResource(String) * * @param name the resource name * @param exportsOnly {@code true} to consider only exported resources or {@code false} to consider all resources * @return the resource URL */ protected URL findResource(final String name, final boolean exportsOnly) { return null; } /** * Never used. {@link ClassLoader#getResource(String)} and related methods can cause a loop condition * when this method is implemented; use {@link #findResource(String, boolean)} instead. * * @param name ignored * @return {@code null} always */ protected final URL findResource(final String name) { // Always return null so that we don't go into a loop from super.getResource*(). return null; } /** * Finds the resources with the given name and exported status. * * @see #getResources(String) * * @param name the resource name * @param exportsOnly {@code true} to consider only exported resources or {@code false} to consider all resources * @return the resource enumeration * @throws IOException if an I/O error occurs */ protected Enumeration<URL> findResources(final String name, final boolean exportsOnly) throws IOException { return EMPTY_ENUMERATION; } /** * Never used. {@link ClassLoader#getResources(String)} and related methods can cause a loop condition * when this method is implemented; use {@link #findResources(String, boolean)} instead. By default, returns * an empty enumeration. * * @param name ignored * @return an empty enumeration */ protected final Enumeration<URL> findResources(final String name) { return EMPTY_ENUMERATION; } /** * Finds the resource with the given name and exported status, returning the resource content as a stream. * * @param name the resource name * @param exportsOnly {@code true} to consider only exported resources or {@code false} to consider all resources * @return the resource stream, or {@code null} if the resource is not found */ protected InputStream findResourceAsStream(final String name, final boolean exportsOnly) { final URL url = findResource(name, exportsOnly); try { return url == null ? null : url.openStream(); } catch (IOException e) { return null; } } /** * Returns an input stream for reading the specified resource. If the resource starts with {@code "java/"}, then * this method delegates to the parent class loader. Otherwise, this method delegates to {@link #findResourceAsStream(String, boolean)}. * * @param name the resource name * @return the resource stream, or {@code null} if the resource is not found */ public final InputStream getResourceAsStream(final String name) { for (String s : Module.systemPaths) { if (name.startsWith(s)) { return super.getResourceAsStream(name); } } return findResourceAsStream(name, false); } // Private members /** * Perform a class load operation. If the class is in the package or a subpackage of a package in the system packages list, * the parent class loader is used to load the class. Otherwise, this method checks to see if the class loader * object is locked; if so, it unlocks it and submits the request to the class loader thread. Otherwise, it will * load the class itself by delegating to {@link #findClass(String, boolean, boolean)}. * * @param className the class name * @param exportsOnly {@code true} to consider only exported resources or {@code false} to consider all resources * @param resolve {@code true} to resolve the loaded class * @return the class returned by {@link #findClass(String, boolean, boolean)} * @throws ClassNotFoundException if {@link #findClass(String, boolean, boolean)} throws this exception */ private Class<?> performLoadClass(String className, boolean exportsOnly, final boolean resolve) throws ClassNotFoundException { if (className == null) { throw new IllegalArgumentException("name is null"); } for (String s : Module.systemPackages) { if (className.startsWith(s)) { // always delegate to system return findSystemClass(className); } } return performLoadClassChecked(className, exportsOnly, resolve); } /** * Perform a class load operation. This method checks to see if the class loader object is locked; if so, it * unlocks it and submits the request to the class loader thread. Otherwise, it will load the class itself by * delegating to {@link #findClass(String, boolean, boolean)}. * <p> * If the {@code jboss.modules.unsafe-locks} system property is set to {@code true}, then rather than using the * class loading thread, the lock is forcibly broken and the load retried. * * @param className the class name * @param exportsOnly {@code true} to consider only exported resources or {@code false} to consider all resources * @param resolve {@code true} to resolve the loaded class * @return the class returned by {@link #findClass(String, boolean, boolean)} * @throws ClassNotFoundException if {@link #findClass(String, boolean, boolean)} throws this exception */ private Class<?> performLoadClassChecked(final String className, final boolean exportsOnly, final boolean resolve) throws ClassNotFoundException { if (Thread.holdsLock(this) && Thread.currentThread() != LoaderThreadHolder.LOADER_THREAD) { if (UNSAFE_LOCKS) { final Unsafe unsafe = ConcurrentClassLoader.UnsafeHolder.UNSAFE; unsafe.monitorExit(this); try { return performLoadClassChecked(className, exportsOnly, resolve); } finally { unsafe.monitorEnter(this); } } // Only the classloader thread may take this lock; use a condition to relinquish it final LoadRequest req = new LoadRequest(className, resolve, exportsOnly, this); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; synchronized (queue) { queue.add(req); queue.notify(); } boolean intr = false; try { while (!req.done) try { wait(); } catch (InterruptedException e) { intr = true; } } finally { if (intr) Thread.currentThread().interrupt(); } return req.result; } else { // no deadlock risk! Either the lock isn't held, or we're inside the class loader thread. return findClass(className, exportsOnly, resolve); } } static final class LoaderThreadHolder { static final Thread LOADER_THREAD; static final Queue<LoadRequest> REQUEST_QUEUE = new ArrayDeque<LoadRequest>(); static { Thread thr = new LoaderThread(); thr.setName("ClassLoader Thread"); // This thread will always run as long as the VM is alive. thr.setDaemon(true); thr.start(); LOADER_THREAD = thr; } private LoaderThreadHolder() { } } static class LoadRequest { private final String className; private final boolean resolve; private final ConcurrentClassLoader requester; Class<?> result; private boolean exportsOnly; boolean done; LoadRequest(final String className, final boolean resolve, final boolean exportsOnly, final ConcurrentClassLoader requester) { this.className = className; this.resolve = resolve; this.exportsOnly = exportsOnly; this.requester = requester; } } static class LoaderThread extends Thread { @Override public void interrupt() { // no interruption } @Override public void run() { /* This resolves a know deadlock that can occur if one thread is in the process of defining a package as part of defining a class, and another thread is defining the system package that can result in loading a class. One holds the Package.pkgs lock and one holds the Classloader lock. */ Package.getPackages(); final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; for (; ;) { try { LoadRequest request; synchronized (queue) { while ((request = queue.poll()) == null) { queue.wait(); } } final ConcurrentClassLoader loader = request.requester; Class<?> result = null; synchronized (loader) { try { result = loader.performLoadClassChecked(request.className, request.exportsOnly, request.resolve); } finally { // no matter what, the requester MUST be notified request.result = result; request.done = true; loader.notifyAll(); } } } catch (Throwable t) { // ignore } } } } private static final class UnsafeHolder { static Unsafe UNSAFE; static { try { final Field field = Unsafe.class.getDeclaredField("theUnsafe"); field.setAccessible(true); UNSAFE = (Unsafe) field.get(null); } catch (IllegalAccessException e) { throw new IllegalAccessError(e.getMessage()); } catch (NoSuchFieldException e) { throw new NoSuchFieldError(e.getMessage()); } } private UnsafeHolder() { } } }
More innocuous name; also, when lockless is used, do not trigger creation of the CL thread
src/main/java/org/jboss/modules/ConcurrentClassLoader.java
More innocuous name; also, when lockless is used, do not trigger creation of the CL thread
<ide><path>rc/main/java/org/jboss/modules/ConcurrentClassLoader.java <ide> */ <ide> public abstract class ConcurrentClassLoader extends SecureClassLoader { <ide> <del> private static final boolean UNSAFE_LOCKS; <add> private static final boolean LOCKLESS; <ide> <ide> static { <del> UNSAFE_LOCKS = Boolean.parseBoolean(AccessController.doPrivileged(new PropertyReadAction("jboss.modules.unsafe-locks"))); <add> LOCKLESS = Boolean.parseBoolean(AccessController.doPrivileged(new PropertyReadAction("jboss.modules.lockless"))); <ide> } <ide> <ide> /** <ide> * @throws ClassNotFoundException if {@link #findClass(String, boolean, boolean)} throws this exception <ide> */ <ide> private Class<?> performLoadClassChecked(final String className, final boolean exportsOnly, final boolean resolve) throws ClassNotFoundException { <del> if (Thread.holdsLock(this) && Thread.currentThread() != LoaderThreadHolder.LOADER_THREAD) { <del> if (UNSAFE_LOCKS) { <del> final Unsafe unsafe = ConcurrentClassLoader.UnsafeHolder.UNSAFE; <add> if (Thread.holdsLock(this)) { <add> if (LOCKLESS) { <add> final Unsafe unsafe = UnsafeHolder.UNSAFE; <ide> unsafe.monitorExit(this); <ide> try { <ide> return performLoadClassChecked(className, exportsOnly, resolve); <ide> unsafe.monitorEnter(this); <ide> } <ide> } <del> // Only the classloader thread may take this lock; use a condition to relinquish it <del> final LoadRequest req = new LoadRequest(className, resolve, exportsOnly, this); <del> final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; <del> synchronized (queue) { <del> queue.add(req); <del> queue.notify(); <del> } <del> boolean intr = false; <del> try { <del> while (!req.done) try { <del> wait(); <del> } catch (InterruptedException e) { <del> intr = true; <add> if (Thread.currentThread() != LoaderThreadHolder.LOADER_THREAD) { <add> // Only the classloader thread may take this lock; use a condition to relinquish it <add> final LoadRequest req = new LoadRequest(className, resolve, exportsOnly, this); <add> final Queue<LoadRequest> queue = LoaderThreadHolder.REQUEST_QUEUE; <add> synchronized (queue) { <add> queue.add(req); <add> queue.notify(); <ide> } <del> } finally { <del> if (intr) Thread.currentThread().interrupt(); <del> } <del> <del> return req.result; <del> } else { <del> // no deadlock risk! Either the lock isn't held, or we're inside the class loader thread. <del> return findClass(className, exportsOnly, resolve); <del> } <add> boolean intr = false; <add> try { <add> while (!req.done) try { <add> wait(); <add> } catch (InterruptedException e) { <add> intr = true; <add> } <add> } finally { <add> if (intr) Thread.currentThread().interrupt(); <add> } <add> <add> return req.result; <add> } <add> } <add> // no deadlock risk! Either the lock isn't held, or we're inside the class loader thread. <add> return findClass(className, exportsOnly, resolve); <ide> } <ide> <ide> static final class LoaderThreadHolder {
Java
apache-2.0
b8089469536bc1369f07950d785a03b8c47b303e
0
kuali/kc-rice,ewestfal/rice-svn2git-test,sonamuthu/rice-1,smith750/rice,geothomasp/kualico-rice-kc,shahess/rice,cniesen/rice,geothomasp/kualico-rice-kc,gathreya/rice-kc,shahess/rice,UniversityOfHawaiiORS/rice,smith750/rice,jwillia/kc-rice1,ewestfal/rice,bhutchinson/rice,cniesen/rice,bhutchinson/rice,geothomasp/kualico-rice-kc,gathreya/rice-kc,bsmith83/rice-1,sonamuthu/rice-1,shahess/rice,ewestfal/rice,cniesen/rice,rojlarge/rice-kc,sonamuthu/rice-1,gathreya/rice-kc,bhutchinson/rice,rojlarge/rice-kc,rojlarge/rice-kc,ewestfal/rice-svn2git-test,UniversityOfHawaiiORS/rice,gathreya/rice-kc,ewestfal/rice-svn2git-test,cniesen/rice,bhutchinson/rice,UniversityOfHawaiiORS/rice,geothomasp/kualico-rice-kc,shahess/rice,jwillia/kc-rice1,UniversityOfHawaiiORS/rice,smith750/rice,rojlarge/rice-kc,cniesen/rice,jwillia/kc-rice1,ewestfal/rice,bsmith83/rice-1,kuali/kc-rice,jwillia/kc-rice1,bsmith83/rice-1,smith750/rice,bsmith83/rice-1,shahess/rice,ewestfal/rice,kuali/kc-rice,rojlarge/rice-kc,smith750/rice,sonamuthu/rice-1,gathreya/rice-kc,jwillia/kc-rice1,kuali/kc-rice,ewestfal/rice,geothomasp/kualico-rice-kc,kuali/kc-rice,ewestfal/rice-svn2git-test,UniversityOfHawaiiORS/rice,bhutchinson/rice
/* * Copyright 2005-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kns.datadictionary; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.kuali.rice.kns.bo.BusinessObject; import org.kuali.rice.kns.datadictionary.exception.AttributeValidationException; import org.kuali.rice.kns.datadictionary.exception.ClassValidationException; import org.kuali.rice.kns.datadictionary.exception.DuplicateEntryException; import org.kuali.rice.kns.document.Document; import org.kuali.rice.kns.document.MaintenanceDocumentBase; import org.kuali.rice.kns.document.authorization.MaintenanceDocumentAuthorizer; import org.kuali.rice.kns.maintenance.Maintainable; /** * MaintenanceDocumentEntry * * */ public class MaintenanceDocumentEntry extends DocumentEntry { protected Class<? extends BusinessObject> businessObjectClass; protected Class<? extends Maintainable> maintainableClass; protected List<MaintainableSectionDefinition> maintainableSections = new ArrayList<MaintainableSectionDefinition>(); protected List<String> lockingKeys = new ArrayList<String>(); protected List<ApcRuleDefinition> apcRules = new ArrayList<ApcRuleDefinition>(); protected Map<String,MaintainableSectionDefinition> maintainableSectionMap = new LinkedHashMap<String, MaintainableSectionDefinition>(); protected Map<String,ApcRuleDefinition> apcRuleMap = new LinkedHashMap<String, ApcRuleDefinition>(); protected boolean allowsNewOrCopy = true; protected String additionalSectionsFile; //for issue KULRice3072, to enable PK field copy protected boolean preserveLockingKeysOnCopy = false; public MaintenanceDocumentEntry() { super(); setDocumentClass(getStandardDocumentBaseClass()); } public Class<? extends Document> getStandardDocumentBaseClass() { return MaintenanceDocumentBase.class; } /* This attribute is used in many contexts, for example, in maintenance docs, it's used to specify the classname of the BO being maintained. */ public void setBusinessObjectClass(Class<? extends BusinessObject> businessObjectClass) { if (businessObjectClass == null) { throw new IllegalArgumentException("invalid (null) businessObjectClass"); } this.businessObjectClass = businessObjectClass; } public Class<? extends BusinessObject> getBusinessObjectClass() { return businessObjectClass; } /** * @see org.kuali.rice.kns.datadictionary.DocumentEntry#getEntryClass() */ @Override public Class getEntryClass() { return businessObjectClass; } /* The maintainableClass element specifies the name of the java class which is responsible for implementing the maintenance logic. The normal one is KualiMaintainableImpl.java. */ public void setMaintainableClass(Class<? extends Maintainable> maintainableClass) { if (maintainableClass == null) { throw new IllegalArgumentException("invalid (null) maintainableClass"); } this.maintainableClass = maintainableClass; } public Class<? extends Maintainable> getMaintainableClass() { return maintainableClass; } /** * @return List of MaintainableSectionDefinition objects contained in this document */ public List<MaintainableSectionDefinition> getMaintainableSections() { return maintainableSections; } /** * @return List of all lockingKey fieldNames associated with this LookupDefinition, in the order in which they were added */ public List<String> getLockingKeyFieldNames() { return lockingKeys; } /** * * @return List of all apcRule ApcRuleDefinitions associated with this MaintenanceDocument, in the order in which they were * added * */ public List<ApcRuleDefinition> getApcRules() { return apcRules; } /** * * @return List of all apcRule rule's fieldNames associated with this MaintenanceDocument, in the order in which they were added * */ public List<String> getApcRuleFieldNames() { List<String> fieldNames = new ArrayList<String>(); fieldNames.addAll(this.apcRuleMap.keySet()); return fieldNames; } /** * Gets the allowsNewOrCopy attribute. * @return Returns the allowsNewOrCopy. */ public boolean getAllowsNewOrCopy() { return allowsNewOrCopy; } /** The allowsNewOrCopy element contains a value of true or false. If true, this indicates the maintainable should allow the new and/or copy maintenance actions. */ public void setAllowsNewOrCopy(boolean allowsNewOrCopy) { this.allowsNewOrCopy = allowsNewOrCopy; } /** * Directly validate simple fields, call completeValidation on Definition fields. * * @see org.kuali.rice.kns.datadictionary.DocumentEntry#completeValidation() */ public void completeValidation() { super.completeValidation(); for ( MaintainableSectionDefinition maintainableSectionDefinition : maintainableSections ) { maintainableSectionDefinition.completeValidation(businessObjectClass, null); } for ( String lockingKey : lockingKeys ) { if (!DataDictionary.isPropertyOf(businessObjectClass, lockingKey)) { throw new AttributeValidationException("unable to find attribute '" + lockingKey + "' for lockingKey in businessObjectClass '" + businessObjectClass.getName() ); } } for ( ReferenceDefinition reference : defaultExistenceChecks ) { reference.completeValidation(businessObjectClass, null); } for ( ApcRuleDefinition apcRule : apcRules ) { apcRule.completeValidation(businessObjectClass, null); } if (documentAuthorizerClass != null && !MaintenanceDocumentAuthorizer.class.isAssignableFrom(documentAuthorizerClass)) { throw new ClassValidationException("This maintenance document for '" + businessObjectClass.getName() + "' has an invalid " + "documentAuthorizerClass ('" + documentAuthorizerClass.getName() + "'). " + "Maintenance Documents must use an implementation of MaintenanceDocumentAuthorizer."); } } /** * @see java.lang.Object#toString() */ public String toString() { return "MaintenanceDocumentEntry for documentType " + getDocumentTypeName(); } public String getAdditionalSectionsFile() { return additionalSectionsFile; } /* The additionalSectionsFile element specifies the name of the location of an additional JSP file to include in the maintenance document after the generation sections but before the notes. The location semantics are those of jsp:include. */ public void setAdditionalSectionsFile(String additionalSectionsFile) { this.additionalSectionsFile = additionalSectionsFile; } public List<String> getLockingKeys() { return lockingKeys; } /* The lockingKeys element specifies a list of fields that comprise a unique key. This is used for record locking during the file maintenance process. */ public void setLockingKeys(List<String> lockingKeys) { for ( String lockingKey : lockingKeys ) { if (lockingKey == null) { throw new IllegalArgumentException("invalid (null) lockingKey"); } } this.lockingKeys = lockingKeys; } /** The maintainableSections elements allows the maintenance document to be presented in sections. Each section can have a different title. JSTL: maintainbleSections is a Map whichis accessed by a key of "maintainableSections". This map contains entries with the following keys: * "0" (for first section) * "1" (for second section) etc. The corresponding value for each entry is a maintainableSection ExportMap. See MaintenanceDocumentEntryMapper.java. */ public void setMaintainableSections(List<MaintainableSectionDefinition> maintainableSections) { maintainableSectionMap.clear(); for ( MaintainableSectionDefinition maintainableSectionDefinition : maintainableSections ) { if (maintainableSectionDefinition == null) { throw new IllegalArgumentException("invalid (null) maintainableSectionDefinition"); } String sectionTitle = maintainableSectionDefinition.getTitle(); if (maintainableSectionMap.containsKey(sectionTitle)) { throw new DuplicateEntryException("section '" + sectionTitle + "' already defined for maintenanceDocument '" + getDocumentTypeName() + "'"); } maintainableSectionMap.put(sectionTitle, maintainableSectionDefinition); } this.maintainableSections = maintainableSections; } /* The apcRule element is used to specifiy legal values for an attribute. This is done by specifiying the key to the System Parameters table that indicates the allowable values. JSTL: apcRules are Maps with the following keys: * attributeName (String) * parameterNamespace (String) * parameterDetailType (String) * parameterName (String) * errorMessage (String) a property key usually defined in ApplicationResources.properties See DictionaryValidationService.validateApcRule */ public void setApcRules(List<ApcRuleDefinition> apcRules) { apcRuleMap.clear(); for ( ApcRuleDefinition apcRule : apcRules ) { if (apcRule == null) { throw new IllegalArgumentException("invalid (null) apcRule"); } String keyName = apcRule.getAttributeName(); if (apcRuleMap.containsKey(keyName)) { throw new DuplicateEntryException("duplicate apcRule entry for attribute '" + keyName + "'"); } apcRuleMap.put(keyName, apcRule); } this.apcRules = apcRules; } /** * @return the preserveLockingKeysOnCopy */ public boolean getPreserveLockingKeysOnCopy() { return this.preserveLockingKeysOnCopy; } /** * @param preserveLockingKeysOnCopy the preserveLockingKeysOnCopy to set */ public void setPreserveLockingKeysOnCopy(boolean preserveLockingKeysOnCopy) { this.preserveLockingKeysOnCopy = preserveLockingKeysOnCopy; } }
impl/src/main/java/org/kuali/rice/kns/datadictionary/MaintenanceDocumentEntry.java
/* * Copyright 2005-2007 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl1.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.rice.kns.datadictionary; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.kuali.rice.kns.bo.BusinessObject; import org.kuali.rice.kns.datadictionary.exception.AttributeValidationException; import org.kuali.rice.kns.datadictionary.exception.ClassValidationException; import org.kuali.rice.kns.datadictionary.exception.DuplicateEntryException; import org.kuali.rice.kns.document.Document; import org.kuali.rice.kns.document.MaintenanceDocumentBase; import org.kuali.rice.kns.document.authorization.MaintenanceDocumentAuthorizer; import org.kuali.rice.kns.maintenance.Maintainable; /** * MaintenanceDocumentEntry * * */ public class MaintenanceDocumentEntry extends DocumentEntry { protected Class<? extends BusinessObject> businessObjectClass; protected Class<? extends Maintainable> maintainableClass; protected List<MaintainableSectionDefinition> maintainableSections = new ArrayList<MaintainableSectionDefinition>(); protected List<String> lockingKeys = new ArrayList<String>(); protected List<ApcRuleDefinition> apcRules = new ArrayList<ApcRuleDefinition>(); protected Map<String,MaintainableSectionDefinition> maintainableSectionMap = new LinkedHashMap<String, MaintainableSectionDefinition>(); protected Map<String,ApcRuleDefinition> apcRuleMap = new LinkedHashMap<String, ApcRuleDefinition>(); protected boolean allowsNewOrCopy = true; protected String additionalSectionsFile; public MaintenanceDocumentEntry() { super(); setDocumentClass(getStandardDocumentBaseClass()); } public Class<? extends Document> getStandardDocumentBaseClass() { return MaintenanceDocumentBase.class; } /* This attribute is used in many contexts, for example, in maintenance docs, it's used to specify the classname of the BO being maintained. */ public void setBusinessObjectClass(Class<? extends BusinessObject> businessObjectClass) { if (businessObjectClass == null) { throw new IllegalArgumentException("invalid (null) businessObjectClass"); } this.businessObjectClass = businessObjectClass; } public Class<? extends BusinessObject> getBusinessObjectClass() { return businessObjectClass; } /** * @see org.kuali.rice.kns.datadictionary.DocumentEntry#getEntryClass() */ @Override public Class getEntryClass() { return businessObjectClass; } /* The maintainableClass element specifies the name of the java class which is responsible for implementing the maintenance logic. The normal one is KualiMaintainableImpl.java. */ public void setMaintainableClass(Class<? extends Maintainable> maintainableClass) { if (maintainableClass == null) { throw new IllegalArgumentException("invalid (null) maintainableClass"); } this.maintainableClass = maintainableClass; } public Class<? extends Maintainable> getMaintainableClass() { return maintainableClass; } /** * @return List of MaintainableSectionDefinition objects contained in this document */ public List<MaintainableSectionDefinition> getMaintainableSections() { return maintainableSections; } /** * @return List of all lockingKey fieldNames associated with this LookupDefinition, in the order in which they were added */ public List<String> getLockingKeyFieldNames() { return lockingKeys; } /** * * @return List of all apcRule ApcRuleDefinitions associated with this MaintenanceDocument, in the order in which they were * added * */ public List<ApcRuleDefinition> getApcRules() { return apcRules; } /** * * @return List of all apcRule rule's fieldNames associated with this MaintenanceDocument, in the order in which they were added * */ public List<String> getApcRuleFieldNames() { List<String> fieldNames = new ArrayList<String>(); fieldNames.addAll(this.apcRuleMap.keySet()); return fieldNames; } /** * Gets the allowsNewOrCopy attribute. * @return Returns the allowsNewOrCopy. */ public boolean getAllowsNewOrCopy() { return allowsNewOrCopy; } /** The allowsNewOrCopy element contains a value of true or false. If true, this indicates the maintainable should allow the new and/or copy maintenance actions. */ public void setAllowsNewOrCopy(boolean allowsNewOrCopy) { this.allowsNewOrCopy = allowsNewOrCopy; } /** * Directly validate simple fields, call completeValidation on Definition fields. * * @see org.kuali.rice.kns.datadictionary.DocumentEntry#completeValidation() */ public void completeValidation() { super.completeValidation(); for ( MaintainableSectionDefinition maintainableSectionDefinition : maintainableSections ) { maintainableSectionDefinition.completeValidation(businessObjectClass, null); } for ( String lockingKey : lockingKeys ) { if (!DataDictionary.isPropertyOf(businessObjectClass, lockingKey)) { throw new AttributeValidationException("unable to find attribute '" + lockingKey + "' for lockingKey in businessObjectClass '" + businessObjectClass.getName() ); } } for ( ReferenceDefinition reference : defaultExistenceChecks ) { reference.completeValidation(businessObjectClass, null); } for ( ApcRuleDefinition apcRule : apcRules ) { apcRule.completeValidation(businessObjectClass, null); } if (documentAuthorizerClass != null && !MaintenanceDocumentAuthorizer.class.isAssignableFrom(documentAuthorizerClass)) { throw new ClassValidationException("This maintenance document for '" + businessObjectClass.getName() + "' has an invalid " + "documentAuthorizerClass ('" + documentAuthorizerClass.getName() + "'). " + "Maintenance Documents must use an implementation of MaintenanceDocumentAuthorizer."); } } /** * @see java.lang.Object#toString() */ public String toString() { return "MaintenanceDocumentEntry for documentType " + getDocumentTypeName(); } public String getAdditionalSectionsFile() { return additionalSectionsFile; } /* The additionalSectionsFile element specifies the name of the location of an additional JSP file to include in the maintenance document after the generation sections but before the notes. The location semantics are those of jsp:include. */ public void setAdditionalSectionsFile(String additionalSectionsFile) { this.additionalSectionsFile = additionalSectionsFile; } public List<String> getLockingKeys() { return lockingKeys; } /* The lockingKeys element specifies a list of fields that comprise a unique key. This is used for record locking during the file maintenance process. */ public void setLockingKeys(List<String> lockingKeys) { for ( String lockingKey : lockingKeys ) { if (lockingKey == null) { throw new IllegalArgumentException("invalid (null) lockingKey"); } } this.lockingKeys = lockingKeys; } /** The maintainableSections elements allows the maintenance document to be presented in sections. Each section can have a different title. JSTL: maintainbleSections is a Map whichis accessed by a key of "maintainableSections". This map contains entries with the following keys: * "0" (for first section) * "1" (for second section) etc. The corresponding value for each entry is a maintainableSection ExportMap. See MaintenanceDocumentEntryMapper.java. */ public void setMaintainableSections(List<MaintainableSectionDefinition> maintainableSections) { maintainableSectionMap.clear(); for ( MaintainableSectionDefinition maintainableSectionDefinition : maintainableSections ) { if (maintainableSectionDefinition == null) { throw new IllegalArgumentException("invalid (null) maintainableSectionDefinition"); } String sectionTitle = maintainableSectionDefinition.getTitle(); if (maintainableSectionMap.containsKey(sectionTitle)) { throw new DuplicateEntryException("section '" + sectionTitle + "' already defined for maintenanceDocument '" + getDocumentTypeName() + "'"); } maintainableSectionMap.put(sectionTitle, maintainableSectionDefinition); } this.maintainableSections = maintainableSections; } /* The apcRule element is used to specifiy legal values for an attribute. This is done by specifiying the key to the System Parameters table that indicates the allowable values. JSTL: apcRules are Maps with the following keys: * attributeName (String) * parameterNamespace (String) * parameterDetailType (String) * parameterName (String) * errorMessage (String) a property key usually defined in ApplicationResources.properties See DictionaryValidationService.validateApcRule */ public void setApcRules(List<ApcRuleDefinition> apcRules) { apcRuleMap.clear(); for ( ApcRuleDefinition apcRule : apcRules ) { if (apcRule == null) { throw new IllegalArgumentException("invalid (null) apcRule"); } String keyName = apcRule.getAttributeName(); if (apcRuleMap.containsKey(keyName)) { throw new DuplicateEntryException("duplicate apcRule entry for attribute '" + keyName + "'"); } apcRuleMap.put(keyName, apcRule); } this.apcRules = apcRules; } }
// fix for issue KULRice 3072
impl/src/main/java/org/kuali/rice/kns/datadictionary/MaintenanceDocumentEntry.java
// fix for issue KULRice 3072
<ide><path>mpl/src/main/java/org/kuali/rice/kns/datadictionary/MaintenanceDocumentEntry.java <ide> <ide> protected boolean allowsNewOrCopy = true; <ide> protected String additionalSectionsFile; <del> <del> public MaintenanceDocumentEntry() { <add> <add> //for issue KULRice3072, to enable PK field copy <add> <add> protected boolean preserveLockingKeysOnCopy = false; <add> <add> public MaintenanceDocumentEntry() { <ide> super(); <ide> setDocumentClass(getStandardDocumentBaseClass()); <ide> } <ide> } <ide> this.apcRules = apcRules; <ide> } <add> <add> /** <add> * @return the preserveLockingKeysOnCopy <add> */ <add> public boolean getPreserveLockingKeysOnCopy() { <add> return this.preserveLockingKeysOnCopy; <add> } <add> <add> /** <add> * @param preserveLockingKeysOnCopy the preserveLockingKeysOnCopy to set <add> */ <add> public void setPreserveLockingKeysOnCopy(boolean preserveLockingKeysOnCopy) { <add> this.preserveLockingKeysOnCopy = preserveLockingKeysOnCopy; <add> } <ide> <ide> }
Java
apache-2.0
cbf2276dba9aabd5abc72f4dff2db7af0d0350a8
0
speedment/speedment,speedment/speedment
/* * * Copyright (c) 2006-2019, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.common.injector.internal.util; import com.speedment.common.injector.InjectorProxy; import com.speedment.common.injector.MissingArgumentStrategy; import com.speedment.common.injector.annotation.*; import com.speedment.common.injector.exception.InjectorException; import java.io.File; import java.lang.reflect.*; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.speedment.common.injector.internal.util.PropertiesUtil.configureParams; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toSet; /** * Some common utility methods for analyzing classes with reflection. * * @author Emil Forslund * @since 1.0.0 */ public final class ReflectionUtil { private ReflectionUtil() {} public static Stream<Field> traverseFields(Class<?> clazz) { final Class<?> parent = clazz.getSuperclass(); final Stream<Field> inherited; if (parent != null) { inherited = traverseFields(parent); } else { inherited = Stream.empty(); } return Stream.concat(inherited, Stream.of(clazz.getDeclaredFields())); } public static Stream<Method> traverseMethods(Class<?> clazz) { return traverseAncestors(clazz) .flatMap(c -> Stream.of(c.getDeclaredMethods())); } public static Stream<Class<?>> traverseAncestors(Class<?> clazz) { if (clazz.getSuperclass() == null) { // We have reached Object.class return Stream.of(clazz); } else { return Stream.concat( Stream.of(clazz), Stream.concat( traverseAncestors(clazz.getSuperclass()), Stream.of(clazz.getInterfaces()) ) ).distinct(); } } public static MissingArgumentStrategy missingArgumentStrategy(Executable executable) { final Execute execute = executable.getAnnotation(Execute.class); final ExecuteBefore executeBefore = executable.getAnnotation(ExecuteBefore.class); if (execute != null) { return execute.missingArgument(); } else if (executeBefore != null) { return executeBefore.missingArgument(); } else { return MissingArgumentStrategy.THROW_EXCEPTION; } } public static <T> Optional<T> tryToCreate(Class<T> clazz, Properties properties, List<Object> instances, Set<Class<?>> allInjectableTypes, InjectorProxy injectorProxy) throws InstantiationException { try { final Optional<Constructor<T>> oConstr = findConstructor(clazz, instances, allInjectableTypes); if (!oConstr.isPresent()) { return Optional.empty(); } final Constructor<T> constr = oConstr.get(); // injectorProxy.setAccessable(constr); final Parameter[] params = constr.getParameters(); final Object[] args = new Object[params.length]; for (int i = 0; i < params.length; i++) { final Parameter param = params[i]; final Config config = param.getAnnotation(Config.class); if (config != null) { final String serialized; if (properties.containsKey(config.name())) { serialized = properties.getProperty(config.name()); } else { serialized = config.value(); } final Class<?> type = param.getType(); Object value; if (boolean.class == type || Boolean.class.isAssignableFrom(type)) { value = Boolean.parseBoolean(serialized); } else if (byte.class == type || Byte.class.isAssignableFrom(type)) { value = Byte.parseByte(serialized); } else if (short.class == type || Short.class.isAssignableFrom(type)) { value = Short.parseShort(serialized); } else if (int.class == type || Integer.class.isAssignableFrom(type)) { value = Integer.parseInt(serialized); } else if (long.class == type || Long.class.isAssignableFrom(type)) { value = Long.parseLong(serialized); } else if (float.class == type || Float.class.isAssignableFrom(type)) { value = Float.parseFloat(serialized); } else if (double.class == type || Double.class.isAssignableFrom(type)) { value = Double.parseDouble(serialized); } else if (String.class.isAssignableFrom(type)) { value = serialized; } else if (char.class == type || Character.class.isAssignableFrom(type)) { if (serialized.length() == 1) { value = serialized.charAt(0); } else { throw new IllegalArgumentException( "Value '" + serialized + "' is to long to be " + "parsed into a field of type '" + type.getName() + "'." ); } } else if (File.class.isAssignableFrom(type)) { value = new File(serialized); } else if (URL.class.isAssignableFrom(type)) { try { value = new URL(serialized); } catch (final MalformedURLException ex) { throw new IllegalArgumentException(String.format( "Specified URL '%s' is malformed.", serialized ), ex); } } else { throw new IllegalArgumentException(String.format( "Unsupported type '%s' injected into the " + "constructor of class '%s'.", type.getName(), clazz.getName() )); } args[i] = value; } else { // Not a @Config-field final Class<?> paramType = param.getType(); final Optional<? extends Class<?>> injectKeyClass = traverseAncestors(paramType) .filter(c -> c.isAnnotationPresent(InjectKey.class)) .map(c -> c.getAnnotation(InjectKey.class).value()) .findFirst(); if (injectKeyClass.isPresent()) { // Make sure that there are no other pending instances that // may implement this type, see #758 // // This set contains all classes that we need to be instantiated // before we know which one to select final Set<Class<?>> needed = allInjectableTypes.stream() .filter(c -> traverseAncestors(c) .anyMatch(a -> a.isAnnotationPresent(InjectKey.class) && a.getAnnotation(InjectKey.class).value().equals(injectKeyClass.get()) ) ) .collect(toSet()); // Remove the existing classes instances.stream() .map(Object::getClass) .forEach(needed::remove); if (!needed.isEmpty()) { // We do not know all instances yet so we have to wait for // their creation return Optional.empty(); } } final Optional<Object> value = instances.stream() .filter(o -> paramType.isAssignableFrom(o.getClass())) .findFirst(); if (value.isPresent()) { args[i] = value.get(); } else { throw new IllegalArgumentException(String.format( "No instance found that match the required type " + "'%s' in the constructor for injected class '%s'.", param.getClass().getName(), clazz.getName() )); } } } final T instance = injectorProxy.newInstance(constr, args); configureParams(instance, properties); return Optional.of(instance); } catch (final IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new InjectorException(String.format( "Unable to create class '%s'.", clazz.getName() ), ex); } } @SuppressWarnings("unchecked") private static <T> Optional<Constructor<T>> findConstructor(Class<T> clazz, List<Object> instances, Set<Class<?>> allInjectableTypes) { // If at least one constructor has the @Inject-annotation, only // @Inject-annotated constructors should be considered. return Arrays.stream(clazz.getDeclaredConstructors()) .sorted(Comparator.comparing(constr -> constr.isAnnotationPresent(Inject.class) ? 1 : 0)) .filter(constr -> isOnlyIfMissingConditionSatisfied(constr, allInjectableTypes)) .filter(constr -> canBeInvoked(constr, instances)) .map(constr -> (Constructor<T>) constr) .findFirst(); } @SuppressWarnings("unchecked") public static <T> String errorMsg(Class<T> c, List<Object> instances) { final Predicate<Constructor<?>> onlyInject; if (hasConstructorWithInjectAnnotation(c)) { onlyInject = constr -> constr.isAnnotationPresent(Inject.class); } else { onlyInject = constr -> true; } return String.format("%s: %n", c.getSimpleName()) + Arrays.stream(c.getDeclaredConstructors()) .map(constructor -> (Constructor<T>) constructor) .filter(onlyInject) .map(con -> String.format(" %s %s %n %s ", con.isAnnotationPresent(Inject.class) ? "@Inject" : " ", con.toString(), Stream.of(con.getParameters()) .map(p -> { if (paramIsConfig(p)) { return String.format(" %s %s%n", Config.class.getSimpleName(), p.toString()); } else { return String.format(" %s %s%n", p.toString(), paramIsInjectable(p, instances) ? "" : " <-- Missing"); } }).collect(joining(String.format("%n"))) ) ).collect(joining(String.format("%n"))); } private static boolean canBeInvoked(Executable executable, List<Object> instances) { return Stream.of(executable.getParameters()) .allMatch(p -> paramIsConfig(p) || paramIsInjectable(p, instances)); } private static boolean paramIsConfig(Parameter param) { return param.isAnnotationPresent(Config.class); } private static boolean paramIsInjectable(Parameter param, List<Object> instances) { return instances.stream() .anyMatch(o -> param.getType().isAssignableFrom(o.getClass())); } private static boolean hasConstructorWithInjectAnnotation(Class<?> clazz) { return Stream.of(clazz.getDeclaredConstructors()) .anyMatch(constr -> constr.isAnnotationPresent(Inject.class)); } private static boolean isOnlyIfMissingConditionSatisfied(Constructor<?> constr, Set<Class<?>> allInjectableTypes) { final OnlyIfMissing missing = constr.getAnnotation(OnlyIfMissing.class); // If the annotation is not there then this constructor // should always be considered. if (missing == null) return true; // If the annotation is present then only if none of the // types listed have an implementation in the set should // the constructor be considered. else return Stream.of(missing.value()).noneMatch(missingType -> allInjectableTypes.stream() .anyMatch(missingType::isAssignableFrom) ); } }
common-parent/injector/src/main/java/com/speedment/common/injector/internal/util/ReflectionUtil.java
/* * * Copyright (c) 2006-2019, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.common.injector.internal.util; import com.speedment.common.injector.InjectorProxy; import com.speedment.common.injector.MissingArgumentStrategy; import com.speedment.common.injector.annotation.*; import com.speedment.common.injector.exception.InjectorException; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import java.util.function.Predicate; import java.util.stream.Stream; import static com.speedment.common.injector.internal.util.PropertiesUtil.configureParams; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toSet; /** * Some common utility methods for analyzing classes with reflection. * * @author Emil Forslund * @since 1.0.0 */ public final class ReflectionUtil { private ReflectionUtil() {} public static Stream<Field> traverseFields(Class<?> clazz) { final Class<?> parent = clazz.getSuperclass(); final Stream<Field> inherited; if (parent != null) { inherited = traverseFields(parent); } else { inherited = Stream.empty(); } return Stream.concat(inherited, Stream.of(clazz.getDeclaredFields())); } public static Stream<Method> traverseMethods(Class<?> clazz) { return traverseAncestors(clazz) .flatMap(c -> Stream.of(c.getDeclaredMethods())); } public static Stream<Class<?>> traverseAncestors(Class<?> clazz) { if (clazz.getSuperclass() == null) { // We have reached Object.class return Stream.of(clazz); } else { return Stream.concat( Stream.of(clazz), Stream.concat( traverseAncestors(clazz.getSuperclass()), Stream.of(clazz.getInterfaces()) ) ).distinct(); } } public static MissingArgumentStrategy missingArgumentStrategy(Executable executable) { final Execute execute = executable.getAnnotation(Execute.class); final ExecuteBefore executeBefore = executable.getAnnotation(ExecuteBefore.class); if (execute != null) { return execute.missingArgument(); } else if (executeBefore != null) { return executeBefore.missingArgument(); } else { return MissingArgumentStrategy.THROW_EXCEPTION; } } public static <T> Optional<T> tryToCreate(Class<T> clazz, Properties properties, List<Object> instances, Set<Class<?>> allInjectableTypes, InjectorProxy injectorProxy) throws InstantiationException { try { final Optional<Constructor<T>> oConstr = findConstructor(clazz, instances, allInjectableTypes); if (!oConstr.isPresent()) { return Optional.empty(); } final Constructor<T> constr = oConstr.get(); // injectorProxy.setAccessable(constr); final Parameter[] params = constr.getParameters(); final Object[] args = new Object[params.length]; for (int i = 0; i < params.length; i++) { final Parameter param = params[i]; final Config config = param.getAnnotation(Config.class); if (config != null) { final String serialized; if (properties.containsKey(config.name())) { serialized = properties.getProperty(config.name()); } else { serialized = config.value(); } final Class<?> type = param.getType(); Object value; if (boolean.class == type || Boolean.class.isAssignableFrom(type)) { value = Boolean.parseBoolean(serialized); } else if (byte.class == type || Byte.class.isAssignableFrom(type)) { value = Byte.parseByte(serialized); } else if (short.class == type || Short.class.isAssignableFrom(type)) { value = Short.parseShort(serialized); } else if (int.class == type || Integer.class.isAssignableFrom(type)) { value = Integer.parseInt(serialized); } else if (long.class == type || Long.class.isAssignableFrom(type)) { value = Long.parseLong(serialized); } else if (float.class == type || Float.class.isAssignableFrom(type)) { value = Float.parseFloat(serialized); } else if (double.class == type || Double.class.isAssignableFrom(type)) { value = Double.parseDouble(serialized); } else if (String.class.isAssignableFrom(type)) { value = serialized; } else if (char.class == type || Character.class.isAssignableFrom(type)) { if (serialized.length() == 1) { value = serialized.charAt(0); } else { throw new IllegalArgumentException( "Value '" + serialized + "' is to long to be " + "parsed into a field of type '" + type.getName() + "'." ); } } else if (File.class.isAssignableFrom(type)) { value = new File(serialized); } else if (URL.class.isAssignableFrom(type)) { try { value = new URL(serialized); } catch (final MalformedURLException ex) { throw new IllegalArgumentException(String.format( "Specified URL '%s' is malformed.", serialized ), ex); } } else { throw new IllegalArgumentException(String.format( "Unsupported type '%s' injected into the " + "constructor of class '%s'.", type.getName(), clazz.getName() )); } args[i] = value; } else { // Not a @Config-field final Class<?> paramType = param.getType(); final Optional<? extends Class<?>> injectKeyClass = traverseAncestors(paramType) .filter(c -> c.isAnnotationPresent(InjectKey.class)) .map(c -> c.getAnnotation(InjectKey.class).value()) .findFirst(); if (injectKeyClass.isPresent()) { // Make sure that there are no other pending instances that // may implement this type, see #758 // // This set contains all classes that we need to be instantiated // before we know which one to select final Set<Class<?>> needed = allInjectableTypes.stream() .filter(c -> traverseAncestors(c) .anyMatch(a -> a.isAnnotationPresent(InjectKey.class) && a.getAnnotation(InjectKey.class).value().equals(injectKeyClass.get()) ) ) .collect(toSet()); // Remove the existing classes instances.stream() .map(Object::getClass) .forEach(needed::remove); if (!needed.isEmpty()) { // We do not know all instances yet so we have to wait for // their creation return Optional.empty(); } } final Optional<Object> value = instances.stream() .filter(o -> paramType.isAssignableFrom(o.getClass())) .findFirst(); if (value.isPresent()) { args[i] = value.get(); } else { throw new IllegalArgumentException(String.format( "No instance found that match the required type " + "'%s' in the constructor for injected class '%s'.", param.getClass().getName(), clazz.getName() )); } } } final T instance = injectorProxy.newInstance(constr, args); configureParams(instance, properties); return Optional.of(instance); } catch (final IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) { throw new InjectorException(String.format( "Unable to create class '%s'.", clazz.getName() ), ex); } } @SuppressWarnings("unchecked") private static <T> Optional<Constructor<T>> findConstructor(Class<T> clazz, List<Object> instances, Set<Class<?>> allInjectableTypes) { // If at least one constructor has the @Inject-annotation, only // @Inject-annotated constructors should be considered. return Arrays.stream(clazz.getDeclaredConstructors()) .sorted(Comparator.comparing(constr -> constr.isAnnotationPresent(Inject.class) ? 1 : 0)) .filter(constr -> isOnlyIfMissingConditionSatisfied(constr, allInjectableTypes)) .filter(constr -> canBeInvoked(constr, instances)) .map(constr -> (Constructor<T>) constr) .findFirst(); } @SuppressWarnings("unchecked") public static <T> String errorMsg(Class<T> c, List<Object> instances) { final Predicate<Constructor<?>> onlyInject; if (hasConstructorWithInjectAnnotation(c)) { onlyInject = constr -> constr.isAnnotationPresent(Inject.class); } else { onlyInject = constr -> true; } return Arrays.stream(c.getDeclaredConstructors()) .map(constructor -> (Constructor<T>) constructor) .filter(onlyInject) .map(con -> String.format(" %s %s %n %s ", con.isAnnotationPresent(Inject.class) ? "@Inject" : " ", con.toString(), Stream.of(con.getParameters()) .map(p -> { if (paramIsConfig(p)) { return String.format(" %s %s%n", Config.class.getSimpleName(), p.toString()); } else { return String.format(" %s %s%n", p.toString(), paramIsInjectable(p, instances) ? "" : " <-- Missing"); } }).collect(joining(String.format("%n"))) ) ).collect(joining(String.format("%n"))); } private static boolean canBeInvoked(Executable executable, List<Object> instances) { return Stream.of(executable.getParameters()) .allMatch(p -> paramIsConfig(p) || paramIsInjectable(p, instances)); } private static boolean paramIsConfig(Parameter param) { return param.isAnnotationPresent(Config.class); } private static boolean paramIsInjectable(Parameter param, List<Object> instances) { return instances.stream() .anyMatch(o -> param.getType().isAssignableFrom(o.getClass())); } private static boolean hasConstructorWithInjectAnnotation(Class<?> clazz) { return Stream.of(clazz.getDeclaredConstructors()) .anyMatch(constr -> constr.isAnnotationPresent(Inject.class)); } private static boolean isOnlyIfMissingConditionSatisfied(Constructor<?> constr, Set<Class<?>> allInjectableTypes) { final OnlyIfMissing missing = constr.getAnnotation(OnlyIfMissing.class); // If the annotation is not there then this constructor // should always be considered. if (missing == null) return true; // If the annotation is present then only if none of the // types listed have an implementation in the set should // the constructor be considered. else return Stream.of(missing.value()).noneMatch(missingType -> allInjectableTypes.stream() .anyMatch(missingType::isAssignableFrom) ); } }
injector: Improve error logging
common-parent/injector/src/main/java/com/speedment/common/injector/internal/util/ReflectionUtil.java
injector: Improve error logging
<ide><path>ommon-parent/injector/src/main/java/com/speedment/common/injector/internal/util/ReflectionUtil.java <ide> import com.speedment.common.injector.exception.InjectorException; <ide> <ide> import java.io.File; <del>import java.lang.reflect.Constructor; <del>import java.lang.reflect.Executable; <del>import java.lang.reflect.Field; <del>import java.lang.reflect.InvocationTargetException; <del>import java.lang.reflect.Method; <del>import java.lang.reflect.Parameter; <add>import java.lang.reflect.*; <ide> import java.net.MalformedURLException; <ide> import java.net.URL; <ide> import java.util.*; <ide> onlyInject = constr -> true; <ide> } <ide> <del> return Arrays.stream(c.getDeclaredConstructors()) <add> return String.format("%s: %n", c.getSimpleName()) + Arrays.stream(c.getDeclaredConstructors()) <ide> .map(constructor -> (Constructor<T>) constructor) <ide> .filter(onlyInject) <ide> .map(con ->
Java
apache-2.0
fb65229f8d9e86b89a38d8b449b66b654a2e2a91
0
mpouttuclarke/cdap,anthcp/cdap,anthcp/cdap,caskdata/cdap,chtyim/cdap,hsaputra/cdap,caskdata/cdap,mpouttuclarke/cdap,hsaputra/cdap,chtyim/cdap,hsaputra/cdap,caskdata/cdap,hsaputra/cdap,caskdata/cdap,chtyim/cdap,mpouttuclarke/cdap,anthcp/cdap,mpouttuclarke/cdap,caskdata/cdap,anthcp/cdap,hsaputra/cdap,chtyim/cdap,chtyim/cdap,caskdata/cdap,chtyim/cdap,anthcp/cdap,mpouttuclarke/cdap
package com.continuuity.logging.appender; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.status.OnConsoleStatusListener; import ch.qos.logback.core.status.StatusManager; import com.google.inject.Inject; import org.slf4j.ILoggerFactory; import org.slf4j.LoggerFactory; import java.util.concurrent.atomic.AtomicBoolean; /** * Creates and sets the logback log appender. */ public class LogAppenderInitializer { private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(LogAppenderInitializer.class); private static final AtomicBoolean initialized = new AtomicBoolean(false); private final LogAppender logAppender; @Inject public LogAppenderInitializer(LogAppender logAppender) { this.logAppender = logAppender; } public void initialize() { initialize(org.slf4j.Logger.ROOT_LOGGER_NAME); } public void initialize(String name) { if (initialized.compareAndSet(false, true)) { // Already initialized. LOG.trace("Log appender {} is already initialized.", logAppender.getName()); return; } LOG.info("Initializing log appender {}", logAppender.getName()); ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); // TODO: fix logging issue in mapreduce: ENG-3279 if (!(loggerFactory instanceof LoggerContext)) { LOG.warn("LoggerFactory is not a logback LoggerContext. No log appender is added."); return; } LoggerContext loggerContext = (LoggerContext) loggerFactory; // Display any errors during initialization of log appender to console StatusManager statusManager = loggerContext.getStatusManager(); OnConsoleStatusListener onConsoleListener = new OnConsoleStatusListener(); statusManager.add(onConsoleListener); logAppender.setContext(loggerContext); logAppender.start(); Logger rootLogger = loggerContext.getLogger(name); rootLogger.addAppender(logAppender); } }
watchdog/src/main/java/com/continuuity/logging/appender/LogAppenderInitializer.java
package com.continuuity.logging.appender; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.core.status.OnConsoleStatusListener; import ch.qos.logback.core.status.StatusManager; import com.google.inject.Inject; import org.slf4j.ILoggerFactory; import org.slf4j.LoggerFactory; /** * Creates and sets the logback log appender. */ public class LogAppenderInitializer { private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(LogAppenderInitializer.class); private final LogAppender logAppender; @Inject public LogAppenderInitializer(LogAppender logAppender) { this.logAppender = logAppender; } public void initialize() { initialize(org.slf4j.Logger.ROOT_LOGGER_NAME); } public void initialize(String name) { LOG.info("Initializing log appender {}", logAppender.getName()); ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory(); // TODO: fix logging issue in mapreduce: ENG-3279 if (!(loggerFactory instanceof LoggerContext)) { LOG.warn("LoggerFactory is not a logback LoggerContext. No log appender is added."); return; } LoggerContext loggerContext = (LoggerContext) loggerFactory; // Display any errors during initialization of log appender to console StatusManager statusManager = loggerContext.getStatusManager(); OnConsoleStatusListener onConsoleListener = new OnConsoleStatusListener(); statusManager.add(onConsoleListener); logAppender.setContext(loggerContext); logAppender.start(); Logger rootLogger = loggerContext.getLogger(name); rootLogger.addAppender(logAppender); } }
Making sure that Log Appender gets initialized only once.
watchdog/src/main/java/com/continuuity/logging/appender/LogAppenderInitializer.java
Making sure that Log Appender gets initialized only once.
<ide><path>atchdog/src/main/java/com/continuuity/logging/appender/LogAppenderInitializer.java <ide> import org.slf4j.ILoggerFactory; <ide> import org.slf4j.LoggerFactory; <ide> <add>import java.util.concurrent.atomic.AtomicBoolean; <add> <ide> /** <ide> * Creates and sets the logback log appender. <ide> */ <ide> public class LogAppenderInitializer { <ide> private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(LogAppenderInitializer.class); <add> private static final AtomicBoolean initialized = new AtomicBoolean(false); <ide> private final LogAppender logAppender; <ide> <ide> @Inject <ide> } <ide> <ide> public void initialize(String name) { <add> if (initialized.compareAndSet(false, true)) { <add> // Already initialized. <add> LOG.trace("Log appender {} is already initialized.", logAppender.getName()); <add> return; <add> } <add> <ide> LOG.info("Initializing log appender {}", logAppender.getName()); <ide> <ide> ILoggerFactory loggerFactory = LoggerFactory.getILoggerFactory();
Java
agpl-3.0
ad754f55996e44df9c50b7bf89b990a8d1cc5e53
0
jaytaylor/sql-layer,relateiq/sql-layer,shunwang/sql-layer-1,wfxiang08/sql-layer-1,relateiq/sql-layer,jaytaylor/sql-layer,qiuyesuifeng/sql-layer,ngaut/sql-layer,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,wfxiang08/sql-layer-1,shunwang/sql-layer-1,qiuyesuifeng/sql-layer,qiuyesuifeng/sql-layer,shunwang/sql-layer-1,ngaut/sql-layer,jaytaylor/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,relateiq/sql-layer,shunwang/sql-layer-1,relateiq/sql-layer,ngaut/sql-layer,jaytaylor/sql-layer
/** * Copyright (C) 2009-2013 FoundationDB, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.foundationdb.sql.pg; import com.foundationdb.server.store.statistics.IndexStatisticsService; import org.junit.Before; import org.junit.Test; import java.io.File; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; /** * This test was created due to the multiple possible plans that were being created as the loader input of a Bloom Filter * Previously this was all done under the assumption of an indexScan being the only possible loader * Because of this we now depend on the rowtype of the input stream to create the collator * * In order to guarantee the use of the Bloom Filter a stats.yaml file is loaded, the same used in operator/coi-index * Also the optimizer.scaleIndexStatistics property has to be set to false in order to allow these stats to have an effect * on the perceived row counts on each side of the join */ public class PostgresServerBloomFilterIT extends PostgresServerITBase{ private static final String DIRECTORY_LOCATION = "src/test/resources/com/foundationdb/sql/optimizer/operator/coi-index/"; private static final String STATS_FILE = DIRECTORY_LOCATION + "stats.yaml"; private static final String SQL = "SELECT items.sku FROM items, categories WHERE items.sku = categories.sku AND categories.cat = 1 ORDER BY items.sku"; Connection connection; private static final String SCHEMA_SETUP[] = { "CREATE TABLE customers(cid int NOT NULL,PRIMARY KEY(cid), name varchar(32) NOT NULL);", "CREATE INDEX name ON customers(name);", "CREATE TABLE orders(oid int NOT NULL,PRIMARY KEY(oid),cid int NOT NULL,order_date date NOT NULL, GROUPING FOREIGN KEY (cid) REFERENCES customers(cid));", "CREATE INDEX \"__akiban_fk_0\" ON orders(cid);", "CREATE INDEX order_date ON orders(order_date);", "CREATE TABLE items(iid int NOT NULL,PRIMARY KEY(iid),oid int NOT NULL, sku varchar(32) NOT NULL, quan int NOT NULL,GROUPING FOREIGN KEY (oid) REFERENCES orders(oid));", "CREATE INDEX sku ON items(sku);", "CREATE TABLE handling (hid int NOT NULL, PRIMARY KEY(hid), iid int NOT NULL, GROUPING FOREIGN KEY (iid) REFERENCES items(iid));", "CREATE TABLE categories(cat int NOT NULL, sku varchar(32) NOT NULL);", "CREATE UNIQUE INDEX cat_sku ON categories(cat,sku);", "INSERT INTO items values(1,2,\'car\', 10),(3,4,\'chair\',11),(4,5,\'desk\',12);", "INSERT INTO categories values(1,\'bug\'),(1,\'chair\'),(2,\'desk\'),(15,\'nothing\');" }; @Override protected Map<String, String> startupConfigProperties() { Map<String,String> map = new HashMap<>(super.startupConfigProperties()); map.put("optimizer.scaleIndexStatistics", "false"); return map; } @Before public void setup() throws Exception{ connection = getConnection(); for(String sqlStatement : SCHEMA_SETUP) { connection.createStatement().execute(sqlStatement); } txnService().run(session(), new Callable<Void>() { @Override public Void call() throws Exception { File file = new File(STATS_FILE); if (file.exists()) { IndexStatisticsService service = serviceManager().getServiceByClass(IndexStatisticsService.class); service.loadIndexStatistics(session(), SCHEMA_NAME, file); } return null; } }); } @Test public void test() throws Exception { Statement statement = connection.createStatement(); ResultSet planRS = statement.executeQuery("EXPLAIN " + SQL); boolean found = false; while (!found && planRS.next()) { if (((String) planRS.getObject(1)).contains("Using_BloomFilter")) found = true; } ResultSet outputRS = statement.executeQuery( SQL); outputRS.next(); assert(outputRS.getObject(1).equals("chair")); assert(!outputRS.next()); } }
src/test/java/com/foundationdb/sql/pg/PostgresServerBloomFilterIT.java
/** * Copyright (C) 2009-2013 FoundationDB, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.foundationdb.sql.pg; import com.foundationdb.server.store.statistics.IndexStatisticsService; import org.junit.Before; import org.junit.Test; import java.io.File; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; /** * This test was created due to the multiple possible plans that were being created as the loader input of a Bloom Filter * Previously this was all done under the assumption of an indexScan being the only possible loader * Because of this we now depend on the rowtype of the input stream to create the collator * * In order to guarantee the use of the Bloom Filter a stats.yaml file is loaded, the same used in operator/coi-index * Also the optimizer.scaleIndexStatistics property has to be set to false in order to allow these stats to have an effect * on the perceived row counts on each side of the join */ public class PostgresServerBloomFilterIT extends PostgresServerITBase{ private static final String DIRECTORY_LOCATION = "src/test/resources/com/foundationdb/sql/optimizer/operator/coi-index/"; private static final String STATS_FILE = DIRECTORY_LOCATION + "stats.yaml"; private static final String SQL = "SELECT items.sku FROM items, categories WHERE items.sku = categories.sku AND categories.cat = 1 ORDER BY items.sku"; Connection connection; private static final String SCHEMA_SETUP[] = { "CREATE TABLE customers(cid int NOT NULL,PRIMARY KEY(cid), name varchar(32) NOT NULL);", "CREATE INDEX name ON customers(name);", "CREATE TABLE orders(oid int NOT NULL,PRIMARY KEY(oid),cid int NOT NULL,order_date date NOT NULL, GROUPING FOREIGN KEY (cid) REFERENCES customers(cid));", "CREATE INDEX \"__akiban_fk_0\" ON orders(cid);", "CREATE INDEX order_date ON orders(order_date);", "CREATE TABLE items(iid int NOT NULL,PRIMARY KEY(iid),oid int NOT NULL, sku varchar(32) NOT NULL, quan int NOT NULL,GROUPING FOREIGN KEY (oid) REFERENCES orders(oid));", "CREATE INDEX sku ON items(sku);", "CREATE TABLE handling (hid int NOT NULL, PRIMARY KEY(hid), iid int NOT NULL, GROUPING FOREIGN KEY (iid) REFERENCES items(iid));", "CREATE TABLE categories(cat int NOT NULL, sku varchar(32) NOT NULL);", "CREATE UNIQUE INDEX cat_sku ON categories(cat,sku);", "INSERT INTO items values(1,2,\'car\', 10),(3,4,\'chair\',11),(4,5,\'desk\',12);", "INSERT INTO categories values(1,\'bug\'),(1,\'chair\'),(2,\'desk\'),(15,\'nothing\');" }; @Override protected Map<String, String> startupConfigProperties() { Map<String,String> map = new HashMap<>(super.startupConfigProperties()); map.put("optimizer.scaleIndexStatistics", "false"); return map; } @Before public void setup() throws Exception{ connection = getConnection(); for(String sqlStatement : SCHEMA_SETUP) { connection.createStatement().execute(sqlStatement); } txnService().run(session(), new Callable<Void>() { @Override public Void call() throws Exception { File file = new File(STATS_FILE); if (file.exists()) { IndexStatisticsService service = serviceManager().getServiceByClass(IndexStatisticsService.class); service.loadIndexStatistics(session(), SCHEMA_NAME, file); } return null; } }); } @Test public void test() throws Exception { Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery("EXPLAIN " + SQL); boolean found = false; while (!found && rs.next()) { if (((String) rs.getObject(1)).contains("Using_BloomFilter")) found = true; } statement.execute( SQL); assert(found == true); } }
Testing output for correctness added simple test to make sure output is correct
src/test/java/com/foundationdb/sql/pg/PostgresServerBloomFilterIT.java
Testing output for correctness
<ide><path>rc/test/java/com/foundationdb/sql/pg/PostgresServerBloomFilterIT.java <ide> @Test <ide> public void test() throws Exception { <ide> Statement statement = connection.createStatement(); <del> ResultSet rs = statement.executeQuery("EXPLAIN " + SQL); <add> ResultSet planRS = statement.executeQuery("EXPLAIN " + SQL); <ide> boolean found = false; <del> while (!found && rs.next()) { <del> if (((String) rs.getObject(1)).contains("Using_BloomFilter")) <add> while (!found && planRS.next()) { <add> if (((String) planRS.getObject(1)).contains("Using_BloomFilter")) <ide> found = true; <ide> } <del> statement.execute( SQL); <del> assert(found == true); <add> ResultSet outputRS = statement.executeQuery( SQL); <add> outputRS.next(); <add> assert(outputRS.getObject(1).equals("chair")); <add> assert(!outputRS.next()); <ide> } <ide> }
Java
apache-2.0
38f4277cb8a23a816d12a24ee785999d1e62fa21
0
rwl/requestfactory-addon
package org.springframework.roo.support.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSSerializer; /** * Utilities related to DOM and XML usage. * * @author Stefan Schmidt * @author Ben Alex * @author Alan Stewart * @since 1.0 */ public final class XmlUtils { private static final Map<String, XPathExpression> compiledExpressionCache = new HashMap<String, XPathExpression>(); private static final XPath xpath = XPathFactory.newInstance().newXPath(); private static final TransformerFactory transformerFactory = TransformerFactory.newInstance(); private static final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); private XmlUtils() { } /** * Read an XML document from the supplied input stream and return a document. * * @param inputStream the input stream to read from (required). The stream is closed upon completion. * @return a document. */ public static final Document readXml(InputStream inputStream) { Assert.notNull(inputStream, "InputStream required"); try { return factory.newDocumentBuilder().parse(inputStream); } catch (Exception e) { throw new IllegalStateException("Could not open input stream", e); } finally { try { inputStream.close(); } catch (IOException inored) {} } } /** * Write an XML document to the OutputStream provided. This will use the pre-configured Roo provided Transformer. * * @param outputStream the output stream to write to. The stream is closed upon completion. * @param document the document to write. */ public static final void writeXml(OutputStream outputStream, Document document) { writeXml(createIndentingTransformer(), outputStream, document); } /** * Write an XML document to the OutputStream provided. This will use the provided Transformer. * * @param transformer the transformer (can be obtained from XmlUtils.createIndentingTransformer()) * @param outputStream the output stream to write to. The stream is closed upon completion. * @param document the document to write. */ public static final void writeXml(Transformer transformer, OutputStream outputStream, Document document) { Assert.notNull(transformer, "Transformer required"); Assert.notNull(outputStream, "OutputStream required"); Assert.notNull(document, "Document required"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); try { StreamResult streamResult = createUnixStreamResultForEntry(outputStream); transformer.transform(new DOMSource(document), streamResult); } catch (Exception e) { throw new IllegalStateException(e); } finally { try { outputStream.close(); } catch (IOException ignored) { // Do nothing } } } public static void writeFormattedXml(OutputStream outputStream, Document document) { // Note that the "format-pretty-print" DOM configuration parameter can only be set in JDK 1.6+. DOMImplementation domImplementation = document.getImplementation(); if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) { DOMImplementationLS domImplementationLS = null; try { domImplementationLS = (DOMImplementationLS) domImplementation.getFeature("LS", "3.0"); } catch (NoSuchMethodError nsme) { // Fall back to default LS DOMImplementationRegistry registry = null; try { registry = DOMImplementationRegistry.newInstance(); } catch (Exception e) { // DOMImplementationRegistry not available. Falling back to TrAX. writeXml(outputStream, document); return; } if (registry != null) { domImplementationLS = (DOMImplementationLS) registry.getDOMImplementation("LS"); } } if (domImplementationLS != null) { LSSerializer lsSerializer = domImplementationLS.createLSSerializer(); DOMConfiguration domConfiguration = lsSerializer.getDomConfig(); if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) { lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); LSOutput lsOutput = domImplementationLS.createLSOutput(); lsOutput.setEncoding("UTF-8"); lsOutput.setByteStream(outputStream); lsSerializer.write(document, lsOutput); } else { // DOMConfiguration 'format-pretty-print' parameter not available. Falling back to TrAX. writeXml(outputStream, document); } } else { // DOMImplementationLS not available. Falling back to TrAX. writeXml(outputStream, document); } } else { // DOM 3.0 LS and/or DOM 2.0 Core not supported. Falling back to TrAX. writeXml(outputStream, document); } } /** * Compares two DOM {@link Node nodes} by comparing the representations of the nodes as XML strings * * @param node1 the first node * @param node2 the second node * @return true if the XML representation node1 is the same as the XML representation of node2, otherwise false */ public static boolean compareNodes(Node node1, Node node2) { Assert.notNull(node1, "First node required"); Assert.notNull(node2, "Second node required"); String s1 = nodeToString(node1); String s2 = nodeToString(node2); return s1.equals(s2); } /** * Converts a {@link Node node} to an XML string * * @param node the first element * @return the XML String representation of the node, never null */ public static String nodeToString(Node node) { try { StringWriter writer = new StringWriter(); createIndentingTransformer().transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); } catch (TransformerException e) { throw new IllegalStateException(e); } } /** * Creates a {@link StreamResult} by wrapping the given outputStream in an * {@link OutputStreamWriter} that transforms Windows line endings (\r\n) * into Unix line endings (\n) on Windows for consistency with Roo's templates. * * @param outputStream * @return StreamResult * @throws UnsupportedEncodingException */ private static StreamResult createUnixStreamResultForEntry(OutputStream outputStream) throws UnsupportedEncodingException { final Writer writer; if (System.getProperty("line.separator").equals("\r\n")) { writer = new OutputStreamWriter(outputStream, "ISO-8859-1") { public void write(char[] cbuf, int off, int len) throws IOException { for (int i = off; i < off + len; i++) { if (cbuf[i] != '\r' || (i < cbuf.length - 1 && cbuf[i + 1] != '\n')) { super.write(cbuf[i]); } } } public void write(int c) throws IOException { if (c != '\r') super.write(c); } public void write(String str, int off, int len) throws IOException { String orig = str.substring(off, off + len); String filtered = orig.replace("\r\n", "\n"); int lengthDiff = orig.length() - filtered.length(); if (filtered.endsWith("\r")) { super.write(filtered.substring(0, filtered.length() - 1), 0, len - lengthDiff - 1); } else { super.write(filtered, 0, len - lengthDiff); } } }; } else { writer = new OutputStreamWriter(outputStream, "ISO-8859-1"); } return new StreamResult(writer); } /** * Checks in under a given root element whether it can find a child element * which matches the XPath expression supplied. Returns {@link Element} if * exists. * * Please note that the XPath parser used is NOT namespace aware. So if you * want to find a element <beans><sec:http> you need to use the following * XPath expression '/beans/http'. * * @param xPathExpression the xPathExpression (required) * @param root the parent DOM element (required) * @return the Element if discovered (null if not found) */ public static Element findFirstElement(String xPathExpression, Element root) { Node node = findNode(xPathExpression, root); if (node != null && node instanceof Element) { return (Element) node; } return null; } /** * Checks in under a given root element whether it can find a child node * which matches the XPath expression supplied. Returns {@link Node} if * exists. * * Please note that the XPath parser used is NOT namespace aware. So if you * want to find a element <beans><sec:http> you need to use the following * XPath expression '/beans/http'. * * @param xPathExpression the XPath expression (required) * @param root the parent DOM element (required) * @return the Node if discovered (null if not found) */ public static Node findNode(String xPathExpression, Element root) { Assert.hasText(xPathExpression, "XPath expression required"); Assert.notNull(root, "Root element required"); Node node = null; try { XPathExpression expr = compiledExpressionCache.get(xPathExpression); if (expr == null) { expr = xpath.compile(xPathExpression); compiledExpressionCache.put(xPathExpression, expr); } node = (Node) expr.evaluate(root, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate XPath expression", e); } return node; } /** * Checks in under a given root element whether it can find a child element * which matches the name supplied. Returns {@link Element} if exists. * * @param name the Element name (required) * @param root the parent DOM element (required) * @return the Element if discovered */ public static Element findFirstElementByName(String name, Element root) { Assert.hasText(name, "Element name required"); Assert.notNull(root, "Root element required"); return (Element) root.getElementsByTagName(name).item(0); } /** * Checks in under a given root element whether it can find a child element * which matches the XPath expression supplied. The {@link Element} must * exist. Returns {@link Element} if exists. * * Please note that the XPath parser used is NOT namespace aware. So if you * want to find a element <beans><sec:http> you need to use the following * XPath expression '/beans/http'. * * @param xPathExpression the XPath expression (required) * @param root the parent DOM element (required) * @return the Element if discovered (never null; an exception is thrown if cannot be found) */ public static Element findRequiredElement(String xPathExpression, Element root) { Assert.hasText(xPathExpression, "XPath expression required"); Assert.notNull(root, "Root element required"); Element element = findFirstElement(xPathExpression, root); Assert.notNull(element, "Unable to obtain required element '" + xPathExpression + "' from element '" + root + "'"); return element; } /** * Checks in under a given root element whether it can find a child elements * which match the XPath expression supplied. Returns a {@link List} of * {@link Element} if they exist. * * Please note that the XPath parser used is NOT namespace aware. So if you * want to find a element <beans><sec:http> you need to use the following * XPath expression '/beans/http'. * * @param xPathExpression the xPathExpression * @param root the parent DOM element * @return a {@link List} of type {@link Element} if discovered, otherwise an empty list (never null) */ public static List<Element> findElements(String xPathExpression, Element root) { List<Element> elements = new ArrayList<Element>(); NodeList nodes = null; try { XPathExpression expr = compiledExpressionCache.get(xPathExpression); if (expr == null) { expr = xpath.compile(xPathExpression); compiledExpressionCache.put(xPathExpression, expr); } nodes = (NodeList) expr.evaluate(root, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate xpath expression", e); } for (int i = 0, n = nodes.getLength(); i < n; i++) { elements.add((Element) nodes.item(i)); } return elements; } /** * Checks for a given element whether it can find an attribute which matches the * XPath expression supplied. Returns {@link Node} if exists. * * @param xPathExpression the xPathExpression (required) * @param element (required) * @return the Node if discovered (null if not found) */ public static Node findFirstAttribute(String xPathExpression, Element element) { Node attr = null; try { XPathExpression expr = compiledExpressionCache.get(xPathExpression); if (expr == null) { expr = xpath.compile(xPathExpression); compiledExpressionCache.put(xPathExpression, expr); } attr = (Node) expr.evaluate(element, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate xpath expression", e); } return attr; } /** * @return a transformer that indents entries by 4 characters (never null) */ public static final Transformer createIndentingTransformer() { Transformer transformer; try { transformerFactory.setAttribute("indent-number", 4); transformer = transformerFactory.newTransformer(); } catch (Exception e) { throw new IllegalStateException(e); } transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); return transformer; } /** * @return a new document builder (never null) */ public static final DocumentBuilder getDocumentBuilder() { // factory.setNamespaceAware(true); try { return factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } /** * Removes empty text nodes from the specified node * * @param node the element where empty text nodes will be removed */ public static void removeTextNodes(Node node) { if (node == null) { return; } NodeList children = node.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i--) { Node child = children.item(i); switch (child.getNodeType()) { case Node.ELEMENT_NODE: removeTextNodes((Element) child); break; case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: if (!StringUtils.hasText(child.getNodeValue())) { node.removeChild(child); } break; } } } /** * Returns the root element of an addon's configuration file. * * @param clazz which owns the configuration * @param configurationPath the path of the configuration file. * @return the configuration root element */ public static Element getConfiguration(Class<?> clazz, String configurationPath) { InputStream templateInputStream = TemplateUtils.getTemplate(clazz, configurationPath); Assert.notNull(templateInputStream, "Could not acquire " + configurationPath + " file"); Document configurationDocument; try { configurationDocument = getDocumentBuilder().parse(templateInputStream); } catch (Exception e) { throw new IllegalStateException(e); } return configurationDocument.getDocumentElement(); } /** * Returns the root element of an addon's configuration file. * * @param clazz which owns the configuration * @return the configuration root element */ public static Element getConfiguration(Class<?> clazz) { return getConfiguration(clazz, "configuration.xml"); } /** * Converts a XHTML compliant id (used in jspx) to a CSS3 selector spec compliant id. In that * it will replace all '.,:,-' to '_' * * @param proposed Id * @return cleaned up Id */ public static String convertId(String proposed) { return proposed.replaceAll("[:\\.-]", "_"); } /** * Checks the presented element for illegal characters that could cause malformed XML. * * @param element the content of the XML element * @throws IllegalArgumentException if the element is null, has no text or contains illegal characters */ public static void assertElementLegal(String element) { if (!StringUtils.hasText(element)) { throw new IllegalArgumentException("Element required"); } // Note regular expression for legal characters found to be x5 slower in profiling than this approach char[] value = element.toCharArray(); for (int i = 0; i < value.length; i++) { char c = value[i]; if (' ' == c || '*' == c || '>' == c || '<' == c || '!' == c || '@' == c || '%' == c || '^' == c || '?' == c || '(' == c || ')' == c || '~' == c || '`' == c || '{' == c || '}' == c || '[' == c || ']' == c || '|' == c || '\\' == c || '\'' == c || '+' == c) { throw new IllegalArgumentException("Illegal name '" + element + "' (illegal character)"); } } } }
support/src/main/java/org/springframework/roo/support/util/XmlUtils.java
package org.springframework.roo.support.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSSerializer; /** * Utilities related to DOM and XML usage. * * @author Stefan Schmidt * @author Ben Alex * @author Alan Stewart * @since 1.0 */ public final class XmlUtils { private static final Map<String, XPathExpression> compiledExpressionCache = new HashMap<String, XPathExpression>(); private static final XPath xpath = XPathFactory.newInstance().newXPath(); private static final TransformerFactory transformerFactory = TransformerFactory.newInstance(); private static final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); private XmlUtils() { } /** * Read an XML document from the supplied input stream and return a document. * * @param inputStream the input stream to read from (required). The stream is closed upon completion. * @return a document. */ public static final Document readXml(InputStream inputStream) { Assert.notNull(inputStream, "InputStream required"); try { return factory.newDocumentBuilder().parse(inputStream); } catch (Exception e) { throw new IllegalStateException("Could not open input stream", e); } finally { try { inputStream.close(); } catch (IOException inored) {} } } /** * Write an XML document to the OutputStream provided. This will use the pre-configured Roo provided Transformer. * * @param outputStream the output stream to write to. The stream is closed upon completion. * @param document the document to write. */ public static final void writeXml(OutputStream outputStream, Document document) { writeXml(createIndentingTransformer(), outputStream, document); } /** * Write an XML document to the OutputStream provided. This will use the provided Transformer. * * @param transformer the transformer (can be obtained from XmlUtils.createIndentingTransformer()) * @param outputStream the output stream to write to. The stream is closed upon completion. * @param document the document to write. */ public static final void writeXml(Transformer transformer, OutputStream outputStream, Document document) { Assert.notNull(transformer, "Transformer required"); Assert.notNull(outputStream, "OutputStream required"); Assert.notNull(document, "Document required"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); try { StreamResult streamResult = createUnixStreamResultForEntry(outputStream); transformer.transform(new DOMSource(document), streamResult); } catch (Exception e) { throw new IllegalStateException(e); } finally { try { outputStream.close(); } catch (IOException ignored) { // Do nothing } } } public static void writeFormattedXml(OutputStream outputStream, Document document) { // Note that the "format-pretty-print" DOM configuration parameter can only be set in JDK 1.6+. DOMImplementation domImplementation = document.getImplementation(); if (domImplementation.hasFeature("LS", "3.0") && domImplementation.hasFeature("Core", "2.0")) { DOMImplementationLS domImplementationLS = null; try { domImplementationLS = (DOMImplementationLS) domImplementation.getFeature("LS", "3.0"); } catch (NoSuchMethodError nsme) { // Fall back to default LS DOMImplementationRegistry registry = null; try { registry = DOMImplementationRegistry.newInstance(); } catch (Exception e) { // DOMImplementationRegistry not available. Falling back to TrAX. writeXml(outputStream, document); return; } if (registry != null) { domImplementationLS = (DOMImplementationLS) registry.getDOMImplementation("LS"); } } if (domImplementationLS != null) { LSSerializer lsSerializer = domImplementationLS.createLSSerializer(); DOMConfiguration domConfiguration = lsSerializer.getDomConfig(); if (domConfiguration.canSetParameter("format-pretty-print", Boolean.TRUE)) { lsSerializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE); LSOutput lsOutput = domImplementationLS.createLSOutput(); lsOutput.setEncoding("UTF-8"); lsOutput.setByteStream(outputStream); lsSerializer.write(document, lsOutput); } else { // DOMConfiguration 'format-pretty-print' parameter not available. Falling back to TrAX. writeXml(outputStream, document); } } else { // DOMImplementationLS not available. Falling back to TrAX. writeXml(outputStream, document); } } else { // DOM 3.0 LS and/or DOM 2.0 Core not supported. Falling back to TrAX. writeXml(outputStream, document); } } /** * Compares two DOM {@link Node nodes} by comparing the representations of the nodes as XML strings * * @param node1 the first node * @param node2 the second node * @return true if the XML representation node1 is the same as the XML representation of node2, otherwise false */ public static boolean compareNodes(Node node1, Node node2) { Assert.notNull(node1, "First node required"); Assert.notNull(node2, "Second node required"); String s1 = nodeToString(node1); String s2 = nodeToString(node2); return s1.equals(s2); } /** * Converts a {@link Node node} to an XML string * * @param node the first element * @return the XML String representation of the node, never null */ public static String nodeToString(Node node) { try { StringWriter writer = new StringWriter(); createIndentingTransformer().transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); } catch (TransformerException e) { throw new IllegalStateException(e); } } /** * Creates a {@link StreamResult} by wrapping the given outputStream in an * {@link OutputStreamWriter} that transforms Windows line endings (\r\n) * into Unix line endings (\n) on Windows for consistency with Roo's templates. * * @param outputStream * @return StreamResult * @throws UnsupportedEncodingException */ private static StreamResult createUnixStreamResultForEntry(OutputStream outputStream) throws UnsupportedEncodingException { final Writer writer; if (System.getProperty("line.separator").equals("\r\n")) { writer = new OutputStreamWriter(outputStream, "ISO-8859-1") { public void write(char[] cbuf, int off, int len) throws IOException { for (int i = off; i < off + len; i++) { if (cbuf[i] != '\r' || (i < cbuf.length - 1 && cbuf[i + 1] != '\n')) { super.write(cbuf[i]); } } } public void write(int c) throws IOException { if (c != '\r') super.write(c); } public void write(String str, int off, int len) throws IOException { String orig = str.substring(off, off + len); String filtered = orig.replace("\r\n", "\n"); int lengthDiff = orig.length() - filtered.length(); if (filtered.endsWith("\r")) { super.write(filtered.substring(0, filtered.length() - 1), 0, len - lengthDiff - 1); } else { super.write(filtered, 0, len - lengthDiff); } } }; } else { writer = new OutputStreamWriter(outputStream, "ISO-8859-1"); } return new StreamResult(writer); } /** * Checks in under a given root element whether it can find a child element * which matches the XPath expression supplied. Returns {@link Element} if * exists. * * Please note that the XPath parser used is NOT namespace aware. So if you * want to find a element <beans><sec:http> you need to use the following * XPath expression '/beans/http'. * * @param xPathExpression the xPathExpression (required) * @param root the parent DOM element (required) * @return the Element if discovered (null if not found) */ public static Element findFirstElement(String xPathExpression, Element root) { Node node = findNode(xPathExpression, root); if (node != null && node instanceof Element) { return (Element) node; } return null; } /** * Checks in under a given root element whether it can find a child node * which matches the XPath expression supplied. Returns {@link Node} if * exists. * * Please note that the XPath parser used is NOT namespace aware. So if you * want to find a element <beans><sec:http> you need to use the following * XPath expression '/beans/http'. * * @param xPathExpression the XPath expression (required) * @param root the parent DOM element (required) * @return the Node if discovered (null if not found) */ public static Node findNode(String xPathExpression, Element root) { Assert.hasText(xPathExpression, "XPath expression required"); Assert.notNull(root, "Root element required"); Node node = null; try { XPathExpression expr = compiledExpressionCache.get(xPathExpression); if (expr == null) { expr = xpath.compile(xPathExpression); compiledExpressionCache.put(xPathExpression, expr); } node = (Node) expr.evaluate(root, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate XPath expression", e); } return node; } /** * Checks in under a given root element whether it can find a child element * which matches the name supplied. Returns {@link Element} if exists. * * @param name the Element name (required) * @param root the parent DOM element (required) * @return the Element if discovered */ public static Element findFirstElementByName(String name, Element root) { Assert.hasText(name, "Element name required"); Assert.notNull(root, "Root element required"); return (Element) root.getElementsByTagName(name).item(0); } /** * Checks in under a given root element whether it can find a child element * which matches the XPath expression supplied. The {@link Element} must * exist. Returns {@link Element} if exists. * * Please note that the XPath parser used is NOT namespace aware. So if you * want to find a element <beans><sec:http> you need to use the following * XPath expression '/beans/http'. * * @param xPathExpression the XPath expression (required) * @param root the parent DOM element (required) * @return the Element if discovered (never null; an exception is thrown if cannot be found) */ public static Element findRequiredElement(String xPathExpression, Element root) { Assert.hasText(xPathExpression, "XPath expression required"); Assert.notNull(root, "Root element required"); Element element = findFirstElement(xPathExpression, root); Assert.notNull(element, "Unable to obtain required element '" + xPathExpression + "' from element '" + root + "'"); return element; } /** * Checks in under a given root element whether it can find a child elements * which match the XPath expression supplied. Returns a {@link List} of * {@link Element} if they exist. * * Please note that the XPath parser used is NOT namespace aware. So if you * want to find a element <beans><sec:http> you need to use the following * XPath expression '/beans/http'. * * @param xPathExpression the xPathExpression * @param root the parent DOM element * @return a {@link List} of type {@link Element} if discovered, otherwise an empty list (never null) */ public static List<Element> findElements(String xPathExpression, Element root) { List<Element> elements = new ArrayList<Element>(); NodeList nodes = null; try { XPathExpression expr = compiledExpressionCache.get(xPathExpression); if (expr == null) { expr = xpath.compile(xPathExpression); compiledExpressionCache.put(xPathExpression, expr); } nodes = (NodeList) expr.evaluate(root, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate xpath expression", e); } for (int i = 0, n = nodes.getLength(); i < n; i++) { elements.add((Element) nodes.item(i)); } return elements; } /** * Checks for a given element whether it can find an attribute which matches the * XPath expression supplied. Returns {@link Node} if exists. * * @param xPathExpression the xPathExpression (required) * @param element (required) * @return the Node if discovered (null if not found) */ public static Node findFirstAttribute(String xPathExpression, Element element) { Node attr = null; try { XPathExpression expr = compiledExpressionCache.get(xPathExpression); if (expr == null) { expr = xpath.compile(xPathExpression); compiledExpressionCache.put(xPathExpression, expr); } attr = (Node) expr.evaluate(element, XPathConstants.NODE); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate xpath expression", e); } return attr; } /** * @return a transformer that indents entries by 4 characters (never null) */ public static final Transformer createIndentingTransformer() { Transformer transformer; try { transformerFactory.setAttribute("indent-number", 4); transformer = transformerFactory.newTransformer(); } catch (Exception e) { throw new IllegalStateException(e); } transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); return transformer; } /** * @return a new document builder (never null) */ public static final DocumentBuilder getDocumentBuilder() { // factory.setNamespaceAware(true); try { return factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException(e); } } /** * Removes empty text nodes from the specified node * * @param node the element where empty text nodes will be removed */ public static void removeTextNodes(Node node) { if (node == null) { return; } NodeList children = node.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i--) { Node child = children.item(i); switch (child.getNodeType()) { case Node.ELEMENT_NODE: removeTextNodes((Element) child); break; case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: if (!StringUtils.hasText(child.getNodeValue())) { node.removeChild(child); } break; } } } /** * Returns the root element of an addon's configuration file. * * @param clazz which owns the configuration * @param configurationPath the path of the configuration file. * @return the configuration root element */ public static Element getConfiguration(Class<?> clazz, String configurationPath) { InputStream templateInputStream = TemplateUtils.getTemplate(clazz, configurationPath); Assert.notNull(templateInputStream, "Could not acquire " + configurationPath + " file"); Document configurationDocument; try { configurationDocument = getDocumentBuilder().parse(templateInputStream); } catch (Exception e) { throw new IllegalStateException(e); } return configurationDocument.getDocumentElement(); } /** * Returns the root element of an addon's configuration file. * * @param clazz which owns the configuration * @return the configuration root element */ public static Element getConfiguration(Class<?> clazz) { return getConfiguration(clazz, "configuration.xml"); } /** * Converts a XHTML compliant id (used in jspx) to a CSS3 selector spec compliant id. In that * it will replace all '.,:,-' to '_' * * @param proposed Id * @return cleaned up Id */ public static String convertId(String proposed) { return proposed.replaceAll("[:\\.-]", "_"); } /** * Checks the presented element for illegal characters that could cause malformed XML. * * @param element the content of the XML element * @throws IllegalArgumentException if the element is null, has no text or contains illegal characters */ public static void assertElementLegal(String element) { if (!StringUtils.hasText(element)) { throw new IllegalArgumentException("Element required"); } // Note regular expression for legal characters found to be x5 slower in profiling than this approach char[] value = element.toCharArray(); for (int i = 0; i < value.length; i++) { char c = value[i]; if (' ' == c || '*' == c || '>' == c || '<' == c || '!' == c || '@' == c || '%' == c || '^' == c || '?' == c || '(' == c || ')' == c || '~' == c || '`' == c || '{' == c || '}' == c || '[' == c || ']' == c || '|' == c || '\\' == c || '\'' == c || '+' == c) { throw new IllegalArgumentException("Illegal name '" + element + "' (illegal character)"); } } } public static String elementToString(Node n) { String name = n.getNodeName(); short type = n.getNodeType(); if (Node.CDATA_SECTION_NODE == type) { return "<![CDATA[" + n.getNodeValue() + "]]&gt;"; } if (name.startsWith("#")) { return ""; } StringBuilder sb = new StringBuilder(); sb.append('<').append(name); NamedNodeMap attrs = n.getAttributes(); if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { Node attr = attrs.item(i); sb.append(' ').append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append("\""); } } String textContent = null; NodeList children = n.getChildNodes(); if (children.getLength() == 0) { if ((textContent = n.getTextContent()) != null && !"".equals(textContent)) { sb.append(textContent).append("</").append(name).append('>'); } else { sb.append("/>"); } } else { sb.append('>'); boolean hasValidChildren = false; for (int i = 0; i < children.getLength(); i++) { String childToString = elementToString(children.item(i)); if (!"".equals(childToString)) { sb.append(childToString); hasValidChildren = true; } } if (!hasValidChildren && ((textContent = n.getTextContent()) != null)) { sb.append(textContent); } sb.append("</").append(name).append('>'); } return sb.toString(); } }
ROO-2360: Enhance the comparability of pom related elements - remove temporary method
support/src/main/java/org/springframework/roo/support/util/XmlUtils.java
ROO-2360: Enhance the comparability of pom related elements - remove temporary method
<ide><path>upport/src/main/java/org/springframework/roo/support/util/XmlUtils.java <ide> import org.w3c.dom.DOMImplementation; <ide> import org.w3c.dom.Document; <ide> import org.w3c.dom.Element; <del>import org.w3c.dom.NamedNodeMap; <ide> import org.w3c.dom.Node; <ide> import org.w3c.dom.NodeList; <ide> import org.w3c.dom.bootstrap.DOMImplementationRegistry; <ide> } <ide> } <ide> } <del> <del> <del> public static String elementToString(Node n) { <del> String name = n.getNodeName(); <del> short type = n.getNodeType(); <del> <del> if (Node.CDATA_SECTION_NODE == type) { <del> return "<![CDATA[" + n.getNodeValue() + "]]&gt;"; <del> } <del> if (name.startsWith("#")) { <del> return ""; <del> } <del> <del> StringBuilder sb = new StringBuilder(); <del> sb.append('<').append(name); <del> <del> NamedNodeMap attrs = n.getAttributes(); <del> if (attrs != null) { <del> for (int i = 0; i < attrs.getLength(); i++) { <del> Node attr = attrs.item(i); <del> sb.append(' ').append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append("\""); <del> } <del> } <del> <del> String textContent = null; <del> NodeList children = n.getChildNodes(); <del> <del> if (children.getLength() == 0) { <del> if ((textContent = n.getTextContent()) != null && !"".equals(textContent)) { <del> sb.append(textContent).append("</").append(name).append('>'); <del> } else { <del> sb.append("/>"); <del> } <del> } else { <del> sb.append('>'); <del> boolean hasValidChildren = false; <del> for (int i = 0; i < children.getLength(); i++) { <del> String childToString = elementToString(children.item(i)); <del> if (!"".equals(childToString)) { <del> sb.append(childToString); <del> hasValidChildren = true; <del> } <del> } <del> <del> if (!hasValidChildren && ((textContent = n.getTextContent()) != null)) { <del> sb.append(textContent); <del> } <del> <del> sb.append("</").append(name).append('>'); <del> } <del> <del> return sb.toString(); <del> } <ide> }
Java
mit
76c25528073e0dbea8d87ec9e948f09cd31b31af
0
weisJ/darklaf,weisJ/darklaf,weisJ/darklaf,weisJ/darklaf
/* * MIT License * * Copyright (c) 2020 Jannis Weis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.weisj.darklaf.platform.windows.ui; import com.github.weisj.darklaf.decorations.CustomTitlePane; import com.github.weisj.darklaf.icons.ScaledIcon; import com.github.weisj.darklaf.icons.ToggleIcon; import com.github.weisj.darklaf.platform.PointerUtil; import com.github.weisj.darklaf.platform.windows.JNIDecorationsWindows; import com.github.weisj.darklaf.util.PropertyKey; import com.github.weisj.darklaf.util.Scale; import sun.awt.SunToolkit; import javax.accessibility.AccessibleContext; import javax.swing.*; import javax.swing.plaf.UIResource; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; /** * @author Konstantin Bulenkov * @author Jannis Weis */ public class WindowsTitlePane extends CustomTitlePane { public static final String KEY_RESIZABLE = "resizable"; public static final String KEY_STATE = "state"; public static final String KEY_ICON_IMAGE = "iconImage"; private static final int PAD = 5; private static final int BAR_HEIGHT = 28; private static final int BUTTON_WIDTH = 46; private static final int ICON_WIDTH = 32; private static final int ICON_SIZE = ICON_WIDTH - 3 * PAD; private final JRootPane rootPane; private final ContainerListener layeredPaneContainerListener = new ContainerListener() { @Override public void componentAdded(final ContainerEvent e) { if (e.getChild() instanceof JMenuBar) { menuBar = getRootPane().getJMenuBar(); //Otherwise, a white bar will appear where the menuBar used to be. menuBar.setPreferredSize(new Dimension(0, 0)); add(menuBar); } if (getRootPane().getJMenuBar() == null && menuBar != null) { remove(menuBar); menuBar = null; } } @Override public void componentRemoved(final ContainerEvent e) { } }; private boolean oldResizable; private PropertyChangeListener propertyChangeListener; private WindowListener windowListener; private ToggleIcon closeIcon; private ToggleIcon maximizeIcon; private ToggleIcon restoreIcon; private ToggleIcon minimizeIcon; private JButton windowIconButton; private JButton closeButton; private JButton maximizeToggleButton; private JButton minimizeButton; private Action closeAction; private Action restoreAction; private Action maximizeAction; private Action minimizeAction; private JLabel titleLabel; private final Window window; private long windowHandle; private JMenuBar menuBar; private final ContainerListener rootPaneContainerListener = new ContainerListener() { @Override public void componentAdded(final ContainerEvent e) { if (e.getChild() instanceof JLayeredPane) { ((JLayeredPane) e.getChild()).addContainerListener(layeredPaneContainerListener); } } @Override public void componentRemoved(final ContainerEvent e) { if (e.getChild() instanceof JLayeredPane) { ((JLayeredPane) e.getChild()).removeContainerListener(layeredPaneContainerListener); } } }; private int state; private Color inactiveBackground; private Color inactiveForeground; private Color activeBackground; private Color activeForeground; private Color border; public WindowsTitlePane(final JRootPane root, final int decorationStyle, final Window window) { this.rootPane = root; this.window = window; rootPane.addContainerListener(rootPaneContainerListener); rootPane.getLayeredPane().addContainerListener(layeredPaneContainerListener); state = -1; oldResizable = true; installSubcomponents(decorationStyle); installDefaults(); setLayout(createLayout()); } private static JButton createButton(final String accessibleName, final Icon icon, final Action action) { return createButton(accessibleName, icon, action, false); } private static JButton createButton(final String accessibleName, final Icon icon, final Action action, final boolean close) { JButton button = new JButton() { @Override public boolean isRolloverEnabled() { return true; } }; if (close) { button.putClientProperty("JButton.shadow.hover", UIManager.getColor("Windows.TitlePane.close.rollOverColor")); button.putClientProperty("JButton.shadow.click", UIManager.getColor("Windows.TitlePane.close.clickColor")); } button.putClientProperty("JButton.noShadowOverwrite", true); button.setFocusable(false); button.setOpaque(true); button.setRolloverEnabled(true); button.putClientProperty("JButton.variant", "fullShadow"); button.putClientProperty("paintActive", Boolean.TRUE); button.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, accessibleName); button.setAction(action); button.setIcon(icon); button.setText(null); return button; } public void uninstall() { uninstallListeners(); uninstallDecorations(); removeAll(); if (menuBar != null) { getRootPane().setJMenuBar(menuBar); } } @Override public Insets getWindowSizeAdjustment() { //Compensate for the insets of the native window peer that include the decorations. Insets insets = window != null && windowHandle != 0 ? window.getInsets() : new Insets(0, 0, 0, 0); insets.set(-insets.top, -insets.left, -insets.bottom, -insets.right); return insets; } private void uninstallListeners() { if (window != null) { window.removeWindowListener(windowListener); window.removePropertyChangeListener(propertyChangeListener); } if (rootPane != null) { rootPane.removeContainerListener(rootPaneContainerListener); rootPane.getLayeredPane().removeContainerListener(layeredPaneContainerListener); } } protected void uninstallDecorations() { if (windowHandle != 0) { JNIDecorationsWindows.uninstallDecorations(windowHandle); windowHandle = 0; } rootPane.removeContainerListener(rootPaneContainerListener); rootPane.getLayeredPane().removeContainerListener(layeredPaneContainerListener); if (menuBar != null) { menuBar.setPreferredSize(null); rootPane.setJMenuBar(menuBar); } } public void install() { if (window != null) { if (!installDecorations()) return; if (window instanceof Frame) { titleLabel.setText(((Frame) window).getTitle()); setState(((Frame) window).getExtendedState()); } else { setState(0); } if (window instanceof Dialog) { titleLabel.setText(((Dialog) window).getTitle()); } determineColors(); setActive(window.isActive()); installListeners(); updateSystemIcon(); } } private boolean installDecorations() { if (window instanceof Dialog || window instanceof Frame) { windowHandle = PointerUtil.getHWND(window); if (windowHandle != 0) { JNIDecorationsWindows.installDecorations(windowHandle); updateResizeBehaviour(); Color color = window.getBackground(); JNIDecorationsWindows.setBackground(windowHandle, color.getRed(), color.getGreen(), color.getBlue()); forceNativeResize(); } else { uninstall(); return false; } } return true; } private void forceNativeResize() { Rectangle bounds = window.getBounds(); Dimension size = bounds.getSize(); Point p = bounds.getLocation(); if (window.isPreferredSizeSet()) { size = window.getPreferredSize(); } else { p.x += size.width / 2; p.y += size.height / 2; } //Resizing triggers #reshapeNativePeer window.setSize(size.width, size.height + 1); window.setSize(size.width, size.height); window.setLocation(p.x - size.width / 2, p.y - size.height / 2); } private void installListeners() { if (window != null) { windowListener = createWindowListener(); window.addWindowListener(windowListener); propertyChangeListener = createWindowPropertyChangeListener(); window.addPropertyChangeListener(propertyChangeListener); } } private WindowListener createWindowListener() { return new WindowsTitlePane.WindowHandler(); } private PropertyChangeListener createWindowPropertyChangeListener() { return new PropertyChangeHandler(); } private void installSubcomponents(final int decorationStyle) { titleLabel = new JLabel(); titleLabel.setHorizontalAlignment(JLabel.LEFT); add(titleLabel); createIcons(); createActions(); createButtons(); if (decorationStyle == JRootPane.FRAME) { windowIconButton = createWindowIcon(); add(windowIconButton); add(minimizeButton); add(maximizeToggleButton); add(closeButton); } else if (decorationStyle == JRootPane.PLAIN_DIALOG || decorationStyle == JRootPane.INFORMATION_DIALOG || decorationStyle == JRootPane.ERROR_DIALOG || decorationStyle == JRootPane.COLOR_CHOOSER_DIALOG || decorationStyle == JRootPane.FILE_CHOOSER_DIALOG || decorationStyle == JRootPane.QUESTION_DIALOG || decorationStyle == JRootPane.WARNING_DIALOG) { add(closeButton); } menuBar = getRootPane().getJMenuBar(); if (menuBar != null) { menuBar.setPreferredSize(new Dimension(0, 0)); add(menuBar); } } private void determineColors() { switch (getWindowDecorationStyle()) { case JRootPane.ERROR_DIALOG: activeBackground = UIManager.getColor("Windows.OptionPane.errorDialog.titlePane.background"); activeForeground = UIManager.getColor("Windows.OptionPane.errorDialog.titlePane.foreground"); break; case JRootPane.QUESTION_DIALOG: case JRootPane.COLOR_CHOOSER_DIALOG: case JRootPane.FILE_CHOOSER_DIALOG: activeBackground = UIManager.getColor("Windows.OptionPane.questionDialog.titlePane.background"); activeForeground = UIManager.getColor("Windows.OptionPane.questionDialog.titlePane.foreground"); break; case JRootPane.WARNING_DIALOG: activeBackground = UIManager.getColor("Windows.OptionPane.warningDialog.titlePane.background"); activeForeground = UIManager.getColor("Windows.OptionPane.warningDialog.titlePane.foreground"); break; default: //JRootPane.Frame activeBackground = UIManager.getColor("Windows.TitlePane.background"); activeForeground = UIManager.getColor("Windows.TitlePane.foreground"); break; } inactiveBackground = UIManager.getColor("Windows.TitlePane.inactiveBackground"); inactiveForeground = UIManager.getColor("Windows.TitlePane.inactiveForeground"); border = UIManager.getColor("Windows.TitlePane.borderColor"); } private void installDefaults() { setFont(UIManager.getFont("InternalFrame.titleFont", getLocale())); } protected JButton createWindowIcon() { windowIconButton = new JButton(); windowIconButton.putClientProperty("JButton.noShadowOverwrite", true); windowIconButton.setComponentPopupMenu(createMenu()); windowIconButton.putClientProperty("JButton.variant", "onlyLabel"); windowIconButton.addActionListener(e -> windowIconButton .getComponentPopupMenu() .show(windowIconButton, windowIconButton.getWidth() / 2, windowIconButton.getHeight() / 2)); windowIconButton.setFocusable(false); windowIconButton.setBorderPainted(false); return windowIconButton; } private JPopupMenu createMenu() { JPopupMenu menu = new JPopupMenu(); if (getWindowDecorationStyle() == JRootPane.FRAME) { addMenuItems(menu); } return menu; } private void addMenuItems(final JPopupMenu menu) { menu.add(new JMenuItem(restoreAction) {{ setDisabledIcon(restoreIcon); }}); menu.add(new JMenuItem(minimizeAction) {{ setDisabledIcon(minimizeIcon); }}); if (Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)) { menu.add(new JMenuItem(maximizeAction) {{ setDisabledIcon(maximizeIcon); }}); } menu.addSeparator(); menu.add(new JMenuItem(closeAction) {{ setDisabledIcon(closeIcon); }}); } private void close() { Window window = getWindow(); if (window != null) { window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); } } private Window getWindow() { return window; } private void minimize() { JNIDecorationsWindows.minimize(windowHandle); } private void maximize() { JNIDecorationsWindows.maximize(windowHandle); } private void restore() { JNIDecorationsWindows.restore(windowHandle); } private void createActions() { closeAction = new CloseAction(); if (getWindowDecorationStyle() == JRootPane.FRAME) { minimizeAction = new MinimizeAction(); restoreAction = new RestoreAction(); maximizeAction = new MaximizeAction(); } } private void createIcons() { minimizeIcon = new ToggleIcon(UIManager.getIcon("Windows.TitlePane.minimize.icon"), UIManager.getIcon("Windows.TitlePane.minimizeInactive.icon")); maximizeIcon = new ToggleIcon(UIManager.getIcon("Windows.TitlePane.maximize.icon"), UIManager.getIcon("Windows.TitlePane.maximizeInactive.icon")); restoreIcon = new ToggleIcon(UIManager.getIcon("Windows.TitlePane.restore.icon"), UIManager.getIcon("Windows.TitlePane.restoreInactive.icon")); closeIcon = new ToggleIcon(UIManager.getIcon("Windows.TitlePane.close.icon"), UIManager.getIcon("Windows.TitlePane.close.icon")); } private void createButtons() { closeButton = createButton("Close", closeIcon, closeAction, true); closeButton.setRolloverIcon(UIManager.getIcon("Windows.TitlePane.closeHover.icon")); if (getWindowDecorationStyle() == JRootPane.FRAME) { minimizeButton = createButton("Iconify", minimizeIcon, minimizeAction); maximizeToggleButton = createButton("Maximize", maximizeIcon, restoreAction); } } private LayoutManager createLayout() { return new TitlePaneLayout(); } private void setActive(final boolean active) { closeIcon.setActive(active); titleLabel.setForeground(active ? activeForeground : inactiveForeground); if (getWindowDecorationStyle() == JRootPane.FRAME) { minimizeIcon.setActive(active); maximizeIcon.setActive(active); restoreIcon.setActive(active); } getRootPane().repaint(); } public void paintComponent(final Graphics g) { if (getFrame() != null) { setState(getFrame().getExtendedState()); } updateResizeBehaviour(); Window window = getWindow(); boolean active = window == null || window.isActive(); int width = getWidth(); int height = getHeight(); Color background = active ? activeBackground : inactiveBackground; g.setColor(background); g.fillRect(0, 0, width, height); if (getWindowDecorationStyle() != JRootPane.NONE && menuBar != null) { g.setColor(border); g.fillRect(0, height - 1, width, 1); } } public JRootPane getRootPane() { return rootPane; } private Frame getFrame() { if (window instanceof Frame) { return (Frame) window; } return null; } private void setState(final int state) { setState(state, false); } protected void updateResizeBehaviour() { boolean res = isResizable(window, rootPane); if (oldResizable != res) { oldResizable = res; JNIDecorationsWindows.setResizable(windowHandle, res); } } private void setState(final int state, final boolean updateRegardless) { Window wnd = getWindow(); if (wnd != null && getWindowDecorationStyle() == JRootPane.FRAME) { if (this.state == state && !updateRegardless) { return; } Frame frame = getFrame(); if (frame != null) { JRootPane rootPane = getRootPane(); if (((state & Frame.MAXIMIZED_BOTH) != 0) && (rootPane.getBorder() == null || (rootPane.getBorder() instanceof UIResource)) && frame.isShowing()) { rootPane.setBorder(null); } if (frame.isResizable()) { if ((state & Frame.MAXIMIZED_BOTH) != 0) { updateToggleButton(restoreAction, restoreIcon); maximizeAction.setEnabled(false); restoreAction.setEnabled(true); } else { updateToggleButton(maximizeAction, maximizeIcon); maximizeAction.setEnabled(true); restoreAction.setEnabled(false); } if (maximizeToggleButton.getParent() == null || minimizeButton.getParent() == null) { add(maximizeToggleButton); add(minimizeButton); revalidate(); repaint(); } maximizeToggleButton.setText(null); } else { maximizeAction.setEnabled(false); restoreAction.setEnabled(false); if (maximizeToggleButton.getParent() != null) { remove(maximizeToggleButton); revalidate(); repaint(); } } } else { // Not contained in a Frame maximizeAction.setEnabled(false); restoreAction.setEnabled(false); minimizeAction.setEnabled(false); remove(maximizeToggleButton); remove(minimizeButton); revalidate(); repaint(); } closeAction.setEnabled(true); this.state = state; } } protected boolean isResizable(final Window window, final JRootPane rootPane) { if (JRootPane.NONE == rootPane.getWindowDecorationStyle()) { return false; } else { if (window instanceof Dialog) { return ((Dialog) window).isResizable(); } else if (window instanceof Frame) { return ((Frame) window).isResizable(); } } return false; } private int getWindowDecorationStyle() { return getRootPane().getWindowDecorationStyle(); } private void updateToggleButton(final Action action, final Icon icon) { maximizeToggleButton.setAction(action); maximizeToggleButton.setIcon(icon); maximizeToggleButton.setText(null); } protected boolean isLeftToRight(final Window window) { return (window == null) ? getRootPane().getComponentOrientation().isLeftToRight() : window.getComponentOrientation().isLeftToRight(); } private void updateSystemIcon() { Window window = getWindow(); if (window == null) { windowIconButton.setIcon(null); return; } List<Image> icons = window.getIconImages(); assert icons != null; Icon systemIcon; if (icons.size() == 0) { systemIcon = UIManager.getIcon("Windows.TitlePane.icon"); } else if (icons.size() == 1) { systemIcon = new ScaledIcon(icons.get(0).getScaledInstance(Scale.scaleWidth(ICON_SIZE), Scale.scaleHeight(ICON_SIZE), Image.SCALE_AREA_AVERAGING)); } else { systemIcon = new ScaledIcon(SunToolkit.getScaledIconImage(icons, Scale.scaleWidth(ICON_SIZE), Scale.scaleHeight(ICON_SIZE)) ); } if (windowIconButton != null) { windowIconButton.setIcon(systemIcon); SwingUtilities.invokeLater(this::repaint); } } private class CloseAction extends AbstractAction { public CloseAction() { super("Close", closeIcon); } public void actionPerformed(final ActionEvent e) { close(); } } private class MinimizeAction extends AbstractAction { public MinimizeAction() { //UIManager.getString("Minimize", getLocale()) super("Minimize", minimizeIcon); } public void actionPerformed(final ActionEvent e) { minimize(); } } private class MaximizeAction extends AbstractAction { public MaximizeAction() { super("Maximize", maximizeIcon); } public void actionPerformed(final ActionEvent e) { maximize(); } } private class RestoreAction extends AbstractAction { public RestoreAction() { super("Restore", restoreIcon); } public void actionPerformed(final ActionEvent e) { restore(); } } private boolean hideTitleBar() { String title = titleLabel.getText(); if (title == null) title = ""; return windowHandle == 0 || (getWindowDecorationStyle() == JRootPane.NONE && menuBar == null && title.length() == 0); } private class TitlePaneLayout implements LayoutManager { public void addLayoutComponent(final String name, final Component c) { } public void removeLayoutComponent(final Component c) { } public Dimension preferredLayoutSize(final Container c) { if (hideTitleBar()) return new Dimension(0, 0); int size = computeHeight(); return new Dimension(size + 1, size + 1); } public Dimension minimumLayoutSize(final Container c) { return preferredLayoutSize(c); } private int computeHeight() { if (hideTitleBar()) return 0; FontMetrics fm = rootPane.getFontMetrics(getFont()); int height = fm.getHeight() + 7; if (menuBar != null) { height = Math.max(height, menuBar.getMinimumSize().height); } return Math.max(BAR_HEIGHT, height); } public void layoutContainer(final Container c) { if (hideTitleBar()) { if (windowIconButton != null) windowIconButton.setBounds(0, 0, 0, 0); if (closeButton != null) closeButton.setBounds(0, 0, 0, 0); if (minimizeButton != null) minimizeButton.setBounds(0, 0, 0, 0); if (maximizeToggleButton != null) maximizeToggleButton.setBounds(0, 0, 0, 0); if (titleLabel != null) titleLabel.setBounds(0, 0, 0, 0); return; } boolean leftToRight = isLeftToRight(window); int w = getWidth(); int x; int start = 0; int y = 0; int height = computeHeight(); int left = 0; int right = 0; if (windowIconButton != null) { int windowButtonWidth = windowIconButton.getIcon() != null ? Math.max(windowIconButton.getIcon().getIconHeight(), windowIconButton.getIcon().getIconWidth()) : ICON_WIDTH; windowButtonWidth = Math.min(ICON_WIDTH, windowButtonWidth); windowIconButton.setBounds(start + PAD / 2, y, windowButtonWidth, height); start += windowButtonWidth + PAD; left = start; } if (menuBar != null) { int menuWidth = getPreferredMenuSize().width; Insets menuInsets = menuBar.getInsets(); menuBar.setBounds(start, y, menuWidth, height + menuInsets.bottom); start += menuWidth + PAD; left += menuWidth; } x = w; if (closeButton != null) { x -= BUTTON_WIDTH; right += BUTTON_WIDTH; closeButton.setBounds(x, y, BUTTON_WIDTH, height); } if (getWindowDecorationStyle() == JRootPane.FRAME) { if (Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)) { if (maximizeToggleButton != null && maximizeToggleButton.getParent() != null) { x -= BUTTON_WIDTH; right += BUTTON_WIDTH; maximizeToggleButton.setBounds(x, y, BUTTON_WIDTH, height); } if (minimizeButton != null && minimizeButton.getParent() != null) { x -= BUTTON_WIDTH; right += BUTTON_WIDTH; minimizeButton.setBounds(x, y, BUTTON_WIDTH, height); } } } start = Math.max(start, PAD); titleLabel.setBounds(start, 0, x - start - PAD, height); if (!leftToRight) { mirror(windowIconButton, w); mirror(menuBar, w); mirror(closeButton, w); mirror(minimizeButton, w); mirror(maximizeToggleButton, w); mirror(titleLabel, w); int tmp = left; left = right; right = tmp; } JNIDecorationsWindows.updateValues(windowHandle, Scale.scaleWidth(left), Scale.scaleWidth(right), Scale.scaleHeight(height)); } private void mirror(final JComponent component, final int w) { if (component != null) { component.setLocation(w - component.getX() - component.getWidth(), component.getY()); } } private Dimension getPreferredMenuSize() { LayoutManager menuBarLayout = menuBar.getLayout(); Dimension size = null; if (menuBarLayout != null) { size = menuBarLayout.preferredLayoutSize(menuBar); } return (size != null) ? size : menuBar.getPreferredSize(); } } protected class PropertyChangeHandler implements PropertyChangeListener { public void propertyChange(final PropertyChangeEvent pce) { String name = pce.getPropertyName(); if (KEY_RESIZABLE.equals(name) || KEY_STATE.equals(name)) { Frame frame = getFrame(); if (frame != null) { setState(frame.getExtendedState(), true); } if (KEY_RESIZABLE.equals(name)) { JNIDecorationsWindows.setResizable(windowHandle, Boolean.TRUE.equals(pce.getNewValue())); getRootPane().repaint(); } } else if (PropertyKey.TITLE.equals(name)) { titleLabel.setText(pce.getNewValue() == null ? "" : pce.getNewValue().toString()); repaint(); } else if (PropertyKey.COMPONENT_ORIENTATION.equals(name)) { revalidate(); repaint(); } else if (KEY_ICON_IMAGE.equals(name)) { updateSystemIcon(); revalidate(); repaint(); } else if (PropertyKey.BACKGROUND.equals(name) && pce.getNewValue() instanceof Color) { Color color = (Color) pce.getNewValue(); if (color == null) return; JNIDecorationsWindows.setBackground(windowHandle, color.getRed(), color.getGreen(), color.getBlue()); } } } protected class WindowHandler extends WindowAdapter { public void windowActivated(final WindowEvent ev) { setActive(true); } public void windowDeactivated(final WindowEvent ev) { setActive(false); } } }
windows/src/main/java/com/github/weisj/darklaf/platform/windows/ui/WindowsTitlePane.java
/* * MIT License * * Copyright (c) 2020 Jannis Weis * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.weisj.darklaf.platform.windows.ui; import com.github.weisj.darklaf.decorations.CustomTitlePane; import com.github.weisj.darklaf.icons.ScaledIcon; import com.github.weisj.darklaf.icons.ToggleIcon; import com.github.weisj.darklaf.platform.PointerUtil; import com.github.weisj.darklaf.platform.windows.JNIDecorationsWindows; import com.github.weisj.darklaf.util.PropertyKey; import com.github.weisj.darklaf.util.Scale; import sun.awt.SunToolkit; import javax.accessibility.AccessibleContext; import javax.swing.*; import javax.swing.plaf.UIResource; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; /** * @author Konstantin Bulenkov * @author Jannis Weis */ public class WindowsTitlePane extends CustomTitlePane { public static final String KEY_RESIZABLE = "resizable"; public static final String KEY_STATE = "state"; public static final String KEY_ICON_IMAGE = "iconImage"; private static final int PAD = 5; private static final int BAR_HEIGHT = 28; private static final int BUTTON_WIDTH = 46; private static final int ICON_WIDTH = 32; private static final int ICON_SIZE = ICON_WIDTH - 3 * PAD; private final JRootPane rootPane; private final ContainerListener layeredPaneContainerListener = new ContainerListener() { @Override public void componentAdded(final ContainerEvent e) { if (e.getChild() instanceof JMenuBar) { menuBar = getRootPane().getJMenuBar(); //Otherwise, a white bar will appear where the menuBar used to be. menuBar.setPreferredSize(new Dimension(0, 0)); add(menuBar); } if (getRootPane().getJMenuBar() == null && menuBar != null) { remove(menuBar); menuBar = null; } } @Override public void componentRemoved(final ContainerEvent e) { } }; private boolean oldResizable; private PropertyChangeListener propertyChangeListener; private WindowListener windowListener; private ToggleIcon closeIcon; private ToggleIcon maximizeIcon; private ToggleIcon restoreIcon; private ToggleIcon minimizeIcon; private JButton windowIconButton; private JButton closeButton; private JButton maximizeToggleButton; private JButton minimizeButton; private Action closeAction; private Action restoreAction; private Action maximizeAction; private Action minimizeAction; private JLabel titleLabel; private final Window window; private long windowHandle; private JMenuBar menuBar; private final ContainerListener rootPaneContainerListener = new ContainerListener() { @Override public void componentAdded(final ContainerEvent e) { if (e.getChild() instanceof JLayeredPane) { ((JLayeredPane) e.getChild()).addContainerListener(layeredPaneContainerListener); } } @Override public void componentRemoved(final ContainerEvent e) { if (e.getChild() instanceof JLayeredPane) { ((JLayeredPane) e.getChild()).removeContainerListener(layeredPaneContainerListener); } } }; private int state; private Color inactiveBackground; private Color inactiveForeground; private Color activeBackground; private Color activeForeground; private Color border; public WindowsTitlePane(final JRootPane root, final int decorationStyle, final Window window) { this.rootPane = root; this.window = window; rootPane.addContainerListener(rootPaneContainerListener); rootPane.getLayeredPane().addContainerListener(layeredPaneContainerListener); state = -1; oldResizable = true; installSubcomponents(decorationStyle); installDefaults(); setLayout(createLayout()); } private static JButton createButton(final String accessibleName, final Icon icon, final Action action) { return createButton(accessibleName, icon, action, false); } private static JButton createButton(final String accessibleName, final Icon icon, final Action action, final boolean close) { JButton button = new JButton() { @Override public boolean isRolloverEnabled() { return true; } }; if (close) { button.putClientProperty("JButton.shadow.hover", UIManager.getColor("Windows.TitlePane.close.rollOverColor")); button.putClientProperty("JButton.shadow.click", UIManager.getColor("Windows.TitlePane.close.clickColor")); } button.putClientProperty("JButton.noShadowOverwrite", true); button.setFocusable(false); button.setOpaque(true); button.setRolloverEnabled(true); button.putClientProperty("JButton.variant", "fullShadow"); button.putClientProperty("paintActive", Boolean.TRUE); button.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, accessibleName); button.setAction(action); button.setIcon(icon); button.setText(null); return button; } public void uninstall() { uninstallListeners(); uninstallDecorations(); removeAll(); if (menuBar != null) { getRootPane().setJMenuBar(menuBar); } } @Override public Insets getWindowSizeAdjustment() { //Compensate for the insets of the native window peer that include the decorations. Insets insets = window != null && windowHandle != 0 ? window.getInsets() : new Insets(0, 0, 0, 0); insets.set(-insets.top, -insets.left, -insets.bottom, -insets.right); return insets; } private void uninstallListeners() { if (window != null) { window.removeWindowListener(windowListener); window.removePropertyChangeListener(propertyChangeListener); } if (rootPane != null) { rootPane.removeContainerListener(rootPaneContainerListener); rootPane.getLayeredPane().removeContainerListener(layeredPaneContainerListener); } } protected void uninstallDecorations() { if (windowHandle != 0) { JNIDecorationsWindows.uninstallDecorations(windowHandle); windowHandle = 0; } rootPane.removeContainerListener(rootPaneContainerListener); rootPane.getLayeredPane().removeContainerListener(layeredPaneContainerListener); if (menuBar != null) { menuBar.setPreferredSize(null); rootPane.setJMenuBar(menuBar); } } public void install() { if (window != null) { if (!installDecorations()) return; if (window instanceof Frame) { titleLabel.setText(((Frame) window).getTitle()); setState(((Frame) window).getExtendedState()); } else { setState(0); } if (window instanceof Dialog) { titleLabel.setText(((Dialog) window).getTitle()); } determineColors(); setActive(window.isActive()); installListeners(); updateSystemIcon(); } } private boolean installDecorations() { if (window instanceof Dialog || window instanceof Frame) { windowHandle = PointerUtil.getHWND(window); if (windowHandle != 0) { JNIDecorationsWindows.installDecorations(windowHandle); updateResizeBehaviour(); Color color = window.getBackground(); JNIDecorationsWindows.setBackground(windowHandle, color.getRed(), color.getGreen(), color.getBlue()); forceNativeResize(); } else { uninstall(); return false; } } return true; } private void forceNativeResize() { Rectangle bounds = window.getBounds(); Dimension size = bounds.getSize(); Point p = bounds.getLocation(); if (window.isPreferredSizeSet()) { size = window.getPreferredSize(); } else { p.x += size.width / 2; p.y += size.height / 2; } //Resizing triggers #reshapeNativePeer window.setSize(size.width, size.height + 1); window.setSize(size.width, size.height); window.setLocation(p.x - size.width / 2, p.y - size.height / 2); } private void installListeners() { if (window != null) { windowListener = createWindowListener(); window.addWindowListener(windowListener); propertyChangeListener = createWindowPropertyChangeListener(); window.addPropertyChangeListener(propertyChangeListener); } } private WindowListener createWindowListener() { return new WindowsTitlePane.WindowHandler(); } private PropertyChangeListener createWindowPropertyChangeListener() { return new PropertyChangeHandler(); } private void installSubcomponents(final int decorationStyle) { titleLabel = new JLabel(); titleLabel.setHorizontalAlignment(JLabel.LEFT); add(titleLabel); createIcons(); createActions(); createButtons(); if (decorationStyle == JRootPane.FRAME) { windowIconButton = createWindowIcon(); add(windowIconButton); add(minimizeButton); add(maximizeToggleButton); add(closeButton); } else if (decorationStyle == JRootPane.PLAIN_DIALOG || decorationStyle == JRootPane.INFORMATION_DIALOG || decorationStyle == JRootPane.ERROR_DIALOG || decorationStyle == JRootPane.COLOR_CHOOSER_DIALOG || decorationStyle == JRootPane.FILE_CHOOSER_DIALOG || decorationStyle == JRootPane.QUESTION_DIALOG || decorationStyle == JRootPane.WARNING_DIALOG) { add(closeButton); } menuBar = getRootPane().getJMenuBar(); if (menuBar != null) { menuBar.setPreferredSize(new Dimension(0, 0)); add(menuBar); } } private void determineColors() { switch (getWindowDecorationStyle()) { case JRootPane.ERROR_DIALOG: activeBackground = UIManager.getColor("Windows.OptionPane.errorDialog.titlePane.background"); activeForeground = UIManager.getColor("Windows.OptionPane.errorDialog.titlePane.foreground"); break; case JRootPane.QUESTION_DIALOG: case JRootPane.COLOR_CHOOSER_DIALOG: case JRootPane.FILE_CHOOSER_DIALOG: activeBackground = UIManager.getColor("Windows.OptionPane.questionDialog.titlePane.background"); activeForeground = UIManager.getColor("Windows.OptionPane.questionDialog.titlePane.foreground"); break; case JRootPane.WARNING_DIALOG: activeBackground = UIManager.getColor("Windows.OptionPane.warningDialog.titlePane.background"); activeForeground = UIManager.getColor("Windows.OptionPane.warningDialog.titlePane.foreground"); break; default: //JRootPane.Frame activeBackground = UIManager.getColor("Windows.TitlePane.background"); activeForeground = UIManager.getColor("Windows.TitlePane.foreground"); break; } inactiveBackground = UIManager.getColor("Windows.TitlePane.inactiveBackground"); inactiveForeground = UIManager.getColor("Windows.TitlePane.inactiveForeground"); border = UIManager.getColor("Windows.TitlePane.borderColor"); } private void installDefaults() { setFont(UIManager.getFont("InternalFrame.titleFont", getLocale())); } protected JButton createWindowIcon() { windowIconButton = new JButton(); windowIconButton.putClientProperty("JButton.noShadowOverwrite", true); windowIconButton.setComponentPopupMenu(createMenu()); windowIconButton.putClientProperty("JButton.variant", "onlyLabel"); windowIconButton.addActionListener(e -> windowIconButton .getComponentPopupMenu() .show(windowIconButton, windowIconButton.getWidth() / 2, windowIconButton.getHeight() / 2)); windowIconButton.setFocusable(false); windowIconButton.setBorderPainted(false); return windowIconButton; } private JPopupMenu createMenu() { JPopupMenu menu = new JPopupMenu(); if (getWindowDecorationStyle() == JRootPane.FRAME) { addMenuItems(menu); } return menu; } private void addMenuItems(final JPopupMenu menu) { menu.add(new JMenuItem(restoreAction) {{ setDisabledIcon(restoreIcon); }}); menu.add(new JMenuItem(minimizeAction) {{ setDisabledIcon(minimizeIcon); }}); if (Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)) { menu.add(new JMenuItem(maximizeAction) {{ setDisabledIcon(maximizeIcon); }}); } menu.add(new JSeparator()); menu.add(new JMenuItem(closeAction) {{ setDisabledIcon(closeIcon); }}); } private void close() { Window window = getWindow(); if (window != null) { window.dispatchEvent(new WindowEvent(window, WindowEvent.WINDOW_CLOSING)); } } private Window getWindow() { return window; } private void minimize() { JNIDecorationsWindows.minimize(windowHandle); } private void maximize() { JNIDecorationsWindows.maximize(windowHandle); } private void restore() { JNIDecorationsWindows.restore(windowHandle); } private void createActions() { closeAction = new CloseAction(); if (getWindowDecorationStyle() == JRootPane.FRAME) { minimizeAction = new MinimizeAction(); restoreAction = new RestoreAction(); maximizeAction = new MaximizeAction(); } } private void createIcons() { minimizeIcon = new ToggleIcon(UIManager.getIcon("Windows.TitlePane.minimize.icon"), UIManager.getIcon("Windows.TitlePane.minimizeInactive.icon")); maximizeIcon = new ToggleIcon(UIManager.getIcon("Windows.TitlePane.maximize.icon"), UIManager.getIcon("Windows.TitlePane.maximizeInactive.icon")); restoreIcon = new ToggleIcon(UIManager.getIcon("Windows.TitlePane.restore.icon"), UIManager.getIcon("Windows.TitlePane.restoreInactive.icon")); closeIcon = new ToggleIcon(UIManager.getIcon("Windows.TitlePane.close.icon"), UIManager.getIcon("Windows.TitlePane.close.icon")); } private void createButtons() { closeButton = createButton("Close", closeIcon, closeAction, true); closeButton.setRolloverIcon(UIManager.getIcon("Windows.TitlePane.closeHover.icon")); if (getWindowDecorationStyle() == JRootPane.FRAME) { minimizeButton = createButton("Iconify", minimizeIcon, minimizeAction); maximizeToggleButton = createButton("Maximize", maximizeIcon, restoreAction); } } private LayoutManager createLayout() { return new TitlePaneLayout(); } private void setActive(final boolean active) { closeIcon.setActive(active); titleLabel.setForeground(active ? activeForeground : inactiveForeground); if (getWindowDecorationStyle() == JRootPane.FRAME) { minimizeIcon.setActive(active); maximizeIcon.setActive(active); restoreIcon.setActive(active); } getRootPane().repaint(); } public void paintComponent(final Graphics g) { if (getFrame() != null) { setState(getFrame().getExtendedState()); } updateResizeBehaviour(); Window window = getWindow(); boolean active = window == null || window.isActive(); int width = getWidth(); int height = getHeight(); Color background = active ? activeBackground : inactiveBackground; g.setColor(background); g.fillRect(0, 0, width, height); if (getWindowDecorationStyle() != JRootPane.NONE && menuBar != null) { g.setColor(border); g.fillRect(0, height - 1, width, 1); } } public JRootPane getRootPane() { return rootPane; } private Frame getFrame() { if (window instanceof Frame) { return (Frame) window; } return null; } private void setState(final int state) { setState(state, false); } protected void updateResizeBehaviour() { boolean res = isResizable(window, rootPane); if (oldResizable != res) { oldResizable = res; JNIDecorationsWindows.setResizable(windowHandle, res); } } private void setState(final int state, final boolean updateRegardless) { Window wnd = getWindow(); if (wnd != null && getWindowDecorationStyle() == JRootPane.FRAME) { if (this.state == state && !updateRegardless) { return; } Frame frame = getFrame(); if (frame != null) { JRootPane rootPane = getRootPane(); if (((state & Frame.MAXIMIZED_BOTH) != 0) && (rootPane.getBorder() == null || (rootPane.getBorder() instanceof UIResource)) && frame.isShowing()) { rootPane.setBorder(null); } if (frame.isResizable()) { if ((state & Frame.MAXIMIZED_BOTH) != 0) { updateToggleButton(restoreAction, restoreIcon); maximizeAction.setEnabled(false); restoreAction.setEnabled(true); } else { updateToggleButton(maximizeAction, maximizeIcon); maximizeAction.setEnabled(true); restoreAction.setEnabled(false); } if (maximizeToggleButton.getParent() == null || minimizeButton.getParent() == null) { add(maximizeToggleButton); add(minimizeButton); revalidate(); repaint(); } maximizeToggleButton.setText(null); } else { maximizeAction.setEnabled(false); restoreAction.setEnabled(false); if (maximizeToggleButton.getParent() != null) { remove(maximizeToggleButton); revalidate(); repaint(); } } } else { // Not contained in a Frame maximizeAction.setEnabled(false); restoreAction.setEnabled(false); minimizeAction.setEnabled(false); remove(maximizeToggleButton); remove(minimizeButton); revalidate(); repaint(); } closeAction.setEnabled(true); this.state = state; } } protected boolean isResizable(final Window window, final JRootPane rootPane) { if (JRootPane.NONE == rootPane.getWindowDecorationStyle()) { return false; } else { if (window instanceof Dialog) { return ((Dialog) window).isResizable(); } else if (window instanceof Frame) { return ((Frame) window).isResizable(); } } return false; } private int getWindowDecorationStyle() { return getRootPane().getWindowDecorationStyle(); } private void updateToggleButton(final Action action, final Icon icon) { maximizeToggleButton.setAction(action); maximizeToggleButton.setIcon(icon); maximizeToggleButton.setText(null); } protected boolean isLeftToRight(final Window window) { return (window == null) ? getRootPane().getComponentOrientation().isLeftToRight() : window.getComponentOrientation().isLeftToRight(); } private void updateSystemIcon() { Window window = getWindow(); if (window == null) { windowIconButton.setIcon(null); return; } List<Image> icons = window.getIconImages(); assert icons != null; Icon systemIcon; if (icons.size() == 0) { systemIcon = UIManager.getIcon("Windows.TitlePane.icon"); } else if (icons.size() == 1) { systemIcon = new ScaledIcon(icons.get(0).getScaledInstance(Scale.scaleWidth(ICON_SIZE), Scale.scaleHeight(ICON_SIZE), Image.SCALE_AREA_AVERAGING)); } else { systemIcon = new ScaledIcon(SunToolkit.getScaledIconImage(icons, Scale.scaleWidth(ICON_SIZE), Scale.scaleHeight(ICON_SIZE)) ); } if (windowIconButton != null) { windowIconButton.setIcon(systemIcon); SwingUtilities.invokeLater(this::repaint); } } private class CloseAction extends AbstractAction { public CloseAction() { super("Close", closeIcon); } public void actionPerformed(final ActionEvent e) { close(); } } private class MinimizeAction extends AbstractAction { public MinimizeAction() { //UIManager.getString("Minimize", getLocale()) super("Minimize", minimizeIcon); } public void actionPerformed(final ActionEvent e) { minimize(); } } private class MaximizeAction extends AbstractAction { public MaximizeAction() { super("Maximize", maximizeIcon); } public void actionPerformed(final ActionEvent e) { maximize(); } } private class RestoreAction extends AbstractAction { public RestoreAction() { super("Restore", restoreIcon); } public void actionPerformed(final ActionEvent e) { restore(); } } private boolean hideTitleBar() { String title = titleLabel.getText(); if (title == null) title = ""; return windowHandle == 0 || (getWindowDecorationStyle() == JRootPane.NONE && menuBar == null && title.length() == 0); } private class TitlePaneLayout implements LayoutManager { public void addLayoutComponent(final String name, final Component c) { } public void removeLayoutComponent(final Component c) { } public Dimension preferredLayoutSize(final Container c) { if (hideTitleBar()) return new Dimension(0, 0); int size = computeHeight(); return new Dimension(size + 1, size + 1); } public Dimension minimumLayoutSize(final Container c) { return preferredLayoutSize(c); } private int computeHeight() { if (hideTitleBar()) return 0; FontMetrics fm = rootPane.getFontMetrics(getFont()); int height = fm.getHeight() + 7; if (menuBar != null) { height = Math.max(height, menuBar.getMinimumSize().height); } return Math.max(BAR_HEIGHT, height); } public void layoutContainer(final Container c) { if (hideTitleBar()) { if (windowIconButton != null) windowIconButton.setBounds(0, 0, 0, 0); if (closeButton != null) closeButton.setBounds(0, 0, 0, 0); if (minimizeButton != null) minimizeButton.setBounds(0, 0, 0, 0); if (maximizeToggleButton != null) maximizeToggleButton.setBounds(0, 0, 0, 0); if (titleLabel != null) titleLabel.setBounds(0, 0, 0, 0); return; } boolean leftToRight = isLeftToRight(window); int w = getWidth(); int x; int start = 0; int y = 0; int height = computeHeight(); int left = 0; int right = 0; if (windowIconButton != null) { int windowButtonWidth = windowIconButton.getIcon() != null ? Math.max(windowIconButton.getIcon().getIconHeight(), windowIconButton.getIcon().getIconWidth()) : ICON_WIDTH; windowButtonWidth = Math.min(ICON_WIDTH, windowButtonWidth); windowIconButton.setBounds(start + PAD / 2, y, windowButtonWidth, height); start += windowButtonWidth + PAD; left = start; } if (menuBar != null) { int menuWidth = getPreferredMenuSize().width; Insets menuInsets = menuBar.getInsets(); menuBar.setBounds(start, y, menuWidth, height + menuInsets.bottom); start += menuWidth + PAD; left += menuWidth; } x = w; if (closeButton != null) { x -= BUTTON_WIDTH; right += BUTTON_WIDTH; closeButton.setBounds(x, y, BUTTON_WIDTH, height); } if (getWindowDecorationStyle() == JRootPane.FRAME) { if (Toolkit.getDefaultToolkit().isFrameStateSupported(Frame.MAXIMIZED_BOTH)) { if (maximizeToggleButton != null && maximizeToggleButton.getParent() != null) { x -= BUTTON_WIDTH; right += BUTTON_WIDTH; maximizeToggleButton.setBounds(x, y, BUTTON_WIDTH, height); } if (minimizeButton != null && minimizeButton.getParent() != null) { x -= BUTTON_WIDTH; right += BUTTON_WIDTH; minimizeButton.setBounds(x, y, BUTTON_WIDTH, height); } } } start = Math.max(start, PAD); titleLabel.setBounds(start, 0, x - start - PAD, height); if (!leftToRight) { mirror(windowIconButton, w); mirror(menuBar, w); mirror(closeButton, w); mirror(minimizeButton, w); mirror(maximizeToggleButton, w); mirror(titleLabel, w); int tmp = left; left = right; right = tmp; } JNIDecorationsWindows.updateValues(windowHandle, Scale.scaleWidth(left), Scale.scaleWidth(right), Scale.scaleHeight(height)); } private void mirror(final JComponent component, final int w) { if (component != null) { component.setLocation(w - component.getX() - component.getWidth(), component.getY()); } } private Dimension getPreferredMenuSize() { LayoutManager menuBarLayout = menuBar.getLayout(); Dimension size = null; if (menuBarLayout != null) { size = menuBarLayout.preferredLayoutSize(menuBar); } return (size != null) ? size : menuBar.getPreferredSize(); } } protected class PropertyChangeHandler implements PropertyChangeListener { public void propertyChange(final PropertyChangeEvent pce) { String name = pce.getPropertyName(); if (KEY_RESIZABLE.equals(name) || KEY_STATE.equals(name)) { Frame frame = getFrame(); if (frame != null) { setState(frame.getExtendedState(), true); } if (KEY_RESIZABLE.equals(name)) { JNIDecorationsWindows.setResizable(windowHandle, Boolean.TRUE.equals(pce.getNewValue())); getRootPane().repaint(); } } else if (PropertyKey.TITLE.equals(name)) { titleLabel.setText(pce.getNewValue() == null ? "" : pce.getNewValue().toString()); repaint(); } else if (PropertyKey.COMPONENT_ORIENTATION.equals(name)) { revalidate(); repaint(); } else if (KEY_ICON_IMAGE.equals(name)) { updateSystemIcon(); revalidate(); repaint(); } else if (PropertyKey.BACKGROUND.equals(name) && pce.getNewValue() instanceof Color) { Color color = (Color) pce.getNewValue(); if (color == null) return; JNIDecorationsWindows.setBackground(windowHandle, color.getRed(), color.getGreen(), color.getBlue()); } } } protected class WindowHandler extends WindowAdapter { public void windowActivated(final WindowEvent ev) { setActive(true); } public void windowDeactivated(final WindowEvent ev) { setActive(false); } } }
Fixed window popupmenu using wrong separator on windows.
windows/src/main/java/com/github/weisj/darklaf/platform/windows/ui/WindowsTitlePane.java
Fixed window popupmenu using wrong separator on windows.
<ide><path>indows/src/main/java/com/github/weisj/darklaf/platform/windows/ui/WindowsTitlePane.java <ide> setDisabledIcon(maximizeIcon); <ide> }}); <ide> } <del> menu.add(new JSeparator()); <add> menu.addSeparator(); <ide> menu.add(new JMenuItem(closeAction) {{ <ide> setDisabledIcon(closeIcon); <ide> }});
Java
agpl-3.0
194dfef38494d40ca551c69cdfe1877b2a0f4ea7
0
rakam-io/rakam,buremba/rakam,buremba/rakam,rakam-io/rakam,buremba/rakam,rakam-io/rakam,buremba/rakam,buremba/rakam
package org.rakam.aws; import com.amazonaws.services.kinesis.AmazonKinesisClient; import com.amazonaws.services.kinesis.model.PutRecordsRequest; import com.amazonaws.services.kinesis.model.PutRecordsRequestEntry; import com.amazonaws.services.kinesis.model.PutRecordsResult; import com.amazonaws.services.kinesis.model.PutRecordsResultEntry; import com.amazonaws.services.kinesis.model.ResourceNotFoundException; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.inject.name.Named; import io.airlift.log.Logger; import org.apache.avro.generic.FilteredRecordWriter; import org.apache.avro.generic.GenericData; import org.apache.avro.io.BinaryEncoder; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.EncoderFactory; import org.rakam.analysis.JDBCPoolDataSource; import org.rakam.analysis.metadata.Metastore; import org.rakam.analysis.metadata.QueryMetadataStore; import org.rakam.collection.Event; import org.rakam.collection.FieldDependencyBuilder; import org.rakam.plugin.ContinuousQuery; import org.rakam.plugin.EventStore; import org.rakam.presto.analysis.PrestoConfig; import org.rakam.presto.analysis.PrestoQueryExecutor; import org.rakam.report.QueryExecution; import org.rakam.report.QueryResult; import org.rakam.util.KByteArrayOutputStream; import org.rakam.util.QueryFormatter; import org.rakam.util.RakamException; import javax.inject.Inject; import java.nio.ByteBuffer; import java.sql.Connection; import java.sql.SQLException; import java.time.Instant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import static java.lang.String.format; import static org.rakam.aws.KinesisUtils.createAndWaitForStreamToBecomeAvailable; public class AWSKinesisEventStore implements EventStore { private final static Logger LOGGER = Logger.get(AWSKinesisEventStore.class); private final AmazonKinesisClient kinesis; private final AWSConfig config; private static final int BATCH_SIZE = 500; private final S3BulkEventStore bulkClient; private final PrestoQueryExecutor executor; private final PrestoConfig prestoConfig; private final QueryMetadataStore queryMetadataStore; private final JDBCPoolDataSource dataSource; private ThreadLocal<KByteArrayOutputStream> buffer = new ThreadLocal<KByteArrayOutputStream>() { @Override protected KByteArrayOutputStream initialValue() { return new KByteArrayOutputStream(1000000); } }; @Inject public AWSKinesisEventStore(AWSConfig config, Metastore metastore, @Named("report.metadata.store.jdbc") JDBCPoolDataSource dataSource, PrestoQueryExecutor executor, QueryMetadataStore queryMetadataStore, PrestoConfig prestoConfig, FieldDependencyBuilder.FieldDependency fieldDependency) { kinesis = new AmazonKinesisClient(config.getCredentials()); kinesis.setRegion(config.getAWSRegion()); if (config.getKinesisEndpoint() != null) { kinesis.setEndpoint(config.getKinesisEndpoint()); } this.config = config; this.executor = executor; this.prestoConfig = prestoConfig; this.dataSource = dataSource; this.queryMetadataStore = queryMetadataStore; this.bulkClient = new S3BulkEventStore(metastore, config, fieldDependency); } public int[] storeBatchInline(List<Event> events, int offset, int limit) { PutRecordsRequestEntry[] records = new PutRecordsRequestEntry[limit]; for (int i = 0; i < limit; i++) { Event event = events.get(offset + i); PutRecordsRequestEntry putRecordsRequestEntry = new PutRecordsRequestEntry() .withData(getBuffer(event)) .withPartitionKey(event.project() + "|" + event.collection()); records[i] = putRecordsRequestEntry; } try { PutRecordsResult putRecordsResult = kinesis.putRecords(new PutRecordsRequest() .withRecords(records) .withStreamName(config.getEventStoreStreamName())); if (putRecordsResult.getFailedRecordCount() > 0) { int[] failedRecordIndexes = new int[putRecordsResult.getFailedRecordCount()]; int idx = 0; Map<String, Integer> errors = new HashMap<>(); List<PutRecordsResultEntry> recordsResponse = putRecordsResult.getRecords(); for (int i = 0; i < recordsResponse.size(); i++) { if (recordsResponse.get(i).getErrorCode() != null) { failedRecordIndexes[idx++] = i; errors.compute(recordsResponse.get(i).getErrorMessage(), (k, v) -> v == null ? 1 : v++); } } LOGGER.warn("Error in Kinesis putRecords: %d records.", putRecordsResult.getFailedRecordCount(), errors.toString()); return failedRecordIndexes; } else { return EventStore.SUCCESSFUL_BATCH; } } catch (ResourceNotFoundException e) { try { createAndWaitForStreamToBecomeAvailable(kinesis, config.getEventStoreStreamName(), 1); return storeBatchInline(events, offset, limit); } catch (Exception e1) { throw new RuntimeException("Couldn't send event to Amazon Kinesis", e); } } } @Override public void storeBulk(List<Event> events, boolean commit) { String project = events.get(0).project(); bulkClient.upload(project, events); if (commit) { events.stream().map(e -> e.collection()).distinct().parallel() .forEach(collection -> commit(project, collection).join()); } } @Override public CompletableFuture<QueryResult> commit(String project, String collection) { Instant now = Instant.now(); try(Connection conn = dataSource.getConnection()) { String lockKey = "lock."+project+"."+collection; conn.createStatement().execute(format("SELECT pg_advisory_lock(hashtext('%s'))", lockKey)); String middlewareTable = format("FROM %s.\"%s\".\"%s\" WHERE \"$created_at\" > date '2016-05-05'", prestoConfig.getBulkConnector(), project, collection); QueryExecution insertQuery = executor.executeRawStatement(format("INSERT INTO %s.\"%s\".\"%s\" SELECT * %s", prestoConfig.getColdStorageConnector(), project, collection, middlewareTable)); return insertQuery.getResult().thenApply(result -> { if (result.isFailed()) { throw new RakamException("Unable to commit data: "+result.getError().toString(), INTERNAL_SERVER_ERROR); } ImmutableList.Builder<CompletableFuture<QueryResult>> builder = ImmutableList.builder(); for (ContinuousQuery continuousQuery : queryMetadataStore.getContinuousQueries(project)) { AtomicBoolean ref = new AtomicBoolean(); String query = QueryFormatter.format(continuousQuery.getQuery(), name -> { if ((name.getPrefix().map(e -> e.equals("collection")).orElse(true) && name.getSuffix().equals(collection)) || !name.getPrefix().isPresent() && name.getSuffix().equals("_all")) { ref.set(true); return format("(SELECT '%s' as \"$collection\", * ", collection) + middlewareTable + ")"; } return executor.formatTableReference(project, name); }); if (!ref.get()) { continue; } CompletableFuture<QueryResult> processQuery = executor.executeRawStatement(format("CREATE OR REPLACE VIEW %s.\"%s\".\"%s\" AS %s", prestoConfig.getStreamingConnector(), project, continuousQuery.tableName, query)) .getResult(); builder.add(processQuery); } ImmutableList<CompletableFuture<QueryResult>> futures = builder.build(); return CompletableFuture.allOf(futures.stream().toArray(CompletableFuture[]::new)) .thenApply(aVoid -> { for (CompletableFuture<QueryResult> future : futures) { if (future.join().isFailed()) { return future.join(); } } return QueryResult.empty(); // return executor.executeRawStatement(format("DELETE FROM %s.%s.%s WHERE \"$created_at\" <= timestamp '%s'", prestoConfig.getBulkConnector(), // project, collection, PRESTO_TIMESTAMP_FORMAT.format(now.atZone(ZoneOffset.UTC)))).getResult().join(); }).join(); }); } catch (SQLException e) { throw Throwables.propagate(e); } } @Override public int[] storeBatch(List<Event> events) { if (events.size() > BATCH_SIZE) { ArrayList<Integer> errors = null; int cursor = 0; while (cursor < events.size()) { int loopSize = Math.min(BATCH_SIZE, events.size() - cursor); int[] errorIndexes = storeBatchInline(events, cursor, loopSize); if (errorIndexes.length > 0) { if (errors == null) { errors = new ArrayList<>(errorIndexes.length); } for (int errorIndex : errorIndexes) { errors.add(errorIndex + cursor); } } cursor += loopSize; } return errors == null ? EventStore.SUCCESSFUL_BATCH : errors.stream().mapToInt(Integer::intValue).toArray(); } else { return storeBatchInline(events, 0, events.size()); } } @Override public void store(Event event) { // try { kinesis.putRecord(config.getEventStoreStreamName(), getBuffer(event), event.project() + "|" + event.collection()); // } catch (ResourceNotFoundException e) { // try { // createAndWaitForStreamToBecomeAvailable(kinesis, config.getEventStoreStreamName(), 1); // } catch (Exception e1) { // throw new RuntimeException("Couldn't send event to Amazon Kinesis", e); // } // } } private ByteBuffer getBuffer(Event event) { DatumWriter writer = new FilteredRecordWriter(event.properties().getSchema(), GenericData.get()); KByteArrayOutputStream out = buffer.get(); int startPosition = out.position(); BinaryEncoder encoder = EncoderFactory.get().directBinaryEncoder(out, null); try { writer.write(event.properties(), encoder); } catch (Exception e) { throw new RuntimeException("Couldn't serialize event", e); } int endPosition = out.position(); // TODO: find a way to make it zero-copy if (out.remaining() < 1000) { out.position(0); } return out.getBuffer(startPosition, endPosition - startPosition); } }
rakam-aws-kinesis/src/main/java/org/rakam/aws/AWSKinesisEventStore.java
package org.rakam.aws; import com.amazonaws.services.kinesis.AmazonKinesisClient; import com.amazonaws.services.kinesis.model.PutRecordsRequest; import com.amazonaws.services.kinesis.model.PutRecordsRequestEntry; import com.amazonaws.services.kinesis.model.PutRecordsResult; import com.amazonaws.services.kinesis.model.PutRecordsResultEntry; import com.amazonaws.services.kinesis.model.ResourceNotFoundException; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.inject.name.Named; import io.airlift.log.Logger; import org.apache.avro.generic.FilteredRecordWriter; import org.apache.avro.generic.GenericData; import org.apache.avro.io.BinaryEncoder; import org.apache.avro.io.DatumWriter; import org.apache.avro.io.EncoderFactory; import org.rakam.analysis.JDBCPoolDataSource; import org.rakam.analysis.metadata.Metastore; import org.rakam.analysis.metadata.QueryMetadataStore; import org.rakam.collection.Event; import org.rakam.collection.FieldDependencyBuilder; import org.rakam.plugin.ContinuousQuery; import org.rakam.plugin.EventStore; import org.rakam.presto.analysis.PrestoConfig; import org.rakam.presto.analysis.PrestoQueryExecutor; import org.rakam.report.QueryExecution; import org.rakam.report.QueryResult; import org.rakam.util.KByteArrayOutputStream; import org.rakam.util.QueryFormatter; import org.rakam.util.RakamException; import javax.inject.Inject; import java.nio.ByteBuffer; import java.sql.Connection; import java.sql.SQLException; import java.time.Instant; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; import static java.lang.String.format; import static org.rakam.aws.KinesisUtils.createAndWaitForStreamToBecomeAvailable; import static org.rakam.presto.analysis.PrestoQueryExecution.PRESTO_TIMESTAMP_FORMAT; public class AWSKinesisEventStore implements EventStore { private final static Logger LOGGER = Logger.get(AWSKinesisEventStore.class); private final AmazonKinesisClient kinesis; private final AWSConfig config; private static final int BATCH_SIZE = 500; private final S3BulkEventStore bulkClient; private final PrestoQueryExecutor executor; private final PrestoConfig prestoConfig; private final QueryMetadataStore queryMetadataStore; private final JDBCPoolDataSource dataSource; private ThreadLocal<KByteArrayOutputStream> buffer = new ThreadLocal<KByteArrayOutputStream>() { @Override protected KByteArrayOutputStream initialValue() { return new KByteArrayOutputStream(1000000); } }; @Inject public AWSKinesisEventStore(AWSConfig config, Metastore metastore, @Named("report.metadata.store.jdbc") JDBCPoolDataSource dataSource, PrestoQueryExecutor executor, QueryMetadataStore queryMetadataStore, PrestoConfig prestoConfig, FieldDependencyBuilder.FieldDependency fieldDependency) { kinesis = new AmazonKinesisClient(config.getCredentials()); kinesis.setRegion(config.getAWSRegion()); if (config.getKinesisEndpoint() != null) { kinesis.setEndpoint(config.getKinesisEndpoint()); } this.config = config; this.executor = executor; this.prestoConfig = prestoConfig; this.dataSource = dataSource; this.queryMetadataStore = queryMetadataStore; this.bulkClient = new S3BulkEventStore(metastore, config, fieldDependency); } public int[] storeBatchInline(List<Event> events, int offset, int limit) { PutRecordsRequestEntry[] records = new PutRecordsRequestEntry[limit]; for (int i = 0; i < limit; i++) { Event event = events.get(offset + i); PutRecordsRequestEntry putRecordsRequestEntry = new PutRecordsRequestEntry() .withData(getBuffer(event)) .withPartitionKey(event.project() + "|" + event.collection()); records[i] = putRecordsRequestEntry; } try { PutRecordsResult putRecordsResult = kinesis.putRecords(new PutRecordsRequest() .withRecords(records) .withStreamName(config.getEventStoreStreamName())); if (putRecordsResult.getFailedRecordCount() > 0) { int[] failedRecordIndexes = new int[putRecordsResult.getFailedRecordCount()]; int idx = 0; Map<String, Integer> errors = new HashMap<>(); List<PutRecordsResultEntry> recordsResponse = putRecordsResult.getRecords(); for (int i = 0; i < recordsResponse.size(); i++) { if (recordsResponse.get(i).getErrorCode() != null) { failedRecordIndexes[idx++] = i; errors.compute(recordsResponse.get(i).getErrorMessage(), (k, v) -> v == null ? 1 : v++); } } LOGGER.warn("Error in Kinesis putRecords: %d records.", putRecordsResult.getFailedRecordCount(), errors.toString()); return failedRecordIndexes; } else { return EventStore.SUCCESSFUL_BATCH; } } catch (ResourceNotFoundException e) { try { createAndWaitForStreamToBecomeAvailable(kinesis, config.getEventStoreStreamName(), 1); return storeBatchInline(events, offset, limit); } catch (Exception e1) { throw new RuntimeException("Couldn't send event to Amazon Kinesis", e); } } } @Override public void storeBulk(List<Event> events, boolean commit) { String project = events.get(0).project(); bulkClient.upload(project, events); if (commit) { events.stream().map(e -> e.collection()).distinct().parallel() .forEach(collection -> commit(project, collection).join()); } } @Override public CompletableFuture<QueryResult> commit(String project, String collection) { Instant now = Instant.now(); try(Connection conn = dataSource.getConnection()) { String lockKey = "lock."+project+"."+collection; conn.createStatement().execute(format("SELECT pg_advisory_lock(hashtext('%s'))", lockKey)); String middlewareTable = format("FROM %s.\"%s\".\"%s\" WHERE \"$created_at\" <= timestamp '%s'", prestoConfig.getBulkConnector(), project, collection, PRESTO_TIMESTAMP_FORMAT.format(now.atZone(ZoneOffset.UTC))); QueryExecution insertQuery = executor.executeRawStatement(format("INSERT INTO %s.\"%s\".\"%s\" SELECT * %s", prestoConfig.getColdStorageConnector(), project, collection, middlewareTable)); return insertQuery.getResult().thenApply(result -> { if (result.isFailed()) { throw new RakamException("Unable to commit data: "+result.getError().toString(), INTERNAL_SERVER_ERROR); } ImmutableList.Builder<CompletableFuture<QueryResult>> builder = ImmutableList.builder(); for (ContinuousQuery continuousQuery : queryMetadataStore.getContinuousQueries(project)) { AtomicBoolean ref = new AtomicBoolean(); String query = QueryFormatter.format(continuousQuery.getQuery(), name -> { if ((name.getPrefix().map(e -> e.equals("collection")).orElse(true) && name.getSuffix().equals(collection)) || !name.getPrefix().isPresent() && name.getSuffix().equals("_all")) { ref.set(true); return format("(SELECT '%s' as \"$collection\", * ", collection) + middlewareTable + ")"; } return executor.formatTableReference(project, name); }); if (!ref.get()) { continue; } CompletableFuture<QueryResult> processQuery = executor.executeRawStatement(format("CREATE OR REPLACE VIEW %s.\"%s\".\"%s\" AS %s", prestoConfig.getStreamingConnector(), project, continuousQuery.tableName, query)) .getResult(); builder.add(processQuery); } ImmutableList<CompletableFuture<QueryResult>> futures = builder.build(); return CompletableFuture.allOf(futures.stream().toArray(CompletableFuture[]::new)) .thenApply(aVoid -> { for (CompletableFuture<QueryResult> future : futures) { if (future.join().isFailed()) { return future.join(); } } return QueryResult.empty(); // return executor.executeRawStatement(format("DELETE FROM %s.%s.%s WHERE \"$created_at\" <= timestamp '%s'", prestoConfig.getBulkConnector(), // project, collection, PRESTO_TIMESTAMP_FORMAT.format(now.atZone(ZoneOffset.UTC)))).getResult().join(); }).join(); }); } catch (SQLException e) { throw Throwables.propagate(e); } } @Override public int[] storeBatch(List<Event> events) { if (events.size() > BATCH_SIZE) { ArrayList<Integer> errors = null; int cursor = 0; while (cursor < events.size()) { int loopSize = Math.min(BATCH_SIZE, events.size() - cursor); int[] errorIndexes = storeBatchInline(events, cursor, loopSize); if (errorIndexes.length > 0) { if (errors == null) { errors = new ArrayList<>(errorIndexes.length); } for (int errorIndex : errorIndexes) { errors.add(errorIndex + cursor); } } cursor += loopSize; } return errors == null ? EventStore.SUCCESSFUL_BATCH : errors.stream().mapToInt(Integer::intValue).toArray(); } else { return storeBatchInline(events, 0, events.size()); } } @Override public void store(Event event) { // try { kinesis.putRecord(config.getEventStoreStreamName(), getBuffer(event), event.project() + "|" + event.collection()); // } catch (ResourceNotFoundException e) { // try { // createAndWaitForStreamToBecomeAvailable(kinesis, config.getEventStoreStreamName(), 1); // } catch (Exception e1) { // throw new RuntimeException("Couldn't send event to Amazon Kinesis", e); // } // } } private ByteBuffer getBuffer(Event event) { DatumWriter writer = new FilteredRecordWriter(event.properties().getSchema(), GenericData.get()); KByteArrayOutputStream out = buffer.get(); int startPosition = out.position(); BinaryEncoder encoder = EncoderFactory.get().directBinaryEncoder(out, null); try { writer.write(event.properties(), encoder); } catch (Exception e) { throw new RuntimeException("Couldn't serialize event", e); } int endPosition = out.position(); // TODO: find a way to make it zero-copy if (out.remaining() < 1000) { out.position(0); } return out.getBuffer(startPosition, endPosition - startPosition); } }
use created_at column for offset mechanism
rakam-aws-kinesis/src/main/java/org/rakam/aws/AWSKinesisEventStore.java
use created_at column for offset mechanism
<ide><path>akam-aws-kinesis/src/main/java/org/rakam/aws/AWSKinesisEventStore.java <ide> import java.sql.Connection; <ide> import java.sql.SQLException; <ide> import java.time.Instant; <del>import java.time.ZoneOffset; <ide> import java.util.ArrayList; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR; <ide> import static java.lang.String.format; <ide> import static org.rakam.aws.KinesisUtils.createAndWaitForStreamToBecomeAvailable; <del>import static org.rakam.presto.analysis.PrestoQueryExecution.PRESTO_TIMESTAMP_FORMAT; <ide> <ide> public class AWSKinesisEventStore implements EventStore { <ide> private final static Logger LOGGER = Logger.get(AWSKinesisEventStore.class); <ide> <ide> conn.createStatement().execute(format("SELECT pg_advisory_lock(hashtext('%s'))", lockKey)); <ide> <del> String middlewareTable = format("FROM %s.\"%s\".\"%s\" WHERE \"$created_at\" <= timestamp '%s'", <del> prestoConfig.getBulkConnector(), project, collection, PRESTO_TIMESTAMP_FORMAT.format(now.atZone(ZoneOffset.UTC))); <add> String middlewareTable = format("FROM %s.\"%s\".\"%s\" WHERE \"$created_at\" > date '2016-05-05'", <add> prestoConfig.getBulkConnector(), project, collection); <ide> <ide> QueryExecution insertQuery = executor.executeRawStatement(format("INSERT INTO %s.\"%s\".\"%s\" SELECT * %s", <ide> prestoConfig.getColdStorageConnector(), project, collection, middlewareTable));
Java
mit
044ecc51e532bf28149bcef6f9feff5c4e9c9446
0
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
package generatedtest; import java.util.Map; import java.util.ResourceBundle; import java.util.SortedMap; import java.util.TreeMap; import java.util.Vector; import org.apache.commons.collections4.Factory; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.IterableSortedMap; import org.apache.commons.collections4.KeyValue; import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.MultiMap; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.keyvalue.AbstractKeyValue; import org.apache.commons.collections4.keyvalue.AbstractMapEntry; import org.apache.commons.collections4.keyvalue.AbstractMapEntryDecorator; import org.apache.commons.collections4.keyvalue.DefaultKeyValue; import org.apache.commons.collections4.keyvalue.DefaultMapEntry; import org.apache.commons.collections4.keyvalue.TiedMapEntry; import org.apache.commons.collections4.keyvalue.UnmodifiableMapEntry; import org.apache.commons.collections4.map.MultiValueMap; //Test case generated by GenerateFlowTestCase.ql public class Test { static Object getMapKey(AbstractKeyValue container) { return container.getKey(); } static Object getMapKeyFromEntry(Map.Entry container) { return container.getKey(); } static Object getMapKey(AbstractMapEntryDecorator container) { return container.getKey(); } static Object getMapKey(Map container) { return container.keySet().iterator().next(); } static Object getMapValue(AbstractKeyValue container) { return container.getValue(); } static Object getMapValueFromEntry(Map.Entry container) { return container.getValue(); } static Object getMapValue(AbstractMapEntryDecorator container) { return container.getValue(); } static Object getMapValue(Map container) { return container.get(null); } Object[] newWithArrayElement(Object element) { return new Object[] {element}; } Iterable<String> newWithElement(String element) { Vector<String> v = new Vector<String>(); v.add(element); return v; } MyAbstractKeyValue newMAKVWithMapKey(Object element) { return new MyAbstractKeyValue(element,null); } DefaultKeyValue newDKVWithMapKey(Object element) { return new DefaultKeyValue(element,null); } MyAbstractMapEntry newMAMEWithMapKey(Object element) { return new MyAbstractMapEntry(element,null); } MyAbstractMapEntryDecorator newMAMEDWithMapKey(Object element) { return new MyAbstractMapEntryDecorator(newMAMEWithMapKey(element)); } ResourceBundle newRBWithMapKey(Object element) { return (ResourceBundle)null; } SortedMap newTreeMapWithMapKey(Object element) { SortedMap m = new TreeMap(); m.put(element,null); return m; } TiedMapEntry newTMEWithMapKey(Object element) { return new TiedMapEntry(newTreeMapWithMapKey(element),element); } MyAbstractKeyValue newMAKVWithMapValue(Object element) { return new MyAbstractKeyValue(null,element); } DefaultKeyValue newDKVWithMapValue(Object element) { return new DefaultKeyValue(null,element); } MyAbstractMapEntry newMAMEWithMapValue(Object element) { return new MyAbstractMapEntry(null,element); } MyAbstractMapEntryDecorator newMAMEDWithMapValue(Object element) { return new MyAbstractMapEntryDecorator(newMAMEWithMapValue(element)); } ResourceBundle newRBWithMapValue(Object element) { return (ResourceBundle)null; } SortedMap newTreeMapWithMapValue(Object element) { SortedMap m = new TreeMap(); m.put(null,element); return m; } TiedMapEntry newTMEWithMapValue(Object element) { return new TiedMapEntry(newTreeMapWithMapValue(element),null); } UnmodifiableMapEntry newUMEWithMapValue(Object element) { return new UnmodifiableMapEntry(null,element); } Object source() { return null; } void sink(Object o) { } class MyAbstractKeyValue<K, V> extends AbstractKeyValue<K, V> { MyAbstractKeyValue(K key, V value) { super(key, value); } K mySetKey(final K key) { return super.setKey(key); } V mySetValue(final V value) { return super.setValue(value); } } class MyAbstractMapEntry<K, V> extends AbstractMapEntry<K, V> { MyAbstractMapEntry(final K key, final V value) { super(key, value); } @Override public K getKey() { return null; } @Override public V getValue() { return null; } } class MyAbstractMapEntryDecorator<K, V> extends AbstractMapEntryDecorator<K, V> { MyAbstractMapEntryDecorator(final Map.Entry<K, V> entry) { super(entry); } Map.Entry<K, V> myGetMapEntry() { return super.getMapEntry(); } } public void test() { { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;AbstractKeyValue;;;Argument[0];MapKey of Argument[-1];value" AbstractKeyValue out = null; Object in = source(); out = new MyAbstractKeyValue(in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;AbstractKeyValue;;;Argument[1];MapValue of Argument[-1];value" AbstractKeyValue out = null; Object in = source(); out = new MyAbstractKeyValue(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;Argument[0];MapKey of Argument[-1];value" DefaultKeyValue out = null; Object in = source(); out.setKey(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;Argument[0];MapKey of Argument[-1];value" MyAbstractKeyValue out = null; Object in = source(); out.mySetKey(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; DefaultKeyValue in = newDKVWithMapValue(source()); out = in.setKey(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; MyAbstractKeyValue in = newMAKVWithMapValue(source()); out = in.mySetKey(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; MyAbstractKeyValue in = newMAKVWithMapValue(source()); out = in.mySetKey((Object)null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" UnmodifiableMapEntry out = null; Object in = source(); out.setValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" DefaultKeyValue out = null; Object in = source(); out.setValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" AbstractMapEntry out = null; Object in = source(); out.setValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" MyAbstractKeyValue out = null; Object in = source(); out.mySetValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; UnmodifiableMapEntry in = newUMEWithMapValue(source()); out = in.setValue(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; DefaultKeyValue in = newDKVWithMapValue(source()); out = in.setValue(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; AbstractMapEntry in = newMAMEWithMapValue(source()); out = in.setValue(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; AbstractMapEntry in = newMAMEWithMapValue(source()); out = in.setValue(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; MyAbstractKeyValue in = newMAKVWithMapValue(source()); out = in.mySetValue(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; MyAbstractKeyValue in = newMAKVWithMapValue(source()); out = in.mySetValue(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;toString;;;MapKey of Argument[-1];ReturnValue;taint" String out = null; AbstractKeyValue in = newMAKVWithMapKey(source()); out = in.toString(); sink(out); // $hasTaintFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;toString;;;MapValue of Argument[-1];ReturnValue;taint" String out = null; AbstractKeyValue in = newMAKVWithMapValue(source()); out = in.toString(); sink(out); // $hasTaintFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntry;true;AbstractMapEntry;;;Argument[0];MapKey of Argument[-1];value" AbstractMapEntry out = null; Object in = source(); out = new MyAbstractMapEntry(in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntry;true;AbstractMapEntry;;;Argument[1];MapValue of Argument[-1];value" AbstractMapEntry out = null; Object in = source(); out = new MyAbstractMapEntry(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;AbstractMapEntryDecorator;;;MapKey of Argument[0];MapKey of Argument[-1];value" AbstractMapEntryDecorator out = null; Map.Entry<String,String> in = newMAMEWithMapKey(source()); out = new MyAbstractMapEntryDecorator(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;AbstractMapEntryDecorator;;;MapValue of Argument[0];MapValue of Argument[-1];value" AbstractMapEntryDecorator out = null; Map.Entry<String,String> in = newMAMEWithMapValue(source()); out = new MyAbstractMapEntryDecorator(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;getMapEntry;;;MapKey of Argument[-1];MapKey of ReturnValue;value" Map.Entry<String,String> out = null; MyAbstractMapEntryDecorator in = newMAMEDWithMapKey(source()); out = in.myGetMapEntry(); sink(getMapKeyFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;getMapEntry;;;MapValue of Argument[-1];MapValue of ReturnValue;value" Map.Entry<String,String> out = null; MyAbstractMapEntryDecorator in = newMAMEDWithMapValue(source()); out = in.myGetMapEntry(); sink(getMapValueFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;toString;;;MapKey of Argument[-1];ReturnValue;taint" String out = null; AbstractMapEntryDecorator in = newMAMEDWithMapKey(source()); out = in.toString(); sink(out); // $hasTaintFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;toString;;;MapValue of Argument[-1];ReturnValue;taint" String out = null; AbstractMapEntryDecorator in = newMAMEDWithMapValue(source()); out = in.toString(); sink(out); // $hasTaintFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Entry);;MapKey of Argument[0];MapKey of Argument[-1];value" DefaultKeyValue out = null; Map.Entry<String,String> in = newMAMEWithMapKey(source()); out = new DefaultKeyValue(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Entry);;MapValue of Argument[0];MapValue of Argument[-1];value" DefaultKeyValue out = null; Map.Entry<String,String> in = newMAMEWithMapValue(source()); out = new DefaultKeyValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(KeyValue);;MapKey of Argument[0];MapKey of Argument[-1];value" DefaultKeyValue out = null; KeyValue in = newMAKVWithMapKey(source()); out = new DefaultKeyValue(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(KeyValue);;MapValue of Argument[0];MapValue of Argument[-1];value" DefaultKeyValue out = null; KeyValue in = newMAKVWithMapValue(source()); out = new DefaultKeyValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Object,Object);;Argument[0];MapKey of Argument[-1];value" DefaultKeyValue out = null; Object in = source(); out = new DefaultKeyValue(in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Object,Object);;Argument[1];MapValue of Argument[-1];value" DefaultKeyValue out = null; Object in = source(); out = new DefaultKeyValue(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;toMapEntry;;;MapKey of Argument[-1];MapKey of ReturnValue;value" Map.Entry<String,String> out = null; DefaultKeyValue in = newDKVWithMapKey(source()); out = in.toMapEntry(); sink(getMapKeyFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;toMapEntry;;;MapValue of Argument[-1];MapValue of ReturnValue;value" Map.Entry<String,String> out = null; DefaultKeyValue in = newDKVWithMapValue(source()); out = in.toMapEntry(); sink(getMapValueFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Entry);;MapKey of Argument[0];MapKey of Argument[-1];value" DefaultMapEntry out = null; Map.Entry<String,String> in = newMAMEWithMapKey(source()); out = new DefaultMapEntry(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Entry);;MapValue of Argument[0];MapValue of Argument[-1];value" DefaultMapEntry out = null; Map.Entry<String,String> in = newMAMEWithMapValue(source()); out = new DefaultMapEntry(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(KeyValue);;MapKey of Argument[0];MapKey of Argument[-1];value" DefaultMapEntry out = null; KeyValue in = newMAKVWithMapKey(source()); out = new DefaultMapEntry(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(KeyValue);;MapValue of Argument[0];MapValue of Argument[-1];value" DefaultMapEntry out = null; KeyValue in = newMAKVWithMapValue(source()); out = new DefaultMapEntry(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Object,Object);;Argument[0];MapKey of Argument[-1];value" DefaultMapEntry out = null; Object in = source(); out = new DefaultMapEntry(in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Object,Object);;Argument[1];MapValue of Argument[-1];value" DefaultMapEntry out = null; Object in = source(); out = new DefaultMapEntry(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;TiedMapEntry;true;TiedMapEntry;;;Argument[1];MapKey of Argument[-1];value" TiedMapEntry out = null; Object in = source(); out = new TiedMapEntry(null, in); sink(getMapKeyFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;TiedMapEntry;true;TiedMapEntry;;;MapValue of Argument[0];MapValue of Argument[-1];value" TiedMapEntry out = null; Map in = newTreeMapWithMapValue(source()); out = new TiedMapEntry(in, null); sink(getMapValueFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Entry);;MapKey of Argument[0];MapKey of Argument[-1];value" UnmodifiableMapEntry out = null; Map.Entry<String,String> in = newMAMEWithMapKey(source()); out = new UnmodifiableMapEntry(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Entry);;MapValue of Argument[0];MapValue of Argument[-1];value" UnmodifiableMapEntry out = null; Map.Entry<String,String> in = newMAMEWithMapValue(source()); out = new UnmodifiableMapEntry(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(KeyValue);;MapKey of Argument[0];MapKey of Argument[-1];value" UnmodifiableMapEntry out = null; KeyValue in = newMAKVWithMapKey(source()); out = new UnmodifiableMapEntry(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(KeyValue);;MapValue of Argument[0];MapValue of Argument[-1];value" UnmodifiableMapEntry out = null; KeyValue in = newMAKVWithMapValue(source()); out = new UnmodifiableMapEntry(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Object,Object);;Argument[0];MapKey of Argument[-1];value" UnmodifiableMapEntry out = null; Object in = source(); out = new UnmodifiableMapEntry(in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Object,Object);;Argument[1];MapValue of Argument[-1];value" UnmodifiableMapEntry out = null; Object in = source(); out = new UnmodifiableMapEntry(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" Object out = null; TiedMapEntry in = newTMEWithMapKey(source()); out = in.getKey(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" Object out = null; KeyValue in = newMAKVWithMapKey(source()); out = in.getKey(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" Object out = null; AbstractMapEntryDecorator in = newMAMEDWithMapKey(source()); out = in.getKey(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" Object out = null; AbstractKeyValue in = newMAKVWithMapKey(source()); out = in.getKey(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; TiedMapEntry in = newTMEWithMapValue(source()); out = in.getValue(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; KeyValue in = newMAKVWithMapValue(source()); out = in.getValue(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; AbstractMapEntryDecorator in = newMAMEDWithMapValue(source()); out = in.getValue(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; AbstractKeyValue in = newMAKVWithMapValue(source()); out = in.getValue(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;emptyIfNull;;;Argument[0];ReturnValue;value" Map out = null; Map in = (Map)source(); out = MapUtils.emptyIfNull(in); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;fixedSizeMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.fixedSizeMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;fixedSizeMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.fixedSizeMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;fixedSizeSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapKey(source()); out = MapUtils.fixedSizeSortedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;fixedSizeSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapValue(source()); out = MapUtils.fixedSizeSortedMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getMap;;;Argument[2];ReturnValue;value" Map out = null; Map in = (Map)source(); out = MapUtils.getMap(null, null, in); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getMap;;;MapValue of Argument[0];ReturnValue;value" Map out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.getMap(in, null, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getMap;;;MapValue of Argument[0];ReturnValue;value" Map out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.getMap(in, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getObject;;;Argument[2];ReturnValue;value" Object out = null; Object in = source(); out = MapUtils.getObject(null, null, in); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getObject;;;MapValue of Argument[0];ReturnValue;value" Object out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.getObject(in, null, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getObject;;;MapValue of Argument[0];ReturnValue;value" Object out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.getObject(in, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getString;;;Argument[2];ReturnValue;value" String out = null; String in = (String)source(); out = MapUtils.getString(null, null, in); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getString;;;MapValue of Argument[0];ReturnValue;value" String out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.getString(in, null, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getString;;;MapValue of Argument[0];ReturnValue;value" String out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.getString(in, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;invertMap;;;MapKey of Argument[0];MapValue of ReturnValue;value" Map out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.invertMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;invertMap;;;MapValue of Argument[0];MapKey of ReturnValue;value" Map out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.invertMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;iterableMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.iterableMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;iterableMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.iterableMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;iterableSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableSortedMap out = null; SortedMap in = newTreeMapWithMapKey(source()); out = MapUtils.iterableSortedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;iterableSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableSortedMap out = null; SortedMap in = newTreeMapWithMapValue(source()); out = MapUtils.iterableSortedMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.lazyMap(in, (Transformer)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.lazyMap(in, (Factory)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.lazyMap(in, (Transformer)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.lazyMap(in, (Factory)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapKey(source()); out = MapUtils.lazySortedMap(in, (Transformer)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapKey(source()); out = MapUtils.lazySortedMap(in, (Factory)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapValue(source()); out = MapUtils.lazySortedMap(in, (Transformer)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapValue(source()); out = MapUtils.lazySortedMap(in, (Factory)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" MultiValueMap out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.multiValueMap(in, (Factory)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" MultiValueMap out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.multiValueMap(in, (Class)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" MultiValueMap out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.multiValueMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" MultiValueMap out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.multiValueMap(in, (Factory)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" MultiValueMap out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.multiValueMap(in, (Class)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" MultiValueMap out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.multiValueMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;orderedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" OrderedMap out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.orderedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;orderedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" OrderedMap out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.orderedMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;populateMap;(Map,Iterable,Transformer);;Element of Argument[1];MapValue of Argument[0];value" Map out = null; Iterable in = newWithElement((String)source()); MapUtils.populateMap(out, in, (Transformer)null); sink(getMapValue(out)); // $hasValueFlow } { // Note it is tricky to get this to compile - the compiler thinks it is ambiguous // which overload it should choose unless you put the generic types in correctly // "org.apache.commons.collections4;MapUtils;true;populateMap;(MultiMap,Iterable,Transformer);;Element of Argument[1];MapValue of Argument[0];value" MultiMap<Integer, String> out = null; Iterable<String> in = newWithElement((String)source()); MapUtils.populateMap(out, in, (Transformer<String, Integer>)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;predicatedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.predicatedMap(in, null, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;predicatedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.predicatedMap(in, null, null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;predicatedSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapKey(source()); out = MapUtils.predicatedSortedMap(in, null, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;predicatedSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapValue(source()); out = MapUtils.predicatedSortedMap(in, null, null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapKey of Argument[0];value" Map out = null; Object[] in = newWithArrayElement(source()); MapUtils.putAll(out, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapKey of ReturnValue;value" Map out = null; Object[] in = newWithArrayElement(source()); out = MapUtils.putAll(null, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapValue of Argument[0];value" Map out = null; Object[] in = newWithArrayElement(source()); MapUtils.putAll(out, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapValue of ReturnValue;value" Map out = null; Object[] in = newWithArrayElement(source()); out = MapUtils.putAll(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapKey of Argument[0];value" Map out = null; Object[] in = newWithArrayElement(newWithArrayElement(source())); MapUtils.putAll(out, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapKey of ReturnValue;value" Map out = null; Object[] in = newWithArrayElement(newWithArrayElement(source())); out = MapUtils.putAll(null, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapValue of Argument[0];value" Map out = null; Object[] in = newWithArrayElement(newWithArrayElement(source())); MapUtils.putAll(out, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapValue of ReturnValue;value" Map out = null; Object[] in = newWithArrayElement(newWithArrayElement(source())); out = MapUtils.putAll(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapKey of ArrayElement of Argument[1];MapKey of Argument[0];value" Map out = null; Object[] in = newWithArrayElement(newMAKVWithMapKey(source())); MapUtils.putAll(out, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapKey of ArrayElement of Argument[1];MapKey of ReturnValue;value" Map out = null; Object[] in = newWithArrayElement(newMAKVWithMapKey(source())); out = MapUtils.putAll(null, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapValue of ArrayElement of Argument[1];MapValue of Argument[0];value" Map out = null; Object[] in = newWithArrayElement(newMAKVWithMapValue(source())); MapUtils.putAll(out, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapValue of ArrayElement of Argument[1];MapValue of ReturnValue;value" Map out = null; Object[] in = newWithArrayElement(newMAKVWithMapValue(source())); out = MapUtils.putAll(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;safeAddToMap;;;Argument[1];MapKey of Argument[0];value" Map out = null; Object in = source(); MapUtils.safeAddToMap(out, in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;safeAddToMap;;;Argument[2];MapValue of Argument[0];value" Map out = null; Object in = source(); MapUtils.safeAddToMap(out, null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;synchronizedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" Map out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.synchronizedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;synchronizedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" Map out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.synchronizedMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;synchronizedSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapKey(source()); out = MapUtils.synchronizedSortedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;synchronizedSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapValue(source()); out = MapUtils.synchronizedSortedMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;toMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" Map out = null; ResourceBundle in = newRBWithMapKey(source()); out = MapUtils.toMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;toMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" Map out = null; ResourceBundle in = newRBWithMapValue(source()); out = MapUtils.toMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;transformedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.transformedMap(in, null, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;transformedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.transformedMap(in, null, null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;transformedSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapKey(source()); out = MapUtils.transformedSortedMap(in, null, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;transformedSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapValue(source()); out = MapUtils.transformedSortedMap(in, null, null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;unmodifiableMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" Map out = null; Map in = newTreeMapWithMapKey(source()); out = MapUtils.unmodifiableMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;unmodifiableMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" Map out = null; Map in = newTreeMapWithMapValue(source()); out = MapUtils.unmodifiableMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;unmodifiableSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapKey(source()); out = MapUtils.unmodifiableSortedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;unmodifiableSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = newTreeMapWithMapValue(source()); out = MapUtils.unmodifiableSortedMap(in); sink(getMapValue(out)); // $hasValueFlow } } }
java/ql/test/library-tests/frameworks/apache-collections/Test.java
package generatedtest; import java.util.Map; import java.util.ResourceBundle; import java.util.SortedMap; import java.util.TreeMap; import java.util.Vector; import org.apache.commons.collections4.Factory; import org.apache.commons.collections4.IterableMap; import org.apache.commons.collections4.IterableSortedMap; import org.apache.commons.collections4.KeyValue; import org.apache.commons.collections4.MapUtils; import org.apache.commons.collections4.MultiMap; import org.apache.commons.collections4.OrderedMap; import org.apache.commons.collections4.Transformer; import org.apache.commons.collections4.keyvalue.AbstractKeyValue; import org.apache.commons.collections4.keyvalue.AbstractMapEntry; import org.apache.commons.collections4.keyvalue.AbstractMapEntryDecorator; import org.apache.commons.collections4.keyvalue.DefaultKeyValue; import org.apache.commons.collections4.keyvalue.DefaultMapEntry; import org.apache.commons.collections4.keyvalue.TiedMapEntry; import org.apache.commons.collections4.keyvalue.UnmodifiableMapEntry; import org.apache.commons.collections4.map.MultiValueMap; //Test case generated by GenerateFlowTestCase.ql public class Test { static Object getMapKey(AbstractKeyValue container) { return container.getKey(); } static Object getMapKeyFromEntry(Map.Entry container) { return container.getKey(); } static Object getMapKey(AbstractMapEntryDecorator container) { return container.getKey(); } static Object getMapKey(Map container) { return container.keySet().iterator().next(); } static Object getMapValue(AbstractKeyValue container) { return container.getValue(); } static Object getMapValueFromEntry(Map.Entry container) { return container.getValue(); } static Object getMapValue(AbstractMapEntryDecorator container) { return container.getValue(); } static Object getMapValue(Map container) { return container.get(null); } Object[] newWithArrayElement(Object element) { return new Object[] {element}; } Object newWithElement(Object element) { Vector<String> v = new Vector<String>(); v.add((String)element); return v; } MyAbstractKeyValue newMAKVWithMapKey(Object element) { return new MyAbstractKeyValue(element,null); } DefaultKeyValue newDKVWithMapKey(Object element) { return new DefaultKeyValue(element,null); } MyAbstractMapEntry newMAMEWithMapKey(Object element) { return new MyAbstractMapEntry(element,null); } MyAbstractMapEntryDecorator newMAMEDWithMapKey(Object element) { return new MyAbstractMapEntryDecorator(newMAMEWithMapKey(element)); } ResourceBundle newRBWithMapKey(Object element) { return (ResourceBundle)null; } Map newTreeMapWithMapKey(Object element) { Map m = new TreeMap(); m.put(element,null); return m; } TiedMapEntry newTMEWithMapKey(Object element) { return new TiedMapEntry(newTreeMapWithMapKey(element),element); } MyAbstractKeyValue newMAKVWithMapValue(Object element) { return new MyAbstractKeyValue(null,element); } DefaultKeyValue newDKVWithMapValue(Object element) { return new DefaultKeyValue(null,element); } MyAbstractMapEntry newMAMEWithMapValue(Object element) { return new MyAbstractMapEntry(null,element); } MyAbstractMapEntryDecorator newMAMEDWithMapValue(Object element) { return new MyAbstractMapEntryDecorator(newMAMEWithMapValue(element)); } ResourceBundle newRBWithMapValue(Object element) { return (ResourceBundle)null; } Map newTreeMapWithMapValue(Object element) { Map m = new TreeMap(); m.put(null,element); return m; } TiedMapEntry newTMEWithMapValue(Object element) { return new TiedMapEntry(newTreeMapWithMapValue(element),null); } UnmodifiableMapEntry newUMEWithMapValue(Object element) { return new UnmodifiableMapEntry(null,element); } Object source() { return null; } void sink(Object o) { } class MyAbstractKeyValue<K, V> extends AbstractKeyValue<K, V> { MyAbstractKeyValue(K key, V value) { super(key, value); } K mySetKey(final K key) { return super.setKey(key); } V mySetValue(final V value) { return super.setValue(value); } } class MyAbstractMapEntry<K, V> extends AbstractMapEntry<K, V> { MyAbstractMapEntry(final K key, final V value) { super(key, value); } @Override public K getKey() { return null; } @Override public V getValue() { return null; } } class MyAbstractMapEntryDecorator<K, V> extends AbstractMapEntryDecorator<K, V> { MyAbstractMapEntryDecorator(final Map.Entry<K, V> entry) { super(entry); } Map.Entry<K, V> myGetMapEntry() { return super.getMapEntry(); } } public void test() { { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;AbstractKeyValue;;;Argument[0];MapKey of Argument[-1];value" AbstractKeyValue out = null; Object in = (Object)source(); out = new MyAbstractKeyValue(in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;AbstractKeyValue;;;Argument[1];MapValue of Argument[-1];value" AbstractKeyValue out = null; Object in = (Object)source(); out = new MyAbstractKeyValue(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;Argument[0];MapKey of Argument[-1];value" DefaultKeyValue out = null; Object in = (Object)source(); out.setKey(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;Argument[0];MapKey of Argument[-1];value" MyAbstractKeyValue out = null; Object in = (Object)source(); out.mySetKey(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; DefaultKeyValue in = (DefaultKeyValue)newDKVWithMapValue(source()); out = in.setKey(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; MyAbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); out = in.mySetKey(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; MyAbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); out = in.mySetKey((Object)null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" UnmodifiableMapEntry out = null; Object in = (Object)source(); out.setValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" DefaultKeyValue out = null; Object in = (Object)source(); out.setValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" AbstractMapEntry out = null; Object in = (Object)source(); out.setValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" MyAbstractKeyValue out = null; Object in = (Object)source(); out.mySetValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; UnmodifiableMapEntry in = (UnmodifiableMapEntry)newUMEWithMapValue(source()); out = in.setValue(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; DefaultKeyValue in = (DefaultKeyValue)newDKVWithMapValue(source()); out = in.setValue(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; AbstractMapEntry in = (MyAbstractMapEntry)newMAMEWithMapValue(source()); out = in.setValue(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; AbstractMapEntry in = (MyAbstractMapEntry)newMAMEWithMapValue(source()); out = in.setValue((Object)null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; MyAbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); out = in.mySetValue(null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; MyAbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); out = in.mySetValue((Object)null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;toString;;;MapKey of Argument[-1];ReturnValue;taint" String out = null; AbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapKey(source()); out = in.toString(); sink(out); // $hasTaintFlow } { // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;toString;;;MapValue of Argument[-1];ReturnValue;taint" String out = null; AbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); out = in.toString(); sink(out); // $hasTaintFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntry;true;AbstractMapEntry;;;Argument[0];MapKey of Argument[-1];value" AbstractMapEntry out = null; Object in = (Object)source(); out = new MyAbstractMapEntry(in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntry;true;AbstractMapEntry;;;Argument[1];MapValue of Argument[-1];value" AbstractMapEntry out = null; Object in = (Object)source(); out = new MyAbstractMapEntry(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;AbstractMapEntryDecorator;;;MapKey of Argument[0];MapKey of Argument[-1];value" AbstractMapEntryDecorator out = null; Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapKey(source()); out = new MyAbstractMapEntryDecorator(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;AbstractMapEntryDecorator;;;MapValue of Argument[0];MapValue of Argument[-1];value" AbstractMapEntryDecorator out = null; Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapValue(source()); out = new MyAbstractMapEntryDecorator(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;getMapEntry;;;MapKey of Argument[-1];MapKey of ReturnValue;value" Map.Entry<String,String> out = null; MyAbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapKey(source()); out = in.myGetMapEntry(); sink(getMapKeyFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;getMapEntry;;;MapValue of Argument[-1];MapValue of ReturnValue;value" Map.Entry<String,String> out = null; MyAbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapValue(source()); out = in.myGetMapEntry(); sink(getMapValueFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;toString;;;MapKey of Argument[-1];ReturnValue;taint" String out = null; AbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapKey(source()); out = in.toString(); sink(out); // $hasTaintFlow } { // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;toString;;;MapValue of Argument[-1];ReturnValue;taint" String out = null; AbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapValue(source()); out = in.toString(); sink(out); // $hasTaintFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Entry);;MapKey of Argument[0];MapKey of Argument[-1];value" DefaultKeyValue out = null; Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapKey(source()); out = new DefaultKeyValue(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Entry);;MapValue of Argument[0];MapValue of Argument[-1];value" DefaultKeyValue out = null; Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapValue(source()); out = new DefaultKeyValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(KeyValue);;MapKey of Argument[0];MapKey of Argument[-1];value" DefaultKeyValue out = null; KeyValue in = (KeyValue)newMAKVWithMapKey(source()); out = new DefaultKeyValue(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(KeyValue);;MapValue of Argument[0];MapValue of Argument[-1];value" DefaultKeyValue out = null; KeyValue in = (KeyValue)newMAKVWithMapValue(source()); out = new DefaultKeyValue(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Object,Object);;Argument[0];MapKey of Argument[-1];value" DefaultKeyValue out = null; Object in = (Object)source(); out = new DefaultKeyValue(in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Object,Object);;Argument[1];MapValue of Argument[-1];value" DefaultKeyValue out = null; Object in = (Object)source(); out = new DefaultKeyValue(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;toMapEntry;;;MapKey of Argument[-1];MapKey of ReturnValue;value" Map.Entry<String,String> out = null; DefaultKeyValue in = (DefaultKeyValue)newDKVWithMapKey(source()); out = in.toMapEntry(); sink(getMapKeyFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;toMapEntry;;;MapValue of Argument[-1];MapValue of ReturnValue;value" Map.Entry<String,String> out = null; DefaultKeyValue in = (DefaultKeyValue)newDKVWithMapValue(source()); out = in.toMapEntry(); sink(getMapValueFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Entry);;MapKey of Argument[0];MapKey of Argument[-1];value" DefaultMapEntry out = null; Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapKey(source()); out = new DefaultMapEntry(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Entry);;MapValue of Argument[0];MapValue of Argument[-1];value" DefaultMapEntry out = null; Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapValue(source()); out = new DefaultMapEntry(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(KeyValue);;MapKey of Argument[0];MapKey of Argument[-1];value" DefaultMapEntry out = null; KeyValue in = (KeyValue)newMAKVWithMapKey(source()); out = new DefaultMapEntry(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(KeyValue);;MapValue of Argument[0];MapValue of Argument[-1];value" DefaultMapEntry out = null; KeyValue in = (KeyValue)newMAKVWithMapValue(source()); out = new DefaultMapEntry(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Object,Object);;Argument[0];MapKey of Argument[-1];value" DefaultMapEntry out = null; Object in = (Object)source(); out = new DefaultMapEntry(in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Object,Object);;Argument[1];MapValue of Argument[-1];value" DefaultMapEntry out = null; Object in = (Object)source(); out = new DefaultMapEntry(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;TiedMapEntry;true;TiedMapEntry;;;Argument[1];MapKey of Argument[-1];value" TiedMapEntry out = null; Object in = (Object)source(); out = new TiedMapEntry(null, in); sink(getMapKeyFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;TiedMapEntry;true;TiedMapEntry;;;MapValue of Argument[0];MapValue of Argument[-1];value" TiedMapEntry out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = new TiedMapEntry(in, null); sink(getMapValueFromEntry(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Entry);;MapKey of Argument[0];MapKey of Argument[-1];value" UnmodifiableMapEntry out = null; Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapKey(source()); out = new UnmodifiableMapEntry(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Entry);;MapValue of Argument[0];MapValue of Argument[-1];value" UnmodifiableMapEntry out = null; Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapValue(source()); out = new UnmodifiableMapEntry(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(KeyValue);;MapKey of Argument[0];MapKey of Argument[-1];value" UnmodifiableMapEntry out = null; KeyValue in = (KeyValue)newMAKVWithMapKey(source()); out = new UnmodifiableMapEntry(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(KeyValue);;MapValue of Argument[0];MapValue of Argument[-1];value" UnmodifiableMapEntry out = null; KeyValue in = (KeyValue)newMAKVWithMapValue(source()); out = new UnmodifiableMapEntry(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Object,Object);;Argument[0];MapKey of Argument[-1];value" UnmodifiableMapEntry out = null; Object in = (Object)source(); out = new UnmodifiableMapEntry(in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Object,Object);;Argument[1];MapValue of Argument[-1];value" UnmodifiableMapEntry out = null; Object in = (Object)source(); out = new UnmodifiableMapEntry(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" Object out = null; TiedMapEntry in = (TiedMapEntry)newTMEWithMapKey(source()); out = in.getKey(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" Object out = null; KeyValue in = (KeyValue)newMAKVWithMapKey(source()); out = in.getKey(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" Object out = null; AbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapKey(source()); out = in.getKey(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" Object out = null; AbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapKey(source()); out = in.getKey(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; TiedMapEntry in = (TiedMapEntry)newTMEWithMapValue(source()); out = in.getValue(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; KeyValue in = (KeyValue)newMAKVWithMapValue(source()); out = in.getValue(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; AbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapValue(source()); out = in.getValue(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" Object out = null; AbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); out = in.getValue(); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;emptyIfNull;;;Argument[0];ReturnValue;value" Map out = null; Map in = (Map)source(); out = MapUtils.emptyIfNull(in); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;fixedSizeMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.fixedSizeMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;fixedSizeMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.fixedSizeMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;fixedSizeSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); out = MapUtils.fixedSizeSortedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;fixedSizeSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); out = MapUtils.fixedSizeSortedMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getMap;;;Argument[2];ReturnValue;value" Map out = null; Map in = (Map)source(); out = MapUtils.getMap(null, null, in); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getMap;;;MapValue of Argument[0];ReturnValue;value" Map out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.getMap(in, null, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getMap;;;MapValue of Argument[0];ReturnValue;value" Map out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.getMap(in, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getObject;;;Argument[2];ReturnValue;value" Object out = null; Object in = (Object)source(); out = MapUtils.getObject(null, null, in); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getObject;;;MapValue of Argument[0];ReturnValue;value" Object out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.getObject(in, null, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getObject;;;MapValue of Argument[0];ReturnValue;value" Object out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.getObject(in, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getString;;;Argument[2];ReturnValue;value" String out = null; String in = (String)source(); out = MapUtils.getString(null, null, in); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getString;;;MapValue of Argument[0];ReturnValue;value" String out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.getString(in, null, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;getString;;;MapValue of Argument[0];ReturnValue;value" String out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.getString(in, null); sink(out); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;invertMap;;;MapKey of Argument[0];MapValue of ReturnValue;value" Map out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.invertMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;invertMap;;;MapValue of Argument[0];MapKey of ReturnValue;value" Map out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.invertMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;iterableMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.iterableMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;iterableMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.iterableMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;iterableSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableSortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); out = MapUtils.iterableSortedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;iterableSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableSortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); out = MapUtils.iterableSortedMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.lazyMap(in, (Transformer)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.lazyMap(in, (Factory)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.lazyMap(in, (Transformer)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.lazyMap(in, (Factory)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); out = MapUtils.lazySortedMap(in, (Transformer)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); out = MapUtils.lazySortedMap(in, (Factory)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); out = MapUtils.lazySortedMap(in, (Transformer)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); out = MapUtils.lazySortedMap(in, (Factory)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" MultiValueMap out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.multiValueMap(in, (Factory)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" MultiValueMap out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.multiValueMap(in, (Class)null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" MultiValueMap out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.multiValueMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" MultiValueMap out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.multiValueMap(in, (Factory)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" MultiValueMap out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.multiValueMap(in, (Class)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" MultiValueMap out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.multiValueMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;orderedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" OrderedMap out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.orderedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;orderedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" OrderedMap out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.orderedMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;populateMap;(Map,Iterable,Transformer);;Element of Argument[1];MapValue of Argument[0];value" Map out = null; Iterable in = (Iterable)newWithElement(source()); MapUtils.populateMap(out, in, (Transformer)null); sink(getMapValue(out)); // $hasValueFlow } { // Note it is tricky to get this to compile - the compiler thinks it is ambiguous // which overload it should choose unless you put the generic types in correctly // "org.apache.commons.collections4;MapUtils;true;populateMap;(MultiMap,Iterable,Transformer);;Element of Argument[1];MapValue of Argument[0];value" MultiMap<Integer, String> out = null; Iterable<String> in = (Iterable<String>)newWithElement(source()); MapUtils.populateMap(out, in, (Transformer<String, Integer>)null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;predicatedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.predicatedMap(in, null, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;predicatedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.predicatedMap(in, null, null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;predicatedSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); out = MapUtils.predicatedSortedMap(in, null, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;predicatedSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); out = MapUtils.predicatedSortedMap(in, null, null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapKey of Argument[0];value" Map out = null; Object[] in = (Object[])newWithArrayElement(source()); MapUtils.putAll(out, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapKey of ReturnValue;value" Map out = null; Object[] in = (Object[])newWithArrayElement(source()); out = MapUtils.putAll(null, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapValue of Argument[0];value" Map out = null; Object[] in = (Object[])newWithArrayElement(source()); MapUtils.putAll(out, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapValue of ReturnValue;value" Map out = null; Object[] in = (Object[])newWithArrayElement(source()); out = MapUtils.putAll(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapKey of Argument[0];value" Map out = null; Object[] in = (Object[])newWithArrayElement(newWithArrayElement(source())); MapUtils.putAll(out, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapKey of ReturnValue;value" Map out = null; Object[] in = (Object[])newWithArrayElement(newWithArrayElement(source())); out = MapUtils.putAll(null, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapValue of Argument[0];value" Map out = null; Object[] in = (Object[])newWithArrayElement(newWithArrayElement(source())); MapUtils.putAll(out, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapValue of ReturnValue;value" Map out = null; Object[] in = (Object[])newWithArrayElement(newWithArrayElement(source())); out = MapUtils.putAll(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapKey of ArrayElement of Argument[1];MapKey of Argument[0];value" Map out = null; Object[] in = (Object[])newWithArrayElement(newMAKVWithMapKey(source())); MapUtils.putAll(out, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapKey of ArrayElement of Argument[1];MapKey of ReturnValue;value" Map out = null; Object[] in = (Object[])newWithArrayElement(newMAKVWithMapKey(source())); out = MapUtils.putAll(null, in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapValue of ArrayElement of Argument[1];MapValue of Argument[0];value" Map out = null; Object[] in = (Object[])newWithArrayElement(newMAKVWithMapValue(source())); MapUtils.putAll(out, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapValue of ArrayElement of Argument[1];MapValue of ReturnValue;value" Map out = null; Object[] in = (Object[])newWithArrayElement(newMAKVWithMapValue(source())); out = MapUtils.putAll(null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;safeAddToMap;;;Argument[1];MapKey of Argument[0];value" Map out = null; Object in = (Object)source(); MapUtils.safeAddToMap(out, in, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;safeAddToMap;;;Argument[2];MapValue of Argument[0];value" Map out = null; Object in = (Object)source(); MapUtils.safeAddToMap(out, null, in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;synchronizedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" Map out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.synchronizedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;synchronizedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" Map out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.synchronizedMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;synchronizedSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); out = MapUtils.synchronizedSortedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;synchronizedSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); out = MapUtils.synchronizedSortedMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;toMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" Map out = null; ResourceBundle in = (ResourceBundle)newRBWithMapKey(source()); out = MapUtils.toMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;toMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" Map out = null; ResourceBundle in = (ResourceBundle)newRBWithMapValue(source()); out = MapUtils.toMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;transformedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.transformedMap(in, null, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;transformedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" IterableMap out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.transformedMap(in, null, null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;transformedSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); out = MapUtils.transformedSortedMap(in, null, null); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;transformedSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); out = MapUtils.transformedSortedMap(in, null, null); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;unmodifiableMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" Map out = null; Map in = (Map)newTreeMapWithMapKey(source()); out = MapUtils.unmodifiableMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;unmodifiableMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" Map out = null; Map in = (Map)newTreeMapWithMapValue(source()); out = MapUtils.unmodifiableMap(in); sink(getMapValue(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;unmodifiableSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); out = MapUtils.unmodifiableSortedMap(in); sink(getMapKey(out)); // $hasValueFlow } { // "org.apache.commons.collections4;MapUtils;true;unmodifiableSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" SortedMap out = null; SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); out = MapUtils.unmodifiableSortedMap(in); sink(getMapValue(out)); // $hasValueFlow } } }
Manually improve tests #2
java/ql/test/library-tests/frameworks/apache-collections/Test.java
Manually improve tests #2
<ide><path>ava/ql/test/library-tests/frameworks/apache-collections/Test.java <ide> static Object getMapValue(Map container) { return container.get(null); } <ide> <ide> Object[] newWithArrayElement(Object element) { return new Object[] {element}; } <del> Object newWithElement(Object element) { Vector<String> v = new Vector<String>(); v.add((String)element); return v; } <add> Iterable<String> newWithElement(String element) { Vector<String> v = new Vector<String>(); v.add(element); return v; } <ide> <ide> MyAbstractKeyValue newMAKVWithMapKey(Object element) { return new MyAbstractKeyValue(element,null); } <ide> DefaultKeyValue newDKVWithMapKey(Object element) { return new DefaultKeyValue(element,null); } <ide> MyAbstractMapEntry newMAMEWithMapKey(Object element) { return new MyAbstractMapEntry(element,null); } <ide> MyAbstractMapEntryDecorator newMAMEDWithMapKey(Object element) { return new MyAbstractMapEntryDecorator(newMAMEWithMapKey(element)); } <ide> ResourceBundle newRBWithMapKey(Object element) { return (ResourceBundle)null; } <del> Map newTreeMapWithMapKey(Object element) { Map m = new TreeMap(); m.put(element,null); return m; } <add> SortedMap newTreeMapWithMapKey(Object element) { SortedMap m = new TreeMap(); m.put(element,null); return m; } <ide> TiedMapEntry newTMEWithMapKey(Object element) { return new TiedMapEntry(newTreeMapWithMapKey(element),element); } <ide> <ide> MyAbstractKeyValue newMAKVWithMapValue(Object element) { return new MyAbstractKeyValue(null,element); } <ide> MyAbstractMapEntry newMAMEWithMapValue(Object element) { return new MyAbstractMapEntry(null,element); } <ide> MyAbstractMapEntryDecorator newMAMEDWithMapValue(Object element) { return new MyAbstractMapEntryDecorator(newMAMEWithMapValue(element)); } <ide> ResourceBundle newRBWithMapValue(Object element) { return (ResourceBundle)null; } <del> Map newTreeMapWithMapValue(Object element) { Map m = new TreeMap(); m.put(null,element); return m; } <add> SortedMap newTreeMapWithMapValue(Object element) { SortedMap m = new TreeMap(); m.put(null,element); return m; } <ide> TiedMapEntry newTMEWithMapValue(Object element) { return new TiedMapEntry(newTreeMapWithMapValue(element),null); } <ide> UnmodifiableMapEntry newUMEWithMapValue(Object element) { return new UnmodifiableMapEntry(null,element); } <ide> <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;AbstractKeyValue;;;Argument[0];MapKey of Argument[-1];value" <ide> AbstractKeyValue out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = new MyAbstractKeyValue(in, null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;AbstractKeyValue;;;Argument[1];MapValue of Argument[-1];value" <ide> AbstractKeyValue out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = new MyAbstractKeyValue(null, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;Argument[0];MapKey of Argument[-1];value" <ide> DefaultKeyValue out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out.setKey(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;Argument[0];MapKey of Argument[-1];value" <ide> MyAbstractKeyValue out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out.mySetKey(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> DefaultKeyValue in = (DefaultKeyValue)newDKVWithMapValue(source()); <add> DefaultKeyValue in = newDKVWithMapValue(source()); <ide> out = in.setKey(null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> MyAbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); <add> MyAbstractKeyValue in = newMAKVWithMapValue(source()); <ide> out = in.mySetKey(null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setKey;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> MyAbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); <add> MyAbstractKeyValue in = newMAKVWithMapValue(source()); <ide> out = in.mySetKey((Object)null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" <ide> UnmodifiableMapEntry out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out.setValue(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" <ide> DefaultKeyValue out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out.setValue(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" <ide> AbstractMapEntry out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out.setValue(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;Argument[0];MapValue of Argument[-1];value" <ide> MyAbstractKeyValue out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out.mySetValue(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> UnmodifiableMapEntry in = (UnmodifiableMapEntry)newUMEWithMapValue(source()); <add> UnmodifiableMapEntry in = newUMEWithMapValue(source()); <ide> out = in.setValue(null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> DefaultKeyValue in = (DefaultKeyValue)newDKVWithMapValue(source()); <add> DefaultKeyValue in = newDKVWithMapValue(source()); <ide> out = in.setValue(null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> AbstractMapEntry in = (MyAbstractMapEntry)newMAMEWithMapValue(source()); <add> AbstractMapEntry in = newMAMEWithMapValue(source()); <ide> out = in.setValue(null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> AbstractMapEntry in = (MyAbstractMapEntry)newMAMEWithMapValue(source()); <del> out = in.setValue((Object)null); <add> AbstractMapEntry in = newMAMEWithMapValue(source()); <add> out = in.setValue(null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> MyAbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); <add> MyAbstractKeyValue in = newMAKVWithMapValue(source()); <ide> out = in.mySetValue(null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;setValue;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> MyAbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); <del> out = in.mySetValue((Object)null); <add> MyAbstractKeyValue in = newMAKVWithMapValue(source()); <add> out = in.mySetValue(null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;toString;;;MapKey of Argument[-1];ReturnValue;taint" <ide> String out = null; <del> AbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapKey(source()); <add> AbstractKeyValue in = newMAKVWithMapKey(source()); <ide> out = in.toString(); <ide> sink(out); // $hasTaintFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractKeyValue;true;toString;;;MapValue of Argument[-1];ReturnValue;taint" <ide> String out = null; <del> AbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); <add> AbstractKeyValue in = newMAKVWithMapValue(source()); <ide> out = in.toString(); <ide> sink(out); // $hasTaintFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractMapEntry;true;AbstractMapEntry;;;Argument[0];MapKey of Argument[-1];value" <ide> AbstractMapEntry out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = new MyAbstractMapEntry(in, null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractMapEntry;true;AbstractMapEntry;;;Argument[1];MapValue of Argument[-1];value" <ide> AbstractMapEntry out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = new MyAbstractMapEntry(null, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;AbstractMapEntryDecorator;;;MapKey of Argument[0];MapKey of Argument[-1];value" <ide> AbstractMapEntryDecorator out = null; <del> Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapKey(source()); <add> Map.Entry<String,String> in = newMAMEWithMapKey(source()); <ide> out = new MyAbstractMapEntryDecorator(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;AbstractMapEntryDecorator;;;MapValue of Argument[0];MapValue of Argument[-1];value" <ide> AbstractMapEntryDecorator out = null; <del> Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapValue(source()); <add> Map.Entry<String,String> in = newMAMEWithMapValue(source()); <ide> out = new MyAbstractMapEntryDecorator(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;getMapEntry;;;MapKey of Argument[-1];MapKey of ReturnValue;value" <ide> Map.Entry<String,String> out = null; <del> MyAbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapKey(source()); <add> MyAbstractMapEntryDecorator in = newMAMEDWithMapKey(source()); <ide> out = in.myGetMapEntry(); <ide> sink(getMapKeyFromEntry(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;getMapEntry;;;MapValue of Argument[-1];MapValue of ReturnValue;value" <ide> Map.Entry<String,String> out = null; <del> MyAbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapValue(source()); <add> MyAbstractMapEntryDecorator in = newMAMEDWithMapValue(source()); <ide> out = in.myGetMapEntry(); <ide> sink(getMapValueFromEntry(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;toString;;;MapKey of Argument[-1];ReturnValue;taint" <ide> String out = null; <del> AbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapKey(source()); <add> AbstractMapEntryDecorator in = newMAMEDWithMapKey(source()); <ide> out = in.toString(); <ide> sink(out); // $hasTaintFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;AbstractMapEntryDecorator;true;toString;;;MapValue of Argument[-1];ReturnValue;taint" <ide> String out = null; <del> AbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapValue(source()); <add> AbstractMapEntryDecorator in = newMAMEDWithMapValue(source()); <ide> out = in.toString(); <ide> sink(out); // $hasTaintFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Entry);;MapKey of Argument[0];MapKey of Argument[-1];value" <ide> DefaultKeyValue out = null; <del> Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapKey(source()); <add> Map.Entry<String,String> in = newMAMEWithMapKey(source()); <ide> out = new DefaultKeyValue(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Entry);;MapValue of Argument[0];MapValue of Argument[-1];value" <ide> DefaultKeyValue out = null; <del> Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapValue(source()); <add> Map.Entry<String,String> in = newMAMEWithMapValue(source()); <ide> out = new DefaultKeyValue(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(KeyValue);;MapKey of Argument[0];MapKey of Argument[-1];value" <ide> DefaultKeyValue out = null; <del> KeyValue in = (KeyValue)newMAKVWithMapKey(source()); <add> KeyValue in = newMAKVWithMapKey(source()); <ide> out = new DefaultKeyValue(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(KeyValue);;MapValue of Argument[0];MapValue of Argument[-1];value" <ide> DefaultKeyValue out = null; <del> KeyValue in = (KeyValue)newMAKVWithMapValue(source()); <add> KeyValue in = newMAKVWithMapValue(source()); <ide> out = new DefaultKeyValue(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Object,Object);;Argument[0];MapKey of Argument[-1];value" <ide> DefaultKeyValue out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = new DefaultKeyValue(in, null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;DefaultKeyValue;(Object,Object);;Argument[1];MapValue of Argument[-1];value" <ide> DefaultKeyValue out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = new DefaultKeyValue(null, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;toMapEntry;;;MapKey of Argument[-1];MapKey of ReturnValue;value" <ide> Map.Entry<String,String> out = null; <del> DefaultKeyValue in = (DefaultKeyValue)newDKVWithMapKey(source()); <add> DefaultKeyValue in = newDKVWithMapKey(source()); <ide> out = in.toMapEntry(); <ide> sink(getMapKeyFromEntry(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultKeyValue;true;toMapEntry;;;MapValue of Argument[-1];MapValue of ReturnValue;value" <ide> Map.Entry<String,String> out = null; <del> DefaultKeyValue in = (DefaultKeyValue)newDKVWithMapValue(source()); <add> DefaultKeyValue in = newDKVWithMapValue(source()); <ide> out = in.toMapEntry(); <ide> sink(getMapValueFromEntry(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Entry);;MapKey of Argument[0];MapKey of Argument[-1];value" <ide> DefaultMapEntry out = null; <del> Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapKey(source()); <add> Map.Entry<String,String> in = newMAMEWithMapKey(source()); <ide> out = new DefaultMapEntry(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Entry);;MapValue of Argument[0];MapValue of Argument[-1];value" <ide> DefaultMapEntry out = null; <del> Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapValue(source()); <add> Map.Entry<String,String> in = newMAMEWithMapValue(source()); <ide> out = new DefaultMapEntry(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(KeyValue);;MapKey of Argument[0];MapKey of Argument[-1];value" <ide> DefaultMapEntry out = null; <del> KeyValue in = (KeyValue)newMAKVWithMapKey(source()); <add> KeyValue in = newMAKVWithMapKey(source()); <ide> out = new DefaultMapEntry(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(KeyValue);;MapValue of Argument[0];MapValue of Argument[-1];value" <ide> DefaultMapEntry out = null; <del> KeyValue in = (KeyValue)newMAKVWithMapValue(source()); <add> KeyValue in = newMAKVWithMapValue(source()); <ide> out = new DefaultMapEntry(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Object,Object);;Argument[0];MapKey of Argument[-1];value" <ide> DefaultMapEntry out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = new DefaultMapEntry(in, null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;DefaultMapEntry;true;DefaultMapEntry;(Object,Object);;Argument[1];MapValue of Argument[-1];value" <ide> DefaultMapEntry out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = new DefaultMapEntry(null, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;TiedMapEntry;true;TiedMapEntry;;;Argument[1];MapKey of Argument[-1];value" <ide> TiedMapEntry out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = new TiedMapEntry(null, in); <ide> sink(getMapKeyFromEntry(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;TiedMapEntry;true;TiedMapEntry;;;MapValue of Argument[0];MapValue of Argument[-1];value" <ide> TiedMapEntry out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = new TiedMapEntry(in, null); <ide> sink(getMapValueFromEntry(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Entry);;MapKey of Argument[0];MapKey of Argument[-1];value" <ide> UnmodifiableMapEntry out = null; <del> Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapKey(source()); <add> Map.Entry<String,String> in = newMAMEWithMapKey(source()); <ide> out = new UnmodifiableMapEntry(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Entry);;MapValue of Argument[0];MapValue of Argument[-1];value" <ide> UnmodifiableMapEntry out = null; <del> Map.Entry<String,String> in = (Map.Entry<String,String>)newMAKVWithMapValue(source()); <add> Map.Entry<String,String> in = newMAMEWithMapValue(source()); <ide> out = new UnmodifiableMapEntry(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(KeyValue);;MapKey of Argument[0];MapKey of Argument[-1];value" <ide> UnmodifiableMapEntry out = null; <del> KeyValue in = (KeyValue)newMAKVWithMapKey(source()); <add> KeyValue in = newMAKVWithMapKey(source()); <ide> out = new UnmodifiableMapEntry(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(KeyValue);;MapValue of Argument[0];MapValue of Argument[-1];value" <ide> UnmodifiableMapEntry out = null; <del> KeyValue in = (KeyValue)newMAKVWithMapValue(source()); <add> KeyValue in = newMAKVWithMapValue(source()); <ide> out = new UnmodifiableMapEntry(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Object,Object);;Argument[0];MapKey of Argument[-1];value" <ide> UnmodifiableMapEntry out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = new UnmodifiableMapEntry(in, null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4.keyvalue;UnmodifiableMapEntry;true;UnmodifiableMapEntry;(Object,Object);;Argument[1];MapValue of Argument[-1];value" <ide> UnmodifiableMapEntry out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = new UnmodifiableMapEntry(null, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> TiedMapEntry in = (TiedMapEntry)newTMEWithMapKey(source()); <add> TiedMapEntry in = newTMEWithMapKey(source()); <ide> out = in.getKey(); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> KeyValue in = (KeyValue)newMAKVWithMapKey(source()); <add> KeyValue in = newMAKVWithMapKey(source()); <ide> out = in.getKey(); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> AbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapKey(source()); <add> AbstractMapEntryDecorator in = newMAMEDWithMapKey(source()); <ide> out = in.getKey(); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;KeyValue;true;getKey;;;MapKey of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> AbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapKey(source()); <add> AbstractKeyValue in = newMAKVWithMapKey(source()); <ide> out = in.getKey(); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> TiedMapEntry in = (TiedMapEntry)newTMEWithMapValue(source()); <add> TiedMapEntry in = newTMEWithMapValue(source()); <ide> out = in.getValue(); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> KeyValue in = (KeyValue)newMAKVWithMapValue(source()); <add> KeyValue in = newMAKVWithMapValue(source()); <ide> out = in.getValue(); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> AbstractMapEntryDecorator in = (MyAbstractMapEntryDecorator)newMAMEDWithMapValue(source()); <add> AbstractMapEntryDecorator in = newMAMEDWithMapValue(source()); <ide> out = in.getValue(); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;KeyValue;true;getValue;;;MapValue of Argument[-1];ReturnValue;value" <ide> Object out = null; <del> AbstractKeyValue in = (MyAbstractKeyValue)newMAKVWithMapValue(source()); <add> AbstractKeyValue in = newMAKVWithMapValue(source()); <ide> out = in.getValue(); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;fixedSizeMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.fixedSizeMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;fixedSizeMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.fixedSizeMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;fixedSizeSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); <add> SortedMap in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.fixedSizeSortedMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;fixedSizeSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); <add> SortedMap in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.fixedSizeSortedMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;getMap;;;MapValue of Argument[0];ReturnValue;value" <ide> Map out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.getMap(in, null, null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;getMap;;;MapValue of Argument[0];ReturnValue;value" <ide> Map out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.getMap(in, null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;getObject;;;Argument[2];ReturnValue;value" <ide> Object out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> out = MapUtils.getObject(null, null, in); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;getObject;;;MapValue of Argument[0];ReturnValue;value" <ide> Object out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.getObject(in, null, null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;getObject;;;MapValue of Argument[0];ReturnValue;value" <ide> Object out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.getObject(in, null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;getString;;;MapValue of Argument[0];ReturnValue;value" <ide> String out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.getString(in, null, null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;getString;;;MapValue of Argument[0];ReturnValue;value" <ide> String out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.getString(in, null); <ide> sink(out); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;invertMap;;;MapKey of Argument[0];MapValue of ReturnValue;value" <ide> Map out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.invertMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;invertMap;;;MapValue of Argument[0];MapKey of ReturnValue;value" <ide> Map out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.invertMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;iterableMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.iterableMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;iterableMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.iterableMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;iterableSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> IterableSortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); <add> SortedMap in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.iterableSortedMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;iterableSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> IterableSortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); <add> SortedMap in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.iterableSortedMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.lazyMap(in, (Transformer)null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.lazyMap(in, (Factory)null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.lazyMap(in, (Transformer)null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;lazyMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.lazyMap(in, (Factory)null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); <add> SortedMap in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.lazySortedMap(in, (Transformer)null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); <add> SortedMap in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.lazySortedMap(in, (Factory)null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); <add> SortedMap in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.lazySortedMap(in, (Transformer)null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;lazySortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); <add> SortedMap in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.lazySortedMap(in, (Factory)null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> MultiValueMap out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.multiValueMap(in, (Factory)null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> MultiValueMap out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.multiValueMap(in, (Class)null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> MultiValueMap out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.multiValueMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> MultiValueMap out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.multiValueMap(in, (Factory)null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> MultiValueMap out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.multiValueMap(in, (Class)null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;multiValueMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> MultiValueMap out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.multiValueMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;orderedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> OrderedMap out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.orderedMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;orderedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> OrderedMap out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.orderedMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;populateMap;(Map,Iterable,Transformer);;Element of Argument[1];MapValue of Argument[0];value" <ide> Map out = null; <del> Iterable in = (Iterable)newWithElement(source()); <add> Iterable in = newWithElement((String)source()); <ide> MapUtils.populateMap(out, in, (Transformer)null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> // which overload it should choose unless you put the generic types in correctly <ide> // "org.apache.commons.collections4;MapUtils;true;populateMap;(MultiMap,Iterable,Transformer);;Element of Argument[1];MapValue of Argument[0];value" <ide> MultiMap<Integer, String> out = null; <del> Iterable<String> in = (Iterable<String>)newWithElement(source()); <add> Iterable<String> in = newWithElement((String)source()); <ide> MapUtils.populateMap(out, in, (Transformer<String, Integer>)null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;predicatedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.predicatedMap(in, null, null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;predicatedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.predicatedMap(in, null, null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;predicatedSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); <add> SortedMap in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.predicatedSortedMap(in, null, null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;predicatedSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); <add> SortedMap in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.predicatedSortedMap(in, null, null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapKey of Argument[0];value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(source()); <add> Object[] in = newWithArrayElement(source()); <ide> MapUtils.putAll(out, in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapKey of ReturnValue;value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(source()); <add> Object[] in = newWithArrayElement(source()); <ide> out = MapUtils.putAll(null, in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapValue of Argument[0];value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(source()); <add> Object[] in = newWithArrayElement(source()); <ide> MapUtils.putAll(out, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of Argument[1];MapValue of ReturnValue;value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(source()); <add> Object[] in = newWithArrayElement(source()); <ide> out = MapUtils.putAll(null, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapKey of Argument[0];value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(newWithArrayElement(source())); <add> Object[] in = newWithArrayElement(newWithArrayElement(source())); <ide> MapUtils.putAll(out, in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapKey of ReturnValue;value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(newWithArrayElement(source())); <add> Object[] in = newWithArrayElement(newWithArrayElement(source())); <ide> out = MapUtils.putAll(null, in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapValue of Argument[0];value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(newWithArrayElement(source())); <add> Object[] in = newWithArrayElement(newWithArrayElement(source())); <ide> MapUtils.putAll(out, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;ArrayElement of ArrayElement of Argument[1];MapValue of ReturnValue;value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(newWithArrayElement(source())); <add> Object[] in = newWithArrayElement(newWithArrayElement(source())); <ide> out = MapUtils.putAll(null, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapKey of ArrayElement of Argument[1];MapKey of Argument[0];value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(newMAKVWithMapKey(source())); <add> Object[] in = newWithArrayElement(newMAKVWithMapKey(source())); <ide> MapUtils.putAll(out, in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapKey of ArrayElement of Argument[1];MapKey of ReturnValue;value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(newMAKVWithMapKey(source())); <add> Object[] in = newWithArrayElement(newMAKVWithMapKey(source())); <ide> out = MapUtils.putAll(null, in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapValue of ArrayElement of Argument[1];MapValue of Argument[0];value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(newMAKVWithMapValue(source())); <add> Object[] in = newWithArrayElement(newMAKVWithMapValue(source())); <ide> MapUtils.putAll(out, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;putAll;;;MapValue of ArrayElement of Argument[1];MapValue of ReturnValue;value" <ide> Map out = null; <del> Object[] in = (Object[])newWithArrayElement(newMAKVWithMapValue(source())); <add> Object[] in = newWithArrayElement(newMAKVWithMapValue(source())); <ide> out = MapUtils.putAll(null, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;safeAddToMap;;;Argument[1];MapKey of Argument[0];value" <ide> Map out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> MapUtils.safeAddToMap(out, in, null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;safeAddToMap;;;Argument[2];MapValue of Argument[0];value" <ide> Map out = null; <del> Object in = (Object)source(); <add> Object in = source(); <ide> MapUtils.safeAddToMap(out, null, in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;synchronizedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> Map out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.synchronizedMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;synchronizedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> Map out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.synchronizedMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;synchronizedSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); <add> SortedMap in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.synchronizedSortedMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;synchronizedSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); <add> SortedMap in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.synchronizedSortedMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;toMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> Map out = null; <del> ResourceBundle in = (ResourceBundle)newRBWithMapKey(source()); <add> ResourceBundle in = newRBWithMapKey(source()); <ide> out = MapUtils.toMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;toMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> Map out = null; <del> ResourceBundle in = (ResourceBundle)newRBWithMapValue(source()); <add> ResourceBundle in = newRBWithMapValue(source()); <ide> out = MapUtils.toMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;transformedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.transformedMap(in, null, null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;transformedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> IterableMap out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.transformedMap(in, null, null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;transformedSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); <add> SortedMap in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.transformedSortedMap(in, null, null); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;transformedSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); <add> SortedMap in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.transformedSortedMap(in, null, null); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;unmodifiableMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> Map out = null; <del> Map in = (Map)newTreeMapWithMapKey(source()); <add> Map in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.unmodifiableMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;unmodifiableMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> Map out = null; <del> Map in = (Map)newTreeMapWithMapValue(source()); <add> Map in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.unmodifiableMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;unmodifiableSortedMap;;;MapKey of Argument[0];MapKey of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapKey(source()); <add> SortedMap in = newTreeMapWithMapKey(source()); <ide> out = MapUtils.unmodifiableSortedMap(in); <ide> sink(getMapKey(out)); // $hasValueFlow <ide> } <ide> { <ide> // "org.apache.commons.collections4;MapUtils;true;unmodifiableSortedMap;;;MapValue of Argument[0];MapValue of ReturnValue;value" <ide> SortedMap out = null; <del> SortedMap in = (SortedMap)newTreeMapWithMapValue(source()); <add> SortedMap in = newTreeMapWithMapValue(source()); <ide> out = MapUtils.unmodifiableSortedMap(in); <ide> sink(getMapValue(out)); // $hasValueFlow <ide> }
Java
epl-1.0
04dc55a86b195178705e37f993cc0eef9228f452
0
sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.internal.ui.dnd; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.model.schematic.HandleAdapterFactory; import org.eclipse.birt.report.designer.core.model.schematic.ListBandProxy; import org.eclipse.birt.report.designer.core.model.schematic.TableHandleAdapter; import org.eclipse.birt.report.designer.data.ui.dataset.DataSetUIUtil; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.AddGroupAction; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportElementEditPart; import org.eclipse.birt.report.designer.internal.ui.util.DataUtil; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.util.ExpressionUtility; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.designer.util.DNDUtil; import org.eclipse.birt.report.designer.util.IVirtualValidator; import org.eclipse.birt.report.model.api.ActionHandle; import org.eclipse.birt.report.model.api.CachedMetaDataHandle; import org.eclipse.birt.report.model.api.CellHandle; import org.eclipse.birt.report.model.api.ColumnHintHandle; import org.eclipse.birt.report.model.api.ComputedColumnHandle; import org.eclipse.birt.report.model.api.DataItemHandle; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DerivedDataSetHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.Expression; import org.eclipse.birt.report.model.api.ExpressionType; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.FreeFormHandle; import org.eclipse.birt.report.model.api.GridHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.JointDataSetHandle; import org.eclipse.birt.report.model.api.LabelHandle; import org.eclipse.birt.report.model.api.ListHandle; import org.eclipse.birt.report.model.api.ListingHandle; import org.eclipse.birt.report.model.api.MasterPageHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.ResultSetColumnHandle; import org.eclipse.birt.report.model.api.RowHandle; import org.eclipse.birt.report.model.api.ScalarParameterHandle; import org.eclipse.birt.report.model.api.SlotHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.StyleHandle; import org.eclipse.birt.report.model.api.TableGroupHandle; import org.eclipse.birt.report.model.api.TableHandle; import org.eclipse.birt.report.model.api.VariableElementHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.ReportDesignConstants; import org.eclipse.birt.report.model.api.elements.structures.Action; import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn; import org.eclipse.birt.report.model.api.elements.structures.FormatValue; import org.eclipse.birt.report.model.api.elements.structures.TOC; import org.eclipse.birt.report.model.api.olap.DimensionHandle; import org.eclipse.birt.report.model.api.olap.MeasureHandle; import org.eclipse.birt.report.model.elements.interfaces.IGroupElementModel; import org.eclipse.birt.report.model.util.ModelUtil; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.gef.EditPart; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; /** * Utility for creation from data view to layout */ public class InsertInLayoutUtil { /** * Rule interface for defining insertion rule */ abstract static interface InsertInLayoutRule { public boolean canInsert( ); public Object getInsertPosition( ); public void insert( Object object ) throws SemanticException; } /** * * Rule for inserting label after inserting data set column */ static class LabelAddRule implements InsertInLayoutRule { private Object container; private CellHandle newTarget; public LabelAddRule( Object container ) { this.container = container; } /* * (non-Javadoc) * * @seeorg.eclipse.birt.report.designer.internal.ui.views.actions. * InsertInLayoutAction.InsertInLayoutRule#canInsert() */ public boolean canInsert( ) { if ( container instanceof SlotHandle ) { container = ( (SlotHandle) container ).getElementHandle( ); } if ( !( container instanceof CellHandle ) ) return false; CellHandle cell = (CellHandle) container; // Validates source position of data item boolean canInsert = false; if ( cell.getContainer( ).getContainer( ) instanceof TableGroupHandle ) { canInsert = true; } else { if ( cell.getContainer( ).getContainerSlotHandle( ).getSlotID( ) == TableHandle.DETAIL_SLOT ) { canInsert = true; } } // Validates column count and gets the target if ( canInsert ) { TableHandle table = null; if ( cell.getContainer( ).getContainer( ) instanceof TableHandle ) { table = (TableHandle) cell.getContainer( ).getContainer( ); } else { table = (TableHandle) cell.getContainer( ) .getContainer( ) .getContainer( ); } SlotHandle header = table.getHeader( ); if ( header != null && header.getCount( ) > 0 ) { int columnNum = HandleAdapterFactory.getInstance( ) .getCellHandleAdapter( cell ) .getColumnNumber( ); newTarget = (CellHandle) HandleAdapterFactory.getInstance( ) .getTableHandleAdapter( table ) .getCell( 1, columnNum, false ); return newTarget != null && newTarget.getContent( ).getCount( ) == 0; } } return false; } /** * Returns new Label insert position in form of <code>CellHandle</code> */ public Object getInsertPosition( ) { return newTarget; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil * .InsertInLayoutRule#insert() */ public void insert( Object object ) throws SemanticException { Assert.isTrue( object instanceof DesignElementHandle ); newTarget.addElement( (DesignElementHandle) object, CellHandle.CONTENT_SLOT ); } } /** * * Rule for inserting multiple data into table, and populating adjacent * cells */ static class MultiItemsExpandRule implements InsertInLayoutRule { private Object[] items; private Object target; private int focusIndex = 0; public MultiItemsExpandRule( Object[] items, Object target ) { this.items = items; this.target = target; } /* * (non-Javadoc) * * @seeorg.eclipse.birt.report.designer.internal.ui.views.actions. * InsertInLayoutAction.InsertInLayoutRule#canInsert() */ public boolean canInsert( ) { return items != null && items.length > 1 && target != null && ( target instanceof DesignElementHandle || target instanceof ListBandProxy ); } /** * * Returns multiple insert positions in form of array */ public Object getInsertPosition( ) { Object[] positions = new Object[items.length]; if ( target instanceof CellHandle ) { CellHandle firstCell = (CellHandle) target; TableHandleAdapter tableAdapter = HandleAdapterFactory.getInstance( ) .getTableHandleAdapter( getTableHandle( firstCell ) ); int currentColumn = HandleAdapterFactory.getInstance( ) .getCellHandleAdapter( firstCell ) .getColumnNumber( ); int currentRow = HandleAdapterFactory.getInstance( ) .getCellHandleAdapter( firstCell ) .getRowNumber( ); int columnDiff = currentColumn + items.length - tableAdapter.getColumnCount( ) - 1; // Insert columns if table can not contain all items if ( columnDiff > 0 ) { int insertColumn = tableAdapter.getColumnCount( ); try { tableAdapter.insertColumns( columnDiff, insertColumn ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); return null; } } for ( int i = 0; i < positions.length; i++ ) { positions[i] = tableAdapter.getCell( currentRow, currentColumn++ ); } focusIndex = 0; } else { for ( int i = 0; i < positions.length; i++ ) { positions[i] = target; } focusIndex = items.length - 1; } return positions; } protected ReportItemHandle getTableHandle( CellHandle firstCell ) { DesignElementHandle tableContainer = firstCell.getContainer( ) .getContainer( ); if ( tableContainer instanceof ReportItemHandle ) { return (ReportItemHandle) tableContainer; } return (ReportItemHandle) tableContainer.getContainer( ); } /** * Returns the index of the focus element in the items */ public int getFocusIndex( ) { return focusIndex; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil * .InsertInLayoutRule#insert() */ public void insert( Object object ) throws SemanticException { // TODO Auto-generated method stub } } /** * * Rule for setting key when inserting data set column to group handle */ static class GroupKeySetRule implements InsertInLayoutRule { private Object container; private ResultSetColumnHandle dataSetColumn; public GroupKeySetRule( Object container, ResultSetColumnHandle dataSetColumn ) { this.container = container; this.dataSetColumn = dataSetColumn; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil * .InsertInLayoutRule#canInsert() */ public boolean canInsert( ) { return getGroupContainer( container ) != null && getGroupHandle( container ).getKeyExpr( ) == null && ( getGroupContainer( container ).getDataSet( ) == getDataSetHandle( dataSetColumn ) || getGroupContainer( container ).getDataSet( ) == null ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil * .InsertInLayoutRule#getInsertPosition() */ public Object getInsertPosition( ) { return null; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil * .InsertInLayoutRule#insert(java.lang.Object) */ public void insert( Object object ) throws SemanticException { Assert.isTrue( object instanceof ResultSetColumnHandle ); Assert.isTrue( object == dataSetColumn || object == null ); ReportItemHandle groupContainer = getGroupContainer( container ); DataSetHandle dataSetHandle = null; dataSetHandle = groupContainer.getDataSet( ); if ( dataSetHandle == null ) { for ( DesignElementHandle elementHandle = groupContainer; elementHandle != null; elementHandle = elementHandle.getContainer( ) ) { if ( elementHandle instanceof ListingHandle && ( dataSetHandle = ( (ListingHandle) elementHandle ).getDataSet( ) ) != null && ( dataSetHandle == getDataSetHandle( dataSetColumn ) ) ) { break; } } } if ( dataSetHandle == null || dataSetHandle != getDataSetHandle( dataSetColumn ) ) { getGroupContainer( container ).setDataSet( getDataSetHandle( dataSetColumn ) ); } getGroupHandle( container ).setKeyExpr( DEUtil.getColumnExpression( dataSetColumn.getColumnName( ) ) ); } protected DataSetHandle getDataSetHandle( ResultSetColumnHandle model ) { return (DataSetHandle) model.getElementHandle( ); } protected GroupHandle getGroupHandle( Object target ) { DesignElementHandle handle = null; if ( target instanceof CellHandle ) { handle = ( (CellHandle) target ).getContainer( ).getContainer( ); } else if ( target instanceof ListBandProxy ) { handle = ( (ListBandProxy) target ).getElemtHandle( ); } if ( handle instanceof GroupHandle ) { return (GroupHandle) handle; } return null; } protected ReportItemHandle getGroupContainer( Object target ) { GroupHandle group = getGroupHandle( target ); if ( group != null && group.getContainer( ) instanceof ReportItemHandle ) return (ReportItemHandle) group.getContainer( ); return null; } } /** * Creates a object to insert. * * @param insertObj * object insert to layout * @param target * insert target, like cell or ListBandProxy * @param targetParent * insert target's non-dummy container, like table or list * @return new object in layout * @throws SemanticException */ public static DesignElementHandle performInsert( Object insertObj, Object target, Object targetParent ) throws SemanticException { Assert.isNotNull( insertObj ); Assert.isNotNull( target ); if ( insertObj instanceof DataSetHandle ) { return performInsertDataSet( (DataSetHandle) insertObj ); } else if ( insertObj instanceof ResultSetColumnHandle ) { return performInsertDataSetColumn( (ResultSetColumnHandle) insertObj, target, targetParent ); } else if ( insertObj instanceof ScalarParameterHandle ) { return performInsertParameter( (ScalarParameterHandle) insertObj ); } else if ( insertObj instanceof VariableElementHandle ) { return performInsertVariable( (VariableElementHandle) insertObj ); } else if ( insertObj instanceof String ) { // Such as invalid group key return performInsertString( (String) insertObj, target ); } else if ( insertObj instanceof Object[] ) { return performMultiInsert( (Object[]) insertObj, target, targetParent ); } else if ( insertObj instanceof IStructuredSelection ) { return performMultiInsert( ( (IStructuredSelection) insertObj ).toArray( ), target, targetParent ); } return null; } /** * Creates a object, "Add" operation to layout needs to handle later. * <p> * Must make sure operation legal before execution. * </p> * * @param insertObj * object insert to layout * @param editPart * target EditPart * @return new object in layout * @throws SemanticException */ public static DesignElementHandle performInsert( Object insertObj, EditPart editPart ) throws SemanticException { Assert.isNotNull( insertObj ); Assert.isNotNull( editPart ); return performInsert( insertObj, editPart.getModel( ), editPart.getParent( ).getModel( ) ); } /** * Creates multiple objects * * @param array * multiple creation source * @param target * @param targetParent * @return first creation in layout * @throws SemanticException */ protected static DesignElementHandle performMultiInsert( Object[] array, Object target, Object targetParent ) throws SemanticException { DesignElementHandle result = null; MultiItemsExpandRule rule = new MultiItemsExpandRule( array, target ); if ( rule.canInsert( ) ) { Object[] positions = (Object[]) rule.getInsertPosition( ); if ( positions != null ) { for ( int i = 0; i < array.length; i++ ) { DesignElementHandle newObj = performInsert( array[i], positions[i], targetParent ); if ( i == rule.getFocusIndex( ) ) { result = newObj; } else { DNDUtil.addElementHandle( positions[i], newObj ); } } } } else if ( array.length != 0 ) { result = performInsert( array[0], target, targetParent ); } return result; } public static DataItemHandle performInsertParameter( ScalarParameterHandle model ) throws SemanticException { // DataItemHandle dataHandle = SessionHandleAdapter.getInstance( ) // .getReportDesignHandle( ) // .getElementFactory( ) // .newDataItem( null ); DataItemHandle dataHandle = DesignElementFactory.getInstance( ) .newDataItem( null ); ComputedColumn bindingColumn = StructureFactory.newComputedColumn( dataHandle, model.getName( ) ); ExpressionUtility.setBindingColumnExpression( model, bindingColumn ); // hardcode // parameter's type datatime is not equals data's. String paramType = model.getDataType( ); if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( paramType ) ) paramType = DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME; bindingColumn.setDataType( paramType ); dataHandle.addColumnBinding( bindingColumn, false ); dataHandle.setResultSetColumn( bindingColumn.getName( ) ); return dataHandle; } public static DataItemHandle performInsertVariable( VariableElementHandle model ) throws SemanticException { DataItemHandle dataHandle = DesignElementFactory.getInstance( ) .newDataItem( null ); ComputedColumn bindingColumn = StructureFactory.newComputedColumn( dataHandle, model.getName( ) ); bindingColumn.setExpression( DEUtil.getExpression( model ) ); // FIXME, currently varialbe does not support type String paramType = DesignChoiceConstants.COLUMN_DATA_TYPE_STRING; bindingColumn.setDataType( paramType ); dataHandle.addColumnBinding( bindingColumn, false ); dataHandle.setResultSetColumn( bindingColumn.getName( ) ); return dataHandle; } private static GroupHandle addGroupHandle(TableHandle tableHandle, String columnName, DataItemHandle dataHandle)throws SemanticException { DesignElementFactory factory = DesignElementFactory.getInstance( tableHandle.getModuleHandle( ) ); GroupHandle groupHandle = factory.newTableGroup( ); int columnCount = tableHandle.getColumnCount( ); groupHandle.getHeader( ) .add( factory.newTableRow( columnCount ) ); groupHandle.getFooter( ) .add( factory.newTableRow( columnCount ) ); groupHandle.setName( columnName ); Expression newKeyExpr = new Expression( ExpressionUtility.getColumnExpression(columnName, ExpressionUtility.getExpressionConverter( ExpressionType.JAVASCRIPT ) ), ExpressionType.JAVASCRIPT ); groupHandle.setExpressionProperty( IGroupElementModel.KEY_EXPR_PROP, newKeyExpr ); TOC toc = StructureFactory.createTOC( ); toc.setExpression( ExpressionUtility.getColumnExpression( columnName, ExpressionUtility.getExpressionConverter( ExpressionType.JAVASCRIPT ) ) ); groupHandle.addTOC( toc ); //slotHandle.add( groupHandle, slotHandle.getCount( ) ); RowHandle rowHandle = ( (RowHandle) groupHandle.getHeader( ) .get( 0 ) ); CellHandle cellHandle = (CellHandle) rowHandle.getCells( ) .get( 0 ); cellHandle.getContent( ).add( dataHandle ); return groupHandle; } /** * Inserts dataset column into the target. Add label or group key if * possible * * @param model * column item * @param target * insert target like cell or ListBandProxy * @param targetParent * target container like table or list * @return to be inserted data item * @throws SemanticException */ protected static DesignElementHandle performInsertDataSetColumn( ResultSetColumnHandle model, Object target, Object targetParent ) throws SemanticException { /* * search the target container, if container has the same dataset, add * the column binding if it does not exist in the container. If the * container's dataset is not the dragged dataset column's dataset, * column binding will be added to the new dataitem, and set dataitem's * dataset with the dragged dataset column's dataset. */ DataItemHandle dataHandle = DesignElementFactory.getInstance( ) .newDataItem( null ); DataSetHandle dataSet = (DataSetHandle) model.getElementHandle( ); if ( targetParent instanceof TableHandle ) { TableHandle tableHandle = (TableHandle) targetParent; if ( tableHandle.isSummaryTable( ) ) { tableHandle.setDataSet( dataSet ); if ( DesignChoiceConstants.ANALYSIS_TYPE_DIMENSION.equals( UIUtil.getColumnAnalysis( model ) ) ) { ComputedColumn bindingColumn = StructureFactory.newComputedColumn( tableHandle, model.getColumnName( ) ); bindingColumn.setDataType( model.getDataType( ) ); ExpressionUtility.setBindingColumnExpression( model, bindingColumn ); bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model ) ); String displayKey = UIUtil.getColumnDisplayNameKey( model ); if ( displayKey != null ) bindingColumn.setDisplayNameID( displayKey ); tableHandle.addColumnBinding( bindingColumn, false ); dataHandle.setResultSetColumn( model.getColumnName( ) ); SlotHandle slotHandle = tableHandle.getGroups( ); for ( Object o : slotHandle.getContents( ) ) { GroupHandle group = (GroupHandle) o; if ( group.getName( ).equals( model.getColumnName( ) ) ) return null; } return addGroupHandle( tableHandle, model.getColumnName( ), dataHandle ); } else if (DesignChoiceConstants.ANALYSIS_TYPE_ATTRIBUTE.equals( UIUtil.getColumnAnalysis( model ) )) { DataSetHandle dataset = (DataSetHandle) model.getElementHandle( ); String str = UIUtil.getAnalysisColumn( model ); String type = ""; //$NON-NLS-1$ ResultSetColumnHandle newResultColumn = null; if (str != null) { List columnList = DataUtil.getColumnList( dataset ); for ( int i = 0; i < columnList.size( ); i++ ) { ResultSetColumnHandle resultSetColumn = (ResultSetColumnHandle) columnList.get( i ); if (str.equals( resultSetColumn.getColumnName( ) )) { newResultColumn = resultSetColumn; break; } } for ( Iterator iter = dataset.getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP ) .iterator( ); iter.hasNext( ); ) { ColumnHintHandle element = (ColumnHintHandle) iter.next( ); if ( element.getColumnName( ).equals( str ) ||str.equals( element.getAlias( ) ) ) { type = element.getAnalysis( ); break; } } if (DesignChoiceConstants.ANALYSIS_TYPE_DIMENSION.equals( type )) { boolean hasGroup = false; SlotHandle slotHandle = tableHandle.getGroups( ); for ( Object o : slotHandle.getContents( ) ) { GroupHandle group = (GroupHandle) o; if ( group.getName( ).equals( str ) ) hasGroup = true; } if (!hasGroup) { ComputedColumn bindingColumn = StructureFactory.newComputedColumn( tableHandle, model.getColumnName( ) ); bindingColumn.setDataType( model.getDataType( )); ExpressionUtility.setBindingColumnExpression( model, bindingColumn ); bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model ) ); String displayKey = UIUtil.getColumnDisplayNameKey( model ); if ( displayKey != null ) bindingColumn.setDisplayNameID( displayKey ); tableHandle.addColumnBinding( bindingColumn, false ); dataHandle.setResultSetColumn( model.getColumnName( ) ); bindingColumn = StructureFactory.newComputedColumn( tableHandle, newResultColumn.getColumnName( ) ); bindingColumn.setDataType( newResultColumn.getDataType( )); ExpressionUtility.setBindingColumnExpression( newResultColumn, bindingColumn ); bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( newResultColumn ) ); displayKey = UIUtil.getColumnDisplayNameKey( newResultColumn ); if ( displayKey != null ) bindingColumn.setDisplayNameID( displayKey ); tableHandle.addColumnBinding( bindingColumn, false ); return addGroupHandle( tableHandle, newResultColumn.getColumnName( ), dataHandle ); } } } if ( target instanceof CellHandle) { ComputedColumn column = StructureFactory.newComputedColumn( tableHandle, model.getColumnName( ) ); ComputedColumnHandle binding = DEUtil.addColumn( tableHandle, column, true ); //binding.setAggregateFunction( DesignChoiceConstants.MEASURE_FUNCTION_MAX ); //binding.setExpression( ExpressionUtil.createJSRowExpression( model.getColumnName( ) ) ); ExpressionUtility.setBindingColumnExpression( model, column ); dataHandle.setResultSetColumn( binding.getName( ) ); InsertInLayoutRule rule = new GroupKeySetRule( target, model ); if ( rule.canInsert( ) ) { rule.insert( model ); } return dataHandle; } } else if (DesignChoiceConstants.ANALYSIS_TYPE_MEASURE.equals( UIUtil.getColumnAnalysis( model ))) { CellHandle cellHandle = (CellHandle) target; ComputedColumn column = StructureFactory.newComputedColumn( tableHandle, model.getColumnName( ) ); ComputedColumnHandle binding = DEUtil.addColumn( tableHandle, column, true ); DesignElementHandle group = cellHandle.getContainer( ) .getContainer( ); if (group instanceof GroupHandle) { binding.setAggregateOn( ((GroupHandle)group).getName( ) ); } else { binding.setAggregateOn(null); } if ( DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER.equals( model.getDataType( ) ) || DesignChoiceConstants.COLUMN_DATA_TYPE_FLOAT.equals( model.getDataType( ) ) || DesignChoiceConstants.COLUMN_DATA_TYPE_DECIMAL.equals( model.getDataType( ) ) ) { binding.setAggregateFunction( DesignChoiceConstants.MEASURE_FUNCTION_COUNT ); } else { binding.setAggregateFunction( DesignChoiceConstants.MEASURE_FUNCTION_SUM ); } //binding.setExpression( ExpressionUtil.createJSRowExpression( model.getColumnName( ) ) ); ExpressionUtility.setBindingColumnExpression( model, column ); dataHandle.setResultSetColumn( binding.getName( ) ); InsertInLayoutRule rule = new GroupKeySetRule( target, model ); if ( rule.canInsert( ) ) { rule.insert( model ); } return dataHandle; } // else if ( DesignChoiceConstants.ANALYSIS_TYPE_MEASURE.equals( UIUtil.getColumnAnalysis( model ) ) // || DesignChoiceConstants.ANALYSIS_TYPE_ATTRIBUTE.equals( UIUtil.getColumnAnalysis( model ) ) ) // { // // check target is a group cell // if ( target instanceof CellHandle // && ( (CellHandle) target ).getContainer( ) // .getContainer( ) instanceof GroupHandle ) // { // CellHandle cellHandle = (CellHandle) target; // GroupHandle group = (GroupHandle) cellHandle.getContainer( ) // .getContainer( ); // // ComputedColumn column = StructureFactory.newComputedColumn( tableHandle, // model.getColumnName( ) ); // ComputedColumnHandle binding = DEUtil.addColumn( tableHandle, // column, // true ); // binding.setAggregateOn( group.getName( ) ); // // if ( DesignChoiceConstants.ANALYSIS_TYPE_MEASURE.equals( UIUtil.getColumnAnalysis( model ) ) ) // binding.setAggregateFunction( DesignChoiceConstants.MEASURE_FUNCTION_SUM ); // else // binding.setAggregateFunction( DesignChoiceConstants.MEASURE_FUNCTION_MAX ); // // binding.setExpression( ExpressionUtil.createJSRowExpression( model.getColumnName( ) ) ); // dataHandle.setResultSetColumn( binding.getName( ) ); // // InsertInLayoutRule rule = new LabelAddRule( target ); // if ( rule.canInsert( ) ) // { // // LabelHandle label = // // SessionHandleAdapter.getInstance( ) // // .getReportDesignHandle( ) // // .getElementFactory( ) // // .newLabel( null ); // LabelHandle label = DesignElementFactory.getInstance( ) // .newLabel( null ); // label.setText( UIUtil.getColumnDisplayName( model ) ); // rule.insert( label ); // } // // rule = new GroupKeySetRule( target, model ); // if ( rule.canInsert( ) ) // { // rule.insert( model ); // } // // return dataHandle; // } // } } } dataHandle.setResultSetColumn( model.getColumnName( ) ); formatDataHandle( dataHandle, model ); if ( targetParent instanceof ReportItemHandle ) { ReportItemHandle container = (ReportItemHandle) targetParent; // ComputedColumn bindingColumn = // StructureFactory.newComputedColumn( container, // model.getColumnName( ) ); // bindingColumn.setDataType( model.getDataType( ) ); // ExpressionUtility.setBindingColumnExpression( model, // bindingColumn ); // bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model // ) ); // String displayKey = UIUtil.getColumnDisplayNameKey( model ); // if ( displayKey != null ) // bindingColumn.setDisplayNameID( displayKey ); // if ( target instanceof DesignElementHandle ) // { // if ( ExpressionUtil.hasAggregation( bindingColumn.getExpression( // ) ) ) // { // String groupType = DEUtil.getGroupControlType( // (DesignElementHandle) target ); // if ( groupType.equals( DEUtil.TYPE_GROUP_GROUP ) ) // bindingColumn.setAggregateOn( ( (GroupHandle) DEUtil.getGroups( // (DesignElementHandle) target ) // .get( 0 ) ).getName( ) ); // else if ( groupType.equals( DEUtil.TYPE_GROUP_LISTING ) ) // bindingColumn.setAggregateOn( null ); // } // } ReportItemHandle root = DEUtil.getBindingRoot( container ); if ( root == null ) { container = DEUtil.getListingContainer( container ); // if listing handle is null, then binding to self, else bind to // list handle. if ( container == null ) { ComputedColumn bindingColumn = createBindingColumn( target, dataHandle, model ); dataHandle.setDataSet( dataSet ); dataHandle.addColumnBinding( bindingColumn, false ); } else { ComputedColumn bindingColumn = createBindingColumn( target, container, model ); container.setDataSet( dataSet ); container.addColumnBinding( bindingColumn, false ); } } else if ( root.getDataSet( ) == dataSet ) { container = DEUtil.getBindingHolder( container ); ComputedColumn bindingColumn = createBindingColumn( target, container, model ); container.addColumnBinding( bindingColumn, false ); } else { ReportItemHandle listingHandle = DEUtil.getListingContainer( container ); if ( listingHandle != null && DEUtil.getBindingRoot( listingHandle ) == root && DEUtil.getBindingHolder( listingHandle ) != listingHandle ) { ComputedColumn bindingColumn = createBindingColumn( target, listingHandle, model ); listingHandle.setDataSet( dataSet ); listingHandle.addColumnBinding( bindingColumn, false ); } // do nothing, forbid dragging into the place. } // // DataSetHandle containerDataSet = DEUtil.getBindingRoot( container // ) // .getDataSet( ); // DataSetHandle itsDataSet = null; // if ( container != null ) // { // itsDataSet = container.getDataSet( ); // } // container = DEUtil.getListingContainer( container ); // if ( ( itsDataSet == null && ( !dataSet.equals( containerDataSet // ) ) ) // && container != null ) // { // container.setDataSet( dataSet ); // containerDataSet = dataSet; // } // if ( dataSet.equals( containerDataSet ) && container != null ) // { // if ( container.getDataBindingReference( ) != null ) // container.getDataBindingReference( ) // .addColumnBinding( bindingColumn, false ); // else // container.addColumnBinding( bindingColumn, false ); // } // else // { // // should not happen // dataHandle.setDataSet( dataSet ); // dataHandle.addColumnBinding( bindingColumn, false ); // } // GroupHandle groupHandle = getGroupHandle( target ); // if ( groupHandle != null ) // { // ComputedColumn bindingColumn = // StructureFactory.newComputedColumn( groupHandle, // model.getColumnName( ) ); // // bindingColumn.setColumnName( model.getColumnName( ) ); // bindingColumn.setDataType( model.getDataType( ) ); // bindingColumn.setExpression( DEUtil.getExpression( model ) ); // // groupHandle.addColumnBinding( bindingColumn, false ); // } // else // { // ComputedColumn bindingColumn = // StructureFactory.newComputedColumn( container, // model.getColumnName( ) ); // bindingColumn.setDataType( model.getDataType( ) ); // bindingColumn.setExpression( DEUtil.getExpression( model ) ); // container.addColumnBinding( bindingColumn, false ); // } // ComputedColumn bindingColumn = // StructureFactory.createComputedColumn( ); // bindingColumn.setName( model.getColumnName( ) ); // bindingColumn.setDataType( model.getDataType( ) ); // bindingColumn.setExpression( DEUtil.getExpression( model ) ); // GroupHandle groupHandle = getGroupHandle( target ); // // if ( groupHandle != null ) // { // for ( Iterator iter = groupHandle.getColumnBindings( ) // .iterator( ); iter.hasNext( ); ) // { // ComputedColumnHandle element = (ComputedColumnHandle) iter.next( // ); // if ( element.getStructure( ).equals( bindingColumn ) ) // { // bindingExist = true; // break; // } // } // } // else // { // for ( Iterator iter = container.getColumnBindings( ).iterator( ); // iter.hasNext( ); ) // { // ComputedColumnHandle element = (ComputedColumnHandle) iter.next( // ); // if ( element.getStructure( ).equals( bindingColumn ) ) // { // bindingExist = true; // break; // } // } // // } } else { ComputedColumn bindingColumn = StructureFactory.newComputedColumn( dataHandle, model.getColumnName( ) ); bindingColumn.setDataType( model.getDataType( ) ); ExpressionUtility.setBindingColumnExpression( model, bindingColumn ); bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model ) ); String displayKey = UIUtil.getColumnDisplayNameKey( model ); if ( displayKey != null ) bindingColumn.setDisplayNameID( displayKey ); if ( target instanceof DesignElementHandle ) { if ( ExpressionUtil.hasAggregation( bindingColumn.getExpression( ) ) ) { String groupType = DEUtil.getGroupControlType( (DesignElementHandle) target ); if ( groupType.equals( DEUtil.TYPE_GROUP_GROUP ) ) bindingColumn.setAggregateOn( ( (GroupHandle) DEUtil.getGroups( (DesignElementHandle) target ) .get( 0 ) ).getName( ) ); else if ( groupType.equals( DEUtil.TYPE_GROUP_LISTING ) ) bindingColumn.setAggregateOn( null ); } } dataHandle.addColumnBinding( bindingColumn, false ); dataHandle.setDataSet( dataSet ); } ActionHandle actionHandle = UIUtil.getColumnAction( model ); if ( actionHandle != null ) { List source = new ArrayList( ); source.add( actionHandle.getStructure( ) ); List newAction = ModelUtil.cloneStructList( source ); dataHandle.setAction( (Action) newAction.get( 0 ) ); } // if ( !bindingExist ) // { // ComputedColumn bindingColumn = StructureFactory.newComputedColumn( // dataHandle, // model.getColumnName( ) ); // bindingColumn.setDataType( model.getDataType( ) ); // bindingColumn.setExpression( DEUtil.getExpression( model ) ); // dataHandle.addColumnBinding( bindingColumn, false ); // dataHandle.setDataSet( dataSet ); // } InsertInLayoutRule rule = new LabelAddRule( target ); if ( rule.canInsert( ) ) { // LabelHandle label = SessionHandleAdapter.getInstance( ) // .getReportDesignHandle( ) // .getElementFactory( ) // .newLabel( null ); LabelHandle label = DesignElementFactory.getInstance( ) .newLabel( null ); label.setText( UIUtil.getColumnDisplayName( model ) ); String displayKey = UIUtil.getColumnDisplayNameKey( model ); if ( displayKey != null ) { label.setTextKey( displayKey ); } rule.insert( label ); } rule = new GroupKeySetRule( target, model ); if ( rule.canInsert( ) ) { rule.insert( model ); } return dataHandle; } /** * create a ComputedColumn object * * @param target * where data item will be inserted. * @param bindingHolder * where the ComputedColumn will be inserted. * @param model * column item * @return */ private static ComputedColumn createBindingColumn( Object target, ReportItemHandle bindingHolder, ResultSetColumnHandle model ) { ComputedColumn bindingColumn = StructureFactory.newComputedColumn( bindingHolder, model.getColumnName( ) ); bindingColumn.setDataType( model.getDataType( ) ); ExpressionUtility.setBindingColumnExpression( model, bindingColumn ); bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model ) ); String displayKey = UIUtil.getColumnDisplayNameKey( model ); if ( displayKey != null ) bindingColumn.setDisplayNameID( displayKey ); if ( target instanceof DesignElementHandle ) { if ( ExpressionUtil.hasAggregation( bindingColumn.getExpression( ) ) ) { String groupType = DEUtil.getGroupControlType( (DesignElementHandle) target ); if ( groupType.equals( DEUtil.TYPE_GROUP_GROUP ) ) bindingColumn.setAggregateOn( ( (GroupHandle) DEUtil.getGroups( (DesignElementHandle) target ) .get( 0 ) ).getName( ) ); else if ( groupType.equals( DEUtil.TYPE_GROUP_LISTING ) ) bindingColumn.setAggregateOn( null ); } } return bindingColumn; } // private static GroupHandle getGroupHandle( Object target ) // { // DesignElementHandle handle = null; // if ( target instanceof CellHandle ) // { // handle = ( (CellHandle) target ).getContainer( ).getContainer( ); // } // else if ( target instanceof ListBandProxy ) // { // handle = ( (ListBandProxy) target ).getElemtHandle( ); // } // // if ( handle instanceof GroupHandle ) // { // return (GroupHandle) handle; // } // return null; // } /** * Inserts invalid column string into the target. Add label if possible * * @param expression * invalid column or other expression * @param target * insert target like cell or ListBandProxy * @return to be inserted data item * @throws SemanticException */ protected static DesignElementHandle performInsertString( String expression, Object target ) throws SemanticException { // DataItemHandle dataHandle = SessionHandleAdapter.getInstance( ) // .getReportDesignHandle( ) // .getElementFactory( ) // .newDataItem( null ); DataItemHandle dataHandle = DesignElementFactory.getInstance( ) .newDataItem( null ); dataHandle.setResultSetColumn( expression ); InsertInLayoutRule rule = new LabelAddRule( target ); if ( rule.canInsert( ) ) { // LabelHandle label = SessionHandleAdapter.getInstance( ) // .getReportDesignHandle( ) // .getElementFactory( ) // .newLabel( null ); LabelHandle label = DesignElementFactory.getInstance( ) .newLabel( null ); label.setText( expression ); rule.insert( label ); } return dataHandle; } protected static TableHandle performInsertDataSet( DataSetHandle model ) throws SemanticException { // DataSetItemModel[] columns = DataSetManager.getCurrentInstance( ) // .getColumns( model, false ); // if ( columns == null || columns.length == 0 ) // { // return null; // } // // TableHandle tableHandle = SessionHandleAdapter.getInstance( ) // // .getReportDesignHandle( ) // // .getElementFactory( ) // // .newTableItem( null, columns.length ); CachedMetaDataHandle cachedMetadata = DataSetUIUtil.getCachedMetaDataHandle( model ); List columList = new ArrayList( ); for ( Iterator iter = cachedMetadata.getResultSet( ).iterator( ); iter.hasNext( ); ) { ResultSetColumnHandle element = (ResultSetColumnHandle) iter.next( ); columList.add( element ); } ResultSetColumnHandle[] columns = (ResultSetColumnHandle[]) columList.toArray( new ResultSetColumnHandle[columList.size( )] ); TableHandle tableHandle = DesignElementFactory.getInstance( ) .newTableItem( null, columns.length ); setInitWidth( tableHandle ); insertToCell( model, tableHandle, tableHandle.getHeader( ), columns, true ); insertToCell( model, tableHandle, tableHandle.getDetail( ), columns, false ); tableHandle.setDataSet( model ); return tableHandle; } /** * Validates object can be inserted to layout. Support the multiple. * * @param insertObj * single inserted object or multi-objects * @param targetPart * @return if can be inserted to layout */ public static boolean handleValidateInsertToLayout( Object insertObj, EditPart targetPart ) { if ( targetPart == null ) { return false; } if ( insertObj instanceof Object[] ) { Object[] array = (Object[]) insertObj; if ( !checkSameDataSetInMultiColumns( array ) ) { return false; } if ( !checkContainContainMulitItem( array, targetPart.getModel( ) ) ) { return false; } for ( int i = 0; i < array.length; i++ ) { if ( !handleValidateInsertToLayout( array[i], targetPart ) ) { return false; } } return true; } else if ( insertObj instanceof IStructuredSelection ) { return handleValidateInsertToLayout( ( (IStructuredSelection) insertObj ).toArray( ), targetPart ); } else if ( insertObj instanceof DataSetHandle ) { return isHandleValid( (DataSetHandle) insertObj ) && handleValidateDataSet( targetPart ); } else if ( insertObj instanceof ResultSetColumnHandle ) { return handleValidateDataSetColumn( (ResultSetColumnHandle) insertObj, targetPart ); } // else if ( insertObj instanceof DimensionHandle ) // { // return handleValidateDimension( (DimensionHandle) insertObj, // targetPart ); // } // else if ( insertObj instanceof MeasureHandle ) // { // return handleValidateMeasure( (MeasureHandle) insertObj, // targetPart ); // } else if ( insertObj instanceof LabelHandle ) { return handleValidateLabel( (LabelHandle) insertObj, targetPart ); } else if ( insertObj instanceof ResultSetColumnHandle ) { return handleValidateDataSetColumn( (ResultSetColumnHandle) insertObj, targetPart ); } else if ( insertObj instanceof ScalarParameterHandle ) { return isHandleValid( (ScalarParameterHandle) insertObj ) && handleValidateParameter( targetPart ); } return false; } private static boolean handleValidateLabel( LabelHandle handle, EditPart targetPart ) { if ( targetPart.getModel( ) instanceof IAdaptable ) { Object obj = ( (IAdaptable) targetPart.getModel( ) ).getAdapter( DesignElementHandle.class ); if ( obj instanceof ExtendedItemHandle ) { return ( (ExtendedItemHandle) obj ).canContain( DEUtil.getDefaultContentName( obj ), handle ); } } return false; } private static boolean checkContainContainMulitItem( Object[] objects, Object slotHandle ) { SlotHandle handle = null; // if ( slotHandle instanceof ReportElementModel ) // { // handle = ( (ReportElementModel) slotHandle ).getSlotHandle( ); // } // else if ( slotHandle instanceof SlotHandle ) { handle = (SlotHandle) slotHandle; } if ( handle != null && objects != null && objects.length > 1 ) { if ( !handle.getDefn( ).isMultipleCardinality( ) ) { return false; } } return true; } /** * Checks if all the DataSetColumn has the same DataSet. * * @param array * all elements * @return false if not same; true if every column has the same DataSet or * the element is not an instance of DataSetColumn */ protected static boolean checkSameDataSetInMultiColumns( Object[] array ) { if ( array == null ) return false; Object dataSet = null; for ( int i = 0; i < array.length; i++ ) { if ( array[i] instanceof ResultSetColumnHandle ) { Object currDataSet = ( (ResultSetColumnHandle) array[i] ).getElementHandle( ); if ( currDataSet == null ) { return false; } if ( dataSet == null ) { dataSet = currDataSet; } else { if ( dataSet != currDataSet ) { return false; } } } } return true; } /** * Validates container of drop target from data set in data view * * @param dropPart * @return validate result */ protected static boolean handleValidateDataSetDropContainer( EditPart dropPart ) { if ( dropPart.getParent( ) == null ) { return false; } Object container = dropPart.getParent( ).getModel( ); return ( container instanceof GridHandle || container instanceof TableHandle || container instanceof FreeFormHandle || container instanceof ListHandle || dropPart.getModel( ) instanceof ModuleHandle ); } /** * Validates container of drop target from data set column in data view * * @param dropPart * @return validate result */ protected static boolean handleValidateDataSetColumnDropContainer( EditPart dropPart ) { if ( dropPart.getParent( ) == null ) { return false; } Object container = dropPart.getParent( ).getModel( ); return ( container instanceof GridHandle || container instanceof TableHandle || container instanceof FreeFormHandle || container instanceof ListHandle || container instanceof MasterPageHandle || dropPart.getModel( ) instanceof ModuleHandle ); } protected static boolean handleValidateMeasureDropContainer( MeasureHandle measure, EditPart dropPart ) { if ( dropPart.getModel( ) instanceof IVirtualValidator ) { return ( (IVirtualValidator) dropPart.getModel( ) ).handleValidate( measure ); } return false; } protected static boolean handleValidateDimensionDropContainer( DimensionHandle dimension, EditPart dropPart ) { if ( dropPart.getModel( ) instanceof IVirtualValidator ) { return ( (IVirtualValidator) dropPart.getModel( ) ).handleValidate( dimension ); } return false; } /** * Validates container of drop target from scalar parameter in data view * * @param dropPart * @return validate result */ protected static boolean handleValidateParameterDropContainer( EditPart dropPart ) { if ( dropPart.getParent( ) == null ) { return false; } Object container = dropPart.getParent( ).getModel( ); return ( container instanceof GridHandle || container instanceof TableHandle || container instanceof FreeFormHandle || container instanceof ListHandle || dropPart.getModel( ) instanceof ModuleHandle ); } /** * Validates drop target from data set in data view. * * @return validate result */ protected static boolean handleValidateDataSet( EditPart target ) { return handleValidateDataSetDropContainer( target ) && DNDUtil.handleValidateTargetCanContainType( target.getModel( ), ReportDesignConstants.TABLE_ITEM ); } protected static boolean handleValidateDimension( DimensionHandle insertObj, EditPart target ) { return handleValidateDimensionDropContainer( insertObj, target ); } protected static boolean handleValidateMeasure( MeasureHandle insertObj, EditPart target ) { return handleValidateMeasureDropContainer( insertObj, target ); } /** * Validates drop target from data set column in data view. * * @return validate result */ protected static boolean handleValidateDataSetColumn( ResultSetColumnHandle insertObj, EditPart target ) { if ( handleValidateDataSetColumnDropContainer( target ) && DNDUtil.handleValidateTargetCanContainType( target.getModel( ), ReportDesignConstants.DATA_ITEM ) ) { // Validates target is report root if ( target.getModel( ) instanceof ModuleHandle || isMasterPageHeaderOrFooter( target.getModel( ) ) ) { return true; } // Validates target's dataset is null or the same with the inserted DesignElementHandle handle = (DesignElementHandle) target.getParent( ) .getModel( ); if (handle instanceof TableHandle && target.getModel( ) instanceof CellHandle) { TableHandle tableHandle = (TableHandle)handle; CellHandle cellHandle = (CellHandle)target.getModel( ); if (DesignChoiceConstants.ANALYSIS_TYPE_DIMENSION.equals( UIUtil.getColumnAnalysis( insertObj ) )) { SlotHandle slotHandle = tableHandle.getGroups( ); for ( Object o : slotHandle.getContents( ) ) { GroupHandle group = (GroupHandle) o; if ( group.getName( ).equals( insertObj.getColumnName( ) ) ) return false; } } else if (DesignChoiceConstants.ANALYSIS_TYPE_ATTRIBUTE.equals(UIUtil.getColumnAnalysis( insertObj ) )) { String str = UIUtil.getAnalysisColumn( insertObj ); DataSetHandle dataset = (DataSetHandle) insertObj.getElementHandle( ); String type = ""; if (str != null) { for ( Iterator iter = dataset.getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP ) .iterator( ); iter.hasNext( ); ) { ColumnHintHandle element = (ColumnHintHandle) iter.next( ); if ( element.getColumnName( ).equals( str ) ||str.equals( element.getAlias( ) ) ) { type = element.getAnalysis( ); break; } } if (DesignChoiceConstants.ANALYSIS_TYPE_DIMENSION.equals( type )) { GroupHandle findGroup = null; SlotHandle slotHandle = tableHandle.getGroups( ); for ( Object o : slotHandle.getContents( ) ) { GroupHandle group = (GroupHandle) o; if ( group.getName( ).equals(str) ) { findGroup = group; } } if (findGroup == null) { // DesignElementHandle container = cellHandle.getContainer( ).getContainer( ); // if (container instanceof TableHandle) // { // return true; // } // if (container instanceof GroupHandle && str.equals( ((GroupHandle)container).getName( ))) // { // return true; // } // return false; return true; } else { if (cellHandle.getContainer( ).getContainer( ) == findGroup) { return true; } else { return false; } } } else if (!type.equals( "" )) //$NON-NLS-1$ { SlotHandle slotHandle = cellHandle.getContainer( ).getContainerSlotHandle( ); if (slotHandle.equals( tableHandle.getHeader( )) || slotHandle.equals( tableHandle.getFooter( ) ) ) { return true; } else { return false; } } } else { SlotHandle slotHandle = cellHandle.getContainer( ).getContainerSlotHandle( ); if (slotHandle == tableHandle.getHeader( ) || slotHandle == tableHandle.getFooter( )) { return true; } return false; } } } if ( handle instanceof ReportItemHandle ) { ReportItemHandle bindingHolder = DEUtil.getListingContainer( handle ); DataSetHandle itsDataSet = ( (ReportItemHandle) handle ).getDataSet( ); DataSetHandle dataSet = null; ReportItemHandle bindingRoot = DEUtil.getBindingRoot( handle ); if ( bindingRoot != null ) { dataSet = bindingRoot.getDataSet( ); } return itsDataSet == null && ( bindingHolder == null || !bindingHolder.getColumnBindings( ) .iterator( ) .hasNext( ) ) || insertObj.getElementHandle( ).equals( dataSet ); } } return false; } private static boolean isMasterPageHeaderOrFooter( Object obj ) { if ( !( obj instanceof SlotHandle ) ) { return false; } if ( ( (SlotHandle) obj ).getElementHandle( ) instanceof MasterPageHandle ) { return true; } return false; } /** * Validates drop target from scalar parameter in data view. * * @return validate result */ protected static boolean handleValidateParameter( EditPart target ) { return handleValidateParameterDropContainer( target ) && DNDUtil.handleValidateTargetCanContainType( target.getModel( ), ReportDesignConstants.DATA_ITEM ); } /** * Validates drag source from data view to layout. Support the multiple. * * @return validate result */ public static boolean handleValidateInsert( Object insertObj ) { if ( insertObj instanceof Object[] ) { Object[] array = (Object[]) insertObj; if ( array.length == 0 ) { return false; } for ( int i = 0; i < array.length; i++ ) { if ( !handleValidateInsert( array[i] ) ) return false; } return true; } else if ( insertObj instanceof IStructuredSelection ) { return handleValidateInsert( ( (IStructuredSelection) insertObj ).toArray( ) ); } // else if ( insertObj instanceof ParameterHandle ) // { // if ( ( (ParameterHandle) insertObj ).getRoot( ) instanceof // LibraryHandle ) // return false; // } if ( insertObj instanceof DataSetHandle ) { return DataSetUIUtil.hasMetaData( (DataSetHandle) insertObj ); } return insertObj instanceof ResultSetColumnHandle || insertObj instanceof ScalarParameterHandle || insertObj instanceof DimensionHandle || insertObj instanceof MeasureHandle; } protected static void insertToCell( DataSetHandle model, TableHandle tableHandle, SlotHandle slot, ResultSetColumnHandle[] columns, boolean isLabel ) { for ( int i = 0; i < slot.getCount( ); i++ ) { SlotHandle cells = ( (RowHandle) slot.get( i ) ).getCells( ); for ( int j = 0; j < cells.getCount( ); j++ ) { CellHandle cell = (CellHandle) cells.get( j ); try { if ( isLabel ) { LabelHandle labelItemHandle = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) .getElementFactory( ) .newLabel( null ); // LabelHandle labelItemHandle = // DesignElementFactory.getInstance( ) // .newLabel( null ); String labelText = UIUtil.getColumnDisplayName( columns[j] ); if ( labelText != null ) { labelItemHandle.setText( labelText ); } String displayKey = UIUtil.getColumnDisplayNameKey( columns[j] ); if ( displayKey != null ) { labelItemHandle.setTextKey( displayKey ); } cell.addElement( labelItemHandle, cells.getSlotID( ) ); } else { DataItemHandle dataHandle = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) .getElementFactory( ) .newDataItem( null ); // DataItemHandle dataHandle = // DesignElementFactory.getInstance( ) // .newDataItem( null ); dataHandle.setResultSetColumn( columns[j].getColumnName( ) ); formatDataHandle( dataHandle, columns[j] ); cell.addElement( dataHandle, cells.getSlotID( ) ); // add data binding to table. ComputedColumn bindingColumn = StructureFactory.newComputedColumn( tableHandle, columns[j].getColumnName( ) ); bindingColumn.setDataType( columns[j].getDataType( ) ); ExpressionUtility.setBindingColumnExpression( columns[j], bindingColumn ); bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( columns[j] ) ); String displayKey = UIUtil.getColumnDisplayNameKey( columns[j] ); if ( displayKey != null ) bindingColumn.setDisplayNameID( displayKey ); tableHandle.addColumnBinding( bindingColumn, false ); ActionHandle actionHandle = UIUtil.getColumnAction( columns[j] ); if ( actionHandle != null ) { List source = new ArrayList( ); source.add( actionHandle.getStructure( ) ); List newAction = ModelUtil.cloneStructList( source ); dataHandle.setAction( (Action) newAction.get( 0 ) ); } } } catch ( Exception e ) { ExceptionHandler.handle( e ); } } } } private static void formatDataHandle(DataItemHandle dataHandle, ResultSetColumnHandle column) { try { StyleHandle styleHandle = dataHandle.getPrivateStyle( ); boolean wordWrap = UIUtil.isWordWrap( column ); if (wordWrap) { styleHandle.setWhiteSpace( DesignChoiceConstants.WHITE_SPACE_NORMAL ); } else { styleHandle.setWhiteSpace( DesignChoiceConstants.WHITE_SPACE_NOWRAP ); } String aliment = UIUtil.getClolumnHandleAlignment( column ); if (aliment != null) { styleHandle.setTextAlign( aliment ); } String helpText = UIUtil.getClolumnHandleHelpText( column ); if (helpText != null) { dataHandle.setHelpText( helpText ); } ColumnHintHandle hintHandle = findColumnHintHandle( column ); if (hintHandle != null) { formatDataHandleDataType( column.getDataType( ), hintHandle.getValueFormat( ), styleHandle ); } } catch(SemanticException e) { //do nothing now } } private static ColumnHintHandle findColumnHintHandle(ResultSetColumnHandle column) { DataSetHandle dataset = (DataSetHandle) column.getElementHandle( ); for ( Iterator iter = dataset.getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP ) .iterator( ); iter.hasNext( ); ) { ColumnHintHandle element = (ColumnHintHandle) iter.next( ); if ( element.getColumnName( ).equals( column.getColumnName( ) ) || column.getColumnName( ).equals( element.getAlias( ) ) ) { return element; } } return null; } public static void formatDataHandleDataType(String type, FormatValue formartValue,StyleHandle styleHandle) { if (formartValue == null) { return; } try { if (DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER.equals( type ) || DesignChoiceConstants.COLUMN_DATA_TYPE_DECIMAL.equals( type ) || DesignChoiceConstants.COLUMN_DATA_TYPE_FLOAT.equals( type )) { if (formartValue.getPattern( ) != null) { styleHandle.setNumberFormat( formartValue.getPattern( ) ); } if (formartValue.getCategory( ) != null) { styleHandle.setNumberFormatCategory( formartValue.getCategory( ) ); } } else if (DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME.equals( type ) || DesignChoiceConstants.COLUMN_DATA_TYPE_DATE.equals( type )) { if (formartValue.getPattern( ) != null) { styleHandle.setDateTimeFormat( formartValue.getPattern( ) ); } if (formartValue.getCategory( ) != null) { styleHandle.setDateTimeFormatCategory( formartValue.getCategory( ) ); } } else if (DesignChoiceConstants.COLUMN_DATA_TYPE_STRING.equals( type )) { if (formartValue.getPattern( ) != null) { styleHandle.setStringFormat( formartValue.getPattern( ) ); } if (formartValue.getCategory( ) != null) { styleHandle.setStringFormatCategory( formartValue.getCategory( ) ); } } } catch ( SemanticException e ) { //do nothing now } } /** * Sets initial width to new object * * @param object * new object */ public static void setInitWidth( Object object ) { // int percentAll = 100; // try // { // if ( object instanceof TableHandle ) // { // TableHandle table = (TableHandle) object; // table.setWidth( percentAll // + DesignChoiceConstants.UNITS_PERCENTAGE ); // } // else if ( object instanceof GridHandle ) // { // GridHandle grid = (GridHandle) object; // grid.setWidth( percentAll // + DesignChoiceConstants.UNITS_PERCENTAGE ); // } // else // return; // } // catch ( SemanticException e ) // { // ExceptionHandler.handle( e ); // } } protected static boolean isHandleValid( DesignElementHandle handle ) { if ( handle instanceof DataSetHandle ) { if ( ( !( handle instanceof JointDataSetHandle || handle instanceof DerivedDataSetHandle ) && ( (DataSetHandle) handle ).getDataSource( ) == null ) || !DataSetUIUtil.hasMetaData( (DataSetHandle) handle ) ) { return false; } } return handle.isValid( ) && handle.getSemanticErrors( ).isEmpty( ); } /** * Converts edit part selection into model selection. * * @param selection * edit part * @return model, return Collections.EMPTY_LIST if selection is null or * empty. */ public static IStructuredSelection editPart2Model( ISelection selection ) { if ( selection == null || !( selection instanceof IStructuredSelection ) ) return new StructuredSelection( Collections.EMPTY_LIST ); List list = ( (IStructuredSelection) selection ).toList( ); List resultList = new ArrayList( ); for ( int i = 0; i < list.size( ); i++ ) { Object obj = list.get( i ); if ( obj instanceof ReportElementEditPart ) { Object model = ( (ReportElementEditPart) obj ).getModel( ); if ( model instanceof ListBandProxy ) { model = ( (ListBandProxy) model ).getSlotHandle( ); } resultList.add( model ); } } return new StructuredSelection( resultList ); } /** * Converts edit part selection into model selection. * * @param selection * edit part * @return model, return Collections.EMPTY_LIST if selection is null or * empty. */ public static IStructuredSelection editPart2Model( List selection ) { if ( selection == null || ( selection.size( ) == 0 ) ) return new StructuredSelection( Collections.EMPTY_LIST ); List list = selection; List resultList = new ArrayList( ); for ( int i = 0; i < list.size( ); i++ ) { Object obj = list.get( i ); if ( obj instanceof ReportElementEditPart ) { Object model = ( (ReportElementEditPart) obj ).getModel( ); if ( model instanceof ListBandProxy ) { model = ( (ListBandProxy) model ).getSlotHandle( ); } resultList.add( model ); } } return new StructuredSelection( resultList ); } }
UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/dnd/InsertInLayoutUtil.java
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.internal.ui.dnd; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import org.eclipse.birt.core.data.ExpressionUtil; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.core.model.schematic.HandleAdapterFactory; import org.eclipse.birt.report.designer.core.model.schematic.ListBandProxy; import org.eclipse.birt.report.designer.core.model.schematic.TableHandleAdapter; import org.eclipse.birt.report.designer.data.ui.dataset.DataSetUIUtil; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.actions.AddGroupAction; import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.ReportElementEditPart; import org.eclipse.birt.report.designer.internal.ui.util.DataUtil; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.util.ExpressionUtility; import org.eclipse.birt.report.designer.internal.ui.util.UIUtil; import org.eclipse.birt.report.designer.ui.newelement.DesignElementFactory; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.designer.util.DNDUtil; import org.eclipse.birt.report.designer.util.IVirtualValidator; import org.eclipse.birt.report.model.api.ActionHandle; import org.eclipse.birt.report.model.api.CachedMetaDataHandle; import org.eclipse.birt.report.model.api.CellHandle; import org.eclipse.birt.report.model.api.ColumnHintHandle; import org.eclipse.birt.report.model.api.ComputedColumnHandle; import org.eclipse.birt.report.model.api.DataItemHandle; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DerivedDataSetHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.Expression; import org.eclipse.birt.report.model.api.ExpressionType; import org.eclipse.birt.report.model.api.ExtendedItemHandle; import org.eclipse.birt.report.model.api.FreeFormHandle; import org.eclipse.birt.report.model.api.GridHandle; import org.eclipse.birt.report.model.api.GroupHandle; import org.eclipse.birt.report.model.api.JointDataSetHandle; import org.eclipse.birt.report.model.api.LabelHandle; import org.eclipse.birt.report.model.api.ListHandle; import org.eclipse.birt.report.model.api.ListingHandle; import org.eclipse.birt.report.model.api.MasterPageHandle; import org.eclipse.birt.report.model.api.ModuleHandle; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.ResultSetColumnHandle; import org.eclipse.birt.report.model.api.RowHandle; import org.eclipse.birt.report.model.api.ScalarParameterHandle; import org.eclipse.birt.report.model.api.SlotHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.StyleHandle; import org.eclipse.birt.report.model.api.TableGroupHandle; import org.eclipse.birt.report.model.api.TableHandle; import org.eclipse.birt.report.model.api.VariableElementHandle; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; import org.eclipse.birt.report.model.api.elements.ReportDesignConstants; import org.eclipse.birt.report.model.api.elements.structures.Action; import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn; import org.eclipse.birt.report.model.api.elements.structures.FormatValue; import org.eclipse.birt.report.model.api.elements.structures.TOC; import org.eclipse.birt.report.model.api.olap.DimensionHandle; import org.eclipse.birt.report.model.api.olap.MeasureHandle; import org.eclipse.birt.report.model.elements.interfaces.IGroupElementModel; import org.eclipse.birt.report.model.util.ModelUtil; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.gef.EditPart; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; /** * Utility for creation from data view to layout */ public class InsertInLayoutUtil { /** * Rule interface for defining insertion rule */ abstract static interface InsertInLayoutRule { public boolean canInsert( ); public Object getInsertPosition( ); public void insert( Object object ) throws SemanticException; } /** * * Rule for inserting label after inserting data set column */ static class LabelAddRule implements InsertInLayoutRule { private Object container; private CellHandle newTarget; public LabelAddRule( Object container ) { this.container = container; } /* * (non-Javadoc) * * @seeorg.eclipse.birt.report.designer.internal.ui.views.actions. * InsertInLayoutAction.InsertInLayoutRule#canInsert() */ public boolean canInsert( ) { if ( container instanceof SlotHandle ) { container = ( (SlotHandle) container ).getElementHandle( ); } if ( !( container instanceof CellHandle ) ) return false; CellHandle cell = (CellHandle) container; // Validates source position of data item boolean canInsert = false; if ( cell.getContainer( ).getContainer( ) instanceof TableGroupHandle ) { canInsert = true; } else { if ( cell.getContainer( ).getContainerSlotHandle( ).getSlotID( ) == TableHandle.DETAIL_SLOT ) { canInsert = true; } } // Validates column count and gets the target if ( canInsert ) { TableHandle table = null; if ( cell.getContainer( ).getContainer( ) instanceof TableHandle ) { table = (TableHandle) cell.getContainer( ).getContainer( ); } else { table = (TableHandle) cell.getContainer( ) .getContainer( ) .getContainer( ); } SlotHandle header = table.getHeader( ); if ( header != null && header.getCount( ) > 0 ) { int columnNum = HandleAdapterFactory.getInstance( ) .getCellHandleAdapter( cell ) .getColumnNumber( ); newTarget = (CellHandle) HandleAdapterFactory.getInstance( ) .getTableHandleAdapter( table ) .getCell( 1, columnNum, false ); return newTarget != null && newTarget.getContent( ).getCount( ) == 0; } } return false; } /** * Returns new Label insert position in form of <code>CellHandle</code> */ public Object getInsertPosition( ) { return newTarget; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil * .InsertInLayoutRule#insert() */ public void insert( Object object ) throws SemanticException { Assert.isTrue( object instanceof DesignElementHandle ); newTarget.addElement( (DesignElementHandle) object, CellHandle.CONTENT_SLOT ); } } /** * * Rule for inserting multiple data into table, and populating adjacent * cells */ static class MultiItemsExpandRule implements InsertInLayoutRule { private Object[] items; private Object target; private int focusIndex = 0; public MultiItemsExpandRule( Object[] items, Object target ) { this.items = items; this.target = target; } /* * (non-Javadoc) * * @seeorg.eclipse.birt.report.designer.internal.ui.views.actions. * InsertInLayoutAction.InsertInLayoutRule#canInsert() */ public boolean canInsert( ) { return items != null && items.length > 1 && target != null && ( target instanceof DesignElementHandle || target instanceof ListBandProxy ); } /** * * Returns multiple insert positions in form of array */ public Object getInsertPosition( ) { Object[] positions = new Object[items.length]; if ( target instanceof CellHandle ) { CellHandle firstCell = (CellHandle) target; TableHandleAdapter tableAdapter = HandleAdapterFactory.getInstance( ) .getTableHandleAdapter( getTableHandle( firstCell ) ); int currentColumn = HandleAdapterFactory.getInstance( ) .getCellHandleAdapter( firstCell ) .getColumnNumber( ); int currentRow = HandleAdapterFactory.getInstance( ) .getCellHandleAdapter( firstCell ) .getRowNumber( ); int columnDiff = currentColumn + items.length - tableAdapter.getColumnCount( ) - 1; // Insert columns if table can not contain all items if ( columnDiff > 0 ) { int insertColumn = tableAdapter.getColumnCount( ); try { tableAdapter.insertColumns( columnDiff, insertColumn ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); return null; } } for ( int i = 0; i < positions.length; i++ ) { positions[i] = tableAdapter.getCell( currentRow, currentColumn++ ); } focusIndex = 0; } else { for ( int i = 0; i < positions.length; i++ ) { positions[i] = target; } focusIndex = items.length - 1; } return positions; } protected ReportItemHandle getTableHandle( CellHandle firstCell ) { DesignElementHandle tableContainer = firstCell.getContainer( ) .getContainer( ); if ( tableContainer instanceof ReportItemHandle ) { return (ReportItemHandle) tableContainer; } return (ReportItemHandle) tableContainer.getContainer( ); } /** * Returns the index of the focus element in the items */ public int getFocusIndex( ) { return focusIndex; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil * .InsertInLayoutRule#insert() */ public void insert( Object object ) throws SemanticException { // TODO Auto-generated method stub } } /** * * Rule for setting key when inserting data set column to group handle */ static class GroupKeySetRule implements InsertInLayoutRule { private Object container; private ResultSetColumnHandle dataSetColumn; public GroupKeySetRule( Object container, ResultSetColumnHandle dataSetColumn ) { this.container = container; this.dataSetColumn = dataSetColumn; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil * .InsertInLayoutRule#canInsert() */ public boolean canInsert( ) { return getGroupContainer( container ) != null && getGroupHandle( container ).getKeyExpr( ) == null && ( getGroupContainer( container ).getDataSet( ) == getDataSetHandle( dataSetColumn ) || getGroupContainer( container ).getDataSet( ) == null ); } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil * .InsertInLayoutRule#getInsertPosition() */ public Object getInsertPosition( ) { return null; } /* * (non-Javadoc) * * @see * org.eclipse.birt.report.designer.internal.ui.dnd.InsertInLayoutUtil * .InsertInLayoutRule#insert(java.lang.Object) */ public void insert( Object object ) throws SemanticException { Assert.isTrue( object instanceof ResultSetColumnHandle ); Assert.isTrue( object == dataSetColumn || object == null ); ReportItemHandle groupContainer = getGroupContainer( container ); DataSetHandle dataSetHandle = null; dataSetHandle = groupContainer.getDataSet( ); if ( dataSetHandle == null ) { for ( DesignElementHandle elementHandle = groupContainer; elementHandle != null; elementHandle = elementHandle.getContainer( ) ) { if ( elementHandle instanceof ListingHandle && ( dataSetHandle = ( (ListingHandle) elementHandle ).getDataSet( ) ) != null && ( dataSetHandle == getDataSetHandle( dataSetColumn ) ) ) { break; } } } if ( dataSetHandle == null || dataSetHandle != getDataSetHandle( dataSetColumn ) ) { getGroupContainer( container ).setDataSet( getDataSetHandle( dataSetColumn ) ); } getGroupHandle( container ).setKeyExpr( DEUtil.getColumnExpression( dataSetColumn.getColumnName( ) ) ); } protected DataSetHandle getDataSetHandle( ResultSetColumnHandle model ) { return (DataSetHandle) model.getElementHandle( ); } protected GroupHandle getGroupHandle( Object target ) { DesignElementHandle handle = null; if ( target instanceof CellHandle ) { handle = ( (CellHandle) target ).getContainer( ).getContainer( ); } else if ( target instanceof ListBandProxy ) { handle = ( (ListBandProxy) target ).getElemtHandle( ); } if ( handle instanceof GroupHandle ) { return (GroupHandle) handle; } return null; } protected ReportItemHandle getGroupContainer( Object target ) { GroupHandle group = getGroupHandle( target ); if ( group != null && group.getContainer( ) instanceof ReportItemHandle ) return (ReportItemHandle) group.getContainer( ); return null; } } /** * Creates a object to insert. * * @param insertObj * object insert to layout * @param target * insert target, like cell or ListBandProxy * @param targetParent * insert target's non-dummy container, like table or list * @return new object in layout * @throws SemanticException */ public static DesignElementHandle performInsert( Object insertObj, Object target, Object targetParent ) throws SemanticException { Assert.isNotNull( insertObj ); Assert.isNotNull( target ); if ( insertObj instanceof DataSetHandle ) { return performInsertDataSet( (DataSetHandle) insertObj ); } else if ( insertObj instanceof ResultSetColumnHandle ) { return performInsertDataSetColumn( (ResultSetColumnHandle) insertObj, target, targetParent ); } else if ( insertObj instanceof ScalarParameterHandle ) { return performInsertParameter( (ScalarParameterHandle) insertObj ); } else if ( insertObj instanceof VariableElementHandle ) { return performInsertVariable( (VariableElementHandle) insertObj ); } else if ( insertObj instanceof String ) { // Such as invalid group key return performInsertString( (String) insertObj, target ); } else if ( insertObj instanceof Object[] ) { return performMultiInsert( (Object[]) insertObj, target, targetParent ); } else if ( insertObj instanceof IStructuredSelection ) { return performMultiInsert( ( (IStructuredSelection) insertObj ).toArray( ), target, targetParent ); } return null; } /** * Creates a object, "Add" operation to layout needs to handle later. * <p> * Must make sure operation legal before execution. * </p> * * @param insertObj * object insert to layout * @param editPart * target EditPart * @return new object in layout * @throws SemanticException */ public static DesignElementHandle performInsert( Object insertObj, EditPart editPart ) throws SemanticException { Assert.isNotNull( insertObj ); Assert.isNotNull( editPart ); return performInsert( insertObj, editPart.getModel( ), editPart.getParent( ).getModel( ) ); } /** * Creates multiple objects * * @param array * multiple creation source * @param target * @param targetParent * @return first creation in layout * @throws SemanticException */ protected static DesignElementHandle performMultiInsert( Object[] array, Object target, Object targetParent ) throws SemanticException { DesignElementHandle result = null; MultiItemsExpandRule rule = new MultiItemsExpandRule( array, target ); if ( rule.canInsert( ) ) { Object[] positions = (Object[]) rule.getInsertPosition( ); if ( positions != null ) { for ( int i = 0; i < array.length; i++ ) { DesignElementHandle newObj = performInsert( array[i], positions[i], targetParent ); if ( i == rule.getFocusIndex( ) ) { result = newObj; } else { DNDUtil.addElementHandle( positions[i], newObj ); } } } } else if ( array.length != 0 ) { result = performInsert( array[0], target, targetParent ); } return result; } public static DataItemHandle performInsertParameter( ScalarParameterHandle model ) throws SemanticException { // DataItemHandle dataHandle = SessionHandleAdapter.getInstance( ) // .getReportDesignHandle( ) // .getElementFactory( ) // .newDataItem( null ); DataItemHandle dataHandle = DesignElementFactory.getInstance( ) .newDataItem( null ); ComputedColumn bindingColumn = StructureFactory.newComputedColumn( dataHandle, model.getName( ) ); ExpressionUtility.setBindingColumnExpression( model, bindingColumn ); // hardcode // parameter's type datatime is not equals data's. String paramType = model.getDataType( ); if ( DesignChoiceConstants.PARAM_TYPE_DATETIME.equals( paramType ) ) paramType = DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME; bindingColumn.setDataType( paramType ); dataHandle.addColumnBinding( bindingColumn, false ); dataHandle.setResultSetColumn( bindingColumn.getName( ) ); return dataHandle; } public static DataItemHandle performInsertVariable( VariableElementHandle model ) throws SemanticException { DataItemHandle dataHandle = DesignElementFactory.getInstance( ) .newDataItem( null ); ComputedColumn bindingColumn = StructureFactory.newComputedColumn( dataHandle, model.getName( ) ); bindingColumn.setExpression( DEUtil.getExpression( model ) ); // FIXME, currently varialbe does not support type String paramType = DesignChoiceConstants.COLUMN_DATA_TYPE_STRING; bindingColumn.setDataType( paramType ); dataHandle.addColumnBinding( bindingColumn, false ); dataHandle.setResultSetColumn( bindingColumn.getName( ) ); return dataHandle; } private static GroupHandle addGroupHandle(TableHandle tableHandle, String columnName, DataItemHandle dataHandle)throws SemanticException { DesignElementFactory factory = DesignElementFactory.getInstance( tableHandle.getModuleHandle( ) ); GroupHandle groupHandle = factory.newTableGroup( ); int columnCount = tableHandle.getColumnCount( ); groupHandle.getHeader( ) .add( factory.newTableRow( columnCount ) ); groupHandle.getFooter( ) .add( factory.newTableRow( columnCount ) ); groupHandle.setName( columnName ); Expression newKeyExpr = new Expression( ExpressionUtility.getColumnExpression(columnName, ExpressionUtility.getExpressionConverter( ExpressionType.JAVASCRIPT ) ), ExpressionType.JAVASCRIPT ); groupHandle.setExpressionProperty( IGroupElementModel.KEY_EXPR_PROP, newKeyExpr ); TOC toc = StructureFactory.createTOC( ); toc.setExpression( ExpressionUtility.getColumnExpression( columnName, ExpressionUtility.getExpressionConverter( ExpressionType.JAVASCRIPT ) ) ); groupHandle.addTOC( toc ); //slotHandle.add( groupHandle, slotHandle.getCount( ) ); RowHandle rowHandle = ( (RowHandle) groupHandle.getHeader( ) .get( 0 ) ); CellHandle cellHandle = (CellHandle) rowHandle.getCells( ) .get( 0 ); cellHandle.getContent( ).add( dataHandle ); return groupHandle; } /** * Inserts dataset column into the target. Add label or group key if * possible * * @param model * column item * @param target * insert target like cell or ListBandProxy * @param targetParent * target container like table or list * @return to be inserted data item * @throws SemanticException */ protected static DesignElementHandle performInsertDataSetColumn( ResultSetColumnHandle model, Object target, Object targetParent ) throws SemanticException { /* * search the target container, if container has the same dataset, add * the column binding if it does not exist in the container. If the * container's dataset is not the dragged dataset column's dataset, * column binding will be added to the new dataitem, and set dataitem's * dataset with the dragged dataset column's dataset. */ DataItemHandle dataHandle = DesignElementFactory.getInstance( ) .newDataItem( null ); DataSetHandle dataSet = (DataSetHandle) model.getElementHandle( ); if ( targetParent instanceof TableHandle ) { TableHandle tableHandle = (TableHandle) targetParent; if ( tableHandle.isSummaryTable( ) ) { tableHandle.setDataSet( dataSet ); if ( DesignChoiceConstants.ANALYSIS_TYPE_DIMENSION.equals( UIUtil.getColumnAnalysis( model ) ) ) { ComputedColumn bindingColumn = StructureFactory.newComputedColumn( tableHandle, model.getColumnName( ) ); bindingColumn.setDataType( model.getDataType( ) ); ExpressionUtility.setBindingColumnExpression( model, bindingColumn ); bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model ) ); String displayKey = UIUtil.getColumnDisplayNameKey( model ); if ( displayKey != null ) bindingColumn.setDisplayNameID( displayKey ); tableHandle.addColumnBinding( bindingColumn, false ); dataHandle.setResultSetColumn( model.getColumnName( ) ); SlotHandle slotHandle = tableHandle.getGroups( ); for ( Object o : slotHandle.getContents( ) ) { GroupHandle group = (GroupHandle) o; if ( group.getName( ).equals( model.getColumnName( ) ) ) return null; } return addGroupHandle( tableHandle, model.getColumnName( ), dataHandle ); } else if (DesignChoiceConstants.ANALYSIS_TYPE_ATTRIBUTE.equals( UIUtil.getColumnAnalysis( model ) )) { DataSetHandle dataset = (DataSetHandle) model.getElementHandle( ); String str = UIUtil.getAnalysisColumn( model ); String type = ""; //$NON-NLS-1$ ResultSetColumnHandle newResultColumn = null; if (str != null) { List columnList = DataUtil.getColumnList( dataset ); for ( int i = 0; i < columnList.size( ); i++ ) { ResultSetColumnHandle resultSetColumn = (ResultSetColumnHandle) columnList.get( i ); if (str.equals( resultSetColumn.getColumnName( ) )) { newResultColumn = resultSetColumn; break; } } for ( Iterator iter = dataset.getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP ) .iterator( ); iter.hasNext( ); ) { ColumnHintHandle element = (ColumnHintHandle) iter.next( ); if ( element.getColumnName( ).equals( str ) ||str.equals( element.getAlias( ) ) ) { type = element.getAnalysis( ); break; } } if (DesignChoiceConstants.ANALYSIS_TYPE_DIMENSION.equals( type )) { boolean hasGroup = false; SlotHandle slotHandle = tableHandle.getGroups( ); for ( Object o : slotHandle.getContents( ) ) { GroupHandle group = (GroupHandle) o; if ( group.getName( ).equals( str ) ) hasGroup = true; } if (!hasGroup) { ComputedColumn bindingColumn = StructureFactory.newComputedColumn( tableHandle, model.getColumnName( ) ); bindingColumn.setDataType( model.getDataType( )); ExpressionUtility.setBindingColumnExpression( model, bindingColumn ); bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model ) ); String displayKey = UIUtil.getColumnDisplayNameKey( model ); if ( displayKey != null ) bindingColumn.setDisplayNameID( displayKey ); tableHandle.addColumnBinding( bindingColumn, false ); dataHandle.setResultSetColumn( model.getColumnName( ) ); return addGroupHandle( tableHandle, newResultColumn.getColumnName( ), dataHandle ); } } } if ( target instanceof CellHandle) { ComputedColumn column = StructureFactory.newComputedColumn( tableHandle, model.getColumnName( ) ); ComputedColumnHandle binding = DEUtil.addColumn( tableHandle, column, true ); //binding.setAggregateFunction( DesignChoiceConstants.MEASURE_FUNCTION_MAX ); //binding.setExpression( ExpressionUtil.createJSRowExpression( model.getColumnName( ) ) ); ExpressionUtility.setBindingColumnExpression( model, column ); dataHandle.setResultSetColumn( binding.getName( ) ); InsertInLayoutRule rule = new GroupKeySetRule( target, model ); if ( rule.canInsert( ) ) { rule.insert( model ); } return dataHandle; } } else if (DesignChoiceConstants.ANALYSIS_TYPE_MEASURE.equals( UIUtil.getColumnAnalysis( model ))) { CellHandle cellHandle = (CellHandle) target; ComputedColumn column = StructureFactory.newComputedColumn( tableHandle, model.getColumnName( ) ); ComputedColumnHandle binding = DEUtil.addColumn( tableHandle, column, true ); DesignElementHandle group = cellHandle.getContainer( ) .getContainer( ); if (group instanceof GroupHandle) { binding.setAggregateOn( ((GroupHandle)group).getName( ) ); } else { binding.setAggregateOn(null); } if ( DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER.equals( model.getDataType( ) ) || DesignChoiceConstants.COLUMN_DATA_TYPE_FLOAT.equals( model.getDataType( ) ) || DesignChoiceConstants.COLUMN_DATA_TYPE_DECIMAL.equals( model.getDataType( ) ) ) { binding.setAggregateFunction( DesignChoiceConstants.MEASURE_FUNCTION_COUNT ); } else { binding.setAggregateFunction( DesignChoiceConstants.MEASURE_FUNCTION_SUM ); } //binding.setExpression( ExpressionUtil.createJSRowExpression( model.getColumnName( ) ) ); ExpressionUtility.setBindingColumnExpression( model, column ); dataHandle.setResultSetColumn( binding.getName( ) ); InsertInLayoutRule rule = new GroupKeySetRule( target, model ); if ( rule.canInsert( ) ) { rule.insert( model ); } return dataHandle; } // else if ( DesignChoiceConstants.ANALYSIS_TYPE_MEASURE.equals( UIUtil.getColumnAnalysis( model ) ) // || DesignChoiceConstants.ANALYSIS_TYPE_ATTRIBUTE.equals( UIUtil.getColumnAnalysis( model ) ) ) // { // // check target is a group cell // if ( target instanceof CellHandle // && ( (CellHandle) target ).getContainer( ) // .getContainer( ) instanceof GroupHandle ) // { // CellHandle cellHandle = (CellHandle) target; // GroupHandle group = (GroupHandle) cellHandle.getContainer( ) // .getContainer( ); // // ComputedColumn column = StructureFactory.newComputedColumn( tableHandle, // model.getColumnName( ) ); // ComputedColumnHandle binding = DEUtil.addColumn( tableHandle, // column, // true ); // binding.setAggregateOn( group.getName( ) ); // // if ( DesignChoiceConstants.ANALYSIS_TYPE_MEASURE.equals( UIUtil.getColumnAnalysis( model ) ) ) // binding.setAggregateFunction( DesignChoiceConstants.MEASURE_FUNCTION_SUM ); // else // binding.setAggregateFunction( DesignChoiceConstants.MEASURE_FUNCTION_MAX ); // // binding.setExpression( ExpressionUtil.createJSRowExpression( model.getColumnName( ) ) ); // dataHandle.setResultSetColumn( binding.getName( ) ); // // InsertInLayoutRule rule = new LabelAddRule( target ); // if ( rule.canInsert( ) ) // { // // LabelHandle label = // // SessionHandleAdapter.getInstance( ) // // .getReportDesignHandle( ) // // .getElementFactory( ) // // .newLabel( null ); // LabelHandle label = DesignElementFactory.getInstance( ) // .newLabel( null ); // label.setText( UIUtil.getColumnDisplayName( model ) ); // rule.insert( label ); // } // // rule = new GroupKeySetRule( target, model ); // if ( rule.canInsert( ) ) // { // rule.insert( model ); // } // // return dataHandle; // } // } } } dataHandle.setResultSetColumn( model.getColumnName( ) ); formatDataHandle( dataHandle, model ); if ( targetParent instanceof ReportItemHandle ) { ReportItemHandle container = (ReportItemHandle) targetParent; // ComputedColumn bindingColumn = // StructureFactory.newComputedColumn( container, // model.getColumnName( ) ); // bindingColumn.setDataType( model.getDataType( ) ); // ExpressionUtility.setBindingColumnExpression( model, // bindingColumn ); // bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model // ) ); // String displayKey = UIUtil.getColumnDisplayNameKey( model ); // if ( displayKey != null ) // bindingColumn.setDisplayNameID( displayKey ); // if ( target instanceof DesignElementHandle ) // { // if ( ExpressionUtil.hasAggregation( bindingColumn.getExpression( // ) ) ) // { // String groupType = DEUtil.getGroupControlType( // (DesignElementHandle) target ); // if ( groupType.equals( DEUtil.TYPE_GROUP_GROUP ) ) // bindingColumn.setAggregateOn( ( (GroupHandle) DEUtil.getGroups( // (DesignElementHandle) target ) // .get( 0 ) ).getName( ) ); // else if ( groupType.equals( DEUtil.TYPE_GROUP_LISTING ) ) // bindingColumn.setAggregateOn( null ); // } // } ReportItemHandle root = DEUtil.getBindingRoot( container ); if ( root == null ) { container = DEUtil.getListingContainer( container ); // if listing handle is null, then binding to self, else bind to // list handle. if ( container == null ) { ComputedColumn bindingColumn = createBindingColumn( target, dataHandle, model ); dataHandle.setDataSet( dataSet ); dataHandle.addColumnBinding( bindingColumn, false ); } else { ComputedColumn bindingColumn = createBindingColumn( target, container, model ); container.setDataSet( dataSet ); container.addColumnBinding( bindingColumn, false ); } } else if ( root.getDataSet( ) == dataSet ) { container = DEUtil.getBindingHolder( container ); ComputedColumn bindingColumn = createBindingColumn( target, container, model ); container.addColumnBinding( bindingColumn, false ); } else { ReportItemHandle listingHandle = DEUtil.getListingContainer( container ); if ( listingHandle != null && DEUtil.getBindingRoot( listingHandle ) == root && DEUtil.getBindingHolder( listingHandle ) != listingHandle ) { ComputedColumn bindingColumn = createBindingColumn( target, listingHandle, model ); listingHandle.setDataSet( dataSet ); listingHandle.addColumnBinding( bindingColumn, false ); } // do nothing, forbid dragging into the place. } // // DataSetHandle containerDataSet = DEUtil.getBindingRoot( container // ) // .getDataSet( ); // DataSetHandle itsDataSet = null; // if ( container != null ) // { // itsDataSet = container.getDataSet( ); // } // container = DEUtil.getListingContainer( container ); // if ( ( itsDataSet == null && ( !dataSet.equals( containerDataSet // ) ) ) // && container != null ) // { // container.setDataSet( dataSet ); // containerDataSet = dataSet; // } // if ( dataSet.equals( containerDataSet ) && container != null ) // { // if ( container.getDataBindingReference( ) != null ) // container.getDataBindingReference( ) // .addColumnBinding( bindingColumn, false ); // else // container.addColumnBinding( bindingColumn, false ); // } // else // { // // should not happen // dataHandle.setDataSet( dataSet ); // dataHandle.addColumnBinding( bindingColumn, false ); // } // GroupHandle groupHandle = getGroupHandle( target ); // if ( groupHandle != null ) // { // ComputedColumn bindingColumn = // StructureFactory.newComputedColumn( groupHandle, // model.getColumnName( ) ); // // bindingColumn.setColumnName( model.getColumnName( ) ); // bindingColumn.setDataType( model.getDataType( ) ); // bindingColumn.setExpression( DEUtil.getExpression( model ) ); // // groupHandle.addColumnBinding( bindingColumn, false ); // } // else // { // ComputedColumn bindingColumn = // StructureFactory.newComputedColumn( container, // model.getColumnName( ) ); // bindingColumn.setDataType( model.getDataType( ) ); // bindingColumn.setExpression( DEUtil.getExpression( model ) ); // container.addColumnBinding( bindingColumn, false ); // } // ComputedColumn bindingColumn = // StructureFactory.createComputedColumn( ); // bindingColumn.setName( model.getColumnName( ) ); // bindingColumn.setDataType( model.getDataType( ) ); // bindingColumn.setExpression( DEUtil.getExpression( model ) ); // GroupHandle groupHandle = getGroupHandle( target ); // // if ( groupHandle != null ) // { // for ( Iterator iter = groupHandle.getColumnBindings( ) // .iterator( ); iter.hasNext( ); ) // { // ComputedColumnHandle element = (ComputedColumnHandle) iter.next( // ); // if ( element.getStructure( ).equals( bindingColumn ) ) // { // bindingExist = true; // break; // } // } // } // else // { // for ( Iterator iter = container.getColumnBindings( ).iterator( ); // iter.hasNext( ); ) // { // ComputedColumnHandle element = (ComputedColumnHandle) iter.next( // ); // if ( element.getStructure( ).equals( bindingColumn ) ) // { // bindingExist = true; // break; // } // } // // } } else { ComputedColumn bindingColumn = StructureFactory.newComputedColumn( dataHandle, model.getColumnName( ) ); bindingColumn.setDataType( model.getDataType( ) ); ExpressionUtility.setBindingColumnExpression( model, bindingColumn ); bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model ) ); String displayKey = UIUtil.getColumnDisplayNameKey( model ); if ( displayKey != null ) bindingColumn.setDisplayNameID( displayKey ); if ( target instanceof DesignElementHandle ) { if ( ExpressionUtil.hasAggregation( bindingColumn.getExpression( ) ) ) { String groupType = DEUtil.getGroupControlType( (DesignElementHandle) target ); if ( groupType.equals( DEUtil.TYPE_GROUP_GROUP ) ) bindingColumn.setAggregateOn( ( (GroupHandle) DEUtil.getGroups( (DesignElementHandle) target ) .get( 0 ) ).getName( ) ); else if ( groupType.equals( DEUtil.TYPE_GROUP_LISTING ) ) bindingColumn.setAggregateOn( null ); } } dataHandle.addColumnBinding( bindingColumn, false ); dataHandle.setDataSet( dataSet ); } ActionHandle actionHandle = UIUtil.getColumnAction( model ); if ( actionHandle != null ) { List source = new ArrayList( ); source.add( actionHandle.getStructure( ) ); List newAction = ModelUtil.cloneStructList( source ); dataHandle.setAction( (Action) newAction.get( 0 ) ); } // if ( !bindingExist ) // { // ComputedColumn bindingColumn = StructureFactory.newComputedColumn( // dataHandle, // model.getColumnName( ) ); // bindingColumn.setDataType( model.getDataType( ) ); // bindingColumn.setExpression( DEUtil.getExpression( model ) ); // dataHandle.addColumnBinding( bindingColumn, false ); // dataHandle.setDataSet( dataSet ); // } InsertInLayoutRule rule = new LabelAddRule( target ); if ( rule.canInsert( ) ) { // LabelHandle label = SessionHandleAdapter.getInstance( ) // .getReportDesignHandle( ) // .getElementFactory( ) // .newLabel( null ); LabelHandle label = DesignElementFactory.getInstance( ) .newLabel( null ); label.setText( UIUtil.getColumnDisplayName( model ) ); String displayKey = UIUtil.getColumnDisplayNameKey( model ); if ( displayKey != null ) { label.setTextKey( displayKey ); } rule.insert( label ); } rule = new GroupKeySetRule( target, model ); if ( rule.canInsert( ) ) { rule.insert( model ); } return dataHandle; } /** * create a ComputedColumn object * * @param target * where data item will be inserted. * @param bindingHolder * where the ComputedColumn will be inserted. * @param model * column item * @return */ private static ComputedColumn createBindingColumn( Object target, ReportItemHandle bindingHolder, ResultSetColumnHandle model ) { ComputedColumn bindingColumn = StructureFactory.newComputedColumn( bindingHolder, model.getColumnName( ) ); bindingColumn.setDataType( model.getDataType( ) ); ExpressionUtility.setBindingColumnExpression( model, bindingColumn ); bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( model ) ); String displayKey = UIUtil.getColumnDisplayNameKey( model ); if ( displayKey != null ) bindingColumn.setDisplayNameID( displayKey ); if ( target instanceof DesignElementHandle ) { if ( ExpressionUtil.hasAggregation( bindingColumn.getExpression( ) ) ) { String groupType = DEUtil.getGroupControlType( (DesignElementHandle) target ); if ( groupType.equals( DEUtil.TYPE_GROUP_GROUP ) ) bindingColumn.setAggregateOn( ( (GroupHandle) DEUtil.getGroups( (DesignElementHandle) target ) .get( 0 ) ).getName( ) ); else if ( groupType.equals( DEUtil.TYPE_GROUP_LISTING ) ) bindingColumn.setAggregateOn( null ); } } return bindingColumn; } // private static GroupHandle getGroupHandle( Object target ) // { // DesignElementHandle handle = null; // if ( target instanceof CellHandle ) // { // handle = ( (CellHandle) target ).getContainer( ).getContainer( ); // } // else if ( target instanceof ListBandProxy ) // { // handle = ( (ListBandProxy) target ).getElemtHandle( ); // } // // if ( handle instanceof GroupHandle ) // { // return (GroupHandle) handle; // } // return null; // } /** * Inserts invalid column string into the target. Add label if possible * * @param expression * invalid column or other expression * @param target * insert target like cell or ListBandProxy * @return to be inserted data item * @throws SemanticException */ protected static DesignElementHandle performInsertString( String expression, Object target ) throws SemanticException { // DataItemHandle dataHandle = SessionHandleAdapter.getInstance( ) // .getReportDesignHandle( ) // .getElementFactory( ) // .newDataItem( null ); DataItemHandle dataHandle = DesignElementFactory.getInstance( ) .newDataItem( null ); dataHandle.setResultSetColumn( expression ); InsertInLayoutRule rule = new LabelAddRule( target ); if ( rule.canInsert( ) ) { // LabelHandle label = SessionHandleAdapter.getInstance( ) // .getReportDesignHandle( ) // .getElementFactory( ) // .newLabel( null ); LabelHandle label = DesignElementFactory.getInstance( ) .newLabel( null ); label.setText( expression ); rule.insert( label ); } return dataHandle; } protected static TableHandle performInsertDataSet( DataSetHandle model ) throws SemanticException { // DataSetItemModel[] columns = DataSetManager.getCurrentInstance( ) // .getColumns( model, false ); // if ( columns == null || columns.length == 0 ) // { // return null; // } // // TableHandle tableHandle = SessionHandleAdapter.getInstance( ) // // .getReportDesignHandle( ) // // .getElementFactory( ) // // .newTableItem( null, columns.length ); CachedMetaDataHandle cachedMetadata = DataSetUIUtil.getCachedMetaDataHandle( model ); List columList = new ArrayList( ); for ( Iterator iter = cachedMetadata.getResultSet( ).iterator( ); iter.hasNext( ); ) { ResultSetColumnHandle element = (ResultSetColumnHandle) iter.next( ); columList.add( element ); } ResultSetColumnHandle[] columns = (ResultSetColumnHandle[]) columList.toArray( new ResultSetColumnHandle[columList.size( )] ); TableHandle tableHandle = DesignElementFactory.getInstance( ) .newTableItem( null, columns.length ); setInitWidth( tableHandle ); insertToCell( model, tableHandle, tableHandle.getHeader( ), columns, true ); insertToCell( model, tableHandle, tableHandle.getDetail( ), columns, false ); tableHandle.setDataSet( model ); return tableHandle; } /** * Validates object can be inserted to layout. Support the multiple. * * @param insertObj * single inserted object or multi-objects * @param targetPart * @return if can be inserted to layout */ public static boolean handleValidateInsertToLayout( Object insertObj, EditPart targetPart ) { if ( targetPart == null ) { return false; } if ( insertObj instanceof Object[] ) { Object[] array = (Object[]) insertObj; if ( !checkSameDataSetInMultiColumns( array ) ) { return false; } if ( !checkContainContainMulitItem( array, targetPart.getModel( ) ) ) { return false; } for ( int i = 0; i < array.length; i++ ) { if ( !handleValidateInsertToLayout( array[i], targetPart ) ) { return false; } } return true; } else if ( insertObj instanceof IStructuredSelection ) { return handleValidateInsertToLayout( ( (IStructuredSelection) insertObj ).toArray( ), targetPart ); } else if ( insertObj instanceof DataSetHandle ) { return isHandleValid( (DataSetHandle) insertObj ) && handleValidateDataSet( targetPart ); } else if ( insertObj instanceof ResultSetColumnHandle ) { return handleValidateDataSetColumn( (ResultSetColumnHandle) insertObj, targetPart ); } // else if ( insertObj instanceof DimensionHandle ) // { // return handleValidateDimension( (DimensionHandle) insertObj, // targetPart ); // } // else if ( insertObj instanceof MeasureHandle ) // { // return handleValidateMeasure( (MeasureHandle) insertObj, // targetPart ); // } else if ( insertObj instanceof LabelHandle ) { return handleValidateLabel( (LabelHandle) insertObj, targetPart ); } else if ( insertObj instanceof ResultSetColumnHandle ) { return handleValidateDataSetColumn( (ResultSetColumnHandle) insertObj, targetPart ); } else if ( insertObj instanceof ScalarParameterHandle ) { return isHandleValid( (ScalarParameterHandle) insertObj ) && handleValidateParameter( targetPart ); } return false; } private static boolean handleValidateLabel( LabelHandle handle, EditPart targetPart ) { if ( targetPart.getModel( ) instanceof IAdaptable ) { Object obj = ( (IAdaptable) targetPart.getModel( ) ).getAdapter( DesignElementHandle.class ); if ( obj instanceof ExtendedItemHandle ) { return ( (ExtendedItemHandle) obj ).canContain( DEUtil.getDefaultContentName( obj ), handle ); } } return false; } private static boolean checkContainContainMulitItem( Object[] objects, Object slotHandle ) { SlotHandle handle = null; // if ( slotHandle instanceof ReportElementModel ) // { // handle = ( (ReportElementModel) slotHandle ).getSlotHandle( ); // } // else if ( slotHandle instanceof SlotHandle ) { handle = (SlotHandle) slotHandle; } if ( handle != null && objects != null && objects.length > 1 ) { if ( !handle.getDefn( ).isMultipleCardinality( ) ) { return false; } } return true; } /** * Checks if all the DataSetColumn has the same DataSet. * * @param array * all elements * @return false if not same; true if every column has the same DataSet or * the element is not an instance of DataSetColumn */ protected static boolean checkSameDataSetInMultiColumns( Object[] array ) { if ( array == null ) return false; Object dataSet = null; for ( int i = 0; i < array.length; i++ ) { if ( array[i] instanceof ResultSetColumnHandle ) { Object currDataSet = ( (ResultSetColumnHandle) array[i] ).getElementHandle( ); if ( currDataSet == null ) { return false; } if ( dataSet == null ) { dataSet = currDataSet; } else { if ( dataSet != currDataSet ) { return false; } } } } return true; } /** * Validates container of drop target from data set in data view * * @param dropPart * @return validate result */ protected static boolean handleValidateDataSetDropContainer( EditPart dropPart ) { if ( dropPart.getParent( ) == null ) { return false; } Object container = dropPart.getParent( ).getModel( ); return ( container instanceof GridHandle || container instanceof TableHandle || container instanceof FreeFormHandle || container instanceof ListHandle || dropPart.getModel( ) instanceof ModuleHandle ); } /** * Validates container of drop target from data set column in data view * * @param dropPart * @return validate result */ protected static boolean handleValidateDataSetColumnDropContainer( EditPart dropPart ) { if ( dropPart.getParent( ) == null ) { return false; } Object container = dropPart.getParent( ).getModel( ); return ( container instanceof GridHandle || container instanceof TableHandle || container instanceof FreeFormHandle || container instanceof ListHandle || container instanceof MasterPageHandle || dropPart.getModel( ) instanceof ModuleHandle ); } protected static boolean handleValidateMeasureDropContainer( MeasureHandle measure, EditPart dropPart ) { if ( dropPart.getModel( ) instanceof IVirtualValidator ) { return ( (IVirtualValidator) dropPart.getModel( ) ).handleValidate( measure ); } return false; } protected static boolean handleValidateDimensionDropContainer( DimensionHandle dimension, EditPart dropPart ) { if ( dropPart.getModel( ) instanceof IVirtualValidator ) { return ( (IVirtualValidator) dropPart.getModel( ) ).handleValidate( dimension ); } return false; } /** * Validates container of drop target from scalar parameter in data view * * @param dropPart * @return validate result */ protected static boolean handleValidateParameterDropContainer( EditPart dropPart ) { if ( dropPart.getParent( ) == null ) { return false; } Object container = dropPart.getParent( ).getModel( ); return ( container instanceof GridHandle || container instanceof TableHandle || container instanceof FreeFormHandle || container instanceof ListHandle || dropPart.getModel( ) instanceof ModuleHandle ); } /** * Validates drop target from data set in data view. * * @return validate result */ protected static boolean handleValidateDataSet( EditPart target ) { return handleValidateDataSetDropContainer( target ) && DNDUtil.handleValidateTargetCanContainType( target.getModel( ), ReportDesignConstants.TABLE_ITEM ); } protected static boolean handleValidateDimension( DimensionHandle insertObj, EditPart target ) { return handleValidateDimensionDropContainer( insertObj, target ); } protected static boolean handleValidateMeasure( MeasureHandle insertObj, EditPart target ) { return handleValidateMeasureDropContainer( insertObj, target ); } /** * Validates drop target from data set column in data view. * * @return validate result */ protected static boolean handleValidateDataSetColumn( ResultSetColumnHandle insertObj, EditPart target ) { if ( handleValidateDataSetColumnDropContainer( target ) && DNDUtil.handleValidateTargetCanContainType( target.getModel( ), ReportDesignConstants.DATA_ITEM ) ) { // Validates target is report root if ( target.getModel( ) instanceof ModuleHandle || isMasterPageHeaderOrFooter( target.getModel( ) ) ) { return true; } // Validates target's dataset is null or the same with the inserted DesignElementHandle handle = (DesignElementHandle) target.getParent( ) .getModel( ); if (handle instanceof TableHandle && target.getModel( ) instanceof CellHandle) { TableHandle tableHandle = (TableHandle)handle; CellHandle cellHandle = (CellHandle)target.getModel( ); if (DesignChoiceConstants.ANALYSIS_TYPE_DIMENSION.equals( UIUtil.getColumnAnalysis( insertObj ) )) { SlotHandle slotHandle = tableHandle.getGroups( ); for ( Object o : slotHandle.getContents( ) ) { GroupHandle group = (GroupHandle) o; if ( group.getName( ).equals( insertObj.getColumnName( ) ) ) return false; } } else if (DesignChoiceConstants.ANALYSIS_TYPE_ATTRIBUTE.equals(UIUtil.getColumnAnalysis( insertObj ) )) { String str = UIUtil.getAnalysisColumn( insertObj ); DataSetHandle dataset = (DataSetHandle) insertObj.getElementHandle( ); String type = ""; if (str != null) { for ( Iterator iter = dataset.getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP ) .iterator( ); iter.hasNext( ); ) { ColumnHintHandle element = (ColumnHintHandle) iter.next( ); if ( element.getColumnName( ).equals( str ) ||str.equals( element.getAlias( ) ) ) { type = element.getAnalysis( ); break; } } if (DesignChoiceConstants.ANALYSIS_TYPE_DIMENSION.equals( type )) { GroupHandle findGroup = null; SlotHandle slotHandle = tableHandle.getGroups( ); for ( Object o : slotHandle.getContents( ) ) { GroupHandle group = (GroupHandle) o; if ( group.getName( ).equals(str) ) { findGroup = group; } } if (findGroup == null) { // DesignElementHandle container = cellHandle.getContainer( ).getContainer( ); // if (container instanceof TableHandle) // { // return true; // } // if (container instanceof GroupHandle && str.equals( ((GroupHandle)container).getName( ))) // { // return true; // } // return false; return true; } else { if (cellHandle.getContainer( ).getContainer( ) == findGroup) { return true; } else { return false; } } } else if (!type.equals( "" )) //$NON-NLS-1$ { SlotHandle slotHandle = cellHandle.getContainer( ).getContainerSlotHandle( ); if (slotHandle.equals( tableHandle.getHeader( )) || slotHandle.equals( tableHandle.getFooter( ) ) ) { return true; } else { return false; } } } else { SlotHandle slotHandle = cellHandle.getContainer( ).getContainerSlotHandle( ); if (slotHandle == tableHandle.getHeader( ) || slotHandle == tableHandle.getFooter( )) { return true; } return false; } } } if ( handle instanceof ReportItemHandle ) { ReportItemHandle bindingHolder = DEUtil.getListingContainer( handle ); DataSetHandle itsDataSet = ( (ReportItemHandle) handle ).getDataSet( ); DataSetHandle dataSet = null; ReportItemHandle bindingRoot = DEUtil.getBindingRoot( handle ); if ( bindingRoot != null ) { dataSet = bindingRoot.getDataSet( ); } return itsDataSet == null && ( bindingHolder == null || !bindingHolder.getColumnBindings( ) .iterator( ) .hasNext( ) ) || insertObj.getElementHandle( ).equals( dataSet ); } } return false; } private static boolean isMasterPageHeaderOrFooter( Object obj ) { if ( !( obj instanceof SlotHandle ) ) { return false; } if ( ( (SlotHandle) obj ).getElementHandle( ) instanceof MasterPageHandle ) { return true; } return false; } /** * Validates drop target from scalar parameter in data view. * * @return validate result */ protected static boolean handleValidateParameter( EditPart target ) { return handleValidateParameterDropContainer( target ) && DNDUtil.handleValidateTargetCanContainType( target.getModel( ), ReportDesignConstants.DATA_ITEM ); } /** * Validates drag source from data view to layout. Support the multiple. * * @return validate result */ public static boolean handleValidateInsert( Object insertObj ) { if ( insertObj instanceof Object[] ) { Object[] array = (Object[]) insertObj; if ( array.length == 0 ) { return false; } for ( int i = 0; i < array.length; i++ ) { if ( !handleValidateInsert( array[i] ) ) return false; } return true; } else if ( insertObj instanceof IStructuredSelection ) { return handleValidateInsert( ( (IStructuredSelection) insertObj ).toArray( ) ); } // else if ( insertObj instanceof ParameterHandle ) // { // if ( ( (ParameterHandle) insertObj ).getRoot( ) instanceof // LibraryHandle ) // return false; // } if ( insertObj instanceof DataSetHandle ) { return DataSetUIUtil.hasMetaData( (DataSetHandle) insertObj ); } return insertObj instanceof ResultSetColumnHandle || insertObj instanceof ScalarParameterHandle || insertObj instanceof DimensionHandle || insertObj instanceof MeasureHandle; } protected static void insertToCell( DataSetHandle model, TableHandle tableHandle, SlotHandle slot, ResultSetColumnHandle[] columns, boolean isLabel ) { for ( int i = 0; i < slot.getCount( ); i++ ) { SlotHandle cells = ( (RowHandle) slot.get( i ) ).getCells( ); for ( int j = 0; j < cells.getCount( ); j++ ) { CellHandle cell = (CellHandle) cells.get( j ); try { if ( isLabel ) { LabelHandle labelItemHandle = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) .getElementFactory( ) .newLabel( null ); // LabelHandle labelItemHandle = // DesignElementFactory.getInstance( ) // .newLabel( null ); String labelText = UIUtil.getColumnDisplayName( columns[j] ); if ( labelText != null ) { labelItemHandle.setText( labelText ); } String displayKey = UIUtil.getColumnDisplayNameKey( columns[j] ); if ( displayKey != null ) { labelItemHandle.setTextKey( displayKey ); } cell.addElement( labelItemHandle, cells.getSlotID( ) ); } else { DataItemHandle dataHandle = SessionHandleAdapter.getInstance( ) .getReportDesignHandle( ) .getElementFactory( ) .newDataItem( null ); // DataItemHandle dataHandle = // DesignElementFactory.getInstance( ) // .newDataItem( null ); dataHandle.setResultSetColumn( columns[j].getColumnName( ) ); formatDataHandle( dataHandle, columns[j] ); cell.addElement( dataHandle, cells.getSlotID( ) ); // add data binding to table. ComputedColumn bindingColumn = StructureFactory.newComputedColumn( tableHandle, columns[j].getColumnName( ) ); bindingColumn.setDataType( columns[j].getDataType( ) ); ExpressionUtility.setBindingColumnExpression( columns[j], bindingColumn ); bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( columns[j] ) ); String displayKey = UIUtil.getColumnDisplayNameKey( columns[j] ); if ( displayKey != null ) bindingColumn.setDisplayNameID( displayKey ); tableHandle.addColumnBinding( bindingColumn, false ); ActionHandle actionHandle = UIUtil.getColumnAction( columns[j] ); if ( actionHandle != null ) { List source = new ArrayList( ); source.add( actionHandle.getStructure( ) ); List newAction = ModelUtil.cloneStructList( source ); dataHandle.setAction( (Action) newAction.get( 0 ) ); } } } catch ( Exception e ) { ExceptionHandler.handle( e ); } } } } private static void formatDataHandle(DataItemHandle dataHandle, ResultSetColumnHandle column) { try { StyleHandle styleHandle = dataHandle.getPrivateStyle( ); boolean wordWrap = UIUtil.isWordWrap( column ); if (wordWrap) { styleHandle.setWhiteSpace( DesignChoiceConstants.WHITE_SPACE_NORMAL ); } else { styleHandle.setWhiteSpace( DesignChoiceConstants.WHITE_SPACE_NOWRAP ); } String aliment = UIUtil.getClolumnHandleAlignment( column ); if (aliment != null) { styleHandle.setTextAlign( aliment ); } String helpText = UIUtil.getClolumnHandleHelpText( column ); if (helpText != null) { dataHandle.setHelpText( helpText ); } ColumnHintHandle hintHandle = findColumnHintHandle( column ); if (hintHandle != null) { formatDataHandleDataType( column.getDataType( ), hintHandle.getValueFormat( ), styleHandle ); } } catch(SemanticException e) { //do nothing now } } private static ColumnHintHandle findColumnHintHandle(ResultSetColumnHandle column) { DataSetHandle dataset = (DataSetHandle) column.getElementHandle( ); for ( Iterator iter = dataset.getPropertyHandle( DataSetHandle.COLUMN_HINTS_PROP ) .iterator( ); iter.hasNext( ); ) { ColumnHintHandle element = (ColumnHintHandle) iter.next( ); if ( element.getColumnName( ).equals( column.getColumnName( ) ) || column.getColumnName( ).equals( element.getAlias( ) ) ) { return element; } } return null; } public static void formatDataHandleDataType(String type, FormatValue formartValue,StyleHandle styleHandle) { if (formartValue == null) { return; } try { if (DesignChoiceConstants.COLUMN_DATA_TYPE_INTEGER.equals( type ) || DesignChoiceConstants.COLUMN_DATA_TYPE_DECIMAL.equals( type ) || DesignChoiceConstants.COLUMN_DATA_TYPE_FLOAT.equals( type )) { if (formartValue.getPattern( ) != null) { styleHandle.setNumberFormat( formartValue.getPattern( ) ); } if (formartValue.getCategory( ) != null) { styleHandle.setNumberFormatCategory( formartValue.getCategory( ) ); } } else if (DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME.equals( type ) || DesignChoiceConstants.COLUMN_DATA_TYPE_DATE.equals( type )) { if (formartValue.getPattern( ) != null) { styleHandle.setDateTimeFormat( formartValue.getPattern( ) ); } if (formartValue.getCategory( ) != null) { styleHandle.setDateTimeFormatCategory( formartValue.getCategory( ) ); } } else if (DesignChoiceConstants.COLUMN_DATA_TYPE_STRING.equals( type )) { if (formartValue.getPattern( ) != null) { styleHandle.setStringFormat( formartValue.getPattern( ) ); } if (formartValue.getCategory( ) != null) { styleHandle.setStringFormatCategory( formartValue.getCategory( ) ); } } } catch ( SemanticException e ) { //do nothing now } } /** * Sets initial width to new object * * @param object * new object */ public static void setInitWidth( Object object ) { // int percentAll = 100; // try // { // if ( object instanceof TableHandle ) // { // TableHandle table = (TableHandle) object; // table.setWidth( percentAll // + DesignChoiceConstants.UNITS_PERCENTAGE ); // } // else if ( object instanceof GridHandle ) // { // GridHandle grid = (GridHandle) object; // grid.setWidth( percentAll // + DesignChoiceConstants.UNITS_PERCENTAGE ); // } // else // return; // } // catch ( SemanticException e ) // { // ExceptionHandler.handle( e ); // } } protected static boolean isHandleValid( DesignElementHandle handle ) { if ( handle instanceof DataSetHandle ) { if ( ( !( handle instanceof JointDataSetHandle || handle instanceof DerivedDataSetHandle ) && ( (DataSetHandle) handle ).getDataSource( ) == null ) || !DataSetUIUtil.hasMetaData( (DataSetHandle) handle ) ) { return false; } } return handle.isValid( ) && handle.getSemanticErrors( ).isEmpty( ); } /** * Converts edit part selection into model selection. * * @param selection * edit part * @return model, return Collections.EMPTY_LIST if selection is null or * empty. */ public static IStructuredSelection editPart2Model( ISelection selection ) { if ( selection == null || !( selection instanceof IStructuredSelection ) ) return new StructuredSelection( Collections.EMPTY_LIST ); List list = ( (IStructuredSelection) selection ).toList( ); List resultList = new ArrayList( ); for ( int i = 0; i < list.size( ); i++ ) { Object obj = list.get( i ); if ( obj instanceof ReportElementEditPart ) { Object model = ( (ReportElementEditPart) obj ).getModel( ); if ( model instanceof ListBandProxy ) { model = ( (ListBandProxy) model ).getSlotHandle( ); } resultList.add( model ); } } return new StructuredSelection( resultList ); } /** * Converts edit part selection into model selection. * * @param selection * edit part * @return model, return Collections.EMPTY_LIST if selection is null or * empty. */ public static IStructuredSelection editPart2Model( List selection ) { if ( selection == null || ( selection.size( ) == 0 ) ) return new StructuredSelection( Collections.EMPTY_LIST ); List list = selection; List resultList = new ArrayList( ); for ( int i = 0; i < list.size( ); i++ ) { Object obj = list.get( i ); if ( obj instanceof ReportElementEditPart ) { Object model = ( (ReportElementEditPart) obj ).getModel( ); if ( model instanceof ListBandProxy ) { model = ( (ListBandProxy) model ).getSlotHandle( ); } resultList.add( model ); } } return new StructuredSelection( resultList ); } }
- Summary:When insert a attribute result column,add the group binding to the table. - Bugzilla Bug (s) Resolved: - Description: - Tests Description : Manual test - Files Edited: - Files Added: - Files Deleted: - Notes to Build Team: - Notes to Developers: - Notes to QA: - Notes to Documentation:
UI/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/dnd/InsertInLayoutUtil.java
- Summary:When insert a attribute result column,add the group binding to the table.
<ide><path>I/org.eclipse.birt.report.designer.ui/src/org/eclipse/birt/report/designer/internal/ui/dnd/InsertInLayoutUtil.java <ide> bindingColumn.setDisplayNameID( displayKey ); <ide> tableHandle.addColumnBinding( bindingColumn, false ); <ide> dataHandle.setResultSetColumn( model.getColumnName( ) ); <add> <add> bindingColumn = StructureFactory.newComputedColumn( tableHandle, <add> newResultColumn.getColumnName( ) ); <add> bindingColumn.setDataType( newResultColumn.getDataType( )); <add> ExpressionUtility.setBindingColumnExpression( newResultColumn, <add> bindingColumn ); <add> bindingColumn.setDisplayName( UIUtil.getColumnDisplayName( newResultColumn ) ); <add> displayKey = UIUtil.getColumnDisplayNameKey( newResultColumn ); <add> if ( displayKey != null ) <add> bindingColumn.setDisplayNameID( displayKey ); <add> tableHandle.addColumnBinding( bindingColumn, false ); <ide> <ide> return addGroupHandle( tableHandle, newResultColumn.getColumnName( ), dataHandle ); <ide> }
Java
apache-2.0
31677920e517f6c3c5b1e8ce5d90b9571d646571
0
pizcogirl/gdx-ai,zgpxgame/gdx-ai,lanen/gdx-ai,atomixnmc/gdx-ai,kishorpv/gdx-ai,domokato/gdx-ai,printedheart/gdx-ai,libgdx/gdx-ai,piotr-j/gdx-ai,atomixnmc/gdx-ai,atomixnmc/gdx-ai
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.ai.steer.paths; import com.badlogic.gdx.ai.steer.behaviors.PathParam; import com.badlogic.gdx.ai.steer.behaviors.Path; import com.badlogic.gdx.ai.steer.paths.LinePath.LinePathParam; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector; import com.badlogic.gdx.utils.Array; /** A path for path following behaviors that is made up of a series of waypoints. Each waypoint is connected to the successor with * a segment. * * @param <T> Type of vector, either 2D or 3D, implementing the {@link Vector} interface * * @author davebaol * @author Daniel Holderbaum */ public class LinePath<T extends Vector<T>> implements Path<T, LinePathParam> { private Array<Segment<T>> segments; private boolean isOpen; private float pathLength; private T nearestPointOnCurrentSegment; private T nearestPointOnPath; private T tmp1; private T tmp2; private T tmp3; /** Creates a closed {@code LinePath} for the specified {@code waypoints}. * @param waypoints the points making up the path * @throws IllegalArgumentException if {@code waypoints} is {@code null} or has less than two (2) waypoints. */ public LinePath (Array<T> waypoints) { this(waypoints, false); } /** Creates a {@code LinePath} for the specified {@code waypoints}. * @param waypoints the points making up the path * @param isOpen a flag indicating whether the path is open or not * @throws IllegalArgumentException if {@code waypoints} is {@code null} or has less than two (2) waypoints. */ public LinePath (Array<T> waypoints, boolean isOpen) { this.isOpen = isOpen; createPath(waypoints); nearestPointOnCurrentSegment = waypoints.first().cpy(); nearestPointOnPath = waypoints.first().cpy(); tmp1 = waypoints.first().cpy(); tmp2 = waypoints.first().cpy(); tmp3 = waypoints.first().cpy(); } @Override public boolean isOpen () { return isOpen; } @Override public float getLength () { return pathLength; } @Override public T getStartPoint () { return segments.first().begin; } @Override public T getEndPoint () { return segments.peek().end; } /** Returns the square distance of the nearest point on line segment {@code a-b}, from point {@code c}. Also, the {@code out} * vector is assigned to the nearest point. * @param out the output vector that contains the nearest point on return * @param a the start point of the line segment * @param b the end point of the line segment * @param c the point to calculate the distance from */ public float calculatePointSegmentSquareDistance (T out, T a, T b, T c) { tmp1.set(a); tmp2.set(b); tmp3.set(c); T ab = tmp2.sub(a); float t = (tmp3.sub(a)).dot(ab) / ab.len2(); t = MathUtils.clamp(t, 0, 1); out.set(tmp1.add(ab.scl(t))); tmp1.set(out); T distance = tmp1.sub(c); return distance.len2(); } @Override public LinePathParam createParam () { return new LinePathParam(); } // We pass the last parameter value to the path in order to calculate the current // parameter value. This is essential to avoid nasty problems when lines are close together. // We should limit the algorithm to only considering areas of the path close to the previous // parameter value. The character is unlikely to have moved far, after all. // This technique, assuming the new value is close to the old one, is called coherence, and it is a // feature of many geometric algorithms. // TODO: Currently coherence is not implemented. @Override public float calculateDistance (T agentCurrPos, LinePathParam parameter) { // Find the nearest segment float smallestDistance2 = Float.POSITIVE_INFINITY; Segment<T> nearestSegment = null; for (int i = 0; i < segments.size; i++) { Segment<T> segment = segments.get(i); float distance2 = calculatePointSegmentSquareDistance(nearestPointOnCurrentSegment, segment.begin, segment.end, agentCurrPos); // first point if (distance2 < smallestDistance2) { nearestPointOnPath.set(nearestPointOnCurrentSegment); smallestDistance2 = distance2; nearestSegment = segment; parameter.segmentIndex = i; } } // Distance from path start float lengthOnPath = nearestSegment.cumulativeLength - nearestPointOnPath.dst(nearestSegment.end); parameter.setDistance(lengthOnPath); return lengthOnPath; } @Override public void calculateTargetPosition (T out, LinePathParam param, float targetDistance) { if (isOpen) { // Open path support if (targetDistance < 0) { // Clamp target distance to the min targetDistance = 0; } else if (targetDistance > pathLength) { // Clamp target distance to the max targetDistance = pathLength; } } else { // Closed path support if (targetDistance < 0) { // Backwards targetDistance = pathLength + (targetDistance % pathLength); } else if (targetDistance > pathLength) { // Forward targetDistance = targetDistance % pathLength; } } // Walk through lines to see on which line we are Segment<T> desiredSegment = null; for (int i = 0; i < segments.size; i++) { Segment<T> segment = segments.get(i); if (segment.cumulativeLength >= targetDistance) { desiredSegment = segment; break; } } // begin-------targetPos-------end float distance = desiredSegment.cumulativeLength - targetDistance; out.set(desiredSegment.begin).sub(desiredSegment.end).scl(distance / desiredSegment.length).add(desiredSegment.end); } /** Sets up this {@link Path} using the given way points. * @param waypoints The way points of this path. * @throws IllegalArgumentException if {@code waypoints} is {@code null} or empty. */ public void createPath (Array<T> waypoints) { if (waypoints == null || waypoints.size < 2) throw new IllegalArgumentException("waypoints cannot be null and must contain at least two (2) waypoints"); segments = new Array<Segment<T>>(waypoints.size); pathLength = 0; T curr = waypoints.first(); T prev = null; for (int i = 1; i <= waypoints.size; i++) { prev = curr; if (i < waypoints.size) curr = waypoints.get(i); else if (isOpen) break; // keep the path open else curr = waypoints.first(); // close the path Segment<T> segment = new Segment<T>(prev, curr); pathLength += segment.length; segment.cumulativeLength = pathLength; segments.add(segment); } } public Array<Segment<T>> getSegments () { return segments; } public static class LinePathParam implements PathParam { int segmentIndex; float distance; @Override public float getDistance () { return distance; } @Override public void setDistance (float distance) { this.distance = distance; } } public static class Segment<T extends Vector<T>> { T begin; T end; float length; float cumulativeLength; Segment (T begin, T end) { this.begin = begin; this.end = end; this.length = begin.dst(end); } public T getBegin () { return begin; } public T getEnd () { return end; } public float getLength () { return length; } public float getCumulativeLength () { return cumulativeLength; } } }
gdx-ai/src/com/badlogic/gdx/ai/steer/paths/LinePath.java
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.badlogic.gdx.ai.steer.paths; import com.badlogic.gdx.ai.steer.behaviors.PathParam; import com.badlogic.gdx.ai.steer.behaviors.Path; import com.badlogic.gdx.ai.steer.paths.LinePath.LinePathParam; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector; import com.badlogic.gdx.utils.Array; /** A path for path following behaviors that is made up of a series of waypoints. Each waypoint is connected to the successor with * a segment. * * @param <T> Type of vector, either 2D or 3D, implementing the {@link Vector} interface * * @author davebaol * @author Daniel Holderbaum */ public class LinePath<T extends Vector<T>> implements Path<T, LinePathParam> { private Array<Segment<T>> segments; private boolean isOpen; private float pathLength; private T nearestPointOnCurrentSegment; private T nearestPointOnPath; private T tmp1; private T tmp2; private T tmp3; /** Creates a closed {@code LinePath} for the specified {@code waypoints}. * @param waypoints the points making up the path * @throws IllegalArgumentException if {@code waypoints} is {@code null} or empty. */ public LinePath (Array<T> waypoints) { this(waypoints, false); } /** Creates a {@code LinePath} for the specified {@code waypoints}. * @param waypoints the points making up the path * @param isOpen a flag indicating whether the path is open or not * @throws IllegalArgumentException if {@code waypoints} is {@code null} or empty. */ public LinePath (Array<T> waypoints, boolean isOpen) { this.isOpen = isOpen; createPath(waypoints); nearestPointOnCurrentSegment = waypoints.first().cpy(); nearestPointOnPath = waypoints.first().cpy(); tmp1 = waypoints.first().cpy(); tmp2 = waypoints.first().cpy(); tmp3 = waypoints.first().cpy(); } @Override public boolean isOpen () { return isOpen; } @Override public float getLength () { return pathLength; } @Override public T getStartPoint () { return segments.first().begin; } @Override public T getEndPoint () { return segments.peek().end; } /** Returns the square distance of the nearest point on line segment {@code a-b}, from point {@code c}. Also, the {@code out} * vector is assigned to the nearest point. * @param out the output vector that contains the nearest point on return * @param a the start point of the line segment * @param b the end point of the line segment * @param c the point to calculate the distance from */ public float calculatePointSegmentSquareDistance (T out, T a, T b, T c) { tmp1.set(a); tmp2.set(b); tmp3.set(c); T ab = tmp2.sub(a); float t = (tmp3.sub(a)).dot(ab) / ab.len2(); t = MathUtils.clamp(t, 0, 1); out.set(tmp1.add(ab.scl(t))); tmp1.set(out); T distance = tmp1.sub(c); return distance.len2(); } @Override public LinePathParam createParam () { return new LinePathParam(); } // We pass the last parameter value to the path in order to calculate the current // parameter value. This is essential to avoid nasty problems when lines are close together. // We should limit the algorithm to only considering areas of the path close to the previous // parameter value. The character is unlikely to have moved far, after all. // This technique, assuming the new value is close to the old one, is called coherence, and it is a // feature of many geometric algorithms. // TODO: Currently coherence is not implemented. @Override public float calculateDistance (T agentCurrPos, LinePathParam parameter) { // Find the nearest segment float smallestDistance2 = Float.POSITIVE_INFINITY; Segment<T> nearestSegment = null; for (int i = 0; i < segments.size; i++) { Segment<T> segment = segments.get(i); float distance2 = calculatePointSegmentSquareDistance(nearestPointOnCurrentSegment, segment.begin, segment.end, agentCurrPos); // first point if (distance2 < smallestDistance2) { nearestPointOnPath.set(nearestPointOnCurrentSegment); smallestDistance2 = distance2; nearestSegment = segment; parameter.segmentIndex = i; } } // Distance from path start float lengthOnPath = nearestSegment.cumulativeLength - nearestPointOnPath.dst(nearestSegment.end); parameter.setDistance(lengthOnPath); return lengthOnPath; } @Override public void calculateTargetPosition (T out, LinePathParam param, float targetDistance) { if (isOpen) { // Open path support if (targetDistance < 0) { // Clamp target distance to the min targetDistance = 0; } else if (targetDistance > pathLength) { // Clamp target distance to the max targetDistance = pathLength; } } else { // Closed path support if (targetDistance < 0) { // Backwards targetDistance = pathLength + (targetDistance % pathLength); } else if (targetDistance > pathLength) { // Forward targetDistance = targetDistance % pathLength; } } // Walk through lines to see on which line we are Segment<T> desiredSegment = null; for (int i = 0; i < segments.size; i++) { Segment<T> segment = segments.get(i); if (segment.cumulativeLength >= targetDistance) { desiredSegment = segment; break; } } // begin-------targetPos-------end float distance = desiredSegment.cumulativeLength - targetDistance; out.set(desiredSegment.begin).sub(desiredSegment.end).scl(distance / desiredSegment.length).add(desiredSegment.end); } /** Sets up this {@link Path} using the given way points. * @param waypoints The way points of this path. * @throws IllegalArgumentException if {@code waypoints} is {@code null} or empty. */ public void createPath (Array<T> waypoints) { if (waypoints == null || waypoints.size == 0) throw new IllegalArgumentException("waypoints cannot be null or empty"); segments = new Array<Segment<T>>(waypoints.size); pathLength = 0; T curr = waypoints.first(); T prev = null; for (int i = 1; i <= waypoints.size; i++) { prev = curr; if (i < waypoints.size) curr = waypoints.get(i); else if (isOpen) break; // keep the path open else curr = waypoints.first(); // close the path Segment<T> segment = new Segment<T>(prev, curr); pathLength += segment.length; segment.cumulativeLength = pathLength; segments.add(segment); } } public Array<Segment<T>> getSegments () { return segments; } public static class LinePathParam implements PathParam { int segmentIndex; float distance; @Override public float getDistance () { return distance; } @Override public void setDistance (float distance) { this.distance = distance; } } public static class Segment<T extends Vector<T>> { T begin; T end; float length; float cumulativeLength; Segment (T begin, T end) { this.begin = begin; this.end = end; this.length = begin.dst(end); } public T getBegin () { return begin; } public T getEnd () { return end; } public float getLength () { return length; } public float getCumulativeLength () { return cumulativeLength; } } }
Changed check for LinePaths, since a path needs to consist of at least two waypoints to work
gdx-ai/src/com/badlogic/gdx/ai/steer/paths/LinePath.java
Changed check for LinePaths, since a path needs to consist of at least two waypoints to work
<ide><path>dx-ai/src/com/badlogic/gdx/ai/steer/paths/LinePath.java <ide> <ide> /** Creates a closed {@code LinePath} for the specified {@code waypoints}. <ide> * @param waypoints the points making up the path <del> * @throws IllegalArgumentException if {@code waypoints} is {@code null} or empty. */ <add> * @throws IllegalArgumentException if {@code waypoints} is {@code null} or has less than two (2) waypoints. */ <ide> public LinePath (Array<T> waypoints) { <ide> this(waypoints, false); <ide> } <ide> /** Creates a {@code LinePath} for the specified {@code waypoints}. <ide> * @param waypoints the points making up the path <ide> * @param isOpen a flag indicating whether the path is open or not <del> * @throws IllegalArgumentException if {@code waypoints} is {@code null} or empty. */ <add> * @throws IllegalArgumentException if {@code waypoints} is {@code null} or has less than two (2) waypoints. */ <ide> public LinePath (Array<T> waypoints, boolean isOpen) { <ide> this.isOpen = isOpen; <ide> createPath(waypoints); <ide> * @param waypoints The way points of this path. <ide> * @throws IllegalArgumentException if {@code waypoints} is {@code null} or empty. */ <ide> public void createPath (Array<T> waypoints) { <del> if (waypoints == null || waypoints.size == 0) throw new IllegalArgumentException("waypoints cannot be null or empty"); <add> if (waypoints == null || waypoints.size < 2) throw new IllegalArgumentException("waypoints cannot be null and must contain at least two (2) waypoints"); <ide> <ide> segments = new Array<Segment<T>>(waypoints.size); <ide> pathLength = 0;
JavaScript
agpl-3.0
d5528156e7a71235ae136719a3240da5728c7561
0
floraXiao/gooderp_addons,OpenERPJeff/gooderp_addons,floraXiao/gooderp_addons,gilbert-yuan/gooderp_addons,Judystudy/gooderp_addons,GoodERPJeff/gooderp_addons,GoodERPJeff/gooderp_addons,Judystudy/gooderp_addons,OpenERPJeff/gooderp_addons,OpenERPJeff/gooderp_addons,luoguizhou/gooderp_addons,luoguizhou/gooderp_addons,gilbert-yuan/gooderp_addons,GoodERPJeff/gooderp_addons,gilbert-yuan/gooderp_addons,floraXiao/gooderp_addons,gilbert-yuan/gooderp_addons,luoguizhou/gooderp_addons,Judystudy/gooderp_addons
odoo.define('web.float_limit', function(require) { var form_widgets = require('web.form_widget'); var form_view = require('web.FormView'); var core = require('web.core'); var float_limit = form_widgets.FieldFloat.extend({ is_valid: function() { res = this._super.apply(this, arguments); if (res && this.view && this.view.fields && !_.isUndefined(this.view.fields[this.options.field])) { var max_float = this.view.fields[this.options.field].get_value(); if (max_float > 0 && parseFloat(this.$('input:first').val()) > max_float) { this.view.float_limit_desc = '当前数量已经超出了最大规定数量' + max_float; return false; } } return res } }); core.form_widget_regist.add('float_limit', float_limit); form_view.include({ on_invalid: function() { if (this.float_limit_desc) { this.do_warn('错误', this.float_limit_desc); } else { this._super.apply(this, arguments); } }, }) });
web_float_limit/static/src/js/limit.js
odoo.web_float_limit = function(instance) { instance.web.form.widgets = instance.web.form.widgets.extend({ 'float_limit' : 'instance.web.form.FieldFloatLimit', }); instance.web.form.FieldFloatLimit = instance.web.form.FieldFloat.extend({ is_valid: function() { res = this._super.apply(this, arguments); var notify = instance.web.notification; if (res && this.view && this.view.fields && !_.isUndefined(this.view.fields[this.options.field])) { var max_float = this.view.fields[this.options.field].get_value(); console.warn('max_float', max_float); if (max_float > 0 && parseFloat(this.$('input:first').val()) > max_float) { this.view.float_limit_desc = '当前数量已经超出了最大规定数量' + max_float; return false; } } return res } }) instance.web.FormView.include({ on_invalid: function() { if (this.float_limit_desc) { this.do_warn('错误', this.float_limit_desc); } else { this._super.apply(this, arguments); } }, }) };
使得web_float_limit适配10.0
web_float_limit/static/src/js/limit.js
使得web_float_limit适配10.0
<ide><path>eb_float_limit/static/src/js/limit.js <del>odoo.web_float_limit = function(instance) { <del> instance.web.form.widgets = instance.web.form.widgets.extend({ <del> 'float_limit' : 'instance.web.form.FieldFloatLimit', <del> }); <del> <del> instance.web.form.FieldFloatLimit = instance.web.form.FieldFloat.extend({ <add>odoo.define('web.float_limit', function(require) { <add> var form_widgets = require('web.form_widget'); <add> var form_view = require('web.FormView'); <add> var core = require('web.core'); <add> <add> var float_limit = form_widgets.FieldFloat.extend({ <ide> is_valid: function() { <ide> res = this._super.apply(this, arguments); <del> var notify = instance.web.notification; <ide> if (res && this.view && this.view.fields && !_.isUndefined(this.view.fields[this.options.field])) { <ide> var max_float = this.view.fields[this.options.field].get_value(); <del> console.warn('max_float', max_float); <ide> if (max_float > 0 && parseFloat(this.$('input:first').val()) > max_float) { <ide> this.view.float_limit_desc = '当前数量已经超出了最大规定数量' + max_float; <ide> return false; <ide> <ide> return res <ide> } <del> }) <del> <del> instance.web.FormView.include({ <add> }); <add> <add> core.form_widget_regist.add('float_limit', float_limit); <add> <add> form_view.include({ <ide> on_invalid: function() { <ide> if (this.float_limit_desc) { <ide> this.do_warn('错误', this.float_limit_desc); <ide> } <ide> }, <ide> }) <del> <del>}; <add>});
JavaScript
apache-2.0
487d45144da5c511e08ea221ebee8b3f9b5ae5a8
0
mcanthony/moonstone,enyojs/moonstone,mcanthony/moonstone,mcanthony/moonstone
/** _moon.Slider_ is a control that presents a range of selection options in the form of a horizontal slider with a control knob. The knob may be tapped and dragged to the desired location. {kind: "moon.Slider", value: 30} The _onChanging_ event is fired while the control knob is being dragged, and the _onChange_ event is fired when the position is set, either by finishing a drag or by tapping the bar. */ enyo.kind({ name: "moon.Slider", kind: "moon.ProgressBar", classes: "moon-slider", spotlight: true, published: { //* Position of slider, expressed as an integer between 0 and 100, //* inclusive value: 0, //* If true, current progress will be styled differently from rest of bar lockBar: true, //* If true, tapping on bar will change current position tappable: true, //* Color of value popup popupColor: "#ffb80d", //* When true, button is shown as disabled and does not generate tap events disabled: false, /** When true, knob and progress move with animation by clicking left/right direction key or by tapping the bar. */ animate: true, //* When false, the slider's popup bubble is displayed when slider is adjusted noPopup: false, //* When true, you can move the knob past the _bgProgress_ pastBgProgress: false, //* When true, you can see elastic effect when drag knob past the _bgProgress_ elasticEffect: false }, events: { //* Fires when bar position is set. The _value_ property contains the //* new position. onChange: "", //* Fires while control knob is being dragged. The _value_ property //* contains the current position. onChanging: "", //* Fires when animation to a position finishes. onAnimateFinish: "" }, //* @protected handlers: { ondragstart: "dragstart", ondrag: "drag", ondragfinish: "dragfinish", onSpotlightFocus: "spotFocus", onSpotlightSelect: "spotSelect", onSpotlightBlur: "spotBlur", onSpotlightLeft: "spotLeft", onSpotlightRight: "spotRight" }, moreComponents: [ {kind: "Animator", onStep: "animatorStep", onEnd: "animatorComplete"}, {classes: "moon-slider-taparea"}, {name: "knob", ondown: "showKnobStatus", onup: "hideKnobStatus", classes: "moon-slider-knob"}, {kind: "enyo.Popup", name: "popup", classes: "moon-slider-popup above", components: [ {tag: "canvas", name: "drawing", attributes: { width: 62, height: 52 }}, {name: "popupLabel", classes: "moon-slider-popup-label"} ]} ], animatingTo: null, create: function() { this.inherited(arguments); if (typeof ilib !== "undefined") { this._nf = new ilib.NumFmt({type: "percentage"}); } this.createComponents(this.moreComponents); this.initValue(); this.disabledChanged(); }, destroy: function() { if (this._nf) { delete this._nf; } this.inherited(arguments); }, rendered: function() { this.inherited(arguments); this.drawToCanvas(this.popupColor); }, disabledChanged: function() { this.addRemoveClass("disabled", this.disabled); this.$.knob.addRemoveClass("disabled", this.disabled); this.setTappable(!this.disabled); }, calcPastBgProgress: function(value) { var max = (this.pastBgProgress == true) ? this.max : this.bgProgress; return this.clampValue(this.min, max, this.getValue()); }, //* Prep value at create time initValue: function() { this.value = this.calcPastBgProgress(this.value); this.updateKnobPosition(this.calcPercent(this.getValue())); if (this.lockBar) { this.setProgress(this.getValue()); } }, setValue: function(inValue) { inValue = this.calcPastBgProgress(inValue); if (this.animate) { this.animateTo(this.getValue(), inValue); } else { this._setValue(inValue); } }, _setValue: function(inValue) { var v = this.calcPastBgProgress(inValue); // If no change, return if (v === this.value) { return; } this.value = v; this.updateKnobPosition(this.calcPercent(this.value)); if (this.lockBar) { this.setProgress(this.value); } this.sendChangeEvent({value: this.getValue()}); }, getValue: function() { return (this.animatingTo !== null) ? this.animatingTo : this.value; }, updateKnobPosition: function(inPercent) { this.$.knob.applyStyle("left", inPercent + "%"); this.$.popup.applyStyle("left", inPercent + "%"); var label = ""; if (typeof ilib !== "undefined") { label = this._nf.format(Math.round(inPercent)); } else { label = Math.round(inPercent) + "%"; } this.$.popupLabel.setContent(label); this.updatePopupPosition(); }, updatePopupPosition: function() { var inControl = this.$.popup; if (!inControl.hasNode().getBoundingClientRect) { return; } var hFlip = false; // popup bounds var pb = inControl.hasNode().getBoundingClientRect(); // container bounds var cb = this.container.hasNode().getBoundingClientRect(); // knob bounds var kb = this.$.knob.hasNode().getBoundingClientRect(); // when the popup's right edge is out of the window, adjust to the left if ( (kb.left + (kb.width/2) + pb.width) > cb.right ) { inControl.applyStyle("left", (kb.left - pb.width) + "px"); hFlip = true; } inControl.addRemoveClass("moon-slider-popup-flip-h", hFlip); this.$.popupLabel.addRemoveClass("moon-slider-popup-flip-h", hFlip); }, calcKnobPosition: function(inEvent) { var x = inEvent.clientX - this.hasNode().getBoundingClientRect().left; return (x / this.getBounds().width) * (this.max - this.min) + this.min; }, dragstart: function(inSender, inEvent) { if (this.disabled) { return; // return nothing } if (inEvent.horizontal) { inEvent.preventDefault(); this.dragging = true; this.$.knob.addClass("active"); this.showKnobStatus(); return true; } }, drag: function(inSender, inEvent) { if (this.dragging) { var v = this.calcKnobPosition(inEvent), ev = 0; v = (this.increment) ? this.calcIncrement(v) : v; emax = (this.pastBgProgress == true) ? this.max : this.bgProgress; ev = emax + (v-emax)*0.4; this.targetValue = v = this.clampValue(this.min, emax, v); if (this.elasticEffect == true) { this.elasticValue = (emax > v) ? v : ev; } else { this.elasticValue = this.targetValue; } var p = this.calcPercent(this.elasticValue); this.updateKnobPosition(p); if (this.lockBar) { this.setProgress(v); } this.sendChangingEvent({value: v}); return true; } }, dragfinish: function(inSender, inEvent) { if (this.disabled) { return; // return nothing } //var v = this.calcKnobPosition(inEvent); // v = (this.increment) ? this.calcIncrement(v) : v; // this._setValue(v); var v = (this.increment) ? this.calcIncrement(this.targetValue) : this.targetValue; this.animateTo(this.elasticValue, v); this.dragging = false; inEvent.preventTap(); this.$.knob.removeClass("active"); this.hideKnobStatus(); return true; }, tap: function(inSender, inEvent) { if (this.tappable && !this.disabled) { var v = this.calcKnobPosition(inEvent); v = (this.increment) ? this.calcIncrement(v) : v; this.setValue(v); return true; } }, //* @public //* Animates to the given value. animateTo: function(inStartValue, inEndValue) { this.animatingTo = inEndValue; this.$.animator.play({ startValue: inStartValue, endValue: inEndValue, node: this.hasNode() }); }, //* @protected animatorStep: function(inSender) { var //max = (this.pastBgProgress == true) ? this.max : this.bgProgress, //v = this.clampValue(this.min, max, inSender.value), v = inSender.value, p = this.calcPercent(v); this.updateKnobPosition(p); if (this.lockBar) { this.setProgress(v); } this.sendChangingEvent({value: v}); return true; }, animatorComplete: function(inSender) { this._setValue(inSender.value); this.animatingTo = null; this.doAnimateFinish(inSender); return true; }, spotFocus: function() { return; }, spotSelect: function() { var sh = this.$.popup.getShowing(); this.$.knob.addRemoveClass("spotselect", !sh); if (!this.noPopup) { this.$.popup.setShowing(!sh); } this.selected = !sh; return true; }, spotBlur: function() { if (this.dragging) { return true; } else { if (this.$.knob) { this.$.knob.removeClass("spotselect"); } if (this.$.popup) { this.$.popup.hide(); } this.selected = false; } }, spotLeft: function(inSender, inEvent) { if (this.selected) { // If in the process of animating, work from the previously set value var v = this.getValue() - (this.increment || 1); this.setValue(v); return true; } }, spotRight: function(inSender, inEvent) { if (this.selected) { var v = this.getValue() + (this.increment || 1); this.setValue(v); return true; } }, showKnobStatus: function(inSender, inEvent) { if ((!this.disabled) && (!this.noPopup)) { this.$.popup.show(); } }, hideKnobStatus: function(inSender, inEvent) { if (!this.noPopup) { this.$.popup.hide(); } }, drawToCanvas: function(bgColor) { var h = 51; // height total var hb = h - 4; // height bubble var hbc = (hb-1)/2; // height of bubble's center var w = 61; // width total var wre = 46; // width's right edge var wle = 16; // width's left edge var r = 20; // radius var ctx = this.$.drawing.hasNode().getContext("2d"); // Set styles. Default color is knob's color ctx.fillStyle = bgColor || enyo.dom.getComputedStyleValue(this.$.knob.hasNode(), "background-color"); // Draw shape with arrow on bottom-left ctx.moveTo(1, h); ctx.arcTo(1, hb, 39, hb, 8); ctx.lineTo(wre, hb); ctx.arcTo(w, hb, w, hbc, r); ctx.arcTo(w, 1, wre, 1, r); ctx.lineTo(wle, 1); ctx.arcTo(1, 1, 1, hbc, r); ctx.lineTo(1, h); ctx.fill(); }, changeDelayMS: 50, sendChangeEvent: function(inEventData) { this.throttleJob("sliderChange", function() { this.doChange(inEventData); }, this.changeDelayMS); }, sendChangingEvent: function(inEventData) { this.throttleJob("sliderChanging", function() { this.doChanging(inEventData); }, this.changeDelayMS); } });
source/Slider.js
/** _moon.Slider_ is a control that presents a range of selection options in the form of a horizontal slider with a control knob. The knob may be tapped and dragged to the desired location. {kind: "moon.Slider", value: 30} The _onChanging_ event is fired while the control knob is being dragged, and the _onChange_ event is fired when the position is set, either by finishing a drag or by tapping the bar. */ enyo.kind({ name: "moon.Slider", kind: "moon.ProgressBar", classes: "moon-slider", spotlight: true, published: { //* Position of slider, expressed as an integer between 0 and 100, //* inclusive value: 0, //* If true, current progress will be styled differently from rest of bar lockBar: true, //* If true, tapping on bar will change current position tappable: true, //* Color of value popup popupColor: "#ffb80d", //* When true, button is shown as disabled and does not generate tap events disabled: false, /** When true, knob and progress move with animation by clicking left/right direction key or by tapping the bar. */ animate: true, //* When false, the slider's popup bubble is displayed when slider is adjusted noPopup: false }, events: { //* Fires when bar position is set. The _value_ property contains the //* new position. onChange: "", //* Fires while control knob is being dragged. The _value_ property //* contains the current position. onChanging: "", //* Fires when animation to a position finishes. onAnimateFinish: "" }, //* @protected handlers: { ondragstart: "dragstart", ondrag: "drag", ondragfinish: "dragfinish", onSpotlightFocus: "spotFocus", onSpotlightSelect: "spotSelect", onSpotlightBlur: "spotBlur", onSpotlightLeft: "spotLeft", onSpotlightRight: "spotRight" }, moreComponents: [ {kind: "Animator", onStep: "animatorStep", onEnd: "animatorComplete"}, {classes: "moon-slider-taparea"}, {name: "knob", ondown: "showKnobStatus", onup: "hideKnobStatus", classes: "moon-slider-knob"}, {kind: "enyo.Popup", name: "popup", classes: "moon-slider-popup above", components: [ {tag: "canvas", name: "drawing", attributes: { width: 62, height: 52 }}, {name: "popupLabel", classes: "moon-slider-popup-label"} ]} ], animatingTo: null, create: function() { this.inherited(arguments); if (typeof ilib !== "undefined") { this._nf = new ilib.NumFmt({type: "percentage"}); } this.createComponents(this.moreComponents); this.initValue(); this.disabledChanged(); }, destroy: function() { if (this._nf) { delete this._nf; } this.inherited(arguments); }, rendered: function() { this.inherited(arguments); this.drawToCanvas(this.popupColor); }, disabledChanged: function() { this.addRemoveClass("disabled", this.disabled); this.$.knob.addRemoveClass("disabled", this.disabled); this.setTappable(!this.disabled); }, //* Prep value at create time initValue: function() { this.updateKnobPosition(this.calcPercent(this.getValue())); if (this.lockBar) { this.setProgress(this.getValue()); } }, setValue: function(inValue) { if (this.animate) { this.animateTo(this.getValue(), inValue); } else { this._setValue(inValue); } }, _setValue: function(inValue) { var v = this.clampValue(this.min, this.max, inValue); // If no change, return if (v === this.value) { return; } this.value = v; this.updateKnobPosition(this.calcPercent(this.value)); if (this.lockBar) { this.setProgress(this.value); } this.sendChangeEvent({value: this.getValue()}); }, getValue: function() { return (this.animatingTo !== null) ? this.animatingTo : this.value; }, updateKnobPosition: function(inPercent) { this.$.knob.applyStyle("left", inPercent + "%"); this.$.popup.applyStyle("left", inPercent + "%"); var label = ""; if (typeof ilib !== "undefined") { label = this._nf.format(Math.round(inPercent)); } else { label = Math.round(inPercent) + "%"; } this.$.popupLabel.setContent(label); this.updatePopupPosition(); }, updatePopupPosition: function() { var inControl = this.$.popup; if (!inControl.hasNode().getBoundingClientRect) { return; } var hFlip = false; // popup bounds var pb = inControl.hasNode().getBoundingClientRect(); // container bounds var cb = this.container.hasNode().getBoundingClientRect(); // knob bounds var kb = this.$.knob.hasNode().getBoundingClientRect(); // when the popup's right edge is out of the window, adjust to the left if ( (kb.left + (kb.width/2) + pb.width) > cb.right ) { inControl.applyStyle("left", (kb.left - pb.width) + "px"); hFlip = true; } inControl.addRemoveClass("moon-slider-popup-flip-h", hFlip); this.$.popupLabel.addRemoveClass("moon-slider-popup-flip-h", hFlip); }, calcKnobPosition: function(inEvent) { var x = inEvent.clientX - this.hasNode().getBoundingClientRect().left; return (x / this.getBounds().width) * (this.max - this.min) + this.min; }, dragstart: function(inSender, inEvent) { if (this.disabled) { return; // return nothing } if (inEvent.horizontal) { inEvent.preventDefault(); this.dragging = true; this.$.knob.addClass("active"); this.showKnobStatus(); return true; } }, drag: function(inSender, inEvent) { if (this.dragging) { var v = this.calcKnobPosition(inEvent); v = (this.increment) ? this.calcIncrement(v) : v; v = this.clampValue(this.min, this.max, v); var p = this.calcPercent(v); this.updateKnobPosition(p); if (this.lockBar) { this.setProgress(v); } this.sendChangingEvent({value: v}); return true; } }, dragfinish: function(inSender, inEvent) { if (this.disabled) { return; // return nothing } var v = this.calcKnobPosition(inEvent); v = (this.increment) ? this.calcIncrement(v) : v; this._setValue(v); this.dragging = false; inEvent.preventTap(); this.$.knob.removeClass("active"); this.hideKnobStatus(); return true; }, tap: function(inSender, inEvent) { if (this.tappable && !this.disabled) { var v = this.calcKnobPosition(inEvent); v = (this.increment) ? this.calcIncrement(v) : v; this.setValue(v); return true; } }, //* @public //* Animates to the given value. animateTo: function(inStartValue, inEndValue) { this.animatingTo = inEndValue; this.$.animator.play({ startValue: inStartValue, endValue: inEndValue, node: this.hasNode() }); }, //* @protected animatorStep: function(inSender) { var v = this.clampValue(this.min, this.max, inSender.value), p = this.calcPercent(v); this.updateKnobPosition(p); if (this.lockBar) { this.setProgress(v); } this.sendChangingEvent({value: v}); return true; }, animatorComplete: function(inSender) { this._setValue(inSender.value); this.animatingTo = null; this.doAnimateFinish(inSender); return true; }, spotFocus: function() { return; }, spotSelect: function() { var sh = this.$.popup.getShowing(); this.$.knob.addRemoveClass("spotselect", !sh); if (!this.noPopup) { this.$.popup.setShowing(!sh); } this.selected = !sh; return true; }, spotBlur: function() { if (this.dragging) { return true; } else { if (this.$.knob) { this.$.knob.removeClass("spotselect"); } if (this.$.popup) { this.$.popup.hide(); } this.selected = false; } }, spotLeft: function(inSender, inEvent) { if (this.selected) { // If in the process of animating, work from the previously set value var v = this.getValue() - (this.increment || 1); this.setValue(v); return true; } }, spotRight: function(inSender, inEvent) { if (this.selected) { var v = this.getValue() + (this.increment || 1); this.setValue(v); return true; } }, showKnobStatus: function(inSender, inEvent) { if ((!this.disabled) && (!this.noPopup)) { this.$.popup.show(); } }, hideKnobStatus: function(inSender, inEvent) { if (!this.noPopup) { this.$.popup.hide(); } }, drawToCanvas: function(bgColor) { var h = 51; // height total var hb = h - 4; // height bubble var hbc = (hb-1)/2; // height of bubble's center var w = 61; // width total var wre = 46; // width's right edge var wle = 16; // width's left edge var r = 20; // radius var ctx = this.$.drawing.hasNode().getContext("2d"); // Set styles. Default color is knob's color ctx.fillStyle = bgColor || enyo.dom.getComputedStyleValue(this.$.knob.hasNode(), "background-color"); // Draw shape with arrow on bottom-left ctx.moveTo(1, h); ctx.arcTo(1, hb, 39, hb, 8); ctx.lineTo(wre, hb); ctx.arcTo(w, hb, w, hbc, r); ctx.arcTo(w, 1, wre, 1, r); ctx.lineTo(wle, 1); ctx.arcTo(1, 1, 1, hbc, r); ctx.lineTo(1, h); ctx.fill(); }, changeDelayMS: 50, sendChangeEvent: function(inEventData) { this.throttleJob("sliderChange", function() { this.doChange(inEventData); }, this.changeDelayMS); }, sendChangingEvent: function(inEventData) { this.throttleJob("sliderChanging", function() { this.doChanging(inEventData); }, this.changeDelayMS); } });
Initial implementation of elastic effect on Slider control http://jira2.lgsvl.com/browse/GF-6668 Enyo-DCO-1.1-Signed-off-by: Kunmyon Choi [email protected]
source/Slider.js
Initial implementation of elastic effect on Slider control
<ide><path>ource/Slider.js <ide> */ <ide> animate: true, <ide> //* When false, the slider's popup bubble is displayed when slider is adjusted <del> noPopup: false <add> noPopup: false, <add> //* When true, you can move the knob past the _bgProgress_ <add> pastBgProgress: false, <add> //* When true, you can see elastic effect when drag knob past the _bgProgress_ <add> elasticEffect: false <ide> }, <ide> events: { <ide> //* Fires when bar position is set. The _value_ property contains the <ide> this.$.knob.addRemoveClass("disabled", this.disabled); <ide> this.setTappable(!this.disabled); <ide> }, <add> calcPastBgProgress: function(value) { <add> var max = (this.pastBgProgress == true) ? this.max : this.bgProgress; <add> return this.clampValue(this.min, max, this.getValue()); <add> }, <ide> //* Prep value at create time <ide> initValue: function() { <add> this.value = this.calcPastBgProgress(this.value); <ide> this.updateKnobPosition(this.calcPercent(this.getValue())); <ide> if (this.lockBar) { <ide> this.setProgress(this.getValue()); <ide> } <ide> }, <ide> setValue: function(inValue) { <add> inValue = this.calcPastBgProgress(inValue); <ide> if (this.animate) { <ide> this.animateTo(this.getValue(), inValue); <ide> } else { <ide> } <ide> }, <ide> _setValue: function(inValue) { <del> var v = this.clampValue(this.min, this.max, inValue); <add> var v = this.calcPastBgProgress(inValue); <ide> <ide> // If no change, return <ide> if (v === this.value) { <ide> }, <ide> drag: function(inSender, inEvent) { <ide> if (this.dragging) { <del> var v = this.calcKnobPosition(inEvent); <add> var v = this.calcKnobPosition(inEvent), <add> ev = 0; <add> <ide> v = (this.increment) ? this.calcIncrement(v) : v; <del> v = this.clampValue(this.min, this.max, v); <del> var p = this.calcPercent(v); <del> <add> <add> emax = (this.pastBgProgress == true) ? this.max : this.bgProgress; <add> ev = emax + (v-emax)*0.4; <add> <add> this.targetValue = v = this.clampValue(this.min, emax, v); <add> if (this.elasticEffect == true) { <add> this.elasticValue = (emax > v) ? v : ev; <add> } else { <add> this.elasticValue = this.targetValue; <add> } <add> <add> var p = this.calcPercent(this.elasticValue); <ide> this.updateKnobPosition(p); <ide> <ide> if (this.lockBar) { <ide> if (this.disabled) { <ide> return; // return nothing <ide> } <del> var v = this.calcKnobPosition(inEvent); <del> v = (this.increment) ? this.calcIncrement(v) : v; <del> this._setValue(v); <add> //var v = this.calcKnobPosition(inEvent); <add> // v = (this.increment) ? this.calcIncrement(v) : v; <add> // this._setValue(v); <add> var v = (this.increment) ? this.calcIncrement(this.targetValue) : this.targetValue; <add> this.animateTo(this.elasticValue, v); <ide> <ide> this.dragging = false; <ide> <ide> }, <ide> //* @protected <ide> animatorStep: function(inSender) { <del> var v = this.clampValue(this.min, this.max, inSender.value), <add> var //max = (this.pastBgProgress == true) ? this.max : this.bgProgress, <add> //v = this.clampValue(this.min, max, inSender.value), <add> v = inSender.value, <ide> p = this.calcPercent(v); <ide> <ide> this.updateKnobPosition(p);
Java
mit
eb18032d9c111b21b73e1a3d2274ec327a038ea4
0
oscargus/jabref,Siedlerchr/jabref,zellerdev/jabref,tobiasdiez/jabref,Mr-DLib/jabref,zellerdev/jabref,sauliusg/jabref,oscargus/jabref,grimes2/jabref,motokito/jabref,Braunch/jabref,ayanai1/jabref,JabRef/jabref,Mr-DLib/jabref,JabRef/jabref,ayanai1/jabref,grimes2/jabref,zellerdev/jabref,obraliar/jabref,bartsch-dev/jabref,oscargus/jabref,mredaelli/jabref,tschechlovdev/jabref,Braunch/jabref,motokito/jabref,Braunch/jabref,mairdl/jabref,Siedlerchr/jabref,mairdl/jabref,mairdl/jabref,tschechlovdev/jabref,obraliar/jabref,ayanai1/jabref,Braunch/jabref,grimes2/jabref,oscargus/jabref,mairdl/jabref,tobiasdiez/jabref,motokito/jabref,tobiasdiez/jabref,mredaelli/jabref,shitikanth/jabref,jhshinn/jabref,JabRef/jabref,jhshinn/jabref,shitikanth/jabref,grimes2/jabref,bartsch-dev/jabref,bartsch-dev/jabref,obraliar/jabref,bartsch-dev/jabref,tobiasdiez/jabref,ayanai1/jabref,Siedlerchr/jabref,shitikanth/jabref,zellerdev/jabref,shitikanth/jabref,mredaelli/jabref,ayanai1/jabref,jhshinn/jabref,Mr-DLib/jabref,motokito/jabref,Mr-DLib/jabref,oscargus/jabref,jhshinn/jabref,tschechlovdev/jabref,sauliusg/jabref,tschechlovdev/jabref,jhshinn/jabref,mredaelli/jabref,sauliusg/jabref,shitikanth/jabref,obraliar/jabref,sauliusg/jabref,bartsch-dev/jabref,motokito/jabref,Mr-DLib/jabref,mredaelli/jabref,grimes2/jabref,zellerdev/jabref,tschechlovdev/jabref,JabRef/jabref,obraliar/jabref,Braunch/jabref,mairdl/jabref,Siedlerchr/jabref
/* Copyright (C) 2003-2012 JabRef contributors. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package net.sf.jabref; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.tree.TreePath; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import net.sf.jabref.autocompleter.AbstractAutoCompleter; import net.sf.jabref.autocompleter.AutoCompleterFactory; import net.sf.jabref.autocompleter.NameFieldAutoCompleter; import net.sf.jabref.collab.ChangeScanner; import net.sf.jabref.collab.FileUpdateListener; import net.sf.jabref.collab.FileUpdatePanel; import net.sf.jabref.export.ExportToClipboardAction; import net.sf.jabref.export.FileActions; import net.sf.jabref.export.SaveDatabaseAction; import net.sf.jabref.export.SaveException; import net.sf.jabref.export.SaveSession; import net.sf.jabref.export.layout.Layout; import net.sf.jabref.export.layout.LayoutHelper; import net.sf.jabref.external.*; import net.sf.jabref.groups.GroupSelector; import net.sf.jabref.groups.GroupTreeNode; import net.sf.jabref.gui.*; import net.sf.jabref.imports.AppendDatabaseAction; import net.sf.jabref.imports.BibtexParser; import net.sf.jabref.imports.SPIRESFetcher; import net.sf.jabref.journals.AbbreviateAction; import net.sf.jabref.journals.UnabbreviateAction; import net.sf.jabref.labelPattern.LabelPatternUtil; import net.sf.jabref.labelPattern.SearchFixDuplicateLabels; import net.sf.jabref.search.NoSearchMatcher; import net.sf.jabref.search.SearchMatcher; import net.sf.jabref.specialfields.SpecialFieldAction; import net.sf.jabref.specialfields.Priority; import net.sf.jabref.specialfields.Quality; import net.sf.jabref.specialfields.Rank; import net.sf.jabref.specialfields.Relevance; import net.sf.jabref.specialfields.SpecialFieldDatabaseChangeListener; import net.sf.jabref.specialfields.SpecialFieldValue; import net.sf.jabref.sql.DBConnectDialog; import net.sf.jabref.sql.DBStrings; import net.sf.jabref.sql.DbConnectAction; import net.sf.jabref.sql.DBExporterAndImporterFactory; import net.sf.jabref.sql.SQLUtil; import net.sf.jabref.sql.exporter.DBExporter; import net.sf.jabref.undo.CountingUndoManager; import net.sf.jabref.undo.NamedCompound; import net.sf.jabref.undo.UndoableChangeType; import net.sf.jabref.undo.UndoableInsertEntry; import net.sf.jabref.undo.UndoableKeyChange; import net.sf.jabref.undo.UndoableRemoveEntry; import net.sf.jabref.wizard.text.gui.TextInputDialog; import ca.odell.glazedlists.FilterList; import ca.odell.glazedlists.event.ListEvent; import ca.odell.glazedlists.event.ListEventListener; import ca.odell.glazedlists.matchers.Matcher; import com.jgoodies.forms.builder.DefaultFormBuilder; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.uif_lite.component.UIFSplitPane; public class BasePanel extends JPanel implements ClipboardOwner, FileUpdateListener { public final static int SHOWING_NOTHING=0, SHOWING_PREVIEW=1, SHOWING_EDITOR=2, WILL_SHOW_EDITOR=3; /* * The database shown in this panel. */ BibtexDatabase database; private int mode=0; private EntryEditor currentEditor = null; private PreviewPanel currentPreview = null; boolean tmp = true; private MainTableSelectionListener selectionListener = null; private ListEventListener<BibtexEntry> groupsHighlightListener; UIFSplitPane contentPane = new UIFSplitPane(); JSplitPane splitPane; JabRefFrame frame; String fileMonitorHandle = null; boolean saving = false, updatedExternally = false; private String encoding; GridBagLayout gbl = new GridBagLayout(); GridBagConstraints con = new GridBagConstraints(); HashMap<String, AbstractAutoCompleter> autoCompleters = new HashMap<String, AbstractAutoCompleter>(); // Hashtable that holds as keys the names of the fields where // autocomplete is active, and references to the autocompleter objects. NameFieldAutoCompleter searchCompleter = null; AutoCompleteListener searchCompleteListener = null; // The undo manager. public CountingUndoManager undoManager = new CountingUndoManager(this); UndoAction undoAction = new UndoAction(); RedoAction redoAction = new RedoAction(); private List<BibtexEntry> previousEntries = new ArrayList<BibtexEntry>(), nextEntries = new ArrayList<BibtexEntry>(); //ExampleFileFilter fileFilter; // File filter for .bib files. boolean baseChanged = false, nonUndoableChange = false; // Used to track whether the base has changed since last save. //EntryTableModel tableModel = null; //public EntryTable entryTable = null; public MainTable mainTable = null; public MainTableFormat tableFormat = null; public FilterList<BibtexEntry> searchFilterList = null, groupFilterList = null; public RightClickMenu rcm; BibtexEntry showing = null; // Variable to prevent erroneous update of back/forward histories at the time // when a Back or Forward operation is being processed: private boolean backOrForwardInProgress = false; // To indicate which entry is currently shown. public HashMap<String, EntryEditor> entryEditors = new HashMap<String, EntryEditor>(); // To contain instantiated entry editors. This is to save time // in switching between entries. //HashMap entryTypeForms = new HashMap(); // Hashmap to keep track of which entries currently have open // EntryTypeForm dialogs. PreambleEditor preambleEditor = null; // Keeps track of the preamble dialog if it is open. StringDialog stringDialog = null; // Keeps track of the string dialog if it is open. SaveDatabaseAction saveAction; CleanUpAction cleanUpAction; /** * The group selector component for this database. Instantiated by the * SidePaneManager if necessary, or from this class if merging groups from a * different database. */ //GroupSelector groupSelector; public boolean showingSearch = false, showingGroup = false, sortingBySearchResults = false, coloringBySearchResults = false, hidingNonHits = false, sortingByGroup = false, sortingByCiteSeerResults = false, coloringByGroup = false; int lastSearchHits = -1; // The number of hits in the latest search. // Potential use in hiding non-hits completely. // MetaData parses, keeps and writes meta data. MetaData metaData; private boolean suppressOutput = false; private HashMap<String, Object> actions = new HashMap<String, Object>(); private SidePaneManager sidePaneManager; /** * Create a new BasePanel with an empty database. * @param frame The application window. */ public BasePanel(JabRefFrame frame) { this.sidePaneManager = Globals.sidePaneManager; database = new BibtexDatabase(); metaData = new MetaData(); metaData.initializeNewDatabase(); this.frame = frame; setupActions(); setupMainPanel(); encoding = Globals.prefs.get("defaultEncoding"); //System.out.println("Default: "+encoding); } public BasePanel(JabRefFrame frame, BibtexDatabase db, File file, MetaData metaData, String encoding) { init(frame, db, file, metaData, encoding); } private void init(JabRefFrame frame, BibtexDatabase db, File file, MetaData metaData, String encoding) { this.encoding = encoding; this.metaData = metaData; // System.out.println(encoding); //super(JSplitPane.HORIZONTAL_SPLIT, true); this.sidePaneManager = Globals.sidePaneManager; this.frame = frame; database = db; setupActions(); setupMainPanel(); metaData.setFile(file); // Register so we get notifications about outside changes to the file. if (file != null) try { fileMonitorHandle = Globals.fileUpdateMonitor.addUpdateListener(this, file); } catch (IOException ex) { } } public boolean isBaseChanged(){ return baseChanged; } public int getMode() { return mode; } //Done by MrDlib public void setMode(int mode) { this.mode = mode; } //Done by MrDlib public BibtexDatabase database() { return database; } public MetaData metaData() { return metaData; } public JabRefFrame frame() { return frame; } public JabRefPreferences prefs() { return Globals.prefs; } public String getEncoding() { return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } public void output(String s) { if (!suppressOutput) frame.output(s); } private void setupActions() { saveAction = new SaveDatabaseAction(this); cleanUpAction = new CleanUpAction(this); actions.put("undo", undoAction); actions.put("redo", redoAction); actions.put("focusTable", new BaseAction() { public void action() throws Throwable { new FocusRequester(mainTable); } }); // The action for opening an entry editor. actions.put("edit", new BaseAction() { public void action() { /*System.out.println(Globals.focusListener.getFocused().getClass().getName()); if (Globals.focusListener.getFocused() instanceof FieldEditor) new FocusRequester(mainTable); else*/ selectionListener.editSignalled(); } /* if (isShowingEditor()) { new FocusRequester(splitPane.getBottomComponent()); return; } frame.block(); //(new Thread() { //public void run() { int clickedOn = -1; // We demand that one and only one row is selected. if (entryTable.getSelectedRowCount() == 1) { clickedOn = entryTable.getSelectedRow(); } if (clickedOn >= 0) { String id = tableModel.getIdForRow(clickedOn); BibtexEntry be = database.getEntryById(id); showEntry(be); if (splitPane.getBottomComponent() != null) { new FocusRequester(splitPane.getBottomComponent()); } } frame.unblock(); } */ }); actions.put("test",// new AccessLinksForEntries.SaveWithLinkedFiles(this)); new FindFullTextAction(this)); // The action for saving a database. actions.put("save", saveAction); actions.put("saveAs", new BaseAction() { public void action() throws Throwable { saveAction.saveAs(); } }); actions.put("saveSelectedAs", new BaseAction () { public void action() throws Throwable { String chosenFile = FileDialogs.getNewFile(frame, new File(Globals.prefs.get("workingDirectory")), ".bib", JFileChooser.SAVE_DIALOG, false); if (chosenFile != null) { File expFile = new File(chosenFile); if (!expFile.exists() || (JOptionPane.showConfirmDialog (frame, "'"+expFile.getName()+"' "+ Globals.lang("exists. Overwrite file?"), Globals.lang("Save database"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION)) { saveDatabase(expFile, true, Globals.prefs.get("defaultEncoding")); //runCommand("save"); frame.getFileHistory().newFile(expFile.getPath()); frame.output(Globals.lang("Saved selected to")+" '" +expFile.getPath()+"'."); } } } }); // The action for copying selected entries. actions.put("copy", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) { TransferableBibtexEntry trbe = new TransferableBibtexEntry(bes); // ! look at ClipBoardManager Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(trbe, BasePanel.this); output(Globals.lang("Copied")+" "+(bes.length>1 ? bes.length+" " +Globals.lang("entries") : "1 "+Globals.lang("entry")+".")); } else { // The user maybe selected a single cell. int[] rows = mainTable.getSelectedRows(), cols = mainTable.getSelectedColumns(); if ((cols.length == 1) && (rows.length == 1)) { // Copy single value. Object o = mainTable.getValueAt(rows[0], cols[0]); if (o != null) { StringSelection ss = new StringSelection(o.toString()); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(ss, BasePanel.this); output(Globals.lang("Copied cell contents")+"."); } } } } }); actions.put("cut", new BaseAction() { public void action() throws Throwable { runCommand("copy"); BibtexEntry[] bes = mainTable.getSelectedEntries(); //int row0 = mainTable.getSelectedRow(); if ((bes != null) && (bes.length > 0)) { // Create a CompoundEdit to make the action undoable. NamedCompound ce = new NamedCompound (Globals.lang(bes.length > 1 ? "cut entries" : "cut entry")); // Loop through the array of entries, and delete them. for (int i=0; i<bes.length; i++) { database.removeEntry(bes[i].getId()); ensureNotShowing(bes[i]); ce.addEdit(new UndoableRemoveEntry (database, bes[i], BasePanel.this)); } //entryTable.clearSelection(); frame.output(Globals.lang("Cut_pr")+" "+ (bes.length>1 ? bes.length +" "+ Globals.lang("entries") : Globals.lang("entry"))+"."); ce.end(); undoManager.addEdit(ce); markBaseChanged(); // Reselect the entry in the first prev. selected position: /*if (row0 >= entryTable.getRowCount()) row0 = entryTable.getRowCount()-1; if (row0 >= 0) entryTable.addRowSelectionInterval(row0, row0);*/ } } }); actions.put("delete", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) { boolean goOn = showDeleteConfirmationDialog(bes.length); if (!goOn) { return; } else { // Create a CompoundEdit to make the action undoable. NamedCompound ce = new NamedCompound (Globals.lang(bes.length > 1 ? "delete entries" : "delete entry")); // Loop through the array of entries, and delete them. for (int i = 0; i < bes.length; i++) { database.removeEntry(bes[i].getId()); ensureNotShowing(bes[i]); ce.addEdit(new UndoableRemoveEntry(database, bes[i], BasePanel.this)); } markBaseChanged(); frame.output(Globals.lang("Deleted") + " " + (bes.length > 1 ? bes.length + " " + Globals.lang("entries") : Globals.lang("entry")) + "."); ce.end(); undoManager.addEdit(ce); //entryTable.clearSelection(); } // Reselect the entry in the first prev. selected position: /*if (row0 >= entryTable.getRowCount()) row0 = entryTable.getRowCount()-1; if (row0 >= 0) { final int toSel = row0; // SwingUtilities.invokeLater(new Runnable() { public void run() { entryTable.addRowSelectionInterval(toSel, toSel); //entryTable.ensureVisible(toSel); } }); */ } } }); // The action for pasting entries or cell contents. // Edited by Seb Wills <[email protected]> on 14-Apr-04: // - more robust detection of available content flavors (doesn't only look at first one offered) // - support for parsing string-flavor clipboard contents which are bibtex entries. // This allows you to (a) paste entire bibtex entries from a text editor, web browser, etc // (b) copy and paste entries between multiple instances of JabRef (since // only the text representation seems to get as far as the X clipboard, at least on my system) actions.put("paste", new BaseAction() { public void action() { // Get clipboard contents, and see if TransferableBibtexEntry is among the content flavors offered Transferable content = Toolkit.getDefaultToolkit() .getSystemClipboard().getContents(null); if (content != null) { BibtexEntry[] bes = null; if (content.isDataFlavorSupported(TransferableBibtexEntry.entryFlavor)) { // We have determined that the clipboard data is a set of entries. try { bes = (BibtexEntry[])(content.getTransferData(TransferableBibtexEntry.entryFlavor)); } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } else if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { BibtexParser bp = new BibtexParser (new java.io.StringReader( (String) (content.getTransferData( DataFlavor.stringFlavor)))); BibtexDatabase db = bp.parse().getDatabase(); Util.pr("Parsed " + db.getEntryCount() + " entries from clipboard text"); if(db.getEntryCount()>0) { bes = db.getEntries().toArray(new BibtexEntry[db.getEntryCount()]); } } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (Throwable ex) { ex.printStackTrace(); } } // finally we paste in the entries (if any), which either came from TransferableBibtexEntries // or were parsed from a string if ((bes != null) && (bes.length > 0)) { NamedCompound ce = new NamedCompound (Globals.lang(bes.length > 1 ? "paste entries" : "paste entry")); // Store the first inserted bibtexentry. // bes[0] does not work as bes[0] is first clonded, // then inserted. // This entry is used to open up an entry editor // for the first inserted entry. BibtexEntry firstBE = null; for (int i=0; i<bes.length; i++) { try { BibtexEntry be = (BibtexEntry)(bes[i].clone()); if (firstBE == null) firstBE = be; Util.setAutomaticFields(be, Globals.prefs.getBoolean("overwriteOwner"), Globals.prefs.getBoolean("overwriteTimeStamp")); // We have to clone the // entries, since the pasted // entries must exist // independently of the copied // ones. be.setId(Util.createNeutralId()); database.insertEntry(be); addToSelectedGroup(be); ce.addEdit(new UndoableInsertEntry (database, be, BasePanel.this)); } catch (KeyCollisionException ex) { Util.pr("KeyCollisionException... this shouldn't happen."); } } ce.end(); undoManager.addEdit(ce); //entryTable.clearSelection(); //entryTable.revalidate(); output(Globals.lang("Pasted") + " " + (bes.length > 1 ? bes.length + " " + Globals.lang("entries") : "1 " + Globals.lang("entry")) + "."); markBaseChanged(); if (Globals.prefs.getBoolean("autoOpenForm")) { selectionListener.editSignalled(firstBE); } highlightEntry(firstBE); } } } }); actions.put("selectAll", new BaseAction() { public void action() { mainTable.selectAll(); } }); // The action for opening the preamble editor actions.put("editPreamble", new BaseAction() { public void action() { if (preambleEditor == null) { PreambleEditor form = new PreambleEditor (frame, BasePanel.this, database, Globals.prefs); Util.placeDialog(form, frame); form.setVisible(true); preambleEditor = form; } else { preambleEditor.setVisible(true); } } }); // The action for opening the string editor actions.put("editStrings", new BaseAction() { public void action() { if (stringDialog == null) { StringDialog form = new StringDialog (frame, BasePanel.this, database, Globals.prefs); Util.placeDialog(form, frame); form.setVisible(true); stringDialog = form; } else { stringDialog.setVisible(true); } } }); // The action for toggling the groups interface actions.put("toggleGroups", new BaseAction() { public void action() { sidePaneManager.toggle("groups"); frame.groupToggle.setSelected(sidePaneManager.isComponentVisible("groups")); } }); // action for collecting database strings from user actions.put("dbConnect", new DbConnectAction(this)); // action for exporting database to external SQL database actions.put("dbExport", new AbstractWorker () { String errorMessage = null; boolean connectToDB = false; // run first, in EDT: public void init() { DBStrings dbs = metaData.getDBStrings(); // get DBStrings from user if necessary if (!dbs.isConfigValid()) { // init DB strings if necessary if (! dbs.isInitialized()) { dbs.initialize(); } // show connection dialog DBConnectDialog dbd = new DBConnectDialog(frame(), dbs); Util.placeDialog(dbd, BasePanel.this ); dbd.setVisible(true); connectToDB = dbd.getConnectToDB(); // store database strings if (connectToDB) { dbs = dbd.getDBStrings(); metaData.setDBStrings(dbs); dbd.dispose(); } } else { connectToDB = true; } } // run second, on a different thread: public void run() { if (connectToDB) { DBStrings dbs = metaData.getDBStrings(); try { /*boolean okToExport = null!=metaData.getFile(); if (!okToExport) { okToExport = false; int response = JOptionPane.showConfirmDialog(null, "You need to save your database in the disk \n" + "before saving. Save it now?", "Database is not saved", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if(response == JOptionPane.YES_OPTION) { try { saveAction.saveAs(); okToExport = (null!=metaData.getFile()); } catch (Throwable e) { e.printStackTrace(); } } } if (okToExport) {*/ frame.output(Globals.lang("Attempting SQL export...")); DBExporterAndImporterFactory factory = new DBExporterAndImporterFactory(); DBExporter exporter = factory.getExporter(dbs.getServerType()); exporter.exportDatabaseToDBMS(database, metaData, null, dbs, frame); dbs.isConfigValid(true); //} //else // errorMessage = "Database was not exported. Your database must be saved \nbefore exporting to a SQL database"; } catch (Exception ex) { String preamble = "Could not export to SQL database for the following reason:"; errorMessage = SQLUtil.getExceptionMessage(ex); ex.printStackTrace(); dbs.isConfigValid(false); JOptionPane.showMessageDialog(frame, Globals.lang(preamble) + "\n" +errorMessage, Globals.lang("Export to SQL database"), JOptionPane.ERROR_MESSAGE); } metaData.setDBStrings(dbs); } } // run third, on EDT: public void update() { // if no error, report success if (errorMessage == null) { if (connectToDB) { frame.output(Globals.lang("%0 export successful")); } } // show an error dialog if an error occurred else { String preamble = "Could not export to SQL database for the following reason:"; frame.output(Globals.lang(preamble) + " " + errorMessage); JOptionPane.showMessageDialog(frame, Globals.lang(preamble) + "\n" + errorMessage, Globals.lang("Export to SQL database"), JOptionPane.ERROR_MESSAGE); errorMessage = null; } } }); actions.put(FindUnlinkedFilesDialog.ACTION_COMMAND, new BaseAction() { @Override public void action() throws Throwable { FindUnlinkedFilesDialog dialog = new FindUnlinkedFilesDialog(frame, frame, BasePanel.this); Util.placeDialog(dialog, frame); dialog.setVisible(true); } }); // The action for auto-generating keys. actions.put("makeKey", new AbstractWorker() { //int[] rows; List<BibtexEntry> entries; int numSelected; boolean cancelled = false; // Run first, in EDT: public void init() { entries = new ArrayList<BibtexEntry>(Arrays.asList(getSelectedEntries())); //rows = entryTable.getSelectedRows() ; numSelected = entries.size(); if (entries.size() == 0) { // None selected. Inform the user to select entries first. JOptionPane.showMessageDialog(frame, Globals.lang("First select the entries you want keys to be generated for."), Globals.lang("Autogenerate BibTeX key"), JOptionPane.INFORMATION_MESSAGE); return ; } frame.block(); output(Globals.lang("Generating BibTeX key for")+" "+ numSelected+" "+(numSelected>1 ? Globals.lang("entries") : Globals.lang("entry"))+"..."); } // Run second, on a different thread: public void run() { BibtexEntry bes = null ; NamedCompound ce = new NamedCompound(Globals.lang("autogenerate keys")); // First check if any entries have keys set already. If so, possibly remove // them from consideration, or warn about overwriting keys. loop: for (Iterator<BibtexEntry> i=entries.iterator(); i.hasNext();) { bes = i.next(); if (bes.getField(BibtexFields.KEY_FIELD) != null) { if (Globals.prefs.getBoolean("avoidOverwritingKey")) // Remove the entry, because its key is already set: i.remove(); else if (Globals.prefs.getBoolean("warnBeforeOverwritingKey")) { // Ask if the user wants to cancel the operation: CheckBoxMessage cbm = new CheckBoxMessage(Globals.lang("One or more keys will be overwritten. Continue?"), Globals.lang("Disable this confirmation dialog"), false); int answer = JOptionPane.showConfirmDialog(frame, cbm, Globals.lang("Overwrite keys"), JOptionPane.YES_NO_OPTION); if (cbm.isSelected()) Globals.prefs.putBoolean("warnBeforeOverwritingKey", false); if (answer == JOptionPane.NO_OPTION) { // Ok, break off the operation. cancelled = true; return; } // No need to check more entries, because the user has already confirmed // that it's ok to overwrite keys: break loop; } } } HashMap<BibtexEntry, Object> oldvals = new HashMap<BibtexEntry, Object>(); // Iterate again, removing already set keys. This is skipped if overwriting // is disabled, since all entries with keys set will have been removed. if (!Globals.prefs.getBoolean("avoidOverwritingKey")) for (Iterator<BibtexEntry> i=entries.iterator(); i.hasNext();) { bes = i.next(); // Store the old value: oldvals.put(bes, bes.getField(BibtexFields.KEY_FIELD)); database.setCiteKeyForEntry(bes.getId(), null); } // Finally, set the new keys: for (Iterator<BibtexEntry> i=entries.iterator(); i.hasNext();) { bes = i.next(); bes = LabelPatternUtil.makeLabel(metaData, database, bes); ce.addEdit(new UndoableKeyChange (database, bes.getId(), (String)oldvals.get(bes), bes.getField(BibtexFields.KEY_FIELD))); } ce.end(); undoManager.addEdit(ce); } // Run third, on EDT: public void update() { database.setFollowCrossrefs(true); if (cancelled) { frame.unblock(); return; } markBaseChanged() ; numSelected = entries.size(); //////////////////////////////////////////////////////////////////////////////// // Prevent selection loss for autogenerated BibTeX-Keys //////////////////////////////////////////////////////////////////////////////// for (Iterator<BibtexEntry> i=entries.iterator(); i.hasNext();) { final BibtexEntry bibEntry = i.next(); SwingUtilities.invokeLater(new Runnable() { public void run() { final int row = mainTable.findEntry( bibEntry ); if (row >= 0 && mainTable.getSelectedRowCount() < entries.size()) mainTable.addRowSelectionInterval(row, row); } }); } //////////////////////////////////////////////////////////////////////////////// output(Globals.lang("Generated BibTeX key for")+" "+ numSelected+" "+(numSelected!=1 ? Globals.lang("entries") : Globals.lang("entry"))); frame.unblock(); } }); // The action for cleaning up entry. actions.put("Cleanup", cleanUpAction); actions.put("search", new BaseAction() { public void action() { //sidePaneManager.togglePanel("search"); sidePaneManager.show("search"); //boolean on = sidePaneManager.isPanelVisible("search"); frame.searchToggle.setSelected(true); if (true) frame.getSearchManager().startSearch(); } }); actions.put("toggleSearch", new BaseAction() { public void action() { //sidePaneManager.togglePanel("search"); sidePaneManager.toggle("search"); boolean on = sidePaneManager.isComponentVisible("search"); frame.searchToggle.setSelected(on); if (on) frame.getSearchManager().startSearch(); } }); actions.put("incSearch", new BaseAction() { public void action() { sidePaneManager.show("search"); frame.searchToggle.setSelected(true); frame.getSearchManager().startIncrementalSearch(); } }); // The action for copying the selected entry's key. actions.put("copyKey", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) { storeCurrentEdit(); //String[] keys = new String[bes.length]; Vector<Object> keys = new Vector<Object>(); // Collect all non-null keys. for (int i=0; i<bes.length; i++) if (bes[i].getField(BibtexFields.KEY_FIELD) != null) keys.add(bes[i].getField(BibtexFields.KEY_FIELD)); if (keys.size() == 0) { output("None of the selected entries have BibTeX keys."); return; } StringBuffer sb = new StringBuffer((String)keys.elementAt(0)); for (int i=1; i<keys.size(); i++) { sb.append(','); sb.append((String)keys.elementAt(i)); } StringSelection ss = new StringSelection(sb.toString()); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(ss, BasePanel.this); if (keys.size() == bes.length) // All entries had keys. output(Globals.lang((bes.length > 1) ? "Copied keys" : "Copied key")+"."); else output(Globals.lang("Warning")+": "+(bes.length-keys.size()) +" "+Globals.lang("out of")+" "+bes.length+" "+ Globals.lang("entries have undefined BibTeX key")+"."); } } }); // The action for copying a cite for the selected entry. actions.put("copyCiteKey", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) { storeCurrentEdit(); //String[] keys = new String[bes.length]; Vector<Object> keys = new Vector<Object>(); // Collect all non-null keys. for (int i=0; i<bes.length; i++) if (bes[i].getField(BibtexFields.KEY_FIELD) != null) keys.add(bes[i].getField(BibtexFields.KEY_FIELD)); if (keys.size() == 0) { output("None of the selected entries have BibTeX keys."); return; } StringBuffer sb = new StringBuffer((String)keys.elementAt(0)); for (int i=1; i<keys.size(); i++) { sb.append(','); sb.append((String)keys.elementAt(i)); } StringSelection ss = new StringSelection ("\\cite{"+sb.toString()+"}"); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(ss, BasePanel.this); if (keys.size() == bes.length) // All entries had keys. output(bes.length > 1 ? Globals.lang("Copied keys") : Globals.lang("Copied key")+"."); else output(Globals.lang("Warning")+": "+(bes.length-keys.size()) +" "+Globals.lang("out of")+" "+bes.length+" "+ Globals.lang("entries have undefined BibTeX key")+"."); } } }); // The action for copying the BibTeX key and the title for the first selected entry actions.put("copyKeyAndTitle", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) { storeCurrentEdit(); // OK: in a future version, this string should be configurable to allow arbitrary exports StringReader sr = new StringReader("\\bibtexkey - \\begin{title}\\format[RemoveBrackets]{\\title}\\end{title}\n"); Layout layout; try { layout = new LayoutHelper(sr).getLayoutFromText(Globals.FORMATTER_PACKAGE); } catch (Exception e) { e.printStackTrace(); return; } StringBuffer sb = new StringBuffer(); int copied = 0; // Collect all non-null keys. for (int i=0; i<bes.length; i++) if (bes[i].getField(BibtexFields.KEY_FIELD) != null) { copied++; sb.append(layout.doLayout(bes[i], database)); } if (copied==0) { output("None of the selected entries have BibTeX keys."); return; } StringSelection ss = new StringSelection(sb.toString()); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(ss, BasePanel.this); if (copied == bes.length) // All entries had keys. output(Globals.lang((bes.length > 1) ? "Copied keys" : "Copied key")+"."); else output(Globals.lang("Warning")+": "+(copied) +" "+Globals.lang("out of")+" "+bes.length+" "+ Globals.lang("entries have undefined BibTeX key")+"."); } } }); actions.put("mergeDatabase", new AppendDatabaseAction(frame, this)); actions.put("openFile", new BaseAction() { public void action() { (new Thread() { public void run() { BibtexEntry[] bes = mainTable.getSelectedEntries(); String field = "ps"; if ((bes != null) && (bes.length == 1)) { FileListEntry entry = null; FileListTableModel tm = new FileListTableModel(); tm.setContent(bes[0].getField("file")); for (int i=0; i< tm.getRowCount(); i++) { FileListEntry flEntry = tm.getEntry(i); if (flEntry.getType().getName().toLowerCase().equals("pdf") || flEntry.getType().getName().toLowerCase().equals("ps")) { entry = flEntry; break; } } if (entry != null) { try { Util.openExternalFileAnyFormat(metaData, entry.getLink(), entry.getType()); output(Globals.lang("External viewer called") + "."); } catch (IOException e) { output(Globals.lang("Could not open link")); e.printStackTrace(); } return; } // If we didn't find anything in the "file" field, check "ps" and "pdf" fields: Object link = bes[0].getField("ps"); if (bes[0].getField("pdf") != null) { link = bes[0].getField("pdf"); field = "pdf"; } String filepath = null; if (link != null) { filepath = link.toString(); } else { if (Globals.prefs.getBoolean("runAutomaticFileSearch")) { /* The search can lead to an unexpected 100% CPU usage which is perceived as a bug, if the search incidentally starts at a directory with lots of stuff below. It is now disabled by default. */ // see if we can fall back to a filename based on the bibtex key final Collection<BibtexEntry> entries = new ArrayList<BibtexEntry>(); entries.add(bes[0]); ExternalFileType[] types = Globals.prefs.getExternalFileTypeSelection(); ArrayList<File> dirs = new ArrayList<File>(); if (metaData.getFileDirectory(GUIGlobals.FILE_FIELD).length > 0) { String[] mdDirs = metaData.getFileDirectory(GUIGlobals.FILE_FIELD); for (int i = 0; i < mdDirs.length; i++) { dirs.add(new File(mdDirs[i])); } } Collection<String> extensions = new ArrayList<String>(); for (int i = 0; i < types.length; i++) { final ExternalFileType type = types[i]; extensions.add(type.getExtension()); } // Run the search operation: Map<BibtexEntry, List<File>> result; if (Globals.prefs.getBoolean(JabRefPreferences.USE_REG_EXP_SEARCH_KEY)) { String regExp = Globals.prefs.get(JabRefPreferences.REG_EXP_SEARCH_EXPRESSION_KEY); result = RegExpFileSearch.findFilesForSet(entries, extensions, dirs, regExp); } else result = Util.findAssociatedFiles(entries, extensions, dirs); if (result.get(bes[0]) != null) { List<File> res = result.get(bes[0]); if (res.size() > 0) { filepath = res.get(0).getPath(); int index = filepath.lastIndexOf('.'); if ((index >= 0) && (index < filepath.length()-1)) { String extension = filepath.substring(index+1); ExternalFileType type = Globals.prefs.getExternalFileTypeByExt(extension); if (type != null) { try { Util.openExternalFileAnyFormat(metaData, filepath, type); output(Globals.lang("External viewer called") + "."); return; } catch (IOException ex) { output(Globals.lang("Error") + ": " + ex.getMessage()); } } } // TODO: add code for opening the file } } /*String basefile; Object key = bes[0].getField(BibtexFields.KEY_FIELD); if (key != null) { basefile = key.toString(); final ExternalFileType[] types = Globals.prefs.getExternalFileTypeSelection(); final String sep = System.getProperty("file.separator"); String dir = metaData.getFileDirectory(GUIGlobals.FILE_FIELD); if ((dir != null) && (dir.length() > 0)) { if (dir.endsWith(sep)) { dir = dir.substring(0, dir.length() - sep.length()); } for (int i = 0; i < types.length; i++) { String found = Util.findPdf(basefile, types[i].getExtension(), dir, new OpenFileFilter("." + types[i].getExtension())); if (found != null) { filepath = dir + sep + found; break; } } } }*/ } } if (filepath != null) { //output(Globals.lang("Calling external viewer...")); try { Util.openExternalViewer(metaData(), filepath, field); output(Globals.lang("External viewer called") + "."); } catch (IOException ex) { output(Globals.lang("Error") + ": " + ex.getMessage()); } } else output(Globals.lang( "No pdf or ps defined, and no file matching Bibtex key found") + "."); } else output(Globals.lang("No entries or multiple entries selected.")); } }).start(); } }); actions.put("addFileLink", new AttachFileAction(this)); actions.put("openExternalFile", new BaseAction() { public void action() { (new Thread() { public void run() { BibtexEntry[] bes = mainTable.getSelectedEntries(); String field = GUIGlobals.FILE_FIELD; if ((bes != null) && (bes.length == 1)) { Object link = bes[0].getField(field); if (link == null) { runCommand("openFile"); // Fall back on PDF/PS fields??? return; } FileListTableModel tableModel = new FileListTableModel(); tableModel.setContent((String)link); if (tableModel.getRowCount() == 0) { runCommand("openFile"); // Fall back on PDF/PS fields??? return; } FileListEntry flEntry = tableModel.getEntry(0); ExternalFileMenuItem item = new ExternalFileMenuItem (frame(), bes[0], "", flEntry.getLink(), flEntry.getType().getIcon(), metaData(), flEntry.getType()); item.openLink(); } else output(Globals.lang("No entries or multiple entries selected.")); } }).start(); } }); actions.put("openUrl", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); String field = "doi"; if ((bes != null) && (bes.length == 1)) { Object link = bes[0].getField("doi"); if (bes[0].getField("url") != null) { link = bes[0].getField("url"); field = "url"; } if (link != null) { //output(Globals.lang("Calling external viewer...")); try { Util.openExternalViewer(metaData(), link.toString(), field); output(Globals.lang("External viewer called")+"."); } catch (IOException ex) { output(Globals.lang("Error") + ": " + ex.getMessage()); } } else { // No URL or DOI found in the "url" and "doi" fields. // Look for web links in the "file" field as a fallback: FileListEntry entry = null; FileListTableModel tm = new FileListTableModel(); tm.setContent(bes[0].getField("file")); for (int i=0; i< tm.getRowCount(); i++) { FileListEntry flEntry = tm.getEntry(i); if (flEntry.getType().getName().toLowerCase().equals("url") || flEntry.getType().getName().toLowerCase().equals("ps")) { entry = flEntry; break; } } if (entry != null) { try { Util.openExternalFileAnyFormat(metaData, entry.getLink(), entry.getType()); output(Globals.lang("External viewer called") + "."); } catch (IOException e) { output(Globals.lang("Could not open link")); e.printStackTrace(); } return; } else output(Globals.lang("No url defined")+"."); } } else output(Globals.lang("No entries or multiple entries selected.")); } }); actions.put("openSpires", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length == 1)) { Object link = null; if (bes[0].getField("eprint") != null) link = SPIRESFetcher.constructUrlFromEprint(bes[0].getField("eprint").toString()); else if (bes[0].getField("slaccitation") != null) link = SPIRESFetcher.constructUrlFromSlaccitation(bes[0].getField("slaccitation").toString()); if (link != null) { //output(Globals.lang("Calling external viewer...")); try { Util.openExternalViewer(metaData(), link.toString(), "url"); output(Globals.lang("External viewer called")+"."); } catch (IOException ex) { output(Globals.lang("Error") + ": " + ex.getMessage()); } } else output(Globals.lang("No url defined")+"."); } else output(Globals.lang("No entries or multiple entries selected.")); } }); /* * It looks like this action was not being supported for SPIRES anyway * so we don't bother to implement it. actions.put("openInspire", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length == 1)) { Object link = null; if (bes[0].getField("eprint") != null) link = INSPIREFetcher.constructUrlFromEprint(bes[0].getField("eprint").toString()); else if (bes[0].getField("slaccitation") != null) link = INSPIREFetcher.constructUrlFromSlaccitation(bes[0].getField("slaccitation").toString()); if (link != null) { //output(Globals.lang("Calling external viewer...")); try { Util.openExternalViewer(metaData(), link.toString(), "url"); output(Globals.lang("External viewer called")+"."); } catch (IOException ex) { output(Globals.lang("Error") + ": " + ex.getMessage()); } } else output(Globals.lang("No url defined")+"."); } else output(Globals.lang("No entries or multiple entries selected.")); } }); */ actions.put("replaceAll", new BaseAction() { public void action() { ReplaceStringDialog rsd = new ReplaceStringDialog(frame); rsd.setVisible(true); if (!rsd.okPressed()) return; int counter = 0; NamedCompound ce = new NamedCompound(Globals.lang("Replace string")); if (!rsd.selOnly()) { for (BibtexEntry entry : database.getEntries()){ counter += rsd.replace(entry, ce); } } else { BibtexEntry[] bes = mainTable.getSelectedEntries(); for (int i=0; i<bes.length; i++) counter += rsd.replace(bes[i], ce); } output(Globals.lang("Replaced")+" "+counter+" "+ Globals.lang(counter==1?"occurence":"occurences")+"."); if (counter > 0) { ce.end(); undoManager.addEdit(ce); markBaseChanged(); } } }); actions.put("dupliCheck", new BaseAction() { public void action() { DuplicateSearch ds = new DuplicateSearch(BasePanel.this); ds.start(); } }); /*actions.put("strictDupliCheck", new BaseAction() { public void action() { StrictDuplicateSearch ds = new StrictDuplicateSearch(BasePanel.this); ds.start(); } });*/ actions.put("plainTextImport", new BaseAction() { public void action() { // get Type of new entry EntryTypeDialog etd = new EntryTypeDialog(frame); Util.placeDialog(etd, BasePanel.this); etd.setVisible(true); BibtexEntryType tp = etd.getChoice(); if (tp == null) return; String id = Util.createNeutralId(); BibtexEntry bibEntry = new BibtexEntry(id, tp) ; TextInputDialog tidialog = new TextInputDialog(frame, BasePanel.this, "import", true, bibEntry) ; Util.placeDialog(tidialog, BasePanel.this); tidialog.setVisible(true); if (tidialog.okPressed()) { Util.setAutomaticFields(Arrays.asList(new BibtexEntry[] {bibEntry}), false, false, false); insertEntry(bibEntry) ; } } }); // The action starts the "import from plain text" dialog /*actions.put("importPlainText", new BaseAction() { public void action() { BibtexEntry bibEntry = null ; // try to get the first marked entry BibtexEntry[] bes = entryTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) bibEntry = bes[0] ; if (bibEntry != null) { // Create an UndoableInsertEntry object. undoManager.addEdit(new UndoableInsertEntry(database, bibEntry, BasePanel.this)); TextInputDialog tidialog = new TextInputDialog(frame, BasePanel.this, "import", true, bibEntry) ; Util.placeDialog(tidialog, BasePanel.this); tidialog.setVisible(true); if (tidialog.okPressed()) { output(Globals.lang("changed ")+" '" +bibEntry.getType().getName().toLowerCase()+"' " +Globals.lang("entry")+"."); refreshTable(); int row = tableModel.getNumberFromName(bibEntry.getId()); entryTable.clearSelection(); entryTable.scrollTo(row); markBaseChanged(); // The database just changed. if (Globals.prefs.getBoolean("autoOpenForm")) { showEntry(bibEntry); } } } } }); */ actions.put("markEntries", new AbstractWorker() { private int besLength = -1; public void run() { NamedCompound ce = new NamedCompound(Globals.lang("Mark entries")); BibtexEntry[] bes = mainTable.getSelectedEntries(); besLength = bes.length; for (int i=0; i<bes.length; i++) { Util.markEntry(bes[i], 1, true, ce); } ce.end(); undoManager.addEdit(ce); } public void update() { markBaseChanged(); output(Globals.lang("Marked selected")+" "+Globals.lang(besLength>0?"entry":"entries")); } }); actions.put("unmarkEntries", new BaseAction() { public void action() { try { NamedCompound ce = new NamedCompound(Globals.lang("Unmark entries")); BibtexEntry[] bes = mainTable.getSelectedEntries(); if (bes == null) return; for (int i=0; i<bes.length; i++) { Util.unmarkEntry(bes[i], false, database, ce); } ce.end(); undoManager.addEdit(ce); markBaseChanged(); output(Globals.lang("Unmarked selected")+" "+Globals.lang(bes.length>0?"entry":"entries")); } catch (Throwable ex) { ex.printStackTrace(); } } }); actions.put("unmarkAll", new BaseAction() { public void action() { NamedCompound ce = new NamedCompound(Globals.lang("Unmark all")); for (BibtexEntry be : database.getEntries()){ Util.unmarkEntry(be, false, database, ce); } ce.end(); undoManager.addEdit(ce); markBaseChanged(); } }); actions.put(Relevance.getInstance().getValues().get(0).getActionName(), new SpecialFieldAction(frame, Relevance.getInstance(), Relevance.getInstance().getValues().get(0).getFieldValue(), true, Globals.lang("Marked entries as relevant"), "Marked %0 entries as relevant")); actions.put(Quality.getInstance().getValues().get(0).getActionName(), new SpecialFieldAction(frame, Quality.getInstance(), Quality.getInstance().getValues().get(0).getFieldValue(), true, Globals.lang("Marked entries' quality as good"), "Set quality of %0 entries to good")); for (SpecialFieldValue prio: Priority.getInstance().getValues()) { actions.put(prio.getActionName(), prio.getAction(this.frame)); } for (SpecialFieldValue prio: Rank.getInstance().getValues()) { actions.put(prio.getActionName(), prio.getAction(this.frame)); } actions.put("togglePreview", new BaseAction() { public void action() { boolean enabled = !Globals.prefs.getBoolean("previewEnabled"); Globals.prefs.putBoolean("previewEnabled", enabled); frame.setPreviewActive(enabled); frame.previewToggle.setSelected(enabled); } }); actions.put("toggleHighlightGroupsMatchingAny", new BaseAction() { public void action() { boolean enabled = !Globals.prefs.getBoolean("highlightGroupsMatchingAny"); Globals.prefs.putBoolean("highlightGroupsMatchingAny", enabled); frame.highlightAny.setSelected(enabled); if (enabled) { frame.highlightAll.setSelected(false); Globals.prefs.putBoolean("highlightGroupsMatchingAll", false); } // ping the listener so it updates: groupsHighlightListener.listChanged(null); } }); actions.put("toggleHighlightGroupsMatchingAll", new BaseAction() { public void action() { boolean enabled = !Globals.prefs.getBoolean("highlightGroupsMatchingAll"); Globals.prefs.putBoolean("highlightGroupsMatchingAll", enabled); frame.highlightAll.setSelected(enabled); if (enabled) { frame.highlightAny.setSelected(false); Globals.prefs.putBoolean("highlightGroupsMatchingAny", false); } // ping the listener so it updates: groupsHighlightListener.listChanged(null); } }); actions.put("switchPreview", new BaseAction() { public void action() { selectionListener.switchPreview(); } }); actions.put("manageSelectors", new BaseAction() { public void action() { ContentSelectorDialog2 csd = new ContentSelectorDialog2 (frame, frame, BasePanel.this, false, metaData, null); Util.placeDialog(csd, frame); csd.setVisible(true); } }); actions.put("exportToClipboard", new ExportToClipboardAction(frame, database())); actions.put("sendAsEmail", new SendAsEMailAction(frame)); actions.put("writeXMP", new WriteXMPAction(this)); actions.put("abbreviateIso", new AbbreviateAction(this, true)); actions.put("abbreviateMedline", new AbbreviateAction(this, false)); actions.put("unabbreviate", new UnabbreviateAction(this)); actions.put("autoSetPdf", new AutoSetExternalFileForEntries(this, "pdf")); actions.put("autoSetPs", new AutoSetExternalFileForEntries(this, "ps")); actions.put("autoSetFile", new SynchronizeFileField(this)); actions.put("back", new BaseAction() { public void action() throws Throwable { back(); } }); actions.put("forward", new BaseAction() { public void action() throws Throwable { forward(); } }); actions.put("resolveDuplicateKeys", new SearchFixDuplicateLabels(this)); //actions.put("downloadFullText", new FindFullTextAction(this)); } /** * This method is called from JabRefFrame is a database specific * action is requested by the user. Runs the command if it is * defined, or prints an error message to the standard error * stream. * * @param _command The name of the command to run. */ public void runCommand(String _command) { final String command = _command; //(new Thread() { // public void run() { if (actions.get(command) == null) Util.pr("No action defined for'" + command + "'"); else { Object o = actions.get(command); try { if (o instanceof BaseAction) ((BaseAction)o).action(); else { // This part uses Spin's features: Worker wrk = ((AbstractWorker)o).getWorker(); // The Worker returned by getWorker() has been wrapped // by Spin.off(), which makes its methods be run in // a different thread from the EDT. CallBack clb = ((AbstractWorker)o).getCallBack(); ((AbstractWorker)o).init(); // This method runs in this same thread, the EDT. // Useful for initial GUI actions, like printing a message. // The CallBack returned by getCallBack() has been wrapped // by Spin.over(), which makes its methods be run on // the EDT. wrk.run(); // Runs the potentially time-consuming action // without freezing the GUI. The magic is that THIS line // of execution will not continue until run() is finished. clb.update(); // Runs the update() method on the EDT. } } catch (Throwable ex) { // If the action has blocked the JabRefFrame before crashing, we need to unblock it. // The call to unblock will simply hide the glasspane, so there is no harm in calling // it even if the frame hasn't been blocked. frame.unblock(); ex.printStackTrace(); } } // } //}).start(); } private boolean saveDatabase(File file, boolean selectedOnly, String encoding) throws SaveException { SaveSession session; frame.block(); try { if (!selectedOnly) session = FileActions.saveDatabase(database, metaData, file, Globals.prefs, false, false, encoding, false); else session = FileActions.savePartOfDatabase(database, metaData, file, Globals.prefs, mainTable.getSelectedEntries(), encoding); } catch (UnsupportedCharsetException ex2) { JOptionPane.showMessageDialog(frame, Globals.lang("Could not save file. " +"Character encoding '%0' is not supported.", encoding), Globals.lang("Save database"), JOptionPane.ERROR_MESSAGE); throw new SaveException("rt"); } catch (SaveException ex) { if (ex.specificEntry()) { // Error occured during processing of // be. Highlight it: int row = mainTable.findEntry(ex.getEntry()), topShow = Math.max(0, row-3); mainTable.setRowSelectionInterval(row, row); mainTable.scrollTo(topShow); showEntry(ex.getEntry()); } else ex.printStackTrace(); JOptionPane.showMessageDialog (frame, Globals.lang("Could not save file") +".\n"+ex.getMessage(), Globals.lang("Save database"), JOptionPane.ERROR_MESSAGE); throw new SaveException("rt"); } finally { frame.unblock(); } boolean commit = true; if (!session.getWriter().couldEncodeAll()) { DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("left:pref, 4dlu, fill:pref", "")); JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters()); ta.setEditable(false); builder.append(Globals.lang("The chosen encoding '%0' could not encode the following characters: ", session.getEncoding())); builder.append(ta); builder.append(Globals.lang("What do you want to do?")); String tryDiff = Globals.lang("Try different encoding"); int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), Globals.lang("Save database"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] {Globals.lang("Save"), tryDiff, Globals.lang("Cancel")}, tryDiff); if (answer == JOptionPane.NO_OPTION) { // The user wants to use another encoding. Object choice = JOptionPane.showInputDialog(frame, Globals.lang("Select encoding"), Globals.lang("Save database"), JOptionPane.QUESTION_MESSAGE, null, Globals.ENCODINGS, encoding); if (choice != null) { String newEncoding = (String)choice; return saveDatabase(file, selectedOnly, newEncoding); } else commit = false; } else if (answer == JOptionPane.CANCEL_OPTION) commit = false; } try { if (commit) { session.commit(); this.encoding = encoding; // Make sure to remember which encoding we used. } else session.cancel(); } catch (IOException e) { e.printStackTrace(); } return commit; } /** * This method is called from JabRefFrame when the user wants to * create a new entry. If the argument is null, the user is * prompted for an entry type. * * @param type The type of the entry to create. * @return The newly created BibtexEntry or null the operation was canceled by the user. */ public BibtexEntry newEntry(BibtexEntryType type) { if (type == null) { // Find out what type is wanted. EntryTypeDialog etd = new EntryTypeDialog(frame); // We want to center the dialog, to make it look nicer. Util.placeDialog(etd, frame); etd.setVisible(true); type = etd.getChoice(); } if (type != null) { // Only if the dialog was not cancelled. String id = Util.createNeutralId(); final BibtexEntry be = new BibtexEntry(id, type); try { database.insertEntry(be); // Set owner/timestamp if options are enabled: ArrayList<BibtexEntry> list = new ArrayList<BibtexEntry>(); list.add(be); Util.setAutomaticFields(list, true, true, false); // Create an UndoableInsertEntry object. undoManager.addEdit(new UndoableInsertEntry(database, be, BasePanel.this)); output(Globals.lang("Added new")+" '"+type.getName().toLowerCase()+"' " +Globals.lang("entry")+"."); // We are going to select the new entry. Before that, make sure that we are in // show-entry mode. If we aren't already in that mode, enter the WILL_SHOW_EDITOR // mode which makes sure the selection will trigger display of the entry editor // and adjustment of the splitter. if (mode != SHOWING_EDITOR) { mode = WILL_SHOW_EDITOR; } int row = mainTable.findEntry(be); if (row >= 0) highlightEntry(be); // Selects the entry. The selection listener will open the editor. else { // The entry is not visible in the table, perhaps due to a filtering search // or group selection. Show the entry editor anyway: showEntry(be); } markBaseChanged(); // The database just changed. new FocusRequester(getEntryEditor(be)); //Add the new entry to the group(s) selected in the Group Panel addToSelectedGroup(be); // Set Self-Created entries to have a high quality be.setField("quality", "1"); return be; } catch (KeyCollisionException ex) { Util.pr(ex.getMessage()); } } return null; } /** * This method is called to add a new entry to a group (or a set of groups) * in case the Group View is selected and one or more groups are marked * @param bibEntry The new entry. */ private void addToSelectedGroup(final BibtexEntry bibEntry) { if (Globals.prefs.getBoolean("autoAssignGroup")){ if (frame.groupToggle.isSelected()){ BibtexEntry[] entries = {bibEntry}; TreePath[] selection = frame.groupSelector.getGroupsTree().getSelectionPaths(); if (selection != null) { // it is possible that the user selected nothing. Therefore, checked for "!= null" for (TreePath tree : selection){ ((GroupTreeNode)(tree.getLastPathComponent())).addToGroup(entries); } } this.updateEntryEditorIfShowing(); this.getGroupSelector().valueChanged(null); } } } /** * This method is called from JabRefFrame when the user wants to * create a new entry. * @param bibEntry The new entry. */ public void insertEntry(BibtexEntry bibEntry) { if (bibEntry != null) { try { database.insertEntry(bibEntry) ; if (Globals.prefs.getBoolean("useOwner")) // Set owner field to default value Util.setAutomaticFields(bibEntry, true, true); // Create an UndoableInsertEntry object. undoManager.addEdit(new UndoableInsertEntry(database, bibEntry, BasePanel.this)); output(Globals.lang("Added new")+" '" +bibEntry.getType().getName().toLowerCase()+"' " +Globals.lang("entry")+"."); markBaseChanged(); // The database just changed. if (Globals.prefs.getBoolean("autoOpenForm")) { selectionListener.editSignalled(bibEntry); } highlightEntry(bibEntry); } catch (KeyCollisionException ex) { Util.pr(ex.getMessage()); } } } public void updateTableFont() { mainTable.updateFont(); } public void createMainTable() { //Comparator comp = new FieldComparator("author"); GlazedEntrySorter eventList = new GlazedEntrySorter(database.getEntryMap()); // Must initialize sort columns somehow: database.addDatabaseChangeListener(eventList); database.addDatabaseChangeListener(SpecialFieldDatabaseChangeListener.getInstance()); groupFilterList = new FilterList<BibtexEntry>(eventList.getTheList(), NoSearchMatcher.INSTANCE); searchFilterList = new FilterList<BibtexEntry>(groupFilterList, NoSearchMatcher.INSTANCE); //final SortedList sortedList = new SortedList(searchFilterList, null); tableFormat = new MainTableFormat(this); tableFormat.updateTableFormat(); //EventTableModel tableModel = new EventTableModel(sortedList, tableFormat); mainTable = new MainTable(tableFormat, searchFilterList, frame, this); selectionListener = new MainTableSelectionListener(this, mainTable); mainTable.updateFont(); mainTable.addSelectionListener(selectionListener); mainTable.addMouseListener(selectionListener); mainTable.addKeyListener(selectionListener); mainTable.addFocusListener(selectionListener); // Add the listener that will take care of highlighting groups as the selection changes: groupsHighlightListener = new ListEventListener<BibtexEntry>() { public void listChanged(ListEvent<BibtexEntry> listEvent) { if (Globals.prefs.getBoolean("highlightGroupsMatchingAny")) getGroupSelector().showMatchingGroups( mainTable.getSelectedEntries(), false); else if (Globals.prefs.getBoolean("highlightGroupsMatchingAll")) getGroupSelector().showMatchingGroups( mainTable.getSelectedEntries(), true); else // no highlight getGroupSelector().showMatchingGroups(null, true); } }; mainTable.addSelectionListener(groupsHighlightListener); mainTable.getActionMap().put("cut", new AbstractAction() { public void actionPerformed(ActionEvent e) { try { runCommand("cut"); } catch (Throwable ex) { ex.printStackTrace(); } } }); mainTable.getActionMap().put("copy", new AbstractAction() { public void actionPerformed(ActionEvent e) { try { runCommand("copy"); } catch (Throwable ex) { ex.printStackTrace(); } } }); mainTable.getActionMap().put("paste", new AbstractAction() { public void actionPerformed(ActionEvent e) { try { runCommand("paste"); } catch (Throwable ex) { ex.printStackTrace(); } } }); mainTable.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { final int keyCode = e.getKeyCode(); final TreePath path = frame.groupSelector.getSelectionPath(); final GroupTreeNode node = path == null ? null : (GroupTreeNode) path.getLastPathComponent(); if (e.isControlDown()) { switch (keyCode) { // The up/down/left/rightkeystrokes are displayed in the // GroupSelector's popup menu, so if they are to be changed, // edit GroupSelector.java accordingly! case KeyEvent.VK_UP: e.consume(); if (node != null) frame.groupSelector.moveNodeUp(node, true); break; case KeyEvent.VK_DOWN: e.consume(); if (node != null) frame.groupSelector.moveNodeDown(node, true); break; case KeyEvent.VK_LEFT: e.consume(); if (node != null) frame.groupSelector.moveNodeLeft(node, true); break; case KeyEvent.VK_RIGHT: e.consume(); if (node != null) frame.groupSelector.moveNodeRight(node, true); break; case KeyEvent.VK_PAGE_DOWN: frame.nextTab.actionPerformed(null); e.consume(); break; case KeyEvent.VK_PAGE_UP: frame.prevTab.actionPerformed(null); e.consume(); break; } } else if (keyCode == KeyEvent.VK_ENTER){ e.consume(); try { runCommand("edit"); } catch (Throwable ex) { ex.printStackTrace(); } } } }); } public void setupMainPanel() { //System.out.println("setupMainPanel"); //splitPane = new com.jgoodies.uif_lite.component.UIFSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane.setDividerSize(GUIGlobals.SPLIT_PANE_DIVIDER_SIZE); // We replace the default FocusTraversalPolicy with a subclass // that only allows FieldEditor components to gain keyboard focus, // if there is an entry editor open. /*splitPane.setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() { protected boolean accept(Component c) { Util.pr("jaa"); if (showing == null) return super.accept(c); else return (super.accept(c) && (c instanceof FieldEditor)); } });*/ createMainTable(); for (EntryEditor ee : entryEditors.values()) { ee.validateAllFields(); } splitPane.setTopComponent(mainTable.getPane()); //setupTable(); // If an entry is currently being shown, make sure it stays shown, // otherwise set the bottom component to null. if (mode == SHOWING_PREVIEW) { mode = SHOWING_NOTHING; int row = mainTable.findEntry(currentPreview.entry); if (row >= 0) mainTable.setRowSelectionInterval(row, row); } else if (mode == SHOWING_EDITOR) { mode = SHOWING_NOTHING; /*int row = mainTable.findEntry(currentEditor.entry); if (row >= 0) mainTable.setRowSelectionInterval(row, row); */ //showEntryEditor(currentEditor); } else splitPane.setBottomComponent(null); setLayout(new BorderLayout()); removeAll(); add(splitPane, BorderLayout.CENTER); // Set up name autocompleter for search: instantiateSearchAutoCompleter(); // Set up AutoCompleters for this panel: if (Globals.prefs.getBoolean("autoComplete")) { instantiateAutoCompleters(); } splitPane.revalidate(); revalidate(); repaint(); } public void updateSearchManager() { frame.getSearchManager().setAutoCompleteListener(searchCompleteListener); } public HashMap<String, AbstractAutoCompleter> getAutoCompleters() { return autoCompleters; } public AbstractAutoCompleter getAutoCompleter(String fieldName) { return autoCompleters.get(fieldName); } private void instantiateSearchAutoCompleter() { //if (!Globals.prefs.getBoolean("searchAutoComplete")) // return; searchCompleter = new NameFieldAutoCompleter(new String[] {"author", "editor"}, true); HashMap<String, AbstractAutoCompleter> hm = new HashMap<String, AbstractAutoCompleter>(); hm.put("x", searchCompleter); for (BibtexEntry entry : database.getEntries()){ Util.updateCompletersForEntry(hm, entry); } searchCompleteListener = new AutoCompleteListener(searchCompleter); searchCompleteListener.setConsumeEnterKey(false); // So you don't have to press Enter twice } private void instantiateAutoCompleters() { autoCompleters.clear(); String[] completeFields = Globals.prefs.getStringArray("autoCompleteFields"); for (int i = 0; i < completeFields.length; i++) { String field = completeFields[i]; AbstractAutoCompleter autoCompleter = AutoCompleterFactory.getFor(field); autoCompleters.put(field, autoCompleter ); } for (BibtexEntry entry : database.getEntries()){ Util.updateCompletersForEntry(autoCompleters, entry); } addJournalListToAutoCompleter(); addContentSelectorValuesToAutoCompleters(); } /** * For all fields with both autocompletion and content selector, add content selector * values to the autocompleter list: */ public void addContentSelectorValuesToAutoCompleters() { for (String field : autoCompleters.keySet()) { AbstractAutoCompleter ac = autoCompleters.get(field); if (metaData.getData(Globals.SELECTOR_META_PREFIX + field) != null) { Vector<String> items = metaData.getData(Globals.SELECTOR_META_PREFIX + field); if (items != null) { Iterator<String> i = items.iterator(); while (i.hasNext()) ac.addWordToIndex(i.next()); } } } } /** * If an autocompleter exists for the "journal" field, add all * journal names in the journal abbreviation list to this autocompleter. */ public void addJournalListToAutoCompleter() { if (autoCompleters.containsKey("journal")) { AbstractAutoCompleter ac = autoCompleters.get("journal"); Set<String> journals = Globals.journalAbbrev.getJournals().keySet(); for (String journal : journals) ac.addWordToIndex(journal); } } /* public void refreshTable() { //System.out.println("hiding="+hidingNonHits+"\tlastHits="+lastSearchHits); // This method is called by EntryTypeForm when a field value is // stored. The table is scheduled for repaint. entryTable.assureNotEditing(); //entryTable.invalidate(); BibtexEntry[] bes = entryTable.getSelectedEntries(); if (hidingNonHits) tableModel.update(lastSearchHits); else tableModel.update(); //tableModel.remap(); if ((bes != null) && (bes.length > 0)) selectEntries(bes, 0); //long toc = System.currentTimeMillis(); // Util.pr("Refresh took: "+(toc-tic)+" ms"); } */ public void updatePreamble() { if (preambleEditor != null) preambleEditor.updatePreamble(); } public void assureStringDialogNotEditing() { if (stringDialog != null) stringDialog.assureNotEditing(); } public void updateStringDialog() { if (stringDialog != null) stringDialog.refreshTable(); } public void updateEntryPreviewToRow(BibtexEntry e) { } public void adjustSplitter() { int mode = getMode(); if (mode == SHOWING_PREVIEW) { splitPane.setDividerLocation(splitPane.getHeight()-Globals.prefs.getInt("previewPanelHeight")); } else { splitPane.setDividerLocation(splitPane.getHeight()-Globals.prefs.getInt("entryEditorHeight")); } } /** * Stores the source view in the entry editor, if one is open, has the source view * selected and the source has been edited. * @return boolean false if there is a validation error in the source panel, true otherwise. */ public boolean entryEditorAllowsChange() { Component c = splitPane.getBottomComponent(); if ((c != null) && (c instanceof EntryEditor)) { return ((EntryEditor)c).lastSourceAccepted(); } else return true; } public void moveFocusToEntryEditor() { Component c = splitPane.getBottomComponent(); if ((c != null) && (c instanceof EntryEditor)) { new FocusRequester(c); } } public boolean isShowingEditor() { return ((splitPane.getBottomComponent() != null) && (splitPane.getBottomComponent() instanceof EntryEditor)); } public void showEntry(final BibtexEntry be) { if (getShowing() == be) { if (splitPane.getBottomComponent() == null) { // This is the special occasion when showing is set to an // entry, but no entry editor is in fact shown. This happens // after Preferences dialog is closed, and it means that we // must make sure the same entry is shown again. We do this by // setting showing to null, and recursively calling this method. newEntryShowing(null); showEntry(be); } else { // The correct entry is already being shown. Make sure the editor // is updated. ((EntryEditor)splitPane.getBottomComponent()).updateAllFields(); } return; } EntryEditor form; int divLoc = -1; String visName = null; if (getShowing() != null) { if (isShowingEditor()) { visName = ((EntryEditor) splitPane.getBottomComponent()).getVisiblePanelName(); } } if (getShowing() != null) divLoc = splitPane.getDividerLocation(); if (entryEditors.containsKey(be.getType().getName())) { // We already have an editor for this entry type. form = entryEditors.get ((be.getType().getName())); form.switchTo(be); if (visName != null) form.setVisiblePanel(visName); splitPane.setBottomComponent(form); //highlightEntry(be); } else { // We must instantiate a new editor for this type. form = new EntryEditor(frame, BasePanel.this, be); if (visName != null) form.setVisiblePanel(visName); splitPane.setBottomComponent(form); //highlightEntry(be); entryEditors.put(be.getType().getName(), form); } if (divLoc > 0) { splitPane.setDividerLocation(divLoc); } else splitPane.setDividerLocation (splitPane.getHeight()-Globals.prefs.getInt("entryEditorHeight")); //new FocusRequester(form); //form.requestFocus(); newEntryShowing(be); setEntryEditorEnabled(true); // Make sure it is enabled. } /** * Get an entry editor ready to edit the given entry. If an appropriate editor is already * cached, it will be updated and returned. * @param entry The entry to be edited. * @return A suitable entry editor. */ public EntryEditor getEntryEditor(BibtexEntry entry) { EntryEditor form; if (entryEditors.containsKey(entry.getType().getName())) { EntryEditor visibleNow = currentEditor; // We already have an editor for this entry type. form = entryEditors.get ((entry.getType().getName())); // If the cached editor is not the same as the currently shown one, // make sure the current one stores its current edit: if ((visibleNow != null) && (form != visibleNow)) { visibleNow.storeCurrentEdit(); } form.switchTo(entry); //if (visName != null) // form.setVisiblePanel(visName); } else { // We must instantiate a new editor for this type. First make sure the old one // stores its last edit: storeCurrentEdit(); // Then start the new one: form = new EntryEditor(frame, BasePanel.this, entry); //if (visName != null) // form.setVisiblePanel(visName); entryEditors.put(entry.getType().getName(), form); } return form; } public EntryEditor getCurrentEditor() { return currentEditor; } /** * Sets the given entry editor as the bottom component in the split pane. If an entry editor already * was shown, makes sure that the divider doesn't move. * Updates the mode to SHOWING_EDITOR. * @param editor The entry editor to add. */ public void showEntryEditor(EntryEditor editor) { int oldSplitterLocation = -1; if (mode == SHOWING_EDITOR) Globals.prefs.putInt("entryEditorHeight", splitPane.getHeight() - splitPane.getDividerLocation()); else if (mode == SHOWING_PREVIEW) Globals.prefs.putInt("previewPanelHeight", splitPane.getHeight()-splitPane.getDividerLocation()); mode = SHOWING_EDITOR; currentEditor = editor; splitPane.setBottomComponent(editor); if (editor.getEntry() != getShowing()) newEntryShowing(editor.getEntry()); adjustSplitter(); } /** * Sets the given preview panel as the bottom component in the split panel. * Updates the mode to SHOWING_PREVIEW. * @param preview The preview to show. */ public void showPreview(PreviewPanel preview) { mode = SHOWING_PREVIEW; currentPreview = preview; splitPane.setBottomComponent(preview); } /** * Removes the bottom component. */ public void hideBottomComponent() { mode = SHOWING_NOTHING; splitPane.setBottomComponent(null); } /** * This method selects the given entry, and scrolls it into view in the table. * If an entryEditor is shown, it is given focus afterwards. */ public void highlightEntry(final BibtexEntry be) { //SwingUtilities.invokeLater(new Thread() { // public void run() { final int row = mainTable.findEntry(be); if (row >= 0) { mainTable.setRowSelectionInterval(row, row); //entryTable.setActiveRow(row); mainTable.ensureVisible(row); } // } //}); } /** * This method is called from an EntryEditor when it should be closed. We relay * to the selection listener, which takes care of the rest. * @param editor The entry editor to close. */ public void entryEditorClosing(EntryEditor editor) { // Store divider location for next time: Globals.prefs.putInt("entryEditorHeight", splitPane.getHeight()-splitPane.getDividerLocation()); selectionListener.entryEditorClosing(editor); } /** * This method selects the given enties. * If an entryEditor is shown, it is given focus afterwards. */ /*public void selectEntries(final BibtexEntry[] bes, final int toScrollTo) { SwingUtilities.invokeLater(new Thread() { public void run() { int rowToScrollTo = 0; entryTable.revalidate(); entryTable.clearSelection(); loop: for (int i=0; i<bes.length; i++) { if (bes[i] == null) continue loop; int row = tableModel.getNumberFromName(bes[i].getId()); if (i==toScrollTo) rowToScrollTo = row; if (row >= 0) entryTable.addRowSelectionIntervalQuietly(row, row); } entryTable.ensureVisible(rowToScrollTo); Component comp = splitPane.getBottomComponent(); //if (comp instanceof EntryEditor) // comp.requestFocus(); } }); } */ /** * Closes the entry editor if it is showing the given entry. * * @param be a <code>BibtexEntry</code> value */ public void ensureNotShowing(BibtexEntry be) { if ((mode == SHOWING_EDITOR) && (currentEditor.getEntry() == be)) { selectionListener.entryEditorClosing(currentEditor); } } public void updateEntryEditorIfShowing() { if (mode == SHOWING_EDITOR) { if (currentEditor.getType() != currentEditor.getEntry().getType()) { // The entry has changed type, so we must get a new editor. newEntryShowing(null); EntryEditor newEditor = getEntryEditor(currentEditor.getEntry()); showEntryEditor(newEditor); } else { currentEditor.updateAllFields(); currentEditor.updateSource(); } } } /** * If an entry editor is showing, make sure its currently focused field * stores its changes, if any. */ public void storeCurrentEdit() { if (isShowingEditor()) { EntryEditor editor = (EntryEditor)splitPane.getBottomComponent(); editor.storeCurrentEdit(); } } /** * This method iterates through all existing entry editors in this * BasePanel, telling each to update all its instances of * FieldContentSelector. This is done to ensure that the list of words * in each selector is up-to-date after the user has made changes in * the Manage dialog. */ public void updateAllContentSelectors() { for (Iterator<String> i=entryEditors.keySet().iterator(); i.hasNext();) { EntryEditor ed = entryEditors.get(i.next()); ed.updateAllContentSelectors(); } } public void rebuildAllEntryEditors() { for (Iterator<String> i=entryEditors.keySet().iterator(); i.hasNext();) { EntryEditor ed = entryEditors.get(i.next()); ed.rebuildPanels(); } } public void markBaseChanged() { baseChanged = true; // Put an asterix behind the file name to indicate the // database has changed. String oldTitle = frame.getTabTitle(this); if (!oldTitle.endsWith("*")) { frame.setTabTitle(this, oldTitle+"*", frame.getTabTooltip(this)); frame.setWindowTitle(); } // If the status line states that the base has been saved, we // remove this message, since it is no longer relevant. If a // different message is shown, we leave it. if (frame.statusLine.getText().startsWith(Globals.lang("Saved database"))); frame.output(" "); } public void markNonUndoableBaseChanged() { nonUndoableChange = true; markBaseChanged(); } public synchronized void markChangedOrUnChanged() { if (undoManager.hasChanged()) { if (!baseChanged) { markBaseChanged(); } } else if (baseChanged && !nonUndoableChange) { baseChanged = false; if (getFile() != null) frame.setTabTitle(BasePanel.this, getFile().getName(), getFile().getAbsolutePath()); else frame.setTabTitle(BasePanel.this, Globals.lang("untitled"), null); } frame.setWindowTitle(); } /** * Selects a single entry, and scrolls the table to center it. * * @param pos Current position of entry to select. * */ public void selectSingleEntry(int pos) { mainTable.clearSelection(); mainTable.addRowSelectionInterval(pos, pos); mainTable.scrollToCenter(pos, 0); } /* * * Selects all entries with a non-zero value in the field * @param field <code>String</code> field name. */ /* public void selectResults(String field) { LinkedList intervals = new LinkedList(); int prevStart = -1, prevToSel = 0; // First we build a list of intervals to select, without touching the table. for (int i = 0; i < entryTable.getRowCount(); i++) { String value = (String) (database.getEntryById (tableModel.getIdForRow(i))) .getField(field); if ( (value != null) && !value.equals("0")) { if (prevStart < 0) prevStart = i; prevToSel = i; } else if (prevStart >= 0) { intervals.add(new int[] {prevStart, prevToSel}); prevStart = -1; } } // Then select those intervals, if any. if (intervals.size() > 0) { entryTable.setSelectionListenerEnabled(false); entryTable.clearSelection(); for (Iterator i=intervals.iterator(); i.hasNext();) { int[] interval = (int[])i.next(); entryTable.addRowSelectionInterval(interval[0], interval[1]); } entryTable.setSelectionListenerEnabled(true); } */ public void setSearchMatcher(SearchMatcher matcher) { searchFilterList.setMatcher(matcher); showingSearch = true; } public void setGroupMatcher(Matcher<BibtexEntry> matcher) { groupFilterList.setMatcher(matcher); showingGroup = true; } public void stopShowingSearchResults() { searchFilterList.setMatcher(NoSearchMatcher.INSTANCE); showingSearch = false; } public void stopShowingGroup() { groupFilterList.setMatcher(NoSearchMatcher.INSTANCE); showingGroup = false; } /** * Query whether this BasePanel is in the mode where a float search result is shown. * @return true if showing float search, false otherwise. */ public boolean isShowingFloatSearch() { return mainTable.isShowingFloatSearch(); } /** * Query whether this BasePanel is in the mode where a filter search result is shown. * @return true if showing filter search, false otherwise. */ public boolean isShowingFilterSearch() { return showingSearch; } public BibtexDatabase getDatabase(){ return database ; } public void preambleEditorClosing() { preambleEditor = null; } public void stringsClosing() { stringDialog = null; } public void changeType(BibtexEntry entry, BibtexEntryType type) { changeType(new BibtexEntry[] {entry}, type); } public void changeType(BibtexEntryType type) { BibtexEntry[] bes = mainTable.getSelectedEntries(); changeType(bes, type); } public void changeType(BibtexEntry[] bes, BibtexEntryType type) { if ((bes == null) || (bes.length == 0)) { output("First select the entries you wish to change type "+ "for."); return; } if (bes.length > 1) { int choice = JOptionPane.showConfirmDialog (this, "Multiple entries selected. Do you want to change" +"\nthe type of all these to '"+type.getName()+"'?", "Change type", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.NO_OPTION) return; } NamedCompound ce = new NamedCompound(Globals.lang("change type")); for (int i=0; i<bes.length; i++) { ce.addEdit(new UndoableChangeType(bes[i], bes[i].getType(), type)); bes[i].setType(type); } output(Globals.lang("Changed type to")+" '"+type.getName()+"' " +Globals.lang("for")+" "+bes.length +" "+Globals.lang("entries")+"."); ce.end(); undoManager.addEdit(ce); markBaseChanged(); updateEntryEditorIfShowing(); } public boolean showDeleteConfirmationDialog(int numberOfEntries) { if (Globals.prefs.getBoolean("confirmDelete")) { String msg = Globals.lang("Really delete the selected") + " " + Globals.lang("entry") + "?", title = Globals.lang("Delete entry"); if (numberOfEntries > 1) { msg = Globals.lang("Really delete the selected") + " " + numberOfEntries + " " + Globals.lang("entries") + "?"; title = Globals.lang("Delete multiple entries"); } CheckBoxMessage cb = new CheckBoxMessage (msg, Globals.lang("Disable this confirmation dialog"), false); int answer = JOptionPane.showConfirmDialog(frame, cb, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (cb.isSelected()) Globals.prefs.putBoolean("confirmDelete", false); return (answer == JOptionPane.YES_OPTION); } else return true; } /** * If the relevant option is set, autogenerate keys for all entries that are * lacking keys. */ public void autoGenerateKeysBeforeSaving() { if (Globals.prefs.getBoolean("generateKeysBeforeSaving")) { NamedCompound ce = new NamedCompound(Globals.lang("autogenerate keys")); boolean any = false; for (BibtexEntry bes : database.getEntries()){ String oldKey = bes.getCiteKey(); if ((oldKey == null) || (oldKey.equals(""))) { LabelPatternUtil.makeLabel(metaData, database, bes); ce.addEdit(new UndoableKeyChange(database, bes.getId(), null, bes.getField(BibtexFields.KEY_FIELD))); any = true; } } // Store undo information, if any: if (any) { ce.end(); undoManager.addEdit(ce); } } } /** * Activates or deactivates the entry preview, depending on the argument. * When deactivating, makes sure that any visible preview is hidden. * @param enabled */ public void setPreviewActive(boolean enabled) { selectionListener.setPreviewActive(enabled); } public void setSelectionListenerEnabled(boolean enabled) { selectionListener.setEnabled(enabled); } /** * Depending on whether a preview or an entry editor is showing, save the current * divider location in the correct preference setting. */ public void saveDividerLocation() { if (mode == SHOWING_PREVIEW) Globals.prefs.putInt("previewPanelHeight", splitPane.getHeight()-splitPane.getDividerLocation()); else if (mode == SHOWING_EDITOR) Globals.prefs.putInt("entryEditorHeight", splitPane.getHeight()-splitPane.getDividerLocation()); } class UndoAction extends BaseAction { public void action() { try { JComponent focused = Globals.focusListener.getFocused(); if ((focused != null) && (focused instanceof FieldEditor) && (focused.hasFocus())) { // User is currently editing a field: // Check if it is the preamble: if ((preambleEditor != null) && (focused == preambleEditor.getFieldEditor())) { preambleEditor.storeCurrentEdit(); } else storeCurrentEdit(); } String name = undoManager.getUndoPresentationName(); undoManager.undo(); markBaseChanged(); frame.output(name); } catch (CannotUndoException ex) { ex.printStackTrace(); frame.output(Globals.lang("Nothing to undo")+"."); } // After everything, enable/disable the undo/redo actions // appropriately. //updateUndoState(); //redoAction.updateRedoState(); markChangedOrUnChanged(); } } class RedoAction extends BaseAction { public void action() { try { JComponent focused = Globals.focusListener.getFocused(); if ((focused != null) && (focused instanceof FieldEditor) && (focused.hasFocus())) { // User is currently editing a field: storeCurrentEdit(); } String name = undoManager.getRedoPresentationName(); undoManager.redo(); markBaseChanged(); frame.output(name); } catch (CannotRedoException ex) { frame.output(Globals.lang("Nothing to redo")+"."); } // After everything, enable/disable the undo/redo actions // appropriately. //updateRedoState(); //undoAction.updateUndoState(); markChangedOrUnChanged(); } } // Method pertaining to the ClipboardOwner interface. public void lostOwnership(Clipboard clipboard, Transferable contents) {} public void setEntryEditorEnabled(boolean enabled) { if ((getShowing() != null) && (splitPane.getBottomComponent() instanceof EntryEditor)) { EntryEditor ed = (EntryEditor)splitPane.getBottomComponent(); if (ed.isEnabled() != enabled) ed.setEnabled(enabled); } } public String fileMonitorHandle() { return fileMonitorHandle; } public void fileUpdated() { if (saving) return; // We are just saving the file, so this message is most likely due //if (updatedExternally) { // return; //} // to bad timing. If not, we'll handle it on the next polling. //Util.pr("File '"+file.getPath()+"' has been modified."); updatedExternally = true; final ChangeScanner scanner = new ChangeScanner(frame, BasePanel.this); // Adding the sidepane component is Swing work, so we must do this in the Swing // thread: Thread t = new Thread() { public void run() { // Check if there is already a notification about external // changes: boolean hasAlready = sidePaneManager.hasComponent(FileUpdatePanel.NAME); if (hasAlready) { sidePaneManager.hideComponent(FileUpdatePanel.NAME); sidePaneManager.unregisterComponent(FileUpdatePanel.NAME); } FileUpdatePanel pan = new FileUpdatePanel(frame, BasePanel.this, sidePaneManager, getFile(), scanner); sidePaneManager.register(FileUpdatePanel.NAME, pan); sidePaneManager.show(FileUpdatePanel.NAME); //setUpdatedExternally(false); //scanner.displayResult(); } }; // Test: running scan automatically in background if ((BasePanel.this.getFile() != null) && !Util.waitForFileLock(BasePanel.this.getFile(), 10)) { // The file is locked even after the maximum wait. Do nothing. System.err.println("File updated externally, but change scan failed because the file is locked."); // Perturb the stored timestamp so successive checks are made: Globals.fileUpdateMonitor.perturbTimestamp(getFileMonitorHandle()); return; } scanner.changeScan(BasePanel.this.getFile()); try { scanner.join(); } catch (InterruptedException e) { e.printStackTrace(); } if (scanner.changesFound()) { SwingUtilities.invokeLater(t); } else { setUpdatedExternally(false); //System.out.println("No changes found."); } } public void fileRemoved() { Util.pr("File '"+getFile().getPath()+"' has been deleted."); } /** * Perform necessary cleanup when this BasePanel is closed. */ public void cleanUp() { if (fileMonitorHandle != null) Globals.fileUpdateMonitor.removeUpdateListener(fileMonitorHandle); // Check if there is a FileUpdatePanel for this BasePanel being shown. If so, // remove it: if (sidePaneManager.hasComponent("fileUpdate")) { FileUpdatePanel fup = (FileUpdatePanel)sidePaneManager.getComponent("fileUpdate"); if (fup.getPanel() == this) { sidePaneManager.hideComponent("fileUpdate"); } } } public void setUpdatedExternally(boolean b) { updatedExternally = b; } /** * Get an array containing the currently selected entries. * * @return An array containing the selected entries. */ public BibtexEntry[] getSelectedEntries() { return mainTable.getSelectedEntries(); } /** * Get the file where this database was last saved to or loaded from, if any. * * @return The relevant File, or null if none is defined. */ public File getFile() { return metaData.getFile(); } /** * Get a String containing a comma-separated list of the bibtex keys * of the selected entries. * * @return A comma-separated list of the keys of the selected entries. */ public String getKeysForSelection() { StringBuffer result = new StringBuffer(); String citeKey = "";//, message = ""; boolean first = true; for (BibtexEntry bes : mainTable.getSelected()){ citeKey = bes.getField(BibtexFields.KEY_FIELD); // if the key is empty we give a warning and ignore this entry if (citeKey == null || citeKey.equals("")) continue; if (first) { result.append(citeKey); first = false; } else { result.append(",").append(citeKey); } } return result.toString(); } public GroupSelector getGroupSelector() { return frame.groupSelector; } public boolean isUpdatedExternally() { return updatedExternally; } public String getFileMonitorHandle() { return fileMonitorHandle; } public void setFileMonitorHandle(String fileMonitorHandle) { this.fileMonitorHandle = fileMonitorHandle; } public SidePaneManager getSidePaneManager() { return sidePaneManager; } public void setNonUndoableChange(boolean nonUndoableChange) { this.nonUndoableChange = nonUndoableChange; } public void setBaseChanged(boolean baseChanged) { this.baseChanged = baseChanged; } public void setSaving(boolean saving) { this.saving = saving; } public boolean isSaving() { return saving; } public BibtexEntry getShowing() { return showing; } /** * Update the pointer to the currently shown entry in all cases where the user has * moved to a new entry, except when using Back and Forward commands. Also updates * history for Back command, and clears history for Forward command. * @param entry The entry that is now to be shown. */ public void newEntryShowing(BibtexEntry entry) { // If this call is the result of a Back or Forward operation, we must take // care not to make any history changes, since the necessary changes will // already have been done in the back() or forward() method: if (backOrForwardInProgress) { showing = entry; backOrForwardInProgress = false; setBackAndForwardEnabledState(); return; } nextEntries.clear(); if (entry != showing) { // Add the entry we are leaving to the history: if (showing != null) { previousEntries.add(showing); if (previousEntries.size() > GUIGlobals.MAX_BACK_HISTORY_SIZE) previousEntries.remove(0); } showing = entry; setBackAndForwardEnabledState(); } } /** * Go back (if there is any recorded history) and update the histories for * the Back and Forward commands. */ private void back() { if (previousEntries.size() > 0) { BibtexEntry toShow = previousEntries.get(previousEntries.size()-1); previousEntries.remove(previousEntries.size()-1); // Add the entry we are going back from to the Forward history: if (showing != null) nextEntries.add(showing); backOrForwardInProgress = true; // to avoid the history getting updated erroneously //showEntry(toShow); highlightEntry(toShow); } } private void forward() { if (nextEntries.size() > 0) { BibtexEntry toShow = nextEntries.get(nextEntries.size()-1); nextEntries.remove(nextEntries.size()-1); // Add the entry we are going forward from to the Back history: if (showing != null) previousEntries.add(showing); backOrForwardInProgress = true; // to avoid the history getting updated erroneously //showEntry(toShow); highlightEntry(toShow); } } public void setBackAndForwardEnabledState() { frame.back.setEnabled(previousEntries.size() > 0); frame.forward.setEnabled(nextEntries.size() > 0); } }
src/java/net/sf/jabref/BasePanel.java
/* Copyright (C) 2003-2012 JabRef contributors. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package net.sf.jabref; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.io.StringReader; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.regex.Pattern; import javax.swing.AbstractAction; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.tree.TreePath; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import net.sf.jabref.autocompleter.AbstractAutoCompleter; import net.sf.jabref.autocompleter.AutoCompleterFactory; import net.sf.jabref.autocompleter.NameFieldAutoCompleter; import net.sf.jabref.collab.ChangeScanner; import net.sf.jabref.collab.FileUpdateListener; import net.sf.jabref.collab.FileUpdatePanel; import net.sf.jabref.export.ExportToClipboardAction; import net.sf.jabref.export.FileActions; import net.sf.jabref.export.SaveDatabaseAction; import net.sf.jabref.export.SaveException; import net.sf.jabref.export.SaveSession; import net.sf.jabref.export.layout.Layout; import net.sf.jabref.export.layout.LayoutHelper; import net.sf.jabref.external.*; import net.sf.jabref.groups.AddToGroupAction; import net.sf.jabref.groups.GroupSelector; import net.sf.jabref.groups.GroupTreeNode; import net.sf.jabref.gui.*; import net.sf.jabref.imports.AppendDatabaseAction; import net.sf.jabref.imports.BibtexParser; import net.sf.jabref.imports.SPIRESFetcher; import net.sf.jabref.imports.INSPIREFetcher; import net.sf.jabref.journals.AbbreviateAction; import net.sf.jabref.journals.UnabbreviateAction; import net.sf.jabref.labelPattern.LabelPatternUtil; import net.sf.jabref.labelPattern.SearchFixDuplicateLabels; import net.sf.jabref.search.NoSearchMatcher; import net.sf.jabref.search.SearchMatcher; import net.sf.jabref.specialfields.SpecialFieldAction; import net.sf.jabref.specialfields.Priority; import net.sf.jabref.specialfields.Quality; import net.sf.jabref.specialfields.Rank; import net.sf.jabref.specialfields.Relevance; import net.sf.jabref.specialfields.SpecialFieldDatabaseChangeListener; import net.sf.jabref.specialfields.SpecialFieldValue; import net.sf.jabref.specialfields.SpecialFieldsUtils; import net.sf.jabref.sql.DBConnectDialog; import net.sf.jabref.sql.DBStrings; import net.sf.jabref.sql.DbConnectAction; import net.sf.jabref.sql.DBExporterAndImporterFactory; import net.sf.jabref.sql.SQLUtil; import net.sf.jabref.sql.exporter.DBExporter; import net.sf.jabref.undo.CountingUndoManager; import net.sf.jabref.undo.NamedCompound; import net.sf.jabref.undo.UndoableChangeType; import net.sf.jabref.undo.UndoableFieldChange; import net.sf.jabref.undo.UndoableInsertEntry; import net.sf.jabref.undo.UndoableKeyChange; import net.sf.jabref.undo.UndoableRemoveEntry; import net.sf.jabref.wizard.text.gui.TextInputDialog; import ca.odell.glazedlists.FilterList; import ca.odell.glazedlists.event.ListEvent; import ca.odell.glazedlists.event.ListEventListener; import ca.odell.glazedlists.matchers.Matcher; import com.jgoodies.forms.builder.DefaultFormBuilder; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.uif_lite.component.UIFSplitPane; public class BasePanel extends JPanel implements ClipboardOwner, FileUpdateListener { public final static int SHOWING_NOTHING=0, SHOWING_PREVIEW=1, SHOWING_EDITOR=2, WILL_SHOW_EDITOR=3; /* * The database shown in this panel. */ BibtexDatabase database; private int mode=0; private EntryEditor currentEditor = null; private PreviewPanel currentPreview = null; boolean tmp = true; private MainTableSelectionListener selectionListener = null; private ListEventListener<BibtexEntry> groupsHighlightListener; UIFSplitPane contentPane = new UIFSplitPane(); JSplitPane splitPane; JabRefFrame frame; String fileMonitorHandle = null; boolean saving = false, updatedExternally = false; private String encoding; GridBagLayout gbl = new GridBagLayout(); GridBagConstraints con = new GridBagConstraints(); HashMap<String, AbstractAutoCompleter> autoCompleters = new HashMap<String, AbstractAutoCompleter>(); // Hashtable that holds as keys the names of the fields where // autocomplete is active, and references to the autocompleter objects. NameFieldAutoCompleter searchCompleter = null; AutoCompleteListener searchCompleteListener = null; // The undo manager. public CountingUndoManager undoManager = new CountingUndoManager(this); UndoAction undoAction = new UndoAction(); RedoAction redoAction = new RedoAction(); private List<BibtexEntry> previousEntries = new ArrayList<BibtexEntry>(), nextEntries = new ArrayList<BibtexEntry>(); //ExampleFileFilter fileFilter; // File filter for .bib files. boolean baseChanged = false, nonUndoableChange = false; // Used to track whether the base has changed since last save. //EntryTableModel tableModel = null; //public EntryTable entryTable = null; public MainTable mainTable = null; public MainTableFormat tableFormat = null; public FilterList<BibtexEntry> searchFilterList = null, groupFilterList = null; public RightClickMenu rcm; BibtexEntry showing = null; // Variable to prevent erroneous update of back/forward histories at the time // when a Back or Forward operation is being processed: private boolean backOrForwardInProgress = false; // To indicate which entry is currently shown. public HashMap<String, EntryEditor> entryEditors = new HashMap<String, EntryEditor>(); // To contain instantiated entry editors. This is to save time // in switching between entries. //HashMap entryTypeForms = new HashMap(); // Hashmap to keep track of which entries currently have open // EntryTypeForm dialogs. PreambleEditor preambleEditor = null; // Keeps track of the preamble dialog if it is open. StringDialog stringDialog = null; // Keeps track of the string dialog if it is open. SaveDatabaseAction saveAction; CleanUpAction cleanUpAction; /** * The group selector component for this database. Instantiated by the * SidePaneManager if necessary, or from this class if merging groups from a * different database. */ //GroupSelector groupSelector; public boolean showingSearch = false, showingGroup = false, sortingBySearchResults = false, coloringBySearchResults = false, hidingNonHits = false, sortingByGroup = false, sortingByCiteSeerResults = false, coloringByGroup = false; int lastSearchHits = -1; // The number of hits in the latest search. // Potential use in hiding non-hits completely. // MetaData parses, keeps and writes meta data. MetaData metaData; private boolean suppressOutput = false; private HashMap<String, Object> actions = new HashMap<String, Object>(); private SidePaneManager sidePaneManager; /** * Create a new BasePanel with an empty database. * @param frame The application window. */ public BasePanel(JabRefFrame frame) { this.sidePaneManager = Globals.sidePaneManager; database = new BibtexDatabase(); metaData = new MetaData(); metaData.initializeNewDatabase(); this.frame = frame; setupActions(); setupMainPanel(); encoding = Globals.prefs.get("defaultEncoding"); //System.out.println("Default: "+encoding); } public BasePanel(JabRefFrame frame, BibtexDatabase db, File file, MetaData metaData, String encoding) { init(frame, db, file, metaData, encoding); } private void init(JabRefFrame frame, BibtexDatabase db, File file, MetaData metaData, String encoding) { this.encoding = encoding; this.metaData = metaData; // System.out.println(encoding); //super(JSplitPane.HORIZONTAL_SPLIT, true); this.sidePaneManager = Globals.sidePaneManager; this.frame = frame; database = db; setupActions(); setupMainPanel(); metaData.setFile(file); // Register so we get notifications about outside changes to the file. if (file != null) try { fileMonitorHandle = Globals.fileUpdateMonitor.addUpdateListener(this, file); } catch (IOException ex) { } } public boolean isBaseChanged(){ return baseChanged; } public int getMode() { return mode; } //Done by MrDlib public void setMode(int mode) { this.mode = mode; } //Done by MrDlib public BibtexDatabase database() { return database; } public MetaData metaData() { return metaData; } public JabRefFrame frame() { return frame; } public JabRefPreferences prefs() { return Globals.prefs; } public String getEncoding() { return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } public void output(String s) { if (!suppressOutput) frame.output(s); } private void setupActions() { saveAction = new SaveDatabaseAction(this); cleanUpAction = new CleanUpAction(this); actions.put("undo", undoAction); actions.put("redo", redoAction); actions.put("focusTable", new BaseAction() { public void action() throws Throwable { new FocusRequester(mainTable); } }); // The action for opening an entry editor. actions.put("edit", new BaseAction() { public void action() { /*System.out.println(Globals.focusListener.getFocused().getClass().getName()); if (Globals.focusListener.getFocused() instanceof FieldEditor) new FocusRequester(mainTable); else*/ selectionListener.editSignalled(); } /* if (isShowingEditor()) { new FocusRequester(splitPane.getBottomComponent()); return; } frame.block(); //(new Thread() { //public void run() { int clickedOn = -1; // We demand that one and only one row is selected. if (entryTable.getSelectedRowCount() == 1) { clickedOn = entryTable.getSelectedRow(); } if (clickedOn >= 0) { String id = tableModel.getIdForRow(clickedOn); BibtexEntry be = database.getEntryById(id); showEntry(be); if (splitPane.getBottomComponent() != null) { new FocusRequester(splitPane.getBottomComponent()); } } frame.unblock(); } */ }); actions.put("test",// new AccessLinksForEntries.SaveWithLinkedFiles(this)); new FindFullTextAction(this)); // The action for saving a database. actions.put("save", saveAction); actions.put("saveAs", new BaseAction() { public void action() throws Throwable { saveAction.saveAs(); } }); actions.put("saveSelectedAs", new BaseAction () { public void action() throws Throwable { String chosenFile = FileDialogs.getNewFile(frame, new File(Globals.prefs.get("workingDirectory")), ".bib", JFileChooser.SAVE_DIALOG, false); if (chosenFile != null) { File expFile = new File(chosenFile); if (!expFile.exists() || (JOptionPane.showConfirmDialog (frame, "'"+expFile.getName()+"' "+ Globals.lang("exists. Overwrite file?"), Globals.lang("Save database"), JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION)) { saveDatabase(expFile, true, Globals.prefs.get("defaultEncoding")); //runCommand("save"); frame.getFileHistory().newFile(expFile.getPath()); frame.output(Globals.lang("Saved selected to")+" '" +expFile.getPath()+"'."); } } } }); // The action for copying selected entries. actions.put("copy", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) { TransferableBibtexEntry trbe = new TransferableBibtexEntry(bes); // ! look at ClipBoardManager Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(trbe, BasePanel.this); output(Globals.lang("Copied")+" "+(bes.length>1 ? bes.length+" " +Globals.lang("entries") : "1 "+Globals.lang("entry")+".")); } else { // The user maybe selected a single cell. int[] rows = mainTable.getSelectedRows(), cols = mainTable.getSelectedColumns(); if ((cols.length == 1) && (rows.length == 1)) { // Copy single value. Object o = mainTable.getValueAt(rows[0], cols[0]); if (o != null) { StringSelection ss = new StringSelection(o.toString()); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(ss, BasePanel.this); output(Globals.lang("Copied cell contents")+"."); } } } } }); actions.put("cut", new BaseAction() { public void action() throws Throwable { runCommand("copy"); BibtexEntry[] bes = mainTable.getSelectedEntries(); //int row0 = mainTable.getSelectedRow(); if ((bes != null) && (bes.length > 0)) { // Create a CompoundEdit to make the action undoable. NamedCompound ce = new NamedCompound (Globals.lang(bes.length > 1 ? "cut entries" : "cut entry")); // Loop through the array of entries, and delete them. for (int i=0; i<bes.length; i++) { database.removeEntry(bes[i].getId()); ensureNotShowing(bes[i]); ce.addEdit(new UndoableRemoveEntry (database, bes[i], BasePanel.this)); } //entryTable.clearSelection(); frame.output(Globals.lang("Cut_pr")+" "+ (bes.length>1 ? bes.length +" "+ Globals.lang("entries") : Globals.lang("entry"))+"."); ce.end(); undoManager.addEdit(ce); markBaseChanged(); // Reselect the entry in the first prev. selected position: /*if (row0 >= entryTable.getRowCount()) row0 = entryTable.getRowCount()-1; if (row0 >= 0) entryTable.addRowSelectionInterval(row0, row0);*/ } } }); actions.put("delete", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) { boolean goOn = showDeleteConfirmationDialog(bes.length); if (!goOn) { return; } else { // Create a CompoundEdit to make the action undoable. NamedCompound ce = new NamedCompound (Globals.lang(bes.length > 1 ? "delete entries" : "delete entry")); // Loop through the array of entries, and delete them. for (int i = 0; i < bes.length; i++) { database.removeEntry(bes[i].getId()); ensureNotShowing(bes[i]); ce.addEdit(new UndoableRemoveEntry(database, bes[i], BasePanel.this)); } markBaseChanged(); frame.output(Globals.lang("Deleted") + " " + (bes.length > 1 ? bes.length + " " + Globals.lang("entries") : Globals.lang("entry")) + "."); ce.end(); undoManager.addEdit(ce); //entryTable.clearSelection(); } // Reselect the entry in the first prev. selected position: /*if (row0 >= entryTable.getRowCount()) row0 = entryTable.getRowCount()-1; if (row0 >= 0) { final int toSel = row0; // SwingUtilities.invokeLater(new Runnable() { public void run() { entryTable.addRowSelectionInterval(toSel, toSel); //entryTable.ensureVisible(toSel); } }); */ } } }); // The action for pasting entries or cell contents. // Edited by Seb Wills <[email protected]> on 14-Apr-04: // - more robust detection of available content flavors (doesn't only look at first one offered) // - support for parsing string-flavor clipboard contents which are bibtex entries. // This allows you to (a) paste entire bibtex entries from a text editor, web browser, etc // (b) copy and paste entries between multiple instances of JabRef (since // only the text representation seems to get as far as the X clipboard, at least on my system) actions.put("paste", new BaseAction() { public void action() { // Get clipboard contents, and see if TransferableBibtexEntry is among the content flavors offered Transferable content = Toolkit.getDefaultToolkit() .getSystemClipboard().getContents(null); if (content != null) { BibtexEntry[] bes = null; if (content.isDataFlavorSupported(TransferableBibtexEntry.entryFlavor)) { // We have determined that the clipboard data is a set of entries. try { bes = (BibtexEntry[])(content.getTransferData(TransferableBibtexEntry.entryFlavor)); } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } else if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { BibtexParser bp = new BibtexParser (new java.io.StringReader( (String) (content.getTransferData( DataFlavor.stringFlavor)))); BibtexDatabase db = bp.parse().getDatabase(); Util.pr("Parsed " + db.getEntryCount() + " entries from clipboard text"); if(db.getEntryCount()>0) { bes = db.getEntries().toArray(new BibtexEntry[db.getEntryCount()]); } } catch (UnsupportedFlavorException ex) { ex.printStackTrace(); } catch (Throwable ex) { ex.printStackTrace(); } } // finally we paste in the entries (if any), which either came from TransferableBibtexEntries // or were parsed from a string if ((bes != null) && (bes.length > 0)) { NamedCompound ce = new NamedCompound (Globals.lang(bes.length > 1 ? "paste entries" : "paste entry")); // Store the first inserted bibtexentry. // bes[0] does not work as bes[0] is first clonded, // then inserted. // This entry is used to open up an entry editor // for the first inserted entry. BibtexEntry firstBE = null; for (int i=0; i<bes.length; i++) { try { BibtexEntry be = (BibtexEntry)(bes[i].clone()); if (firstBE == null) firstBE = be; Util.setAutomaticFields(be, Globals.prefs.getBoolean("overwriteOwner"), Globals.prefs.getBoolean("overwriteTimeStamp")); // We have to clone the // entries, since the pasted // entries must exist // independently of the copied // ones. be.setId(Util.createNeutralId()); database.insertEntry(be); addToSelectedGroup(be); ce.addEdit(new UndoableInsertEntry (database, be, BasePanel.this)); } catch (KeyCollisionException ex) { Util.pr("KeyCollisionException... this shouldn't happen."); } } ce.end(); undoManager.addEdit(ce); //entryTable.clearSelection(); //entryTable.revalidate(); output(Globals.lang("Pasted") + " " + (bes.length > 1 ? bes.length + " " + Globals.lang("entries") : "1 " + Globals.lang("entry")) + "."); markBaseChanged(); if (Globals.prefs.getBoolean("autoOpenForm")) { selectionListener.editSignalled(firstBE); } highlightEntry(firstBE); } } } }); actions.put("selectAll", new BaseAction() { public void action() { mainTable.selectAll(); } }); // The action for opening the preamble editor actions.put("editPreamble", new BaseAction() { public void action() { if (preambleEditor == null) { PreambleEditor form = new PreambleEditor (frame, BasePanel.this, database, Globals.prefs); Util.placeDialog(form, frame); form.setVisible(true); preambleEditor = form; } else { preambleEditor.setVisible(true); } } }); // The action for opening the string editor actions.put("editStrings", new BaseAction() { public void action() { if (stringDialog == null) { StringDialog form = new StringDialog (frame, BasePanel.this, database, Globals.prefs); Util.placeDialog(form, frame); form.setVisible(true); stringDialog = form; } else { stringDialog.setVisible(true); } } }); // The action for toggling the groups interface actions.put("toggleGroups", new BaseAction() { public void action() { sidePaneManager.toggle("groups"); frame.groupToggle.setSelected(sidePaneManager.isComponentVisible("groups")); } }); // action for collecting database strings from user actions.put("dbConnect", new DbConnectAction(this)); // action for exporting database to external SQL database actions.put("dbExport", new AbstractWorker () { String errorMessage = null; boolean connectToDB = false; // run first, in EDT: public void init() { DBStrings dbs = metaData.getDBStrings(); // get DBStrings from user if necessary if (!dbs.isConfigValid()) { // init DB strings if necessary if (! dbs.isInitialized()) { dbs.initialize(); } // show connection dialog DBConnectDialog dbd = new DBConnectDialog(frame(), dbs); Util.placeDialog(dbd, BasePanel.this ); dbd.setVisible(true); connectToDB = dbd.getConnectToDB(); // store database strings if (connectToDB) { dbs = dbd.getDBStrings(); metaData.setDBStrings(dbs); dbd.dispose(); } } else { connectToDB = true; } } // run second, on a different thread: public void run() { if (connectToDB) { DBStrings dbs = metaData.getDBStrings(); try { /*boolean okToExport = null!=metaData.getFile(); if (!okToExport) { okToExport = false; int response = JOptionPane.showConfirmDialog(null, "You need to save your database in the disk \n" + "before saving. Save it now?", "Database is not saved", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if(response == JOptionPane.YES_OPTION) { try { saveAction.saveAs(); okToExport = (null!=metaData.getFile()); } catch (Throwable e) { e.printStackTrace(); } } } if (okToExport) {*/ frame.output(Globals.lang("Attempting SQL export...")); DBExporterAndImporterFactory factory = new DBExporterAndImporterFactory(); DBExporter exporter = factory.getExporter(dbs.getServerType()); exporter.exportDatabaseToDBMS(database, metaData, null, dbs, frame); dbs.isConfigValid(true); //} //else // errorMessage = "Database was not exported. Your database must be saved \nbefore exporting to a SQL database"; } catch (Exception ex) { String preamble = "Could not export to SQL database for the following reason:"; errorMessage = SQLUtil.getExceptionMessage(ex); ex.printStackTrace(); dbs.isConfigValid(false); JOptionPane.showMessageDialog(frame, Globals.lang(preamble) + "\n" +errorMessage, Globals.lang("Export to SQL database"), JOptionPane.ERROR_MESSAGE); } metaData.setDBStrings(dbs); } } // run third, on EDT: public void update() { // if no error, report success if (errorMessage == null) { if (connectToDB) { frame.output(Globals.lang("%0 export successful")); } } // show an error dialog if an error occurred else { String preamble = "Could not export to SQL database for the following reason:"; frame.output(Globals.lang(preamble) + " " + errorMessage); JOptionPane.showMessageDialog(frame, Globals.lang(preamble) + "\n" + errorMessage, Globals.lang("Export to SQL database"), JOptionPane.ERROR_MESSAGE); errorMessage = null; } } }); actions.put(FindUnlinkedFilesDialog.ACTION_COMMAND, new BaseAction() { @Override public void action() throws Throwable { FindUnlinkedFilesDialog dialog = new FindUnlinkedFilesDialog(frame, frame, BasePanel.this); Util.placeDialog(dialog, frame); dialog.setVisible(true); } }); // The action for auto-generating keys. actions.put("makeKey", new AbstractWorker() { //int[] rows; List<BibtexEntry> entries; int numSelected; boolean cancelled = false; // Run first, in EDT: public void init() { entries = new ArrayList<BibtexEntry>(Arrays.asList(getSelectedEntries())); //rows = entryTable.getSelectedRows() ; numSelected = entries.size(); if (entries.size() == 0) { // None selected. Inform the user to select entries first. JOptionPane.showMessageDialog(frame, Globals.lang("First select the entries you want keys to be generated for."), Globals.lang("Autogenerate BibTeX key"), JOptionPane.INFORMATION_MESSAGE); return ; } frame.block(); output(Globals.lang("Generating BibTeX key for")+" "+ numSelected+" "+(numSelected>1 ? Globals.lang("entries") : Globals.lang("entry"))+"..."); } // Run second, on a different thread: public void run() { BibtexEntry bes = null ; NamedCompound ce = new NamedCompound(Globals.lang("autogenerate keys")); // First check if any entries have keys set already. If so, possibly remove // them from consideration, or warn about overwriting keys. loop: for (Iterator<BibtexEntry> i=entries.iterator(); i.hasNext();) { bes = i.next(); if (bes.getField(BibtexFields.KEY_FIELD) != null) { if (Globals.prefs.getBoolean("avoidOverwritingKey")) // Remove the entry, because its key is already set: i.remove(); else if (Globals.prefs.getBoolean("warnBeforeOverwritingKey")) { // Ask if the user wants to cancel the operation: CheckBoxMessage cbm = new CheckBoxMessage(Globals.lang("One or more keys will be overwritten. Continue?"), Globals.lang("Disable this confirmation dialog"), false); int answer = JOptionPane.showConfirmDialog(frame, cbm, Globals.lang("Overwrite keys"), JOptionPane.YES_NO_OPTION); if (cbm.isSelected()) Globals.prefs.putBoolean("warnBeforeOverwritingKey", false); if (answer == JOptionPane.NO_OPTION) { // Ok, break off the operation. cancelled = true; return; } // No need to check more entries, because the user has already confirmed // that it's ok to overwrite keys: break loop; } } } HashMap<BibtexEntry, Object> oldvals = new HashMap<BibtexEntry, Object>(); // Iterate again, removing already set keys. This is skipped if overwriting // is disabled, since all entries with keys set will have been removed. if (!Globals.prefs.getBoolean("avoidOverwritingKey")) for (Iterator<BibtexEntry> i=entries.iterator(); i.hasNext();) { bes = i.next(); // Store the old value: oldvals.put(bes, bes.getField(BibtexFields.KEY_FIELD)); database.setCiteKeyForEntry(bes.getId(), null); } // Finally, set the new keys: for (Iterator<BibtexEntry> i=entries.iterator(); i.hasNext();) { bes = i.next(); bes = LabelPatternUtil.makeLabel(metaData, database, bes); ce.addEdit(new UndoableKeyChange (database, bes.getId(), (String)oldvals.get(bes), bes.getField(BibtexFields.KEY_FIELD))); } ce.end(); undoManager.addEdit(ce); } // Run third, on EDT: public void update() { database.setFollowCrossrefs(true); if (cancelled) { frame.unblock(); return; } markBaseChanged() ; numSelected = entries.size(); //////////////////////////////////////////////////////////////////////////////// // Prevent selection loss for autogenerated BibTeX-Keys //////////////////////////////////////////////////////////////////////////////// for (Iterator<BibtexEntry> i=entries.iterator(); i.hasNext();) { final BibtexEntry bibEntry = i.next(); SwingUtilities.invokeLater(new Runnable() { public void run() { final int row = mainTable.findEntry( bibEntry ); if (row >= 0 && mainTable.getSelectedRowCount() < entries.size()) mainTable.addRowSelectionInterval(row, row); } }); } //////////////////////////////////////////////////////////////////////////////// output(Globals.lang("Generated BibTeX key for")+" "+ numSelected+" "+(numSelected!=1 ? Globals.lang("entries") : Globals.lang("entry"))); frame.unblock(); } }); // The action for cleaning up entry. actions.put("Cleanup", cleanUpAction); actions.put("search", new BaseAction() { public void action() { //sidePaneManager.togglePanel("search"); sidePaneManager.show("search"); //boolean on = sidePaneManager.isPanelVisible("search"); frame.searchToggle.setSelected(true); if (true) frame.getSearchManager().startSearch(); } }); actions.put("toggleSearch", new BaseAction() { public void action() { //sidePaneManager.togglePanel("search"); sidePaneManager.toggle("search"); boolean on = sidePaneManager.isComponentVisible("search"); frame.searchToggle.setSelected(on); if (on) frame.getSearchManager().startSearch(); } }); actions.put("incSearch", new BaseAction() { public void action() { sidePaneManager.show("search"); frame.searchToggle.setSelected(true); frame.getSearchManager().startIncrementalSearch(); } }); // The action for copying the selected entry's key. actions.put("copyKey", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) { storeCurrentEdit(); //String[] keys = new String[bes.length]; Vector<Object> keys = new Vector<Object>(); // Collect all non-null keys. for (int i=0; i<bes.length; i++) if (bes[i].getField(BibtexFields.KEY_FIELD) != null) keys.add(bes[i].getField(BibtexFields.KEY_FIELD)); if (keys.size() == 0) { output("None of the selected entries have BibTeX keys."); return; } StringBuffer sb = new StringBuffer((String)keys.elementAt(0)); for (int i=1; i<keys.size(); i++) { sb.append(','); sb.append((String)keys.elementAt(i)); } StringSelection ss = new StringSelection(sb.toString()); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(ss, BasePanel.this); if (keys.size() == bes.length) // All entries had keys. output(Globals.lang((bes.length > 1) ? "Copied keys" : "Copied key")+"."); else output(Globals.lang("Warning")+": "+(bes.length-keys.size()) +" "+Globals.lang("out of")+" "+bes.length+" "+ Globals.lang("entries have undefined BibTeX key")+"."); } } }); // The action for copying a cite for the selected entry. actions.put("copyCiteKey", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) { storeCurrentEdit(); //String[] keys = new String[bes.length]; Vector<Object> keys = new Vector<Object>(); // Collect all non-null keys. for (int i=0; i<bes.length; i++) if (bes[i].getField(BibtexFields.KEY_FIELD) != null) keys.add(bes[i].getField(BibtexFields.KEY_FIELD)); if (keys.size() == 0) { output("None of the selected entries have BibTeX keys."); return; } StringBuffer sb = new StringBuffer((String)keys.elementAt(0)); for (int i=1; i<keys.size(); i++) { sb.append(','); sb.append((String)keys.elementAt(i)); } StringSelection ss = new StringSelection ("\\cite{"+sb.toString()+"}"); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(ss, BasePanel.this); if (keys.size() == bes.length) // All entries had keys. output(bes.length > 1 ? Globals.lang("Copied keys") : Globals.lang("Copied key")+"."); else output(Globals.lang("Warning")+": "+(bes.length-keys.size()) +" "+Globals.lang("out of")+" "+bes.length+" "+ Globals.lang("entries have undefined BibTeX key")+"."); } } }); // The action for copying the BibTeX key and the title for the first selected entry actions.put("copyKeyAndTitle", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) { storeCurrentEdit(); // OK: in a future version, this string should be configurable to allow arbitrary exports StringReader sr = new StringReader("\\bibtexkey - \\begin{title}\\format[RemoveBrackets]{\\title}\\end{title}\n"); Layout layout; try { layout = new LayoutHelper(sr).getLayoutFromText(Globals.FORMATTER_PACKAGE); } catch (Exception e) { e.printStackTrace(); return; } StringBuffer sb = new StringBuffer(); int copied = 0; // Collect all non-null keys. for (int i=0; i<bes.length; i++) if (bes[i].getField(BibtexFields.KEY_FIELD) != null) { copied++; sb.append(layout.doLayout(bes[i], database)); } if (copied==0) { output("None of the selected entries have BibTeX keys."); return; } StringSelection ss = new StringSelection(sb.toString()); Toolkit.getDefaultToolkit().getSystemClipboard() .setContents(ss, BasePanel.this); if (copied == bes.length) // All entries had keys. output(Globals.lang((bes.length > 1) ? "Copied keys" : "Copied key")+"."); else output(Globals.lang("Warning")+": "+(copied) +" "+Globals.lang("out of")+" "+bes.length+" "+ Globals.lang("entries have undefined BibTeX key")+"."); } } }); actions.put("mergeDatabase", new AppendDatabaseAction(frame, this)); actions.put("openFile", new BaseAction() { public void action() { (new Thread() { public void run() { BibtexEntry[] bes = mainTable.getSelectedEntries(); String field = "ps"; if ((bes != null) && (bes.length == 1)) { FileListEntry entry = null; FileListTableModel tm = new FileListTableModel(); tm.setContent(bes[0].getField("file")); for (int i=0; i< tm.getRowCount(); i++) { FileListEntry flEntry = tm.getEntry(i); if (flEntry.getType().getName().toLowerCase().equals("pdf") || flEntry.getType().getName().toLowerCase().equals("ps")) { entry = flEntry; break; } } if (entry != null) { try { Util.openExternalFileAnyFormat(metaData, entry.getLink(), entry.getType()); output(Globals.lang("External viewer called") + "."); } catch (IOException e) { output(Globals.lang("Could not open link")); e.printStackTrace(); } return; } // If we didn't find anything in the "file" field, check "ps" and "pdf" fields: Object link = bes[0].getField("ps"); if (bes[0].getField("pdf") != null) { link = bes[0].getField("pdf"); field = "pdf"; } String filepath = null; if (link != null) { filepath = link.toString(); } else { if (Globals.prefs.getBoolean("runAutomaticFileSearch")) { /* The search can lead to an unexpected 100% CPU usage which is perceived as a bug, if the search incidentally starts at a directory with lots of stuff below. It is now disabled by default. */ // see if we can fall back to a filename based on the bibtex key final Collection<BibtexEntry> entries = new ArrayList<BibtexEntry>(); entries.add(bes[0]); ExternalFileType[] types = Globals.prefs.getExternalFileTypeSelection(); ArrayList<File> dirs = new ArrayList<File>(); if (metaData.getFileDirectory(GUIGlobals.FILE_FIELD).length > 0) { String[] mdDirs = metaData.getFileDirectory(GUIGlobals.FILE_FIELD); for (int i = 0; i < mdDirs.length; i++) { dirs.add(new File(mdDirs[i])); } } Collection<String> extensions = new ArrayList<String>(); for (int i = 0; i < types.length; i++) { final ExternalFileType type = types[i]; extensions.add(type.getExtension()); } // Run the search operation: Map<BibtexEntry, List<File>> result; if (Globals.prefs.getBoolean(JabRefPreferences.USE_REG_EXP_SEARCH_KEY)) { String regExp = Globals.prefs.get(JabRefPreferences.REG_EXP_SEARCH_EXPRESSION_KEY); result = RegExpFileSearch.findFilesForSet(entries, extensions, dirs, regExp); } else result = Util.findAssociatedFiles(entries, extensions, dirs); if (result.get(bes[0]) != null) { List<File> res = result.get(bes[0]); if (res.size() > 0) { filepath = res.get(0).getPath(); int index = filepath.lastIndexOf('.'); if ((index >= 0) && (index < filepath.length()-1)) { String extension = filepath.substring(index+1); ExternalFileType type = Globals.prefs.getExternalFileTypeByExt(extension); if (type != null) { try { Util.openExternalFileAnyFormat(metaData, filepath, type); output(Globals.lang("External viewer called") + "."); return; } catch (IOException ex) { output(Globals.lang("Error") + ": " + ex.getMessage()); } } } // TODO: add code for opening the file } } /*String basefile; Object key = bes[0].getField(BibtexFields.KEY_FIELD); if (key != null) { basefile = key.toString(); final ExternalFileType[] types = Globals.prefs.getExternalFileTypeSelection(); final String sep = System.getProperty("file.separator"); String dir = metaData.getFileDirectory(GUIGlobals.FILE_FIELD); if ((dir != null) && (dir.length() > 0)) { if (dir.endsWith(sep)) { dir = dir.substring(0, dir.length() - sep.length()); } for (int i = 0; i < types.length; i++) { String found = Util.findPdf(basefile, types[i].getExtension(), dir, new OpenFileFilter("." + types[i].getExtension())); if (found != null) { filepath = dir + sep + found; break; } } } }*/ } } if (filepath != null) { //output(Globals.lang("Calling external viewer...")); try { Util.openExternalViewer(metaData(), filepath, field); output(Globals.lang("External viewer called") + "."); } catch (IOException ex) { output(Globals.lang("Error") + ": " + ex.getMessage()); } } else output(Globals.lang( "No pdf or ps defined, and no file matching Bibtex key found") + "."); } else output(Globals.lang("No entries or multiple entries selected.")); } }).start(); } }); actions.put("addFileLink", new AttachFileAction(this)); actions.put("openExternalFile", new BaseAction() { public void action() { (new Thread() { public void run() { BibtexEntry[] bes = mainTable.getSelectedEntries(); String field = GUIGlobals.FILE_FIELD; if ((bes != null) && (bes.length == 1)) { Object link = bes[0].getField(field); if (link == null) { runCommand("openFile"); // Fall back on PDF/PS fields??? return; } FileListTableModel tableModel = new FileListTableModel(); tableModel.setContent((String)link); if (tableModel.getRowCount() == 0) { runCommand("openFile"); // Fall back on PDF/PS fields??? return; } FileListEntry flEntry = tableModel.getEntry(0); ExternalFileMenuItem item = new ExternalFileMenuItem (frame(), bes[0], "", flEntry.getLink(), flEntry.getType().getIcon(), metaData(), flEntry.getType()); item.openLink(); } else output(Globals.lang("No entries or multiple entries selected.")); } }).start(); } }); actions.put("openUrl", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); String field = "doi"; if ((bes != null) && (bes.length == 1)) { Object link = bes[0].getField("doi"); if (bes[0].getField("url") != null) { link = bes[0].getField("url"); field = "url"; } if (link != null) { //output(Globals.lang("Calling external viewer...")); try { Util.openExternalViewer(metaData(), link.toString(), field); output(Globals.lang("External viewer called")+"."); } catch (IOException ex) { output(Globals.lang("Error") + ": " + ex.getMessage()); } } else { // No URL or DOI found in the "url" and "doi" fields. // Look for web links in the "file" field as a fallback: FileListEntry entry = null; FileListTableModel tm = new FileListTableModel(); tm.setContent(bes[0].getField("file")); for (int i=0; i< tm.getRowCount(); i++) { FileListEntry flEntry = tm.getEntry(i); if (flEntry.getType().getName().toLowerCase().equals("url") || flEntry.getType().getName().toLowerCase().equals("ps")) { entry = flEntry; break; } } if (entry != null) { try { Util.openExternalFileAnyFormat(metaData, entry.getLink(), entry.getType()); output(Globals.lang("External viewer called") + "."); } catch (IOException e) { output(Globals.lang("Could not open link")); e.printStackTrace(); } return; } else output(Globals.lang("No url defined")+"."); } } else output(Globals.lang("No entries or multiple entries selected.")); } }); actions.put("openSpires", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length == 1)) { Object link = null; if (bes[0].getField("eprint") != null) link = SPIRESFetcher.constructUrlFromEprint(bes[0].getField("eprint").toString()); else if (bes[0].getField("slaccitation") != null) link = SPIRESFetcher.constructUrlFromSlaccitation(bes[0].getField("slaccitation").toString()); if (link != null) { //output(Globals.lang("Calling external viewer...")); try { Util.openExternalViewer(metaData(), link.toString(), "url"); output(Globals.lang("External viewer called")+"."); } catch (IOException ex) { output(Globals.lang("Error") + ": " + ex.getMessage()); } } else output(Globals.lang("No url defined")+"."); } else output(Globals.lang("No entries or multiple entries selected.")); } }); /* * It looks like this action was not being supported for SPIRES anyway * so we don't bother to implement it. actions.put("openInspire", new BaseAction() { public void action() { BibtexEntry[] bes = mainTable.getSelectedEntries(); if ((bes != null) && (bes.length == 1)) { Object link = null; if (bes[0].getField("eprint") != null) link = INSPIREFetcher.constructUrlFromEprint(bes[0].getField("eprint").toString()); else if (bes[0].getField("slaccitation") != null) link = INSPIREFetcher.constructUrlFromSlaccitation(bes[0].getField("slaccitation").toString()); if (link != null) { //output(Globals.lang("Calling external viewer...")); try { Util.openExternalViewer(metaData(), link.toString(), "url"); output(Globals.lang("External viewer called")+"."); } catch (IOException ex) { output(Globals.lang("Error") + ": " + ex.getMessage()); } } else output(Globals.lang("No url defined")+"."); } else output(Globals.lang("No entries or multiple entries selected.")); } }); */ actions.put("replaceAll", new BaseAction() { public void action() { ReplaceStringDialog rsd = new ReplaceStringDialog(frame); rsd.setVisible(true); if (!rsd.okPressed()) return; int counter = 0; NamedCompound ce = new NamedCompound(Globals.lang("Replace string")); if (!rsd.selOnly()) { for (BibtexEntry entry : database.getEntries()){ counter += rsd.replace(entry, ce); } } else { BibtexEntry[] bes = mainTable.getSelectedEntries(); for (int i=0; i<bes.length; i++) counter += rsd.replace(bes[i], ce); } output(Globals.lang("Replaced")+" "+counter+" "+ Globals.lang(counter==1?"occurence":"occurences")+"."); if (counter > 0) { ce.end(); undoManager.addEdit(ce); markBaseChanged(); } } }); actions.put("dupliCheck", new BaseAction() { public void action() { DuplicateSearch ds = new DuplicateSearch(BasePanel.this); ds.start(); } }); /*actions.put("strictDupliCheck", new BaseAction() { public void action() { StrictDuplicateSearch ds = new StrictDuplicateSearch(BasePanel.this); ds.start(); } });*/ actions.put("plainTextImport", new BaseAction() { public void action() { // get Type of new entry EntryTypeDialog etd = new EntryTypeDialog(frame); Util.placeDialog(etd, BasePanel.this); etd.setVisible(true); BibtexEntryType tp = etd.getChoice(); if (tp == null) return; String id = Util.createNeutralId(); BibtexEntry bibEntry = new BibtexEntry(id, tp) ; TextInputDialog tidialog = new TextInputDialog(frame, BasePanel.this, "import", true, bibEntry) ; Util.placeDialog(tidialog, BasePanel.this); tidialog.setVisible(true); if (tidialog.okPressed()) { Util.setAutomaticFields(Arrays.asList(new BibtexEntry[] {bibEntry}), false, false, false); insertEntry(bibEntry) ; } } }); // The action starts the "import from plain text" dialog /*actions.put("importPlainText", new BaseAction() { public void action() { BibtexEntry bibEntry = null ; // try to get the first marked entry BibtexEntry[] bes = entryTable.getSelectedEntries(); if ((bes != null) && (bes.length > 0)) bibEntry = bes[0] ; if (bibEntry != null) { // Create an UndoableInsertEntry object. undoManager.addEdit(new UndoableInsertEntry(database, bibEntry, BasePanel.this)); TextInputDialog tidialog = new TextInputDialog(frame, BasePanel.this, "import", true, bibEntry) ; Util.placeDialog(tidialog, BasePanel.this); tidialog.setVisible(true); if (tidialog.okPressed()) { output(Globals.lang("changed ")+" '" +bibEntry.getType().getName().toLowerCase()+"' " +Globals.lang("entry")+"."); refreshTable(); int row = tableModel.getNumberFromName(bibEntry.getId()); entryTable.clearSelection(); entryTable.scrollTo(row); markBaseChanged(); // The database just changed. if (Globals.prefs.getBoolean("autoOpenForm")) { showEntry(bibEntry); } } } } }); */ actions.put("markEntries", new AbstractWorker() { private int besLength = -1; public void run() { NamedCompound ce = new NamedCompound(Globals.lang("Mark entries")); BibtexEntry[] bes = mainTable.getSelectedEntries(); besLength = bes.length; for (int i=0; i<bes.length; i++) { Util.markEntry(bes[i], 1, true, ce); } ce.end(); undoManager.addEdit(ce); } public void update() { markBaseChanged(); output(Globals.lang("Marked selected")+" "+Globals.lang(besLength>0?"entry":"entries")); } }); actions.put("unmarkEntries", new BaseAction() { public void action() { try { NamedCompound ce = new NamedCompound(Globals.lang("Unmark entries")); BibtexEntry[] bes = mainTable.getSelectedEntries(); if (bes == null) return; for (int i=0; i<bes.length; i++) { Util.unmarkEntry(bes[i], false, database, ce); } ce.end(); undoManager.addEdit(ce); markBaseChanged(); output(Globals.lang("Unmarked selected")+" "+Globals.lang(bes.length>0?"entry":"entries")); } catch (Throwable ex) { ex.printStackTrace(); } } }); actions.put("unmarkAll", new BaseAction() { public void action() { NamedCompound ce = new NamedCompound(Globals.lang("Unmark all")); for (BibtexEntry be : database.getEntries()){ Util.unmarkEntry(be, false, database, ce); } ce.end(); undoManager.addEdit(ce); markBaseChanged(); } }); actions.put(Relevance.getInstance().getValues().get(0).getActionName(), new SpecialFieldAction(frame, Relevance.getInstance(), Relevance.getInstance().getValues().get(0).getFieldValue(), true, Globals.lang("Marked entries as relevant"), "Marked %0 entries as relevant")); actions.put(Quality.getInstance().getValues().get(0).getActionName(), new SpecialFieldAction(frame, Quality.getInstance(), Quality.getInstance().getValues().get(0).getFieldValue(), true, Globals.lang("Marked entries' quality as good"), "Set quality of %0 entries to good")); for (SpecialFieldValue prio: Priority.getInstance().getValues()) { actions.put(prio.getActionName(), prio.getAction(this.frame)); } for (SpecialFieldValue prio: Rank.getInstance().getValues()) { actions.put(prio.getActionName(), prio.getAction(this.frame)); } actions.put("togglePreview", new BaseAction() { public void action() { boolean enabled = !Globals.prefs.getBoolean("previewEnabled"); Globals.prefs.putBoolean("previewEnabled", enabled); frame.setPreviewActive(enabled); frame.previewToggle.setSelected(enabled); } }); actions.put("toggleHighlightGroupsMatchingAny", new BaseAction() { public void action() { boolean enabled = !Globals.prefs.getBoolean("highlightGroupsMatchingAny"); Globals.prefs.putBoolean("highlightGroupsMatchingAny", enabled); frame.highlightAny.setSelected(enabled); if (enabled) { frame.highlightAll.setSelected(false); Globals.prefs.putBoolean("highlightGroupsMatchingAll", false); } // ping the listener so it updates: groupsHighlightListener.listChanged(null); } }); actions.put("toggleHighlightGroupsMatchingAll", new BaseAction() { public void action() { boolean enabled = !Globals.prefs.getBoolean("highlightGroupsMatchingAll"); Globals.prefs.putBoolean("highlightGroupsMatchingAll", enabled); frame.highlightAll.setSelected(enabled); if (enabled) { frame.highlightAny.setSelected(false); Globals.prefs.putBoolean("highlightGroupsMatchingAny", false); } // ping the listener so it updates: groupsHighlightListener.listChanged(null); } }); actions.put("switchPreview", new BaseAction() { public void action() { selectionListener.switchPreview(); } }); actions.put("manageSelectors", new BaseAction() { public void action() { ContentSelectorDialog2 csd = new ContentSelectorDialog2 (frame, frame, BasePanel.this, false, metaData, null); Util.placeDialog(csd, frame); csd.setVisible(true); } }); actions.put("exportToClipboard", new ExportToClipboardAction(frame, database())); actions.put("sendAsEmail", new SendAsEMailAction(frame)); actions.put("writeXMP", new WriteXMPAction(this)); actions.put("abbreviateIso", new AbbreviateAction(this, true)); actions.put("abbreviateMedline", new AbbreviateAction(this, false)); actions.put("unabbreviate", new UnabbreviateAction(this)); actions.put("autoSetPdf", new AutoSetExternalFileForEntries(this, "pdf")); actions.put("autoSetPs", new AutoSetExternalFileForEntries(this, "ps")); actions.put("autoSetFile", new SynchronizeFileField(this)); actions.put("back", new BaseAction() { public void action() throws Throwable { back(); } }); actions.put("forward", new BaseAction() { public void action() throws Throwable { forward(); } }); actions.put("resolveDuplicateKeys", new SearchFixDuplicateLabels(this)); //actions.put("downloadFullText", new FindFullTextAction(this)); } /** * This method is called from JabRefFrame is a database specific * action is requested by the user. Runs the command if it is * defined, or prints an error message to the standard error * stream. * * @param _command The name of the command to run. */ public void runCommand(String _command) { final String command = _command; //(new Thread() { // public void run() { if (actions.get(command) == null) Util.pr("No action defined for'" + command + "'"); else { Object o = actions.get(command); try { if (o instanceof BaseAction) ((BaseAction)o).action(); else { // This part uses Spin's features: Worker wrk = ((AbstractWorker)o).getWorker(); // The Worker returned by getWorker() has been wrapped // by Spin.off(), which makes its methods be run in // a different thread from the EDT. CallBack clb = ((AbstractWorker)o).getCallBack(); ((AbstractWorker)o).init(); // This method runs in this same thread, the EDT. // Useful for initial GUI actions, like printing a message. // The CallBack returned by getCallBack() has been wrapped // by Spin.over(), which makes its methods be run on // the EDT. wrk.run(); // Runs the potentially time-consuming action // without freezing the GUI. The magic is that THIS line // of execution will not continue until run() is finished. clb.update(); // Runs the update() method on the EDT. } } catch (Throwable ex) { // If the action has blocked the JabRefFrame before crashing, we need to unblock it. // The call to unblock will simply hide the glasspane, so there is no harm in calling // it even if the frame hasn't been blocked. frame.unblock(); ex.printStackTrace(); } } // } //}).start(); } private boolean saveDatabase(File file, boolean selectedOnly, String encoding) throws SaveException { SaveSession session; frame.block(); try { if (!selectedOnly) session = FileActions.saveDatabase(database, metaData, file, Globals.prefs, false, false, encoding, false); else session = FileActions.savePartOfDatabase(database, metaData, file, Globals.prefs, mainTable.getSelectedEntries(), encoding); } catch (UnsupportedCharsetException ex2) { JOptionPane.showMessageDialog(frame, Globals.lang("Could not save file. " +"Character encoding '%0' is not supported.", encoding), Globals.lang("Save database"), JOptionPane.ERROR_MESSAGE); throw new SaveException("rt"); } catch (SaveException ex) { if (ex.specificEntry()) { // Error occured during processing of // be. Highlight it: int row = mainTable.findEntry(ex.getEntry()), topShow = Math.max(0, row-3); mainTable.setRowSelectionInterval(row, row); mainTable.scrollTo(topShow); showEntry(ex.getEntry()); } else ex.printStackTrace(); JOptionPane.showMessageDialog (frame, Globals.lang("Could not save file") +".\n"+ex.getMessage(), Globals.lang("Save database"), JOptionPane.ERROR_MESSAGE); throw new SaveException("rt"); } finally { frame.unblock(); } boolean commit = true; if (!session.getWriter().couldEncodeAll()) { DefaultFormBuilder builder = new DefaultFormBuilder(new FormLayout("left:pref, 4dlu, fill:pref", "")); JTextArea ta = new JTextArea(session.getWriter().getProblemCharacters()); ta.setEditable(false); builder.append(Globals.lang("The chosen encoding '%0' could not encode the following characters: ", session.getEncoding())); builder.append(ta); builder.append(Globals.lang("What do you want to do?")); String tryDiff = Globals.lang("Try different encoding"); int answer = JOptionPane.showOptionDialog(frame, builder.getPanel(), Globals.lang("Save database"), JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, new String[] {Globals.lang("Save"), tryDiff, Globals.lang("Cancel")}, tryDiff); if (answer == JOptionPane.NO_OPTION) { // The user wants to use another encoding. Object choice = JOptionPane.showInputDialog(frame, Globals.lang("Select encoding"), Globals.lang("Save database"), JOptionPane.QUESTION_MESSAGE, null, Globals.ENCODINGS, encoding); if (choice != null) { String newEncoding = (String)choice; return saveDatabase(file, selectedOnly, newEncoding); } else commit = false; } else if (answer == JOptionPane.CANCEL_OPTION) commit = false; } try { if (commit) { session.commit(); this.encoding = encoding; // Make sure to remember which encoding we used. } else session.cancel(); } catch (IOException e) { e.printStackTrace(); } return commit; } /** * This method is called from JabRefFrame when the user wants to * create a new entry. If the argument is null, the user is * prompted for an entry type. * * @param type The type of the entry to create. * @return The newly created BibtexEntry or null the operation was canceled by the user. */ public BibtexEntry newEntry(BibtexEntryType type) { if (type == null) { // Find out what type is wanted. EntryTypeDialog etd = new EntryTypeDialog(frame); // We want to center the dialog, to make it look nicer. Util.placeDialog(etd, frame); etd.setVisible(true); type = etd.getChoice(); } if (type != null) { // Only if the dialog was not cancelled. String id = Util.createNeutralId(); final BibtexEntry be = new BibtexEntry(id, type); try { database.insertEntry(be); // Set owner/timestamp if options are enabled: ArrayList<BibtexEntry> list = new ArrayList<BibtexEntry>(); list.add(be); Util.setAutomaticFields(list, true, true, false); // Create an UndoableInsertEntry object. undoManager.addEdit(new UndoableInsertEntry(database, be, BasePanel.this)); output(Globals.lang("Added new")+" '"+type.getName().toLowerCase()+"' " +Globals.lang("entry")+"."); // We are going to select the new entry. Before that, make sure that we are in // show-entry mode. If we aren't already in that mode, enter the WILL_SHOW_EDITOR // mode which makes sure the selection will trigger display of the entry editor // and adjustment of the splitter. if (mode != SHOWING_EDITOR) { mode = WILL_SHOW_EDITOR; } int row = mainTable.findEntry(be); if (row >= 0) highlightEntry(be); // Selects the entry. The selection listener will open the editor. else { // The entry is not visible in the table, perhaps due to a filtering search // or group selection. Show the entry editor anyway: showEntry(be); } markBaseChanged(); // The database just changed. new FocusRequester(getEntryEditor(be)); //Add the new entry to the group(s) selected in the Group Panel addToSelectedGroup(be); // Set Self-Created entries to have a high quality be.setField("quality", "1"); return be; } catch (KeyCollisionException ex) { Util.pr(ex.getMessage()); } } return null; } /** * This method is called to add a new entry to a group (or a set of groups) * in case the Group View is selected and one or more groups are marked * @param bibEntry The new entry. */ private void addToSelectedGroup(final BibtexEntry bibEntry) { if (Globals.prefs.getBoolean("autoAssignGroup")){ if (frame.groupToggle.isSelected()){ BibtexEntry[] entries = {bibEntry}; TreePath[] selection = frame.groupSelector.getGroupsTree().getSelectionPaths(); if (selection != null) { // it is possible that the user selected nothing. Therefore, checked for "!= null" for (TreePath tree : selection){ ((GroupTreeNode)(tree.getLastPathComponent())).addToGroup(entries); } } this.updateEntryEditorIfShowing(); this.getGroupSelector().valueChanged(null); } } } /** * This method is called from JabRefFrame when the user wants to * create a new entry. * @param bibEntry The new entry. */ public void insertEntry(BibtexEntry bibEntry) { if (bibEntry != null) { try { database.insertEntry(bibEntry) ; if (Globals.prefs.getBoolean("useOwner")) // Set owner field to default value Util.setAutomaticFields(bibEntry, true, true); // Create an UndoableInsertEntry object. undoManager.addEdit(new UndoableInsertEntry(database, bibEntry, BasePanel.this)); output(Globals.lang("Added new")+" '" +bibEntry.getType().getName().toLowerCase()+"' " +Globals.lang("entry")+"."); markBaseChanged(); // The database just changed. if (Globals.prefs.getBoolean("autoOpenForm")) { selectionListener.editSignalled(bibEntry); } highlightEntry(bibEntry); } catch (KeyCollisionException ex) { Util.pr(ex.getMessage()); } } } public void updateTableFont() { mainTable.updateFont(); } public void createMainTable() { //Comparator comp = new FieldComparator("author"); GlazedEntrySorter eventList = new GlazedEntrySorter(database.getEntryMap()); // Must initialize sort columns somehow: database.addDatabaseChangeListener(eventList); database.addDatabaseChangeListener(SpecialFieldDatabaseChangeListener.getInstance()); groupFilterList = new FilterList<BibtexEntry>(eventList.getTheList(), NoSearchMatcher.INSTANCE); searchFilterList = new FilterList<BibtexEntry>(groupFilterList, NoSearchMatcher.INSTANCE); //final SortedList sortedList = new SortedList(searchFilterList, null); tableFormat = new MainTableFormat(this); tableFormat.updateTableFormat(); //EventTableModel tableModel = new EventTableModel(sortedList, tableFormat); mainTable = new MainTable(tableFormat, searchFilterList, frame, this); selectionListener = new MainTableSelectionListener(this, mainTable); mainTable.updateFont(); mainTable.addSelectionListener(selectionListener); mainTable.addMouseListener(selectionListener); mainTable.addKeyListener(selectionListener); mainTable.addFocusListener(selectionListener); // Add the listener that will take care of highlighting groups as the selection changes: groupsHighlightListener = new ListEventListener<BibtexEntry>() { public void listChanged(ListEvent<BibtexEntry> listEvent) { if (Globals.prefs.getBoolean("highlightGroupsMatchingAny")) getGroupSelector().showMatchingGroups( mainTable.getSelectedEntries(), false); else if (Globals.prefs.getBoolean("highlightGroupsMatchingAll")) getGroupSelector().showMatchingGroups( mainTable.getSelectedEntries(), true); else // no highlight getGroupSelector().showMatchingGroups(null, true); } }; mainTable.addSelectionListener(groupsHighlightListener); mainTable.getActionMap().put("cut", new AbstractAction() { public void actionPerformed(ActionEvent e) { try { runCommand("cut"); } catch (Throwable ex) { ex.printStackTrace(); } } }); mainTable.getActionMap().put("copy", new AbstractAction() { public void actionPerformed(ActionEvent e) { try { runCommand("copy"); } catch (Throwable ex) { ex.printStackTrace(); } } }); mainTable.getActionMap().put("paste", new AbstractAction() { public void actionPerformed(ActionEvent e) { try { runCommand("paste"); } catch (Throwable ex) { ex.printStackTrace(); } } }); mainTable.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { final int keyCode = e.getKeyCode(); final TreePath path = frame.groupSelector.getSelectionPath(); final GroupTreeNode node = path == null ? null : (GroupTreeNode) path.getLastPathComponent(); if (e.isControlDown()) { switch (keyCode) { // The up/down/left/rightkeystrokes are displayed in the // GroupSelector's popup menu, so if they are to be changed, // edit GroupSelector.java accordingly! case KeyEvent.VK_UP: e.consume(); if (node != null) frame.groupSelector.moveNodeUp(node, true); break; case KeyEvent.VK_DOWN: e.consume(); if (node != null) frame.groupSelector.moveNodeDown(node, true); break; case KeyEvent.VK_LEFT: e.consume(); if (node != null) frame.groupSelector.moveNodeLeft(node, true); break; case KeyEvent.VK_RIGHT: e.consume(); if (node != null) frame.groupSelector.moveNodeRight(node, true); break; case KeyEvent.VK_PAGE_DOWN: frame.nextTab.actionPerformed(null); e.consume(); break; case KeyEvent.VK_PAGE_UP: frame.prevTab.actionPerformed(null); e.consume(); break; } } else if (keyCode == KeyEvent.VK_ENTER){ e.consume(); try { runCommand("edit"); } catch (Throwable ex) { ex.printStackTrace(); } } } }); } public void setupMainPanel() { //System.out.println("setupMainPanel"); //splitPane = new com.jgoodies.uif_lite.component.UIFSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane.setDividerSize(GUIGlobals.SPLIT_PANE_DIVIDER_SIZE); // We replace the default FocusTraversalPolicy with a subclass // that only allows FieldEditor components to gain keyboard focus, // if there is an entry editor open. /*splitPane.setFocusTraversalPolicy(new LayoutFocusTraversalPolicy() { protected boolean accept(Component c) { Util.pr("jaa"); if (showing == null) return super.accept(c); else return (super.accept(c) && (c instanceof FieldEditor)); } });*/ createMainTable(); for (EntryEditor ee : entryEditors.values()) { ee.validateAllFields(); } splitPane.setTopComponent(mainTable.getPane()); //setupTable(); // If an entry is currently being shown, make sure it stays shown, // otherwise set the bottom component to null. if (mode == SHOWING_PREVIEW) { mode = SHOWING_NOTHING; int row = mainTable.findEntry(currentPreview.entry); if (row >= 0) mainTable.setRowSelectionInterval(row, row); } else if (mode == SHOWING_EDITOR) { mode = SHOWING_NOTHING; /*int row = mainTable.findEntry(currentEditor.entry); if (row >= 0) mainTable.setRowSelectionInterval(row, row); */ //showEntryEditor(currentEditor); } else splitPane.setBottomComponent(null); setLayout(new BorderLayout()); removeAll(); add(splitPane, BorderLayout.CENTER); // Set up name autocompleter for search: instantiateSearchAutoCompleter(); // Set up AutoCompleters for this panel: if (Globals.prefs.getBoolean("autoComplete")) { instantiateAutoCompleters(); } splitPane.revalidate(); revalidate(); repaint(); } public void updateSearchManager() { frame.getSearchManager().setAutoCompleteListener(searchCompleteListener); } public HashMap<String, AbstractAutoCompleter> getAutoCompleters() { return autoCompleters; } public AbstractAutoCompleter getAutoCompleter(String fieldName) { return autoCompleters.get(fieldName); } private void instantiateSearchAutoCompleter() { //if (!Globals.prefs.getBoolean("searchAutoComplete")) // return; searchCompleter = new NameFieldAutoCompleter(new String[] {"author", "editor"}, true); HashMap<String, AbstractAutoCompleter> hm = new HashMap<String, AbstractAutoCompleter>(); hm.put("x", searchCompleter); for (BibtexEntry entry : database.getEntries()){ Util.updateCompletersForEntry(hm, entry); } searchCompleteListener = new AutoCompleteListener(searchCompleter); searchCompleteListener.setConsumeEnterKey(false); // So you don't have to press Enter twice } private void instantiateAutoCompleters() { autoCompleters.clear(); String[] completeFields = Globals.prefs.getStringArray("autoCompleteFields"); for (int i = 0; i < completeFields.length; i++) { String field = completeFields[i]; AbstractAutoCompleter autoCompleter = AutoCompleterFactory.getFor(field); autoCompleters.put(field, autoCompleter ); } for (BibtexEntry entry : database.getEntries()){ Util.updateCompletersForEntry(autoCompleters, entry); } addJournalListToAutoCompleter(); addContentSelectorValuesToAutoCompleters(); } /** * For all fields with both autocompletion and content selector, add content selector * values to the autocompleter list: */ public void addContentSelectorValuesToAutoCompleters() { for (String field : autoCompleters.keySet()) { AbstractAutoCompleter ac = autoCompleters.get(field); if (metaData.getData(Globals.SELECTOR_META_PREFIX + field) != null) { Vector<String> items = metaData.getData(Globals.SELECTOR_META_PREFIX + field); if (items != null) { Iterator<String> i = items.iterator(); while (i.hasNext()) ac.addWordToIndex(i.next()); } } } } /** * If an autocompleter exists for the "journal" field, add all * journal names in the journal abbreviation list to this autocompleter. */ public void addJournalListToAutoCompleter() { if (autoCompleters.containsKey("journal")) { AbstractAutoCompleter ac = autoCompleters.get("journal"); Set<String> journals = Globals.journalAbbrev.getJournals().keySet(); for (String journal : journals) ac.addWordToIndex(journal); } } /* public void refreshTable() { //System.out.println("hiding="+hidingNonHits+"\tlastHits="+lastSearchHits); // This method is called by EntryTypeForm when a field value is // stored. The table is scheduled for repaint. entryTable.assureNotEditing(); //entryTable.invalidate(); BibtexEntry[] bes = entryTable.getSelectedEntries(); if (hidingNonHits) tableModel.update(lastSearchHits); else tableModel.update(); //tableModel.remap(); if ((bes != null) && (bes.length > 0)) selectEntries(bes, 0); //long toc = System.currentTimeMillis(); // Util.pr("Refresh took: "+(toc-tic)+" ms"); } */ public void updatePreamble() { if (preambleEditor != null) preambleEditor.updatePreamble(); } public void assureStringDialogNotEditing() { if (stringDialog != null) stringDialog.assureNotEditing(); } public void updateStringDialog() { if (stringDialog != null) stringDialog.refreshTable(); } public void updateEntryPreviewToRow(BibtexEntry e) { } public void adjustSplitter() { int mode = getMode(); if (mode == SHOWING_PREVIEW) { splitPane.setDividerLocation(splitPane.getHeight()-Globals.prefs.getInt("previewPanelHeight")); } else { splitPane.setDividerLocation(splitPane.getHeight()-Globals.prefs.getInt("entryEditorHeight")); } } /** * Stores the source view in the entry editor, if one is open, has the source view * selected and the source has been edited. * @return boolean false if there is a validation error in the source panel, true otherwise. */ public boolean entryEditorAllowsChange() { Component c = splitPane.getBottomComponent(); if ((c != null) && (c instanceof EntryEditor)) { return ((EntryEditor)c).lastSourceAccepted(); } else return true; } public void moveFocusToEntryEditor() { Component c = splitPane.getBottomComponent(); if ((c != null) && (c instanceof EntryEditor)) { new FocusRequester(c); } } public boolean isShowingEditor() { return ((splitPane.getBottomComponent() != null) && (splitPane.getBottomComponent() instanceof EntryEditor)); } public void showEntry(final BibtexEntry be) { if (getShowing() == be) { if (splitPane.getBottomComponent() == null) { // This is the special occasion when showing is set to an // entry, but no entry editor is in fact shown. This happens // after Preferences dialog is closed, and it means that we // must make sure the same entry is shown again. We do this by // setting showing to null, and recursively calling this method. newEntryShowing(null); showEntry(be); } else { // The correct entry is already being shown. Make sure the editor // is updated. ((EntryEditor)splitPane.getBottomComponent()).updateAllFields(); } return; } EntryEditor form; int divLoc = -1; String visName = null; if (getShowing() != null) { if (isShowingEditor()) { visName = ((EntryEditor) splitPane.getBottomComponent()).getVisiblePanelName(); } } if (getShowing() != null) divLoc = splitPane.getDividerLocation(); if (entryEditors.containsKey(be.getType().getName())) { // We already have an editor for this entry type. form = entryEditors.get ((be.getType().getName())); form.switchTo(be); if (visName != null) form.setVisiblePanel(visName); splitPane.setBottomComponent(form); //highlightEntry(be); } else { // We must instantiate a new editor for this type. form = new EntryEditor(frame, BasePanel.this, be); if (visName != null) form.setVisiblePanel(visName); splitPane.setBottomComponent(form); //highlightEntry(be); entryEditors.put(be.getType().getName(), form); } if (divLoc > 0) { splitPane.setDividerLocation(divLoc); } else splitPane.setDividerLocation (splitPane.getHeight()-Globals.prefs.getInt("entryEditorHeight")); //new FocusRequester(form); //form.requestFocus(); newEntryShowing(be); setEntryEditorEnabled(true); // Make sure it is enabled. } /** * Get an entry editor ready to edit the given entry. If an appropriate editor is already * cached, it will be updated and returned. * @param entry The entry to be edited. * @return A suitable entry editor. */ public EntryEditor getEntryEditor(BibtexEntry entry) { EntryEditor form; if (entryEditors.containsKey(entry.getType().getName())) { EntryEditor visibleNow = currentEditor; // We already have an editor for this entry type. form = entryEditors.get ((entry.getType().getName())); // If the cached editor is not the same as the currently shown one, // make sure the current one stores its current edit: if ((visibleNow != null) && (form != visibleNow)) { visibleNow.storeCurrentEdit(); } form.switchTo(entry); //if (visName != null) // form.setVisiblePanel(visName); } else { // We must instantiate a new editor for this type. First make sure the old one // stores its last edit: storeCurrentEdit(); // Then start the new one: form = new EntryEditor(frame, BasePanel.this, entry); //if (visName != null) // form.setVisiblePanel(visName); entryEditors.put(entry.getType().getName(), form); } return form; } public EntryEditor getCurrentEditor() { return currentEditor; } /** * Sets the given entry editor as the bottom component in the split pane. If an entry editor already * was shown, makes sure that the divider doesn't move. * Updates the mode to SHOWING_EDITOR. * @param editor The entry editor to add. */ public void showEntryEditor(EntryEditor editor) { int oldSplitterLocation = -1; if (mode == SHOWING_EDITOR) Globals.prefs.putInt("entryEditorHeight", splitPane.getHeight() - splitPane.getDividerLocation()); else if (mode == SHOWING_PREVIEW) Globals.prefs.putInt("previewPanelHeight", splitPane.getHeight()-splitPane.getDividerLocation()); mode = SHOWING_EDITOR; currentEditor = editor; splitPane.setBottomComponent(editor); if (editor.getEntry() != getShowing()) newEntryShowing(editor.getEntry()); adjustSplitter(); } /** * Sets the given preview panel as the bottom component in the split panel. * Updates the mode to SHOWING_PREVIEW. * @param preview The preview to show. */ public void showPreview(PreviewPanel preview) { mode = SHOWING_PREVIEW; currentPreview = preview; splitPane.setBottomComponent(preview); } /** * Removes the bottom component. */ public void hideBottomComponent() { mode = SHOWING_NOTHING; splitPane.setBottomComponent(null); } /** * This method selects the given entry, and scrolls it into view in the table. * If an entryEditor is shown, it is given focus afterwards. */ public void highlightEntry(final BibtexEntry be) { //SwingUtilities.invokeLater(new Thread() { // public void run() { final int row = mainTable.findEntry(be); if (row >= 0) { mainTable.setRowSelectionInterval(row, row); //entryTable.setActiveRow(row); mainTable.ensureVisible(row); } // } //}); } /** * This method is called from an EntryEditor when it should be closed. We relay * to the selection listener, which takes care of the rest. * @param editor The entry editor to close. */ public void entryEditorClosing(EntryEditor editor) { // Store divider location for next time: Globals.prefs.putInt("entryEditorHeight", splitPane.getHeight()-splitPane.getDividerLocation()); selectionListener.entryEditorClosing(editor); } /** * This method selects the given enties. * If an entryEditor is shown, it is given focus afterwards. */ /*public void selectEntries(final BibtexEntry[] bes, final int toScrollTo) { SwingUtilities.invokeLater(new Thread() { public void run() { int rowToScrollTo = 0; entryTable.revalidate(); entryTable.clearSelection(); loop: for (int i=0; i<bes.length; i++) { if (bes[i] == null) continue loop; int row = tableModel.getNumberFromName(bes[i].getId()); if (i==toScrollTo) rowToScrollTo = row; if (row >= 0) entryTable.addRowSelectionIntervalQuietly(row, row); } entryTable.ensureVisible(rowToScrollTo); Component comp = splitPane.getBottomComponent(); //if (comp instanceof EntryEditor) // comp.requestFocus(); } }); } */ /** * Closes the entry editor if it is showing the given entry. * * @param be a <code>BibtexEntry</code> value */ public void ensureNotShowing(BibtexEntry be) { if ((mode == SHOWING_EDITOR) && (currentEditor.getEntry() == be)) { selectionListener.entryEditorClosing(currentEditor); } } public void updateEntryEditorIfShowing() { if (mode == SHOWING_EDITOR) { if (currentEditor.getType() != currentEditor.getEntry().getType()) { // The entry has changed type, so we must get a new editor. newEntryShowing(null); EntryEditor newEditor = getEntryEditor(currentEditor.getEntry()); showEntryEditor(newEditor); } else { currentEditor.updateAllFields(); currentEditor.updateSource(); } } } /** * If an entry editor is showing, make sure its currently focused field * stores its changes, if any. */ public void storeCurrentEdit() { if (isShowingEditor()) { EntryEditor editor = (EntryEditor)splitPane.getBottomComponent(); editor.storeCurrentEdit(); } } /** * This method iterates through all existing entry editors in this * BasePanel, telling each to update all its instances of * FieldContentSelector. This is done to ensure that the list of words * in each selector is up-to-date after the user has made changes in * the Manage dialog. */ public void updateAllContentSelectors() { for (Iterator<String> i=entryEditors.keySet().iterator(); i.hasNext();) { EntryEditor ed = entryEditors.get(i.next()); ed.updateAllContentSelectors(); } } public void rebuildAllEntryEditors() { for (Iterator<String> i=entryEditors.keySet().iterator(); i.hasNext();) { EntryEditor ed = entryEditors.get(i.next()); ed.rebuildPanels(); } } public void markBaseChanged() { baseChanged = true; // Put an asterix behind the file name to indicate the // database has changed. String oldTitle = frame.getTabTitle(this); if (!oldTitle.endsWith("*")) { frame.setTabTitle(this, oldTitle+"*", frame.getTabTooltip(this)); frame.setWindowTitle(); } // If the status line states that the base has been saved, we // remove this message, since it is no longer relevant. If a // different message is shown, we leave it. if (frame.statusLine.getText().startsWith(Globals.lang("Saved database"))); frame.output(" "); } public void markNonUndoableBaseChanged() { nonUndoableChange = true; markBaseChanged(); } public synchronized void markChangedOrUnChanged() { if (undoManager.hasChanged()) { if (!baseChanged) { markBaseChanged(); } } else if (baseChanged && !nonUndoableChange) { baseChanged = false; if (getFile() != null) frame.setTabTitle(BasePanel.this, getFile().getName(), getFile().getAbsolutePath()); else frame.setTabTitle(BasePanel.this, Globals.lang("untitled"), null); } frame.setWindowTitle(); } /** * Selects a single entry, and scrolls the table to center it. * * @param pos Current position of entry to select. * */ public void selectSingleEntry(int pos) { mainTable.clearSelection(); mainTable.addRowSelectionInterval(pos, pos); mainTable.scrollToCenter(pos, 0); } /* * * Selects all entries with a non-zero value in the field * @param field <code>String</code> field name. */ /* public void selectResults(String field) { LinkedList intervals = new LinkedList(); int prevStart = -1, prevToSel = 0; // First we build a list of intervals to select, without touching the table. for (int i = 0; i < entryTable.getRowCount(); i++) { String value = (String) (database.getEntryById (tableModel.getIdForRow(i))) .getField(field); if ( (value != null) && !value.equals("0")) { if (prevStart < 0) prevStart = i; prevToSel = i; } else if (prevStart >= 0) { intervals.add(new int[] {prevStart, prevToSel}); prevStart = -1; } } // Then select those intervals, if any. if (intervals.size() > 0) { entryTable.setSelectionListenerEnabled(false); entryTable.clearSelection(); for (Iterator i=intervals.iterator(); i.hasNext();) { int[] interval = (int[])i.next(); entryTable.addRowSelectionInterval(interval[0], interval[1]); } entryTable.setSelectionListenerEnabled(true); } */ public void setSearchMatcher(SearchMatcher matcher) { searchFilterList.setMatcher(matcher); showingSearch = true; } public void setGroupMatcher(Matcher<BibtexEntry> matcher) { groupFilterList.setMatcher(matcher); showingGroup = true; } public void stopShowingSearchResults() { searchFilterList.setMatcher(NoSearchMatcher.INSTANCE); showingSearch = false; } public void stopShowingGroup() { groupFilterList.setMatcher(NoSearchMatcher.INSTANCE); showingGroup = false; } /** * Query whether this BasePanel is in the mode where a float search result is shown. * @return true if showing float search, false otherwise. */ public boolean isShowingFloatSearch() { return mainTable.isShowingFloatSearch(); } /** * Query whether this BasePanel is in the mode where a filter search result is shown. * @return true if showing filter search, false otherwise. */ public boolean isShowingFilterSearch() { return showingSearch; } public BibtexDatabase getDatabase(){ return database ; } public void preambleEditorClosing() { preambleEditor = null; } public void stringsClosing() { stringDialog = null; } public void changeType(BibtexEntry entry, BibtexEntryType type) { changeType(new BibtexEntry[] {entry}, type); } public void changeType(BibtexEntryType type) { BibtexEntry[] bes = mainTable.getSelectedEntries(); changeType(bes, type); } public void changeType(BibtexEntry[] bes, BibtexEntryType type) { if ((bes == null) || (bes.length == 0)) { output("First select the entries you wish to change type "+ "for."); return; } if (bes.length > 1) { int choice = JOptionPane.showConfirmDialog (this, "Multiple entries selected. Do you want to change" +"\nthe type of all these to '"+type.getName()+"'?", "Change type", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (choice == JOptionPane.NO_OPTION) return; } NamedCompound ce = new NamedCompound(Globals.lang("change type")); for (int i=0; i<bes.length; i++) { ce.addEdit(new UndoableChangeType(bes[i], bes[i].getType(), type)); bes[i].setType(type); } output(Globals.lang("Changed type to")+" '"+type.getName()+"' " +Globals.lang("for")+" "+bes.length +" "+Globals.lang("entries")+"."); ce.end(); undoManager.addEdit(ce); markBaseChanged(); updateEntryEditorIfShowing(); } public boolean showDeleteConfirmationDialog(int numberOfEntries) { if (Globals.prefs.getBoolean("confirmDelete")) { String msg = Globals.lang("Really delete the selected") + " " + Globals.lang("entry") + "?", title = Globals.lang("Delete entry"); if (numberOfEntries > 1) { msg = Globals.lang("Really delete the selected") + " " + numberOfEntries + " " + Globals.lang("entries") + "?"; title = Globals.lang("Delete multiple entries"); } CheckBoxMessage cb = new CheckBoxMessage (msg, Globals.lang("Disable this confirmation dialog"), false); int answer = JOptionPane.showConfirmDialog(frame, cb, title, JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (cb.isSelected()) Globals.prefs.putBoolean("confirmDelete", false); return (answer == JOptionPane.YES_OPTION); } else return true; } /** * If the relevant option is set, autogenerate keys for all entries that are * lacking keys. */ public void autoGenerateKeysBeforeSaving() { if (Globals.prefs.getBoolean("generateKeysBeforeSaving")) { NamedCompound ce = new NamedCompound(Globals.lang("autogenerate keys")); boolean any = false; for (BibtexEntry bes : database.getEntries()){ String oldKey = bes.getCiteKey(); if ((oldKey == null) || (oldKey.equals(""))) { LabelPatternUtil.makeLabel(metaData, database, bes); ce.addEdit(new UndoableKeyChange(database, bes.getId(), null, bes.getField(BibtexFields.KEY_FIELD))); any = true; } } // Store undo information, if any: if (any) { ce.end(); undoManager.addEdit(ce); } } } /** * Activates or deactivates the entry preview, depending on the argument. * When deactivating, makes sure that any visible preview is hidden. * @param enabled */ public void setPreviewActive(boolean enabled) { selectionListener.setPreviewActive(enabled); } public void setSelectionListenerEnabled(boolean enabled) { selectionListener.setEnabled(enabled); } /** * Depending on whether a preview or an entry editor is showing, save the current * divider location in the correct preference setting. */ public void saveDividerLocation() { if (mode == SHOWING_PREVIEW) Globals.prefs.putInt("previewPanelHeight", splitPane.getHeight()-splitPane.getDividerLocation()); else if (mode == SHOWING_EDITOR) Globals.prefs.putInt("entryEditorHeight", splitPane.getHeight()-splitPane.getDividerLocation()); } class UndoAction extends BaseAction { public void action() { try { JComponent focused = Globals.focusListener.getFocused(); if ((focused != null) && (focused instanceof FieldEditor) && (focused.hasFocus())) { // User is currently editing a field: // Check if it is the preamble: if ((preambleEditor != null) && (focused == preambleEditor.getFieldEditor())) { preambleEditor.storeCurrentEdit(); } else storeCurrentEdit(); } String name = undoManager.getUndoPresentationName(); undoManager.undo(); markBaseChanged(); frame.output(name); } catch (CannotUndoException ex) { ex.printStackTrace(); frame.output(Globals.lang("Nothing to undo")+"."); } // After everything, enable/disable the undo/redo actions // appropriately. //updateUndoState(); //redoAction.updateRedoState(); markChangedOrUnChanged(); } } class RedoAction extends BaseAction { public void action() { try { JComponent focused = Globals.focusListener.getFocused(); if ((focused != null) && (focused instanceof FieldEditor) && (focused.hasFocus())) { // User is currently editing a field: storeCurrentEdit(); } String name = undoManager.getRedoPresentationName(); undoManager.redo(); markBaseChanged(); frame.output(name); } catch (CannotRedoException ex) { frame.output(Globals.lang("Nothing to redo")+"."); } // After everything, enable/disable the undo/redo actions // appropriately. //updateRedoState(); //undoAction.updateUndoState(); markChangedOrUnChanged(); } } // Method pertaining to the ClipboardOwner interface. public void lostOwnership(Clipboard clipboard, Transferable contents) {} public void setEntryEditorEnabled(boolean enabled) { if ((getShowing() != null) && (splitPane.getBottomComponent() instanceof EntryEditor)) { EntryEditor ed = (EntryEditor)splitPane.getBottomComponent(); if (ed.isEnabled() != enabled) ed.setEnabled(enabled); } } public String fileMonitorHandle() { return fileMonitorHandle; } public void fileUpdated() { if (saving) return; // We are just saving the file, so this message is most likely due //if (updatedExternally) { // return; //} // to bad timing. If not, we'll handle it on the next polling. //Util.pr("File '"+file.getPath()+"' has been modified."); updatedExternally = true; final ChangeScanner scanner = new ChangeScanner(frame, BasePanel.this); // Adding the sidepane component is Swing work, so we must do this in the Swing // thread: Thread t = new Thread() { public void run() { // Check if there is already a notification about external // changes: boolean hasAlready = sidePaneManager.hasComponent(FileUpdatePanel.NAME); if (hasAlready) { sidePaneManager.hideComponent(FileUpdatePanel.NAME); sidePaneManager.unregisterComponent(FileUpdatePanel.NAME); } FileUpdatePanel pan = new FileUpdatePanel(frame, BasePanel.this, sidePaneManager, getFile(), scanner); sidePaneManager.register(FileUpdatePanel.NAME, pan); sidePaneManager.show(FileUpdatePanel.NAME); //setUpdatedExternally(false); //scanner.displayResult(); } }; // Test: running scan automatically in background if ((BasePanel.this.getFile() != null) && !Util.waitForFileLock(BasePanel.this.getFile(), 10)) { // The file is locked even after the maximum wait. Do nothing. System.err.println("File updated externally, but change scan failed because the file is locked."); // Perturb the stored timestamp so successive checks are made: Globals.fileUpdateMonitor.perturbTimestamp(getFileMonitorHandle()); return; } scanner.changeScan(BasePanel.this.getFile()); try { scanner.join(); } catch (InterruptedException e) { e.printStackTrace(); } if (scanner.changesFound()) { SwingUtilities.invokeLater(t); } else { setUpdatedExternally(false); //System.out.println("No changes found."); } } public void fileRemoved() { Util.pr("File '"+getFile().getPath()+"' has been deleted."); } /** * Perform necessary cleanup when this BasePanel is closed. */ public void cleanUp() { if (fileMonitorHandle != null) Globals.fileUpdateMonitor.removeUpdateListener(fileMonitorHandle); // Check if there is a FileUpdatePanel for this BasePanel being shown. If so, // remove it: if (sidePaneManager.hasComponent("fileUpdate")) { FileUpdatePanel fup = (FileUpdatePanel)sidePaneManager.getComponent("fileUpdate"); if (fup.getPanel() == this) { sidePaneManager.hideComponent("fileUpdate"); } } } public void setUpdatedExternally(boolean b) { updatedExternally = b; } /** * Get an array containing the currently selected entries. * * @return An array containing the selected entries. */ public BibtexEntry[] getSelectedEntries() { return mainTable.getSelectedEntries(); } /** * Get the file where this database was last saved to or loaded from, if any. * * @return The relevant File, or null if none is defined. */ public File getFile() { return metaData.getFile(); } /** * Get a String containing a comma-separated list of the bibtex keys * of the selected entries. * * @return A comma-separated list of the keys of the selected entries. */ public String getKeysForSelection() { StringBuffer result = new StringBuffer(); String citeKey = "";//, message = ""; boolean first = true; for (BibtexEntry bes : mainTable.getSelected()){ citeKey = bes.getField(BibtexFields.KEY_FIELD); // if the key is empty we give a warning and ignore this entry if (citeKey == null || citeKey.equals("")) continue; if (first) { result.append(citeKey); first = false; } else { result.append(",").append(citeKey); } } return result.toString(); } public GroupSelector getGroupSelector() { return frame.groupSelector; } public boolean isUpdatedExternally() { return updatedExternally; } public String getFileMonitorHandle() { return fileMonitorHandle; } public void setFileMonitorHandle(String fileMonitorHandle) { this.fileMonitorHandle = fileMonitorHandle; } public SidePaneManager getSidePaneManager() { return sidePaneManager; } public void setNonUndoableChange(boolean nonUndoableChange) { this.nonUndoableChange = nonUndoableChange; } public void setBaseChanged(boolean baseChanged) { this.baseChanged = baseChanged; } public void setSaving(boolean saving) { this.saving = saving; } public boolean isSaving() { return saving; } public BibtexEntry getShowing() { return showing; } /** * Update the pointer to the currently shown entry in all cases where the user has * moved to a new entry, except when using Back and Forward commands. Also updates * history for Back command, and clears history for Forward command. * @param entry The entry that is now to be shown. */ public void newEntryShowing(BibtexEntry entry) { // If this call is the result of a Back or Forward operation, we must take // care not to make any history changes, since the necessary changes will // already have been done in the back() or forward() method: if (backOrForwardInProgress) { showing = entry; backOrForwardInProgress = false; setBackAndForwardEnabledState(); return; } nextEntries.clear(); if (entry != showing) { // Add the entry we are leaving to the history: if (showing != null) { previousEntries.add(showing); if (previousEntries.size() > GUIGlobals.MAX_BACK_HISTORY_SIZE) previousEntries.remove(0); } showing = entry; setBackAndForwardEnabledState(); } } /** * Go back (if there is any recorded history) and update the histories for * the Back and Forward commands. */ private void back() { if (previousEntries.size() > 0) { BibtexEntry toShow = previousEntries.get(previousEntries.size()-1); previousEntries.remove(previousEntries.size()-1); // Add the entry we are going back from to the Forward history: if (showing != null) nextEntries.add(showing); backOrForwardInProgress = true; // to avoid the history getting updated erroneously //showEntry(toShow); highlightEntry(toShow); } } private void forward() { if (nextEntries.size() > 0) { BibtexEntry toShow = nextEntries.get(nextEntries.size()-1); nextEntries.remove(nextEntries.size()-1); // Add the entry we are going forward from to the Back history: if (showing != null) previousEntries.add(showing); backOrForwardInProgress = true; // to avoid the history getting updated erroneously //showEntry(toShow); highlightEntry(toShow); } } public void setBackAndForwardEnabledState() { frame.back.setEnabled(previousEntries.size() > 0); frame.forward.setEnabled(nextEntries.size() > 0); } }
Removes obsolete imports at BasePanel
src/java/net/sf/jabref/BasePanel.java
Removes obsolete imports at BasePanel
<ide><path>rc/java/net/sf/jabref/BasePanel.java <ide> import java.awt.datatransfer.Transferable; <ide> import java.awt.datatransfer.UnsupportedFlavorException; <ide> import java.awt.event.ActionEvent; <del>import java.awt.event.ActionListener; <ide> import java.awt.event.KeyAdapter; <ide> import java.awt.event.KeyEvent; <ide> import java.io.File; <ide> import java.util.Map; <ide> import java.util.Set; <ide> import java.util.Vector; <del>import java.util.regex.Pattern; <del> <ide> import javax.swing.AbstractAction; <del>import javax.swing.JButton; <ide> import javax.swing.JComponent; <ide> import javax.swing.JFileChooser; <del>import javax.swing.JFrame; <ide> import javax.swing.JOptionPane; <ide> import javax.swing.JPanel; <ide> import javax.swing.JSplitPane; <ide> import net.sf.jabref.export.layout.Layout; <ide> import net.sf.jabref.export.layout.LayoutHelper; <ide> import net.sf.jabref.external.*; <del>import net.sf.jabref.groups.AddToGroupAction; <ide> import net.sf.jabref.groups.GroupSelector; <ide> import net.sf.jabref.groups.GroupTreeNode; <ide> import net.sf.jabref.gui.*; <ide> import net.sf.jabref.imports.AppendDatabaseAction; <ide> import net.sf.jabref.imports.BibtexParser; <ide> import net.sf.jabref.imports.SPIRESFetcher; <del>import net.sf.jabref.imports.INSPIREFetcher; <ide> import net.sf.jabref.journals.AbbreviateAction; <ide> import net.sf.jabref.journals.UnabbreviateAction; <ide> import net.sf.jabref.labelPattern.LabelPatternUtil; <ide> import net.sf.jabref.specialfields.Relevance; <ide> import net.sf.jabref.specialfields.SpecialFieldDatabaseChangeListener; <ide> import net.sf.jabref.specialfields.SpecialFieldValue; <del>import net.sf.jabref.specialfields.SpecialFieldsUtils; <ide> import net.sf.jabref.sql.DBConnectDialog; <ide> import net.sf.jabref.sql.DBStrings; <ide> import net.sf.jabref.sql.DbConnectAction; <ide> import net.sf.jabref.undo.CountingUndoManager; <ide> import net.sf.jabref.undo.NamedCompound; <ide> import net.sf.jabref.undo.UndoableChangeType; <del>import net.sf.jabref.undo.UndoableFieldChange; <ide> import net.sf.jabref.undo.UndoableInsertEntry; <ide> import net.sf.jabref.undo.UndoableKeyChange; <ide> import net.sf.jabref.undo.UndoableRemoveEntry;
Java
mit
678e336f89661f4504971989b032d17d6d72eb0d
0
welovecoding/editorconfig-netbeans,welovecoding/editorconfig-netbeans
package com.welovecoding.netbeans.plugin.editorconfig.processor.operation; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import org.netbeans.junit.NbTestCase; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; public class CharsetOperationTest extends NbTestCase { public CharsetOperationTest() { super("CharsetOperationTest"); } public void testSetup() throws FileNotFoundException, IOException, URISyntaxException { String path = "files/charsets/utf-8-bom.txt"; URL url = Thread.currentThread().getContextClassLoader().getResource(path); Path testFilePath = Paths.get(url.toURI()); FileObject fo = FileUtil.toFileObject(testFilePath.toFile()); assertEquals(fo.getName(), "utf-8-bom"); } }
src/test/java/com/welovecoding/netbeans/plugin/editorconfig/processor/operation/CharsetOperationTest.java
package com.welovecoding.netbeans.plugin.editorconfig.processor.operation; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.Test; import org.netbeans.junit.NbTestCase; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; public class CharsetOperationTest extends NbTestCase { public CharsetOperationTest() { super("CharsetOperationTest"); } @Test public void testSetup() throws FileNotFoundException, IOException, URISyntaxException { String path = "files/charsets/utf-8-bom.txt"; URL url = Thread.currentThread().getContextClassLoader().getResource(path); Path testFilePath = Paths.get(url.toURI()); FileObject fo = FileUtil.toFileObject(testFilePath.toFile()); assertEquals(fo.getName(), "utf-8-bom"); } }
Removed @Test
src/test/java/com/welovecoding/netbeans/plugin/editorconfig/processor/operation/CharsetOperationTest.java
Removed @Test
<ide><path>rc/test/java/com/welovecoding/netbeans/plugin/editorconfig/processor/operation/CharsetOperationTest.java <ide> import java.net.URL; <ide> import java.nio.file.Path; <ide> import java.nio.file.Paths; <del>import org.junit.Test; <ide> import org.netbeans.junit.NbTestCase; <ide> import org.openide.filesystems.FileObject; <ide> import org.openide.filesystems.FileUtil; <ide> super("CharsetOperationTest"); <ide> } <ide> <del> @Test <ide> public void testSetup() throws FileNotFoundException, IOException, URISyntaxException { <ide> String path = "files/charsets/utf-8-bom.txt"; <ide> URL url = Thread.currentThread().getContextClassLoader().getResource(path);
Java
mit
aa8da78685803780f7f84ddc55e8eb4dfe8b1b32
0
DefectiveMan/DidIt
package com.example.tylerpelaez.didit; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONObject; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; /** * Created by Stephen on 4/9/2017. */ public class Habit extends JSONObject implements Serializable { public String name; ArrayList<String> labels; ArrayList<String> descriptors; // Key is date, Value is descriptors HashMap<String, ArrayList<Descriptor>> log; public boolean everyOther; public HashMap<String,Boolean> weekdays; // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeString(name); // out.writeStringList(labels); // out.writeStringList(descriptors); // } // // public static final Parcelable.Creator<Habit> CREATOR = new Parcelable.Creator<Habit>() { // public Habit createFromParcel(Parcel in) { // return new Habit(in); // } // // public Habit[] newArray(int size) { // return new Habit[size]; // } // }; // // private Habit(Parcel in) { // name = in.readString(); // in.readStringList(labels); // in.readStringList(descriptors); // } public Habit(String n){ name = n; labels = new ArrayList<String>(); descriptors = new ArrayList<String>(); log = new HashMap<String, ArrayList<Descriptor>>(); everyOther = false; weekdays = new HashMap<String,Boolean>(); weekdays.put("Monday",false); weekdays.put("Tuesday",false); weekdays.put("Wednesday",false); weekdays.put("Thursday",false); weekdays.put("Friday",false); weekdays.put("Saturday",false); weekdays.put("Sunday",false); } public ArrayList<ArrayList<String>> getDescriptors(){ ArrayList<ArrayList<String>> desc = new ArrayList<ArrayList<String>>(); desc.add(labels); desc.add(descriptors); return desc; } void addDescriptor(String l, String d){ labels.add(l); descriptors.add(d); } void removeDescriptor(String l){ int loc = labels.indexOf(l); labels.remove(loc); descriptors.remove(loc); } void goalCompleted(ArrayList<Descriptor> desc){ SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy"); String today = sdf.format(Calendar.getInstance().get(Calendar.DATE)); log.put(today,desc); } void addWeekday(String d){ if(weekdays.containsKey(d)) { weekdays.put(d, true); } } void removeWeekday(String d){ if(weekdays.containsKey(d)) { weekdays.put(d, false); } } void setEveryOther(boolean v){ everyOther = v; } }
app/src/main/java/com/example/tylerpelaez/didit/Habit.java
package com.example.tylerpelaez.didit; import android.os.Parcel; import android.os.Parcelable; import org.json.JSONObject; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; /** * Created by Stephen on 4/9/2017. */ public class Habit extends JSONObject implements Serializable { public String name; ArrayList<String> labels; ArrayList<String> descriptors; // Key is date, Value is descriptors HashMap<String, ArrayList<Descriptor>> log; // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel out, int flags) { // out.writeString(name); // out.writeStringList(labels); // out.writeStringList(descriptors); // } // // public static final Parcelable.Creator<Habit> CREATOR = new Parcelable.Creator<Habit>() { // public Habit createFromParcel(Parcel in) { // return new Habit(in); // } // // public Habit[] newArray(int size) { // return new Habit[size]; // } // }; // // private Habit(Parcel in) { // name = in.readString(); // in.readStringList(labels); // in.readStringList(descriptors); // } public Habit(String n){ name = n; labels = new ArrayList<String>(); descriptors = new ArrayList<String>(); log = new HashMap<String, ArrayList<Descriptor>>(); } public ArrayList<ArrayList<String>> getDescriptors(){ ArrayList<ArrayList<String>> desc = new ArrayList<ArrayList<String>>(); desc.add(labels); desc.add(descriptors); return desc; } void addDescriptor(String l, String d){ labels.add(l); descriptors.add(d); } void removeDescriptor(String l){ int loc = labels.indexOf(l); labels.remove(loc); descriptors.remove(loc); } void goalCompleted(ArrayList<Descriptor> desc){ SimpleDateFormat sdf = new SimpleDateFormat("mm/dd/yyyy"); String today = sdf.format(Calendar.getInstance().get(Calendar.DATE)); log.put(today,desc); } }
Added day of week selection and every other day
app/src/main/java/com/example/tylerpelaez/didit/Habit.java
Added day of week selection and every other day
<ide><path>pp/src/main/java/com/example/tylerpelaez/didit/Habit.java <ide> ArrayList<String> descriptors; <ide> // Key is date, Value is descriptors <ide> HashMap<String, ArrayList<Descriptor>> log; <add> public boolean everyOther; <add> public HashMap<String,Boolean> weekdays; <ide> <ide> // @Override <ide> // public int describeContents() { <ide> labels = new ArrayList<String>(); <ide> descriptors = new ArrayList<String>(); <ide> log = new HashMap<String, ArrayList<Descriptor>>(); <add> everyOther = false; <add> weekdays = new HashMap<String,Boolean>(); <add> weekdays.put("Monday",false); <add> weekdays.put("Tuesday",false); <add> weekdays.put("Wednesday",false); <add> weekdays.put("Thursday",false); <add> weekdays.put("Friday",false); <add> weekdays.put("Saturday",false); <add> weekdays.put("Sunday",false); <ide> } <ide> <ide> public ArrayList<ArrayList<String>> getDescriptors(){ <ide> log.put(today,desc); <ide> } <ide> <add> void addWeekday(String d){ <add> if(weekdays.containsKey(d)) { <add> weekdays.put(d, true); <add> } <add> } <ide> <add> void removeWeekday(String d){ <add> if(weekdays.containsKey(d)) { <add> weekdays.put(d, false); <add> } <add> } <ide> <del> <add> void setEveryOther(boolean v){ <add> everyOther = v; <add> } <ide> }
Java
mit
0239f4e772a8990eb36f806501a08f8a7e1169c4
0
bcvsolutions/CzechIdMng,bcvsolutions/CzechIdMng,bcvsolutions/CzechIdMng,bcvsolutions/CzechIdMng
package eu.bcvsolutions.idm.acc.provisioning; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import org.junit.Test; import eu.bcvsolutions.idm.acc.domain.ProvisioningEventType; import eu.bcvsolutions.idm.acc.dto.SysProvisioningBreakItems; import eu.bcvsolutions.idm.test.api.AbstractUnitTest; /** * Tests for check synchronized block and multithread behavior with {@link SysProvisioningBreakItems} * * @author Ondrej Kopr * */ public class SysProvisioningBreakItemsTest extends AbstractUnitTest { @Test public void testAdd() throws InterruptedException { List<Thread> threads = new ArrayList<Thread>(); int maximumIteration = 10; CountDownLatch readyCounter = new CountDownLatch(maximumIteration); CountDownLatch lock = new CountDownLatch(1); CountDownLatch completeCounter = new CountDownLatch(maximumIteration); SysProvisioningBreakItems items = new SysProvisioningBreakItems(); for (int index = 0; index < maximumIteration; index++) { Thread thread = new Thread(new ItemsWorker(readyCounter, lock, completeCounter, new Callable<Void>() { @Override public Void call() throws Exception { items.addItem(ProvisioningEventType.UPDATE, System.currentTimeMillis()); return null; } })); thread.start(); // We need them for stop threads.add(thread); } List<Long> executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(0, executedItems.size()); // Wait on all thread readyCounter.await(); // Release all thread lock.countDown(); // Wait on all thread completeCounter.await(); executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(maximumIteration, executedItems.size()); interruptThreads(threads); } @Test public void testRemove() throws InterruptedException { List<Thread> threads = new ArrayList<Thread>(); int maximumIteration = 20; CountDownLatch readyCounter = new CountDownLatch(maximumIteration); CountDownLatch lock = new CountDownLatch(1); CountDownLatch completeCounter = new CountDownLatch(maximumIteration); SysProvisioningBreakItems items = new SysProvisioningBreakItems(); for (int index = 0; index < maximumIteration; index++) { items.addItem(ProvisioningEventType.UPDATE, Long.valueOf(1000 + index)); } for (int index = 0; index < maximumIteration; index++) { Thread thread = new Thread(new ItemsWorker(readyCounter, lock, completeCounter, new Callable<Void>() { @Override public Void call() throws Exception { items.removeOlderRecordsThan(ProvisioningEventType.UPDATE, Long.valueOf(100000)); return null; } })); thread.start(); // We need them for stop threads.add(thread); } List<Long> executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(maximumIteration, executedItems.size()); // Wait on all thread readyCounter.await(); // Release all thread lock.countDown(); // Wait on all thread completeCounter.await(); executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(0, executedItems.size()); interruptThreads(threads); } @Test public void testClear() throws InterruptedException { List<Thread> threads = new ArrayList<Thread>(); int maximumIteration = 10; CountDownLatch readyCounter = new CountDownLatch(maximumIteration); CountDownLatch lock = new CountDownLatch(1); CountDownLatch completeCounter = new CountDownLatch(maximumIteration); SysProvisioningBreakItems items = new SysProvisioningBreakItems(); for (int index = 0; index < maximumIteration; index++) { items.addItem(ProvisioningEventType.UPDATE, Long.valueOf(1000 + index)); } for (int index = 0; index < 1000; index++) { Thread thread = new Thread(new ItemsWorker(readyCounter, lock, completeCounter, new Callable<Void>() { @Override public Void call() throws Exception { items.clearRecords(ProvisioningEventType.UPDATE); return null; } })); thread.start(); // We need them for stop threads.add(thread); } List<Long> executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(maximumIteration, executedItems.size()); // Wait on all thread readyCounter.await(); // Release all thread lock.countDown(); // Wait on all thread completeCounter.await(); executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(0, executedItems.size()); } /** * Class that initialize that workers will be processed from barrier together. * * @author Ondrej Kopr * */ public class ItemsWorker implements Runnable { private CountDownLatch readyCounter; private CountDownLatch lock; private CountDownLatch completeCounter; private Callable<Void> func; public ItemsWorker(CountDownLatch readyCounter, CountDownLatch lock, CountDownLatch completeCounter, Callable<Void> func) { this.readyCounter = readyCounter; this.lock = lock; this.completeCounter = completeCounter; this.func = func; } @Override public void run() { // Count ready workers readyCounter.countDown(); try { // Wait for initializer lock.await(); // Call method func.call(); } catch (Exception e) { fail(e.getMessage()); } finally { // Complete counter, on this wait initializer completeCounter.countDown(); } } } /** * Interrupts all given threads. In java doesn't exists way how to stop thread. * * @param threads */ private void interruptThreads(List<Thread> threads) { assertNotNull(threads); assertFalse(threads.isEmpty()); // Stop method is deprecated threads.forEach(Thread::interrupt); } }
Realization/backend/acc/src/test/java/eu/bcvsolutions/idm/acc/provisioning/SysProvisioningBreakItemsTest.java
package eu.bcvsolutions.idm.acc.provisioning; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import org.junit.Test; import eu.bcvsolutions.idm.acc.domain.ProvisioningEventType; import eu.bcvsolutions.idm.acc.dto.SysProvisioningBreakItems; /** * Tests for check synchronized block and multithread behavior with {@link SysProvisioningBreakItems} * * @author Ondrej Kopr * */ public class SysProvisioningBreakItemsTest { @Test public void testAdd() throws InterruptedException { CountDownLatch readyCounter = new CountDownLatch(1000); CountDownLatch lock = new CountDownLatch(1); CountDownLatch completeCounter = new CountDownLatch(1000); SysProvisioningBreakItems items = new SysProvisioningBreakItems(); for (int index = 0; index < 1000; index++) { Thread thread = new Thread(new ItemsWorker(readyCounter, lock, completeCounter, new Callable<Void>() { @Override public Void call() throws Exception { items.addItem(ProvisioningEventType.UPDATE, System.currentTimeMillis()); return null; } })); thread.start(); } List<Long> executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(0, executedItems.size()); // Wait on all thread readyCounter.await(); // Release all thread lock.countDown(); // Wait on all thread completeCounter.await(); executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(1000, executedItems.size()); } @Test public void testRemove() throws InterruptedException { CountDownLatch readyCounter = new CountDownLatch(5000); CountDownLatch lock = new CountDownLatch(1); CountDownLatch completeCounter = new CountDownLatch(5000); SysProvisioningBreakItems items = new SysProvisioningBreakItems(); for (int index = 0; index < 5000; index++) { items.addItem(ProvisioningEventType.UPDATE, Long.valueOf(1000 + index)); } for (int index = 0; index < 5000; index++) { Thread thread = new Thread(new ItemsWorker(readyCounter, lock, completeCounter, new Callable<Void>() { @Override public Void call() throws Exception { items.removeOlderRecordsThan(ProvisioningEventType.UPDATE, Long.valueOf(100000)); return null; } })); thread.start(); } List<Long> executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(5000, executedItems.size()); // Wait on all thread readyCounter.await(); // Release all thread lock.countDown(); // Wait on all thread completeCounter.await(); executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(0, executedItems.size()); } @Test public void testClear() throws InterruptedException { CountDownLatch readyCounter = new CountDownLatch(1000); CountDownLatch lock = new CountDownLatch(1); CountDownLatch completeCounter = new CountDownLatch(1000); SysProvisioningBreakItems items = new SysProvisioningBreakItems(); for (int index = 0; index < 1000; index++) { items.addItem(ProvisioningEventType.UPDATE, Long.valueOf(1000 + index)); } for (int index = 0; index < 1000; index++) { Thread thread = new Thread(new ItemsWorker(readyCounter, lock, completeCounter, new Callable<Void>() { @Override public Void call() throws Exception { items.clearRecords(ProvisioningEventType.UPDATE); return null; } })); thread.start(); } List<Long> executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(1000, executedItems.size()); // Wait on all thread readyCounter.await(); // Release all thread lock.countDown(); // Wait on all thread completeCounter.await(); executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); assertEquals(0, executedItems.size()); } /** * Class that initialize that workers will be processed from barrier together. * * @author Ondrej Kopr * */ public class ItemsWorker implements Runnable { private CountDownLatch readyCounter; private CountDownLatch lock; private CountDownLatch completeCounter; private Callable<Void> func; public ItemsWorker(CountDownLatch readyCounter, CountDownLatch lock, CountDownLatch completeCounter, Callable<Void> func) { this.readyCounter = readyCounter; this.lock = lock; this.completeCounter = completeCounter; this.func = func; } @Override public void run() { // Count ready workers readyCounter.countDown(); try { // Wait for initializer lock.await(); // Call method func.call(); } catch (Exception e) { fail(e.getMessage()); } finally { // Complete counter, on this wait initializer completeCounter.countDown(); } } } }
#1673 change threads count
Realization/backend/acc/src/test/java/eu/bcvsolutions/idm/acc/provisioning/SysProvisioningBreakItemsTest.java
#1673 change threads count
<ide><path>ealization/backend/acc/src/test/java/eu/bcvsolutions/idm/acc/provisioning/SysProvisioningBreakItemsTest.java <ide> package eu.bcvsolutions.idm.acc.provisioning; <ide> <ide> import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertNotNull; <ide> import static org.junit.Assert.fail; <ide> <add>import java.util.ArrayList; <ide> import java.util.List; <ide> import java.util.concurrent.Callable; <ide> import java.util.concurrent.CountDownLatch; <ide> <ide> import eu.bcvsolutions.idm.acc.domain.ProvisioningEventType; <ide> import eu.bcvsolutions.idm.acc.dto.SysProvisioningBreakItems; <add>import eu.bcvsolutions.idm.test.api.AbstractUnitTest; <ide> <ide> /** <ide> * Tests for check synchronized block and multithread behavior with {@link SysProvisioningBreakItems} <ide> * @author Ondrej Kopr <ide> * <ide> */ <del>public class SysProvisioningBreakItemsTest { <add>public class SysProvisioningBreakItemsTest extends AbstractUnitTest { <ide> <ide> @Test <ide> public void testAdd() throws InterruptedException { <del> CountDownLatch readyCounter = new CountDownLatch(1000); <add> List<Thread> threads = new ArrayList<Thread>(); <add> int maximumIteration = 10; <add> <add> CountDownLatch readyCounter = new CountDownLatch(maximumIteration); <ide> CountDownLatch lock = new CountDownLatch(1); <del> CountDownLatch completeCounter = new CountDownLatch(1000); <add> CountDownLatch completeCounter = new CountDownLatch(maximumIteration); <ide> <ide> SysProvisioningBreakItems items = new SysProvisioningBreakItems(); <ide> <del> for (int index = 0; index < 1000; index++) { <add> for (int index = 0; index < maximumIteration; index++) { <ide> Thread thread = new Thread(new ItemsWorker(readyCounter, lock, completeCounter, new Callable<Void>() { <ide> @Override <ide> public Void call() throws Exception { <ide> } <ide> })); <ide> thread.start(); <add> // We need them for stop <add> threads.add(thread); <ide> } <ide> <ide> List<Long> executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); <ide> completeCounter.await(); <ide> <ide> executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); <del> assertEquals(1000, executedItems.size()); <del> <add> assertEquals(maximumIteration, executedItems.size()); <add> interruptThreads(threads); <ide> } <ide> <ide> @Test <ide> public void testRemove() throws InterruptedException { <del> CountDownLatch readyCounter = new CountDownLatch(5000); <add> List<Thread> threads = new ArrayList<Thread>(); <add> int maximumIteration = 20; <add> CountDownLatch readyCounter = new CountDownLatch(maximumIteration); <ide> CountDownLatch lock = new CountDownLatch(1); <del> CountDownLatch completeCounter = new CountDownLatch(5000); <add> CountDownLatch completeCounter = new CountDownLatch(maximumIteration); <ide> <ide> SysProvisioningBreakItems items = new SysProvisioningBreakItems(); <ide> <del> for (int index = 0; index < 5000; index++) { <add> for (int index = 0; index < maximumIteration; index++) { <ide> items.addItem(ProvisioningEventType.UPDATE, Long.valueOf(1000 + index)); <ide> } <ide> <del> for (int index = 0; index < 5000; index++) { <add> for (int index = 0; index < maximumIteration; index++) { <ide> Thread thread = new Thread(new ItemsWorker(readyCounter, lock, completeCounter, new Callable<Void>() { <ide> @Override <ide> public Void call() throws Exception { <ide> } <ide> })); <ide> thread.start(); <add> // We need them for stop <add> threads.add(thread); <ide> } <ide> <ide> List<Long> executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); <del> assertEquals(5000, executedItems.size()); <add> assertEquals(maximumIteration, executedItems.size()); <ide> <ide> // Wait on all thread <ide> readyCounter.await(); <ide> <ide> executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); <ide> assertEquals(0, executedItems.size()); <add> interruptThreads(threads); <ide> } <ide> <ide> @Test <ide> public void testClear() throws InterruptedException { <del> CountDownLatch readyCounter = new CountDownLatch(1000); <add> List<Thread> threads = new ArrayList<Thread>(); <add> int maximumIteration = 10; <add> CountDownLatch readyCounter = new CountDownLatch(maximumIteration); <ide> CountDownLatch lock = new CountDownLatch(1); <del> CountDownLatch completeCounter = new CountDownLatch(1000); <add> CountDownLatch completeCounter = new CountDownLatch(maximumIteration); <ide> <ide> SysProvisioningBreakItems items = new SysProvisioningBreakItems(); <ide> <del> for (int index = 0; index < 1000; index++) { <add> for (int index = 0; index < maximumIteration; index++) { <ide> items.addItem(ProvisioningEventType.UPDATE, Long.valueOf(1000 + index)); <ide> } <ide> <ide> } <ide> })); <ide> thread.start(); <add> // We need them for stop <add> threads.add(thread); <ide> } <ide> <ide> List<Long> executedItems = items.getExecutedItems(ProvisioningEventType.UPDATE); <del> assertEquals(1000, executedItems.size()); <add> assertEquals(maximumIteration, executedItems.size()); <ide> <ide> // Wait on all thread <ide> readyCounter.await(); <ide> } <ide> } <ide> } <add> <add> /** <add> * Interrupts all given threads. In java doesn't exists way how to stop thread. <add> * <add> * @param threads <add> */ <add> private void interruptThreads(List<Thread> threads) { <add> assertNotNull(threads); <add> assertFalse(threads.isEmpty()); <add> // Stop method is deprecated <add> threads.forEach(Thread::interrupt); <add> <add> } <ide> }
Java
mit
a2d31ec3e3164453fcbf7c89bb225ecf03929766
0
derrickoswald/CIMApplication,derrickoswald/CIMApplication,derrickoswald/CIMApplication,derrickoswald/CIMApplication,derrickoswald/CIMApplication
package ch.ninecode.cim.cimweb; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.sql.SQLException; import javax.resource.ResourceException; import javax.resource.cci.Connection; import javax.resource.cci.Interaction; import javax.resource.cci.MappedRecord; import javax.resource.cci.Record; import ch.ninecode.cim.connector.CIMConnectionFactory; import ch.ninecode.cim.connector.CIMConnectionSpec; import ch.ninecode.cim.connector.CIMInteractionSpec; import ch.ninecode.cim.connector.CIMInteractionSpecImpl; import ch.ninecode.cim.connector.CIMMappedRecord; import ch.ninecode.cim.connector.CIMResultSet; import ch.ninecode.sc.ShortCircuitOptions; @Stateless @Path("/ShortCircuitCalculation/{file}") public class ShortCircuitCalculation { @Resource (lookup="openejb:Resource/CIMConnector.rar") CIMConnectionFactory factory; /** * Build a connection specification used by all the tests. * @return */ CIMConnectionSpec remoteConfig () { CIMConnectionSpec ret; ret = new CIMConnectionSpec (); ret.setUserName ("derrick"); // not currently used ret.setPassword ("secret"); // not currently used ret.getProperties ().put ("spark.driver.memory", "1g"); ret.getProperties ().put ("spark.executor.memory", "4g"); return (ret); } @SuppressWarnings ("unchecked") @GET @Path("{p:/?}{item:((.*)?)}") @Produces ({"text/plain", "application/json"}) public String GetShortCircuitData (@PathParam("file") String filename, @PathParam("item") String item) { String transformer = (null != item && !item.equals ("")) ? item : null; String spreadsheet = "KS_Leistungen"; // ToDo: load up preset values for transformer parameters StringBuffer out = new StringBuffer (); if (null != factory) { Connection connection; try { connection = factory.getConnection (remoteConfig ()); if (null != connection) { try { String full_file = "hdfs://sandbox:8020/data/" + filename + ".rdf"; final CIMInteractionSpecImpl spec = new CIMInteractionSpecImpl (); spec.setFunctionName (CIMInteractionSpec.EXECUTE_METHOD_FUNCTION); final MappedRecord input = factory.getRecordFactory ().createMappedRecord (CIMMappedRecord.INPUT); input.setRecordShortDescription ("record containing the file name and class and method to run"); input.put ("filename", full_file); input.put ("csv", "hdfs://sandbox:8020/data/" + spreadsheet + ".csv"); // set up the method call details for the CIMConnector ShortCircuitOptions sc = new ShortCircuitOptions (false, null, false, null, null, null, null, null); // see https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file String path = sc.getClass ().getProtectionDomain ().getCodeSource ().getLocation ().getPath (); String decodedPath; try { decodedPath = URLDecoder.decode (path, "UTF-8"); } catch (UnsupportedEncodingException e) { decodedPath = path; } if (decodedPath.endsWith (".jar")) input.put ("jars", decodedPath); input.put ("class", "ch.ninecode.sc.ShortCircuit"); if (null == transformer) input.put ("method", "preparation"); else input.put ("method", "run"); if (null != transformer) input.put ("transformer", transformer); final Interaction interaction = connection.createInteraction (); final Record output = interaction.execute (spec, input); if ((null == output) || !output.getClass ().isAssignableFrom (CIMResultSet.class)) throw new ResourceException ("object of class " + output.getClass ().toGenericString () + " is not a ResultSet"); else { CIMResultSet resultset = (CIMResultSet)output; try { if (null != transformer) { out.append ("{ \"type\": \"FeatureCollection\",\n\"features\": [\n"); while (resultset.next ()) { out.append ("\n{ \"type\": \"Feature\",\n" + "\"geometry\": {\"type\": \"Point\", \"coordinates\": [" + resultset.getString (15) + ", " + resultset.getString (16) + "]},\n" + "\"properties\": {" + "\"mRID\": \"" + resultset.getString (1) + "\", " + "\"node\": \"" + resultset.getString (2) + "\", " + "\"transformer\": \"" + resultset.getString (3) + "\", " + "\"r\": \"" + resultset.getDouble (4) + "\", " + "\"x\": \"" + resultset.getDouble (5) + "\", " + "\"r0\": \"" + resultset.getDouble (6) + "\", " + "\"x0\": \"" + resultset.getDouble (7) + "\", " + "\"fuses\": \"" + resultset.getString (8) + "\", " + "\"ik\": \"" + resultset.getDouble (9) + "\", " + "\"ik3pol\": \"" + resultset.getDouble (10) + "\", " + "\"ip\": \"" + resultset.getDouble (11) + "\", " + "\"wires_valid\": " + resultset.getBoolean (12) + ", " + "\"trafo_valid\": " + resultset.getBoolean (13) + ", " + "\"fuse_valid\": " + resultset.getBoolean (14) + "}\n" + "},"); } out.deleteCharAt (out.length () - 1); // get rid of trailing comma out.append ("\n] }\n"); } else { out.append ("[\n"); while (resultset.next ()) out.append ("\"" + resultset.getString (1) + "\",\n"); out.deleteCharAt (out.length () - 1); // get rid of trailing newline out.deleteCharAt (out.length () - 1); // get rid of trailing comma out.append ("\n]\n"); } resultset.close (); } catch (SQLException sqlexception) { out.append ("SQLException on ResultSet"); out.append ("\n"); StringWriter string = new StringWriter (); PrintWriter writer = new PrintWriter (string); sqlexception.printStackTrace (writer); out.append (string.toString ()); writer.close (); } } interaction.close (); connection.close (); } catch (ResourceException resourceexception) { out.append ("ResourceException on interaction"); out.append ("\n"); StringWriter string = new StringWriter (); PrintWriter writer = new PrintWriter (string); resourceexception.printStackTrace (writer); out.append (string.toString ()); writer.close (); } finally { try { connection.close (); } catch (ResourceException resourceexception) { out.append ("ResourceException on close"); out.append ("\n"); StringWriter string = new StringWriter (); PrintWriter writer = new PrintWriter (string); resourceexception.printStackTrace (writer); out.append (string.toString ()); writer.close (); } } } } catch (ResourceException exception) { out.append ("ResourceException"); out.append ("\n"); StringWriter string = new StringWriter (); PrintWriter writer = new PrintWriter (string); exception.printStackTrace (writer); out.append (string.toString ()); writer.close (); } } return (out.toString ()); } }
CIMWeb/src/main/java/ch/ninecode/cim/cimweb/ShortCircuitCalculation.java
package ch.ninecode.cim.cimweb; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.sql.SQLException; import javax.resource.ResourceException; import javax.resource.cci.Connection; import javax.resource.cci.Interaction; import javax.resource.cci.MappedRecord; import javax.resource.cci.Record; import ch.ninecode.cim.connector.CIMConnectionFactory; import ch.ninecode.cim.connector.CIMConnectionSpec; import ch.ninecode.cim.connector.CIMInteractionSpec; import ch.ninecode.cim.connector.CIMInteractionSpecImpl; import ch.ninecode.cim.connector.CIMMappedRecord; import ch.ninecode.cim.connector.CIMResultSet; import ch.ninecode.sc.ShortCircuit; @Stateless @Path("/ShortCircuitCalculation/{file}") public class ShortCircuitCalculation { @Resource (lookup="openejb:Resource/CIMConnector.rar") CIMConnectionFactory factory; /** * Build a connection specification used by all the tests. * @return */ CIMConnectionSpec remoteConfig () { CIMConnectionSpec ret; ret = new CIMConnectionSpec (); ret.setUserName ("derrick"); // not currently used ret.setPassword ("secret"); // not currently used ret.getProperties ().put ("spark.driver.memory", "1g"); ret.getProperties ().put ("spark.executor.memory", "4g"); return (ret); } @SuppressWarnings ("unchecked") @GET @Path("{p:/?}{item:((.*)?)}") @Produces ({"text/plain", "application/json"}) public String GetShortCircuitData (@PathParam("file") String filename, @PathParam("item") String item) { String transformer = (null != item && !item.equals ("")) ? item : null; String spreadsheet = "KS_Leistungen"; // ToDo: load up preset values for transformer parameters StringBuffer out = new StringBuffer (); if (null != factory) { Connection connection; try { connection = factory.getConnection (remoteConfig ()); if (null != connection) { try { String full_file = "hdfs://sandbox:8020/data/" + filename + ".rdf"; final CIMInteractionSpecImpl spec = new CIMInteractionSpecImpl (); spec.setFunctionName (CIMInteractionSpec.EXECUTE_METHOD_FUNCTION); final MappedRecord input = factory.getRecordFactory ().createMappedRecord (CIMMappedRecord.INPUT); input.setRecordShortDescription ("record containing the file name and class and method to run"); input.put ("filename", full_file); input.put ("csv", "hdfs://sandbox:8020/data/" + spreadsheet + ".csv"); // set up the method call details for the CIMConnector ShortCircuit sc = new ShortCircuit (); input.put ("class", sc.getClass ().getName ()); // see https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file String path = sc.getClass ().getProtectionDomain ().getCodeSource ().getLocation ().getPath (); String decodedPath; try { decodedPath = URLDecoder.decode (path, "UTF-8"); } catch (UnsupportedEncodingException e) { decodedPath = path; } if (decodedPath.endsWith (".jar")) input.put ("jars", decodedPath); input.put ("class", "ch.ninecode.sc.ShortCircuit"); if (null == transformer) input.put ("method", "preparation"); else input.put ("method", "stuff"); if (null != transformer) input.put ("transformer", transformer); final Interaction interaction = connection.createInteraction (); final Record output = interaction.execute (spec, input); if ((null == output) || !output.getClass ().isAssignableFrom (CIMResultSet.class)) throw new ResourceException ("object of class " + output.getClass ().toGenericString () + " is not a ResultSet"); else { CIMResultSet resultset = (CIMResultSet)output; try { if (null != transformer) { out.append ("{ \"type\": \"FeatureCollection\",\n\"features\": [\n"); while (resultset.next ()) { out.append ("\n{ \"type\": \"Feature\",\n" + "\"geometry\": {\"type\": \"Point\", \"coordinates\": [" + resultset.getString (15) + ", " + resultset.getString (16) + "]},\n" + "\"properties\": {" + "\"mRID\": \"" + resultset.getString (1) + "\", " + "\"node\": \"" + resultset.getString (2) + "\", " + "\"transformer\": \"" + resultset.getString (3) + "\", " + "\"r\": \"" + resultset.getDouble (4) + "\", " + "\"x\": \"" + resultset.getDouble (5) + "\", " + "\"r0\": \"" + resultset.getDouble (6) + "\", " + "\"x0\": \"" + resultset.getDouble (7) + "\", " + "\"fuses\": \"" + resultset.getString (8) + "\", " + "\"ik\": \"" + resultset.getDouble (9) + "\", " + "\"ik3pol\": \"" + resultset.getDouble (10) + "\", " + "\"ip\": \"" + resultset.getDouble (11) + "\", " + "\"wires_valid\": " + resultset.getBoolean (12) + ", " + "\"trafo_valid\": " + resultset.getBoolean (13) + ", " + "\"fuse_valid\": " + resultset.getBoolean (14) + "}\n" + "},"); } out.deleteCharAt (out.length () - 1); // get rid of trailing comma out.append ("\n] }\n"); } else { out.append ("[\n"); while (resultset.next ()) out.append ("\"" + resultset.getString (1) + "\",\n"); out.deleteCharAt (out.length () - 1); // get rid of trailing newline out.deleteCharAt (out.length () - 1); // get rid of trailing comma out.append ("\n]\n"); } resultset.close (); } catch (SQLException sqlexception) { out.append ("SQLException on ResultSet"); out.append ("\n"); StringWriter string = new StringWriter (); PrintWriter writer = new PrintWriter (string); sqlexception.printStackTrace (writer); out.append (string.toString ()); writer.close (); } } interaction.close (); connection.close (); } catch (ResourceException resourceexception) { out.append ("ResourceException on interaction"); out.append ("\n"); StringWriter string = new StringWriter (); PrintWriter writer = new PrintWriter (string); resourceexception.printStackTrace (writer); out.append (string.toString ()); writer.close (); } finally { try { connection.close (); } catch (ResourceException resourceexception) { out.append ("ResourceException on close"); out.append ("\n"); StringWriter string = new StringWriter (); PrintWriter writer = new PrintWriter (string); resourceexception.printStackTrace (writer); out.append (string.toString ()); writer.close (); } } } } catch (ResourceException exception) { out.append ("ResourceException"); out.append ("\n"); StringWriter string = new StringWriter (); PrintWriter writer = new PrintWriter (string); exception.printStackTrace (writer); out.append (string.toString ()); writer.close (); } } return (out.toString ()); } }
update ShortCircuit signature
CIMWeb/src/main/java/ch/ninecode/cim/cimweb/ShortCircuitCalculation.java
update ShortCircuit signature
<ide><path>IMWeb/src/main/java/ch/ninecode/cim/cimweb/ShortCircuitCalculation.java <ide> import ch.ninecode.cim.connector.CIMInteractionSpecImpl; <ide> import ch.ninecode.cim.connector.CIMMappedRecord; <ide> import ch.ninecode.cim.connector.CIMResultSet; <del>import ch.ninecode.sc.ShortCircuit; <add>import ch.ninecode.sc.ShortCircuitOptions; <ide> <ide> @Stateless <ide> @Path("/ShortCircuitCalculation/{file}") <ide> input.put ("csv", "hdfs://sandbox:8020/data/" + spreadsheet + ".csv"); <ide> <ide> // set up the method call details for the CIMConnector <del> ShortCircuit sc = new ShortCircuit (); <del> input.put ("class", sc.getClass ().getName ()); <add> ShortCircuitOptions sc = new ShortCircuitOptions (false, null, false, null, null, null, null, null); <ide> // see https://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file <ide> String path = sc.getClass ().getProtectionDomain ().getCodeSource ().getLocation ().getPath (); <ide> String decodedPath; <ide> if (null == transformer) <ide> input.put ("method", "preparation"); <ide> else <del> input.put ("method", "stuff"); <add> input.put ("method", "run"); <ide> if (null != transformer) <ide> input.put ("transformer", transformer); <ide> final Interaction interaction = connection.createInteraction ();
Java
apache-2.0
ea18c27420039a7ebee7551a82a2d7a6a902b0aa
0
izonder/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,samthor/intellij-community,da1z/intellij-community,asedunov/intellij-community,da1z/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,signed/intellij-community,alphafoobar/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,izonder/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,izonder/intellij-community,slisson/intellij-community,allotria/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,nicolargo/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,clumsy/intellij-community,jagguli/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,slisson/intellij-community,blademainer/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,fnouama/intellij-community,xfournet/intellij-community,kdwink/intellij-community,caot/intellij-community,fnouama/intellij-community,ibinti/intellij-community,robovm/robovm-studio,asedunov/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,da1z/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,adedayo/intellij-community,signed/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,ryano144/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,petteyg/intellij-community,apixandru/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,ivan-fedorov/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,petteyg/intellij-community,hurricup/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,supersven/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,hurricup/intellij-community,slisson/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,xfournet/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,izonder/intellij-community,apixandru/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,dslomov/intellij-community,dslomov/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,semonte/intellij-community,dslomov/intellij-community,fitermay/intellij-community,fitermay/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,suncycheng/intellij-community,signed/intellij-community,holmes/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,kdwink/intellij-community,vladmm/intellij-community,izonder/intellij-community,supersven/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,vladmm/intellij-community,amith01994/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,samthor/intellij-community,blademainer/intellij-community,adedayo/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,kdwink/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,fnouama/intellij-community,ibinti/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,allotria/intellij-community,kdwink/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,adedayo/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,signed/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,nicolargo/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,signed/intellij-community,petteyg/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,da1z/intellij-community,gnuhub/intellij-community,caot/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,adedayo/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,Distrotech/intellij-community,holmes/intellij-community,caot/intellij-community,ibinti/intellij-community,kool79/intellij-community,samthor/intellij-community,xfournet/intellij-community,hurricup/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,samthor/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,ibinti/intellij-community,retomerz/intellij-community,jagguli/intellij-community,FHannes/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,kool79/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,slisson/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,caot/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,FHannes/intellij-community,apixandru/intellij-community,da1z/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,holmes/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,Lekanich/intellij-community,allotria/intellij-community,amith01994/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,retomerz/intellij-community,vladmm/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,kool79/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,signed/intellij-community,holmes/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,semonte/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,holmes/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,amith01994/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,allotria/intellij-community,Lekanich/intellij-community,caot/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,fnouama/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,samthor/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,adedayo/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,kool79/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,holmes/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,amith01994/intellij-community,da1z/intellij-community,apixandru/intellij-community,ryano144/intellij-community,retomerz/intellij-community,semonte/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,semonte/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,ibinti/intellij-community,supersven/intellij-community,hurricup/intellij-community,caot/intellij-community,supersven/intellij-community,allotria/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,caot/intellij-community,kool79/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,petteyg/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,hurricup/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,apixandru/intellij-community,fnouama/intellij-community,samthor/intellij-community,xfournet/intellij-community,dslomov/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ibinti/intellij-community,asedunov/intellij-community,kdwink/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,caot/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,fitermay/intellij-community,clumsy/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,dslomov/intellij-community,kool79/intellij-community,jagguli/intellij-community,izonder/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,semonte/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,allotria/intellij-community,robovm/robovm-studio,dslomov/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,jagguli/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,retomerz/intellij-community,samthor/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,apixandru/intellij-community,amith01994/intellij-community,petteyg/intellij-community,signed/intellij-community,slisson/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,hurricup/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,izonder/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,asedunov/intellij-community,kdwink/intellij-community,petteyg/intellij-community,ryano144/intellij-community,FHannes/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,supersven/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,gnuhub/intellij-community,kool79/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,caot/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,signed/intellij-community,ibinti/intellij-community,fnouama/intellij-community,apixandru/intellij-community,jagguli/intellij-community,signed/intellij-community,signed/intellij-community,vladmm/intellij-community,asedunov/intellij-community,slisson/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,fitermay/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,holmes/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,supersven/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,asedunov/intellij-community,supersven/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.progress.impl; import com.google.common.collect.ConcurrentHashMultiset; import com.intellij.concurrency.JobScheduler; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.progress.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.wm.ex.ProgressIndicatorEx; import com.intellij.util.containers.ConcurrentLongObjectMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.SmartHashSet; import gnu.trove.THashMap; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class CoreProgressManager extends ProgressManager implements Disposable { static final int CHECK_CANCELED_DELAY_MILLIS = 10; final AtomicInteger myCurrentUnsafeProgressCount = new AtomicInteger(0); private final AtomicInteger myCurrentModalProgressCount = new AtomicInteger(0); private static final boolean ENABLED = !"disabled".equals(System.getProperty("idea.ProcessCanceledException")); private final ScheduledFuture<?> myCheckCancelledFuture; // indicator -> threads which are running under this indicator. guarded by threadsUnderIndicator. private static final Map<ProgressIndicator, Set<Thread>> threadsUnderIndicator = new THashMap<ProgressIndicator, Set<Thread>>(); // the active indicator for the thread id private static final ConcurrentLongObjectMap<ProgressIndicator> currentIndicators = ContainerUtil.createConcurrentLongObjectMap(); // threads which are running under canceled indicator static final Set<Thread> threadsUnderCanceledIndicator = ContainerUtil.newConcurrentSet(); private static volatile boolean thereIsProcessUnderCanceledIndicator; // active (i.e. which have executeProcessUnderProgress() method running) indicators which are not inherited from StandardProgressIndicator. // for them an extra processing thread (see myCheckCancelledFuture) has to be run to call their non-standard checkCanceled() method private static final Collection<ProgressIndicator> nonStandardIndicators = ConcurrentHashMultiset.create(); public CoreProgressManager() { myCheckCancelledFuture = JobScheduler.getScheduler().scheduleWithFixedDelay(new Runnable() { @Override public void run() { for (ProgressIndicator indicator : nonStandardIndicators) { try { indicator.checkCanceled(); } catch (ProcessCanceledException e) { indicatorCanceled(indicator); } } } }, 0, CHECK_CANCELED_DELAY_MILLIS, TimeUnit.MILLISECONDS); } @Override public void dispose() { myCheckCancelledFuture.cancel(true); } @Override protected void doCheckCanceled() throws ProcessCanceledException { if (thereIsProcessUnderCanceledIndicator) { final ProgressIndicator progress = getProgressIndicator(); if (progress != null && ENABLED) { progress.checkCanceled(); } } } @Override public boolean hasProgressIndicator() { return getProgressIndicator() != null; } @Override public boolean hasUnsafeProgressIndicator() { return myCurrentUnsafeProgressCount.get() > 0; } @Override public boolean hasModalProgressIndicator() { return myCurrentModalProgressCount.get() > 0; } @Override public void runProcess(@NotNull final Runnable process, final ProgressIndicator progress) { executeProcessUnderProgress(new Runnable(){ @Override public void run() { try { try { if (progress != null && !progress.isRunning()) { progress.start(); } } catch (RuntimeException e) { throw e; } catch (Throwable e) { throw new RuntimeException(e); } process.run(); } finally { if (progress != null && progress.isRunning()) { progress.stop(); if (progress instanceof ProgressIndicatorEx) { ((ProgressIndicatorEx)progress).processFinish(); } } } } },progress); } @Override public <T> T runProcess(@NotNull final Computable<T> process, ProgressIndicator progress) throws ProcessCanceledException { final Ref<T> ref = new Ref<T>(); runProcess(new Runnable() { @Override public void run() { ref.set(process.compute()); } }, progress); return ref.get(); } @Override public void executeNonCancelableSection(@NotNull Runnable runnable) { executeProcessUnderProgress(runnable, new NonCancelableIndicator()); } @Override public void setCancelButtonText(String cancelButtonText) { } @Override public boolean runProcessWithProgressSynchronously(@NotNull Runnable process, @NotNull @Nls String progressTitle, boolean canBeCanceled, @Nullable Project project) { return runProcessWithProgressSynchronously(process, progressTitle, canBeCanceled, project, null); } @Override public <T, E extends Exception> T runProcessWithProgressSynchronously(@NotNull final ThrowableComputable<T, E> process, @NotNull @Nls String progressTitle, boolean canBeCanceled, @Nullable Project project) throws E { final AtomicReference<T> result = new AtomicReference<T>(); final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); runProcessWithProgressSynchronously(new Task.Modal(project, progressTitle, canBeCanceled) { @Override public void run(@NotNull ProgressIndicator indicator) { try { T compute = process.compute(); result.set(compute); } catch (Throwable t) { exception.set(t); } } }, null); Throwable t = exception.get(); if (t != null) { if (t instanceof Error) throw (Error)t; if (t instanceof RuntimeException) throw (RuntimeException)t; @SuppressWarnings("unchecked") E e = (E)t; throw e; } return result.get(); } @Override public boolean runProcessWithProgressSynchronously(@NotNull final Runnable process, @NotNull @Nls String progressTitle, boolean canBeCanceled, @Nullable Project project, @Nullable JComponent parentComponent) { Task.Modal task = new Task.Modal(project, progressTitle, canBeCanceled) { @Override public void run(@NotNull ProgressIndicator indicator) { process.run(); } }; return runProcessWithProgressSynchronously(task, parentComponent); } @Override public void runProcessWithProgressAsynchronously(@NotNull Project project, @NotNull @Nls String progressTitle, @NotNull Runnable process, @Nullable Runnable successRunnable, @Nullable Runnable canceledRunnable) { runProcessWithProgressAsynchronously(project, progressTitle, process, successRunnable, canceledRunnable, PerformInBackgroundOption.DEAF); } @Override public void runProcessWithProgressAsynchronously(@NotNull Project project, @NotNull @Nls String progressTitle, @NotNull final Runnable process, @Nullable final Runnable successRunnable, @Nullable final Runnable canceledRunnable, @NotNull PerformInBackgroundOption option) { runProcessWithProgressAsynchronously(new Task.Backgroundable(project, progressTitle, true, option) { @Override public void run(@NotNull final ProgressIndicator indicator) { process.run(); } @Override public void onCancel() { if (canceledRunnable != null) { canceledRunnable.run(); } } @Override public void onSuccess() { if (successRunnable != null) { successRunnable.run(); } } }); } @Override public void run(@NotNull final Task task) { if (task.isHeadless()) { if (ApplicationManager.getApplication().isDispatchThread()) { runProcessWithProgressSynchronously(task, null); } else { new TaskRunnable(task, new EmptyProgressIndicator()).run(); } } else if (task.isModal()) { runProcessWithProgressSynchronously(task.asModal(), null); } else { final Task.Backgroundable backgroundable = task.asBackgroundable(); if (backgroundable.isConditionalModal() && !backgroundable.shouldStartInBackground()) { runProcessWithProgressSynchronously(task, null); } else { runProcessWithProgressAsynchronously(backgroundable); } } } @NotNull public Future<?> runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task) { return runProcessWithProgressAsynchronously(task, new EmptyProgressIndicator(), null); } @NotNull public Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task, @NotNull final ProgressIndicator progressIndicator, @Nullable final Runnable continuation) { return runProcessWithProgressAsynchronously(task, progressIndicator, continuation, ModalityState.NON_MODAL); } @NotNull public Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task, @NotNull final ProgressIndicator progressIndicator, @Nullable final Runnable continuation, @NotNull final ModalityState modalityState) { if (progressIndicator instanceof Disposable) { Disposer.register(ApplicationManager.getApplication(), (Disposable)progressIndicator); } final Runnable process = new TaskRunnable(task, progressIndicator, continuation); Runnable action = new TaskContainer(task) { @Override public void run() { boolean canceled = false; try { ProgressManager.getInstance().runProcess(process, progressIndicator); } catch (ProcessCanceledException e) { canceled = true; } if (canceled || progressIndicator.isCanceled()) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { task.onCancel(); } }, modalityState); } else { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { task.onSuccess(); } }, modalityState); } } }; return ApplicationManager.getApplication().executeOnPooledThread(action); } protected boolean runProcessWithProgressSynchronously(@NotNull final Task task, @Nullable final JComponent parentComponent) { final boolean result = ((ApplicationEx)ApplicationManager.getApplication()) .runProcessWithProgressSynchronously(new TaskContainer(task) { @Override public void run() { new TaskRunnable(task, ProgressManager.getInstance().getProgressIndicator()).run(); } }, task.getTitle(), task.isCancellable(), task.getProject(), parentComponent, task.getCancelText()); if (result) { task.onSuccess(); } else { task.onCancel(); } return result; } @Override public void runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task, @NotNull ProgressIndicator progressIndicator) { runProcessWithProgressAsynchronously(task, progressIndicator, null); } @Override public ProgressIndicator getProgressIndicator() { return getCurrentIndicator(Thread.currentThread()); } @Override public void executeProcessUnderProgress(@NotNull Runnable process, ProgressIndicator progress) throws ProcessCanceledException { boolean modal = progress != null && progress.isModal(); if (modal) myCurrentModalProgressCount.incrementAndGet(); if (progress == null) myCurrentUnsafeProgressCount.incrementAndGet(); try { ProgressIndicator oldIndicator = null; boolean set = progress != null && progress != (oldIndicator = getProgressIndicator()); if (set) { Thread currentThread = Thread.currentThread(); setCurrentIndicator(currentThread, progress); try { registerIndicatorAndRun(progress, currentThread, oldIndicator, process); } finally { setCurrentIndicator(currentThread, oldIndicator); } } else { process.run(); } } finally { if (progress == null) myCurrentUnsafeProgressCount.decrementAndGet(); if (modal) myCurrentModalProgressCount.decrementAndGet(); } } private static void registerIndicatorAndRun(@NotNull ProgressIndicator indicator, @NotNull Thread currentThread, ProgressIndicator oldIndicator, @NotNull Runnable process) { Set<Thread> underIndicator; boolean alreadyUnder; boolean isStandard; synchronized (threadsUnderIndicator) { underIndicator = threadsUnderIndicator.get(indicator); if (underIndicator == null) { underIndicator = new SmartHashSet<Thread>(); threadsUnderIndicator.put(indicator, underIndicator); } alreadyUnder = !underIndicator.add(currentThread); isStandard = indicator instanceof StandardProgressIndicator; if (!isStandard) { nonStandardIndicators.add(indicator); } if (indicator.isCanceled()) { threadsUnderCanceledIndicator.add(currentThread); } else { threadsUnderCanceledIndicator.remove(currentThread); } thereIsProcessUnderCanceledIndicator = !threadsUnderCanceledIndicator.isEmpty(); } try { if (indicator instanceof WrappedProgressIndicator) { ProgressIndicator wrappee = ((WrappedProgressIndicator)indicator).getOriginalProgressIndicator(); assert wrappee != indicator : indicator + " wraps itself"; registerIndicatorAndRun(wrappee, currentThread, oldIndicator, process); } else { process.run(); } } finally { synchronized (threadsUnderIndicator) { boolean removed = alreadyUnder || underIndicator.remove(currentThread); if (removed && underIndicator.isEmpty()) { threadsUnderIndicator.remove(indicator); } if (!isStandard) { nonStandardIndicators.remove(indicator); } // by this time oldIndicator may have been canceled if (oldIndicator != null && oldIndicator.isCanceled()) { threadsUnderCanceledIndicator.add(currentThread); } else { threadsUnderCanceledIndicator.remove(currentThread); } thereIsProcessUnderCanceledIndicator = !threadsUnderCanceledIndicator.isEmpty(); } } } @Override protected void indicatorCanceled(@NotNull ProgressIndicator indicator) { // mark threads running under this indicator as canceled synchronized (threadsUnderIndicator) { Set<Thread> threads = threadsUnderIndicator.get(indicator); if (threads != null) { for (Thread thread : threads) { boolean underCancelledIndicator = false; for (ProgressIndicator currentIndicator = getCurrentIndicator(thread); currentIndicator != null; currentIndicator = currentIndicator instanceof WrappedProgressIndicator ? ((WrappedProgressIndicator)currentIndicator).getOriginalProgressIndicator() : null) { if (currentIndicator == indicator) { underCancelledIndicator = true; break; } } if (underCancelledIndicator) { threadsUnderCanceledIndicator.add(thread); thereIsProcessUnderCanceledIndicator = true; } } } } } @TestOnly public static boolean isCanceledThread(@NotNull Thread thread) { return threadsUnderCanceledIndicator.contains(thread); } @NotNull @Override public final NonCancelableSection startNonCancelableSection() { final ProgressIndicator myOld = ProgressManager.getInstance().getProgressIndicator(); final Thread currentThread = Thread.currentThread(); NonCancelableIndicator nonCancelor = new NonCancelableIndicator() { @Override public void done() { setCurrentIndicator(currentThread, myOld); } }; setCurrentIndicator(currentThread, nonCancelor); return nonCancelor; } private static void setCurrentIndicator(@NotNull Thread currentThread, ProgressIndicator indicator) { if (indicator == null) { currentIndicators.remove(currentThread.getId()); } else { currentIndicators.put(currentThread.getId(), indicator); } } private static ProgressIndicator getCurrentIndicator(@NotNull Thread thread) { return currentIndicators.get(thread.getId()); } protected abstract static class TaskContainer implements Runnable { private final Task myTask; protected TaskContainer(@NotNull Task task) { myTask = task; } @NotNull public Task getTask() { return myTask; } } protected static class TaskRunnable extends TaskContainer { private final ProgressIndicator myIndicator; private final Runnable myContinuation; public TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator) { this(task, indicator, null); } public TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator, @Nullable Runnable continuation) { super(task); myIndicator = indicator; myContinuation = continuation; } @Override public void run() { try { getTask().run(myIndicator); } finally { try { if (myIndicator instanceof ProgressIndicatorEx) { ((ProgressIndicatorEx)myIndicator).finish(getTask()); } } finally { if (myContinuation != null) { myContinuation.run(); } } } } } }
platform/core-impl/src/com/intellij/openapi/progress/impl/CoreProgressManager.java
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.progress.impl; import com.google.common.collect.ConcurrentHashMultiset; import com.intellij.concurrency.JobScheduler; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.progress.*; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.wm.ex.ProgressIndicatorEx; import com.intellij.util.containers.ConcurrentLongObjectMap; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.SmartHashSet; import gnu.trove.THashMap; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.TestOnly; import javax.swing.*; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; public class CoreProgressManager extends ProgressManager implements Disposable { static final int CHECK_CANCELED_DELAY_MILLIS = 10; final AtomicInteger myCurrentUnsafeProgressCount = new AtomicInteger(0); private final AtomicInteger myCurrentModalProgressCount = new AtomicInteger(0); private static final boolean ENABLED = !"disabled".equals(System.getProperty("idea.ProcessCanceledException")); private final ScheduledFuture<?> myCheckCancelledFuture; // indicator -> threads which are running under this indicator. guarded by this. private static final Map<ProgressIndicator, Set<Thread>> threadsUnderIndicator = new THashMap<ProgressIndicator, Set<Thread>>(); // the active indicator for the thread id private static final ConcurrentLongObjectMap<ProgressIndicator> currentIndicators = ContainerUtil.createConcurrentLongObjectMap(); // threads which are running under canceled indicator static final Set<Thread> threadsUnderCanceledIndicator = ContainerUtil.newConcurrentSet(); // active (i.e. which have executeProcessUnderProgress() method running) indicators which are not inherited from StandardProgressIndicator. // for them an extra processing thread (see myCheckCancelledFuture) has to be run to call their non-standard checkCanceled() method private static final Collection<ProgressIndicator> nonStandardIndicators = ConcurrentHashMultiset.create(); public CoreProgressManager() { myCheckCancelledFuture = JobScheduler.getScheduler().scheduleWithFixedDelay(new Runnable() { @Override public void run() { for (ProgressIndicator indicator : nonStandardIndicators) { try { indicator.checkCanceled(); } catch (ProcessCanceledException e) { indicatorCanceled(indicator); } } } }, 0, CHECK_CANCELED_DELAY_MILLIS, TimeUnit.MILLISECONDS); } @Override public void dispose() { myCheckCancelledFuture.cancel(true); } @Override protected void doCheckCanceled() throws ProcessCanceledException { boolean thereIsCanceledIndicator = !threadsUnderCanceledIndicator.isEmpty(); if (thereIsCanceledIndicator) { final ProgressIndicator progress = getProgressIndicator(); if (progress != null && ENABLED) { progress.checkCanceled(); } } } @Override public boolean hasProgressIndicator() { return getProgressIndicator() != null; } @Override public boolean hasUnsafeProgressIndicator() { return myCurrentUnsafeProgressCount.get() > 0; } @Override public boolean hasModalProgressIndicator() { return myCurrentModalProgressCount.get() > 0; } @Override public void runProcess(@NotNull final Runnable process, final ProgressIndicator progress) { executeProcessUnderProgress(new Runnable(){ @Override public void run() { try { try { if (progress != null && !progress.isRunning()) { progress.start(); } } catch (RuntimeException e) { throw e; } catch (Throwable e) { throw new RuntimeException(e); } process.run(); } finally { if (progress != null && progress.isRunning()) { progress.stop(); if (progress instanceof ProgressIndicatorEx) { ((ProgressIndicatorEx)progress).processFinish(); } } } } },progress); } @Override public <T> T runProcess(@NotNull final Computable<T> process, ProgressIndicator progress) throws ProcessCanceledException { final Ref<T> ref = new Ref<T>(); runProcess(new Runnable() { @Override public void run() { ref.set(process.compute()); } }, progress); return ref.get(); } @Override public void executeNonCancelableSection(@NotNull Runnable runnable) { executeProcessUnderProgress(runnable, new NonCancelableIndicator()); } @Override public void setCancelButtonText(String cancelButtonText) { } @Override public boolean runProcessWithProgressSynchronously(@NotNull Runnable process, @NotNull @Nls String progressTitle, boolean canBeCanceled, @Nullable Project project) { return runProcessWithProgressSynchronously(process, progressTitle, canBeCanceled, project, null); } @Override public <T, E extends Exception> T runProcessWithProgressSynchronously(@NotNull final ThrowableComputable<T, E> process, @NotNull @Nls String progressTitle, boolean canBeCanceled, @Nullable Project project) throws E { final AtomicReference<T> result = new AtomicReference<T>(); final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); runProcessWithProgressSynchronously(new Task.Modal(project, progressTitle, canBeCanceled) { @Override public void run(@NotNull ProgressIndicator indicator) { try { T compute = process.compute(); result.set(compute); } catch (Throwable t) { exception.set(t); } } }, null); Throwable t = exception.get(); if (t != null) { if (t instanceof Error) throw (Error)t; if (t instanceof RuntimeException) throw (RuntimeException)t; @SuppressWarnings("unchecked") E e = (E)t; throw e; } return result.get(); } @Override public boolean runProcessWithProgressSynchronously(@NotNull final Runnable process, @NotNull @Nls String progressTitle, boolean canBeCanceled, @Nullable Project project, @Nullable JComponent parentComponent) { Task.Modal task = new Task.Modal(project, progressTitle, canBeCanceled) { @Override public void run(@NotNull ProgressIndicator indicator) { process.run(); } }; return runProcessWithProgressSynchronously(task, parentComponent); } @Override public void runProcessWithProgressAsynchronously(@NotNull Project project, @NotNull @Nls String progressTitle, @NotNull Runnable process, @Nullable Runnable successRunnable, @Nullable Runnable canceledRunnable) { runProcessWithProgressAsynchronously(project, progressTitle, process, successRunnable, canceledRunnable, PerformInBackgroundOption.DEAF); } @Override public void runProcessWithProgressAsynchronously(@NotNull Project project, @NotNull @Nls String progressTitle, @NotNull final Runnable process, @Nullable final Runnable successRunnable, @Nullable final Runnable canceledRunnable, @NotNull PerformInBackgroundOption option) { runProcessWithProgressAsynchronously(new Task.Backgroundable(project, progressTitle, true, option) { @Override public void run(@NotNull final ProgressIndicator indicator) { process.run(); } @Override public void onCancel() { if (canceledRunnable != null) { canceledRunnable.run(); } } @Override public void onSuccess() { if (successRunnable != null) { successRunnable.run(); } } }); } @Override public void run(@NotNull final Task task) { if (task.isHeadless()) { if (ApplicationManager.getApplication().isDispatchThread()) { runProcessWithProgressSynchronously(task, null); } else { new TaskRunnable(task, new EmptyProgressIndicator()).run(); } } else if (task.isModal()) { runProcessWithProgressSynchronously(task.asModal(), null); } else { final Task.Backgroundable backgroundable = task.asBackgroundable(); if (backgroundable.isConditionalModal() && !backgroundable.shouldStartInBackground()) { runProcessWithProgressSynchronously(task, null); } else { runProcessWithProgressAsynchronously(backgroundable); } } } @NotNull public Future<?> runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task) { return runProcessWithProgressAsynchronously(task, new EmptyProgressIndicator(), null); } @NotNull public Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task, @NotNull final ProgressIndicator progressIndicator, @Nullable final Runnable continuation) { return runProcessWithProgressAsynchronously(task, progressIndicator, continuation, ModalityState.NON_MODAL); } @NotNull public Future<?> runProcessWithProgressAsynchronously(@NotNull final Task.Backgroundable task, @NotNull final ProgressIndicator progressIndicator, @Nullable final Runnable continuation, @NotNull final ModalityState modalityState) { if (progressIndicator instanceof Disposable) { Disposer.register(ApplicationManager.getApplication(), (Disposable)progressIndicator); } final Runnable process = new TaskRunnable(task, progressIndicator, continuation); Runnable action = new TaskContainer(task) { @Override public void run() { boolean canceled = false; try { ProgressManager.getInstance().runProcess(process, progressIndicator); } catch (ProcessCanceledException e) { canceled = true; } if (canceled || progressIndicator.isCanceled()) { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { task.onCancel(); } }, modalityState); } else { ApplicationManager.getApplication().invokeLater(new Runnable() { @Override public void run() { task.onSuccess(); } }, modalityState); } } }; return ApplicationManager.getApplication().executeOnPooledThread(action); } protected boolean runProcessWithProgressSynchronously(@NotNull final Task task, @Nullable final JComponent parentComponent) { final boolean result = ((ApplicationEx)ApplicationManager.getApplication()) .runProcessWithProgressSynchronously(new TaskContainer(task) { @Override public void run() { new TaskRunnable(task, ProgressManager.getInstance().getProgressIndicator()).run(); } }, task.getTitle(), task.isCancellable(), task.getProject(), parentComponent, task.getCancelText()); if (result) { task.onSuccess(); } else { task.onCancel(); } return result; } @Override public void runProcessWithProgressAsynchronously(@NotNull Task.Backgroundable task, @NotNull ProgressIndicator progressIndicator) { runProcessWithProgressAsynchronously(task, progressIndicator, null); } @Override public ProgressIndicator getProgressIndicator() { return getCurrentIndicator(Thread.currentThread()); } @Override public void executeProcessUnderProgress(@NotNull Runnable process, ProgressIndicator progress) throws ProcessCanceledException { boolean modal = progress != null && progress.isModal(); if (modal) myCurrentModalProgressCount.incrementAndGet(); if (progress == null) myCurrentUnsafeProgressCount.incrementAndGet(); try { ProgressIndicator oldIndicator = null; boolean set = progress != null && progress != (oldIndicator = getProgressIndicator()); if (set) { Thread currentThread = Thread.currentThread(); setCurrentIndicator(currentThread, progress); try { registerIndicatorAndRun(progress, currentThread, oldIndicator, process); } finally { setCurrentIndicator(currentThread, oldIndicator); } } else { process.run(); } } finally { if (progress == null) myCurrentUnsafeProgressCount.decrementAndGet(); if (modal) myCurrentModalProgressCount.decrementAndGet(); } } private static void registerIndicatorAndRun(@NotNull ProgressIndicator indicator, @NotNull Thread currentThread, ProgressIndicator oldIndicator, @NotNull Runnable process) { Set<Thread> underIndicator; boolean alreadyUnder; boolean isStandard; synchronized (threadsUnderIndicator) { underIndicator = threadsUnderIndicator.get(indicator); if (underIndicator == null) { underIndicator = new SmartHashSet<Thread>(); threadsUnderIndicator.put(indicator, underIndicator); } alreadyUnder = !underIndicator.add(currentThread); isStandard = indicator instanceof StandardProgressIndicator; if (!isStandard) { nonStandardIndicators.add(indicator); } if (indicator.isCanceled()) { threadsUnderCanceledIndicator.add(currentThread); } else { threadsUnderCanceledIndicator.remove(currentThread); } } try { if (indicator instanceof WrappedProgressIndicator) { ProgressIndicator wrappee = ((WrappedProgressIndicator)indicator).getOriginalProgressIndicator(); assert wrappee != indicator : indicator + " wraps itself"; registerIndicatorAndRun(wrappee, currentThread, oldIndicator, process); } else { process.run(); } } finally { synchronized (threadsUnderIndicator) { boolean removed = alreadyUnder || underIndicator.remove(currentThread); if (removed && underIndicator.isEmpty()) { threadsUnderIndicator.remove(indicator); } if (!isStandard) { nonStandardIndicators.remove(indicator); } // by this time oldIndicator may have been canceled if (oldIndicator != null && oldIndicator.isCanceled()) { threadsUnderCanceledIndicator.add(currentThread); } else { threadsUnderCanceledIndicator.remove(currentThread); } } } } @Override protected void indicatorCanceled(@NotNull ProgressIndicator indicator) { // mark threads running under this indicator as canceled synchronized (threadsUnderIndicator) { Set<Thread> threads = threadsUnderIndicator.get(indicator); if (threads != null) { for (Thread thread : threads) { boolean underCancelledIndicator = false; for (ProgressIndicator currentIndicator = getCurrentIndicator(thread); currentIndicator != null; currentIndicator = currentIndicator instanceof WrappedProgressIndicator ? ((WrappedProgressIndicator)currentIndicator).getOriginalProgressIndicator() : null) { if (currentIndicator == indicator) { underCancelledIndicator = true; break; } } if (underCancelledIndicator) { threadsUnderCanceledIndicator.add(thread); } } } } } @TestOnly public static boolean isCanceledThread(@NotNull Thread thread) { return threadsUnderCanceledIndicator.contains(thread); } @NotNull @Override public final NonCancelableSection startNonCancelableSection() { final ProgressIndicator myOld = ProgressManager.getInstance().getProgressIndicator(); final Thread currentThread = Thread.currentThread(); NonCancelableIndicator nonCancelor = new NonCancelableIndicator() { @Override public void done() { setCurrentIndicator(currentThread, myOld); } }; setCurrentIndicator(currentThread, nonCancelor); return nonCancelor; } private static void setCurrentIndicator(@NotNull Thread currentThread, ProgressIndicator indicator) { if (indicator == null) { currentIndicators.remove(currentThread.getId()); } else { currentIndicators.put(currentThread.getId(), indicator); } } private static ProgressIndicator getCurrentIndicator(@NotNull Thread thread) { return currentIndicators.get(thread.getId()); } protected abstract static class TaskContainer implements Runnable { private final Task myTask; protected TaskContainer(@NotNull Task task) { myTask = task; } @NotNull public Task getTask() { return myTask; } } protected static class TaskRunnable extends TaskContainer { private final ProgressIndicator myIndicator; private final Runnable myContinuation; public TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator) { this(task, indicator, null); } public TaskRunnable(@NotNull Task task, @NotNull ProgressIndicator indicator, @Nullable Runnable continuation) { super(task); myIndicator = indicator; myContinuation = continuation; } @Override public void run() { try { getTask().run(myIndicator); } finally { try { if (myIndicator instanceof ProgressIndicatorEx) { ((ProgressIndicatorEx)myIndicator).finish(getTask()); } } finally { if (myContinuation != null) { myContinuation.run(); } } } } } }
optimisation: reduce volatile reads to one down from three
platform/core-impl/src/com/intellij/openapi/progress/impl/CoreProgressManager.java
optimisation: reduce volatile reads to one down from three
<ide><path>latform/core-impl/src/com/intellij/openapi/progress/impl/CoreProgressManager.java <ide> private static final boolean ENABLED = !"disabled".equals(System.getProperty("idea.ProcessCanceledException")); <ide> private final ScheduledFuture<?> myCheckCancelledFuture; <ide> <del> // indicator -> threads which are running under this indicator. guarded by this. <add> // indicator -> threads which are running under this indicator. guarded by threadsUnderIndicator. <ide> private static final Map<ProgressIndicator, Set<Thread>> threadsUnderIndicator = new THashMap<ProgressIndicator, Set<Thread>>(); <ide> // the active indicator for the thread id <ide> private static final ConcurrentLongObjectMap<ProgressIndicator> currentIndicators = ContainerUtil.createConcurrentLongObjectMap(); <ide> // threads which are running under canceled indicator <ide> static final Set<Thread> threadsUnderCanceledIndicator = ContainerUtil.newConcurrentSet(); <add> private static volatile boolean thereIsProcessUnderCanceledIndicator; <ide> <ide> // active (i.e. which have executeProcessUnderProgress() method running) indicators which are not inherited from StandardProgressIndicator. <ide> // for them an extra processing thread (see myCheckCancelledFuture) has to be run to call their non-standard checkCanceled() method <ide> <ide> @Override <ide> protected void doCheckCanceled() throws ProcessCanceledException { <del> boolean thereIsCanceledIndicator = !threadsUnderCanceledIndicator.isEmpty(); <del> if (thereIsCanceledIndicator) { <add> if (thereIsProcessUnderCanceledIndicator) { <ide> final ProgressIndicator progress = getProgressIndicator(); <ide> if (progress != null && ENABLED) { <ide> progress.checkCanceled(); <ide> else { <ide> threadsUnderCanceledIndicator.remove(currentThread); <ide> } <add> thereIsProcessUnderCanceledIndicator = !threadsUnderCanceledIndicator.isEmpty(); <ide> } <ide> <ide> try { <ide> else { <ide> threadsUnderCanceledIndicator.remove(currentThread); <ide> } <add> thereIsProcessUnderCanceledIndicator = !threadsUnderCanceledIndicator.isEmpty(); <ide> } <ide> } <ide> } <ide> <ide> if (underCancelledIndicator) { <ide> threadsUnderCanceledIndicator.add(thread); <add> thereIsProcessUnderCanceledIndicator = true; <ide> } <ide> } <ide> }
Java
apache-2.0
947732ea3e868e7de712d5315375174f6d58ed8c
0
milindaperera/product-is,wso2/product-is,madurangasiriwardena/product-is,madurangasiriwardena/product-is,mefarazath/product-is,madurangasiriwardena/product-is,mefarazath/product-is,milindaperera/product-is,mefarazath/product-is,milindaperera/product-is,wso2/product-is,milindaperera/product-is,wso2/product-is,mefarazath/product-is,mefarazath/product-is,milindaperera/product-is,wso2/product-is,madurangasiriwardena/product-is,wso2/product-is,madurangasiriwardena/product-is
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.sample.identity.oauth2.grant.mobile; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.ResponseHeader; import org.wso2.carbon.identity.oauth2.model.RequestParameter; import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; import org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler; /** * New grant type for Identity Server */ public class MobileGrant extends AbstractAuthorizationGrantHandler { private static Log log = LogFactory.getLog(MobileGrant.class); public static final String MOBILE_GRANT_PARAM = "mobileNumber"; @Override public boolean validateGrant(OAuthTokenReqMessageContext oAuthTokenReqMessageContext) throws IdentityOAuth2Exception { log.info("Mobile Grant handler is hit"); boolean authStatus = false; // extract request parameters RequestParameter[] parameters = oAuthTokenReqMessageContext.getOauth2AccessTokenReqDTO().getRequestParameters(); String mobileNumber = null; // find out mobile number for(RequestParameter parameter : parameters){ if(MOBILE_GRANT_PARAM.equals(parameter.getKey())){ if(parameter.getValue() != null && parameter.getValue().length > 0){ mobileNumber = parameter.getValue()[0]; } } } if(mobileNumber != null) { //validate mobile number authStatus = isValidMobileNumber(mobileNumber); if(authStatus) { // if valid set authorized mobile number as grant user AuthenticatedUser mobileUser = new AuthenticatedUser(); mobileUser.setUserName(mobileNumber); mobileUser.setAuthenticatedSubjectIdentifier(mobileNumber); mobileUser.setFederatedUser(true); oAuthTokenReqMessageContext.setAuthorizedUser(mobileUser); oAuthTokenReqMessageContext.setScope(oAuthTokenReqMessageContext.getOauth2AccessTokenReqDTO().getScope()); } else{ ResponseHeader responseHeader = new ResponseHeader(); responseHeader.setKey("SampleHeader-999"); responseHeader.setValue("Provided Mobile Number is Invalid."); oAuthTokenReqMessageContext.addProperty("RESPONSE_HEADERS", new ResponseHeader[]{responseHeader}); } } return authStatus; } public boolean authorizeAccessDelegation(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { // if we need to just ignore the end user's extended verification return true; // if we need to verify with the end user's access delegation by calling callback chain. // However, you need to register a callback for this. Default call back just return true. // OAuthCallback authzCallback = new OAuthCallback( // tokReqMsgCtx.getAuthorizedUser(), // tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId(), // OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_TOKEN); // authzCallback.setRequestedScope(tokReqMsgCtx.getScope()); // authzCallback.setCarbonGrantType(org.wso2.carbon.identity.oauth.common.GrantType.valueOf(tokReqMsgCtx. // getOauth2AccessTokenReqDTO().getGrantType())); // callbackManager.handleCallback(authzCallback); // tokReqMsgCtx.setValidityPeriod(authzCallback.getValidityPeriod()); // return authzCallback.isAuthorized(); } public boolean validateScope(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { // if we need to just ignore the scope verification return true; // if we need to verify with the scope n by calling callback chain. // However, you need to register a callback for this. Default call back just return true. // you can find more details on writing custom scope validator from here // http://xacmlinfo.org/2014/10/24/authorization-for-apis-with-xacml-and-oauth-2-0/ // OAuthCallback scopeValidationCallback = new OAuthCallback( // tokReqMsgCtx.getAuthorizedUser().toString(), // tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId(), // OAuthCallback.OAuthCallbackType.SCOPE_VALIDATION_TOKEN); // scopeValidationCallback.setRequestedScope(tokReqMsgCtx.getScope()); // scopeValidationCallback.setCarbonGrantType(org.wso2.carbon.identity.oauth.common.GrantType.valueOf(tokReqMsgCtx. // getOauth2AccessTokenReqDTO().getGrantType())); // // callbackManager.handleCallback(scopeValidationCallback); // tokReqMsgCtx.setValidityPeriod(scopeValidationCallback.getValidityPeriod()); // tokReqMsgCtx.setScope(scopeValidationCallback.getApprovedScope()); // return scopeValidationCallback.isValidScope(); } /** * TODO * * You need to implement how to validate the mobile number * * @param mobileNumber * @return */ private boolean isValidMobileNumber(String mobileNumber){ // just demo validation if(mobileNumber.startsWith("033")){ return true; } return false; } @Override public boolean isOfTypeApplicationUser() throws IdentityOAuth2Exception { return true; } }
modules/samples/oauth2/custom-grant/src/main/java/org/wso2/sample/identity/oauth2/grant/mobile/MobileGrant.java
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.sample.identity.oauth2.grant.mobile; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.ResponseHeader; import org.wso2.carbon.identity.oauth2.model.RequestParameter; import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; import org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler; /** * New grant type for Identity Server */ public class MobileGrant extends AbstractAuthorizationGrantHandler { private static Log log = LogFactory.getLog(MobileGrant.class); public static final String MOBILE_GRANT_PARAM = "mobileNumber"; @Override public boolean validateGrant(OAuthTokenReqMessageContext oAuthTokenReqMessageContext) throws IdentityOAuth2Exception { log.info("Mobile Grant handler is hit"); boolean authStatus = false; // extract request parameters RequestParameter[] parameters = oAuthTokenReqMessageContext.getOauth2AccessTokenReqDTO().getRequestParameters(); String mobileNumber = null; // find out mobile number for(RequestParameter parameter : parameters){ if(MOBILE_GRANT_PARAM.equals(parameter.getKey())){ if(parameter.getValue() != null && parameter.getValue().length > 0){ mobileNumber = parameter.getValue()[0]; } } } if(mobileNumber != null) { //validate mobile number authStatus = isValidMobileNumber(mobileNumber); if(authStatus) { // if valid set authorized mobile number as grant user AuthenticatedUser mobileUser = new AuthenticatedUser(); mobileUser.setUserName(mobileNumber); mobileUser.setAuthenticatedSubjectIdentifier(mobileNumber); mobileUser.setFederatedUser(true); oAuthTokenReqMessageContext.setAuthorizedUser(mobileUser); oAuthTokenReqMessageContext.setScope(oAuthTokenReqMessageContext.getOauth2AccessTokenReqDTO().getScope()); } else{ ResponseHeader responseHeader = new ResponseHeader(); responseHeader.setKey("SampleHeader-999"); responseHeader.setValue("Provided Mobile Number is Invalid."); oAuthTokenReqMessageContext.addProperty("RESPONSE_HEADERS", new ResponseHeader[]{responseHeader}); } } return authStatus; } public boolean authorizeAccessDelegation(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { // if we need to just ignore the end user's extended verification return true; // if we need to verify with the end user's access delegation by calling callback chain. // However, you need to register a callback for this. Default call back just return true. // OAuthCallback authzCallback = new OAuthCallback( // tokReqMsgCtx.getAuthorizedUser(), // tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId(), // OAuthCallback.OAuthCallbackType.ACCESS_DELEGATION_TOKEN); // authzCallback.setRequestedScope(tokReqMsgCtx.getScope()); // authzCallback.setCarbonGrantType(org.wso2.carbon.identity.oauth.common.GrantType.valueOf(tokReqMsgCtx. // getOauth2AccessTokenReqDTO().getGrantType())); // callbackManager.handleCallback(authzCallback); // tokReqMsgCtx.setValidityPeriod(authzCallback.getValidityPeriod()); // return authzCallback.isAuthorized(); } public boolean validateScope(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception { // if we need to just ignore the scope verification return true; // if we need to verify with the scope n by calling callback chain. // However, you need to register a callback for this. Default call back just return true. // you can find more details on writing custom scope validator from here // http://xacmlinfo.org/2014/10/24/authorization-for-apis-with-xacml-and-oauth-2-0/ // OAuthCallback scopeValidationCallback = new OAuthCallback( // tokReqMsgCtx.getAuthorizedUser().toString(), // tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId(), // OAuthCallback.OAuthCallbackType.SCOPE_VALIDATION_TOKEN); // scopeValidationCallback.setRequestedScope(tokReqMsgCtx.getScope()); // scopeValidationCallback.setCarbonGrantType(org.wso2.carbon.identity.oauth.common.GrantType.valueOf(tokReqMsgCtx. // getOauth2AccessTokenReqDTO().getGrantType())); // // callbackManager.handleCallback(scopeValidationCallback); // tokReqMsgCtx.setValidityPeriod(scopeValidationCallback.getValidityPeriod()); // tokReqMsgCtx.setScope(scopeValidationCallback.getApprovedScope()); // return scopeValidationCallback.isValidScope(); } /** * TODO * * You need to implement how to validate the mobile number * * @param mobileNumber * @return */ private boolean isValidMobileNumber(String mobileNumber){ // just demo validation if(mobileNumber.startsWith("033")){ return true; } return false; } public boolean isOfTypeApplicationUser() throws IdentityOAuth2Exception { return true; } }
adding override annotation.
modules/samples/oauth2/custom-grant/src/main/java/org/wso2/sample/identity/oauth2/grant/mobile/MobileGrant.java
adding override annotation.
<ide><path>odules/samples/oauth2/custom-grant/src/main/java/org/wso2/sample/identity/oauth2/grant/mobile/MobileGrant.java <ide> return false; <ide> } <ide> <add> @Override <ide> public boolean isOfTypeApplicationUser() throws IdentityOAuth2Exception { <ide> return true; <ide> }
Java
apache-2.0
fd44820f7c3e3f59ab449f7c0c874066f6eb4528
0
java110/MicroCommunity,java110/MicroCommunity,java110/MicroCommunity,java110/MicroCommunity
package com.java110.front.smo.assetImport.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.java110.core.component.BaseComponentSMO; import com.java110.core.context.IPageData; import com.java110.entity.assetImport.*; import com.java110.entity.component.ComponentValidateResult; import com.java110.front.smo.assetImport.IAssetImportSMO; import com.java110.utils.constant.FeeTypeConstant; import com.java110.utils.constant.ServiceConstant; import com.java110.utils.util.*; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import java.util.ArrayList; import java.util.List; /** * @ClassName AssetImportSmoImpl * @Description TODO * @Author wuxw * @Date 2019/9/23 23:14 * @Version 1.0 * add by wuxw 2019/9/23 **/ @Service("assetImportSMOImpl") public class AssetImportSMOImpl extends BaseComponentSMO implements IAssetImportSMO { private final static Logger logger = LoggerFactory.getLogger(AssetImportSMOImpl.class); @Autowired private RestTemplate restTemplate; @Override public ResponseEntity<String> importExcelData(IPageData pd, MultipartFile uploadFile) throws Exception { try { ComponentValidateResult result = this.validateStoreStaffCommunityRelationship(pd, restTemplate); //InputStream is = uploadFile.getInputStream(); Workbook workbook = null; //工作簿 //工作表 String[] headers = null; //表头信息 List<ImportFloor> floors = new ArrayList<ImportFloor>(); List<ImportOwner> owners = new ArrayList<ImportOwner>(); List<ImportFee> fees = new ArrayList<>(); List<ImportRoom> rooms = new ArrayList<ImportRoom>(); List<ImportParkingSpace> parkingSpaces = new ArrayList<ImportParkingSpace>(); workbook = ImportExcelUtils.createWorkbook(uploadFile); //获取楼信息 getFloors(workbook, floors); //获取业主信息 getOwners(workbook, owners); getFee(workbook, fees); //获取房屋信息 getRooms(workbook, rooms, floors, owners); //获取车位信息 getParkingSpaces(workbook, parkingSpaces, owners); //数据校验 importExcelDataValidate(floors, owners, rooms, fees, parkingSpaces); // 保存数据 return dealExcelData(pd, floors, owners, rooms, parkingSpaces, fees, result); } catch (Exception e) { logger.error("导入失败 ", e); return new ResponseEntity<String>("非常抱歉,您填写的模板数据有误:" + e.getMessage(), HttpStatus.BAD_REQUEST); } } /** * 处理ExcelData数据 * * @param floors 楼栋单元信息 * @param owners 业主信息 * @param rooms 房屋信息 * @param parkingSpaces 车位信息 */ private ResponseEntity<String> dealExcelData(IPageData pd, List<ImportFloor> floors, List<ImportOwner> owners, List<ImportRoom> rooms, List<ImportParkingSpace> parkingSpaces, List<ImportFee> fees, ComponentValidateResult result) { ResponseEntity<String> responseEntity = null; //保存单元信息 和 楼栋信息 responseEntity = savedFloorAndUnitInfo(pd, floors, result); if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) { return responseEntity; } // 保存业主信息 responseEntity = savedOwnerInfo(pd, owners, result); if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) { return responseEntity; } // 保存费用项 responseEntity = savedFeeInfo(pd, fees, result); if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) { return responseEntity; } //保存房屋 responseEntity = savedRoomInfo(pd, rooms, fees, result); if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) { return responseEntity; } //保存车位 responseEntity = savedParkingSpaceInfo(pd, parkingSpaces, result); if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) { return responseEntity; } return responseEntity; } private ResponseEntity<String> savedFeeInfo(IPageData pd, List<ImportFee> fees, ComponentValidateResult result) { String apiUrl = ""; JSONObject paramIn = null; ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功", HttpStatus.OK); ImportOwner owner = null; for (ImportFee fee : fees) { JSONObject savedFeeConfigInfo = getExistsFee(pd, result, fee); if (savedFeeConfigInfo != null) { continue; } //paramIn = new JSONObject(); //保存 费用项 apiUrl = ServiceConstant.SERVICE_API_URL + "/api/feeConfig.saveFeeConfig"; paramIn = JSONObject.parseObject(JSONObject.toJSONString(fee)); paramIn.put("communityId", result.getCommunityId()); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); if (responseEntity.getStatusCode() != HttpStatus.OK) { continue; } } return responseEntity; } /** * 保存车位信息 * * @param pd * @param parkingSpaces * @param result * @return */ private ResponseEntity<String> savedParkingSpaceInfo(IPageData pd, List<ImportParkingSpace> parkingSpaces, ComponentValidateResult result) { String apiUrl = ""; JSONObject paramIn = null; ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功", HttpStatus.OK); ImportOwner owner = null; for (ImportParkingSpace parkingSpace : parkingSpaces) { JSONObject savedParkingAreaInfo = getExistsParkingArea(pd, result, parkingSpace); paramIn = new JSONObject(); // 如果不存在,才插入 if (savedParkingAreaInfo == null) { apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingArea.saveParkingArea"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("typeCd", parkingSpace.getTypeCd()); paramIn.put("num", parkingSpace.getPaNum()); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); savedParkingAreaInfo = getExistsParkingArea(pd, result, parkingSpace); } if (responseEntity != null && responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 continue; } JSONObject savedParkingSpaceInfo = getExistsParkSpace(pd, result, parkingSpace); if (savedParkingSpaceInfo != null) { continue; } apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingSpace.saveParkingSpace"; paramIn.put("paId", savedParkingAreaInfo.getString("paId")); paramIn.put("communityId", result.getCommunityId()); paramIn.put("userId", result.getUserId()); paramIn.put("num", parkingSpace.getPsNum()); paramIn.put("area", parkingSpace.getArea()); paramIn.put("typeCd", parkingSpace.getTypeCd()); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); if (responseEntity.getStatusCode() != HttpStatus.OK) { continue; } savedParkingSpaceInfo = getExistsParkSpace(pd, result, parkingSpace); if (savedParkingSpaceInfo == null) { continue; } //是否有业主信息 if (parkingSpace.getImportOwner() == null) { continue; } paramIn.clear(); paramIn.put("communityId", result.getCommunityId()); paramIn.put("ownerId", parkingSpace.getImportOwner().getOwnerId()); paramIn.put("userId", result.getUserId()); paramIn.put("carNum", parkingSpace.getCarNum()); paramIn.put("carBrand", parkingSpace.getCarBrand()); paramIn.put("carType", parkingSpace.getCarType()); paramIn.put("carColor", parkingSpace.getCarColor()); paramIn.put("psId", savedParkingSpaceInfo.getString("psId")); paramIn.put("storeId", result.getStoreId()); paramIn.put("sellOrHire", parkingSpace.getSellOrHire()); if ("H".equals(parkingSpace.getSellOrHire())) { paramIn.put("cycles", "0"); } String feeTypeCd = "1001".equals(parkingSpace.getTypeCd()) ? FeeTypeConstant.FEE_TYPE_SELL_UP_PARKING_SPACE : FeeTypeConstant.FEE_TYPE_SELL_DOWN_PARKING_SPACE; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/feeConfig.listFeeConfigs?page=1&row=1&communityId=" + result.getCommunityId() + "&feeTypeCd=" + feeTypeCd + "&isDefault=T"; responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { continue; } JSONObject configInfo = JSONObject.parseObject(responseEntity.getBody()).getJSONArray("feeConfigs").getJSONObject(0); if (!configInfo.containsKey("additionalAmount")) { continue; } paramIn.put("receivedAmount", configInfo.getString("additionalAmount")); apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingSpace.sellParkingSpace"; responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); } return responseEntity; } /** * 保存房屋信息 * * @param pd * @param rooms * @param result * @return */ private ResponseEntity<String> savedRoomInfo(IPageData pd, List<ImportRoom> rooms, List<ImportFee> fees, ComponentValidateResult result) { String apiUrl = ""; JSONObject paramIn = null; ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功", HttpStatus.OK); ImportOwner owner = null; for (ImportRoom room : rooms) { JSONObject savedRoomInfo = getExistsRoom(pd, result, room); if (savedRoomInfo != null) { continue; } paramIn = new JSONObject(); //保存 房屋 apiUrl = ServiceConstant.SERVICE_API_URL + "/api/room.saveRoom"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("unitId", room.getFloor().getUnitId()); paramIn.put("roomNum", room.getRoomNum()); paramIn.put("layer", room.getLayer()); paramIn.put("section", "1"); paramIn.put("apartment", room.getSection()); paramIn.put("state", "2002"); paramIn.put("builtUpArea", room.getBuiltUpArea()); paramIn.put("unitPrice", "1000.00"); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); if (responseEntity.getStatusCode() != HttpStatus.OK) { continue; } savedRoomInfo = getExistsRoom(pd, result, room); if (savedRoomInfo == null) { continue; } if (room.getImportOwner() == null) { continue; } paramIn.clear(); apiUrl = ServiceConstant.SERVICE_API_URL + "/api/room.sellRoom"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("ownerId", room.getImportOwner().getOwnerId()); paramIn.put("roomId", savedRoomInfo.getString("roomId")); paramIn.put("state", "2001"); paramIn.put("storeId", result.getStoreId()); if (!StringUtil.isEmpty(room.getRoomFeeId()) && "0".equals(room.getRoomFeeId())) { paramIn.put("feeEndDate", room.getFeeEndDate()); } responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); if (responseEntity.getStatusCode() != HttpStatus.OK) { continue; } //创建费用 if (StringUtil.isEmpty(room.getRoomFeeId()) || "0".equals(room.getRoomFeeId())) { continue; } String[] feeIds = room.getRoomFeeId().split("#"); for (int feeIndex = 0; feeIndex < feeIds.length; feeIndex++) { String feeId = feeIds[feeIndex]; ImportFee tmpFee = null; for (ImportFee fee : fees) { if (feeId.equals(fee.getId())) { tmpFee = fee; } } if (tmpFee == null) { continue;//没有费用项,可能写错了 } JSONObject ttFee = getExistsFee(pd, result, tmpFee); if (ttFee == null) { continue;//没有费用项,可能写错了 } apiUrl = ServiceConstant.SERVICE_API_URL + "/api/fee.saveRoomCreateFee"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("locationTypeCd", "3000"); paramIn.put("locationObjId", savedRoomInfo.getString("roomId")); paramIn.put("configId", ttFee.getString("configId")); paramIn.put("storeId", result.getStoreId()); paramIn.put("feeEndDate", room.getFeeEndDate().split("#")[feeIndex]); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); } } return responseEntity; } /** * 查询存在的房屋信息 * room.queryRooms * * @param pd * @param result * @param parkingSpace * @return */ private JSONObject getExistsParkSpace(IPageData pd, ComponentValidateResult result, ImportParkingSpace parkingSpace) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingSpace.queryParkingSpaces?page=1&row=1&communityId=" + result.getCommunityId() + "&num=" + parkingSpace.getPsNum(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedParkingSpaceInfoResults = JSONObject.parseObject(responseEntity.getBody()); if (!savedParkingSpaceInfoResults.containsKey("parkingSpaces") || savedParkingSpaceInfoResults.getJSONArray("parkingSpaces").size() != 1) { return null; } JSONObject savedParkingSpaceInfo = savedParkingSpaceInfoResults.getJSONArray("parkingSpaces").getJSONObject(0); return savedParkingSpaceInfo; } /** * 查询存在的房屋信息 * room.queryRooms * * @param pd * @param result * @param fee * @return */ private JSONObject getExistsFee(IPageData pd, ComponentValidateResult result, ImportFee fee) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/feeConfig.listFeeConfigs?page=1&row=1&communityId=" + result.getCommunityId() + "&feeName=" + fee.getFeeName(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedRoomInfoResults = JSONObject.parseObject(responseEntity.getBody()); if (!savedRoomInfoResults.containsKey("feeConfigs") || savedRoomInfoResults.getJSONArray("feeConfigs").size() != 1) { return null; } JSONObject savedFeeConfigInfo = savedRoomInfoResults.getJSONArray("feeConfigs").getJSONObject(0); return savedFeeConfigInfo; } /** * 查询存在的房屋信息 * room.queryRooms * * @param pd * @param result * @param room * @return */ private JSONObject getExistsRoom(IPageData pd, ComponentValidateResult result, ImportRoom room) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/room.queryRooms?page=1&row=1&communityId=" + result.getCommunityId() + "&floorId=" + room.getFloor().getFloorId() + "&unitId=" + room.getFloor().getUnitId() + "&roomNum=" + room.getRoomNum(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedRoomInfoResults = JSONObject.parseObject(responseEntity.getBody()); if (!savedRoomInfoResults.containsKey("rooms") || savedRoomInfoResults.getJSONArray("rooms").size() != 1) { return null; } JSONObject savedRoomInfo = savedRoomInfoResults.getJSONArray("rooms").getJSONObject(0); return savedRoomInfo; } /** * 保存业主信息 * * @param pd * @param owners * @param result * @return */ private ResponseEntity<String> savedOwnerInfo(IPageData pd, List<ImportOwner> owners, ComponentValidateResult result) { String apiUrl = ""; JSONObject paramIn = null; ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功", HttpStatus.OK); for (ImportOwner owner : owners) { JSONObject savedOwnerInfo = getExistsOwner(pd, result, owner); if (savedOwnerInfo != null) { owner.setOwnerId(savedOwnerInfo.getString("ownerId")); continue; } paramIn = new JSONObject(); apiUrl = ServiceConstant.SERVICE_API_URL + "/api/owner.saveOwner"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("userId", result.getUserId()); paramIn.put("name", owner.getOwnerName()); paramIn.put("age", owner.getAge()); paramIn.put("link", owner.getTel()); paramIn.put("sex", owner.getSex()); paramIn.put("ownerTypeCd", "1001"); paramIn.put("idCard", owner.getIdCard()); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); if (responseEntity.getStatusCode() == HttpStatus.OK) { JSONObject body = JSONObject.parseObject(responseEntity.getBody()); if (body.containsKey("code") && body.getIntValue("code") != 0) { throw new IllegalArgumentException(body.getString("msg")); } savedOwnerInfo = getExistsOwner(pd, result, owner); owner.setOwnerId(savedOwnerInfo.getString("ownerId")); } } return responseEntity; } /** * 保存 楼栋和 单元信息 * * @param pd * @param floors * @param result * @return */ private ResponseEntity<String> savedFloorAndUnitInfo(IPageData pd, List<ImportFloor> floors, ComponentValidateResult result) { String apiUrl = ""; JSONObject paramIn = null; ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功", HttpStatus.OK); for (ImportFloor importFloor : floors) { paramIn = new JSONObject(); //先保存 楼栋信息 JSONObject savedFloorInfo = getExistsFloor(pd, result, importFloor); // 如果不存在,才插入 if (savedFloorInfo == null) { apiUrl = ServiceConstant.SERVICE_API_URL + "/api/floor.saveFloor"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("floorNum", importFloor.getFloorNum()); paramIn.put("userId", result.getUserId()); paramIn.put("name", importFloor.getFloorNum() + "号楼"); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); savedFloorInfo = getExistsFloor(pd, result, importFloor); } if (responseEntity != null && responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 continue; } if (savedFloorInfo == null) { continue; } importFloor.setFloorId(savedFloorInfo.getString("floorId")); paramIn.clear(); //判断单元信息是否已经存在,如果存在则不保存数据unit.queryUnits JSONObject savedUnitInfo = getExistsUnit(pd, result, importFloor); if (savedUnitInfo != null) { importFloor.setUnitId(savedUnitInfo.getString("unitId")); continue; } apiUrl = ServiceConstant.SERVICE_API_URL + "/api/unit.saveUnit"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("floorId", savedFloorInfo.getString("floorId")); paramIn.put("unitNum", importFloor.getUnitNum()); paramIn.put("layerCount", importFloor.getLayerCount()); paramIn.put("lift", importFloor.getLift()); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); //将unitId 刷入ImportFloor对象 savedUnitInfo = getExistsUnit(pd, result, importFloor); importFloor.setUnitId(savedUnitInfo.getString("unitId")); } return responseEntity; } private JSONObject getExistsUnit(IPageData pd, ComponentValidateResult result, ImportFloor importFloor) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/unit.queryUnits?communityId=" + result.getCommunityId() + "&floorId=" + importFloor.getFloorId() + "&unitNum=" + importFloor.getUnitNum(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONArray savedFloorInfoResults = JSONArray.parseArray(responseEntity.getBody()); if (savedFloorInfoResults == null || savedFloorInfoResults.size() != 1) { return null; } JSONObject savedUnitInfo = savedFloorInfoResults.getJSONObject(0); return savedUnitInfo; } private JSONObject getExistsFloor(IPageData pd, ComponentValidateResult result, ImportFloor importFloor) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/floor.queryFloors?page=1&row=1&communityId=" + result.getCommunityId() + "&floorNum=" + importFloor.getFloorNum(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedFloorInfoResult = JSONObject.parseObject(responseEntity.getBody()); if (!savedFloorInfoResult.containsKey("apiFloorDataVoList") || savedFloorInfoResult.getJSONArray("apiFloorDataVoList").size() != 1) { return null; } JSONObject savedFloorInfo = savedFloorInfoResult.getJSONArray("apiFloorDataVoList").getJSONObject(0); return savedFloorInfo; } /** * 查询存在的业主 * * @param pd * @param result * @param importOwner * @return */ private JSONObject getExistsOwner(IPageData pd, ComponentValidateResult result, ImportOwner importOwner) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/owner.queryOwners?page=1&row=1&communityId=" + result.getCommunityId() + "&ownerTypeCd=1001&name=" + importOwner.getOwnerName() + "&link=" + importOwner.getTel(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedOwnerInfoResult = JSONObject.parseObject(responseEntity.getBody()); if (!savedOwnerInfoResult.containsKey("owners") || savedOwnerInfoResult.getJSONArray("owners").size() != 1) { return null; } JSONObject savedOwnerInfo = savedOwnerInfoResult.getJSONArray("owners").getJSONObject(0); return savedOwnerInfo; } /** * 查询存在的停车场 * * @param pd * @param result * @param parkingSpace * @return */ private JSONObject getExistsParkingArea(IPageData pd, ComponentValidateResult result, ImportParkingSpace parkingSpace) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingArea.listParkingAreas?page=1&row=1&communityId=" + result.getCommunityId() + "&num=" + parkingSpace.getPaNum(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedParkingAreaInfoResult = JSONObject.parseObject(responseEntity.getBody()); if (!savedParkingAreaInfoResult.containsKey("parkingAreas") || savedParkingAreaInfoResult.getJSONArray("parkingAreas").size() != 1) { return null; } JSONObject savedParkingAreaInfo = savedParkingAreaInfoResult.getJSONArray("parkingAreas").getJSONObject(0); return savedParkingAreaInfo; } /** * 数据校验处理 * * @param floors * @param owners * @param rooms * @param parkingSpaces */ private void importExcelDataValidate(List<ImportFloor> floors, List<ImportOwner> owners, List<ImportRoom> rooms, List<ImportFee> fees, List<ImportParkingSpace> parkingSpaces) { } /** * 获取车位信息 * * @param workbook * @param parkingSpaces */ private void getParkingSpaces(Workbook workbook, List<ImportParkingSpace> parkingSpaces, List<ImportOwner> owners) { Sheet sheet = null; sheet = ImportExcelUtils.getSheet(workbook, "车位信息"); List<Object[]> oList = ImportExcelUtils.listFromSheet(sheet); ImportParkingSpace importParkingSpace = null; for (int osIndex = 0; osIndex < oList.size(); osIndex++) { Object[] os = oList.get(osIndex); if (osIndex == 0) { // 第一行是 头部信息 直接跳过 continue; } if (StringUtil.isNullOrNone(os[0])) { continue; } Assert.hasValue(os[0], "车位信息选项中" + (osIndex + 1) + "行停车场编号为空"); Assert.hasValue(os[1], "车位信息选项中" + (osIndex + 1) + "行车位编码为空"); Assert.hasValue(os[2], "车位信息选项中" + (osIndex + 1) + "行停车场类型为空"); Assert.hasValue(os[3], "车位信息选项中" + (osIndex + 1) + "行面积为空,没有请填写规定值 如10"); importParkingSpace = new ImportParkingSpace(); importParkingSpace.setPaNum(os[0].toString()); importParkingSpace.setPsNum(os[1].toString()); importParkingSpace.setTypeCd(os[2].toString()); importParkingSpace.setArea(Double.parseDouble(os[3].toString())); if (StringUtil.isNullOrNone(os[4])) { parkingSpaces.add(importParkingSpace); continue; } ImportOwner importOwner = getImportOwner(owners, os[4].toString()); importParkingSpace.setImportOwner(importOwner); if (importOwner != null) { importParkingSpace.setCarNum(os[5].toString()); importParkingSpace.setCarBrand(os[6].toString()); importParkingSpace.setCarType(os[7].toString()); importParkingSpace.setCarColor(os[8].toString()); importParkingSpace.setSellOrHire(os[9].toString()); } parkingSpaces.add(importParkingSpace); } } /** * 获取 房屋信息 * * @param workbook * @param rooms */ private void getRooms(Workbook workbook, List<ImportRoom> rooms, List<ImportFloor> floors, List<ImportOwner> owners) { Sheet sheet = null; sheet = ImportExcelUtils.getSheet(workbook, "房屋信息"); List<Object[]> oList = ImportExcelUtils.listFromSheet(sheet); ImportRoom importRoom = null; for (int osIndex = 0; osIndex < oList.size(); osIndex++) { Object[] os = oList.get(osIndex); if (osIndex == 0) { // 第一行是 头部信息 直接跳过 continue; } if (StringUtil.isNullOrNone(os[0])) { continue; } Assert.hasValue(os[1], "房屋信息选项中" + (osIndex + 1) + "行楼栋编号为空"); Assert.hasValue(os[2], "房屋信息选项中" + (osIndex + 1) + "行单元编号为空"); Assert.hasValue(os[3], "房屋信息选项中" + (osIndex + 1) + "行房屋楼层为空"); Assert.hasValue(os[4], "房屋信息选项中" + (osIndex + 1) + "行房屋户型为空"); Assert.hasValue(os[5], "房屋信息选项中" + (osIndex + 1) + "行建筑面积为空"); if (!StringUtil.isNullOrNone(os[6])) { Assert.hasValue(os[7], "房屋信息选项中" + (osIndex + 1) + "行房屋费用为空"); Assert.hasValue(os[8], "房屋信息选项中" + (osIndex + 1) + "行费用到期时间为空"); } importRoom = new ImportRoom(); importRoom.setRoomNum(os[0].toString()); importRoom.setFloor(getImportFloor(floors, os[1].toString(), os[2].toString())); importRoom.setLayer(Integer.parseInt(os[3].toString())); importRoom.setSection(os[4].toString()); importRoom.setBuiltUpArea(Double.parseDouble(os[5].toString())); if (!StringUtil.isNullOrNone(os[6])) { importRoom.setRoomFeeId(os[7].toString()); importRoom.setFeeEndDate(os[8].toString()); } if (StringUtil.isNullOrNone(os[6])) { rooms.add(importRoom); continue; } importRoom.setImportOwner(getImportOwner(owners, os[6].toString())); rooms.add(importRoom); } } /** * 获取 房屋信息 * * @param workbook * @param importFees */ private void getFee(Workbook workbook, List<ImportFee> importFees) { Sheet sheet = null; sheet = ImportExcelUtils.getSheet(workbook, "费用设置"); List<Object[]> oList = ImportExcelUtils.listFromSheet(sheet); ImportFee importFee = null; for (int osIndex = 0; osIndex < oList.size(); osIndex++) { Object[] os = oList.get(osIndex); if (osIndex == 0) { // 第一行是 头部信息 直接跳过 continue; } if (StringUtil.isNullOrNone(os[0])) { continue; } Assert.hasValue(os[0], "费用设置选项中" + (osIndex + 1) + "行费用编号为空"); Assert.hasValue(os[1], "费用设置选项中" + (osIndex + 1) + "行费用类型为空"); Assert.hasValue(os[2], "费用设置选项中" + (osIndex + 1) + "行收费项目为空"); Assert.hasValue(os[3], "费用设置选项中" + (osIndex + 1) + "行费用标识为空"); Assert.hasValue(os[4], "费用设置选项中" + (osIndex + 1) + "行费用类型为空"); Assert.hasValue(os[5], "费用设置选项中" + (osIndex + 1) + "行缴费周期为空"); Assert.isInteger(os[5].toString(), "费用设置选项中" + (osIndex + 1) + "行缴费周期不是正整数"); Assert.hasValue(os[6], "费用设置选项中" + (osIndex + 1) + "行出账类型为空"); Assert.isDate(os[7].toString(), DateUtil.DATE_FORMATE_STRING_B, "费用设置选项中" + (osIndex + 1) + "行计费起始时间不是有效时间格式 请输入类似2020-06-01"); Assert.isDate(os[8].toString(), DateUtil.DATE_FORMATE_STRING_B, "费用设置选项中" + (osIndex + 1) + "行计费终止时间不是有效时间格式 请输入类似2037-01-01"); Assert.hasValue(os[9], "费用设置选项中" + (osIndex + 1) + "行计算公式为空"); if (!"1001".equals(os[9].toString()) && !"2002".equals(os[9].toString())) { throw new IllegalArgumentException("费用设置选项中" + (osIndex + 1) + "行计算公式错误 请填写1001 或者2002"); } Assert.hasValue(os[10], "费用设置选项中" + (osIndex + 1) + "行计费单价为空"); Assert.hasValue(os[11], "费用设置选项中" + (osIndex + 1) + "行固定费用为空"); importFee = new ImportFee(); importFee.setId(os[0].toString()); importFee.setFeeTypeCd("物业费".equals(os[1]) ? "888800010001" : "888800010002"); importFee.setFeeName(os[2].toString()); importFee.setFeeFlag("周期性费用".equals(os[3]) ? "1003006" : "2006012"); importFee.setPaymentCd("预付费".equals(os[4]) ? "1200" : "2100"); String billType = ""; if ("每年1月1日".equals(os[6])) { billType = "001"; } else if ("每月1日".equals(os[6])) { billType = "002"; } else if ("每日".equals(os[6])) { billType = "003"; } else { billType = "004"; } importFee.setBillType(billType); importFee.setPaymentCycle(os[5].toString()); importFee.setStartTime(os[7].toString()); importFee.setEndTime(os[8].toString()); importFee.setComputingFormula(os[9].toString()); importFee.setSquarePrice(os[10].toString()); importFee.setAdditionalAmount(os[11].toString()); importFees.add(importFee); } } /** * 从导入的业主信息中获取业主,如果没有返回 null * * @param owners * @param ownerNum * @return */ private ImportOwner getImportOwner(List<ImportOwner> owners, String ownerNum) { for (ImportOwner importOwner : owners) { if (ownerNum.equals(importOwner.getOwnerNum())) { return importOwner; } } return null; } /** * get 导入楼栋信息 * * @param floors */ private ImportFloor getImportFloor(List<ImportFloor> floors, String floorNum, String unitNum) { for (ImportFloor importFloor : floors) { if (floorNum.equals(importFloor.getFloorNum()) && unitNum.equals(importFloor.getUnitNum())) { return importFloor; } } throw new IllegalArgumentException("在楼栋单元sheet中未找到楼栋编号[" + floorNum + "],单元编号[" + unitNum + "]数据"); } /** * 获取业主信息 * * @param workbook * @param owners */ private void getOwners(Workbook workbook, List<ImportOwner> owners) { Sheet sheet = null; sheet = ImportExcelUtils.getSheet(workbook, "业主信息"); List<Object[]> oList = ImportExcelUtils.listFromSheet(sheet); ImportOwner importOwner = null; for (int osIndex = 0; osIndex < oList.size(); osIndex++) { Object[] os = oList.get(osIndex); if (osIndex == 0) { // 第一行是 头部信息 直接跳过 continue; } if (StringUtil.isNullOrNone(os[0])) { continue; } Assert.hasValue(os[0], "业主信息选项中" + (osIndex + 1) + "行业主编号为空"); Assert.hasValue(os[1], "业主信息选项中" + (osIndex + 1) + "行业主名称为空"); Assert.hasValue(os[2], "业主信息选项中" + (osIndex + 1) + "行业主性别为空"); String tel = StringUtil.isNullOrNone(os[4]) ? "19999999999" : os[4].toString(); String idCard = StringUtil.isNullOrNone(os[5]) ? "10000000000000000001" : os[5].toString(); if (os[4].toString().length() > 11) { throw new IllegalArgumentException(os[1].toString() + " 的手机号超过11位,请核实"); } if (os[5].toString().length() > 18) { throw new IllegalArgumentException(os[1].toString() + " 的身份证超过18位,请核实"); } String age = StringUtil.isNullOrNone(os[3]) ? CommonUtil.getAgeByCertId(idCard) : os[3].toString(); importOwner = new ImportOwner(); importOwner.setOwnerNum(os[0].toString()); importOwner.setOwnerName(os[1].toString()); importOwner.setSex("男".equals(os[2].toString()) ? "0" : "1"); importOwner.setAge(Integer.parseInt(age)); importOwner.setTel(tel); importOwner.setIdCard(idCard); owners.add(importOwner); } } /** * 获取小区 * * @param workbook * @param floors */ private void getFloors(Workbook workbook, List<ImportFloor> floors) { Sheet sheet = null; sheet = ImportExcelUtils.getSheet(workbook, "楼栋单元"); List<Object[]> oList = ImportExcelUtils.listFromSheet(sheet); ImportFloor importFloor = null; for (int osIndex = 0; osIndex < oList.size(); osIndex++) { Object[] os = oList.get(osIndex); if (osIndex == 0) { // 第一行是 头部信息 直接跳过 continue; } if (StringUtil.isNullOrNone(os[0])) { continue; } Assert.hasValue(os[0], "楼栋单元选项中" + (osIndex + 1) + "行楼栋号为空"); Assert.hasValue(os[1], "楼栋单元选项中" + (osIndex + 1) + "行单元编号为空"); Assert.hasValue(os[2], "楼栋单元选项中" + (osIndex + 1) + "行总楼层为空"); Assert.hasValue(os[3], "楼栋单元选项中" + (osIndex + 1) + "行是否有电梯为空"); importFloor = new ImportFloor(); importFloor.setFloorNum(os[0].toString()); importFloor.setUnitNum(os[1].toString()); importFloor.setLayerCount(os[2].toString()); importFloor.setLift("有".equals(os[3].toString()) ? "1010" : "2020"); floors.add(importFloor); } } public RestTemplate getRestTemplate() { return restTemplate; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } }
service-front/src/main/java/com/java110/front/smo/assetImport/impl/AssetImportSMOImpl.java
package com.java110.front.smo.assetImport.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.java110.core.component.BaseComponentSMO; import com.java110.core.context.IPageData; import com.java110.entity.assetImport.*; import com.java110.entity.component.ComponentValidateResult; import com.java110.front.smo.assetImport.IAssetImportSMO; import com.java110.utils.constant.FeeTypeConstant; import com.java110.utils.constant.ServiceConstant; import com.java110.utils.util.*; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import java.util.ArrayList; import java.util.List; /** * @ClassName AssetImportSmoImpl * @Description TODO * @Author wuxw * @Date 2019/9/23 23:14 * @Version 1.0 * add by wuxw 2019/9/23 **/ @Service("assetImportSMOImpl") public class AssetImportSMOImpl extends BaseComponentSMO implements IAssetImportSMO { private final static Logger logger = LoggerFactory.getLogger(AssetImportSMOImpl.class); @Autowired private RestTemplate restTemplate; @Override public ResponseEntity<String> importExcelData(IPageData pd, MultipartFile uploadFile) throws Exception { try { ComponentValidateResult result = this.validateStoreStaffCommunityRelationship(pd, restTemplate); //InputStream is = uploadFile.getInputStream(); Workbook workbook = null; //工作簿 //工作表 String[] headers = null; //表头信息 List<ImportFloor> floors = new ArrayList<ImportFloor>(); List<ImportOwner> owners = new ArrayList<ImportOwner>(); List<ImportFee> fees = new ArrayList<>(); List<ImportRoom> rooms = new ArrayList<ImportRoom>(); List<ImportParkingSpace> parkingSpaces = new ArrayList<ImportParkingSpace>(); workbook = ImportExcelUtils.createWorkbook(uploadFile); //获取楼信息 getFloors(workbook, floors); //获取业主信息 getOwners(workbook, owners); getFee(workbook, fees); //获取房屋信息 getRooms(workbook, rooms, floors, owners); //获取车位信息 getParkingSpaces(workbook, parkingSpaces, owners); //数据校验 importExcelDataValidate(floors, owners, rooms, fees, parkingSpaces); // 保存数据 return dealExcelData(pd, floors, owners, rooms, parkingSpaces, fees, result); } catch (Exception e) { logger.error("导入失败 ", e); return new ResponseEntity<String>("非常抱歉,您填写的模板数据有误:" + e.getMessage(), HttpStatus.BAD_REQUEST); } } /** * 处理ExcelData数据 * * @param floors 楼栋单元信息 * @param owners 业主信息 * @param rooms 房屋信息 * @param parkingSpaces 车位信息 */ private ResponseEntity<String> dealExcelData(IPageData pd, List<ImportFloor> floors, List<ImportOwner> owners, List<ImportRoom> rooms, List<ImportParkingSpace> parkingSpaces, List<ImportFee> fees, ComponentValidateResult result) { ResponseEntity<String> responseEntity = null; //保存单元信息 和 楼栋信息 responseEntity = savedFloorAndUnitInfo(pd, floors, result); if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) { return responseEntity; } // 保存业主信息 responseEntity = savedOwnerInfo(pd, owners, result); if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) { return responseEntity; } // 保存费用项 responseEntity = savedFeeInfo(pd, fees, result); if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) { return responseEntity; } //保存房屋 responseEntity = savedRoomInfo(pd, rooms, fees, result); if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) { return responseEntity; } //保存车位 responseEntity = savedParkingSpaceInfo(pd, parkingSpaces, result); if (responseEntity == null || responseEntity.getStatusCode() != HttpStatus.OK) { return responseEntity; } return responseEntity; } private ResponseEntity<String> savedFeeInfo(IPageData pd, List<ImportFee> fees, ComponentValidateResult result) { String apiUrl = ""; JSONObject paramIn = null; ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功", HttpStatus.OK); ImportOwner owner = null; for (ImportFee fee : fees) { JSONObject savedFeeConfigInfo = getExistsFee(pd, result, fee); if (savedFeeConfigInfo != null) { continue; } //paramIn = new JSONObject(); //保存 费用项 apiUrl = ServiceConstant.SERVICE_API_URL + "/api/feeConfig.saveFeeConfig"; paramIn = JSONObject.parseObject(JSONObject.toJSONString(fee)); paramIn.put("communityId", result.getCommunityId()); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); if (responseEntity.getStatusCode() != HttpStatus.OK) { continue; } } return responseEntity; } /** * 保存车位信息 * * @param pd * @param parkingSpaces * @param result * @return */ private ResponseEntity<String> savedParkingSpaceInfo(IPageData pd, List<ImportParkingSpace> parkingSpaces, ComponentValidateResult result) { String apiUrl = ""; JSONObject paramIn = null; ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功", HttpStatus.OK); ImportOwner owner = null; for (ImportParkingSpace parkingSpace : parkingSpaces) { JSONObject savedParkingAreaInfo = getExistsParkingArea(pd, result, parkingSpace); paramIn = new JSONObject(); // 如果不存在,才插入 if (savedParkingAreaInfo == null) { apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingArea.saveParkingArea"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("typeCd", parkingSpace.getTypeCd()); paramIn.put("num", parkingSpace.getPaNum()); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); savedParkingAreaInfo = getExistsParkingArea(pd, result, parkingSpace); } if (responseEntity != null && responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 continue; } JSONObject savedParkingSpaceInfo = getExistsParkSpace(pd, result, parkingSpace); if (savedParkingSpaceInfo != null) { continue; } apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingSpace.saveParkingSpace"; paramIn.put("paId", savedParkingAreaInfo.getString("paId")); paramIn.put("communityId", result.getCommunityId()); paramIn.put("userId", result.getUserId()); paramIn.put("num", parkingSpace.getPsNum()); paramIn.put("area", parkingSpace.getArea()); paramIn.put("typeCd", parkingSpace.getTypeCd()); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); if (responseEntity.getStatusCode() != HttpStatus.OK) { continue; } savedParkingSpaceInfo = getExistsParkSpace(pd, result, parkingSpace); if (savedParkingSpaceInfo == null) { continue; } //是否有业主信息 if (parkingSpace.getImportOwner() == null) { continue; } paramIn.clear(); paramIn.put("communityId", result.getCommunityId()); paramIn.put("ownerId", parkingSpace.getImportOwner().getOwnerId()); paramIn.put("userId", result.getUserId()); paramIn.put("carNum", parkingSpace.getCarNum()); paramIn.put("carBrand", parkingSpace.getCarBrand()); paramIn.put("carType", parkingSpace.getCarType()); paramIn.put("carColor", parkingSpace.getCarColor()); paramIn.put("psId", savedParkingSpaceInfo.getString("psId")); paramIn.put("storeId", result.getStoreId()); paramIn.put("sellOrHire", parkingSpace.getSellOrHire()); if ("H".equals(parkingSpace.getSellOrHire())) { paramIn.put("cycles", "0"); } String feeTypeCd = "1001".equals(parkingSpace.getTypeCd()) ? FeeTypeConstant.FEE_TYPE_SELL_UP_PARKING_SPACE : FeeTypeConstant.FEE_TYPE_SELL_DOWN_PARKING_SPACE; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/feeConfig.listFeeConfigs?page=1&row=1&communityId=" + result.getCommunityId() + "&feeTypeCd=" + feeTypeCd + "&isDefault=T"; responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { continue; } JSONObject configInfo = JSONObject.parseObject(responseEntity.getBody()).getJSONArray("feeConfigs").getJSONObject(0); if (!configInfo.containsKey("additionalAmount")) { continue; } paramIn.put("receivedAmount", configInfo.getString("additionalAmount")); apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingSpace.sellParkingSpace"; responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); } return responseEntity; } /** * 保存房屋信息 * * @param pd * @param rooms * @param result * @return */ private ResponseEntity<String> savedRoomInfo(IPageData pd, List<ImportRoom> rooms, List<ImportFee> fees, ComponentValidateResult result) { String apiUrl = ""; JSONObject paramIn = null; ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功", HttpStatus.OK); ImportOwner owner = null; for (ImportRoom room : rooms) { JSONObject savedRoomInfo = getExistsRoom(pd, result, room); if (savedRoomInfo != null) { continue; } paramIn = new JSONObject(); //保存 房屋 apiUrl = ServiceConstant.SERVICE_API_URL + "/api/room.saveRoom"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("unitId", room.getFloor().getUnitId()); paramIn.put("roomNum", room.getRoomNum()); paramIn.put("layer", room.getLayer()); paramIn.put("section", "1"); paramIn.put("apartment", room.getSection()); paramIn.put("state", "2002"); paramIn.put("builtUpArea", room.getBuiltUpArea()); paramIn.put("unitPrice", "1000.00"); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); if (responseEntity.getStatusCode() != HttpStatus.OK) { continue; } savedRoomInfo = getExistsRoom(pd, result, room); if (savedRoomInfo == null) { continue; } if (room.getImportOwner() == null) { continue; } paramIn.clear(); apiUrl = ServiceConstant.SERVICE_API_URL + "/api/room.sellRoom"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("ownerId", room.getImportOwner().getOwnerId()); paramIn.put("roomId", savedRoomInfo.getString("roomId")); paramIn.put("state", "2001"); paramIn.put("storeId", result.getStoreId()); if (!StringUtil.isEmpty(room.getRoomFeeId()) && "0".equals(room.getRoomFeeId())) { paramIn.put("feeEndDate", room.getFeeEndDate()); } responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); if (responseEntity.getStatusCode() != HttpStatus.OK) { continue; } //创建费用 if (StringUtil.isEmpty(room.getRoomFeeId()) || "0".equals(room.getRoomFeeId())) { continue; } String[] feeIds = room.getRoomFeeId().split("#"); for (int feeIndex = 0; feeIndex < feeIds.length; feeIndex++) { String feeId = feeIds[feeIndex]; ImportFee tmpFee = null; for (ImportFee fee : fees) { if (feeId.equals(fee.getId())) { tmpFee = fee; } } if (tmpFee == null) { continue;//没有费用项,可能写错了 } JSONObject ttFee = getExistsFee(pd, result, tmpFee); if (ttFee == null) { continue;//没有费用项,可能写错了 } apiUrl = ServiceConstant.SERVICE_API_URL + "/api/fee.saveRoomCreateFee"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("locationTypeCd", "3000"); paramIn.put("locationObjId", savedRoomInfo.getString("roomId")); paramIn.put("configId", ttFee.getString("configId")); paramIn.put("storeId", result.getStoreId()); paramIn.put("feeEndDate", room.getFeeEndDate().split("#")[feeIndex]); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); } } return responseEntity; } /** * 查询存在的房屋信息 * room.queryRooms * * @param pd * @param result * @param parkingSpace * @return */ private JSONObject getExistsParkSpace(IPageData pd, ComponentValidateResult result, ImportParkingSpace parkingSpace) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingSpace.queryParkingSpaces?page=1&row=1&communityId=" + result.getCommunityId() + "&num=" + parkingSpace.getPsNum(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedParkingSpaceInfoResults = JSONObject.parseObject(responseEntity.getBody()); if (!savedParkingSpaceInfoResults.containsKey("parkingSpaces") || savedParkingSpaceInfoResults.getJSONArray("parkingSpaces").size() != 1) { return null; } JSONObject savedParkingSpaceInfo = savedParkingSpaceInfoResults.getJSONArray("parkingSpaces").getJSONObject(0); return savedParkingSpaceInfo; } /** * 查询存在的房屋信息 * room.queryRooms * * @param pd * @param result * @param fee * @return */ private JSONObject getExistsFee(IPageData pd, ComponentValidateResult result, ImportFee fee) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/feeConfig.listFeeConfigs?page=1&row=1&communityId=" + result.getCommunityId() + "&feeName=" + fee.getFeeName(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedRoomInfoResults = JSONObject.parseObject(responseEntity.getBody()); if (!savedRoomInfoResults.containsKey("feeConfigs") || savedRoomInfoResults.getJSONArray("feeConfigs").size() != 1) { return null; } JSONObject savedFeeConfigInfo = savedRoomInfoResults.getJSONArray("feeConfigs").getJSONObject(0); return savedFeeConfigInfo; } /** * 查询存在的房屋信息 * room.queryRooms * * @param pd * @param result * @param room * @return */ private JSONObject getExistsRoom(IPageData pd, ComponentValidateResult result, ImportRoom room) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/room.queryRooms?page=1&row=1&communityId=" + result.getCommunityId() + "&floorId=" + room.getFloor().getFloorId() + "&unitId=" + room.getFloor().getUnitId() + "&roomNum=" + room.getRoomNum(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedRoomInfoResults = JSONObject.parseObject(responseEntity.getBody()); if (!savedRoomInfoResults.containsKey("rooms") || savedRoomInfoResults.getJSONArray("rooms").size() != 1) { return null; } JSONObject savedRoomInfo = savedRoomInfoResults.getJSONArray("rooms").getJSONObject(0); return savedRoomInfo; } /** * 保存业主信息 * * @param pd * @param owners * @param result * @return */ private ResponseEntity<String> savedOwnerInfo(IPageData pd, List<ImportOwner> owners, ComponentValidateResult result) { String apiUrl = ""; JSONObject paramIn = null; ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功", HttpStatus.OK); for (ImportOwner owner : owners) { JSONObject savedOwnerInfo = getExistsOwner(pd, result, owner); if (savedOwnerInfo != null) { owner.setOwnerId(savedOwnerInfo.getString("ownerId")); continue; } paramIn = new JSONObject(); apiUrl = ServiceConstant.SERVICE_API_URL + "/api/owner.saveOwner"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("userId", result.getUserId()); paramIn.put("name", owner.getOwnerName()); paramIn.put("age", owner.getAge()); paramIn.put("link", owner.getTel()); paramIn.put("sex", owner.getSex()); paramIn.put("ownerTypeCd", "1001"); paramIn.put("idCard", owner.getIdCard()); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); if (responseEntity.getStatusCode() == HttpStatus.OK) { JSONObject body = JSONObject.parseObject(responseEntity.getBody()); if (body.containsKey("code") && body.getIntValue("code") != 0) { throw new IllegalArgumentException(body.getString("msg")); } savedOwnerInfo = getExistsOwner(pd, result, owner); owner.setOwnerId(savedOwnerInfo.getString("ownerId")); } } return responseEntity; } /** * 保存 楼栋和 单元信息 * * @param pd * @param floors * @param result * @return */ private ResponseEntity<String> savedFloorAndUnitInfo(IPageData pd, List<ImportFloor> floors, ComponentValidateResult result) { String apiUrl = ""; JSONObject paramIn = null; ResponseEntity<String> responseEntity = new ResponseEntity<String>("成功", HttpStatus.OK); for (ImportFloor importFloor : floors) { paramIn = new JSONObject(); //先保存 楼栋信息 JSONObject savedFloorInfo = getExistsFloor(pd, result, importFloor); // 如果不存在,才插入 if (savedFloorInfo == null) { apiUrl = ServiceConstant.SERVICE_API_URL + "/api/floor.saveFloor"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("floorNum", importFloor.getFloorNum()); paramIn.put("userId", result.getUserId()); paramIn.put("name", importFloor.getFloorNum() + "号楼"); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); savedFloorInfo = getExistsFloor(pd, result, importFloor); } if (responseEntity != null && responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 continue; } if (savedFloorInfo == null) { continue; } importFloor.setFloorId(savedFloorInfo.getString("floorId")); paramIn.clear(); //判断单元信息是否已经存在,如果存在则不保存数据unit.queryUnits JSONObject savedUnitInfo = getExistsUnit(pd, result, importFloor); if (savedUnitInfo != null) { importFloor.setUnitId(savedUnitInfo.getString("unitId")); continue; } apiUrl = ServiceConstant.SERVICE_API_URL + "/api/unit.saveUnit"; paramIn.put("communityId", result.getCommunityId()); paramIn.put("floorId", savedFloorInfo.getString("floorId")); paramIn.put("unitNum", importFloor.getUnitNum()); paramIn.put("layerCount", importFloor.getLayerCount()); paramIn.put("lift", importFloor.getLift()); responseEntity = this.callCenterService(restTemplate, pd, paramIn.toJSONString(), apiUrl, HttpMethod.POST); //将unitId 刷入ImportFloor对象 savedUnitInfo = getExistsUnit(pd, result, importFloor); importFloor.setUnitId(savedUnitInfo.getString("unitId")); } return responseEntity; } private JSONObject getExistsUnit(IPageData pd, ComponentValidateResult result, ImportFloor importFloor) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/unit.queryUnits?communityId=" + result.getCommunityId() + "&floorId=" + importFloor.getFloorId() + "&unitNum=" + importFloor.getUnitNum(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONArray savedFloorInfoResults = JSONArray.parseArray(responseEntity.getBody()); if (savedFloorInfoResults == null || savedFloorInfoResults.size() != 1) { return null; } JSONObject savedUnitInfo = savedFloorInfoResults.getJSONObject(0); return savedUnitInfo; } private JSONObject getExistsFloor(IPageData pd, ComponentValidateResult result, ImportFloor importFloor) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/floor.queryFloors?page=1&row=1&communityId=" + result.getCommunityId() + "&floorNum=" + importFloor.getFloorNum(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedFloorInfoResult = JSONObject.parseObject(responseEntity.getBody()); if (!savedFloorInfoResult.containsKey("apiFloorDataVoList") || savedFloorInfoResult.getJSONArray("apiFloorDataVoList").size() != 1) { return null; } JSONObject savedFloorInfo = savedFloorInfoResult.getJSONArray("apiFloorDataVoList").getJSONObject(0); return savedFloorInfo; } /** * 查询存在的业主 * * @param pd * @param result * @param importOwner * @return */ private JSONObject getExistsOwner(IPageData pd, ComponentValidateResult result, ImportOwner importOwner) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/owner.queryOwners?page=1&row=1&communityId=" + result.getCommunityId() + "&ownerTypeCd=1001&name=" + importOwner.getOwnerName() + "&link=" + importOwner.getTel(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedOwnerInfoResult = JSONObject.parseObject(responseEntity.getBody()); if (!savedOwnerInfoResult.containsKey("owners") || savedOwnerInfoResult.getJSONArray("owners").size() != 1) { return null; } JSONObject savedOwnerInfo = savedOwnerInfoResult.getJSONArray("owners").getJSONObject(0); return savedOwnerInfo; } /** * 查询存在的停车场 * * @param pd * @param result * @param parkingSpace * @return */ private JSONObject getExistsParkingArea(IPageData pd, ComponentValidateResult result, ImportParkingSpace parkingSpace) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/parkingArea.listParkingAreas?page=1&row=1&communityId=" + result.getCommunityId() + "&num=" + parkingSpace.getPaNum(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedParkingAreaInfoResult = JSONObject.parseObject(responseEntity.getBody()); if (!savedParkingAreaInfoResult.containsKey("parkingAreas") || savedParkingAreaInfoResult.getJSONArray("parkingAreas").size() != 1) { return null; } JSONObject savedParkingAreaInfo = savedParkingAreaInfoResult.getJSONArray("parkingAreas").getJSONObject(0); return savedParkingAreaInfo; } /** * 数据校验处理 * * @param floors * @param owners * @param rooms * @param parkingSpaces */ private void importExcelDataValidate(List<ImportFloor> floors, List<ImportOwner> owners, List<ImportRoom> rooms, List<ImportFee> fees, List<ImportParkingSpace> parkingSpaces) { } /** * 获取车位信息 * * @param workbook * @param parkingSpaces */ private void getParkingSpaces(Workbook workbook, List<ImportParkingSpace> parkingSpaces, List<ImportOwner> owners) { Sheet sheet = null; sheet = ImportExcelUtils.getSheet(workbook, "车位信息"); List<Object[]> oList = ImportExcelUtils.listFromSheet(sheet); ImportParkingSpace importParkingSpace = null; for (int osIndex = 0; osIndex < oList.size(); osIndex++) { Object[] os = oList.get(osIndex); if (osIndex == 0) { // 第一行是 头部信息 直接跳过 continue; } if (StringUtil.isNullOrNone(os[0])) { continue; } Assert.hasValue(os[0], "车位信息选项中" + (osIndex + 1) + "行停车场编号为空"); Assert.hasValue(os[1], "车位信息选项中" + (osIndex + 1) + "行车位编码为空"); Assert.hasValue(os[2], "车位信息选项中" + (osIndex + 1) + "行停车场类型为空"); Assert.hasValue(os[3], "车位信息选项中" + (osIndex + 1) + "行面积为空,没有请填写规定值 如10"); importParkingSpace = new ImportParkingSpace(); importParkingSpace.setPaNum(os[0].toString()); importParkingSpace.setPsNum(os[1].toString()); importParkingSpace.setTypeCd(os[2].toString()); importParkingSpace.setArea(Double.parseDouble(os[3].toString())); if (StringUtil.isNullOrNone(os[4])) { parkingSpaces.add(importParkingSpace); continue; } ImportOwner importOwner = getImportOwner(owners, os[4].toString()); importParkingSpace.setImportOwner(importOwner); if (importOwner != null) { importParkingSpace.setCarNum(os[5].toString()); importParkingSpace.setCarBrand(os[6].toString()); importParkingSpace.setCarType(os[7].toString()); importParkingSpace.setCarColor(os[8].toString()); importParkingSpace.setSellOrHire(os[9].toString()); } parkingSpaces.add(importParkingSpace); } } /** * 获取 房屋信息 * * @param workbook * @param rooms */ private void getRooms(Workbook workbook, List<ImportRoom> rooms, List<ImportFloor> floors, List<ImportOwner> owners) { Sheet sheet = null; sheet = ImportExcelUtils.getSheet(workbook, "房屋信息"); List<Object[]> oList = ImportExcelUtils.listFromSheet(sheet); ImportRoom importRoom = null; for (int osIndex = 0; osIndex < oList.size(); osIndex++) { Object[] os = oList.get(osIndex); if (osIndex == 0) { // 第一行是 头部信息 直接跳过 continue; } if (StringUtil.isNullOrNone(os[0])) { continue; } Assert.hasValue(os[1], "房屋信息选项中" + (osIndex + 1) + "行楼栋编号为空"); Assert.hasValue(os[2], "房屋信息选项中" + (osIndex + 1) + "行单元编号为空"); Assert.hasValue(os[3], "房屋信息选项中" + (osIndex + 1) + "行房屋楼层为空"); Assert.hasValue(os[4], "房屋信息选项中" + (osIndex + 1) + "行房屋户型为空"); Assert.hasValue(os[5], "房屋信息选项中" + (osIndex + 1) + "行建筑面积为空"); if (!StringUtil.isNullOrNone(os[6])) { Assert.hasValue(os[7], "房屋信息选项中" + (osIndex + 1) + "行房屋费用为空"); Assert.hasValue(os[8], "房屋信息选项中" + (osIndex + 1) + "行费用到期时间为空"); } importRoom = new ImportRoom(); importRoom.setRoomNum(os[0].toString()); importRoom.setFloor(getImportFloor(floors, os[1].toString(), os[2].toString())); importRoom.setLayer(Integer.parseInt(os[3].toString())); importRoom.setSection(os[4].toString()); importRoom.setBuiltUpArea(Double.parseDouble(os[5].toString())); if (!StringUtil.isNullOrNone(os[6])) { importRoom.setRoomFeeId(os[7].toString()); importRoom.setFeeEndDate(os[8].toString()); } if (StringUtil.isNullOrNone(os[6])) { rooms.add(importRoom); continue; } importRoom.setImportOwner(getImportOwner(owners, os[6].toString())); rooms.add(importRoom); } } /** * 获取 房屋信息 * * @param workbook * @param importFees */ private void getFee(Workbook workbook, List<ImportFee> importFees) { Sheet sheet = null; sheet = ImportExcelUtils.getSheet(workbook, "费用设置"); List<Object[]> oList = ImportExcelUtils.listFromSheet(sheet); ImportFee importFee = null; for (int osIndex = 0; osIndex < oList.size(); osIndex++) { Object[] os = oList.get(osIndex); if (osIndex == 0) { // 第一行是 头部信息 直接跳过 continue; } if (StringUtil.isNullOrNone(os[0])) { continue; } Assert.hasValue(os[0], "费用设置选项中" + (osIndex + 1) + "行费用编号为空"); Assert.hasValue(os[1], "费用设置选项中" + (osIndex + 1) + "行费用类型为空"); Assert.hasValue(os[2], "费用设置选项中" + (osIndex + 1) + "行收费项目为空"); Assert.hasValue(os[3], "费用设置选项中" + (osIndex + 1) + "行费用标识为空"); Assert.hasValue(os[4], "费用设置选项中" + (osIndex + 1) + "行费用类型为空"); Assert.hasValue(os[5], "费用设置选项中" + (osIndex + 1) + "行缴费周期为空"); Assert.isInteger(os[5].toString(), "费用设置选项中" + (osIndex + 1) + "行缴费周期不是正整数"); Assert.hasValue(os[6], "费用设置选项中" + (osIndex + 1) + "行出账类型为空"); Assert.isDate(os[7].toString(), DateUtil.DATE_FORMATE_STRING_B, "费用设置选项中" + (osIndex + 1) + "行计费起始时间不是有效时间格式 请输入类似2020-06-01"); Assert.isDate(os[8].toString(), DateUtil.DATE_FORMATE_STRING_B, "费用设置选项中" + (osIndex + 1) + "行计费终止时间不是有效时间格式 请输入类似2037-01-01"); Assert.hasValue(os[9], "费用设置选项中" + (osIndex + 1) + "行计算公式为空"); if (!"1001".equals(os[9].toString()) && !"2002".equals(os[9].toString())) { throw new IllegalArgumentException("费用设置选项中" + (osIndex + 1) + "行计算公式错误 请填写1001 或者2002"); } Assert.hasValue(os[10], "费用设置选项中" + (osIndex + 1) + "行计费单价为空"); Assert.hasValue(os[11], "费用设置选项中" + (osIndex + 1) + "行固定费用为空"); importFee = new ImportFee(); importFee.setId(os[0].toString()); importFee.setFeeTypeCd("物业费".equals(os[1]) ? "888800010001" : "888800010002"); importFee.setFeeName(os[2].toString()); importFee.setFeeFlag("周期性费用".equals(os[3]) ? "1003006" : "2006012"); importFee.setPaymentCd("预付费".equals(os[4]) ? "1200" : "2100"); String billType = ""; if ("每年1月1日".equals(os[6])) { billType = "001"; } else if ("每月1日".equals(os[6])) { billType = "002"; } else if ("每日".equals(os[6])) { billType = "003"; } else { billType = "004"; } importFee.setBillType(billType); importFee.setPaymentCycle(os[5].toString()); importFee.setStartTime(os[7].toString()); importFee.setEndTime(os[8].toString()); importFee.setComputingFormula(os[9].toString()); importFee.setSquarePrice(os[10].toString()); importFee.setAdditionalAmount(os[11].toString()); importFees.add(importFee); } } /** * 从导入的业主信息中获取业主,如果没有返回 null * * @param owners * @param ownerNum * @return */ private ImportOwner getImportOwner(List<ImportOwner> owners, String ownerNum) { for (ImportOwner importOwner : owners) { if (ownerNum.equals(importOwner.getOwnerNum())) { return importOwner; } } return null; } /** * get 导入楼栋信息 * * @param floors */ private ImportFloor getImportFloor(List<ImportFloor> floors, String floorNum, String unitNum) { for (ImportFloor importFloor : floors) { if (floorNum.equals(importFloor.getFloorNum()) && unitNum.equals(importFloor.getUnitNum())) { return importFloor; } } throw new IllegalArgumentException("在楼栋单元sheet中未找到楼栋编号[" + floorNum + "],单元编号[" + unitNum + "]数据"); } /** * 获取业主信息 * * @param workbook * @param owners */ private void getOwners(Workbook workbook, List<ImportOwner> owners) { Sheet sheet = null; sheet = ImportExcelUtils.getSheet(workbook, "业主信息"); List<Object[]> oList = ImportExcelUtils.listFromSheet(sheet); ImportOwner importOwner = null; for (int osIndex = 0; osIndex < oList.size(); osIndex++) { Object[] os = oList.get(osIndex); if (osIndex == 0) { // 第一行是 头部信息 直接跳过 continue; } if (StringUtil.isNullOrNone(os[0])) { continue; } Assert.hasValue(os[0], "业主信息选项中" + (osIndex + 1) + "行业主编号为空"); Assert.hasValue(os[1], "业主信息选项中" + (osIndex + 1) + "行业主名称为空"); Assert.hasValue(os[2], "业主信息选项中" + (osIndex + 1) + "行业主性别为空"); String tel = StringUtil.isNullOrNone(os[4]) ? "19999999999" : os[4].toString(); String idCard = StringUtil.isNullOrNone(os[5]) ? "10000000000000000001" : os[5].toString(); if (os[5].toString().length() > 18) { throw new IllegalArgumentException(os[1].toString() + " 的身份证超过18位,请核实"); } String age = StringUtil.isNullOrNone(os[3]) ? CommonUtil.getAgeByCertId(idCard) : os[3].toString(); importOwner = new ImportOwner(); importOwner.setOwnerNum(os[0].toString()); importOwner.setOwnerName(os[1].toString()); importOwner.setSex("男".equals(os[2].toString()) ? "0" : "1"); importOwner.setAge(Integer.parseInt(age)); importOwner.setTel(tel); importOwner.setIdCard(idCard); owners.add(importOwner); } } /** * 获取小区 * * @param workbook * @param floors */ private void getFloors(Workbook workbook, List<ImportFloor> floors) { Sheet sheet = null; sheet = ImportExcelUtils.getSheet(workbook, "楼栋单元"); List<Object[]> oList = ImportExcelUtils.listFromSheet(sheet); ImportFloor importFloor = null; for (int osIndex = 0; osIndex < oList.size(); osIndex++) { Object[] os = oList.get(osIndex); if (osIndex == 0) { // 第一行是 头部信息 直接跳过 continue; } if (StringUtil.isNullOrNone(os[0])) { continue; } Assert.hasValue(os[0], "楼栋单元选项中" + (osIndex + 1) + "行楼栋号为空"); Assert.hasValue(os[1], "楼栋单元选项中" + (osIndex + 1) + "行单元编号为空"); Assert.hasValue(os[2], "楼栋单元选项中" + (osIndex + 1) + "行总楼层为空"); Assert.hasValue(os[3], "楼栋单元选项中" + (osIndex + 1) + "行是否有电梯为空"); importFloor = new ImportFloor(); importFloor.setFloorNum(os[0].toString()); importFloor.setUnitNum(os[1].toString()); importFloor.setLayerCount(os[2].toString()); importFloor.setLift("有".equals(os[3].toString()) ? "1010" : "2020"); floors.add(importFloor); } } public RestTemplate getRestTemplate() { return restTemplate; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } }
资产导入时校验手机号位数 超过11位报错
service-front/src/main/java/com/java110/front/smo/assetImport/impl/AssetImportSMOImpl.java
资产导入时校验手机号位数 超过11位报错
<ide><path>ervice-front/src/main/java/com/java110/front/smo/assetImport/impl/AssetImportSMOImpl.java <ide> String tel = StringUtil.isNullOrNone(os[4]) ? "19999999999" : os[4].toString(); <ide> String idCard = StringUtil.isNullOrNone(os[5]) ? "10000000000000000001" : os[5].toString(); <ide> <add> if (os[4].toString().length() > 11) { <add> throw new IllegalArgumentException(os[1].toString() + " 的手机号超过11位,请核实"); <add> } <ide> if (os[5].toString().length() > 18) { <ide> throw new IllegalArgumentException(os[1].toString() + " 的身份证超过18位,请核实"); <ide> }
Java
apache-2.0
f70a319677b2a131b41b8e581406de066ea86c2d
0
osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi
/* * Copyright (c) IBM Corporation (2010, 2011). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.test.cases.framework.junit.wiring; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.Filter; import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.osgi.framework.FrameworkUtil; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleRevisions; import org.osgi.framework.wiring.BundleWire; import org.osgi.framework.wiring.BundleWiring; import org.osgi.framework.wiring.FrameworkWiring; import org.osgi.test.support.OSGiTestCase; public class BundleWiringTests extends OSGiTestCase { private final List<Bundle> bundles = new ArrayList<Bundle>(); FrameworkWiring frameworkWiring; public Bundle install(String bundle) { Bundle result = null; try { result = super.install(bundle); } catch (BundleException e) { fail("failed to install bundle: " + bundle, e); } catch (IOException e) { fail("failed to install bundle: " + bundle, e); } if (!bundles.contains(result)) bundles.add(result); return result; } protected void setUp() throws Exception { bundles.clear(); frameworkWiring = (FrameworkWiring) getContext().getBundle(0).adapt(FrameworkWiring.class); } protected void tearDown() throws Exception { for (Iterator<Bundle> iBundles = bundles.iterator(); iBundles.hasNext();) try { iBundles.next().uninstall(); } catch (BundleException e) { // nothing } catch (IllegalStateException e) { // happens if the test uninstalls the bundle itself } refreshBundles(bundles); bundles.clear(); } private void refreshBundles(List<Bundle> bundles) { final boolean[] done = new boolean[] {false}; FrameworkListener listener = new FrameworkListener() { public void frameworkEvent(FrameworkEvent event) { synchronized (done) { if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) { done[0] = true; done.notify(); } } } }; frameworkWiring.refreshBundles(bundles, new FrameworkListener[] {listener}); synchronized (done) { if (!done[0]) try { done.wait(5000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); fail("Unexepected interruption.", e); } if (!done[0]) fail("Timed out waiting for refresh bundles to finish."); } } public void testGetRevision() { Bundle tb1 = install("resolver.tb1.v110.jar"); Bundle tb2 = install("resolver.tb2.jar"); Bundle tb3 = install("resolver.tb3.jar"); Bundle tb4 = install("resolver.tb4.jar"); Bundle tb5 = install("resolver.tb5.jar"); Bundle tb14 = install("resolver.tb14.jar"); List<Bundle> testBundles = Arrays.asList(tb1, tb2, tb3, tb4, tb5, tb14); assertTrue(frameworkWiring.resolveBundles(testBundles)); List<BundleRevision> testRevisions = getRevisions(testBundles); BundleRevision tb1Revision = testRevisions.get(0); BundleRevision tb2Revision = testRevisions.get(1); BundleRevision tb3Revision = testRevisions.get(2); BundleRevision tb4Revision = testRevisions.get(3); BundleRevision tb5Revision = testRevisions.get(4); BundleRevision tb14Revision = testRevisions.get(5); List<BundleCapability> tb1AllCapabilities = tb1Revision.getDeclaredCapabilities(null); List<BundleCapability> tb1BundleCapabilities = tb1Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb1HostCapabilities = tb1Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb1PackageCapabilities = tb1Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); List<BundleCapability> tb1TestCapabilities = tb1Revision.getDeclaredCapabilities("test"); List<BundleCapability> tb1TestMultipleCapabilities = tb1Revision.getDeclaredCapabilities("test.multiple"); List<BundleCapability> tb1TestFragmentCapabilities = tb1Revision.getDeclaredCapabilities("test.fragment"); checkCapabilities(tb1BundleCapabilities, tb1AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 1, tb1Revision); checkCapabilities(tb1HostCapabilities, tb1AllCapabilities, BundleRevision.HOST_NAMESPACE, 1, tb1Revision); checkCapabilities(tb1PackageCapabilities, tb1AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 1, tb1Revision); checkCapabilities(tb1TestCapabilities, tb1AllCapabilities, "test", 1, tb1Revision); checkCapabilities(tb1TestMultipleCapabilities, tb1AllCapabilities, "test.multiple", 2, tb1Revision); checkCapabilities(tb1TestFragmentCapabilities, tb1AllCapabilities, "test.fragment", 0, tb1Revision); List<BundleRequirement> tb1AllRequirements = tb1Revision.getDeclaredRequirements(null); List<BundleRequirement> tb1BundleRequirements = tb1Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb1HostRequirements = tb1Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb1PackageRequirements = tb1Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); checkRequirements(tb1BundleRequirements, tb1AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 0, tb1Revision); checkRequirements(tb1HostRequirements, tb1AllRequirements, BundleRevision.HOST_NAMESPACE, 0, tb1Revision); checkRequirements(tb1PackageRequirements, tb1AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 0, tb1Revision); List<BundleCapability> tb2AllCapabilities = tb2Revision.getDeclaredCapabilities(null); List<BundleCapability> tb2BundleCapabilities = tb2Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb2HostCapabilities = tb2Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb2PackageCapabilities = tb2Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); checkCapabilities(tb2BundleCapabilities, tb2AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 1, tb2Revision); checkCapabilities(tb2HostCapabilities, tb2AllCapabilities, BundleRevision.HOST_NAMESPACE, 0, tb2Revision); checkCapabilities(tb2PackageCapabilities, tb2AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 0, tb2Revision); List<BundleRequirement> tb2AllRequirements = tb2Revision.getDeclaredRequirements(null); List<BundleRequirement> tb2BundleRequirements = tb2Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb2HostRequirements = tb2Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb2PackageRequirements = tb2Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); checkRequirements(tb2BundleRequirements, tb2AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 0, tb2Revision); checkRequirements(tb2HostRequirements, tb2AllRequirements, BundleRevision.HOST_NAMESPACE, 0, tb2Revision); checkRequirements(tb2PackageRequirements, tb2AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 2, tb2Revision); List<BundleCapability> tb3AllCapabilities = tb3Revision.getDeclaredCapabilities(null); List<BundleCapability> tb3BundleCapabilities = tb3Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb3HostCapabilities = tb3Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb3PackageCapabilities = tb3Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); checkCapabilities(tb3BundleCapabilities, tb3AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 1, tb3Revision); checkCapabilities(tb3HostCapabilities, tb3AllCapabilities, BundleRevision.HOST_NAMESPACE, 1, tb3Revision); checkCapabilities(tb3PackageCapabilities, tb3AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 0, tb3Revision); List<BundleRequirement> tb3AllRequirements = tb3Revision.getDeclaredRequirements(null); List<BundleRequirement> tb3BundleRequirements = tb3Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb3HostRequirements = tb3Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb3PackageRequirements = tb3Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); checkRequirements(tb3BundleRequirements, tb3AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 1, tb3Revision); checkRequirements(tb3HostRequirements, tb3AllRequirements, BundleRevision.HOST_NAMESPACE, 0, tb3Revision); checkRequirements(tb3PackageRequirements, tb3AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 1, tb3Revision); List<BundleCapability> tb4AllCapabilities = tb4Revision.getDeclaredCapabilities(null); List<BundleCapability> tb4BundleCapabilities = tb4Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb4HostCapabilities = tb4Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb4PackageCapabilities = tb4Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); List<BundleCapability> tb4TestFragmentCapabilities = tb4Revision.getDeclaredCapabilities("test.fragment"); checkCapabilities(tb4BundleCapabilities, tb4AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 0, tb4Revision); checkCapabilities(tb4HostCapabilities, tb4AllCapabilities, BundleRevision.HOST_NAMESPACE, 0, tb4Revision); checkCapabilities(tb4PackageCapabilities, tb4AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 0, tb4Revision); checkCapabilities(tb4TestFragmentCapabilities, tb4AllCapabilities, "test.fragment", 1, tb4Revision); List<BundleRequirement> tb4AllRequirements = tb4Revision.getDeclaredRequirements(null); List<BundleRequirement> tb4BundleRequirements = tb4Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb4HostRequirements = tb4Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb4PackageRequirements = tb4Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); checkRequirements(tb4BundleRequirements, tb4AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 0, tb4Revision); checkRequirements(tb4HostRequirements, tb4AllRequirements, BundleRevision.HOST_NAMESPACE, 1, tb4Revision); checkRequirements(tb4PackageRequirements, tb4AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 0, tb4Revision); List<BundleCapability> tb5AllCapabilities = tb5Revision.getDeclaredCapabilities(null); List<BundleCapability> tb5BundleCapabilities = tb5Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb5HostCapabilities = tb5Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb5PackageCapabilities = tb5Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); checkCapabilities(tb5BundleCapabilities, tb5AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 1, tb5Revision); checkCapabilities(tb5HostCapabilities, tb5AllCapabilities, BundleRevision.HOST_NAMESPACE, 1, tb5Revision); checkCapabilities(tb5PackageCapabilities, tb5AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 0, tb5Revision); List<BundleRequirement> tb5AllRequirements = tb5Revision.getDeclaredRequirements(null); List<BundleRequirement> tb5BundleRequirements = tb5Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb5HostRequirements = tb5Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb5PackageRequirements = tb5Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); List<BundleRequirement> tb5TestRequirements = tb5Revision.getDeclaredRequirements("test"); List<BundleRequirement> tb5TestNoAttrsRequirements = tb5Revision.getDeclaredRequirements("test.no.attrs"); checkRequirements(tb5BundleRequirements, tb5AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 0, tb5Revision); checkRequirements(tb5HostRequirements, tb5AllRequirements, BundleRevision.HOST_NAMESPACE, 0, tb5Revision); checkRequirements(tb5PackageRequirements, tb5AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 0, tb5Revision); checkRequirements(tb5TestRequirements, tb5AllRequirements, "test", 10, tb5Revision); checkRequirements(tb5TestNoAttrsRequirements, tb5AllRequirements, "test.no.attrs", 1, tb5Revision); List<BundleCapability> tb14AllCapabilities = tb14Revision.getDeclaredCapabilities(null); List<BundleCapability> tb14BundleCapabilities = tb14Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb14HostCapabilities = tb14Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb14PackageCapabilities = tb14Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); checkCapabilities(tb14BundleCapabilities, tb14AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 1, tb14Revision); checkCapabilities(tb14HostCapabilities, tb14AllCapabilities, BundleRevision.HOST_NAMESPACE, 1, tb14Revision); checkCapabilities(tb14PackageCapabilities, tb14AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 0, tb14Revision); List<BundleRequirement> tb14AllRequirements = tb14Revision.getDeclaredRequirements(null); List<BundleRequirement> tb14BundleRequirements = tb14Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb14HostRequirements = tb14Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb14PackageRequirements = tb14Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); List<BundleRequirement> tb14TestFragmentRequirements = tb14Revision.getDeclaredRequirements("test.fragment"); checkRequirements(tb14BundleRequirements, tb14AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 0, tb14Revision); checkRequirements(tb14HostRequirements, tb14AllRequirements, BundleRevision.HOST_NAMESPACE, 0, tb14Revision); checkRequirements(tb14PackageRequirements, tb14AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 0, tb14Revision); checkRequirements(tb14TestFragmentRequirements, tb14AllRequirements, "test.fragment", 1, tb14Revision); } void checkCapabilities(List<BundleCapability> toCheck, List<BundleCapability> all, String namespace, int expectedNum, BundleRevision provider) { assertEquals("Wrong number of capabilities for " + namespace + " from " + provider, expectedNum, toCheck.size()); for (BundleCapability capability : toCheck) { assertTrue("Capability is not in all capabilities", all.contains(capability)); assertEquals("Wrong namespace", namespace, capability.getNamespace()); assertEquals("Wrong provider", provider, capability.getRevision()); } } void checkRequirements(List<BundleRequirement> toCheck, List<BundleRequirement> all, String namespace, int expectedNum, BundleRevision requirer) { assertEquals("Wrong number of requirements for " + namespace + " from " + requirer, expectedNum, toCheck.size()); for (BundleRequirement requirement : toCheck) { assertTrue("Capability is not in all capabilities", all.contains(requirement)); assertEquals("Wrong namespace", namespace, requirement.getNamespace()); assertEquals("Wrong requirer", requirer, requirement.getRevision()); } } void checkWires(List<BundleWire> toCheck, List<BundleWire> all, String namespace, int expectedNum) { assertEquals("Wrong number of wires for " + namespace, expectedNum, toCheck.size()); for (BundleWire wire : toCheck) { assertTrue("Capability is not in all capabilities for revision", all.contains(wire)); } } private List<BundleRevision> getRevisions(List<Bundle> testBundles) { ArrayList<BundleRevision> result = new ArrayList<BundleRevision>(testBundles.size()); for (Bundle bundle : testBundles) { BundleRevision revision = bundle.adapt(BundleRevision.class); result.add(revision); assertEquals("Wrong BSN", bundle.getSymbolicName(), revision.getSymbolicName()); assertEquals("Wrong bundle", bundle, revision.getBundle()); assertEquals("Wrong version", bundle.getVersion(), revision.getVersion()); assertEquals("Wrong type", bundle.getHeaders("").get(Constants.FRAGMENT_HOST) == null ? 0 : BundleRevision.TYPE_FRAGMENT, revision.getTypes()); Collection<BundleWire> hostWirings = revision.getWiring().getRequiredWires(BundleRevision.HOST_NAMESPACE); assertNotNull("Host wirings must never be null.", hostWirings); if ((revision.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) { // we assume the fragment resolved to one host assertEquals("Wrong number of host wirings found", 1, hostWirings.size()); } else { // regular bundles must have empty host wirings assertEquals("Must have empty wirings for regular bundles", 0, hostWirings.size()); } } return result; } public void testGetWiring() { Bundle tb1 = install("resolver.tb1.v110.jar"); Bundle tb2 = install("resolver.tb2.jar"); Bundle tb3 = install("resolver.tb3.jar"); Bundle tb4 = install("resolver.tb4.jar"); Bundle tb5 = install("resolver.tb5.jar"); Bundle tb14 = install("resolver.tb14.jar"); List<Bundle> testBundles = Arrays.asList(tb1, tb2, tb3, tb4, tb5, tb14); assertTrue(frameworkWiring.resolveBundles(testBundles)); BundleWiring tb1Wiring = tb1.adapt(BundleWiring.class); BundleWiring tb2Wiring = tb2.adapt(BundleWiring.class); BundleWiring tb3Wiring = tb3.adapt(BundleWiring.class); BundleWiring tb4Wiring = tb4.adapt(BundleWiring.class); BundleWiring tb5Wiring = tb5.adapt(BundleWiring.class); BundleWiring tb14Wiring = tb14.adapt(BundleWiring.class); BundleWiring[] wirings = new BundleWiring[] {tb1Wiring, tb2Wiring, tb3Wiring, tb4Wiring, tb5Wiring, tb14Wiring}; checkBundleWiring(testBundles.toArray(new Bundle[6]), wirings); List<BundleWire> allTb1Capabilities = tb1Wiring.getProvidedWires(null); List<BundleWire> osgiBundleTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.BUNDLE_NAMESPACE); List<BundleWire> osgiHostTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); List<BundleWire> osgiPackageTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE); List<BundleWire> genTestTb1Capabilities = tb1Wiring.getProvidedWires("test"); List<BundleWire> genTestMultipleTb1Capabilities = tb1Wiring.getProvidedWires("test.multiple"); List<BundleWire> genTestNoAttrsTb1Capabilities = tb1Wiring.getProvidedWires("test.no.attrs"); List<BundleWire> genTestFragmentTb1Capabilities = tb1Wiring.getProvidedWires("test.fragment"); // check for osgi.wiring.host capability from wiring with // fragment-attachment:="never" List<BundleCapability> osgiHostTb2Capabilities = tb2Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE); assertEquals("Expecting no osgi.wiring.host capability", 0, osgiHostTb2Capabilities.size()); checkBundleWires(tb1Wiring, tb2Wiring, tb3Wiring, tb5Wiring, tb14Wiring, tb4, allTb1Capabilities, osgiBundleTb1Capabilities, osgiHostTb1Capabilities, osgiPackageTb1Capabilities, genTestTb1Capabilities, genTestMultipleTb1Capabilities, genTestFragmentTb1Capabilities, genTestNoAttrsTb1Capabilities); // test the refresh case refreshBundles(Arrays.asList(new Bundle[]{tb1})); assertTrue(frameworkWiring.resolveBundles(testBundles)); checkNotInUseWirings(wirings); tb1Wiring = tb1.adapt(BundleWiring.class); tb2Wiring = tb2.adapt(BundleWiring.class); tb3Wiring = tb3.adapt(BundleWiring.class); tb4Wiring = tb4.adapt(BundleWiring.class); tb5Wiring = tb5.adapt(BundleWiring.class); tb14Wiring = tb14.adapt(BundleWiring.class); wirings = new BundleWiring[] {tb1Wiring, tb2Wiring, tb3Wiring, tb4Wiring, tb5Wiring, tb14Wiring}; checkBundleWiring(testBundles.toArray(new Bundle[6]), wirings); // get wired capabilities before update osgiBundleTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.BUNDLE_NAMESPACE); osgiHostTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); osgiPackageTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE); genTestTb1Capabilities = tb1Wiring.getProvidedWires("test"); genTestMultipleTb1Capabilities = tb1Wiring.getProvidedWires("test.multiple"); genTestNoAttrsTb1Capabilities = tb1Wiring.getProvidedWires("test.no.attrs"); genTestFragmentTb1Capabilities = tb1Wiring.getProvidedWires("test.fragment"); // test the update case URL content = getContext().getBundle().getEntry("resolver.tb1.v110.jar"); assertNotNull("Cannot find content for update", content); try { tb1.update(content.openStream()); } catch (BundleException e) { fail("Unexpected update failure",e); } catch (IOException e) { fail("Unexpected update failure",e); } assertTrue("Could not resolve updated bundle", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb1}))); // check that the updated wiring has no requirers BundleWiring updatedWiring = (BundleWiring) tb1.adapt(BundleWiring.class); checkBundleWiring(new Bundle[] {tb1}, new BundleWiring[] {updatedWiring}); List<BundleWire> updatedWires = updatedWiring.getProvidedWires(null); assertNotNull("Requirers is null", updatedWires); assertEquals("Wrong number of requirers", 0, updatedWires.size()); assertTrue("Wiring is not in use for: " + tb1, tb1Wiring.isInUse()); assertFalse("Wiring is current for: " + tb1, tb1Wiring.isCurrent()); // Check that old wiring for tb1 is still correct allTb1Capabilities = tb1Wiring.getProvidedWires(null); checkBundleWires(tb1Wiring, tb2Wiring, tb3Wiring, tb5Wiring, tb14Wiring, tb4, allTb1Capabilities, osgiBundleTb1Capabilities, osgiHostTb1Capabilities, osgiPackageTb1Capabilities, genTestTb1Capabilities, genTestMultipleTb1Capabilities, genTestFragmentTb1Capabilities, genTestNoAttrsTb1Capabilities); // test the refresh case refreshBundles(Arrays.asList(new Bundle[]{tb1})); assertTrue(frameworkWiring.resolveBundles(testBundles)); checkNotInUseWirings(wirings); checkNotInUseWirings(new BundleWiring[] {updatedWiring}); tb1Wiring = tb1.adapt(BundleWiring.class); tb2Wiring = tb2.adapt(BundleWiring.class); tb3Wiring = tb3.adapt(BundleWiring.class); tb4Wiring = tb4.adapt(BundleWiring.class); tb5Wiring = tb5.adapt(BundleWiring.class); tb14Wiring = tb14.adapt(BundleWiring.class); wirings = new BundleWiring[] {tb1Wiring, tb2Wiring, tb3Wiring, tb4Wiring, tb5Wiring, tb14Wiring}; checkBundleWiring(testBundles.toArray(new Bundle[6]), wirings); // test uninstall case try { tb1.uninstall(); } catch (BundleException e) { fail("Unexpecte error on uninstall", e); } assertNull("Bundle wiring is not null for bundle: " + tb1, tb1.adapt(BundleWiring.class)); // note that we do not reget tb1Wiring because it must be null on uninstall from the check above tb2Wiring = tb2.adapt(BundleWiring.class); tb3Wiring = tb3.adapt(BundleWiring.class); tb4Wiring = tb4.adapt(BundleWiring.class); tb5Wiring = tb5.adapt(BundleWiring.class); tb14Wiring = tb14.adapt(BundleWiring.class); wirings = new BundleWiring[] {tb1Wiring, tb2Wiring, tb3Wiring, tb4Wiring, tb5Wiring, tb14Wiring}; assertTrue("Wiring is not in use for: " + tb1, tb1Wiring.isInUse()); assertFalse("Wring is current for: " + tb1, tb1Wiring.isCurrent()); allTb1Capabilities = tb1Wiring.getProvidedWires(null); osgiBundleTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.BUNDLE_NAMESPACE); osgiHostTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); osgiPackageTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE); genTestTb1Capabilities = tb1Wiring.getProvidedWires("test"); genTestMultipleTb1Capabilities = tb1Wiring.getProvidedWires("test.multiple"); genTestNoAttrsTb1Capabilities = tb1Wiring.getProvidedWires("test.no.attrs"); genTestFragmentTb1Capabilities = tb1Wiring.getProvidedWires("test.fragment"); checkBundleWires(tb1Wiring, tb2Wiring, tb3Wiring, tb5Wiring, tb14Wiring, tb4, allTb1Capabilities, osgiBundleTb1Capabilities, osgiHostTb1Capabilities, osgiPackageTb1Capabilities, genTestTb1Capabilities, genTestMultipleTb1Capabilities, genTestFragmentTb1Capabilities, genTestNoAttrsTb1Capabilities); // test the refresh case refreshBundles(null); assertFalse(frameworkWiring.resolveBundles(testBundles)); checkNotInUseWirings(wirings); // Wirings must be null now since the bundles are not resolved assertNull("Bundle wiring is not null for bundle: " + tb1, tb1.adapt(BundleWiring.class)); assertNull("Bundle wiring is not null for bundle: " + tb2, tb2.adapt(BundleWiring.class)); assertNull("Bundle wiring is not null for bundle: " + tb3, tb3.adapt(BundleWiring.class)); assertNull("Bundle wiring is not null for bundle: " + tb4, tb4.adapt(BundleWiring.class)); assertNull("Bundle wiring is not null for bundle: " + tb5, tb5.adapt(BundleWiring.class)); } private void checkBundleWiring(Bundle[] bundles, BundleWiring[] wirings) { assertEquals("Lists are not the same size", bundles.length, wirings.length); for (int i = 0; i < wirings.length; i++) { BundleWiring wiring = wirings[i]; Bundle bundle = bundles[i]; BundleRevision revision = bundle.adapt(BundleRevision.class); assertNotNull("BundleRevision is null for: " + bundle, revision); assertEquals("Wrong BSN", bundle.getSymbolicName(), revision.getSymbolicName()); assertEquals("Wrong version", bundle.getVersion(), revision.getVersion()); assertNotNull("BundleWiring is null for bundle: " + bundle, wiring); assertEquals("Wrong bundle for wiring: " + bundle, bundle, wiring.getBundle()); BundleRevision wiringRevision = wiring.getRevision(); assertNotNull("Wiring revision is null for bundle: " + bundle, wiringRevision); assertEquals("Wrong BSN", bundle.getSymbolicName(), wiringRevision.getSymbolicName()); assertEquals("Wrong version", bundle.getVersion(), wiringRevision.getVersion()); assertTrue("Wiring is not current for: " + bundle, wiring.isCurrent()); assertTrue("Wiring is not in use for: " + bundle, wiring.isInUse()); } } private void checkNotInUseWirings(BundleWiring[] wirings) { for (int i = 0; i < wirings.length; i++) { BundleWiring wiring = wirings[i]; if (wiring == null) continue; // fragment case assertFalse("Wiring is current for: " + wiring.getBundle(), wiring.isCurrent()); assertFalse("Wiring is in use for: " + wiring.getBundle(), wiring.isInUse()); assertNull("Wiring capabilities must be null: " + wiring.getBundle(), wiring.getCapabilities(null)); assertNull("Wiring requirements must be null: " + wiring.getBundle(), wiring.getRequirements(null)); assertNull("Wiring class loader must be null: " + wiring.getBundle(), wiring.getClassLoader()); assertNull("Wiring findEntries must be null: " + wiring.getBundle(), wiring.findEntries("/", "*", 0)); assertNull("Wiring listResources must be null: " + wiring.getBundle(), wiring.listResources("/", "*", 0)); assertNull("Wiring providedWires must be null: " + wiring.getBundle(), wiring.getProvidedWires(null)); assertNull("Wiring requiredWires must be null: " + wiring.getBundle(), wiring.getRequiredWires(null)); } } private void checkCapabilitiesTb1v110(BundleWiring tb1Wiring, Bundle tb4) { assertEquals("Wrong number of capabilities", 8, tb1Wiring.getCapabilities(null).size()); checkCapabilities( tb1Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE), tb1Wiring.getCapabilities(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb1Wiring.getRevision()); checkCapabilities( tb1Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE), tb1Wiring.getCapabilities(null), BundleRevision.HOST_NAMESPACE, 1, tb1Wiring.getRevision()); checkCapabilities( tb1Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE), tb1Wiring.getCapabilities(null), BundleRevision.PACKAGE_NAMESPACE, 1, tb1Wiring.getRevision()); checkCapabilities( tb1Wiring.getCapabilities("test"), tb1Wiring.getCapabilities(null), "test", 1, tb1Wiring.getRevision()); checkCapabilities( tb1Wiring.getCapabilities("test.multiple"), tb1Wiring.getCapabilities(null), "test.multiple", 2, tb1Wiring.getRevision()); checkCapabilities( tb1Wiring.getCapabilities("test.fragment"), tb1Wiring.getCapabilities(null), "test.fragment", 1, tb4.adapt(BundleRevision.class)); checkCapabilities( tb1Wiring.getCapabilities("test.no.attrs"), tb1Wiring.getCapabilities(null), "test.no.attrs", 1, tb1Wiring.getRevision()); } private void checkCapabilitiesTb2(BundleWiring tb2Wiring) { assertEquals("Wrong number of capabilities", 1, tb2Wiring.getCapabilities(null).size()); checkCapabilities( tb2Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE), tb2Wiring.getCapabilities(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb2Wiring.getRevision()); checkCapabilities( tb2Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE), tb2Wiring.getCapabilities(null), BundleRevision.HOST_NAMESPACE, 0, tb2Wiring.getRevision()); checkCapabilities( tb2Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE), tb2Wiring.getCapabilities(null), BundleRevision.PACKAGE_NAMESPACE, 0, tb2Wiring.getRevision()); } private void checkCapabilitiesTb3(BundleWiring tb3Wiring) { assertEquals("Wrong number of capabilities", 2, tb3Wiring.getCapabilities(null).size()); checkCapabilities( tb3Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE), tb3Wiring.getCapabilities(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb3Wiring.getRevision()); checkCapabilities( tb3Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE), tb3Wiring.getCapabilities(null), BundleRevision.HOST_NAMESPACE, 1, tb3Wiring.getRevision()); checkCapabilities( tb3Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getCapabilities(null), BundleRevision.PACKAGE_NAMESPACE, 0, tb3Wiring.getRevision()); } private void checkCapabilitiesTb4(BundleWiring tb4Wiring) { assertEquals("Wrong number of capabilities", 0, tb4Wiring.getCapabilities(null).size()); } private void checkCapabilitiesTb5(BundleWiring tb5Wiring) { assertEquals("Wrong number of capabilities", 2, tb5Wiring.getCapabilities(null).size()); checkCapabilities( tb5Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE), tb5Wiring.getCapabilities(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb5Wiring.getRevision()); checkCapabilities( tb5Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE), tb5Wiring.getCapabilities(null), BundleRevision.HOST_NAMESPACE, 1, tb5Wiring.getRevision()); checkCapabilities( tb5Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE), tb5Wiring.getCapabilities(null), BundleRevision.PACKAGE_NAMESPACE, 0, tb5Wiring.getRevision()); } private void checkCapabilitiesTb14(BundleWiring tb14Wiring) { assertEquals("Wrong number of capabilities", 2, tb14Wiring.getCapabilities(null).size()); checkCapabilities( tb14Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE), tb14Wiring.getCapabilities(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb14Wiring.getRevision()); checkCapabilities( tb14Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE), tb14Wiring.getCapabilities(null), BundleRevision.HOST_NAMESPACE, 1, tb14Wiring.getRevision()); checkCapabilities( tb14Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE), tb14Wiring.getCapabilities(null), BundleRevision.PACKAGE_NAMESPACE, 0, tb14Wiring.getRevision()); } private void checkRequirementsTb1v110(BundleWiring tb1Wiring) { assertEquals("Wrong number of requirements", 0, tb1Wiring.getRequirements(null).size()); } private void checkRequirementsTb2(BundleWiring tb2Wiring) { assertEquals("Wrong number of requirements", 2, tb2Wiring.getRequirements(null).size()); checkRequirements( tb2Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE), tb2Wiring.getRequirements(null), BundleRevision.PACKAGE_NAMESPACE, 2, tb2Wiring.getRevision()); } private void checkRequirementsTb3(BundleWiring tb3Wiring) { assertEquals("Wrong number of requirements", 2, tb3Wiring.getRequirements(null).size()); checkRequirements( tb3Wiring.getRequirements(BundleRevision.BUNDLE_NAMESPACE), tb3Wiring.getRequirements(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb3Wiring.getRevision()); checkRequirements( tb3Wiring.getRequirements(BundleRevision.HOST_NAMESPACE), tb3Wiring.getRequirements(null), BundleRevision.HOST_NAMESPACE, 0, tb3Wiring.getRevision()); checkRequirements( tb3Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequirements(null), BundleRevision.PACKAGE_NAMESPACE, 1, tb3Wiring.getRevision()); } private void checkRequirementsTb4(BundleWiring tb4Wiring) { assertEquals("Wrong number of requirements", 1, tb4Wiring.getRequirements(null).size()); checkRequirements( tb4Wiring.getRequirements(BundleRevision.BUNDLE_NAMESPACE), tb4Wiring.getRequirements(null), BundleRevision.BUNDLE_NAMESPACE, 0, tb4Wiring.getRevision()); checkRequirements( tb4Wiring.getRequirements(BundleRevision.HOST_NAMESPACE), tb4Wiring.getRequirements(null), BundleRevision.HOST_NAMESPACE, 1, tb4Wiring.getRevision()); checkRequirements( tb4Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE), tb4Wiring.getRequirements(null), BundleRevision.PACKAGE_NAMESPACE, 0, tb4Wiring.getRevision()); } private void checkRequirementsTb5(BundleWiring tb5Wiring) { assertEquals("Wrong number of requirements", 11, tb5Wiring.getRequirements(null).size()); checkRequirements( tb5Wiring.getRequirements("test"), tb5Wiring.getRequirements(null), "test", 10, tb5Wiring.getRevision()); checkRequirements( tb5Wiring.getRequirements("test.no.attrs"), tb5Wiring.getRequirements(null), "test.no.attrs", 1, tb5Wiring.getRevision()); } private void checkRequirementsTb14(BundleWiring tb14Wiring) { assertEquals("Wrong number of requirements", 1, tb14Wiring.getRequirements(null).size()); checkRequirements( tb14Wiring.getRequirements("test.fragment"), tb14Wiring.getRequirements(null), "test.fragment", 1, tb14Wiring.getRevision()); } private void checkBundleWires( BundleWiring tb1Wiring, BundleWiring tb2Wiring, BundleWiring tb3Wiring, BundleWiring tb5Wiring, BundleWiring tb14Wiring, Bundle tb4, List<BundleWire> allTb1ProvidedWires, List<BundleWire> osgiBundleTb1ProvidedWires, List<BundleWire> osgiHostTb1ProvidedWires, List<BundleWire> osgiPackageTb1ProvidedWires, List<BundleWire> genTestTb1ProvidedWires, List<BundleWire> genTestMultipleTb1ProvidedWires, List<BundleWire> genTestFragmentTb1ProvidedWires, List<BundleWire> genTestNoAttrsTb1ProvidedWires) { assertEquals("Wrong number of wires", 15, allTb1ProvidedWires.size()); checkWires(osgiBundleTb1ProvidedWires, allTb1ProvidedWires, BundleRevision.BUNDLE_NAMESPACE, 1); checkWires(osgiHostTb1ProvidedWires, allTb1ProvidedWires, BundleRevision.HOST_NAMESPACE, 1); checkWires(osgiPackageTb1ProvidedWires, allTb1ProvidedWires, BundleRevision.PACKAGE_NAMESPACE, 1); checkWires(genTestTb1ProvidedWires, allTb1ProvidedWires, "test", 10); checkWires(genTestMultipleTb1ProvidedWires, allTb1ProvidedWires, "test.multiple", 0); checkWires(genTestFragmentTb1ProvidedWires, allTb1ProvidedWires, "test.fragment", 1); checkWires(genTestNoAttrsTb1ProvidedWires, allTb1ProvidedWires, "test.no.attrs", 1); checkCapabilitiesTb1v110(tb1Wiring, tb4); checkCapabilitiesTb2(tb2Wiring); checkCapabilitiesTb3(tb3Wiring); checkCapabilitiesTb4(tb4.adapt(BundleWiring.class)); checkCapabilitiesTb5(tb5Wiring); checkCapabilitiesTb14(tb14Wiring); checkRequirementsTb1v110(tb1Wiring); checkRequirementsTb2(tb2Wiring); checkRequirementsTb3(tb3Wiring); checkRequirementsTb4(tb4.adapt(BundleWiring.class)); checkRequirementsTb5(tb5Wiring); checkRequirementsTb14(tb14Wiring); checkBundleWire( osgiBundleTb1ProvidedWires.get(0), tb1Wiring, tb3Wiring, tb1Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE).get(0), tb3Wiring.getRequirements(BundleRevision.BUNDLE_NAMESPACE).get(0)); checkBundleWire( osgiHostTb1ProvidedWires.get(0), tb1Wiring, tb4.adapt(BundleWiring.class), tb1Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE).get(0), tb4.adapt(BundleWiring.class).getRequirements(BundleRevision.HOST_NAMESPACE).get(0)); checkBundleWire( osgiPackageTb1ProvidedWires.get(0), tb1Wiring, tb2Wiring, tb1Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE).get(0), tb2Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE).get(1)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(0), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(0)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(1), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(1)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(2), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(2)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(3), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(3)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(4), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(4)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(5), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(5)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(6), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(6)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(7), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(7)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(8), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(8)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(9), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(9)); checkBundleWire( genTestNoAttrsTb1ProvidedWires.get(0), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test.no.attrs").get(0), tb5Wiring.getRequirements("test.no.attrs").get(0)); checkBundleWire( genTestFragmentTb1ProvidedWires.get(0), tb1Wiring, tb14Wiring, tb1Wiring.getCapabilities("test.fragment").get(0), tb14Wiring.getRequirements("test.fragment").get(0)); List<BundleWire> fragments = tb1Wiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); assertEquals("Wrong number of fragments", 1, fragments.size()); assertEquals("Wrong fragment", tb4, fragments.get(0).getRequirerWiring().getBundle()); } private void checkBundleWire( BundleWire wire, BundleWiring provider, BundleWiring requirer, BundleCapability capability, BundleRequirement requirement) { assertEquals("Wrong provider", provider, wire.getProviderWiring()); assertEquals("Wrong requirer", requirer, wire.getRequirerWiring()); assertEquals("Wrong capability", capability, wire.getCapability()); assertEquals("Wrong requirement", requirement, wire.getRequirement()); assertTrue("Requirement does not match capability", wire.getRequirement().matches(wire.getCapability())); String filterDirective = wire.getRequirement().getDirectives().get(Constants.FILTER_DIRECTIVE); if (wire.getRequirement().getNamespace().startsWith("osgi.wiring.")) { assertTrue("An osgi.wiring.* requirement has non-empty attribute map.", wire.getRequirement().getAttributes().isEmpty()); assertNotNull("Null filter directive is not allowed for osgi.wiring.* name spaces.", filterDirective); try { Filter filter = FrameworkUtil.createFilter(filterDirective); assertTrue("Filter directive does not match capability attributes: " + filterDirective, filter.matches(wire.getCapability().getAttributes())); } catch (InvalidSyntaxException e) { fail("Failed to create filter: " + filterDirective, e); } } } public void testGetRevisions() { Bundle tb1 = install("resolver.tb1.v110.jar"); Bundle tb2 = install("resolver.tb2.jar"); Bundle tb3 = install("resolver.tb3.jar"); Bundle tb4 = install("resolver.tb4.jar"); Bundle tb5 = install("resolver.tb5.jar"); List<Bundle> testBundles = Arrays.asList(new Bundle[]{tb1, tb2, tb3, tb4, tb5}); assertTrue(frameworkWiring.resolveBundles(testBundles)); BundleRevisions tb1Revisions = tb1.adapt(BundleRevisions.class); BundleRevisions tb2Revisions = tb2.adapt(BundleRevisions.class); BundleRevisions tb3Revisions = tb3.adapt(BundleRevisions.class); BundleRevisions tb4Revisions = tb4.adapt(BundleRevisions.class); BundleRevisions tb5Revisions = tb5.adapt(BundleRevisions.class); BundleRevisions[] revisions = new BundleRevisions[] {tb1Revisions, tb2Revisions, tb3Revisions, tb4Revisions, tb5Revisions}; checkWirings((Bundle[]) testBundles.toArray(new Bundle[testBundles.size()]), revisions, 1, true); // test the refresh case refreshBundles(Arrays.asList(new Bundle[]{tb1})); assertTrue(frameworkWiring.resolveBundles(testBundles)); // do not reget the BundleRevisions must survive refresh operations checkWirings((Bundle[]) testBundles.toArray(new Bundle[testBundles.size()]), revisions, 1, true); // test the update case Bundle tb8 = install("resolver.tb8.jar"); BundleRevision tb1Revision1 = (BundleRevision) tb1.adapt(BundleRevision.class); URL content = getContext().getBundle().getEntry("resolver.tb1.v120.jar"); assertNotNull("Cannot find content for update", content); try { tb1.update(content.openStream()); } catch (BundleException e) { fail("Unexpected update failure",e); } catch (IOException e) { fail("Unexpected update failure",e); } BundleRevision tb1Revision2 = (BundleRevision) tb1.adapt(BundleRevision.class); assertTrue("Could not resolve updated bundle", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb1, tb8}))); checkWirings(new Bundle[] {tb1}, new BundleRevisions[] {tb1Revisions}, 2, true); checkRevisions(tb1Revisions, new BundleRevision[] {tb1Revision2, tb1Revision1}); Bundle tb9 = install("resolver.tb9.jar"); content = getContext().getBundle().getEntry("resolver.tb1.v130.jar"); assertNotNull("Cannot find content for update", content); try { tb1.update(content.openStream()); } catch (BundleException e) { fail("Unexpected update failure",e); } catch (IOException e) { fail("Unexpected update failure",e); } BundleRevision tb1Revision3 = (BundleRevision) tb1.adapt(BundleRevision.class); assertTrue("Could not resolve updated bundle", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb1, tb9}))); checkWirings(new Bundle[] {tb1}, new BundleRevisions[] {tb1Revisions}, 3, true); checkRevisions(tb1Revisions, new BundleRevision[] {tb1Revision3, tb1Revision2, tb1Revision1}); // test the refresh case refreshBundles(Arrays.asList(new Bundle[]{tb1})); assertTrue("Could not resolve test bundles", frameworkWiring.resolveBundles(testBundles)); // do not reget the BundleRevisions must survive refresh operations checkWirings((Bundle[]) testBundles.toArray(new Bundle[testBundles.size()]), revisions, 1, true); // test uninstall case try { tb1.uninstall(); } catch (BundleException e) { fail("Unexpected error on uninstall", e); } // regetting tb1 revisions to test that we can still get it after uninstall // this revision will only have 1 revision and it is not current tb1Revisions = tb1.adapt(BundleRevisions.class); checkWirings(new Bundle[] {tb1}, new BundleRevisions[] {tb1Revisions}, 1, false); // all other wirings are current and will only have one wiring each BundleRevisions[] otherRevisions = new BundleRevisions[] {tb2Revisions, tb3Revisions, tb4Revisions, tb5Revisions}; Bundle[] otherBundes = new Bundle[] {tb2, tb3, tb4, tb5}; checkWirings(otherBundes, otherRevisions, 1, true); } private void checkRevisions(BundleRevisions revisions, BundleRevision[] bundleRevisions) { List<BundleRevision> revisionList = revisions.getRevisions(); assertEquals("Wrong number of revisions", bundleRevisions.length, revisionList.size()); int i = 0; for (Iterator<BundleRevision> iRevisions = revisionList.iterator(); iRevisions.hasNext(); i++) assertEquals("Wrong revision found", bundleRevisions[i], iRevisions.next()); } private void checkWirings(Bundle[] bundles, BundleRevisions[] bundlesRevisions, int expectedNumRevisions, boolean hasCurrent) { assertEquals("Lists are not the same size", bundles.length, bundlesRevisions.length); for (int i = 0; i < bundlesRevisions.length; i++) { Bundle bundle = bundles[i]; BundleRevision current = (BundleRevision) bundle.adapt(BundleRevision.class); if (hasCurrent) { assertNotNull("BundleRevision is null for: " + bundle, current); assertEquals("Wrong BSN", bundle.getSymbolicName(), current.getSymbolicName()); assertEquals("Wrong version", bundle.getVersion(), current.getVersion()); } else { assertNull("BundleRevision must be null for: " + bundle, current); } BundleRevisions bundleRevisions = (BundleRevisions) bundlesRevisions[i]; assertNotNull("BundleRevisions is null for bundle: " + bundle, bundleRevisions); assertEquals("Wrong bundle for revisions", bundle, bundleRevisions.getBundle()); List<BundleRevision> revisions = bundleRevisions.getRevisions(); if (hasCurrent) assertEquals("Wrong current revision for bundle", current, revisions.get(0)); assertEquals("Wrong number of in use revisions", expectedNumRevisions, revisions.size()); int index = 0; for (Iterator<BundleRevision> iter = revisions.iterator(); iter.hasNext(); index++) { BundleRevision revision = (BundleRevision) iter.next(); BundleWiring wiring = revision.getWiring(); assertNotNull("bundle wiring is null", wiring); Collection<BundleWire> hostWires = wiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); Collection<BundleWire> fragmentWires = wiring.getRequiredWires(BundleRevision.HOST_NAMESPACE); assertNotNull("Host wires is null", hostWires); assertNotNull("Fragment wires is null", fragmentWires); if ((revision.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) { assertEquals("Wrong number of host wires", 0, hostWires.size()); assertEquals("Wrong number of fragment wires", 1, fragmentWires.size()); BundleWire fragmentWire = fragmentWires.iterator().next(); assertTrue("Fragment wire not found", fragmentWire.getProviderWiring().getProvidedWires(BundleRevision.HOST_NAMESPACE).contains(fragmentWire)); continue; } assertEquals("Wrong number of fragment wires", 0, fragmentWires.size()); if (index == 0 && hasCurrent) assertTrue("Wiring is not current for: " + bundle, wiring.isCurrent()); else assertFalse("Wiring is current for: " + bundle, wiring.isCurrent()); assertTrue("Wiring is not in use for: " + bundle, wiring.isInUse()); } } } // Note that this test assumes the tests are run on a JavaSE 1.5 vm or higher public void testOSGiEE() { // First bundle tests that the framework sets reasonable defaults for JavaSE 1.5 Bundle tb10v100 = install("resolver.tb10.v100.jar"); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb10v100}))); // Second bundle requires an osgi.ee that should not be able to resolve Bundle tb10v110 = install("resolver.tb10.v110.jar"); assertFalse(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb10v110}))); // Third bundle requires an osgi.ee that is specified by the system.capabilities.extra property Bundle tb10v120 = install("resolver.tb10.v120.jar"); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb10v120}))); // forth bundle requires JavaSE [1.3, 1.4) Bundle tb10v130 = install("resolver.tb10.v130.jar"); assertFalse(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb10v130}))); // fifth bundle requires JavaSE [1.3, 2.0) Bundle tb10v140 = install("resolver.tb10.v140.jar"); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb10v140}))); // Test that the ees come from the system bundle BundleWiring tb10v100Wiring = (BundleWiring) tb10v100.adapt(BundleWiring.class); assertNotNull("Wiring is null for: " + tb10v100, tb10v100Wiring); List<BundleWire> v100RequiredEEs = tb10v100Wiring.getRequiredWires("osgi.ee"); assertEquals("Wrong number of required osgi.ees", 7, v100RequiredEEs.size()); Bundle systemBundle = getContext().getBundle(0); assertNotNull("SystemBundle is null", systemBundle); for (Iterator<BundleWire> ees = v100RequiredEEs.iterator(); ees.hasNext();) { assertEquals("Wrong provider for osgi.ee", systemBundle, ees.next().getProviderWiring().getBundle()); } BundleWiring tb10v120Wiring = (BundleWiring) tb10v120.adapt(BundleWiring.class); assertNotNull("Wiring is null for: " + tb10v120, tb10v120Wiring); List<BundleWire> v120RequiredEEs = tb10v120Wiring.getRequiredWires("osgi.ee"); assertEquals("Wrong number of required osgi.ees", 1, v120RequiredEEs.size()); assertNotNull("SystemBundle is null", systemBundle); for (Iterator<BundleWire> ees = v120RequiredEEs.iterator(); ees.hasNext();) { assertEquals("Wrong provider for osgi.ee", systemBundle, ees.next().getProviderWiring().getBundle()); } } public void testOptionalRequireCapability() { Bundle tb11 = install("resolver.tb11.jar"); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb11}))); BundleWiring tb11Wiring = (BundleWiring) tb11.adapt(BundleWiring.class); assertNotNull("Wiring is null", tb11Wiring); List<BundleRequirement> requirements = tb11Wiring.getRequirements(null); assertNotNull("Requirements is null", requirements); assertEquals("Wrong number of requirements", 0, requirements.size()); List<BundleWire> wires = tb11Wiring.getRequiredWires(null); assertNotNull("Wires is null", wires); assertEquals("Wrong number of wires", 0, wires.size()); Bundle tb12 = install("resolver.tb12.jar"); refreshBundles(Arrays.asList(new Bundle[] {tb11})); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb11, tb12}))); tb11Wiring = (BundleWiring) tb11.adapt(BundleWiring.class); assertNotNull("Wiring is null", tb11Wiring); requirements = tb11Wiring.getRequirements(null); assertNotNull("Requirements is null", requirements); assertEquals("Wrong number of requirements", 1, requirements.size()); wires = tb11Wiring.getRequiredWires(null); assertNotNull("Wires is null", wires); assertEquals("Wrong number of wires", 1, wires.size()); BundleWire wire = wires.get(0); assertEquals("Wrong provider", tb12, wire.getProviderWiring().getBundle()); assertEquals("Wrong requirer", tb11, wire.getRequirerWiring().getBundle()); } // Note that this test is done in GetEntryResourceTest // public void testFindEntries() { // fail("Need to write a findEntries test."); // } public void testListResources() { install("wiring.base.jar"); // force base to resolve first assertTrue("Could not resolve test bundles", frameworkWiring.resolveBundles(bundles)); Bundle exporter = install("wiring.exporter.jar"); Bundle importer = install("wiring.importer.jar"); Bundle requirer = install("wiring.requirer.jar"); install("wiring.reexport.jar"); assertTrue("Could not resolve test bundles", frameworkWiring.resolveBundles(bundles)); BundleWiring exporterWiring = (BundleWiring) exporter.adapt(BundleWiring.class); BundleWiring importerWiring = (BundleWiring) importer.adapt(BundleWiring.class); BundleWiring requirerWiring = (BundleWiring) requirer.adapt(BundleWiring.class); // test that empty lists are returned when no resources are found Collection empty = exporterWiring.listResources("", "*.notfound", BundleWiring.LISTRESOURCES_RECURSE); assertNotNull("Should return empty list", empty); assertEquals("Should have 0 resources", 0, empty.size()); empty = importerWiring.listResources("", "*.notfound", BundleWiring.LISTRESOURCES_RECURSE); assertNotNull("Should return empty list", empty); assertEquals("Should have 0 resources", 0, empty.size()); empty = requirerWiring.listResources("", "*.notfound", BundleWiring.LISTRESOURCES_RECURSE); assertNotNull("Should return empty list", empty); assertEquals("Should have 0 resources", 0, empty.size()); // test exporter resources Collection rootResources = exporterWiring.listResources("/root", "*.txt", 0); assertEquals("Wrong number of resources", 1, rootResources.size()); assertEquals("Wrong resource", "root/root.export.txt", rootResources .iterator().next()); checkResources(exporterWiring.getClassLoader(), rootResources); // note that root.B package has been substituted List expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/b/b.export.txt", "root/A/A.export.txt", "root/A/A.reexport.txt", "root/B/a/a.export.txt", "root/B/b/b.export.txt", "root/B/B.base.txt", // this has been substituted "root/C/C.reexport.txt", "root/root.export.txt"}); rootResources = exporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(exporterWiring.getClassLoader(), rootResources); // test local resources of exporter; note that root.B resources are not available expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/b/b.export.txt", "root/A/A.export.txt", "root/B/a/a.export.txt", "root/B/b/b.export.txt", "root/root.export.txt"}); rootResources = exporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(exporterWiring.getClassLoader(), rootResources); // test importer resources rootResources = importerWiring.listResources("/root", "*.txt", 0); assertEquals("Wrong number of resources", 1, rootResources.size()); assertEquals("Wrong resource", "root/root.local.txt", rootResources .iterator().next()); checkResources(importerWiring.getClassLoader(), rootResources); // note that root.B package has been substituted rootResources = importerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/b/b.local.txt", "root/A/A.local.txt", "root/B/a/a.export.txt", "root/B/b/b.export.txt", "root/B/B.base.txt", // this has been substituted "root/root.local.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(importerWiring.getClassLoader(), rootResources); // test local resources, anything shadowed by an import must not be included rootResources = importerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/b/b.local.txt", "root/A/A.local.txt", "root/root.local.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(importerWiring.getClassLoader(), rootResources); // test the require bundle case rootResources = requirerWiring.listResources("/root", "*.txt", 0); expected = Arrays.asList(new String[] { "root/root.export.txt", "root/root.local.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // test require case; no shadowing of local resources; still have root.B substituted rootResources = requirerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/a/a.local.txt", "root/A/b/b.export.txt", "root/A/b/b.local.txt", "root/A/A.export.txt", "root/A/A.reexport.txt", "root/A/A.local.txt", "root/B/a/a.export.txt", "root/B/a/a.local.txt", "root/B/b/b.export.txt", "root/B/b/b.local.txt", "root/B/B.base.txt", // this has been substituted "root/B/B.local.txt", "root/C/C.reexport.txt", "root/root.export.txt", "root/root.local.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // test require local resources; not there is no shadowing so we get all local resources rootResources = requirerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/b/b.local.txt", "root/A/A.local.txt", "root/B/a/a.local.txt", "root/B/b/b.local.txt", "root/B/B.local.txt", "root/root.local.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // install fragments to test install("wiring.exporter.frag.jar"); install("wiring.importer.frag.jar"); install("wiring.requirer.frag.jar"); refreshBundles(bundles); assertTrue("failed to resolve test fragments", frameworkWiring.resolveBundles(bundles)); // test that old wirings return null rootResources = exporterWiring.listResources("/root", "*.txt", 0); assertNull("Old wiring still accesses resources", rootResources); rootResources = importerWiring.listResources("/root", "*.txt", 0); assertNull("Old wiring still accesses resources", rootResources); rootResources = requirerWiring.listResources("/root", "*.txt", 0); assertNull("Old wiring still accesses resources", rootResources); // get the latest wiring exporterWiring = (BundleWiring) exporter.adapt(BundleWiring.class); importerWiring = (BundleWiring) importer.adapt(BundleWiring.class); requirerWiring = (BundleWiring) requirer.adapt(BundleWiring.class); // test exporter resources expected = Arrays.asList(new String[] { "root/root.export.txt", "root/root.frag.txt"}); rootResources = exporterWiring.listResources("/root", "*.txt", 0); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(exporterWiring.getClassLoader(), rootResources); // note that root.B package has been substituted expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/a/a.frag.txt", "root/A/b/b.export.txt", "root/A/b/b.frag.txt", "root/A/A.export.txt", "root/A/A.frag.txt", "root/A/A.reexport.txt", "root/B/a/a.export.txt", "root/B/a/a.frag.txt", "root/B/b/b.export.txt", "root/B/b/b.frag.txt", "root/B/B.base.txt", // this has been substituted "root/C/C.reexport.txt", "root/root.export.txt", "root/root.frag.txt"}); rootResources = exporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(exporterWiring.getClassLoader(), rootResources); // test local resources of exporter; note that root.B resources are not available expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/a/a.frag.txt", "root/A/b/b.export.txt", "root/A/b/b.frag.txt", "root/A/A.export.txt", "root/A/A.frag.txt", "root/B/a/a.export.txt", "root/B/a/a.frag.txt", "root/B/b/b.export.txt", "root/B/b/b.frag.txt", "root/root.export.txt", "root/root.frag.txt"}); rootResources = exporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(exporterWiring.getClassLoader(), rootResources); // test importer resources expected = Arrays.asList(new String[] { "root/root.local.txt", "root/root.frag.txt"}); rootResources = importerWiring.listResources("/root", "*.txt", 0); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(importerWiring.getClassLoader(), rootResources); // note that root.B package has been substituted rootResources = importerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/a/a.frag.txt", "root/A/b/b.local.txt", "root/A/b/b.frag.txt", "root/A/A.local.txt", "root/A/A.frag.txt", "root/B/a/a.export.txt", "root/B/a/a.frag.txt", "root/B/b/b.export.txt", "root/B/b/b.frag.txt", "root/B/B.base.txt", // this has been substituted "root/root.local.txt", "root/root.frag.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(importerWiring.getClassLoader(), rootResources); // test local resources, anything shadowed by an import must not be included rootResources = importerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/a/a.frag.txt", "root/A/b/b.local.txt", "root/A/b/b.frag.txt", "root/A/A.local.txt", "root/A/A.frag.txt", "root/root.local.txt", "root/root.frag.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(importerWiring.getClassLoader(), rootResources); // test the require bundle case rootResources = requirerWiring.listResources("/root", "*.txt", 0); expected = Arrays.asList(new String[] { "root/root.export.txt", "root/root.local.txt", "root/root.frag.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // test require case; no shadowing of local resources; still have root.B substituted rootResources = requirerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/a/a.local.txt", "root/A/a/a.frag.txt", "root/A/b/b.export.txt", "root/A/b/b.local.txt", "root/A/b/b.frag.txt", "root/A/A.export.txt", "root/A/A.reexport.txt", "root/A/A.local.txt", "root/A/A.frag.txt", "root/B/a/a.export.txt", "root/B/a/a.local.txt", "root/B/a/a.frag.txt", "root/B/b/b.export.txt", "root/B/b/b.local.txt", "root/B/b/b.frag.txt", "root/B/B.base.txt", // this has been substituted "root/B/B.local.txt", "root/B/B.frag.txt", "root/C/C.reexport.txt", "root/root.export.txt", "root/root.local.txt", "root/root.frag.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // test require local resources; not there is no shadowing so we get all local resources rootResources = requirerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/a/a.frag.txt", "root/A/b/b.local.txt", "root/A/b/b.frag.txt", "root/A/A.local.txt", "root/A/A.frag.txt", "root/B/a/a.local.txt", "root/B/a/a.frag.txt", "root/B/b/b.local.txt", "root/B/b/b.frag.txt", "root/B/B.local.txt", "root/B/B.frag.txt", "root/root.local.txt", "root/root.frag.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // test update case URL updateContent = getContext().getBundle().getEntry("wiring.exporter.v2.jar"); assertNotNull("Could not find update content", updateContent); try { exporter.update(updateContent.openStream()); } catch (Exception e) { fail("Failed to update bundle", e); } assertTrue("Failed to resolve bundle", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {exporter}))); BundleWiring oldExporterWiring = exporterWiring; BundleWiring newExporterWiring = (BundleWiring) exporter.adapt(BundleWiring.class); // Do a sanity check to make sure the old wiring still works // note that root.B package has been substituted // note that the fragment should still be providing content to the old wiring expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/a/a.frag.txt", "root/A/b/b.export.txt", "root/A/b/b.frag.txt", "root/A/A.export.txt", "root/A/A.frag.txt", "root/A/A.reexport.txt", "root/B/a/a.export.txt", "root/B/a/a.frag.txt", "root/B/b/b.export.txt", "root/B/b/b.frag.txt", "root/B/B.base.txt", // this has been substituted "root/C/C.reexport.txt", "root/root.export.txt", "root/root.frag.txt"}); rootResources = oldExporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(oldExporterWiring.getClassLoader(), rootResources); // check the new wiring; no fragment attached // note that root.B package has been substituted expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/b/b.export.txt", "root/A/A.export.txt", "root/A/A.reexport.txt", "root/B/a/a.export.txt", "root/B/b/b.export.txt", "root/B/B.base.txt", // this has been substituted "root/C/C.reexport.txt", "root/root.export.txt"}); rootResources = newExporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(newExporterWiring.getClassLoader(), rootResources); } public void testBSNMatchingAttributes() { Bundle tb13a = install("resolver.tb13a.jar"); Bundle tb13b = install("resolver.tb13b.jar"); Bundle tb13Client1 = install("resolver.tb13.client1.jar"); Bundle tb13Client2 = install("resolver.tb13.client2.jar"); Bundle tb13Client3 = install("resolver.tb13.client3.jar"); Bundle tb13Client4 = install("resolver.tb13.client4.jar"); Bundle tb13Frag1 = install("resolver.tb13.frag1.jar"); Bundle tb13Frag2 = install("resolver.tb13.frag2.jar"); Bundle tb13Frag3 = install("resolver.tb13.frag3.jar"); Bundle tb13Frag4 = install("resolver.tb13.frag4.jar"); assertFalse(frameworkWiring.resolveBundles(bundles)); assertEquals("Unexpected state for: " + tb13a.getSymbolicName(), Bundle.RESOLVED, tb13a.getState()); assertEquals("Unexpected state for: " + tb13b.getSymbolicName(), Bundle.RESOLVED, tb13b.getState()); assertEquals("Unexpected state for: " + tb13Client1.getSymbolicName(), Bundle.INSTALLED, tb13Client1.getState()); assertEquals("Unexpected state for: " + tb13Client2.getSymbolicName(), Bundle.RESOLVED, tb13Client2.getState()); assertEquals("Unexpected state for: " + tb13Client3.getSymbolicName(), Bundle.INSTALLED, tb13Client3.getState()); assertEquals("Unexpected state for: " + tb13Client4.getSymbolicName(), Bundle.RESOLVED, tb13Client4.getState()); assertEquals("Unexpected state for: " + tb13Frag1.getSymbolicName(), Bundle.INSTALLED, tb13Frag1.getState()); assertEquals("Unexpected state for: " + tb13Frag2.getSymbolicName(), Bundle.RESOLVED, tb13Frag2.getState()); assertEquals("Unexpected state for: " + tb13Frag3.getSymbolicName(), Bundle.INSTALLED, tb13Frag3.getState()); assertEquals("Unexpected state for: " + tb13Frag4.getSymbolicName(), Bundle.RESOLVED, tb13Frag4.getState()); BundleWiring tb13Client1Wiring = (BundleWiring) tb13Client1.adapt(BundleWiring.class); assertNull("Expected null Wiring: " + tb13Client1.getSymbolicName(), tb13Client1Wiring); BundleWiring tb13Client3Wiring = (BundleWiring) tb13Client3.adapt(BundleWiring.class); assertNull("Expected null Wiring: " + tb13Client3.getSymbolicName(), tb13Client3Wiring); BundleWiring tb13aWiring = (BundleWiring) tb13a.adapt(BundleWiring.class); assertNotNull("Expected non-null wiring: " + tb13a.getSymbolicName(), tb13aWiring); BundleWiring tb13bWiring = (BundleWiring) tb13b.adapt(BundleWiring.class); assertNotNull("Expected non-null wiring: " + tb13b.getSymbolicName(), tb13bWiring); BundleWiring tb13Client2Wiring = (BundleWiring) tb13Client2.adapt(BundleWiring.class); assertNotNull("Expected non-null wiring: " + tb13Client2.getSymbolicName(), tb13Client2Wiring); BundleWiring tb13Client4Wiring = (BundleWiring) tb13Client4.adapt(BundleWiring.class); assertNotNull("Expected non-null wiring: " + tb13Client4.getSymbolicName(), tb13Client4Wiring); List<BundleRequirement> client2Requirements = tb13Client2Wiring.getRequirements(BundleRevision.BUNDLE_NAMESPACE); assertEquals("Unexpected number of requirements", 1, client2Requirements.size()); assertEquals("Wrong provider", tb13Client2, client2Requirements.get(0).getRevision().getBundle()); List<BundleWire> client2RequiredWires = tb13Client2Wiring.getRequiredWires(BundleRevision.BUNDLE_NAMESPACE); assertEquals("Unexpected number of wires", 1, client2RequiredWires.size()); assertEquals("Wrong provider", tb13a, client2RequiredWires.get(0).getProviderWiring().getBundle()); List<BundleWire> client4RequiredWires = tb13Client4Wiring.getRequiredWires(BundleRevision.BUNDLE_NAMESPACE); assertEquals("Unexpected number of wires", 1, client4RequiredWires.size()); assertEquals("Wrong provider", tb13b, client4RequiredWires.get(0).getProviderWiring().getBundle()); List<BundleWire> tb13aProvidedWires = tb13aWiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); assertEquals("Unexpected number of wires", 1, tb13aProvidedWires.size()); assertEquals("Wrong fragment attached", tb13Frag2, tb13aProvidedWires.get(0).getRequirerWiring().getBundle()); BundleWiring tb13Frag2Wiring = tb13Frag2.adapt(BundleWiring.class); assertNotNull("Fragments must be adaptable to BundleWiring", tb13Frag2Wiring); List<BundleWire> tb13Frag2RequiredWires = tb13Frag2Wiring.getRequiredWires(BundleRevision.HOST_NAMESPACE); assertEquals("Unexpected number of wires", 1, tb13Frag2RequiredWires.size()); assertEquals("Wrong host attached", tb13a, tb13Frag2RequiredWires.get(0).getProviderWiring().getBundle()); List<BundleWire> tb13bProvidedWires = tb13bWiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); assertEquals("Unexpected number of wires", 1, tb13bProvidedWires.size()); assertEquals("Wrong fragment attached", tb13Frag4, tb13bProvidedWires.get(0).getRequirerWiring().getBundle()); BundleWiring tb13Frag4Wiring = tb13Frag4.adapt(BundleWiring.class); assertNotNull("Fragments must be adaptable to BundleWiring", tb13Frag2Wiring); List<BundleWire> tb13Frag4RequiredWires = tb13Frag4Wiring.getRequiredWires(BundleRevision.HOST_NAMESPACE); assertEquals("Unexpected number of wires", 1, tb13Frag4RequiredWires.size()); assertEquals("Wrong host attached", tb13b, tb13Frag4RequiredWires.get(0).getProviderWiring().getBundle()); } private void assertResourcesEquals(String message, Collection expected, Collection actual) { if (expected.size() != actual.size()) fail(message + ": Collections are not the same size: " + expected + ": " + actual); assertTrue(message + ": Colections do not contain the same content: " + expected + ": " + actual, actual.containsAll(expected)); } private void checkResources(ClassLoader cl, Collection resources) { for(Iterator iResources = resources.iterator(); iResources.hasNext();) { String path = (String) iResources.next(); URL resource = cl.getResource(path); assertNotNull("Could not find resource: " + path, resource); } } /** * Ensures an implementation delivers a bundle wiring's provided wires in * the proper order. The ordering rules are as follows. * * (1) For a given name space, the list contains the wires in the order the * capabilities were specified in the manifests of the bundle revision and * the attached fragments of this bundle wiring. * * (2) There is no ordering defined between wires in different namespaces. * * (3) There is no ordering defined between multiple wires for the same * capability, but the wires must be contiguous, and the group must be * ordered as in (1). */ public void testProvidedWiresOrdering() { Bundle tb1 = install("wiring.tb1.jar"); Bundle tb2 = install("wiring.tb2.jar"); Bundle tb3 = install("wiring.tb3.jar"); Bundle tb4 = install("wiring.tb4.jar"); assertTrue("Bundles should have resolved", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb1,tb2,tb3,tb4}))); BundleWiring tb1Wiring = tb1.adapt(BundleWiring.class); BundleWiring tb2Wiring = tb2.adapt(BundleWiring.class); BundleWiring tb3Wiring = tb3.adapt(BundleWiring.class); BundleWiring tb4Wiring = tb4.adapt(BundleWiring.class); List<BundleWire> tb1Wires = tb1Wiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE); assertEquals("Wrong number of wires", 6, tb1Wires.size()); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1a", tb1Wires.get(0).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(0).getRequirerWiring().equals(tb2Wiring) || tb1Wires.get(0).getRequirerWiring().equals(tb3Wiring)); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1a", tb1Wires.get(1).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(1).getRequirerWiring().equals(tb2Wiring) || tb1Wires.get(1).getRequirerWiring().equals(tb3Wiring)); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1b", tb1Wires.get(2).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(2).getRequirerWiring().equals(tb2Wiring) || tb1Wires.get(2).getRequirerWiring().equals(tb4Wiring)); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1b", tb1Wires.get(3).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(3).getRequirerWiring().equals(tb2Wiring) || tb1Wires.get(3).getRequirerWiring().equals(tb4Wiring)); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1c", tb1Wires.get(4).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(4).getRequirerWiring().equals(tb3Wiring) || tb1Wires.get(4).getRequirerWiring().equals(tb4Wiring)); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1c", tb1Wires.get(5).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(5).getRequirerWiring().equals(tb3Wiring) || tb1Wires.get(5).getRequirerWiring().equals(tb4Wiring)); } /** * Basic test for support of the DynamicImport-Package requirement. */ public void testDynamicImportPackage() throws Exception { Bundle tb1 = install("resolver.tb1.v110.jar"); Bundle tb2 = install("wiring.tb1.jar"); Bundle tb3 = install("wiring.tb5.jar"); assertTrue("The bundles should have resolved", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb1,tb2,tb3}))); BundleRevision tb3Revision = (BundleRevision)tb3.adapt(BundleRevision.class); BundleWiring tb1Wiring = (BundleWiring)tb1.adapt(BundleWiring.class); BundleWiring tb2Wiring = (BundleWiring)tb2.adapt(BundleWiring.class); BundleWiring tb3Wiring = (BundleWiring)tb3.adapt(BundleWiring.class); checkRequirements( tb3Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE), tb3Revision.getDeclaredRequirements(null), BundleRevision.PACKAGE_NAMESPACE, 1, tb3Revision); checkRequirements( tb3Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequirements(null), BundleRevision.PACKAGE_NAMESPACE, 1, tb3Wiring.getRevision()); checkWires( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequiredWires(null), BundleRevision.PACKAGE_NAMESPACE, 0); tb3.loadClass("org.osgi.test.cases.framework.resolver.tb1.Test"); checkWires( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequiredWires(null), BundleRevision.PACKAGE_NAMESPACE, 1); checkBundleWire( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE).get(0), tb1Wiring, tb3Wiring, tb1Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE).get(0), tb3Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE).get(0)); tb3.loadClass("org.osgi.test.cases.framework.wiring.tb1a.PlaceHolder"); checkWires( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequiredWires(null), BundleRevision.PACKAGE_NAMESPACE, 2); BundleCapability bc = tb2Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE).get(0); assertEquals("Wrong attribute", "org.osgi.test.cases.framework.wiring.tb1a", bc.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); checkBundleWire( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE).get(1), tb2Wiring, tb3Wiring, bc, tb3Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE).get(0)); tb3.loadClass("org.osgi.test.cases.framework.wiring.tb1b.PlaceHolder"); checkWires( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequiredWires(null), BundleRevision.PACKAGE_NAMESPACE, 3); bc = tb2Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE).get(1); assertEquals("Wrong attribute", "org.osgi.test.cases.framework.wiring.tb1b", bc.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); checkBundleWire( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE).get(2), tb2Wiring, tb3Wiring, bc, tb3Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE).get(0)); } }
org.osgi.test.cases.framework/src/org/osgi/test/cases/framework/junit/wiring/BundleWiringTests.java
/* * Copyright (c) IBM Corporation (2010, 2011). All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.osgi.test.cases.framework.junit.wiring; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.osgi.framework.Constants; import org.osgi.framework.FrameworkEvent; import org.osgi.framework.FrameworkListener; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleRevisions; import org.osgi.framework.wiring.BundleWire; import org.osgi.framework.wiring.BundleWiring; import org.osgi.framework.wiring.FrameworkWiring; import org.osgi.test.support.OSGiTestCase; public class BundleWiringTests extends OSGiTestCase { private final List<Bundle> bundles = new ArrayList<Bundle>(); FrameworkWiring frameworkWiring; public Bundle install(String bundle) { Bundle result = null; try { result = super.install(bundle); } catch (BundleException e) { fail("failed to install bundle: " + bundle, e); } catch (IOException e) { fail("failed to install bundle: " + bundle, e); } if (!bundles.contains(result)) bundles.add(result); return result; } protected void setUp() throws Exception { bundles.clear(); frameworkWiring = (FrameworkWiring) getContext().getBundle(0).adapt(FrameworkWiring.class); } protected void tearDown() throws Exception { for (Iterator<Bundle> iBundles = bundles.iterator(); iBundles.hasNext();) try { iBundles.next().uninstall(); } catch (BundleException e) { // nothing } catch (IllegalStateException e) { // happens if the test uninstalls the bundle itself } refreshBundles(bundles); bundles.clear(); } private void refreshBundles(List<Bundle> bundles) { final boolean[] done = new boolean[] {false}; FrameworkListener listener = new FrameworkListener() { public void frameworkEvent(FrameworkEvent event) { synchronized (done) { if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) { done[0] = true; done.notify(); } } } }; frameworkWiring.refreshBundles(bundles, new FrameworkListener[] {listener}); synchronized (done) { if (!done[0]) try { done.wait(5000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); fail("Unexepected interruption.", e); } if (!done[0]) fail("Timed out waiting for refresh bundles to finish."); } } public void testGetRevision() { Bundle tb1 = install("resolver.tb1.v110.jar"); Bundle tb2 = install("resolver.tb2.jar"); Bundle tb3 = install("resolver.tb3.jar"); Bundle tb4 = install("resolver.tb4.jar"); Bundle tb5 = install("resolver.tb5.jar"); Bundle tb14 = install("resolver.tb14.jar"); List<Bundle> testBundles = Arrays.asList(tb1, tb2, tb3, tb4, tb5, tb14); assertTrue(frameworkWiring.resolveBundles(testBundles)); List<BundleRevision> testRevisions = getRevisions(testBundles); BundleRevision tb1Revision = testRevisions.get(0); BundleRevision tb2Revision = testRevisions.get(1); BundleRevision tb3Revision = testRevisions.get(2); BundleRevision tb4Revision = testRevisions.get(3); BundleRevision tb5Revision = testRevisions.get(4); BundleRevision tb14Revision = testRevisions.get(5); List<BundleCapability> tb1AllCapabilities = tb1Revision.getDeclaredCapabilities(null); List<BundleCapability> tb1BundleCapabilities = tb1Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb1HostCapabilities = tb1Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb1PackageCapabilities = tb1Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); List<BundleCapability> tb1TestCapabilities = tb1Revision.getDeclaredCapabilities("test"); List<BundleCapability> tb1TestMultipleCapabilities = tb1Revision.getDeclaredCapabilities("test.multiple"); List<BundleCapability> tb1TestFragmentCapabilities = tb1Revision.getDeclaredCapabilities("test.fragment"); checkCapabilities(tb1BundleCapabilities, tb1AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 1, tb1Revision); checkCapabilities(tb1HostCapabilities, tb1AllCapabilities, BundleRevision.HOST_NAMESPACE, 1, tb1Revision); checkCapabilities(tb1PackageCapabilities, tb1AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 1, tb1Revision); checkCapabilities(tb1TestCapabilities, tb1AllCapabilities, "test", 1, tb1Revision); checkCapabilities(tb1TestMultipleCapabilities, tb1AllCapabilities, "test.multiple", 2, tb1Revision); checkCapabilities(tb1TestFragmentCapabilities, tb1AllCapabilities, "test.fragment", 0, tb1Revision); List<BundleRequirement> tb1AllRequirements = tb1Revision.getDeclaredRequirements(null); List<BundleRequirement> tb1BundleRequirements = tb1Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb1HostRequirements = tb1Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb1PackageRequirements = tb1Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); checkRequirements(tb1BundleRequirements, tb1AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 0, tb1Revision); checkRequirements(tb1HostRequirements, tb1AllRequirements, BundleRevision.HOST_NAMESPACE, 0, tb1Revision); checkRequirements(tb1PackageRequirements, tb1AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 0, tb1Revision); List<BundleCapability> tb2AllCapabilities = tb2Revision.getDeclaredCapabilities(null); List<BundleCapability> tb2BundleCapabilities = tb2Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb2HostCapabilities = tb2Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb2PackageCapabilities = tb2Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); checkCapabilities(tb2BundleCapabilities, tb2AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 1, tb2Revision); checkCapabilities(tb2HostCapabilities, tb2AllCapabilities, BundleRevision.HOST_NAMESPACE, 0, tb2Revision); checkCapabilities(tb2PackageCapabilities, tb2AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 0, tb2Revision); List<BundleRequirement> tb2AllRequirements = tb2Revision.getDeclaredRequirements(null); List<BundleRequirement> tb2BundleRequirements = tb2Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb2HostRequirements = tb2Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb2PackageRequirements = tb2Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); checkRequirements(tb2BundleRequirements, tb2AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 0, tb2Revision); checkRequirements(tb2HostRequirements, tb2AllRequirements, BundleRevision.HOST_NAMESPACE, 0, tb2Revision); checkRequirements(tb2PackageRequirements, tb2AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 2, tb2Revision); List<BundleCapability> tb3AllCapabilities = tb3Revision.getDeclaredCapabilities(null); List<BundleCapability> tb3BundleCapabilities = tb3Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb3HostCapabilities = tb3Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb3PackageCapabilities = tb3Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); checkCapabilities(tb3BundleCapabilities, tb3AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 1, tb3Revision); checkCapabilities(tb3HostCapabilities, tb3AllCapabilities, BundleRevision.HOST_NAMESPACE, 1, tb3Revision); checkCapabilities(tb3PackageCapabilities, tb3AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 0, tb3Revision); List<BundleRequirement> tb3AllRequirements = tb3Revision.getDeclaredRequirements(null); List<BundleRequirement> tb3BundleRequirements = tb3Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb3HostRequirements = tb3Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb3PackageRequirements = tb3Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); checkRequirements(tb3BundleRequirements, tb3AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 1, tb3Revision); checkRequirements(tb3HostRequirements, tb3AllRequirements, BundleRevision.HOST_NAMESPACE, 0, tb3Revision); checkRequirements(tb3PackageRequirements, tb3AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 1, tb3Revision); List<BundleCapability> tb4AllCapabilities = tb4Revision.getDeclaredCapabilities(null); List<BundleCapability> tb4BundleCapabilities = tb4Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb4HostCapabilities = tb4Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb4PackageCapabilities = tb4Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); List<BundleCapability> tb4TestFragmentCapabilities = tb4Revision.getDeclaredCapabilities("test.fragment"); checkCapabilities(tb4BundleCapabilities, tb4AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 0, tb4Revision); checkCapabilities(tb4HostCapabilities, tb4AllCapabilities, BundleRevision.HOST_NAMESPACE, 0, tb4Revision); checkCapabilities(tb4PackageCapabilities, tb4AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 0, tb4Revision); checkCapabilities(tb4TestFragmentCapabilities, tb4AllCapabilities, "test.fragment", 1, tb4Revision); List<BundleRequirement> tb4AllRequirements = tb4Revision.getDeclaredRequirements(null); List<BundleRequirement> tb4BundleRequirements = tb4Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb4HostRequirements = tb4Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb4PackageRequirements = tb4Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); checkRequirements(tb4BundleRequirements, tb4AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 0, tb4Revision); checkRequirements(tb4HostRequirements, tb4AllRequirements, BundleRevision.HOST_NAMESPACE, 1, tb4Revision); checkRequirements(tb4PackageRequirements, tb4AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 0, tb4Revision); List<BundleCapability> tb5AllCapabilities = tb5Revision.getDeclaredCapabilities(null); List<BundleCapability> tb5BundleCapabilities = tb5Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb5HostCapabilities = tb5Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb5PackageCapabilities = tb5Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); checkCapabilities(tb5BundleCapabilities, tb5AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 1, tb5Revision); checkCapabilities(tb5HostCapabilities, tb5AllCapabilities, BundleRevision.HOST_NAMESPACE, 1, tb5Revision); checkCapabilities(tb5PackageCapabilities, tb5AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 0, tb5Revision); List<BundleRequirement> tb5AllRequirements = tb5Revision.getDeclaredRequirements(null); List<BundleRequirement> tb5BundleRequirements = tb5Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb5HostRequirements = tb5Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb5PackageRequirements = tb5Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); List<BundleRequirement> tb5TestRequirements = tb5Revision.getDeclaredRequirements("test"); List<BundleRequirement> tb5TestNoAttrsRequirements = tb5Revision.getDeclaredRequirements("test.no.attrs"); checkRequirements(tb5BundleRequirements, tb5AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 0, tb5Revision); checkRequirements(tb5HostRequirements, tb5AllRequirements, BundleRevision.HOST_NAMESPACE, 0, tb5Revision); checkRequirements(tb5PackageRequirements, tb5AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 0, tb5Revision); checkRequirements(tb5TestRequirements, tb5AllRequirements, "test", 10, tb5Revision); checkRequirements(tb5TestNoAttrsRequirements, tb5AllRequirements, "test.no.attrs", 1, tb5Revision); List<BundleCapability> tb14AllCapabilities = tb14Revision.getDeclaredCapabilities(null); List<BundleCapability> tb14BundleCapabilities = tb14Revision.getDeclaredCapabilities(BundleRevision.BUNDLE_NAMESPACE); List<BundleCapability> tb14HostCapabilities = tb14Revision.getDeclaredCapabilities(BundleRevision.HOST_NAMESPACE); List<BundleCapability> tb14PackageCapabilities = tb14Revision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE); checkCapabilities(tb14BundleCapabilities, tb14AllCapabilities, BundleRevision.BUNDLE_NAMESPACE, 1, tb14Revision); checkCapabilities(tb14HostCapabilities, tb14AllCapabilities, BundleRevision.HOST_NAMESPACE, 1, tb14Revision); checkCapabilities(tb14PackageCapabilities, tb14AllCapabilities, BundleRevision.PACKAGE_NAMESPACE, 0, tb14Revision); List<BundleRequirement> tb14AllRequirements = tb14Revision.getDeclaredRequirements(null); List<BundleRequirement> tb14BundleRequirements = tb14Revision.getDeclaredRequirements(BundleRevision.BUNDLE_NAMESPACE); List<BundleRequirement> tb14HostRequirements = tb14Revision.getDeclaredRequirements(BundleRevision.HOST_NAMESPACE); List<BundleRequirement> tb14PackageRequirements = tb14Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE); List<BundleRequirement> tb14TestFragmentRequirements = tb14Revision.getDeclaredRequirements("test.fragment"); checkRequirements(tb14BundleRequirements, tb14AllRequirements, BundleRevision.BUNDLE_NAMESPACE, 0, tb14Revision); checkRequirements(tb14HostRequirements, tb14AllRequirements, BundleRevision.HOST_NAMESPACE, 0, tb14Revision); checkRequirements(tb14PackageRequirements, tb14AllRequirements, BundleRevision.PACKAGE_NAMESPACE, 0, tb14Revision); checkRequirements(tb14TestFragmentRequirements, tb14AllRequirements, "test.fragment", 1, tb14Revision); } void checkCapabilities(List<BundleCapability> toCheck, List<BundleCapability> all, String namespace, int expectedNum, BundleRevision provider) { assertEquals("Wrong number of capabilities for " + namespace + " from " + provider, expectedNum, toCheck.size()); for (BundleCapability capability : toCheck) { assertTrue("Capability is not in all capabilities", all.contains(capability)); assertEquals("Wrong namespace", namespace, capability.getNamespace()); assertEquals("Wrong provider", provider, capability.getRevision()); } } void checkRequirements(List<BundleRequirement> toCheck, List<BundleRequirement> all, String namespace, int expectedNum, BundleRevision requirer) { assertEquals("Wrong number of requirements for " + namespace + " from " + requirer, expectedNum, toCheck.size()); for (BundleRequirement requirement : toCheck) { assertTrue("Capability is not in all capabilities", all.contains(requirement)); assertEquals("Wrong namespace", namespace, requirement.getNamespace()); assertEquals("Wrong requirer", requirer, requirement.getRevision()); } } void checkWires(List<BundleWire> toCheck, List<BundleWire> all, String namespace, int expectedNum) { assertEquals("Wrong number of wires for " + namespace, expectedNum, toCheck.size()); for (BundleWire wire : toCheck) { assertTrue("Capability is not in all capabilities for revision", all.contains(wire)); } } private List<BundleRevision> getRevisions(List<Bundle> testBundles) { ArrayList<BundleRevision> result = new ArrayList<BundleRevision>(testBundles.size()); for (Bundle bundle : testBundles) { BundleRevision revision = bundle.adapt(BundleRevision.class); result.add(revision); assertEquals("Wrong BSN", bundle.getSymbolicName(), revision.getSymbolicName()); assertEquals("Wrong bundle", bundle, revision.getBundle()); assertEquals("Wrong version", bundle.getVersion(), revision.getVersion()); assertEquals("Wrong type", bundle.getHeaders("").get(Constants.FRAGMENT_HOST) == null ? 0 : BundleRevision.TYPE_FRAGMENT, revision.getTypes()); Collection<BundleWire> hostWirings = revision.getWiring().getRequiredWires(BundleRevision.HOST_NAMESPACE); assertNotNull("Host wirings must never be null.", hostWirings); if ((revision.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) { // we assume the fragment resolved to one host assertEquals("Wrong number of host wirings found", 1, hostWirings.size()); } else { // regular bundles must have empty host wirings assertEquals("Must have empty wirings for regular bundles", 0, hostWirings.size()); } } return result; } public void testGetWiring() { Bundle tb1 = install("resolver.tb1.v110.jar"); Bundle tb2 = install("resolver.tb2.jar"); Bundle tb3 = install("resolver.tb3.jar"); Bundle tb4 = install("resolver.tb4.jar"); Bundle tb5 = install("resolver.tb5.jar"); Bundle tb14 = install("resolver.tb14.jar"); List<Bundle> testBundles = Arrays.asList(tb1, tb2, tb3, tb4, tb5, tb14); assertTrue(frameworkWiring.resolveBundles(testBundles)); BundleWiring tb1Wiring = tb1.adapt(BundleWiring.class); BundleWiring tb2Wiring = tb2.adapt(BundleWiring.class); BundleWiring tb3Wiring = tb3.adapt(BundleWiring.class); BundleWiring tb4Wiring = tb4.adapt(BundleWiring.class); BundleWiring tb5Wiring = tb5.adapt(BundleWiring.class); BundleWiring tb14Wiring = tb14.adapt(BundleWiring.class); BundleWiring[] wirings = new BundleWiring[] {tb1Wiring, tb2Wiring, tb3Wiring, tb4Wiring, tb5Wiring, tb14Wiring}; checkBundleWiring(testBundles.toArray(new Bundle[6]), wirings); List<BundleWire> allTb1Capabilities = tb1Wiring.getProvidedWires(null); List<BundleWire> osgiBundleTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.BUNDLE_NAMESPACE); List<BundleWire> osgiHostTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); List<BundleWire> osgiPackageTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE); List<BundleWire> genTestTb1Capabilities = tb1Wiring.getProvidedWires("test"); List<BundleWire> genTestMultipleTb1Capabilities = tb1Wiring.getProvidedWires("test.multiple"); List<BundleWire> genTestNoAttrsTb1Capabilities = tb1Wiring.getProvidedWires("test.no.attrs"); List<BundleWire> genTestFragmentTb1Capabilities = tb1Wiring.getProvidedWires("test.fragment"); // check for osgi.wiring.host capability from wiring with // fragment-attachment:="never" List<BundleCapability> osgiHostTb2Capabilities = tb2Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE); assertEquals("Expecting no osgi.wiring.host capability", 0, osgiHostTb2Capabilities.size()); checkBundleWires(tb1Wiring, tb2Wiring, tb3Wiring, tb5Wiring, tb14Wiring, tb4, allTb1Capabilities, osgiBundleTb1Capabilities, osgiHostTb1Capabilities, osgiPackageTb1Capabilities, genTestTb1Capabilities, genTestMultipleTb1Capabilities, genTestFragmentTb1Capabilities, genTestNoAttrsTb1Capabilities); // test the refresh case refreshBundles(Arrays.asList(new Bundle[]{tb1})); assertTrue(frameworkWiring.resolveBundles(testBundles)); checkNotInUseWirings(wirings); tb1Wiring = tb1.adapt(BundleWiring.class); tb2Wiring = tb2.adapt(BundleWiring.class); tb3Wiring = tb3.adapt(BundleWiring.class); tb4Wiring = tb4.adapt(BundleWiring.class); tb5Wiring = tb5.adapt(BundleWiring.class); tb14Wiring = tb14.adapt(BundleWiring.class); wirings = new BundleWiring[] {tb1Wiring, tb2Wiring, tb3Wiring, tb4Wiring, tb5Wiring, tb14Wiring}; checkBundleWiring(testBundles.toArray(new Bundle[6]), wirings); // get wired capabilities before update osgiBundleTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.BUNDLE_NAMESPACE); osgiHostTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); osgiPackageTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE); genTestTb1Capabilities = tb1Wiring.getProvidedWires("test"); genTestMultipleTb1Capabilities = tb1Wiring.getProvidedWires("test.multiple"); genTestNoAttrsTb1Capabilities = tb1Wiring.getProvidedWires("test.no.attrs"); genTestFragmentTb1Capabilities = tb1Wiring.getProvidedWires("test.fragment"); // test the update case URL content = getContext().getBundle().getEntry("resolver.tb1.v110.jar"); assertNotNull("Cannot find content for update", content); try { tb1.update(content.openStream()); } catch (BundleException e) { fail("Unexpected update failure",e); } catch (IOException e) { fail("Unexpected update failure",e); } assertTrue("Could not resolve updated bundle", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb1}))); // check that the updated wiring has no requirers BundleWiring updatedWiring = (BundleWiring) tb1.adapt(BundleWiring.class); checkBundleWiring(new Bundle[] {tb1}, new BundleWiring[] {updatedWiring}); List<BundleWire> updatedWires = updatedWiring.getProvidedWires(null); assertNotNull("Requirers is null", updatedWires); assertEquals("Wrong number of requirers", 0, updatedWires.size()); assertTrue("Wiring is not in use for: " + tb1, tb1Wiring.isInUse()); assertFalse("Wiring is current for: " + tb1, tb1Wiring.isCurrent()); // Check that old wiring for tb1 is still correct allTb1Capabilities = tb1Wiring.getProvidedWires(null); checkBundleWires(tb1Wiring, tb2Wiring, tb3Wiring, tb5Wiring, tb14Wiring, tb4, allTb1Capabilities, osgiBundleTb1Capabilities, osgiHostTb1Capabilities, osgiPackageTb1Capabilities, genTestTb1Capabilities, genTestMultipleTb1Capabilities, genTestFragmentTb1Capabilities, genTestNoAttrsTb1Capabilities); // test the refresh case refreshBundles(Arrays.asList(new Bundle[]{tb1})); assertTrue(frameworkWiring.resolveBundles(testBundles)); checkNotInUseWirings(wirings); checkNotInUseWirings(new BundleWiring[] {updatedWiring}); tb1Wiring = tb1.adapt(BundleWiring.class); tb2Wiring = tb2.adapt(BundleWiring.class); tb3Wiring = tb3.adapt(BundleWiring.class); tb4Wiring = tb4.adapt(BundleWiring.class); tb5Wiring = tb5.adapt(BundleWiring.class); tb14Wiring = tb14.adapt(BundleWiring.class); wirings = new BundleWiring[] {tb1Wiring, tb2Wiring, tb3Wiring, tb4Wiring, tb5Wiring, tb14Wiring}; checkBundleWiring(testBundles.toArray(new Bundle[6]), wirings); // test uninstall case try { tb1.uninstall(); } catch (BundleException e) { fail("Unexpecte error on uninstall", e); } assertNull("Bundle wiring is not null for bundle: " + tb1, tb1.adapt(BundleWiring.class)); // note that we do not reget tb1Wiring because it must be null on uninstall from the check above tb2Wiring = tb2.adapt(BundleWiring.class); tb3Wiring = tb3.adapt(BundleWiring.class); tb4Wiring = tb4.adapt(BundleWiring.class); tb5Wiring = tb5.adapt(BundleWiring.class); tb14Wiring = tb14.adapt(BundleWiring.class); wirings = new BundleWiring[] {tb1Wiring, tb2Wiring, tb3Wiring, tb4Wiring, tb5Wiring, tb14Wiring}; assertTrue("Wiring is not in use for: " + tb1, tb1Wiring.isInUse()); assertFalse("Wring is current for: " + tb1, tb1Wiring.isCurrent()); allTb1Capabilities = tb1Wiring.getProvidedWires(null); osgiBundleTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.BUNDLE_NAMESPACE); osgiHostTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); osgiPackageTb1Capabilities = tb1Wiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE); genTestTb1Capabilities = tb1Wiring.getProvidedWires("test"); genTestMultipleTb1Capabilities = tb1Wiring.getProvidedWires("test.multiple"); genTestNoAttrsTb1Capabilities = tb1Wiring.getProvidedWires("test.no.attrs"); genTestFragmentTb1Capabilities = tb1Wiring.getProvidedWires("test.fragment"); checkBundleWires(tb1Wiring, tb2Wiring, tb3Wiring, tb5Wiring, tb14Wiring, tb4, allTb1Capabilities, osgiBundleTb1Capabilities, osgiHostTb1Capabilities, osgiPackageTb1Capabilities, genTestTb1Capabilities, genTestMultipleTb1Capabilities, genTestFragmentTb1Capabilities, genTestNoAttrsTb1Capabilities); // test the refresh case refreshBundles(null); assertFalse(frameworkWiring.resolveBundles(testBundles)); checkNotInUseWirings(wirings); // Wirings must be null now since the bundles are not resolved assertNull("Bundle wiring is not null for bundle: " + tb1, tb1.adapt(BundleWiring.class)); assertNull("Bundle wiring is not null for bundle: " + tb2, tb2.adapt(BundleWiring.class)); assertNull("Bundle wiring is not null for bundle: " + tb3, tb3.adapt(BundleWiring.class)); assertNull("Bundle wiring is not null for bundle: " + tb4, tb4.adapt(BundleWiring.class)); assertNull("Bundle wiring is not null for bundle: " + tb5, tb5.adapt(BundleWiring.class)); } private void checkBundleWiring(Bundle[] bundles, BundleWiring[] wirings) { assertEquals("Lists are not the same size", bundles.length, wirings.length); for (int i = 0; i < wirings.length; i++) { BundleWiring wiring = wirings[i]; Bundle bundle = bundles[i]; BundleRevision revision = bundle.adapt(BundleRevision.class); assertNotNull("BundleRevision is null for: " + bundle, revision); assertEquals("Wrong BSN", bundle.getSymbolicName(), revision.getSymbolicName()); assertEquals("Wrong version", bundle.getVersion(), revision.getVersion()); assertNotNull("BundleWiring is null for bundle: " + bundle, wiring); assertEquals("Wrong bundle for wiring: " + bundle, bundle, wiring.getBundle()); BundleRevision wiringRevision = wiring.getRevision(); assertNotNull("Wiring revision is null for bundle: " + bundle, wiringRevision); assertEquals("Wrong BSN", bundle.getSymbolicName(), wiringRevision.getSymbolicName()); assertEquals("Wrong version", bundle.getVersion(), wiringRevision.getVersion()); assertTrue("Wiring is not current for: " + bundle, wiring.isCurrent()); assertTrue("Wiring is not in use for: " + bundle, wiring.isInUse()); } } private void checkNotInUseWirings(BundleWiring[] wirings) { for (int i = 0; i < wirings.length; i++) { BundleWiring wiring = wirings[i]; if (wiring == null) continue; // fragment case assertFalse("Wiring is current for: " + wiring.getBundle(), wiring.isCurrent()); assertFalse("Wiring is in use for: " + wiring.getBundle(), wiring.isInUse()); assertNull("Wiring capabilities must be null: " + wiring.getBundle(), wiring.getCapabilities(null)); assertNull("Wiring requirements must be null: " + wiring.getBundle(), wiring.getRequirements(null)); assertNull("Wiring class loader must be null: " + wiring.getBundle(), wiring.getClassLoader()); assertNull("Wiring findEntries must be null: " + wiring.getBundle(), wiring.findEntries("/", "*", 0)); assertNull("Wiring listResources must be null: " + wiring.getBundle(), wiring.listResources("/", "*", 0)); assertNull("Wiring providedWires must be null: " + wiring.getBundle(), wiring.getProvidedWires(null)); assertNull("Wiring requiredWires must be null: " + wiring.getBundle(), wiring.getRequiredWires(null)); } } private void checkCapabilitiesTb1v110(BundleWiring tb1Wiring, Bundle tb4) { assertEquals("Wrong number of capabilities", 8, tb1Wiring.getCapabilities(null).size()); checkCapabilities( tb1Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE), tb1Wiring.getCapabilities(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb1Wiring.getRevision()); checkCapabilities( tb1Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE), tb1Wiring.getCapabilities(null), BundleRevision.HOST_NAMESPACE, 1, tb1Wiring.getRevision()); checkCapabilities( tb1Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE), tb1Wiring.getCapabilities(null), BundleRevision.PACKAGE_NAMESPACE, 1, tb1Wiring.getRevision()); checkCapabilities( tb1Wiring.getCapabilities("test"), tb1Wiring.getCapabilities(null), "test", 1, tb1Wiring.getRevision()); checkCapabilities( tb1Wiring.getCapabilities("test.multiple"), tb1Wiring.getCapabilities(null), "test.multiple", 2, tb1Wiring.getRevision()); checkCapabilities( tb1Wiring.getCapabilities("test.fragment"), tb1Wiring.getCapabilities(null), "test.fragment", 1, tb4.adapt(BundleRevision.class)); checkCapabilities( tb1Wiring.getCapabilities("test.no.attrs"), tb1Wiring.getCapabilities(null), "test.no.attrs", 1, tb1Wiring.getRevision()); } private void checkCapabilitiesTb2(BundleWiring tb2Wiring) { assertEquals("Wrong number of capabilities", 1, tb2Wiring.getCapabilities(null).size()); checkCapabilities( tb2Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE), tb2Wiring.getCapabilities(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb2Wiring.getRevision()); checkCapabilities( tb2Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE), tb2Wiring.getCapabilities(null), BundleRevision.HOST_NAMESPACE, 0, tb2Wiring.getRevision()); checkCapabilities( tb2Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE), tb2Wiring.getCapabilities(null), BundleRevision.PACKAGE_NAMESPACE, 0, tb2Wiring.getRevision()); } private void checkCapabilitiesTb3(BundleWiring tb3Wiring) { assertEquals("Wrong number of capabilities", 2, tb3Wiring.getCapabilities(null).size()); checkCapabilities( tb3Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE), tb3Wiring.getCapabilities(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb3Wiring.getRevision()); checkCapabilities( tb3Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE), tb3Wiring.getCapabilities(null), BundleRevision.HOST_NAMESPACE, 1, tb3Wiring.getRevision()); checkCapabilities( tb3Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getCapabilities(null), BundleRevision.PACKAGE_NAMESPACE, 0, tb3Wiring.getRevision()); } private void checkCapabilitiesTb4(BundleWiring tb4Wiring) { assertEquals("Wrong number of capabilities", 0, tb4Wiring.getCapabilities(null).size()); } private void checkCapabilitiesTb5(BundleWiring tb5Wiring) { assertEquals("Wrong number of capabilities", 2, tb5Wiring.getCapabilities(null).size()); checkCapabilities( tb5Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE), tb5Wiring.getCapabilities(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb5Wiring.getRevision()); checkCapabilities( tb5Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE), tb5Wiring.getCapabilities(null), BundleRevision.HOST_NAMESPACE, 1, tb5Wiring.getRevision()); checkCapabilities( tb5Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE), tb5Wiring.getCapabilities(null), BundleRevision.PACKAGE_NAMESPACE, 0, tb5Wiring.getRevision()); } private void checkCapabilitiesTb14(BundleWiring tb14Wiring) { assertEquals("Wrong number of capabilities", 2, tb14Wiring.getCapabilities(null).size()); checkCapabilities( tb14Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE), tb14Wiring.getCapabilities(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb14Wiring.getRevision()); checkCapabilities( tb14Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE), tb14Wiring.getCapabilities(null), BundleRevision.HOST_NAMESPACE, 1, tb14Wiring.getRevision()); checkCapabilities( tb14Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE), tb14Wiring.getCapabilities(null), BundleRevision.PACKAGE_NAMESPACE, 0, tb14Wiring.getRevision()); } private void checkRequirementsTb1v110(BundleWiring tb1Wiring) { assertEquals("Wrong number of requirements", 0, tb1Wiring.getRequirements(null).size()); } private void checkRequirementsTb2(BundleWiring tb2Wiring) { assertEquals("Wrong number of requirements", 2, tb2Wiring.getRequirements(null).size()); checkRequirements( tb2Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE), tb2Wiring.getRequirements(null), BundleRevision.PACKAGE_NAMESPACE, 2, tb2Wiring.getRevision()); } private void checkRequirementsTb3(BundleWiring tb3Wiring) { assertEquals("Wrong number of requirements", 2, tb3Wiring.getRequirements(null).size()); checkRequirements( tb3Wiring.getRequirements(BundleRevision.BUNDLE_NAMESPACE), tb3Wiring.getRequirements(null), BundleRevision.BUNDLE_NAMESPACE, 1, tb3Wiring.getRevision()); checkRequirements( tb3Wiring.getRequirements(BundleRevision.HOST_NAMESPACE), tb3Wiring.getRequirements(null), BundleRevision.HOST_NAMESPACE, 0, tb3Wiring.getRevision()); checkRequirements( tb3Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequirements(null), BundleRevision.PACKAGE_NAMESPACE, 1, tb3Wiring.getRevision()); } private void checkRequirementsTb4(BundleWiring tb4Wiring) { assertEquals("Wrong number of requirements", 1, tb4Wiring.getRequirements(null).size()); checkRequirements( tb4Wiring.getRequirements(BundleRevision.BUNDLE_NAMESPACE), tb4Wiring.getRequirements(null), BundleRevision.BUNDLE_NAMESPACE, 0, tb4Wiring.getRevision()); checkRequirements( tb4Wiring.getRequirements(BundleRevision.HOST_NAMESPACE), tb4Wiring.getRequirements(null), BundleRevision.HOST_NAMESPACE, 1, tb4Wiring.getRevision()); checkRequirements( tb4Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE), tb4Wiring.getRequirements(null), BundleRevision.PACKAGE_NAMESPACE, 0, tb4Wiring.getRevision()); } private void checkRequirementsTb5(BundleWiring tb5Wiring) { assertEquals("Wrong number of requirements", 11, tb5Wiring.getRequirements(null).size()); checkRequirements( tb5Wiring.getRequirements("test"), tb5Wiring.getRequirements(null), "test", 10, tb5Wiring.getRevision()); checkRequirements( tb5Wiring.getRequirements("test.no.attrs"), tb5Wiring.getRequirements(null), "test.no.attrs", 1, tb5Wiring.getRevision()); } private void checkRequirementsTb14(BundleWiring tb14Wiring) { assertEquals("Wrong number of requirements", 1, tb14Wiring.getRequirements(null).size()); checkRequirements( tb14Wiring.getRequirements("test.fragment"), tb14Wiring.getRequirements(null), "test.fragment", 1, tb14Wiring.getRevision()); } private void checkBundleWires( BundleWiring tb1Wiring, BundleWiring tb2Wiring, BundleWiring tb3Wiring, BundleWiring tb5Wiring, BundleWiring tb14Wiring, Bundle tb4, List<BundleWire> allTb1ProvidedWires, List<BundleWire> osgiBundleTb1ProvidedWires, List<BundleWire> osgiHostTb1ProvidedWires, List<BundleWire> osgiPackageTb1ProvidedWires, List<BundleWire> genTestTb1ProvidedWires, List<BundleWire> genTestMultipleTb1ProvidedWires, List<BundleWire> genTestFragmentTb1ProvidedWires, List<BundleWire> genTestNoAttrsTb1ProvidedWires) { assertEquals("Wrong number of wires", 15, allTb1ProvidedWires.size()); checkWires(osgiBundleTb1ProvidedWires, allTb1ProvidedWires, BundleRevision.BUNDLE_NAMESPACE, 1); checkWires(osgiHostTb1ProvidedWires, allTb1ProvidedWires, BundleRevision.HOST_NAMESPACE, 1); checkWires(osgiPackageTb1ProvidedWires, allTb1ProvidedWires, BundleRevision.PACKAGE_NAMESPACE, 1); checkWires(genTestTb1ProvidedWires, allTb1ProvidedWires, "test", 10); checkWires(genTestMultipleTb1ProvidedWires, allTb1ProvidedWires, "test.multiple", 0); checkWires(genTestFragmentTb1ProvidedWires, allTb1ProvidedWires, "test.fragment", 1); checkWires(genTestNoAttrsTb1ProvidedWires, allTb1ProvidedWires, "test.no.attrs", 1); checkCapabilitiesTb1v110(tb1Wiring, tb4); checkCapabilitiesTb2(tb2Wiring); checkCapabilitiesTb3(tb3Wiring); checkCapabilitiesTb4(tb4.adapt(BundleWiring.class)); checkCapabilitiesTb5(tb5Wiring); checkCapabilitiesTb14(tb14Wiring); checkRequirementsTb1v110(tb1Wiring); checkRequirementsTb2(tb2Wiring); checkRequirementsTb3(tb3Wiring); checkRequirementsTb4(tb4.adapt(BundleWiring.class)); checkRequirementsTb5(tb5Wiring); checkRequirementsTb14(tb14Wiring); checkBundleWire( osgiBundleTb1ProvidedWires.get(0), tb1Wiring, tb3Wiring, tb1Wiring.getCapabilities(BundleRevision.BUNDLE_NAMESPACE).get(0), tb3Wiring.getRequirements(BundleRevision.BUNDLE_NAMESPACE).get(0)); checkBundleWire( osgiHostTb1ProvidedWires.get(0), tb1Wiring, tb4.adapt(BundleWiring.class), tb1Wiring.getCapabilities(BundleRevision.HOST_NAMESPACE).get(0), tb4.adapt(BundleWiring.class).getRequirements(BundleRevision.HOST_NAMESPACE).get(0)); checkBundleWire( osgiPackageTb1ProvidedWires.get(0), tb1Wiring, tb2Wiring, tb1Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE).get(0), tb2Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE).get(1)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(0), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(0)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(1), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(1)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(2), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(2)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(3), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(3)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(4), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(4)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(5), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(5)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(6), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(6)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(7), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(7)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(8), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(8)); checkBundleWire( tb5Wiring.getRequiredWires("test").get(9), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test").get(0), tb5Wiring.getRequirements("test").get(9)); checkBundleWire( genTestNoAttrsTb1ProvidedWires.get(0), tb1Wiring, tb5Wiring, tb1Wiring.getCapabilities("test.no.attrs").get(0), tb5Wiring.getRequirements("test.no.attrs").get(0)); checkBundleWire( genTestFragmentTb1ProvidedWires.get(0), tb1Wiring, tb14Wiring, tb1Wiring.getCapabilities("test.fragment").get(0), tb14Wiring.getRequirements("test.fragment").get(0)); List<BundleWire> fragments = tb1Wiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); assertEquals("Wrong number of fragments", 1, fragments.size()); assertEquals("Wrong fragment", tb4, fragments.get(0).getRequirerWiring().getBundle()); } private void checkBundleWire( BundleWire wire, BundleWiring provider, BundleWiring requirer, BundleCapability capability, BundleRequirement requirement) { assertEquals("Wrong provider", provider, wire.getProviderWiring()); assertEquals("Wrong requirer", requirer, wire.getRequirerWiring()); assertEquals("Wrong capability", capability, wire.getCapability()); assertEquals("Wrong requirement", requirement, wire.getRequirement()); assertTrue("Requirement does not match capability", wire.getRequirement().matches(wire.getCapability())); } public void testGetRevisions() { Bundle tb1 = install("resolver.tb1.v110.jar"); Bundle tb2 = install("resolver.tb2.jar"); Bundle tb3 = install("resolver.tb3.jar"); Bundle tb4 = install("resolver.tb4.jar"); Bundle tb5 = install("resolver.tb5.jar"); List<Bundle> testBundles = Arrays.asList(new Bundle[]{tb1, tb2, tb3, tb4, tb5}); assertTrue(frameworkWiring.resolveBundles(testBundles)); BundleRevisions tb1Revisions = tb1.adapt(BundleRevisions.class); BundleRevisions tb2Revisions = tb2.adapt(BundleRevisions.class); BundleRevisions tb3Revisions = tb3.adapt(BundleRevisions.class); BundleRevisions tb4Revisions = tb4.adapt(BundleRevisions.class); BundleRevisions tb5Revisions = tb5.adapt(BundleRevisions.class); BundleRevisions[] revisions = new BundleRevisions[] {tb1Revisions, tb2Revisions, tb3Revisions, tb4Revisions, tb5Revisions}; checkWirings((Bundle[]) testBundles.toArray(new Bundle[testBundles.size()]), revisions, 1, true); // test the refresh case refreshBundles(Arrays.asList(new Bundle[]{tb1})); assertTrue(frameworkWiring.resolveBundles(testBundles)); // do not reget the BundleRevisions must survive refresh operations checkWirings((Bundle[]) testBundles.toArray(new Bundle[testBundles.size()]), revisions, 1, true); // test the update case Bundle tb8 = install("resolver.tb8.jar"); BundleRevision tb1Revision1 = (BundleRevision) tb1.adapt(BundleRevision.class); URL content = getContext().getBundle().getEntry("resolver.tb1.v120.jar"); assertNotNull("Cannot find content for update", content); try { tb1.update(content.openStream()); } catch (BundleException e) { fail("Unexpected update failure",e); } catch (IOException e) { fail("Unexpected update failure",e); } BundleRevision tb1Revision2 = (BundleRevision) tb1.adapt(BundleRevision.class); assertTrue("Could not resolve updated bundle", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb1, tb8}))); checkWirings(new Bundle[] {tb1}, new BundleRevisions[] {tb1Revisions}, 2, true); checkRevisions(tb1Revisions, new BundleRevision[] {tb1Revision2, tb1Revision1}); Bundle tb9 = install("resolver.tb9.jar"); content = getContext().getBundle().getEntry("resolver.tb1.v130.jar"); assertNotNull("Cannot find content for update", content); try { tb1.update(content.openStream()); } catch (BundleException e) { fail("Unexpected update failure",e); } catch (IOException e) { fail("Unexpected update failure",e); } BundleRevision tb1Revision3 = (BundleRevision) tb1.adapt(BundleRevision.class); assertTrue("Could not resolve updated bundle", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb1, tb9}))); checkWirings(new Bundle[] {tb1}, new BundleRevisions[] {tb1Revisions}, 3, true); checkRevisions(tb1Revisions, new BundleRevision[] {tb1Revision3, tb1Revision2, tb1Revision1}); // test the refresh case refreshBundles(Arrays.asList(new Bundle[]{tb1})); assertTrue("Could not resolve test bundles", frameworkWiring.resolveBundles(testBundles)); // do not reget the BundleRevisions must survive refresh operations checkWirings((Bundle[]) testBundles.toArray(new Bundle[testBundles.size()]), revisions, 1, true); // test uninstall case try { tb1.uninstall(); } catch (BundleException e) { fail("Unexpected error on uninstall", e); } // regetting tb1 revisions to test that we can still get it after uninstall // this revision will only have 1 revision and it is not current tb1Revisions = tb1.adapt(BundleRevisions.class); checkWirings(new Bundle[] {tb1}, new BundleRevisions[] {tb1Revisions}, 1, false); // all other wirings are current and will only have one wiring each BundleRevisions[] otherRevisions = new BundleRevisions[] {tb2Revisions, tb3Revisions, tb4Revisions, tb5Revisions}; Bundle[] otherBundes = new Bundle[] {tb2, tb3, tb4, tb5}; checkWirings(otherBundes, otherRevisions, 1, true); } private void checkRevisions(BundleRevisions revisions, BundleRevision[] bundleRevisions) { List<BundleRevision> revisionList = revisions.getRevisions(); assertEquals("Wrong number of revisions", bundleRevisions.length, revisionList.size()); int i = 0; for (Iterator<BundleRevision> iRevisions = revisionList.iterator(); iRevisions.hasNext(); i++) assertEquals("Wrong revision found", bundleRevisions[i], iRevisions.next()); } private void checkWirings(Bundle[] bundles, BundleRevisions[] bundlesRevisions, int expectedNumRevisions, boolean hasCurrent) { assertEquals("Lists are not the same size", bundles.length, bundlesRevisions.length); for (int i = 0; i < bundlesRevisions.length; i++) { Bundle bundle = bundles[i]; BundleRevision current = (BundleRevision) bundle.adapt(BundleRevision.class); if (hasCurrent) { assertNotNull("BundleRevision is null for: " + bundle, current); assertEquals("Wrong BSN", bundle.getSymbolicName(), current.getSymbolicName()); assertEquals("Wrong version", bundle.getVersion(), current.getVersion()); } else { assertNull("BundleRevision must be null for: " + bundle, current); } BundleRevisions bundleRevisions = (BundleRevisions) bundlesRevisions[i]; assertNotNull("BundleRevisions is null for bundle: " + bundle, bundleRevisions); assertEquals("Wrong bundle for revisions", bundle, bundleRevisions.getBundle()); List<BundleRevision> revisions = bundleRevisions.getRevisions(); if (hasCurrent) assertEquals("Wrong current revision for bundle", current, revisions.get(0)); assertEquals("Wrong number of in use revisions", expectedNumRevisions, revisions.size()); int index = 0; for (Iterator<BundleRevision> iter = revisions.iterator(); iter.hasNext(); index++) { BundleRevision revision = (BundleRevision) iter.next(); BundleWiring wiring = revision.getWiring(); assertNotNull("bundle wiring is null", wiring); Collection<BundleWire> hostWires = wiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); Collection<BundleWire> fragmentWires = wiring.getRequiredWires(BundleRevision.HOST_NAMESPACE); assertNotNull("Host wires is null", hostWires); assertNotNull("Fragment wires is null", fragmentWires); if ((revision.getTypes() & BundleRevision.TYPE_FRAGMENT) != 0) { assertEquals("Wrong number of host wires", 0, hostWires.size()); assertEquals("Wrong number of fragment wires", 1, fragmentWires.size()); BundleWire fragmentWire = fragmentWires.iterator().next(); assertTrue("Fragment wire not found", fragmentWire.getProviderWiring().getProvidedWires(BundleRevision.HOST_NAMESPACE).contains(fragmentWire)); continue; } assertEquals("Wrong number of fragment wires", 0, fragmentWires.size()); if (index == 0 && hasCurrent) assertTrue("Wiring is not current for: " + bundle, wiring.isCurrent()); else assertFalse("Wiring is current for: " + bundle, wiring.isCurrent()); assertTrue("Wiring is not in use for: " + bundle, wiring.isInUse()); } } } // Note that this test assumes the tests are run on a JavaSE 1.5 vm or higher public void testOSGiEE() { // First bundle tests that the framework sets reasonable defaults for JavaSE 1.5 Bundle tb10v100 = install("resolver.tb10.v100.jar"); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb10v100}))); // Second bundle requires an osgi.ee that should not be able to resolve Bundle tb10v110 = install("resolver.tb10.v110.jar"); assertFalse(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb10v110}))); // Third bundle requires an osgi.ee that is specified by the system.capabilities.extra property Bundle tb10v120 = install("resolver.tb10.v120.jar"); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb10v120}))); // forth bundle requires JavaSE [1.3, 1.4) Bundle tb10v130 = install("resolver.tb10.v130.jar"); assertFalse(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb10v130}))); // fifth bundle requires JavaSE [1.3, 2.0) Bundle tb10v140 = install("resolver.tb10.v140.jar"); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb10v140}))); // Test that the ees come from the system bundle BundleWiring tb10v100Wiring = (BundleWiring) tb10v100.adapt(BundleWiring.class); assertNotNull("Wiring is null for: " + tb10v100, tb10v100Wiring); List<BundleWire> v100RequiredEEs = tb10v100Wiring.getRequiredWires("osgi.ee"); assertEquals("Wrong number of required osgi.ees", 7, v100RequiredEEs.size()); Bundle systemBundle = getContext().getBundle(0); assertNotNull("SystemBundle is null", systemBundle); for (Iterator<BundleWire> ees = v100RequiredEEs.iterator(); ees.hasNext();) { assertEquals("Wrong provider for osgi.ee", systemBundle, ees.next().getProviderWiring().getBundle()); } BundleWiring tb10v120Wiring = (BundleWiring) tb10v120.adapt(BundleWiring.class); assertNotNull("Wiring is null for: " + tb10v120, tb10v120Wiring); List<BundleWire> v120RequiredEEs = tb10v120Wiring.getRequiredWires("osgi.ee"); assertEquals("Wrong number of required osgi.ees", 1, v120RequiredEEs.size()); assertNotNull("SystemBundle is null", systemBundle); for (Iterator<BundleWire> ees = v120RequiredEEs.iterator(); ees.hasNext();) { assertEquals("Wrong provider for osgi.ee", systemBundle, ees.next().getProviderWiring().getBundle()); } } public void testOptionalRequireCapability() { Bundle tb11 = install("resolver.tb11.jar"); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb11}))); BundleWiring tb11Wiring = (BundleWiring) tb11.adapt(BundleWiring.class); assertNotNull("Wiring is null", tb11Wiring); List<BundleRequirement> requirements = tb11Wiring.getRequirements(null); assertNotNull("Requirements is null", requirements); assertEquals("Wrong number of requirements", 0, requirements.size()); List<BundleWire> wires = tb11Wiring.getRequiredWires(null); assertNotNull("Wires is null", wires); assertEquals("Wrong number of wires", 0, wires.size()); Bundle tb12 = install("resolver.tb12.jar"); refreshBundles(Arrays.asList(new Bundle[] {tb11})); assertTrue(frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {tb11, tb12}))); tb11Wiring = (BundleWiring) tb11.adapt(BundleWiring.class); assertNotNull("Wiring is null", tb11Wiring); requirements = tb11Wiring.getRequirements(null); assertNotNull("Requirements is null", requirements); assertEquals("Wrong number of requirements", 1, requirements.size()); wires = tb11Wiring.getRequiredWires(null); assertNotNull("Wires is null", wires); assertEquals("Wrong number of wires", 1, wires.size()); BundleWire wire = wires.get(0); assertEquals("Wrong provider", tb12, wire.getProviderWiring().getBundle()); assertEquals("Wrong requirer", tb11, wire.getRequirerWiring().getBundle()); } // Note that this test is done in GetEntryResourceTest // public void testFindEntries() { // fail("Need to write a findEntries test."); // } public void testListResources() { install("wiring.base.jar"); // force base to resolve first assertTrue("Could not resolve test bundles", frameworkWiring.resolveBundles(bundles)); Bundle exporter = install("wiring.exporter.jar"); Bundle importer = install("wiring.importer.jar"); Bundle requirer = install("wiring.requirer.jar"); install("wiring.reexport.jar"); assertTrue("Could not resolve test bundles", frameworkWiring.resolveBundles(bundles)); BundleWiring exporterWiring = (BundleWiring) exporter.adapt(BundleWiring.class); BundleWiring importerWiring = (BundleWiring) importer.adapt(BundleWiring.class); BundleWiring requirerWiring = (BundleWiring) requirer.adapt(BundleWiring.class); // test that empty lists are returned when no resources are found Collection empty = exporterWiring.listResources("", "*.notfound", BundleWiring.LISTRESOURCES_RECURSE); assertNotNull("Should return empty list", empty); assertEquals("Should have 0 resources", 0, empty.size()); empty = importerWiring.listResources("", "*.notfound", BundleWiring.LISTRESOURCES_RECURSE); assertNotNull("Should return empty list", empty); assertEquals("Should have 0 resources", 0, empty.size()); empty = requirerWiring.listResources("", "*.notfound", BundleWiring.LISTRESOURCES_RECURSE); assertNotNull("Should return empty list", empty); assertEquals("Should have 0 resources", 0, empty.size()); // test exporter resources Collection rootResources = exporterWiring.listResources("/root", "*.txt", 0); assertEquals("Wrong number of resources", 1, rootResources.size()); assertEquals("Wrong resource", "root/root.export.txt", rootResources .iterator().next()); checkResources(exporterWiring.getClassLoader(), rootResources); // note that root.B package has been substituted List expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/b/b.export.txt", "root/A/A.export.txt", "root/A/A.reexport.txt", "root/B/a/a.export.txt", "root/B/b/b.export.txt", "root/B/B.base.txt", // this has been substituted "root/C/C.reexport.txt", "root/root.export.txt"}); rootResources = exporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(exporterWiring.getClassLoader(), rootResources); // test local resources of exporter; note that root.B resources are not available expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/b/b.export.txt", "root/A/A.export.txt", "root/B/a/a.export.txt", "root/B/b/b.export.txt", "root/root.export.txt"}); rootResources = exporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(exporterWiring.getClassLoader(), rootResources); // test importer resources rootResources = importerWiring.listResources("/root", "*.txt", 0); assertEquals("Wrong number of resources", 1, rootResources.size()); assertEquals("Wrong resource", "root/root.local.txt", rootResources .iterator().next()); checkResources(importerWiring.getClassLoader(), rootResources); // note that root.B package has been substituted rootResources = importerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/b/b.local.txt", "root/A/A.local.txt", "root/B/a/a.export.txt", "root/B/b/b.export.txt", "root/B/B.base.txt", // this has been substituted "root/root.local.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(importerWiring.getClassLoader(), rootResources); // test local resources, anything shadowed by an import must not be included rootResources = importerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/b/b.local.txt", "root/A/A.local.txt", "root/root.local.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(importerWiring.getClassLoader(), rootResources); // test the require bundle case rootResources = requirerWiring.listResources("/root", "*.txt", 0); expected = Arrays.asList(new String[] { "root/root.export.txt", "root/root.local.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // test require case; no shadowing of local resources; still have root.B substituted rootResources = requirerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/a/a.local.txt", "root/A/b/b.export.txt", "root/A/b/b.local.txt", "root/A/A.export.txt", "root/A/A.reexport.txt", "root/A/A.local.txt", "root/B/a/a.export.txt", "root/B/a/a.local.txt", "root/B/b/b.export.txt", "root/B/b/b.local.txt", "root/B/B.base.txt", // this has been substituted "root/B/B.local.txt", "root/C/C.reexport.txt", "root/root.export.txt", "root/root.local.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // test require local resources; not there is no shadowing so we get all local resources rootResources = requirerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/b/b.local.txt", "root/A/A.local.txt", "root/B/a/a.local.txt", "root/B/b/b.local.txt", "root/B/B.local.txt", "root/root.local.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // install fragments to test install("wiring.exporter.frag.jar"); install("wiring.importer.frag.jar"); install("wiring.requirer.frag.jar"); refreshBundles(bundles); assertTrue("failed to resolve test fragments", frameworkWiring.resolveBundles(bundles)); // test that old wirings return null rootResources = exporterWiring.listResources("/root", "*.txt", 0); assertNull("Old wiring still accesses resources", rootResources); rootResources = importerWiring.listResources("/root", "*.txt", 0); assertNull("Old wiring still accesses resources", rootResources); rootResources = requirerWiring.listResources("/root", "*.txt", 0); assertNull("Old wiring still accesses resources", rootResources); // get the latest wiring exporterWiring = (BundleWiring) exporter.adapt(BundleWiring.class); importerWiring = (BundleWiring) importer.adapt(BundleWiring.class); requirerWiring = (BundleWiring) requirer.adapt(BundleWiring.class); // test exporter resources expected = Arrays.asList(new String[] { "root/root.export.txt", "root/root.frag.txt"}); rootResources = exporterWiring.listResources("/root", "*.txt", 0); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(exporterWiring.getClassLoader(), rootResources); // note that root.B package has been substituted expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/a/a.frag.txt", "root/A/b/b.export.txt", "root/A/b/b.frag.txt", "root/A/A.export.txt", "root/A/A.frag.txt", "root/A/A.reexport.txt", "root/B/a/a.export.txt", "root/B/a/a.frag.txt", "root/B/b/b.export.txt", "root/B/b/b.frag.txt", "root/B/B.base.txt", // this has been substituted "root/C/C.reexport.txt", "root/root.export.txt", "root/root.frag.txt"}); rootResources = exporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(exporterWiring.getClassLoader(), rootResources); // test local resources of exporter; note that root.B resources are not available expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/a/a.frag.txt", "root/A/b/b.export.txt", "root/A/b/b.frag.txt", "root/A/A.export.txt", "root/A/A.frag.txt", "root/B/a/a.export.txt", "root/B/a/a.frag.txt", "root/B/b/b.export.txt", "root/B/b/b.frag.txt", "root/root.export.txt", "root/root.frag.txt"}); rootResources = exporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(exporterWiring.getClassLoader(), rootResources); // test importer resources expected = Arrays.asList(new String[] { "root/root.local.txt", "root/root.frag.txt"}); rootResources = importerWiring.listResources("/root", "*.txt", 0); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(importerWiring.getClassLoader(), rootResources); // note that root.B package has been substituted rootResources = importerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/a/a.frag.txt", "root/A/b/b.local.txt", "root/A/b/b.frag.txt", "root/A/A.local.txt", "root/A/A.frag.txt", "root/B/a/a.export.txt", "root/B/a/a.frag.txt", "root/B/b/b.export.txt", "root/B/b/b.frag.txt", "root/B/B.base.txt", // this has been substituted "root/root.local.txt", "root/root.frag.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(importerWiring.getClassLoader(), rootResources); // test local resources, anything shadowed by an import must not be included rootResources = importerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/a/a.frag.txt", "root/A/b/b.local.txt", "root/A/b/b.frag.txt", "root/A/A.local.txt", "root/A/A.frag.txt", "root/root.local.txt", "root/root.frag.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(importerWiring.getClassLoader(), rootResources); // test the require bundle case rootResources = requirerWiring.listResources("/root", "*.txt", 0); expected = Arrays.asList(new String[] { "root/root.export.txt", "root/root.local.txt", "root/root.frag.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // test require case; no shadowing of local resources; still have root.B substituted rootResources = requirerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/a/a.local.txt", "root/A/a/a.frag.txt", "root/A/b/b.export.txt", "root/A/b/b.local.txt", "root/A/b/b.frag.txt", "root/A/A.export.txt", "root/A/A.reexport.txt", "root/A/A.local.txt", "root/A/A.frag.txt", "root/B/a/a.export.txt", "root/B/a/a.local.txt", "root/B/a/a.frag.txt", "root/B/b/b.export.txt", "root/B/b/b.local.txt", "root/B/b/b.frag.txt", "root/B/B.base.txt", // this has been substituted "root/B/B.local.txt", "root/B/B.frag.txt", "root/C/C.reexport.txt", "root/root.export.txt", "root/root.local.txt", "root/root.frag.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // test require local resources; not there is no shadowing so we get all local resources rootResources = requirerWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE | BundleWiring.LISTRESOURCES_LOCAL); expected = Arrays.asList(new String[] { "root/A/a/a.local.txt", "root/A/a/a.frag.txt", "root/A/b/b.local.txt", "root/A/b/b.frag.txt", "root/A/A.local.txt", "root/A/A.frag.txt", "root/B/a/a.local.txt", "root/B/a/a.frag.txt", "root/B/b/b.local.txt", "root/B/b/b.frag.txt", "root/B/B.local.txt", "root/B/B.frag.txt", "root/root.local.txt", "root/root.frag.txt" }); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(requirerWiring.getClassLoader(), rootResources); // test update case URL updateContent = getContext().getBundle().getEntry("wiring.exporter.v2.jar"); assertNotNull("Could not find update content", updateContent); try { exporter.update(updateContent.openStream()); } catch (Exception e) { fail("Failed to update bundle", e); } assertTrue("Failed to resolve bundle", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[] {exporter}))); BundleWiring oldExporterWiring = exporterWiring; BundleWiring newExporterWiring = (BundleWiring) exporter.adapt(BundleWiring.class); // Do a sanity check to make sure the old wiring still works // note that root.B package has been substituted // note that the fragment should still be providing content to the old wiring expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/a/a.frag.txt", "root/A/b/b.export.txt", "root/A/b/b.frag.txt", "root/A/A.export.txt", "root/A/A.frag.txt", "root/A/A.reexport.txt", "root/B/a/a.export.txt", "root/B/a/a.frag.txt", "root/B/b/b.export.txt", "root/B/b/b.frag.txt", "root/B/B.base.txt", // this has been substituted "root/C/C.reexport.txt", "root/root.export.txt", "root/root.frag.txt"}); rootResources = oldExporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(oldExporterWiring.getClassLoader(), rootResources); // check the new wiring; no fragment attached // note that root.B package has been substituted expected = Arrays.asList(new String[] { "root/A/a/a.export.txt", "root/A/b/b.export.txt", "root/A/A.export.txt", "root/A/A.reexport.txt", "root/B/a/a.export.txt", "root/B/b/b.export.txt", "root/B/B.base.txt", // this has been substituted "root/C/C.reexport.txt", "root/root.export.txt"}); rootResources = newExporterWiring.listResources("/root", "*.txt", BundleWiring.LISTRESOURCES_RECURSE); assertResourcesEquals("Wrong resources", expected, rootResources); checkResources(newExporterWiring.getClassLoader(), rootResources); } public void testBSNMatchingAttributes() { Bundle tb13a = install("resolver.tb13a.jar"); Bundle tb13b = install("resolver.tb13b.jar"); Bundle tb13Client1 = install("resolver.tb13.client1.jar"); Bundle tb13Client2 = install("resolver.tb13.client2.jar"); Bundle tb13Client3 = install("resolver.tb13.client3.jar"); Bundle tb13Client4 = install("resolver.tb13.client4.jar"); Bundle tb13Frag1 = install("resolver.tb13.frag1.jar"); Bundle tb13Frag2 = install("resolver.tb13.frag2.jar"); Bundle tb13Frag3 = install("resolver.tb13.frag3.jar"); Bundle tb13Frag4 = install("resolver.tb13.frag4.jar"); assertFalse(frameworkWiring.resolveBundles(bundles)); assertEquals("Unexpected state for: " + tb13a.getSymbolicName(), Bundle.RESOLVED, tb13a.getState()); assertEquals("Unexpected state for: " + tb13b.getSymbolicName(), Bundle.RESOLVED, tb13b.getState()); assertEquals("Unexpected state for: " + tb13Client1.getSymbolicName(), Bundle.INSTALLED, tb13Client1.getState()); assertEquals("Unexpected state for: " + tb13Client2.getSymbolicName(), Bundle.RESOLVED, tb13Client2.getState()); assertEquals("Unexpected state for: " + tb13Client3.getSymbolicName(), Bundle.INSTALLED, tb13Client3.getState()); assertEquals("Unexpected state for: " + tb13Client4.getSymbolicName(), Bundle.RESOLVED, tb13Client4.getState()); assertEquals("Unexpected state for: " + tb13Frag1.getSymbolicName(), Bundle.INSTALLED, tb13Frag1.getState()); assertEquals("Unexpected state for: " + tb13Frag2.getSymbolicName(), Bundle.RESOLVED, tb13Frag2.getState()); assertEquals("Unexpected state for: " + tb13Frag3.getSymbolicName(), Bundle.INSTALLED, tb13Frag3.getState()); assertEquals("Unexpected state for: " + tb13Frag4.getSymbolicName(), Bundle.RESOLVED, tb13Frag4.getState()); BundleWiring tb13Client1Wiring = (BundleWiring) tb13Client1.adapt(BundleWiring.class); assertNull("Expected null Wiring: " + tb13Client1.getSymbolicName(), tb13Client1Wiring); BundleWiring tb13Client3Wiring = (BundleWiring) tb13Client3.adapt(BundleWiring.class); assertNull("Expected null Wiring: " + tb13Client3.getSymbolicName(), tb13Client3Wiring); BundleWiring tb13aWiring = (BundleWiring) tb13a.adapt(BundleWiring.class); assertNotNull("Expected non-null wiring: " + tb13a.getSymbolicName(), tb13aWiring); BundleWiring tb13bWiring = (BundleWiring) tb13b.adapt(BundleWiring.class); assertNotNull("Expected non-null wiring: " + tb13b.getSymbolicName(), tb13bWiring); BundleWiring tb13Client2Wiring = (BundleWiring) tb13Client2.adapt(BundleWiring.class); assertNotNull("Expected non-null wiring: " + tb13Client2.getSymbolicName(), tb13Client2Wiring); BundleWiring tb13Client4Wiring = (BundleWiring) tb13Client4.adapt(BundleWiring.class); assertNotNull("Expected non-null wiring: " + tb13Client4.getSymbolicName(), tb13Client4Wiring); List<BundleRequirement> client2Requirements = tb13Client2Wiring.getRequirements(BundleRevision.BUNDLE_NAMESPACE); assertEquals("Unexpected number of requirements", 1, client2Requirements.size()); assertEquals("Wrong provider", tb13Client2, client2Requirements.get(0).getRevision().getBundle()); List<BundleWire> client2RequiredWires = tb13Client2Wiring.getRequiredWires(BundleRevision.BUNDLE_NAMESPACE); assertEquals("Unexpected number of wires", 1, client2RequiredWires.size()); assertEquals("Wrong provider", tb13a, client2RequiredWires.get(0).getProviderWiring().getBundle()); List<BundleWire> client4RequiredWires = tb13Client4Wiring.getRequiredWires(BundleRevision.BUNDLE_NAMESPACE); assertEquals("Unexpected number of wires", 1, client4RequiredWires.size()); assertEquals("Wrong provider", tb13b, client4RequiredWires.get(0).getProviderWiring().getBundle()); List<BundleWire> tb13aProvidedWires = tb13aWiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); assertEquals("Unexpected number of wires", 1, tb13aProvidedWires.size()); assertEquals("Wrong fragment attached", tb13Frag2, tb13aProvidedWires.get(0).getRequirerWiring().getBundle()); BundleWiring tb13Frag2Wiring = tb13Frag2.adapt(BundleWiring.class); assertNotNull("Fragments must be adaptable to BundleWiring", tb13Frag2Wiring); List<BundleWire> tb13Frag2RequiredWires = tb13Frag2Wiring.getRequiredWires(BundleRevision.HOST_NAMESPACE); assertEquals("Unexpected number of wires", 1, tb13Frag2RequiredWires.size()); assertEquals("Wrong host attached", tb13a, tb13Frag2RequiredWires.get(0).getProviderWiring().getBundle()); List<BundleWire> tb13bProvidedWires = tb13bWiring.getProvidedWires(BundleRevision.HOST_NAMESPACE); assertEquals("Unexpected number of wires", 1, tb13bProvidedWires.size()); assertEquals("Wrong fragment attached", tb13Frag4, tb13bProvidedWires.get(0).getRequirerWiring().getBundle()); BundleWiring tb13Frag4Wiring = tb13Frag4.adapt(BundleWiring.class); assertNotNull("Fragments must be adaptable to BundleWiring", tb13Frag2Wiring); List<BundleWire> tb13Frag4RequiredWires = tb13Frag4Wiring.getRequiredWires(BundleRevision.HOST_NAMESPACE); assertEquals("Unexpected number of wires", 1, tb13Frag4RequiredWires.size()); assertEquals("Wrong host attached", tb13b, tb13Frag4RequiredWires.get(0).getProviderWiring().getBundle()); } private void assertResourcesEquals(String message, Collection expected, Collection actual) { if (expected.size() != actual.size()) fail(message + ": Collections are not the same size: " + expected + ": " + actual); assertTrue(message + ": Colections do not contain the same content: " + expected + ": " + actual, actual.containsAll(expected)); } private void checkResources(ClassLoader cl, Collection resources) { for(Iterator iResources = resources.iterator(); iResources.hasNext();) { String path = (String) iResources.next(); URL resource = cl.getResource(path); assertNotNull("Could not find resource: " + path, resource); } } /** * Ensures an implementation delivers a bundle wiring's provided wires in * the proper order. The ordering rules are as follows. * * (1) For a given name space, the list contains the wires in the order the * capabilities were specified in the manifests of the bundle revision and * the attached fragments of this bundle wiring. * * (2) There is no ordering defined between wires in different namespaces. * * (3) There is no ordering defined between multiple wires for the same * capability, but the wires must be contiguous, and the group must be * ordered as in (1). */ public void testProvidedWiresOrdering() { Bundle tb1 = install("wiring.tb1.jar"); Bundle tb2 = install("wiring.tb2.jar"); Bundle tb3 = install("wiring.tb3.jar"); Bundle tb4 = install("wiring.tb4.jar"); assertTrue("Bundles should have resolved", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb1,tb2,tb3,tb4}))); BundleWiring tb1Wiring = tb1.adapt(BundleWiring.class); BundleWiring tb2Wiring = tb2.adapt(BundleWiring.class); BundleWiring tb3Wiring = tb3.adapt(BundleWiring.class); BundleWiring tb4Wiring = tb4.adapt(BundleWiring.class); List<BundleWire> tb1Wires = tb1Wiring.getProvidedWires(BundleRevision.PACKAGE_NAMESPACE); assertEquals("Wrong number of wires", 6, tb1Wires.size()); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1a", tb1Wires.get(0).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(0).getRequirerWiring().equals(tb2Wiring) || tb1Wires.get(0).getRequirerWiring().equals(tb3Wiring)); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1a", tb1Wires.get(1).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(1).getRequirerWiring().equals(tb2Wiring) || tb1Wires.get(1).getRequirerWiring().equals(tb3Wiring)); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1b", tb1Wires.get(2).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(2).getRequirerWiring().equals(tb2Wiring) || tb1Wires.get(2).getRequirerWiring().equals(tb4Wiring)); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1b", tb1Wires.get(3).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(3).getRequirerWiring().equals(tb2Wiring) || tb1Wires.get(3).getRequirerWiring().equals(tb4Wiring)); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1c", tb1Wires.get(4).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(4).getRequirerWiring().equals(tb3Wiring) || tb1Wires.get(4).getRequirerWiring().equals(tb4Wiring)); assertEquals("Wrong order", "org.osgi.test.cases.framework.wiring.tb1c", tb1Wires.get(5).getCapability().getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); assertTrue("Wrong requirer", tb1Wires.get(5).getRequirerWiring().equals(tb3Wiring) || tb1Wires.get(5).getRequirerWiring().equals(tb4Wiring)); } /** * Basic test for support of the DynamicImport-Package requirement. */ public void testDynamicImportPackage() throws Exception { Bundle tb1 = install("resolver.tb1.v110.jar"); Bundle tb2 = install("wiring.tb1.jar"); Bundle tb3 = install("wiring.tb5.jar"); assertTrue("The bundles should have resolved", frameworkWiring.resolveBundles(Arrays.asList(new Bundle[]{tb1,tb2,tb3}))); BundleRevision tb3Revision = (BundleRevision)tb3.adapt(BundleRevision.class); BundleWiring tb1Wiring = (BundleWiring)tb1.adapt(BundleWiring.class); BundleWiring tb2Wiring = (BundleWiring)tb2.adapt(BundleWiring.class); BundleWiring tb3Wiring = (BundleWiring)tb3.adapt(BundleWiring.class); checkRequirements( tb3Revision.getDeclaredRequirements(BundleRevision.PACKAGE_NAMESPACE), tb3Revision.getDeclaredRequirements(null), BundleRevision.PACKAGE_NAMESPACE, 1, tb3Revision); checkRequirements( tb3Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequirements(null), BundleRevision.PACKAGE_NAMESPACE, 1, tb3Wiring.getRevision()); checkWires( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequiredWires(null), BundleRevision.PACKAGE_NAMESPACE, 0); tb3.loadClass("org.osgi.test.cases.framework.resolver.tb1.Test"); checkWires( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequiredWires(null), BundleRevision.PACKAGE_NAMESPACE, 1); checkBundleWire( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE).get(0), tb1Wiring, tb3Wiring, tb1Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE).get(0), tb3Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE).get(0)); tb3.loadClass("org.osgi.test.cases.framework.wiring.tb1a.PlaceHolder"); checkWires( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequiredWires(null), BundleRevision.PACKAGE_NAMESPACE, 2); BundleCapability bc = tb2Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE).get(0); assertEquals("Wrong attribute", "org.osgi.test.cases.framework.wiring.tb1a", bc.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); checkBundleWire( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE).get(1), tb2Wiring, tb3Wiring, bc, tb3Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE).get(0)); tb3.loadClass("org.osgi.test.cases.framework.wiring.tb1b.PlaceHolder"); checkWires( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE), tb3Wiring.getRequiredWires(null), BundleRevision.PACKAGE_NAMESPACE, 3); bc = tb2Wiring.getCapabilities(BundleRevision.PACKAGE_NAMESPACE).get(1); assertEquals("Wrong attribute", "org.osgi.test.cases.framework.wiring.tb1b", bc.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE)); checkBundleWire( tb3Wiring.getRequiredWires(BundleRevision.PACKAGE_NAMESPACE).get(2), tb2Wiring, tb3Wiring, bc, tb3Wiring.getRequirements(BundleRevision.PACKAGE_NAMESPACE).get(0)); } }
Add simple test for bug 1922
org.osgi.test.cases.framework/src/org/osgi/test/cases/framework/junit/wiring/BundleWiringTests.java
Add simple test for bug 1922
<ide><path>rg.osgi.test.cases.framework/src/org/osgi/test/cases/framework/junit/wiring/BundleWiringTests.java <ide> import org.osgi.framework.Bundle; <ide> import org.osgi.framework.BundleException; <ide> import org.osgi.framework.Constants; <add>import org.osgi.framework.Filter; <ide> import org.osgi.framework.FrameworkEvent; <ide> import org.osgi.framework.FrameworkListener; <add>import org.osgi.framework.FrameworkUtil; <add>import org.osgi.framework.InvalidSyntaxException; <ide> import org.osgi.framework.wiring.BundleCapability; <ide> import org.osgi.framework.wiring.BundleRequirement; <ide> import org.osgi.framework.wiring.BundleRevision; <ide> assertEquals("Wrong capability", capability, wire.getCapability()); <ide> assertEquals("Wrong requirement", requirement, wire.getRequirement()); <ide> assertTrue("Requirement does not match capability", wire.getRequirement().matches(wire.getCapability())); <add> String filterDirective = wire.getRequirement().getDirectives().get(Constants.FILTER_DIRECTIVE); <add> if (wire.getRequirement().getNamespace().startsWith("osgi.wiring.")) { <add> assertTrue("An osgi.wiring.* requirement has non-empty attribute map.", wire.getRequirement().getAttributes().isEmpty()); <add> assertNotNull("Null filter directive is not allowed for osgi.wiring.* name spaces.", filterDirective); <add> try { <add> Filter filter = FrameworkUtil.createFilter(filterDirective); <add> assertTrue("Filter directive does not match capability attributes: " + filterDirective, filter.matches(wire.getCapability().getAttributes())); <add> } catch (InvalidSyntaxException e) { <add> fail("Failed to create filter: " + filterDirective, e); <add> } <add> } <ide> } <ide> <ide> public void testGetRevisions() {
JavaScript
mit
3df73cfdce4d2f3ad7f6b62449a874239390de73
0
jbaicoianu/janusweb,jbaicoianu/janusweb,jbaicoianu/janusweb
elation.require(['engine.engine', 'engine.assets', 'engine.things.light_ambient', 'engine.things.light_directional', 'engine.things.light_point', 'janusweb.janusweb', 'janusweb.chat', 'janusweb.janusplayer', 'janusweb.ui'], function() { // If getCurrentScript returns non-null here, then it means we're in release mode var clientScript = elation.utils.getCurrentScript(); elation.extend('janusweb.init', function(args) { if (!args) args = {}; var proto = elation.utils.any(args.protocol, elation.config.get('dependencies.protocol'), document.location.protocol); var host = elation.utils.any(args.host, elation.config.get('dependencies.host'), document.location.host); var rootdir = elation.utils.any(args.rootdir, elation.config.get('dependencies.rootdir'), document.location.pathname); var path = elation.utils.any(args.path, elation.config.get('dependencies.path'), '/'); var homepage = elation.utils.any(args.homepage, elation.config.get('janusweb.homepage'), document.location.href); var container = elation.utils.any(args.container, document.body); var fullsize = (container == document.body); var fullpath = proto + '//' + host + rootdir; if (clientScript) { // && clientScript.src.match(/\/janusweb.js^/)) { var parts = clientScript.src.split('/'); var fname = parts.pop(); fullpath = parts.join('/') + '/'; parts.shift(); parts.shift(); parts.shift(); var rootdir = '/'; if (parts.length > 0) { rootdir += parts.join('/') + '/'; } elation.config.set('dependencies.main', fname); elation.config.set('dependencies.rootdir', rootdir); elation.config.set('dependencies.host', document.location.host); elation.config.set('dependencies.protocol', document.location.protocol); elation.config.set('janusweb.datapath', fullpath + 'media/'); elation.config.set('engine.assets.font.path', fullpath + 'media/fonts/'); } elation.config.set('dependencies.path', fullpath); var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = fullpath + 'janusweb.css'; document.head.appendChild(link); elation.html.addclass(document.body, 'dark'); elation.html.addclass(document.body, 'janusweb'); var janusweb = elation.janusweb.client({ append: container, homepage: homepage, shownavigation: args.shownavigation, showchat: elation.utils.any(args.showchat, true), usevoip: elation.utils.any(args.usevoip, false), resolution: args.resolution, url: args.url, networking: args.networking, autoload: args.autoload, urltemplate: args.urltemplate }); return new Promise(function(resolve, reject) { elation.events.add(janusweb.engine, 'engine_start', function() { resolve(janusweb); }); }); }); elation.component.add('janusweb.client', function() { this.initEngine = function() { this.initLoader(); var hashargs = elation.url(); this.enginecfg.stats = false; this.enginecfg.systems = []; this.enginecfg.systems.push("controls"); this.enginecfg.systems.push("physics"); this.enginecfg.systems.push("ai"); this.enginecfg.systems.push("world"); //if (hashargs.admin == 1) { this.enginecfg.systems.push("admin"); //} this.enginecfg.systems.push("render"); this.enginecfg.systems.push("sound"); this.enginecfg.crosshair = false; this.enginecfg.picking = true; this.buttons = elation.ui.buttonbar({append: document.body, classname: 'janusweb_ui_buttons'}) setTimeout(elation.bind(this, function() { this.initSharing(); }), 0); } this.initSharing = function() { this.sharedialog = elation.engine.sharing({append: document.body, client: this}); this.sharebutton = elation.ui.button({classname: 'janusweb_sharing', label: 'Share'}); elation.events.add(this.sharebutton, 'ui_button_click', elation.bind(this.sharedialog, this.sharedialog.showShareDialog)); this.buttons.add('sharing', this.sharebutton); } this.initWorld = function() { var things = this.world.load({ name: 'janusweb', type: 'janusweb', properties: { corsproxy: elation.config.get('engine.assets.corsproxy'), datapath: elation.config.get('janusweb.datapath'), homepage: this.args.homepage, url: this.args.url, showchat: this.args.showchat, networking: this.args.networking, autoload: this.args.autoload, urltemplate: this.args.urltemplate, } }); this.janusweb = things.children.janusweb; this.player = this.janusweb.spawn('janusplayer', 'player', { janus: this.janusweb, position: [0,0,0], mass: 10, movespeed: 5000, collidable: true, usevoip: this.args.usevoip }); this.shownavigation = elation.utils.any(this.args.shownavigation, true); if (this.shownavigation) { this.ui = elation.janusweb.ui({append: document.body, client: this}); } } this.initLoader = function() { var loader = document.getElementsByClassName('engine_loading')[0]; if (loader) { var logo = loader.getElementsByTagName('svg')[0]; var label = loader.getElementsByClassName('janusweb_loading_status')[0]; this.loadingscreen = { container: loader, logo: logo, label: label }; elation.events.add(this, 'engine_error', elation.bind(this, this.handleEngineError)); elation.events.add(this.engine, 'engine_start', elation.bind(this, this.handleEngineStart)); } } this.handleEngineStart = function(ev) { if (this.loadingscreen) { this.loadingscreen.container.parentNode.removeChild(this.loadingscreen.container); } } this.handleEngineError = function(ev) { console.log('omg error!', ev); if (this.loadingscreen) { this.loadingscreen.label.innerHTML = 'Error!'; elation.html.addclass(this.loadingscreen.container, 'state_error'); var err = ev.data; var msg = err.message + '\n' + err.stack; var errordiv = elation.html.create({tag: 'pre', append: this.loadingscreen.container, content: msg, classname: 'janusweb_error'}); } } this.showAbout = function() { var aboutwin = elation.ui.window({append: document.body, center: true, title: 'About JanusWeb'}); var frame = elation.ui.iframe({src: 'http://github.com/jbaicoianu/janusweb/', classname: 'janusweb_about'}); aboutwin.setcontent(frame); } }, elation.engine.client); });
scripts/client.js
elation.require(['engine.engine', 'engine.assets', 'engine.things.light_ambient', 'engine.things.light_directional', 'engine.things.light_point', 'janusweb.janusweb', 'janusweb.chat', 'janusweb.janusplayer', 'janusweb.ui'], function() { // If getCurrentScript returns non-null here, then it means we're in release mode var clientScript = elation.utils.getCurrentScript(); elation.extend('janusweb.init', function(args) { if (!args) args = {}; var proto = elation.utils.any(args.protocol, elation.config.get('dependencies.protocol'), document.location.protocol); var host = elation.utils.any(args.host, elation.config.get('dependencies.host'), document.location.host); var rootdir = elation.utils.any(args.rootdir, elation.config.get('dependencies.rootdir'), document.location.pathname); var path = elation.utils.any(args.path, elation.config.get('dependencies.path'), '/'); var homepage = elation.utils.any(args.homepage, elation.config.get('janusweb.homepage'), document.location.href); var container = elation.utils.any(args.container, document.body); var fullsize = (container == document.body); var fullpath = proto + '//' + host + rootdir; if (clientScript) { // && clientScript.src.match(/\/janusweb.js^/)) { var parts = clientScript.src.split('/'); var fname = parts.pop(); fullpath = parts.join('/') + '/'; parts.shift(); parts.shift(); parts.shift(); var rootdir = '/'; if (parts.length > 0) { rootdir += parts.join('/') + '/'; } elation.config.set('dependencies.main', fname); elation.config.set('dependencies.rootdir', rootdir); elation.config.set('dependencies.host', document.location.host); elation.config.set('dependencies.protocol', document.location.protocol); elation.config.set('janusweb.datapath', fullpath + 'media/'); elation.config.set('engine.assets.font.path', fullpath + 'media/fonts/'); } elation.config.set('dependencies.path', fullpath); var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = fullpath + 'janusweb.css'; document.head.appendChild(link); elation.html.addclass(document.body, 'dark'); elation.html.addclass(document.body, 'janusweb'); var janusweb = elation.janusweb.client({ append: container, homepage: homepage, shownavigation: args.shownavigation, showchat: elation.utils.any(args.showchat, true), usevoip: elation.utils.any(args.usevoip, false), resolution: args.resolution, url: args.url, networking: args.networking, autoload: args.autoload, urltemplate: args.urltemplate }); return new Promise(function(resolve, reject) { elation.events.add(janusweb.engine, 'engine_start', function() { resolve(janusweb); }); }); }); elation.component.add('janusweb.client', function() { this.initEngine = function() { this.initLoader(); var hashargs = elation.url(); this.enginecfg.stats = false; this.enginecfg.systems = []; this.enginecfg.systems.push("controls"); this.enginecfg.systems.push("physics"); this.enginecfg.systems.push("ai"); this.enginecfg.systems.push("world"); //if (hashargs.admin == 1) { this.enginecfg.systems.push("admin"); //} this.enginecfg.systems.push("render"); this.enginecfg.systems.push("sound"); this.enginecfg.crosshair = false; this.enginecfg.picking = true; this.buttons = elation.ui.buttonbar({append: document.body, classname: 'janusweb_ui_buttons'}) setTimeout(elation.bind(this, function() { this.initSharing(); }), 0); } this.initWorld = function() { var things = this.world.load({ name: 'janusweb', type: 'janusweb', properties: { corsproxy: elation.config.get('engine.assets.corsproxy'), datapath: elation.config.get('janusweb.datapath'), homepage: this.args.homepage, url: this.args.url, showchat: this.args.showchat, networking: this.args.networking, autoload: this.args.autoload, urltemplate: this.args.urltemplate, } }); this.janusweb = things.children.janusweb; this.player = this.janusweb.spawn('janusplayer', 'player', { janus: this.janusweb, position: [0,0,0], mass: 10, movespeed: 5000, collidable: true, usevoip: this.args.usevoip }); this.shownavigation = elation.utils.any(this.args.shownavigation, true); if (this.shownavigation) { this.ui = elation.janusweb.ui({append: document.body, client: this}); } } this.initLoader = function() { var loader = document.getElementsByClassName('engine_loading')[0]; if (loader) { var logo = loader.getElementsByTagName('svg')[0]; var label = loader.getElementsByClassName('janusweb_loading_status')[0]; this.loadingscreen = { container: loader, logo: logo, label: label }; elation.events.add(this, 'engine_error', elation.bind(this, this.handleEngineError)); elation.events.add(this.engine, 'engine_start', elation.bind(this, this.handleEngineStart)); } } this.handleEngineStart = function(ev) { if (this.loadingscreen) { this.loadingscreen.container.parentNode.removeChild(this.loadingscreen.container); } } this.handleEngineError = function(ev) { console.log('omg error!', ev); if (this.loadingscreen) { this.loadingscreen.label.innerHTML = 'Error!'; elation.html.addclass(this.loadingscreen.container, 'state_error'); var err = ev.data; var msg = err.message + '\n' + err.stack; var errordiv = elation.html.create({tag: 'pre', append: this.loadingscreen.container, content: msg, classname: 'janusweb_error'}); } } this.showAbout = function() { var aboutwin = elation.ui.window({append: document.body, center: true, title: 'About JanusWeb'}); var frame = elation.ui.iframe({src: 'http://github.com/jbaicoianu/janusweb/', classname: 'janusweb_about'}); aboutwin.setcontent(frame); } }, elation.engine.client); });
Init sharing function
scripts/client.js
Init sharing function
<ide><path>cripts/client.js <ide> this.initSharing(); <ide> }), 0); <ide> } <add> this.initSharing = function() { <add> this.sharedialog = elation.engine.sharing({append: document.body, client: this}); <add> this.sharebutton = elation.ui.button({classname: 'janusweb_sharing', label: 'Share'}); <add> elation.events.add(this.sharebutton, 'ui_button_click', elation.bind(this.sharedialog, this.sharedialog.showShareDialog)); <add> this.buttons.add('sharing', this.sharebutton); <add> } <ide> this.initWorld = function() { <ide> var things = this.world.load({ <ide> name: 'janusweb',
Java
apache-2.0
b12bdc315b6b0afa3a20ca7f9f56c7ad6cfaa038
0
mjanicek/rembulan,kroepke/luna
package net.sandius.rembulan.compiler.analysis; import net.sandius.rembulan.compiler.IRFunc; import net.sandius.rembulan.compiler.ir.*; import net.sandius.rembulan.compiler.util.CodeUtils; import net.sandius.rembulan.util.Check; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Stack; public class LivenessAnalyser { private final IRFunc fn; private final Map<IRNode, Set<Var>> varLiveIn; private final Map<IRNode, Set<AbstractVal>> valLiveIn; private Map<Label, Set<Var>> endVarLiveIn; private Map<Label, Set<AbstractVal>> endValLiveIn; private LivenessAnalyser(IRFunc fn) { this.fn = Check.notNull(fn); this.varLiveIn = new HashMap<>(); this.valLiveIn = new HashMap<>(); this.endVarLiveIn = new HashMap<>(); this.endValLiveIn = new HashMap<>(); } public static LivenessInfo computeLiveness(IRFunc fn) { LivenessAnalyser analyser = new LivenessAnalyser(fn); return analyser.analyse(); } public LivenessInfo analyse() { Code code = fn.code(); Map<Label, Set<Label>> in = CodeUtils.inLabels(code); // initialise { for (Label l : code.labels()) { endVarLiveIn.put(l, new HashSet<Var>()); endValLiveIn.put(l, new HashSet<AbstractVal>()); } Iterator<IRNode> ns = CodeUtils.nodeIterator(code); while (ns.hasNext()) { IRNode n = ns.next(); varLiveIn.put(n, new HashSet<Var>()); valLiveIn.put(n, new HashSet<AbstractVal>()); } } Stack<Label> open = new Stack<>(); // make sure we'll visit all labels at least once for (Label l : CodeUtils.labelsBreadthFirst(code)) { open.push(l); } while (!open.isEmpty()) { Label l = open.pop(); LivenessVisitor visitor = new LivenessVisitor( endVarLiveIn.get(l), endValLiveIn.get(l)); processBlock(visitor, code.block(l)); for (Label inl : in.get(l)) { boolean changed = false; changed |= endVarLiveIn.get(inl).addAll(visitor.currentVarLiveIn()); changed |= endValLiveIn.get(inl).addAll(visitor.currentValLiveIn()); if (changed) { if (open.contains(inl)) { open.remove(inl); } open.push(inl); } } } return result(); } private static void mergeLiveOut(Map<IRNode, LivenessInfo.Entry> entries, IRNode m, IRNode n) { LivenessInfo.Entry e_m = entries.get(m); LivenessInfo.Entry e_n = entries.get(n); e_m.outVar().addAll(e_n.inVar()); e_m.outVal().addAll(e_n.inVal()); } private LivenessInfo result() { Map<IRNode, LivenessInfo.Entry> entries = new HashMap<>(); // initialise Iterator<IRNode> nodeIterator = CodeUtils.nodeIterator(fn.code()); while (nodeIterator.hasNext()) { IRNode node = nodeIterator.next(); Set<Var> var_in = varLiveIn.get(node); Set<AbstractVal> val_in = valLiveIn.get(node); entries.put(node, new LivenessInfo.Entry(var_in, new HashSet<Var>(), val_in, new HashSet<AbstractVal>())); } // compute live-out from live-in Iterator<BasicBlock> blockIterator = fn.code().blockIterator(); while (blockIterator.hasNext()) { BasicBlock b = blockIterator.next(); // body for (int i = 0; i < b.body().size(); i++) { BodyNode m = b.body().get(i); IRNode n = i + 1 < b.body().size() ? b.body().get(i + 1) : b.end(); mergeLiveOut(entries, m, n); } // end BlockTermNode end = b.end(); LivenessInfo.Entry e_end = entries.get(end); for (Label nxt : end.nextLabels()) { BasicBlock nextBlock = fn.code().block(nxt); IRNode n = !nextBlock.body().isEmpty() ? nextBlock.body().get(0) : nextBlock.end(); mergeLiveOut(entries, end, n); } } return new LivenessInfo(entries); } private boolean processBlock(LivenessVisitor visitor, BasicBlock block) { // iterating backwards boolean changed = processNode(visitor, block.end()); for (int i = block.body().size() - 1; i >= 0; i--) { changed |= processNode(visitor, block.body().get(i)); } return changed; } private boolean processNode(LivenessVisitor visitor, IRNode node) { Check.notNull(node); final Set<Var> varLive_in = varLiveIn.get(node); final Set<AbstractVal> valLive_in = valLiveIn.get(node); node.accept(visitor); boolean varSame = visitor.currentVarLiveIn().equals(varLive_in); boolean valSame = visitor.currentValLiveIn().equals(valLive_in); if (!varSame) { varLive_in.clear(); varLive_in.addAll(visitor.currentVarLiveIn()); } if (!valSame) { valLive_in.clear(); valLive_in.addAll(visitor.currentValLiveIn()); } return !varSame || !valSame; } private class LivenessVisitor extends AbstractUseDefVisitor { private Set<Var> currentVarLiveIn; private Set<AbstractVal> currentValLiveIn; public LivenessVisitor(Set<Var> currentVarLiveIn, Set<AbstractVal> currentValLiveIn) { this.currentVarLiveIn = new HashSet<>(Check.notNull(currentVarLiveIn)); this.currentValLiveIn = new HashSet<>(Check.notNull(currentValLiveIn)); } public Set<Var> currentVarLiveIn() { return currentVarLiveIn; } public Set<AbstractVal> currentValLiveIn() { return currentValLiveIn; } @Override protected void def(Val v) { currentValLiveIn.remove(v); } @Override protected void use(Val v) { currentValLiveIn.add(v); } @Override protected void def(PhiVal pv) { currentValLiveIn.remove(pv); } @Override protected void use(PhiVal pv) { currentValLiveIn.add(pv); } @Override protected void def(Var v) { currentVarLiveIn.remove(v); } @Override protected void use(Var v) { currentVarLiveIn.add(v); } @Override protected void def(UpVar uv) { // no effect on liveness } @Override protected void use(UpVar uv) { // no effect on liveness } @Override public void visit(VarStore node) { use(node.src()); use(node.var()); // Note that this is a use, not a def } } }
rembulan-compiler/src/main/java/net/sandius/rembulan/compiler/analysis/LivenessAnalyser.java
package net.sandius.rembulan.compiler.analysis; import net.sandius.rembulan.compiler.IRFunc; import net.sandius.rembulan.compiler.ir.*; import net.sandius.rembulan.compiler.util.CodeUtils; import net.sandius.rembulan.util.Check; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Stack; public class LivenessAnalyser { private final IRFunc fn; private final Map<IRNode, Set<Var>> varLiveIn; private final Map<IRNode, Set<AbstractVal>> valLiveIn; private Map<Label, Set<Var>> endVarLiveIn; private Map<Label, Set<AbstractVal>> endValLiveIn; private LivenessAnalyser(IRFunc fn) { this.fn = Check.notNull(fn); this.varLiveIn = new HashMap<>(); this.valLiveIn = new HashMap<>(); this.endVarLiveIn = new HashMap<>(); this.endValLiveIn = new HashMap<>(); } public static LivenessInfo computeLiveness(IRFunc fn) { LivenessAnalyser analyser = new LivenessAnalyser(fn); return analyser.analyse(); } public LivenessInfo analyse() { Code code = fn.code(); Map<Label, Set<Label>> in = CodeUtils.inLabels(code); // initialise { for (Label l : code.labels()) { endVarLiveIn.put(l, new HashSet<Var>()); endValLiveIn.put(l, new HashSet<AbstractVal>()); } Iterator<IRNode> ns = CodeUtils.nodeIterator(code); while (ns.hasNext()) { IRNode n = ns.next(); varLiveIn.put(n, new HashSet<Var>()); valLiveIn.put(n, new HashSet<AbstractVal>()); } } Stack<Label> open = new Stack<>(); // make sure we'll visit all labels at least once for (Label l : CodeUtils.labelsBreadthFirst(code)) { open.push(l); } while (!open.isEmpty()) { Label l = open.pop(); LivenessVisitor visitor = new LivenessVisitor( endVarLiveIn.get(l), endValLiveIn.get(l)); processBlock(visitor, code.block(l)); for (Label inl : in.get(l)) { boolean changed = false; changed |= endVarLiveIn.get(inl).addAll(visitor.currentVarLiveIn()); changed |= endValLiveIn.get(inl).addAll(visitor.currentValLiveIn()); if (changed) { if (open.contains(inl)) { open.remove(inl); } open.push(inl); } } } return result(); } private static void mergeLiveOut(Map<IRNode, LivenessInfo.Entry> entries, IRNode m, IRNode n) { LivenessInfo.Entry e_m = entries.get(m); LivenessInfo.Entry e_n = entries.get(n); e_m.outVar().addAll(e_n.inVar()); e_m.outVal().addAll(e_n.inVal()); } private LivenessInfo result() { Map<IRNode, Set<Var>> varLiveOut = new HashMap<>(); Map<IRNode, Set<AbstractVal>> valLiveOut = new HashMap<>(); Map<IRNode, LivenessInfo.Entry> entries = new HashMap<>(); // initialise Iterator<IRNode> nodeIterator = CodeUtils.nodeIterator(fn.code()); while (nodeIterator.hasNext()) { IRNode node = nodeIterator.next(); Set<Var> var_in = varLiveIn.get(node); Set<AbstractVal> val_in = valLiveIn.get(node); entries.put(node, new LivenessInfo.Entry(var_in, new HashSet<Var>(), val_in, new HashSet<AbstractVal>())); } // compute live-out from live-in Iterator<BasicBlock> blockIterator = fn.code().blockIterator(); while (blockIterator.hasNext()) { BasicBlock b = blockIterator.next(); // body for (int i = 0; i < b.body().size(); i++) { BodyNode m = b.body().get(i); IRNode n = i + 1 < b.body().size() ? b.body().get(i + 1) : b.end(); mergeLiveOut(entries, m, n); } // end BlockTermNode end = b.end(); LivenessInfo.Entry e_end = entries.get(end); for (Label nxt : end.nextLabels()) { BasicBlock nextBlock = fn.code().block(nxt); IRNode n = !nextBlock.body().isEmpty() ? nextBlock.body().get(0) : nextBlock.end(); mergeLiveOut(entries, end, n); } } return new LivenessInfo(entries); } private boolean processBlock(LivenessVisitor visitor, BasicBlock block) { // iterating backwards boolean changed = processNode(visitor, block.end()); for (int i = block.body().size() - 1; i >= 0; i--) { changed |= processNode(visitor, block.body().get(i)); } return changed; } private boolean processNode(LivenessVisitor visitor, IRNode node) { Check.notNull(node); final Set<Var> varLive_in = varLiveIn.get(node); final Set<AbstractVal> valLive_in = valLiveIn.get(node); node.accept(visitor); boolean varSame = visitor.currentVarLiveIn().equals(varLive_in); boolean valSame = visitor.currentValLiveIn().equals(valLive_in); if (!varSame) { varLive_in.clear(); varLive_in.addAll(visitor.currentVarLiveIn()); } if (!valSame) { valLive_in.clear(); valLive_in.addAll(visitor.currentValLiveIn()); } return !varSame || !valSame; } private class LivenessVisitor extends AbstractUseDefVisitor { private Set<Var> currentVarLiveIn; private Set<AbstractVal> currentValLiveIn; public LivenessVisitor(Set<Var> currentVarLiveIn, Set<AbstractVal> currentValLiveIn) { this.currentVarLiveIn = new HashSet<>(Check.notNull(currentVarLiveIn)); this.currentValLiveIn = new HashSet<>(Check.notNull(currentValLiveIn)); } public Set<Var> currentVarLiveIn() { return currentVarLiveIn; } public Set<AbstractVal> currentValLiveIn() { return currentValLiveIn; } @Override protected void def(Val v) { currentValLiveIn.remove(v); } @Override protected void use(Val v) { currentValLiveIn.add(v); } @Override protected void def(PhiVal pv) { currentValLiveIn.remove(pv); } @Override protected void use(PhiVal pv) { currentValLiveIn.add(pv); } @Override protected void def(Var v) { currentVarLiveIn.remove(v); } @Override protected void use(Var v) { currentVarLiveIn.add(v); } @Override protected void def(UpVar uv) { // no effect on liveness } @Override protected void use(UpVar uv) { // no effect on liveness } @Override public void visit(VarStore node) { use(node.src()); use(node.var()); // Note that this is a use, not a def } } }
Removing unused local variables.
rembulan-compiler/src/main/java/net/sandius/rembulan/compiler/analysis/LivenessAnalyser.java
Removing unused local variables.
<ide><path>embulan-compiler/src/main/java/net/sandius/rembulan/compiler/analysis/LivenessAnalyser.java <ide> } <ide> <ide> private LivenessInfo result() { <del> Map<IRNode, Set<Var>> varLiveOut = new HashMap<>(); <del> Map<IRNode, Set<AbstractVal>> valLiveOut = new HashMap<>(); <del> <ide> Map<IRNode, LivenessInfo.Entry> entries = new HashMap<>(); <ide> <ide> // initialise
Java
apache-2.0
d821c26838afa30ffc2711af980a140bc9b9dc8e
0
tmaret/sling,wimsymons/sling,sdmcraft/sling,ieb/sling,klcodanr/sling,trekawek/sling,mmanski/sling,anchela/sling,tteofili/sling,Nimco/sling,mcdan/sling,tteofili/sling,awadheshv/sling,vladbailescu/sling,tteofili/sling,klcodanr/sling,awadheshv/sling,tyge68/sling,mcdan/sling,ffromm/sling,Sivaramvt/sling,trekawek/sling,cleliameneghin/sling,codders/k2-sling-fork,anchela/sling,plutext/sling,dulvac/sling,SylvesterAbreu/sling,tmaret/sling,ieb/sling,mmanski/sling,trekawek/sling,wimsymons/sling,sdmcraft/sling,Sivaramvt/sling,plutext/sling,JEBailey/sling,nleite/sling,headwirecom/sling,roele/sling,JEBailey/sling,mikibrv/sling,anchela/sling,plutext/sling,SylvesterAbreu/sling,tmaret/sling,headwirecom/sling,ist-dresden/sling,SylvesterAbreu/sling,dulvac/sling,ist-dresden/sling,JEBailey/sling,cleliameneghin/sling,JEBailey/sling,gutsy/sling,Nimco/sling,tteofili/sling,ffromm/sling,tmaret/sling,cleliameneghin/sling,klcodanr/sling,mmanski/sling,cleliameneghin/sling,headwirecom/sling,mmanski/sling,ffromm/sling,SylvesterAbreu/sling,sdmcraft/sling,labertasch/sling,dulvac/sling,vladbailescu/sling,tmaret/sling,vladbailescu/sling,anchela/sling,ffromm/sling,ffromm/sling,tyge68/sling,sdmcraft/sling,ffromm/sling,SylvesterAbreu/sling,gutsy/sling,roele/sling,plutext/sling,labertasch/sling,mcdan/sling,trekawek/sling,sdmcraft/sling,trekawek/sling,Sivaramvt/sling,vladbailescu/sling,mcdan/sling,mikibrv/sling,headwirecom/sling,trekawek/sling,mikibrv/sling,mmanski/sling,plutext/sling,codders/k2-sling-fork,dulvac/sling,ist-dresden/sling,awadheshv/sling,tteofili/sling,awadheshv/sling,vladbailescu/sling,ieb/sling,Nimco/sling,Sivaramvt/sling,anchela/sling,nleite/sling,ieb/sling,Nimco/sling,mikibrv/sling,mmanski/sling,nleite/sling,dulvac/sling,labertasch/sling,klcodanr/sling,Sivaramvt/sling,ieb/sling,plutext/sling,Sivaramvt/sling,mcdan/sling,JEBailey/sling,Nimco/sling,gutsy/sling,sdmcraft/sling,Nimco/sling,roele/sling,codders/k2-sling-fork,wimsymons/sling,SylvesterAbreu/sling,cleliameneghin/sling,wimsymons/sling,tyge68/sling,ieb/sling,nleite/sling,klcodanr/sling,labertasch/sling,awadheshv/sling,tteofili/sling,mikibrv/sling,nleite/sling,roele/sling,klcodanr/sling,ist-dresden/sling,ist-dresden/sling,tyge68/sling,tyge68/sling,roele/sling,mikibrv/sling,gutsy/sling,nleite/sling,dulvac/sling,tyge68/sling,wimsymons/sling,gutsy/sling,awadheshv/sling,mcdan/sling,headwirecom/sling,wimsymons/sling,gutsy/sling,labertasch/sling
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.launchpad.webapp.integrationtest; import org.apache.sling.ujax.UjaxPostServlet; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** Test the rendering of JCR Properties, directly addressed by URLs. * See SLING-133 */ public class PropertyRenderingTest extends RenderingTestBase { private String slingResourceType; @Override protected void setUp() throws Exception { super.setUp(); // set test values testText = "This is a test " + System.currentTimeMillis(); slingResourceType = getClass().getName(); // create the test node, under a path that's specific to this class to allow collisions final String url = HTTP_BASE_URL + "/" + getClass().getSimpleName() + "/" + System.currentTimeMillis() + UjaxPostServlet.DEFAULT_CREATE_SUFFIX; final Map<String,String> props = new HashMap<String,String>(); props.put("sling:resourceType", slingResourceType); props.put("text", testText); displayUrl = testClient.createNode(url, props); } public void testNodeAccess() throws IOException { final String json = getContent(displayUrl + ".json", CONTENT_TYPE_JSON); assertJavascript(testText, json, "out.println(data.text)"); } public void testTextJson() throws IOException { final String json = getContent(displayUrl + "/text.json", CONTENT_TYPE_JSON); assertEquals("{\"text\":\"" + testText + "\"}",json); } public void testTextHtml() throws IOException { final String data = getContent(displayUrl + "/text.html", CONTENT_TYPE_HTML); assertEquals(testText, data); } public void testTextTxt() throws IOException { final String data = getContent(displayUrl + "/text.txt", CONTENT_TYPE_PLAIN); assertEquals(testText, data); } public void testTextNoExt() throws IOException { final String data = getContent(displayUrl + "/text", null); assertEquals(testText, data); } public void testResourceTypeNoExt() throws IOException { final String data = getContent(displayUrl + "/sling:resourceType", null); assertEquals(slingResourceType, data); } }
launchpad/launchpad-webapp/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/PropertyRenderingTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.launchpad.webapp.integrationtest; import org.apache.sling.ujax.UjaxPostServlet; import java.io.IOException; import java.util.HashMap; import java.util.Map; /** Test the rendering of JCR Properties, directly addressed by URLs. * See SLING-133 */ public class PropertyRenderingTest extends RenderingTestBase { private String slingResourceType; @Override protected void setUp() throws Exception { super.setUp(); // set test values testText = "This is a test " + System.currentTimeMillis(); slingResourceType = getClass().getName(); // create the test node, under a path that's specific to this class to allow collisions final String url = HTTP_BASE_URL + "/" + getClass().getSimpleName() + "/" + System.currentTimeMillis() + UjaxPostServlet.DEFAULT_CREATE_SUFFIX; final Map<String,String> props = new HashMap<String,String>(); props.put("sling:resourceType", slingResourceType); props.put("text", testText); displayUrl = testClient.createNode(url, props); } public void testNodeAccess() throws IOException { final String json = getContent(displayUrl + ".json", CONTENT_TYPE_JSON); assertJavascript(testText, json, "out.println(data.text)"); } public void testTextJson() throws IOException { final String json = getContent(displayUrl + "/text.json", CONTENT_TYPE_JSON); assertEquals("{\"text\":\"" + testText + "\"}",json); } public void testTextHtml() throws IOException { final String data = getContent(displayUrl + "/text.html", CONTENT_TYPE_HTML); assertEquals(testText, data); } public void testTextTxt() throws IOException { final String data = getContent(displayUrl + "/text.txt", CONTENT_TYPE_PLAIN); assertEquals(testText, data); } public void testTextNoExt() throws IOException { final String data = getContent(displayUrl + "/text", CONTENT_TYPE_PLAIN); assertEquals(testText, data); } public void testResourceTypeNoExt() throws IOException { final String data = getContent(displayUrl + "/sling:resourceType", CONTENT_TYPE_PLAIN); assertEquals(slingResourceType, data); } }
Do not expect any content type on a request without extension - strange is, that this seems to have worked until now .... git-svn-id: c3eb811ccca381e673aa62a65336ec26649ed58c@631991 13f79535-47bb-0310-9956-ffa450edef68
launchpad/launchpad-webapp/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/PropertyRenderingTest.java
Do not expect any content type on a request without extension - strange is, that this seems to have worked until now ....
<ide><path>aunchpad/launchpad-webapp/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/PropertyRenderingTest.java <ide> } <ide> <ide> public void testTextNoExt() throws IOException { <del> final String data = getContent(displayUrl + "/text", CONTENT_TYPE_PLAIN); <add> final String data = getContent(displayUrl + "/text", null); <ide> assertEquals(testText, data); <ide> } <ide> <ide> public void testResourceTypeNoExt() throws IOException { <del> final String data = getContent(displayUrl + "/sling:resourceType", CONTENT_TYPE_PLAIN); <add> final String data = getContent(displayUrl + "/sling:resourceType", null); <ide> assertEquals(slingResourceType, data); <ide> } <ide> }
JavaScript
mit
f77ef400718b32cd025f9aea56397a530973897a
0
briggySmalls/late-train-mate,briggySmalls/late-train-mate,briggySmalls/late-train-mate
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { configuration = { basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, files: [ { pattern: './src/test.ts', watched: false } ], preprocessors: { './src/test.ts': ['@angular/cli'] }, mime: { 'text/x-typescript': ['ts','tsx'] }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: config.angularCli && config.angularCli.codeCoverage ? ['progress', 'coverage-istanbul'] : ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, customLaunchers: { ChromeHeadless: { base: 'Chrome', flags: [ '--headless', '--disable-gpu', // Without a remote debugging port, Google Chrome exits immediately. '--remote-debugging-port=9222', ], } }, }; // Update browser configuration for Travis CI if (process.env.TRAVIS) { configuration.browsers = ['ChromeHeadless']; } config.set(configuration); };
karma.conf.js
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { configuration = { basePath: '', frameworks: ['jasmine', '@angular/cli'], plugins: [ require('karma-jasmine'), require('karma-chrome-launcher'), require('karma-jasmine-html-reporter'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], client:{ clearContext: false // leave Jasmine Spec Runner output visible in browser }, files: [ { pattern: './src/test.ts', watched: false } ], preprocessors: { './src/test.ts': ['@angular/cli'] }, mime: { 'text/x-typescript': ['ts','tsx'] }, coverageIstanbulReporter: { reports: [ 'html', 'lcovonly' ], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: config.angularCli && config.angularCli.codeCoverage ? ['progress', 'coverage-istanbul'] : ['progress', 'kjhtml'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false, customLaunchers: { Chrome_travis_ci: { base: 'Chrome', flags: ['--no-sandbox'] } }, }; // Update browser configuration for Travis CI if (process.env.TRAVIS) { configuration.browsers = ['Chrome_travis_ci']; } config.set(configuration); };
Use headless chrome for travis?
karma.conf.js
Use headless chrome for travis?
<ide><path>arma.conf.js <ide> browsers: ['Chrome'], <ide> singleRun: false, <ide> customLaunchers: { <del> Chrome_travis_ci: { <del> base: 'Chrome', <del> flags: ['--no-sandbox'] <add> ChromeHeadless: { <add> base: 'Chrome', <add> flags: [ <add> '--headless', <add> '--disable-gpu', <add> // Without a remote debugging port, Google Chrome exits immediately. <add> '--remote-debugging-port=9222', <add> ], <ide> } <ide> }, <ide> }; <ide> <ide> // Update browser configuration for Travis CI <ide> if (process.env.TRAVIS) { <del> configuration.browsers = ['Chrome_travis_ci']; <add> configuration.browsers = ['ChromeHeadless']; <ide> } <ide> <ide> config.set(configuration);
Java
mit
70d191f0e5c05fe8f1cb3c4bf3f4f512f0dd434b
0
Doist/TodoistModels,Doist/TodoistPojos
package com.todoist.model; public class BaseReminder extends TodoistObjectWithId { public static final String TYPE_ABSOLUTE = "absolute"; public static final String TYPE_RELATIVE = "relative"; public static final String TYPE_LOCATION = "location"; public static final String SERVICE_EMAIL = "email"; public static final String SERVICE_PUSH = "push"; public static final String SERVICE_MOBILE = "mobile"; public static final String SERVICE_NO_DEFAULT = "no_default"; public static final String SERVICE_OTHER = "other"; public static final String LOC_TRIGGER_ON_ENTER = "on_enter"; public static final String LOC_TRIGGER_ON_LEAVE = "on_leave"; private String type; /** Exclusive to reminders of type {@link #TYPE_ABSOLUTE}. */ private String dateString; /** Exclusive to reminders of type {@link #TYPE_ABSOLUTE}. */ private Long dueDate; /** Exclusive to reminders of type {@link #TYPE_RELATIVE}. */ private Integer minuteOffset; /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ private String name; /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ private Double locLat; /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ private Double locLong; /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ private Integer radius; /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ private String locTrigger; private String service; private Long notifyUid; private long itemId; public BaseReminder(long id, String type, String dateString, Long dueDate, Integer minuteOffset, String name, Double locLat, Double locLong, Integer radius, String locTrigger, String service, Long notifyUid, long itemId, boolean deleted) { super(id, deleted); this.type = type; this.dateString = dateString; this.dueDate = dueDate; this.minuteOffset = minuteOffset; this.name = name; this.locLat = locLat; this.locLong = locLong; this.radius = radius; this.locTrigger = locTrigger; this.service = service; this.notifyUid = notifyUid; this.itemId = itemId; } public BaseReminder(long id, String type, String dateString, Long dueDate, Integer minuteOffset, String name, Double locLat, Double locLong, Integer radius, String locTrigger, String service, Long notifyUid, long itemId) { this(id, type, dateString, dueDate, minuteOffset, name, locLat, locLong, radius, locTrigger, service, notifyUid, itemId, false); } public String getType() { return type; } public boolean isAbsolute() { return TYPE_ABSOLUTE.equals(type); } public boolean isRelative() { return TYPE_RELATIVE.equals(type); } public boolean isLocation() { return TYPE_LOCATION.equals(type); } public void setType(String type) { this.type = type; } public String getDateString() { return dateString; } public void setDateString(String dateString) { this.dateString = dateString; } public Long getDueDate() { return dueDate; } public void setDueDate(Long dueDate) { this.dueDate = dueDate; } public Integer getMinuteOffset() { return minuteOffset; } public void setMinuteOffset(Integer minuteOffset) { this.minuteOffset = minuteOffset; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getLocLat() { return locLat; } public void setLocLat(Double locLat) { this.locLat = locLat; } public Double getLocLong() { return locLong; } public void setLocLong(Double locLong) { this.locLong = locLong; } public Integer getRadius() { return radius; } public void setRadius(Integer radius) { this.radius = radius; } public String getLocTrigger() { return locTrigger; } public void setLocTrigger(String locTrigger) { this.locTrigger = locTrigger; } public String getService() { return service; } public void setService(String service) { this.service = service; } public Long getNotifyUid() { return notifyUid; } public void setNotifyUid(Long notifyUid) { this.notifyUid = notifyUid; } public long getItemId() { return itemId; } public void setItemId(long itemId) { this.itemId = itemId; } }
src/main/java/com/todoist/model/BaseReminder.java
package com.todoist.model; public class BaseReminder extends TodoistObjectWithId { public static final String TYPE_ABSOLUTE = "absolute"; public static final String TYPE_RELATIVE = "relative"; public static final String TYPE_LOCATION = "location"; public static final String SERVICE_EMAIL = "email"; public static final String SERVICE_PUSH = "push"; public static final String SERVICE_MOBILE = "mobile"; public static final String SERVICE_NO_DEFAULT = "no_default"; public static final String SERVICE_OTHER = "other"; public static final String LOC_TRIGGER_ON_ENTER = "on_enter"; public static final String LOC_TRIGGER_ON_LEAVE = "on_leave"; private String type; /** Exclusive to reminders of type {@link #TYPE_ABSOLUTE}. */ private String dateString; /** Exclusive to reminders of type {@link #TYPE_ABSOLUTE}. */ private String dueDate; /** Exclusive to reminders of type {@link #TYPE_RELATIVE}. */ private Integer minuteOffset; /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ private String name; /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ private Double locLat; /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ private Double locLong; /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ private Integer radius; /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ private String locTrigger; private Long notifyUid; private long itemId; public BaseReminder(long id, String type, String dateString, String dueDate, Integer minuteOffset, String name, Double locLat, Double locLong, Integer radius, String locTrigger, Long notifyUid, long itemId, boolean deleted) { super(id, deleted); this.type = type; this.dateString = dateString; this.dueDate = dueDate; this.minuteOffset = minuteOffset; this.name = name; this.locLat = locLat; this.locLong = locLong; this.radius = radius; this.locTrigger = locTrigger; this.notifyUid = notifyUid; this.itemId = itemId; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getDateString() { return dateString; } public void setDateString(String dateString) { this.dateString = dateString; } public String getDueDate() { return dueDate; } public void setDueDate(String dueDate) { this.dueDate = dueDate; } public Integer getMinuteOffset() { return minuteOffset; } public void setMinuteOffset(Integer minuteOffset) { this.minuteOffset = minuteOffset; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getLocLat() { return locLat; } public void setLocLat(Double locLat) { this.locLat = locLat; } public Double getLocLong() { return locLong; } public void setLocLong(Double locLong) { this.locLong = locLong; } public Integer getRadius() { return radius; } public void setRadius(Integer radius) { this.radius = radius; } public String getLocTrigger() { return locTrigger; } public void setLocTrigger(String locTrigger) { this.locTrigger = locTrigger; } public Long getNotifyUid() { return notifyUid; } public void setNotifyUid(Long notifyUid) { this.notifyUid = notifyUid; } public long getItemId() { return itemId; } }
Fix dueDate type, add service in BaseReminder
src/main/java/com/todoist/model/BaseReminder.java
Fix dueDate type, add service in BaseReminder
<ide><path>rc/main/java/com/todoist/model/BaseReminder.java <ide> /** Exclusive to reminders of type {@link #TYPE_ABSOLUTE}. */ <ide> private String dateString; <ide> /** Exclusive to reminders of type {@link #TYPE_ABSOLUTE}. */ <del> private String dueDate; <add> private Long dueDate; <ide> /** Exclusive to reminders of type {@link #TYPE_RELATIVE}. */ <ide> private Integer minuteOffset; <ide> /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ <ide> private Integer radius; <ide> /** Exclusive to reminders of type {@link #TYPE_LOCATION}. */ <ide> private String locTrigger; <add> private String service; <ide> private Long notifyUid; <ide> private long itemId; <ide> <del> public BaseReminder(long id, String type, String dateString, <del> String dueDate, Integer minuteOffset, String name, Double locLat, Double locLong, <del> Integer radius, String locTrigger, Long notifyUid, long itemId, boolean deleted) { <add> public BaseReminder(long id, String type, <add> String dateString, Long dueDate, <add> Integer minuteOffset, <add> String name, Double locLat, Double locLong, Integer radius, String locTrigger, <add> String service, Long notifyUid, long itemId, boolean deleted) { <ide> super(id, deleted); <ide> this.type = type; <ide> this.dateString = dateString; <ide> this.locLong = locLong; <ide> this.radius = radius; <ide> this.locTrigger = locTrigger; <add> this.service = service; <ide> this.notifyUid = notifyUid; <ide> this.itemId = itemId; <ide> } <ide> <add> public BaseReminder(long id, String type, <add> String dateString, Long dueDate, <add> Integer minuteOffset, <add> String name, Double locLat, Double locLong, Integer radius, String locTrigger, <add> String service, Long notifyUid, long itemId) { <add> this(id, type, dateString, dueDate, minuteOffset, name, locLat, locLong, radius, locTrigger, service, notifyUid, <add> itemId, false); <add> } <add> <ide> public String getType() { <ide> return type; <add> } <add> <add> public boolean isAbsolute() { <add> return TYPE_ABSOLUTE.equals(type); <add> } <add> <add> public boolean isRelative() { <add> return TYPE_RELATIVE.equals(type); <add> } <add> <add> public boolean isLocation() { <add> return TYPE_LOCATION.equals(type); <ide> } <ide> <ide> public void setType(String type) { <ide> this.dateString = dateString; <ide> } <ide> <del> public String getDueDate() { <add> public Long getDueDate() { <ide> return dueDate; <ide> } <ide> <del> public void setDueDate(String dueDate) { <add> public void setDueDate(Long dueDate) { <ide> this.dueDate = dueDate; <ide> } <ide> <ide> this.locTrigger = locTrigger; <ide> } <ide> <add> public String getService() { <add> return service; <add> } <add> <add> public void setService(String service) { <add> this.service = service; <add> } <add> <ide> public Long getNotifyUid() { <ide> return notifyUid; <ide> } <ide> public long getItemId() { <ide> return itemId; <ide> } <add> <add> public void setItemId(long itemId) { <add> this.itemId = itemId; <add> } <ide> }
Java
bsd-3-clause
5ea42099549cd563bffb2aebeb068c77e5cfdfcd
0
MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2
package org.carrot2.workbench.editors.impl; import java.io.File; import java.net.*; import org.carrot2.util.resource.*; import org.carrot2.workbench.core.helpers.DisposeBin; import org.carrot2.workbench.core.helpers.GUIFactory; import org.carrot2.workbench.editors.*; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; /** * Editor for attributes that are of {@link Resource} type. */ public class ResourceEditor extends AttributeEditorAdapter { /* * Disposal of resources. */ private DisposeBin disposeBin = new DisposeBin(); /** * Resource information string. */ private Text resourceInfo; /** * The actual resource (most recent valid value or <code>null</code>). */ private Resource resource = null; /* * Event cycle avoidance. */ private boolean updating; /* * Validator for URIs. */ private final static IInputValidator validatorURI = new IInputValidator() { public String isValid(String text) { try { URI validURI = new URI(text); if (validURI.getScheme() == null) { throw new URISyntaxException(text, "Empty scheme."); } } catch (URISyntaxException e) { return "Not a valid URI"; } return null; } }; /* * */ public ResourceEditor() { super(new AttributeEditorInfo(1, false)); } /* * */ @Override public void createEditor(Composite parent, int gridColumns) { final Composite holder = new Composite(parent, SWT.NONE); holder.setLayoutData( GUIFactory.editorGridData() .grab(true, false) .span(gridColumns, 1).create()); GridLayout gl = GUIFactory.zeroMarginGridLayout(); gl.numColumns = 3; gl.horizontalSpacing = 3; holder.setLayout(gl); createTextBox(holder); createFileButton(holder); createUrlButton(holder); } /* * */ private void createTextBox(Composite holder) { this.resourceInfo = new Text(holder, SWT.READ_ONLY | SWT.NO_FOCUS | SWT.BORDER | SWT.SINGLE); final GridData gd = GridDataFactory.fillDefaults() .grab(true, false) .hint(100, SWT.DEFAULT) .create(); resourceInfo.setLayoutData(gd); } /* * */ private void createFileButton(Composite holder) { final Image image = EditorsPlugin.getImageDescriptor("icons/open_folder.gif").createImage(); disposeBin.add(image); final Button button = new Button(holder, SWT.PUSH | SWT.CENTER); button.setImage(image); button.setLayoutData(GridDataFactory.fillDefaults().create()); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { openFileResourceDialog(); } }); } /* * */ private void openFileResourceDialog() { final FileDialog dialog = new FileDialog(this.resourceInfo.getShell()); dialog.setFilterExtensions(new String [] { "*.xml;*.XML", "*.*" }); dialog.setFilterNames(new String [] { "XML files", "All" }); if (this.resource != null && resource instanceof FileResource) { dialog.setFileName(((FileResource) resource).file.getAbsolutePath()); } else { // In case we can't restore last file, refer to global last key. dialog.setFileName( EditorsPlugin.getDefault().getPreferenceStore().getString( EditorsPluginConstants.PREF_LAST_SELECTED_FILE)); } final String path = dialog.open(); if (path != null) { final File file = new File(path); EditorsPlugin.getDefault().getPreferenceStore().setValue( EditorsPluginConstants.PREF_LAST_SELECTED_FILE, file.getAbsolutePath()); setValue(new FileResource(file)); } } /* * */ private void createUrlButton(Composite holder) { final Image image = EditorsPlugin.getImageDescriptor("icons/open_url.gif").createImage(); disposeBin.add(image); final Button button = new Button(holder, SWT.PUSH | SWT.CENTER); button.setImage(image); button.setLayoutData(GridDataFactory.fillDefaults().create()); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { openURLResourceDialog(); } }); } /* * */ private void openURLResourceDialog() { String previous = ""; if (resource != null && resource instanceof URLResource) { previous = ((URLResource) resource).url.toExternalForm(); } final InputDialog dialog = new InputDialog(resourceInfo.getShell(), "Enter resource URL", "Enter resource URL", previous, validatorURI); if (dialog.open() == IDialogConstants.OK_ID) { try { setValue(new URLResource(new URL(dialog.getValue()))); } catch (MalformedURLException e) { // Simply skip, shouldn't happen. } } } /* * */ @Override public void setValue(Object newValue) { if (updating || newValue == resource) { return; } if (resource != null && resource.equals(newValue)) { return; } if (!(newValue instanceof Resource)) { return; } updating = true; this.resource = (Resource) newValue; this.resourceInfo.setText( resource == null ? "" : resource.toString()); fireAttributeChange(new AttributeChangedEvent(this)); updating = false; } /* * */ @Override public Object getValue() { return resource; } /* * */ @Override public void dispose() { disposeBin.dispose(); } }
workbench/org.carrot2.workbench.editors/src/org/carrot2/workbench/editors/impl/ResourceEditor.java
package org.carrot2.workbench.editors.impl; import java.io.File; import java.net.*; import org.carrot2.util.resource.*; import org.carrot2.workbench.core.helpers.DisposeBin; import org.carrot2.workbench.core.helpers.GUIFactory; import org.carrot2.workbench.editors.*; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.layout.GridDataFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; /** * Editor for attributes that are of {@link Resource} type. */ public class ResourceEditor extends AttributeEditorAdapter { /* * Disposal of resources. */ private DisposeBin disposeBin = new DisposeBin(); /** * Resource information string. */ private Text resourceInfo; /** * The actual resource (most recent valid value or <code>null</code>). */ private Resource resource = null; /* * Event cycle avoidance. */ private boolean updating; /* * Validator for URIs. */ private final static IInputValidator validatorURI = new IInputValidator() { public String isValid(String text) { try { URI validURI = new URI(text); if (validURI.getScheme() == null) { throw new URISyntaxException(text, "Empty scheme."); } } catch (URISyntaxException e) { return "Not a valid URI"; } return null; } }; /* * */ public ResourceEditor() { super(new AttributeEditorInfo(1, false)); } /* * */ @Override public void createEditor(Composite parent, int gridColumns) { final Composite holder = new Composite(parent, SWT.NONE); holder.setLayoutData( GUIFactory.editorGridData() .grab(true, false) .span(gridColumns, 1).create()); GridLayout gl = GUIFactory.zeroMarginGridLayout(); gl.numColumns = 3; gl.horizontalSpacing = 3; holder.setLayout(gl); createTextBox(holder); createFileButton(holder); createUrlButton(holder); } /* * */ private void createTextBox(Composite holder) { this.resourceInfo = new Text(holder, SWT.READ_ONLY | SWT.NO_FOCUS | SWT.BORDER | SWT.SINGLE); resourceInfo.setBackground( resourceInfo.getDisplay().getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND)); final GridData gd = GridDataFactory.fillDefaults() .grab(true, false) .hint(100, SWT.DEFAULT) .create(); resourceInfo.setLayoutData(gd); } /* * */ private void createFileButton(Composite holder) { final Image image = EditorsPlugin.getImageDescriptor("icons/open_folder.gif").createImage(); disposeBin.add(image); final Button button = new Button(holder, SWT.PUSH | SWT.CENTER); button.setImage(image); button.setLayoutData(GridDataFactory.fillDefaults().create()); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { openFileResourceDialog(); } }); } /* * */ private void openFileResourceDialog() { final FileDialog dialog = new FileDialog(this.resourceInfo.getShell()); dialog.setFilterExtensions(new String [] { "*.xml;*.XML", "*.*" }); dialog.setFilterNames(new String [] { "XML files", "All" }); if (this.resource != null && resource instanceof FileResource) { dialog.setFileName(((FileResource) resource).file.getAbsolutePath()); } else { // In case we can't restore last file, refer to global last key. dialog.setFileName( EditorsPlugin.getDefault().getPreferenceStore().getString( EditorsPluginConstants.PREF_LAST_SELECTED_FILE)); } final String path = dialog.open(); if (path != null) { final File file = new File(path); EditorsPlugin.getDefault().getPreferenceStore().setValue( EditorsPluginConstants.PREF_LAST_SELECTED_FILE, file.getAbsolutePath()); setValue(new FileResource(file)); } } /* * */ private void createUrlButton(Composite holder) { final Image image = EditorsPlugin.getImageDescriptor("icons/open_url.gif").createImage(); disposeBin.add(image); final Button button = new Button(holder, SWT.PUSH | SWT.CENTER); button.setImage(image); button.setLayoutData(GridDataFactory.fillDefaults().create()); button.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { openURLResourceDialog(); } }); } /* * */ private void openURLResourceDialog() { String previous = ""; if (resource != null && resource instanceof URLResource) { previous = ((URLResource) resource).url.toExternalForm(); } final InputDialog dialog = new InputDialog(resourceInfo.getShell(), "Enter resource URL", "Enter resource URL", previous, validatorURI); if (dialog.open() == IDialogConstants.OK_ID) { try { setValue(new URLResource(new URL(dialog.getValue()))); } catch (MalformedURLException e) { // Simply skip, shouldn't happen. } } } /* * */ @Override public void setValue(Object newValue) { if (updating || newValue == resource) { return; } if (resource != null && resource.equals(newValue)) { return; } if (!(newValue instanceof Resource)) { return; } updating = true; this.resource = (Resource) newValue; this.resourceInfo.setText( resource == null ? "" : resource.toString()); fireAttributeChange(new AttributeChangedEvent(this)); updating = false; } /* * */ @Override public Object getValue() { return resource; } /* * */ @Override public void dispose() { disposeBin.dispose(); } }
Removed gray border (works on Windows). git-svn-id: f05d591df75ba7f0993a7f82cc16d06976130918@2802 7ff1d41c-760d-0410-a7ff-a3a56f310b35
workbench/org.carrot2.workbench.editors/src/org/carrot2/workbench/editors/impl/ResourceEditor.java
Removed gray border (works on Windows).
<ide><path>orkbench/org.carrot2.workbench.editors/src/org/carrot2/workbench/editors/impl/ResourceEditor.java <ide> { <ide> this.resourceInfo = new Text(holder, SWT.READ_ONLY | SWT.NO_FOCUS | SWT.BORDER | SWT.SINGLE); <ide> <del> resourceInfo.setBackground( <del> resourceInfo.getDisplay().getSystemColor(SWT.COLOR_TITLE_INACTIVE_BACKGROUND)); <del> <ide> final GridData gd = GridDataFactory.fillDefaults() <ide> .grab(true, false) <ide> .hint(100, SWT.DEFAULT)
Java
mit
6d5fff9c7323518066623cc79dd87b38a2736869
0
AmadouSallah/Programming-Interview-Questions,AmadouSallah/Programming-Interview-Questions
/* Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. Follow up: What if the input array is sorted in ascending order? */ import java.util.HashMap; import java.util.Map; public class twoSum { // O(n^2) runtime and O(n) space complexities public static int[] twoSum(int[] nums, int target) { if (nums == null || nums.length < 2) return new int[0]; int n = nums.length; for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { if (nums[i] + nums[j] == target) return new int[] {i, j}; } } return new int[0]; } // O(n) runtime and O(n) space complexities public static int[] twoSumII(int[] nums, int target) { if (nums == null || nums.length < 2) return new int[0]; int n = nums.length; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < n; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) return new int[] {map.get(complement), i}; else map.put(nums[i], i); } return new int[0]; } // Follow up: What if input array is sorted in ascending order (Leetcode Problem 167) // O(n*long(n)) runtime and O(1) space complexities public static int[] twoSumIII(int[] nums, int target) { if (nums == null || nums.length < 2) return new int[0]; int n = nums.length, left = 0, right = n-1, sum = 0; while (left < right) { sum = nums[left] + nums[right]; if (sum == target) { return new int[] {left, right}; } else if (sum < target) { // Decreasing right will not help since it will make sum even smaller. So we increment left left++; } else { // Increasing left will not help since it will make sum even bigger. So we decrement right right--; } } return new int[0]; } public static String printArray(int[] arr) { String s = "["; int n = arr.length; for (int i = 0; i < n-1; i++) s += arr[i] + ", "; s += (n > 0) ? (arr[n-1] + "]") : "]"; return s; } public static void main(String[] args) { System.out.println("\nSolution 1: O(n^2) runtime and O(1) space complexities"); System.out.println("twoSum(new int[] {}, 9): " + printArray(twoSum(new int[] {}, 9))); System.out.println("twoSum(new int[] {1}, 9): " + printArray(twoSum(new int[] {1}, 9))); System.out.println("twoSum(new int[] {2, 7}, 9): " + printArray(twoSum(new int[] {2, 7}, 9))); System.out.println("twoSum(new int[] {2, 15, 11, 7}, 9): " + printArray(twoSum(new int[] {2, 15, 11, 7}, 9))); System.out.println("\nSolution 2: O(n) runtime and O(n) space complexities"); System.out.println("twoSumII(new int[] {}, 9): " + printArray(twoSumII(new int[] {}, 9))); System.out.println("twoSumII(new int[] {1}, 9): " + printArray(twoSumII(new int[] {1}, 9))); System.out.println("twoSumII(new int[] {2, 7}, 9): " + printArray(twoSumII(new int[] {2, 7}, 9))); System.out.println("twoSumII(new int[] {2, 7, 9, 11}, 9): " + printArray(twoSumII(new int[] {2, 15, 11, 7}, 9))); System.out.println("\nSolution 3: Assuming that the input array is sorted in increasing order:"); System.out.println("twoSumIII(new int[] {}, 9): " + printArray(twoSumIII(new int[] {}, 9))); System.out.println("twoSumIII(new int[] {1}, 9): " + printArray(twoSumIII(new int[] {1}, 9))); System.out.println("twoSumIII(new int[] {2, 7}, 9): " + printArray(twoSumIII(new int[] {2, 7}, 9))); System.out.println("twoSumIII(new int[] {2, 7, 9, 11}, 9): " + printArray(twoSumIII(new int[] {2, 15, 11, 7}, 9))); } } /* Older one: Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 */ /* SOLUTION 1: 0(n^2) running time and 0(1) space Pseudocode: We go through the input array from the begining. For each array element, we go through the rest of the array elements to see if there is an element whose sum with the current element adds up to the target. If so, these 2 elements are the ones we are looking for. We then print each of their indexes + 1 (since it's not zero based, we add 1 to each index). */ /* import java.util.HashMap; class TwoSum { public static void main(String[] args) { int[] array = {2, 7, 11, 15}; twoSum1(array, 9); // index1=1, index2=2 twoSum1(array, 13); // index1=1, index2=3 twoSum1(array, 17); // index1=1, index2=4 twoSum1(array, 18); // index1=2, index2=3 twoSum1(array, 22); // index1=2, index2=4 System.out.println("Testing the 2nd solution: 0(n) running time and 0(n) space complexities"); twoSum2(array, 9); // index1=1, index2=2 } public static void twoSum1(int[] numbers, int target) { int len = numbers.length; for(int i = 0; i < len; i++) { int element = numbers[i]; for(int j = i+1; j < len; j++) { if(element + numbers[j] == target) { System.out.println("index1=" + (i+1) + ", index2=" + (j+1) ); return; } } } } public static void twoSum2(int[] numbers, int target) { HashMap myHashMap = new HashMap(); int len = numbers.length; for(int i = 0; i < len; i++) { int element = numbers[i]; int key = target - element; // int value = myHashMap.get(key); if(myHashMap.get(key) != null) { int index1 = numbers.indexOf(target) + 1; System.out.println("index1=" + index1 + ", index2=" + (i+1)); } else { myHashMap.put(key, value); } } } } */
leetcode/java/prob1TwoSum/twoSum.java
/* Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. Follow up: What if the input array is sorted in ascending order? */ import java.util.HashMap; import java.util.Map; public class twoSum { public static int[] twoSum(int[] nums, int target) { if ( (nums == null) || (nums.length == 0) ) { return new int[0]; } int n = nums.length; int[] result = new int[2]; Map<Integer, Integer> hashmap = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) { int currentElement = nums[i]; int difference = target - currentElement; if (hashmap.containsKey(difference)) { result[0] = hashmap.get(difference); result[1] = i; break; } else { hashmap.put(currentElement, i); } } return result; } // Follow up: What if input array is sorted in ascending order (Problem 167) public static int[] twoSumII(int[] nums, int target) { // We assume nums is sorted in ascending order: int len = nums.length, left = 0, right = len - 1; int[] result = new int[2]; while (left < right) { int sum = nums[left] + nums[right]; if (sum < target) // Decreasing right will not help since it will make sum even smaller. So we increment left left++; else if (sum > target) // Increasing left will not help since it will make sum even bigger. So we decrement right right--; else { // sum = target // We have found the answer result[0] = left; result[1] = right; break; } } return result; } public static String printArray(int[] arr) { String s = "["; int n = arr.length; for (int i = 0; i < n-1; i++) s += arr[i] + ", "; s += (n > 0) ? (arr[n-1] + "]") : "]"; return s; } public static void main(String[] args) { System.out.println("twoSum(new int[] {}, 9): " + printArray(twoSum(new int[] {}, 9))); System.out.println("twoSum(new int[] {1}, 9): " + printArray(twoSum(new int[] {1}, 9))); System.out.println("twoSum(new int[] {2, 7}, 9): " + printArray(twoSum(new int[] {2, 7}, 9))); System.out.println("twoSum(new int[] {2, 15, 11, 7}, 9): " + printArray(twoSum(new int[] {2, 15, 11, 7}, 9))); System.out.println("\nCases where the input array is sorted:"); System.out.println("twoSumII(new int[] {}, 9): " + printArray(twoSumII(new int[] {}, 9))); System.out.println("twoSumII(new int[] {1}, 9): " + printArray(twoSumII(new int[] {1}, 9))); System.out.println("twoSumII(new int[] {2, 7}, 9): " + printArray(twoSumII(new int[] {2, 7}, 9))); System.out.println("twoSumII(new int[] {2, 7, 9, 11}, 9): " + printArray(twoSumII(new int[] {2, 15, 11, 7}, 9))); } } /* Older one: Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution. Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 */ /* SOLUTION 1: 0(n^2) running time and 0(1) space Pseudocode: We go through the input array from the begining. For each array element, we go through the rest of the array elements to see if there is an element whose sum with the current element adds up to the target. If so, these 2 elements are the ones we are looking for. We then print each of their indexes + 1 (since it's not zero based, we add 1 to each index). */ /* import java.util.HashMap; class TwoSum { public static void main(String[] args) { int[] array = {2, 7, 11, 15}; twoSum1(array, 9); // index1=1, index2=2 twoSum1(array, 13); // index1=1, index2=3 twoSum1(array, 17); // index1=1, index2=4 twoSum1(array, 18); // index1=2, index2=3 twoSum1(array, 22); // index1=2, index2=4 System.out.println("Testing the 2nd solution: 0(n) running time and 0(n) space complexities"); twoSum2(array, 9); // index1=1, index2=2 } public static void twoSum1(int[] numbers, int target) { int len = numbers.length; for(int i = 0; i < len; i++) { int element = numbers[i]; for(int j = i+1; j < len; j++) { if(element + numbers[j] == target) { System.out.println("index1=" + (i+1) + ", index2=" + (j+1) ); return; } } } } public static void twoSum2(int[] numbers, int target) { HashMap myHashMap = new HashMap(); int len = numbers.length; for(int i = 0; i < len; i++) { int element = numbers[i]; int key = target - element; // int value = myHashMap.get(key); if(myHashMap.get(key) != null) { int index1 = numbers.indexOf(target) + 1; System.out.println("index1=" + index1 + ", index2=" + (i+1)); } else { myHashMap.put(key, value); } } } } */
Updated solutions for twoSum.java
leetcode/java/prob1TwoSum/twoSum.java
Updated solutions for twoSum.java
<ide><path>eetcode/java/prob1TwoSum/twoSum.java <ide> <ide> public class twoSum { <ide> <add> // O(n^2) runtime and O(n) space complexities <ide> public static int[] twoSum(int[] nums, int target) { <ide> <del> if ( (nums == null) || (nums.length == 0) ) { <del> return new int[0]; <del> } <add> if (nums == null || nums.length < 2) return new int[0]; <ide> <ide> int n = nums.length; <del> int[] result = new int[2]; <del> Map<Integer, Integer> hashmap = new HashMap<Integer, Integer>(); <ide> <ide> for (int i = 0; i < n; i++) { <del> <del> int currentElement = nums[i]; <del> int difference = target - currentElement; <del> <del> if (hashmap.containsKey(difference)) { <del> <del> result[0] = hashmap.get(difference); <del> result[1] = i; <del> break; <del> <del> } else { <del> hashmap.put(currentElement, i); <add> for (int j = i+1; j < n; j++) { <add> if (nums[i] + nums[j] == target) <add> return new int[] {i, j}; <ide> } <ide> } <del> <del> return result; <add> return new int[0]; <ide> } <ide> <del> // Follow up: What if input array is sorted in ascending order (Problem 167) <add> // O(n) runtime and O(n) space complexities <ide> public static int[] twoSumII(int[] nums, int target) { <del> // We assume nums is sorted in ascending order: <del> int len = nums.length, left = 0, right = len - 1; <del> int[] result = new int[2]; <add> if (nums == null || nums.length < 2) return new int[0]; <ide> <del> while (left < right) { <del> int sum = nums[left] + nums[right]; <del> if (sum < target) <del> // Decreasing right will not help since it will make sum even smaller. So we increment left <del> left++; <del> else if (sum > target) <del> // Increasing left will not help since it will make sum even bigger. So we decrement right <del> right--; <del> else { // sum = target <del> // We have found the answer <del> result[0] = left; <del> result[1] = right; <del> break; <add> int n = nums.length; <add> Map<Integer, Integer> map = new HashMap<>(); <add> for (int i = 0; i < n; i++) { <add> int complement = target - nums[i]; <add> if (map.containsKey(complement)) <add> return new int[] {map.get(complement), i}; <add> else <add> map.put(nums[i], i); <add> } <add> return new int[0]; <add> } <add> <add> <add> // Follow up: What if input array is sorted in ascending order (Leetcode Problem 167) <add> // O(n*long(n)) runtime and O(1) space complexities <add> public static int[] twoSumIII(int[] nums, int target) { <add> <add> if (nums == null || nums.length < 2) return new int[0]; <add> <add> int n = nums.length, left = 0, right = n-1, sum = 0; <add> <add> while (left < right) { <add> sum = nums[left] + nums[right]; <add> if (sum == target) { <add> return new int[] {left, right}; <add> } else if (sum < target) { // Decreasing right will not help since it will make sum even smaller. So we increment left <add> left++; <add> } else { // Increasing left will not help since it will make sum even bigger. So we decrement right <add> right--; <add> } <ide> } <del> } <del> return result; <add> return new int[0]; <ide> } <ide> <ide> public static String printArray(int[] arr) { <ide> } <ide> <ide> public static void main(String[] args) { <del> <add> System.out.println("\nSolution 1: O(n^2) runtime and O(1) space complexities"); <ide> System.out.println("twoSum(new int[] {}, 9): " + printArray(twoSum(new int[] {}, 9))); <ide> System.out.println("twoSum(new int[] {1}, 9): " + printArray(twoSum(new int[] {1}, 9))); <ide> System.out.println("twoSum(new int[] {2, 7}, 9): " + printArray(twoSum(new int[] {2, 7}, 9))); <ide> System.out.println("twoSum(new int[] {2, 15, 11, 7}, 9): " + printArray(twoSum(new int[] {2, 15, 11, 7}, 9))); <ide> <del> System.out.println("\nCases where the input array is sorted:"); <add> System.out.println("\nSolution 2: O(n) runtime and O(n) space complexities"); <ide> System.out.println("twoSumII(new int[] {}, 9): " + printArray(twoSumII(new int[] {}, 9))); <ide> System.out.println("twoSumII(new int[] {1}, 9): " + printArray(twoSumII(new int[] {1}, 9))); <ide> System.out.println("twoSumII(new int[] {2, 7}, 9): " + printArray(twoSumII(new int[] {2, 7}, 9))); <ide> System.out.println("twoSumII(new int[] {2, 7, 9, 11}, 9): " + printArray(twoSumII(new int[] {2, 15, 11, 7}, 9))); <add> <add> System.out.println("\nSolution 3: Assuming that the input array is sorted in increasing order:"); <add> System.out.println("twoSumIII(new int[] {}, 9): " + printArray(twoSumIII(new int[] {}, 9))); <add> System.out.println("twoSumIII(new int[] {1}, 9): " + printArray(twoSumIII(new int[] {1}, 9))); <add> System.out.println("twoSumIII(new int[] {2, 7}, 9): " + printArray(twoSumIII(new int[] {2, 7}, 9))); <add> System.out.println("twoSumIII(new int[] {2, 7, 9, 11}, 9): " + printArray(twoSumIII(new int[] {2, 15, 11, 7}, 9))); <ide> } <ide> <ide> } <ide> } <ide> } <ide> */ <del>
Java
mit
ba093c85635b4c3a14c2347ec583a504ca1847b6
0
cortext/geoclust,risis-eu/geoclust
import java.util.Vector; public class DBScan { public Vector<Integer> MNumClust; public ExtractionDonnees exd; public int v1; DBScan(ExtractionDonnees ex) { exd = ex; v1 = exd.Coord.size(); System.out.println("v1 = "+v1); int MinPts = Integer.valueOf(exd.ui.tnbpts.getText()); //choix minPts //System.out.println("min pts = "+MinPts); int MinPds = Integer.valueOf(exd.ui.tpoids.getText()); double eps = Double.valueOf(exd.ui.tray.getText()); //choix du seuil d'aloignement (pour le densite) R MNumClust = new Vector<Integer>();// matrice associant a chaque identifiant de pole un numero de cluster int numClust = 1; //on remplit MClust des identifiants des poles sur la premiere colonne et de zeros sur la seconde colonne for (int k=0; k<v1; k++ ) { MNumClust.add(0); }//fin for k System.out.println("Fin remplissage de numClust avec des zeros"); for (int i=0; i<v1; i++ )// i represente un pole { if(exd.Coord.get(i).get(3)==0.0){ exd.Coord.get(i).set(3,1.0);//En indiquant que le pole est visite Vector<Object> PtsVoisinsPoids = regionQuery(i, eps); Vector<Integer> PtsVoisins = (Vector<Integer>) PtsVoisinsPoids.get(0); int poids_cluster = Integer.valueOf(PtsVoisinsPoids.get(1).toString()); //if(MinPts>0 && PtsVoisins.size()>MinPts && poids_cluster>=MinPds){ if(poids_cluster>=MinPds){// expandCluster(i,PtsVoisins,numClust,eps,MinPts,MinPds);//fait appel a la methode pour trouver les voisins du cluster numClust++; } } }//fin boucle sur i System.out.println("Fin DBScan quantite clusters "+numClust); } /** * Methode pour calculer la distance entre deux coordonnees geographiques * * @param lambdai * @param phii * @param lambdaj * @param phij * @return distance en metres */ public double DistancePts(double lambdai,double phii,double lambdaj,double phij) { double a = 6378137.0; //en m double b = 6356752.314; // en m //il faut transformer les degres en radians lambdai = lambdai*Math.PI/180; lambdaj = lambdaj*Math.PI/180; phii = phii*Math.PI/180; phij = phij*Math.PI/180; double wi = (b*b*Math.tan(phii))/(a*a); double wj = (b*b*Math.tan(phij))/(a*a); double xi = (a*Math.cos(lambdai)*Math.cos(phii))/wi; double xj = (a*Math.cos(lambdaj)*Math.cos(phij))/wj; double yi = (a*Math.sin(lambdai)*Math.cos(phii))/wi; double yj = (a*Math.sin(lambdaj)*Math.cos(phij))/wj; double zi = (b*b*Math.sin(phii))/(a*wi); double zj = (b*b*Math.sin(phij))/(a*wj); double x = xi-xj; double y = yi-yj; double z = zi - zj; double r = Math.sqrt(x*x+y*y+z*z); return r; } /*Trouve les points voisines d un point specifique, on fait lanlyse des voisins en obtenant le poids si le critere de distance minimale est remplie */ public Vector<Object> regionQuery(int i,Double eps){ Vector<Integer> indexVoisins = new Vector<Integer>(); Vector<Object> indexVoisinsPoids= new Vector<Object>(); int poids = 0; int poids_i=(int)(double)exd.Coord.get(i).get(4); poids += poids_i; for (int j=0; j<v1; j++) //boucle pour compter le nombre de voisins proches de i. j est un voisin de i. { if(i!=j && MNumClust.get(j)==0){//excluir lui-meme double lambdai = exd.Coord.get(i).get(1); double lambdaj = exd.Coord.get(j).get(1); double phii = exd.Coord.get(i).get(2); double phij = exd.Coord.get(j).get(2); double distancePoints = DistancePts(lambdai, phii, lambdaj, phij); int poids_j=(int)(double)exd.Coord.get(j).get(4); if (distancePoints <= eps )//ici, en excluant la distance nulle, on considere que i n'est pas voisin de lui-meme. et si le point est visite { indexVoisins.add(j); poids=poids_j+poids;//TODO quitar poids i modifier le poids, il faut additioner juste le poids_j + poids } } } indexVoisinsPoids.add(indexVoisins); indexVoisinsPoids.add(poids); return indexVoisinsPoids; } public void expandCluster(int i,Vector<Integer>PtsVoisins,int numClust,double eps,int MinPts,int MinPds){ MNumClust.set(i,numClust); //liste contient les index des voisins if(PtsVoisins.size()!=0){ for(int x=0;x<=PtsVoisins.size()-1;x++){ int icousin=PtsVoisins.get(x); //on verifie si le p cousin(i cousin) n est pas visite if(exd.Coord.get(icousin).get(3)==0.0){ //Change pour visite exd.Coord.get(icousin).set(3, 1.0); Vector<Object> PtsVoisinsCousinsPoids = regionQuery(icousin, eps); Vector<Integer> PtsVoisinsCousins = (Vector<Integer>) PtsVoisinsCousinsPoids.get(0); int poids_cluster = Integer.valueOf(PtsVoisinsCousinsPoids.get(1).toString()); //if((PtsVoisinsCousins.size()-1)>=MinPts && poids_cluster>=MinPds){ if(poids_cluster>=MinPds){ PtsVoisins.addAll(PtsVoisinsCousins); } } if(MNumClust.get(icousin)==0){ MNumClust.set(icousin,numClust); } } } } }
src/DBScan.java
import java.util.Vector; public class DBScan { public Vector<Integer> MNumClust; public ExtractionDonnees exd; public int v1; DBScan(ExtractionDonnees ex) { exd = ex; v1 = exd.Coord.size(); // v1 = 10000; System.out.println("v1 = "+v1); //choix minPts int MinPts = Integer.valueOf(exd.ui.tnbpts.getText()); // System.out.println("min pts = "+MinPts); int MinPds = Integer.valueOf(exd.ui.tpoids.getText()); //choix du seuil d'aloignement (pour le densite) R double eps = Double.valueOf(exd.ui.tray.getText());//en metres // System.out.println("ray = "+R); MNumClust = new Vector<Integer>();// matrice associant a chaque identifiant de pole un numero de cluster int numClust = 0; //on remplit MClust des identifiants des poles sur la premiere colonne et de zeros sur la seconde colonne for (int k=0; k<v1; k++ ) { MNumClust.add(0); }//fin for k //fin remplissage num clust avec des zeros System.out.println("Fin remplissage de numClust avec des zeros"); for (int i=0; i<v1; i++ )// i represente un pole { if(exd.Coord.get(i).get(3)==0.0){ exd.Coord.get(i).set(3,1.0); Vector<Object> PtsVoisinsPoids = regionQuery(i, eps); Vector<Integer> PtsVoisins = (Vector<Integer>) PtsVoisinsPoids.get(0); int poids_cluster = Integer.valueOf(PtsVoisinsPoids.get(1).toString()); //if(MinPts>0 && PtsVoisins.size()>MinPts && poids_cluster>=MinPds){ if(poids_cluster>=MinPds){ numClust++; expandCluster(i,PtsVoisins,numClust,eps,MinPts,MinPds); } } } //fin boucle sur i System.out.println("Fin DBScan quantite clusters "+numClust); } public double DistancePts(double lambdai,double phii,double lambdaj,double phij) { double a = 6378137.0; //en m double b = 6356752.314; // en m //il faut transformer les degres en radians lambdai = lambdai*Math.PI/180; lambdaj = lambdaj*Math.PI/180; phii = phii*Math.PI/180; phij = phij*Math.PI/180; double wi = (b*b*Math.tan(phii))/(a*a); double wj = (b*b*Math.tan(phij))/(a*a); double xi = (a*Math.cos(lambdai)*Math.cos(phii))/wi; double xj = (a*Math.cos(lambdaj)*Math.cos(phij))/wj; double yi = (a*Math.sin(lambdai)*Math.cos(phii))/wi; double yj = (a*Math.sin(lambdaj)*Math.cos(phij))/wj; double zi = (b*b*Math.sin(phii))/(a*wi); double zj = (b*b*Math.sin(phij))/(a*wj); double x = xi-xj; double y = yi-yj; double z = zi - zj; double r = Math.sqrt(x*x+y*y+z*z); return r; } /*Trouve les points voisines d un point specifique, on fait lanlyse des voisins en obtenant le poids si le critere de distance minimale est remplie */ public Vector<Object> regionQuery(int i,Double eps){ Vector<Integer> indexVoisins = new Vector<Integer>(); Vector<Object> indexVoisinsPoids= new Vector<Object>(); int poids = 0; int poids_i=(int)(double)exd.Coord.get(i).get(4); poids += poids_i; for (int j=0; j<v1; j++) //boucle pour compter le nombre de voisins proches de i. j est un voisin de i. { if(i!=j){//excluir lui-meme double lambdai = exd.Coord.get(i).get(1); double lambdaj = exd.Coord.get(j).get(1); double phii = exd.Coord.get(i).get(2); double phij = exd.Coord.get(j).get(2); double distancePoints = DistancePts(lambdai, phii, lambdaj, phij); int poids_j=(int)(double)exd.Coord.get(j).get(4); if (distancePoints <= eps )//ici, en excluant la distance nulle, on considere que i n'est pas voisin de lui-meme. et si le point est visite { indexVoisins.add(j); poids=poids_i+poids_j+poids;//modifier le poids, il faut additioner juste le poids_j + poids } } } indexVoisinsPoids.add(indexVoisins); indexVoisinsPoids.add(poids); return indexVoisinsPoids; } public void expandCluster(int i,Vector<Integer>PtsVoisins,int numClust,double eps,int MinPts,int MinPds){ MNumClust.set(i,numClust); //liste contient les index des voisins if(PtsVoisins.size()!=0){ for(int x=0;x<=PtsVoisins.size()-1;x++){ int icousin=PtsVoisins.get(x); //on verifie si le p cousin(i cousin) n est pas visite if(exd.Coord.get(icousin).get(3)==0.0){ //Change pour visite exd.Coord.get(icousin).set(3, 1.0); Vector<Object> PtsVoisinsCousinsPoids = regionQuery(icousin, eps); Vector<Integer> PtsVoisinsCousins = (Vector<Integer>) PtsVoisinsCousinsPoids.get(0); int poids_cluster = Integer.valueOf(PtsVoisinsCousinsPoids.get(1).toString()); //if((PtsVoisinsCousins.size()-1)>=MinPts && poids_cluster>=MinPds){ if(poids_cluster>=MinPds){ PtsVoisins.addAll(PtsVoisinsCousins); } } if(MNumClust.get(icousin)==0){ MNumClust.set(icousin,numClust); } } } } /** * Methode pour creer les clusters a partir des points qui ont le poid au dessus du parametre * et qui sont pas dans un cluster parce que ils ne remplissent pas la condition des voisines (MinPoints) * * @param i = point en question, numClust = le numero du nouveau cluster * @author Michel Revollo * */ public void createClusterCities(int i,int numClust){ } }
Changement validation MinPoids, formule pour obtenir le poids par cluster
src/DBScan.java
Changement validation MinPoids, formule pour obtenir le poids par cluster
<ide><path>rc/DBScan.java <ide> { <ide> exd = ex; <ide> v1 = exd.Coord.size(); <del>// v1 = 10000; <ide> System.out.println("v1 = "+v1); <del> //choix minPts <del> int MinPts = Integer.valueOf(exd.ui.tnbpts.getText()); <del>// System.out.println("min pts = "+MinPts); <add> int MinPts = Integer.valueOf(exd.ui.tnbpts.getText()); //choix minPts <add> //System.out.println("min pts = "+MinPts); <ide> int MinPds = Integer.valueOf(exd.ui.tpoids.getText()); <del> //choix du seuil d'aloignement (pour le densite) R <del> double eps = Double.valueOf(exd.ui.tray.getText());//en metres <del>// System.out.println("ray = "+R); <del> <add> <add> double eps = Double.valueOf(exd.ui.tray.getText()); //choix du seuil d'aloignement (pour le densite) R <ide> MNumClust = new Vector<Integer>();// matrice associant a chaque identifiant de pole un numero de cluster <add> int numClust = 1; <ide> <del> int numClust = 0; <del> <ide> //on remplit MClust des identifiants des poles sur la premiere colonne et de zeros sur la seconde colonne <del> <ide> for (int k=0; k<v1; k++ ) <del> { <add> { <ide> MNumClust.add(0); <ide> }//fin for k <del> <del> //fin remplissage num clust avec des zeros <ide> System.out.println("Fin remplissage de numClust avec des zeros"); <ide> <ide> for (int i=0; i<v1; i++ )// i represente un pole <ide> { <ide> if(exd.Coord.get(i).get(3)==0.0){ <del> exd.Coord.get(i).set(3,1.0); <add> exd.Coord.get(i).set(3,1.0);//En indiquant que le pole est visite <ide> <ide> Vector<Object> PtsVoisinsPoids = regionQuery(i, eps); <ide> Vector<Integer> PtsVoisins = (Vector<Integer>) PtsVoisinsPoids.get(0); <ide> int poids_cluster = Integer.valueOf(PtsVoisinsPoids.get(1).toString()); <ide> //if(MinPts>0 && PtsVoisins.size()>MinPts && poids_cluster>=MinPds){ <del> if(poids_cluster>=MinPds){ <add> if(poids_cluster>=MinPds){// <add> expandCluster(i,PtsVoisins,numClust,eps,MinPts,MinPds);//fait appel a la methode pour trouver les voisins du cluster <ide> numClust++; <del> expandCluster(i,PtsVoisins,numClust,eps,MinPts,MinPds); <ide> } <ide> } <del> } <del> //fin boucle sur i <add> }//fin boucle sur i <ide> System.out.println("Fin DBScan quantite clusters "+numClust); <ide> } <ide> <add> /** <add> * Methode pour calculer la distance entre deux coordonnees geographiques <add> * <add> * @param lambdai <add> * @param phii <add> * @param lambdaj <add> * @param phij <add> * @return distance en metres <add> */ <ide> public double DistancePts(double lambdai,double phii,double lambdaj,double phij) <ide> { <ide> double a = 6378137.0; //en m <ide> poids += poids_i; <ide> for (int j=0; j<v1; j++) //boucle pour compter le nombre de voisins proches de i. j est un voisin de i. <ide> { <del> if(i!=j){//excluir lui-meme <add> if(i!=j && MNumClust.get(j)==0){//excluir lui-meme <ide> double lambdai = exd.Coord.get(i).get(1); <ide> double lambdaj = exd.Coord.get(j).get(1); <ide> double phii = exd.Coord.get(i).get(2); <ide> if (distancePoints <= eps )//ici, en excluant la distance nulle, on considere que i n'est pas voisin de lui-meme. et si le point est visite <ide> { <ide> indexVoisins.add(j); <del> poids=poids_i+poids_j+poids;//modifier le poids, il faut additioner juste le poids_j + poids <add> poids=poids_j+poids;//TODO quitar poids i modifier le poids, il faut additioner juste le poids_j + poids <ide> } <ide> } <ide> } <ide> } <ide> } <ide> } <del> /** <del> * Methode pour creer les clusters a partir des points qui ont le poid au dessus du parametre <del> * et qui sont pas dans un cluster parce que ils ne remplissent pas la condition des voisines (MinPoints) <del> * <del> * @param i = point en question, numClust = le numero du nouveau cluster <del> * @author Michel Revollo <del> * */ <del> public void createClusterCities(int i,int numClust){ <del> } <ide> }
JavaScript
apache-2.0
1125786b676c0ed856fb78b2859bbce9779fe6f2
0
Gillespie59/angular-logs2server
(function(){ 'use strict'; /** * @ngdoc module * @name logs2server * @module logs2server * @description * * # logs2server * The logs2server module will provide a decorator to the ExceptionHandler service. You will be able to send * to your server any client-side exception (throw Error("message")), and this exception will be sent to your * server, with some complementary informations (navigator object, $location informations, ...) */ angular.module('logs2server', ['ng']) .config(exceptionConfig) .provider('log2serverConfigService', log2serverConfigServiceProvider); exceptionConfig.$inject = ['$provide']; function exceptionConfig($provide) { $provide.decorator('$exceptionHandler', extendExceptionHandler); } extendExceptionHandler.$inject = ['$delegate', 'log2serverConfigService', '$injector']; function extendExceptionHandler($delegate, log2serverConfigService, $injector) { /** * @ngdoc function * @name generateNavigatorData * @module logs2server * @kind function * * @returns {object} Object containing some Navigator property */ function generateNavigatorData(){ var $window = $injector.get('$window'); return { appCodeName: $window.navigator.appCodeName, appName: $window.navigator.appName, appVersion: $window.navigator.appVersion, cookieEnabled: $window.navigator.cookieEnabled, hardwareConcurrency: $window.navigator.hardwareConcurrency, language: $window.navigator.language, languages: $window.navigator.languages, maxTouchPoints: $window.navigator.maxTouchPoints, onLine: $window.navigator.onLine, platform: $window.navigator.platform, product: $window.navigator.product, productSub: $window.navigator.productSub, userAgent: $window.navigator.userAgent, vendor: $window.navigator.vendor, vendorSub: $window.navigator.vendorSub }; } /** * @ngdoc function * @name generateLocationData * @module logs2server * @kind function * * @returns {object} Object containing ^the result of some $location methods */ function generateLocationData(){ var $location = $injector.get('$location'); return { absUrl: $location.absUrl(), hash: $location.hash(), host: $location.host(), path: $location.path(), port: $location.port(), protocol: $location.protocol(), url: $location.url() }; } return function (exception, cause) { var serverURL = log2serverConfigService.getUrl(); if(angular.isDefined(serverURL)){ var data = { exception: exception, cause: cause, navigator: generateNavigatorData(), location: generateLocationData() }; $injector.get('$http').post(serverURL, data); } if(log2serverConfigService.getDefaultExceptionHandler()){ $delegate(exception, cause); } }; } /** * @ngdoc provider * @name $log2serverConfigServiceProvider * @description * The provider is used to configure the exceptionHandler decorator provided by the logs2server module. * * This provider allows the configuration of the log2server module with : * {@link logs2server.$log2serverConfigServiceProvider#setServerURL setServerURL} method. * {@link logs2server.$log2serverConfigServiceProvider#setDefaultExceptionHandler setDefaultExceptionHandler} method. */ log2serverConfigServiceProvider.$inject = []; function log2serverConfigServiceProvider(){ var serverURL; var defaultExceptionHandler = true; /** * @ngdoc method * @name $log2serverConfigServiceProvider#setServerURL * @param {string} url URL of the REST API receiving the logs, via a POST request. */ this.setServerURL = function(url){ serverURL = url; }; /** * @ngdoc method * @name $log2serverConfigServiceProvider#setDefaultExceptionHandler * @param {boolean} flag Indicate if the default exceptionHandler behavior should be enabled. */ this.setDefaultExceptionHandler = function(flag){ defaultExceptionHandler = flag; }; this.$get = [function(){ return { getUrl: function(){ return serverURL; } }; }]; } })();
angular-logs2server.js
(function(){ 'use strict'; /** * @ngdoc module * @name logs2server * @module logs2server * @description * * # logs2server * The logs2server module will provide a decorator to the ExceptionHandler service. You will be able to send * to your server any client-side exception (throw Error("message")), and this exception will be sent to your * server, with some complementary informations (navigator object, $location informations, ...) */ angular.module('logs2server', ['ng']) .config(exceptionConfig) .provider('log2serverConfigService', log2serverConfigServiceProvider); exceptionConfig.$inject = ['$provide']; function exceptionConfig($provide) { $provide.decorator('$exceptionHandler', extendExceptionHandler); } extendExceptionHandler.$inject = ['$delegate', 'log2serverConfigService', '$injector']; function extendExceptionHandler($delegate, log2serverConfigService, $injector) { /** * @ngdoc function * @name generateNavigatorData * @module logs2server * @kind function * * @returns {object} Object containing some Navigator property */ function generateNavigatorData(){ var $window = $injector.get('$window'); return { appCodeName: $window.navigator.appCodeName, appName: $window.navigator.appName, appVersion: $window.navigator.appVersion, cookieEnabled: $window.navigator.cookieEnabled, hardwareConcurrency: $window.navigator.hardwareConcurrency, language: $window.navigator.language, languages: $window.navigator.languages, maxTouchPoints: $window.navigator.maxTouchPoints, onLine: $window.navigator.onLine, platform: $window.navigator.platform, product: $window.navigator.product, productSub: $window.navigator.productSub, userAgent: $window.navigator.userAgent, vendor: $window.navigator.vendor, vendorSub: $window.navigator.vendorSub }; } /** * @ngdoc function * @name generateLocationData * @module logs2server * @kind function * * @returns {object} Object containing ^the result of some $location methods */ function generateLocationData(){ var $location = $injector.get('$location'); return { absUrl: $location.absUrl(), hash: $location.hash(), host: $location.host(), path: $location.path(), port: $location.port(), protocol: $location.protocol(), url: $location.url() }; } return function (exception, cause) { var serverURL = log2serverConfigService.getUrl(); if(angular.isDefined(serverURL)){ var data = { exception: exception, cause: cause, navigator: generateNavigatorData(), location: generateLocationData() }; $injector.get('$http').post(serverURL, data); } if(log2serverConfigService.getDefaultExceptionHandler()){ $delegate(exception, cause); } }; } /** * @ngdoc provider * @name $log2serverConfigServiceProvider * @description * The provider is used to configure the exceptionHandler decorator provided by the logs2server module. * * This provider allows the configuration of the log2server module with : * {@link logs2server.$log2serverConfigServiceProvider#setServerURL setServerURL} method. * {@link logs2server.$log2serverConfigServiceProvider#setDefaultExceptionHandler setDefaultExceptionHandler} method. */ log2serverConfigServiceProvider.$inject = []; function log2serverConfigServiceProvider(){ var serverURL; var defaultExceptionHandler = true; /** * @ngdoc method * @name $log2serverConfigServiceProvider#setServerURL * @param {string} url URL of the REST API receiving the logs, via a POST request. */ this.setServerURL = function(url){ serverURL = url; }; /** * @ngdoc method * @name $log2serverConfigServiceProvider#setDefaultExceptionHandler * @param {boolean} flag Indicate if the default exceptionHandler behavior should be enabled. */ this.setDefaultExceptionHandler = function(flag){ defaultExceptionHandler = flag; }; this.$get = [function(){ return { getUrl: function(){ return serverURL; } }; }]; } })();
Align ngdoc
angular-logs2server.js
Align ngdoc
<ide><path>ngular-logs2server.js <ide> var defaultExceptionHandler = true; <ide> <ide> /** <del> * @ngdoc method <del> * @name $log2serverConfigServiceProvider#setServerURL <del> * @param {string} url URL of the REST API receiving the logs, via a POST request. <del> */ <add> * @ngdoc method <add> * @name $log2serverConfigServiceProvider#setServerURL <add> * @param {string} url URL of the REST API receiving the logs, via a POST request. <add> */ <ide> this.setServerURL = function(url){ <ide> serverURL = url; <ide> }; <ide> <ide> /** <del> * @ngdoc method <del> * @name $log2serverConfigServiceProvider#setDefaultExceptionHandler <del> * @param {boolean} flag Indicate if the default exceptionHandler behavior should be enabled. <del> */ <add> * @ngdoc method <add> * @name $log2serverConfigServiceProvider#setDefaultExceptionHandler <add> * @param {boolean} flag Indicate if the default exceptionHandler behavior should be enabled. <add> */ <ide> this.setDefaultExceptionHandler = function(flag){ <ide> defaultExceptionHandler = flag; <ide> };
Java
apache-2.0
63ea7789ce7be1ec53a8d9cd822cb8e00d301033
0
KurtStam/fabric8,KurtStam/fabric8,dhirajsb/fabric8,zmhassan/fabric8,christian-posta/fabric8,christian-posta/fabric8,rhuss/fabric8,chirino/fabric8v2,chirino/fabric8v2,dhirajsb/fabric8,chirino/fabric8v2,zmhassan/fabric8,rhuss/fabric8,dhirajsb/fabric8,KurtStam/fabric8,dhirajsb/fabric8,rhuss/fabric8,rhuss/fabric8,christian-posta/fabric8,christian-posta/fabric8,KurtStam/fabric8,zmhassan/fabric8,zmhassan/fabric8,chirino/fabric8v2
/** * Copyright 2005-2015 Red Hat, Inc. * * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.forge.camel.maven; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import io.fabric8.forge.camel.commands.project.helper.RouteBuilderParser; import io.fabric8.forge.camel.commands.project.helper.XmlRouteParser; import io.fabric8.forge.camel.commands.project.model.CamelEndpointDetails; import org.apache.camel.catalog.CamelCatalog; import org.apache.camel.catalog.DefaultCamelCatalog; import org.apache.camel.catalog.EndpointValidationResult; import org.apache.camel.catalog.lucene.LuceneSuggestionStrategy; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; import org.jboss.forge.roaster.Roaster; import org.jboss.forge.roaster.model.JavaType; import org.jboss.forge.roaster.model.source.JavaClassSource; /** * Analyses the project source code for Camel routes, and validates the endpoint uris whether there may be invalid uris. */ @Mojo(name = "validate", defaultPhase = LifecyclePhase.PROCESS_TEST_CLASSES, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) public class EndpointMojo extends AbstractMojo { @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** * Whether to fail if invalid Camel endpoints was found. By default the plugin logs the errors at WARN level */ @Parameter(property = "camel.failOnError", defaultValue = "false", readonly = true, required = false) private boolean failOnError; /** * Whether to include Java files to be validated for invalid Camel endpoints */ @Parameter(property = "camel.includeJava", defaultValue = "true", readonly = true, required = false) private boolean includeJava; /** * Whether to include XML files to be validated for invalid Camel endpoints */ @Parameter(property = "camel.includeXml", defaultValue = "true", readonly = true, required = false) private boolean includeXml; /** * Whether to include test source code */ @Parameter(property = "camel.includeTest", defaultValue = "false", readonly = true, required = false) private boolean includeTest; /** * To filter the names of java and xml files to only include files matching any of the given list of patterns (wildcard and regular expression). * Multiple values can be separated by comma. */ @Parameter(property = "camel.includes", readonly = true, required = false) private String includes; /** * To filter the names of java and xml files to exclude files matching any of the given list of patterns (wildcard and regular expression). * Multiple values can be separated by comma. */ @Parameter(property = "camel.excludes", readonly = true, required = false) private String excludes; @Override public void execute() throws MojoExecutionException, MojoFailureException { CamelCatalog catalog = new DefaultCamelCatalog(); // enable did you mean catalog.setSuggestionStrategy(new LuceneSuggestionStrategy()); List<CamelEndpointDetails> endpoints = new ArrayList<>(); Set<File> javaFiles = new LinkedHashSet<File>(); Set<File> xmlFiles = new LinkedHashSet<File>(); // find all java route builder classes if (includeJava) { for (String dir : project.getCompileSourceRoots()) { findJavaFiles(new File(dir), javaFiles); } if (includeTest) { for (String dir : project.getTestCompileSourceRoots()) { findJavaFiles(new File(dir), javaFiles); } } } // find all xml routes if (includeXml) { for (Resource dir : project.getResources()) { findXmlFiles(new File(dir.getDirectory()), xmlFiles); } if (includeTest) { for (Resource dir : project.getTestResources()) { findXmlFiles(new File(dir.getDirectory()), xmlFiles); } } } for (File file : javaFiles) { if (matchFile(file)) { try { // parse the java source code and find Camel RouteBuilder classes String fqn = file.getPath(); String baseDir = "."; JavaType out = Roaster.parse(file); // we should only parse java classes (not interfaces and enums etc) if (out != null && out instanceof JavaClassSource) { JavaClassSource clazz = (JavaClassSource) out; RouteBuilderParser.parseRouteBuilder(clazz, baseDir, fqn, endpoints); } } catch (Exception e) { getLog().warn("Error parsing java file " + file + " code due " + e.getMessage(), e); } } } for (File file : xmlFiles) { if (matchFile(file)) { try { // parse the xml source code and find Camel routes String fqn = file.getPath(); String baseDir = "."; InputStream is = new FileInputStream(file); XmlRouteParser.parseXmlRoute(is, baseDir, fqn, endpoints); is.close(); } catch (Exception e) { getLog().warn("Error parsing xml file " + file + " code due " + e.getMessage(), e); } } } int errors = 0; for (CamelEndpointDetails detail : endpoints) { EndpointValidationResult result = catalog.validateEndpointProperties(detail.getEndpointUri()); if (!result.isSuccess()) { errors++; StringBuilder sb = new StringBuilder(); sb.append("Endpoint validation error in file: ").append(asRelativeFile(detail.getFileName())); if (detail.getLineNumber() != null) { sb.append(" at line: ").append(detail.getLineNumber()); } sb.append("\n\n"); String out = result.summaryErrorMessage(false); sb.append(out); sb.append("\n\n"); getLog().warn(sb.toString()); } } String summary; if (errors == 0) { int ok = endpoints.size() - errors; summary = String.format("Endpoint validation success: (%s = passed, %s = invalid)", ok, errors); } else { int ok = endpoints.size() - errors; summary = String.format("Endpoint validation error: (%s = passed, %s = invalid)", ok, errors); } if (failOnError && errors > 0) { throw new MojoExecutionException(summary); } if (errors > 0) { getLog().warn(summary); } else { getLog().info(summary); } } private void findJavaFiles(File dir, Set<File> javaFiles) { File[] files = dir.isDirectory() ? dir.listFiles() : null; if (files != null) { for (File file : files) { if (file.getName().endsWith(".java")) { javaFiles.add(file); } else if (file.isDirectory()) { findJavaFiles(file, javaFiles); } } } } private void findXmlFiles(File dir, Set<File> xmlFiles) { File[] files = dir.isDirectory() ? dir.listFiles() : null; if (files != null) { for (File file : files) { if (file.getName().endsWith(".xml")) { xmlFiles.add(file); } else if (file.isDirectory()) { findXmlFiles(file, xmlFiles); } } } } private boolean matchFile(File file) { if (excludes == null && includes == null) { return true; } // exclude take precedence if (excludes != null) { for (String exclude : excludes.split(",")) { exclude = exclude.trim(); // try both with and without directory in the name String fqn = asPackageName(asRelativeFile(file.getAbsolutePath())); boolean match = EndpointHelper.matchPattern(fqn, exclude) || EndpointHelper.matchPattern(file.getName(), exclude); if (match) { return false; } } } // include if (includes != null) { for (String include : includes.split(",")) { include = include.trim(); // try both with and without directory in the name String fqn = asPackageName(asRelativeFile(file.getAbsolutePath())); boolean match = EndpointHelper.matchPattern(fqn, include) || EndpointHelper.matchPattern(file.getName(), include); if (match) { return true; } } // did not match any includes return false; } // was not excluded nor failed include so its accepted return true; } private String asRelativeFile(String name) { String answer = name; String base = project.getBasedir().getAbsolutePath(); if (name.startsWith(base)) { answer = name.substring(base.length()); // skip leading slash for relative path if (answer.startsWith(File.separator)) { answer = answer.substring(1); } } return answer; } private String asPackageName(String name) { // strip out any leading source / resource directory for (String dir : project.getCompileSourceRoots()) { dir = asRelativeFile(dir); if (name.startsWith(dir)) { return name.substring(dir.length() + 1); } } for (String dir : project.getTestCompileSourceRoots()) { dir = asRelativeFile(dir); if (name.startsWith(dir)) { return name.substring(dir.length() + 1); } } for (Resource resource : project.getResources()) { String dir = asRelativeFile(resource.getDirectory()); if (name.startsWith(dir)) { return name.substring(dir.length() + 1); } } for (Resource resource : project.getTestResources()) { String dir = asRelativeFile(resource.getDirectory()); if (name.startsWith(dir)) { return name.substring(dir.length() + 1); } } return name; } }
forge/addons/camel-maven-plugin/src/main/java/io/fabric8/forge/camel/maven/EndpointMojo.java
/** * Copyright 2005-2015 Red Hat, Inc. * <p/> * Red Hat licenses this file to you under the Apache License, version * 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package io.fabric8.forge.camel.maven; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import io.fabric8.forge.camel.commands.project.helper.RouteBuilderParser; import io.fabric8.forge.camel.commands.project.helper.XmlRouteParser; import io.fabric8.forge.camel.commands.project.model.CamelEndpointDetails; import org.apache.camel.catalog.CamelCatalog; import org.apache.camel.catalog.DefaultCamelCatalog; import org.apache.camel.catalog.EndpointValidationResult; import org.apache.camel.catalog.lucene.LuceneSuggestionStrategy; import org.apache.maven.model.Resource; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.apache.maven.project.MavenProject; import org.jboss.forge.roaster.Roaster; import org.jboss.forge.roaster.model.JavaType; import org.jboss.forge.roaster.model.source.JavaClassSource; /** * Analyses the project source code for Camel routes, and validates the endpoint uris whether there may be invalid uris. */ @Mojo(name = "validate", defaultPhase = LifecyclePhase.PROCESS_TEST_CLASSES, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) public class EndpointMojo extends AbstractMojo { @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** * Whether to fail if invalid Camel endpoints was found. By default the plugin logs the errors at WARN level */ @Parameter(property = "camel.failOnError", defaultValue = "false", readonly = true, required = false) private boolean failOnError; /** * Whether to include Java files to be validated for invalid Camel endpoints */ @Parameter(property = "camel.includeJava", defaultValue = "true", readonly = true, required = false) private boolean includeJava; /** * Whether to include XML files to be validated for invalid Camel endpoints */ @Parameter(property = "camel.includeXml", defaultValue = "true", readonly = true, required = false) private boolean includeXml; /** * Whether to include test source code */ @Parameter(property = "camel.includeTest", defaultValue = "false", readonly = true, required = false) private boolean includeTest; /** * To filter the names of java and xml files to only include files matching any of the given list of patterns (wildcard and regular expression). * Multiple values can be separated by comma. */ @Parameter(property = "camel.includes", readonly = true, required = false) private String includes; /** * To filter the names of java and xml files to exclude files matching any of the given list of patterns (wildcard and regular expression). * Multiple values can be separated by comma. */ @Parameter(property = "camel.excludes", readonly = true, required = false) private String excludes; @Override public void execute() throws MojoExecutionException, MojoFailureException { CamelCatalog catalog = new DefaultCamelCatalog(); // enable did you mean catalog.setSuggestionStrategy(new LuceneSuggestionStrategy()); List<CamelEndpointDetails> endpoints = new ArrayList<>(); Set<File> javaFiles = new LinkedHashSet<File>(); Set<File> xmlFiles = new LinkedHashSet<File>(); // find all java route builder classes if (includeJava) { for (String dir : project.getCompileSourceRoots()) { findJavaFiles(new File(dir), javaFiles); } if (includeTest) { for (String dir : project.getTestCompileSourceRoots()) { findJavaFiles(new File(dir), javaFiles); } } } // find all xml routes if (includeXml) { for (Resource dir : project.getResources()) { findXmlFiles(new File(dir.getDirectory()), xmlFiles); } if (includeTest) { for (Resource dir : project.getTestResources()) { findXmlFiles(new File(dir.getDirectory()), xmlFiles); } } } for (File file : javaFiles) { if (matchFile(file)) { try { // parse the java source code and find Camel RouteBuilder classes String fqn = file.getPath(); String baseDir = "."; JavaType out = Roaster.parse(file); // we should only parse java classes (not interfaces and enums etc) if (out != null && out instanceof JavaClassSource) { JavaClassSource clazz = (JavaClassSource) out; RouteBuilderParser.parseRouteBuilder(clazz, baseDir, fqn, endpoints); } } catch (Exception e) { getLog().warn("Error parsing java file " + file + " code due " + e.getMessage(), e); } } } for (File file : xmlFiles) { if (matchFile(file)) { try { // parse the xml source code and find Camel routes String fqn = file.getPath(); String baseDir = "."; InputStream is = new FileInputStream(file); XmlRouteParser.parseXmlRoute(is, baseDir, fqn, endpoints); is.close(); } catch (Exception e) { getLog().warn("Error parsing xml file " + file + " code due " + e.getMessage(), e); } } } int errors = 0; for (CamelEndpointDetails detail : endpoints) { EndpointValidationResult result = catalog.validateEndpointProperties(detail.getEndpointUri()); if (!result.isSuccess()) { errors++; StringBuilder sb = new StringBuilder(); sb.append("Endpoint validation error in file: ").append(asRelativeFile(detail.getFileName())); if (detail.getLineNumber() != null) { sb.append(" at line: ").append(detail.getLineNumber()); } sb.append("\n\n"); String out = result.summaryErrorMessage(false); sb.append(out); sb.append("\n\n"); getLog().warn(sb.toString()); } } String summary; if (errors == 0) { int ok = endpoints.size() - errors; summary = String.format("Endpoint validation success: (%s = passed, %s = invalid)", ok, errors); } else { int ok = endpoints.size() - errors; summary = String.format("Endpoint validation error: (%s = passed, %s = invalid)", ok, errors); } if (failOnError && errors > 0) { throw new MojoExecutionException(summary); } if (errors > 0) { getLog().warn(summary); } else { getLog().info(summary); } } private void findJavaFiles(File dir, Set<File> javaFiles) { File[] files = dir.isDirectory() ? dir.listFiles() : null; if (files != null) { for (File file : files) { if (file.getName().endsWith(".java")) { javaFiles.add(file); } else if (file.isDirectory()) { findJavaFiles(file, javaFiles); } } } } private void findXmlFiles(File dir, Set<File> xmlFiles) { File[] files = dir.isDirectory() ? dir.listFiles() : null; if (files != null) { for (File file : files) { if (file.getName().endsWith(".xml")) { xmlFiles.add(file); } else if (file.isDirectory()) { findXmlFiles(file, xmlFiles); } } } } private boolean matchFile(File file) { if (excludes == null && includes == null) { return true; } // exclude take precedence if (excludes != null) { for (String exclude : excludes.split(",")) { exclude = exclude.trim(); // try both with and without directory in the name String fqn = asPackageName(asRelativeFile(file.getAbsolutePath())); boolean match = EndpointHelper.matchPattern(fqn, exclude) || EndpointHelper.matchPattern(file.getName(), exclude); if (match) { return false; } } } // include if (includes != null) { for (String include : includes.split(",")) { include = include.trim(); // try both with and without directory in the name String fqn = asPackageName(asRelativeFile(file.getAbsolutePath())); boolean match = EndpointHelper.matchPattern(fqn, include) || EndpointHelper.matchPattern(file.getName(), include); if (match) { return true; } } // did not match any includes return false; } // was not excluded nor failed include so its accepted return true; } private String asRelativeFile(String name) { String answer = name; String base = project.getBasedir().getAbsolutePath(); if (name.startsWith(base)) { answer = name.substring(base.length()); // skip leading slash for relative path if (answer.startsWith(File.separator)) { answer = answer.substring(1); } } return answer; } private String asPackageName(String name) { // strip out any leading source / resource directory for (String dir : project.getCompileSourceRoots()) { dir = asRelativeFile(dir); if (name.startsWith(dir)) { return name.substring(dir.length() + 1); } } for (String dir : project.getTestCompileSourceRoots()) { dir = asRelativeFile(dir); if (name.startsWith(dir)) { return name.substring(dir.length() + 1); } } for (Resource resource : project.getResources()) { String dir = asRelativeFile(resource.getDirectory()); if (name.startsWith(dir)) { return name.substring(dir.length() + 1); } } for (Resource resource : project.getTestResources()) { String dir = asRelativeFile(resource.getDirectory()); if (name.startsWith(dir)) { return name.substring(dir.length() + 1); } } return name; } }
#5411: Lic header
forge/addons/camel-maven-plugin/src/main/java/io/fabric8/forge/camel/maven/EndpointMojo.java
#5411: Lic header
<ide><path>orge/addons/camel-maven-plugin/src/main/java/io/fabric8/forge/camel/maven/EndpointMojo.java <ide> /** <del> * Copyright 2005-2015 Red Hat, Inc. <del> * <p/> <del> * Red Hat licenses this file to you under the Apache License, version <del> * 2.0 (the "License"); you may not use this file except in compliance <del> * with the License. You may obtain a copy of the License at <del> * <p/> <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <p/> <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or <del> * implied. See the License for the specific language governing <del> * permissions and limitations under the License. <add> * Copyright 2005-2015 Red Hat, Inc. <add> * <add> * Red Hat licenses this file to you under the Apache License, version <add> * 2.0 (the "License"); you may not use this file except in compliance <add> * with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or <add> * implied. See the License for the specific language governing <add> * permissions and limitations under the License. <ide> */ <ide> package io.fabric8.forge.camel.maven; <ide>
JavaScript
mit
60e8a81231c6224c420888c6fe89c45497244bfa
0
hubcivico/civicBot
/** * PublicController * * @description :: Server-side logic for managing public * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ var moment = require('moment'); module.exports = { getContributionList: function (req, res) { Classify.find({published: true}).populate(['label', 'party', 'location', 'media']).exec(function(ko, contributions){ if(ko){ res.serverError(ko); } else if(contributions){ res.ok(contributions); } }); }, //CHECKED! getTotalContributions: function (req, res) { Classify.count({published: true}).exec(function(ko, count){ if(ko){ res.serverError(ko); } res.ok({count: count}); }) }, //CHECKED! getTotalActiveUsers: function (req, res) { Users.count().exec(function(ko, count){ if(ko){ res.serverError(ko); } res.ok({count: count}); }) }, //CHECKED! getContribByCategory: function (req, res) { statistics.getStatistics("A").then( function(sumA){ statistics.getStatistics("B").then( function(sumB){ statistics.getStatistics("C").then( function(sumC){ statistics.getStatistics("D").then( function(sumD){ statistics.getStatistics("E").then( function(sumE){ statistics.getStatistics("F").then( function(sumF){ statistics.getStatistics("G").then( function(sumG){ statistics.getStatistics("H").then( function(sumH){ var response = { A: { count: sumA, cat: "Cultura" }, B: { count: sumB, cat: "Economía" }, C: { count: sumC, cat: "Educación" }, D: { count: sumD, cat: "Medio Ambiente" }, E: { count: sumE, cat: "Medios de Comunicación" }, F: { count: sumF, cat: "Política" }, G: { count: sumG, cat: "Sanidad" }, H: { count: sumH, cat: "Otros Temas" } }; res.ok(response); } ) } ) } ) } ) } ) } ) } ) } ) }, //CHECKED! getTotalReceivedMsg: function (req, res) { Classify.count({type: 2}).exec(function (ko, count){ if(ko){ res.serverError(ko); } sails.log.info("COUNT: "+JSON.stringify(count)); res.ok({count: count}); }) }, //CHECKED! getTotalReceivedImg: function (req, res) { Classify.count({type: 1}).exec(function (ko, count){ if(ko){ res.serverError(ko); } res.ok({count: count}); }) }, //CHECKED! getTodayContribNum: function (req, res) { var now = moment(); var nowDay = now.date(); var nowMonth = now.month()+1; var nowYear = now.year(); var future = now.add(1, 'days'); var futureDay = future.date(); var futureMonth = future.month()+1; var futureYear = now.year(); var today = new Date(nowYear+'-'+nowMonth+'-'+nowDay); var tomorrow = new Date (futureYear+'-'+futureMonth+'-'+futureDay); Classify.count({createdAt:{'>=': today, '<': tomorrow } }).exec(function(ko, count){ if(ko){ res.serverError(ko); } res.ok({count: count}); }) }, getTopParties: function (req, res) { TopParties.find().populate('party').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); /* Party.count().exec(function(err, count){ Classify.find({published: true}).populate('party').exec(function(err, contributions){ var partyCount = Array.apply(null, Array(count+1)).map(Number.prototype.valueOf,0); for(var i=0; i<contributions.length; i++){ partyCount[contributions[i].party.id]++; } var index1 = partyCount.indexOf(Math.max.apply(Math, partyCount)); var count1 = partyCount[index1]; partyCount[index1]=0; var index2 = partyCount.indexOf(Math.max.apply(Math, partyCount)); var count2 = partyCount[index2]; if(index2 == 0){ index2 = index1; count2 = count1; } Party.findOne({id: index1}).exec(function(ko, party1){ if(ko){ res.serverError(ko); } else if(party1){ var p1 = party1; Party.findOne({id: index2}).exec(function(ko, party2){ if(ko){ res.serverError(ko); } else if(party2){ var p2=party2; var result = []; result.push({id: p1.id, party: p1.party, count: count1}); result.push({id: p2.id, party: p2.party, count: count2}); res.ok(result); } }) } }) }) }); */ }, getTopLocations: function (req, res) { TopLocations.find().populate('location').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); }, getTopMedia: function (req, res) { TopMedia.find().populate('media').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); }, getTopPartiesByMonth: function (req, res) { //TODO: HARDCODED TopParties.find().populate('party').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); }, getTopLocationsByMonth: function (req, res) { //TODO: HARDCODED TopLocations.find().populate('location').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); }, getTopCategoryByMonth: function (req, res) { //TODO: HARDCODED statistics.getStatistics("A").then( function(sumA){ statistics.getStatistics("B").then( function(sumB){ statistics.getStatistics("C").then( function(sumC){ statistics.getStatistics("D").then( function(sumD){ statistics.getStatistics("E").then( function(sumE){ statistics.getStatistics("F").then( function(sumF){ statistics.getStatistics("G").then( function(sumG){ statistics.getStatistics("H").then( function(sumH){ var response = { A: { count: sumA, cat: "Cultura" }, B: { count: sumB, cat: "Economía" }, C: { count: sumC, cat: "Educación" }, D: { count: sumD, cat: "Medio Ambiente" }, E: { count: sumE, cat: "Medios de Comunicación" }, F: { count: sumF, cat: "Política" }, G: { count: sumG, cat: "Sanidad" }, H: { count: sumH, cat: "Otros Temas" } }; res.ok(response); } ) } ) } ) } ) } ) } ) } ) } ) }, getTopMediaByMonth: function (req, res) { //TODO: HARDCODED TopMedia.find().populate('media').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); } };
api/controllers/PublicController.js
/** * PublicController * * @description :: Server-side logic for managing public * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ var moment = require('moment'); module.exports = { getContributionList: function (req, res) { Classify.find({published: true}).populate(['label', 'party', 'location', 'media']).exec(function(ko, contributions){ if(ko){ res.serverError(ko); } else if(contributions){ res.ok(contributions); } }); }, //CHECKED! getTotalContributions: function (req, res) { Classify.count({published: true}).exec(function(ko, count){ if(ko){ res.serverError(ko); } res.ok({count: count}); }) }, //CHECKED! getTotalActiveUsers: function (req, res) { Users.count().exec(function(ko, count){ if(ko){ res.serverError(ko); } res.ok({count: count}); }) }, //CHECKED! getContribByCategory: function (req, res) { statistics.getStatistics("A").then( function(sumA){ statistics.getStatistics("B").then( function(sumB){ statistics.getStatistics("C").then( function(sumC){ statistics.getStatistics("D").then( function(sumD){ statistics.getStatistics("E").then( function(sumE){ statistics.getStatistics("F").then( function(sumF){ statistics.getStatistics("G").then( function(sumG){ statistics.getStatistics("H").then( function(sumH){ var response = { A: { count: sumA, cat: "Cultura" }, B: { count: sumB, cat: "Economía" }, C: { count: sumC, cat: "Educación" }, D: { count: sumD, cat: "Medio Ambiente" }, E: { count: sumE, cat: "Medios de Comunicación" }, F: { count: sumF, cat: "Política" }, G: { count: sumG, cat: "Sanidad" }, H: { count: sumH, cat: "Otros Temas" } }; res.ok(response); } ) } ) } ) } ) } ) } ) } ) } ) }, //CHECKED! getTotalReceivedMsg: function (req, res) { Classify.count({type: 2}).exec(function (ko, count){ if(ko){ res.serverError(ko); } sails.log.info("COUNT: "+JSON.stringify(count)); res.ok({count: count}); }) }, getTotalReceivedImg: function (req, res) { Classify.count({type: 1}).exec(function (ko, count){ if(ko){ res.serverError(ko); } res.ok({count: count}); }) }, getTodayContribNum: function (req, res) { var now = moment(); var nowDay = now.date(); var nowMonth = now.month()+1; var nowYear = now.year(); var future = now.add(1, 'days'); var futureDay = future.date(); var futureMonth = future.month()+1; var futureYear = now.year(); var today = new Date(nowYear+'-'+nowMonth+'-'+nowDay); var tomorrow = new Date (futureYear+'-'+futureMonth+'-'+futureDay); Classify.count({createdAt:{'>=': today, '<': tomorrow } }).exec(function(ko, count){ if(ko){ res.serverError(ko); } res.ok({count: count}); }) }, getTopParties: function (req, res) { TopParties.find().populate('party').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); /* Party.count().exec(function(err, count){ Classify.find({published: true}).populate('party').exec(function(err, contributions){ var partyCount = Array.apply(null, Array(count+1)).map(Number.prototype.valueOf,0); for(var i=0; i<contributions.length; i++){ partyCount[contributions[i].party.id]++; } var index1 = partyCount.indexOf(Math.max.apply(Math, partyCount)); var count1 = partyCount[index1]; partyCount[index1]=0; var index2 = partyCount.indexOf(Math.max.apply(Math, partyCount)); var count2 = partyCount[index2]; if(index2 == 0){ index2 = index1; count2 = count1; } Party.findOne({id: index1}).exec(function(ko, party1){ if(ko){ res.serverError(ko); } else if(party1){ var p1 = party1; Party.findOne({id: index2}).exec(function(ko, party2){ if(ko){ res.serverError(ko); } else if(party2){ var p2=party2; var result = []; result.push({id: p1.id, party: p1.party, count: count1}); result.push({id: p2.id, party: p2.party, count: count2}); res.ok(result); } }) } }) }) }); */ }, getTopLocations: function (req, res) { TopLocations.find().populate('location').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); }, getTopMedia: function (req, res) { TopMedia.find().populate('media').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); }, getTopPartiesByMonth: function (req, res) { //TODO: HARDCODED TopParties.find().populate('party').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); }, getTopLocationsByMonth: function (req, res) { //TODO: HARDCODED TopLocations.find().populate('location').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); }, getTopCategoryByMonth: function (req, res) { //TODO: HARDCODED statistics.getStatistics(1).then( function(sumA){ statistics.getStatistics(2).then( function(sumB){ statistics.getStatistics(3).then( function(sumC){ statistics.getStatistics(4).then( function(sumD){ statistics.getStatistics(5).then( function(sumE){ statistics.getStatistics(6).then( function(sumF){ statistics.getStatistics(7).then( function(sumG){ statistics.getStatistics(8).then( function(sumH){ var response = { A: { count: sumA, cat: "Cultura" }, B: { count: sumB, cat: "Economía" }, C: { count: sumC, cat: "Educación" }, D: { count: sumD, cat: "Medio Ambiente" }, E: { count: sumE, cat: "Medios de Comunicación" }, F: { count: sumF, cat: "Política" }, G: { count: sumG, cat: "Sanidad" }, H: { count: sumH, cat: "Otros Temas" } }; res.ok(response); } ) } ) } ) } ) } ) } ) } ) } ) }, getTopMediaByMonth: function (req, res) { //TODO: HARDCODED TopMedia.find().populate('media').exec(function (ko, ok){ if(ko){ res.serverError(ko); }else if(ok){ res.ok(ok); } }); } };
Final migration to MongoDB
api/controllers/PublicController.js
Final migration to MongoDB
<ide><path>pi/controllers/PublicController.js <ide> <ide> }) <ide> <del> }, <add> }, //CHECKED! <ide> <ide> getTotalReceivedImg: function (req, res) { <ide> Classify.count({type: 1}).exec(function (ko, count){ <ide> <ide> }) <ide> <del> }, <add> }, //CHECKED! <ide> <ide> getTodayContribNum: function (req, res) { <ide> var now = moment(); <ide> <ide> getTopCategoryByMonth: function (req, res) { <ide> //TODO: HARDCODED <del> statistics.getStatistics(1).then( <add> statistics.getStatistics("A").then( <ide> function(sumA){ <del> statistics.getStatistics(2).then( <add> statistics.getStatistics("B").then( <ide> function(sumB){ <del> statistics.getStatistics(3).then( <add> statistics.getStatistics("C").then( <ide> function(sumC){ <del> statistics.getStatistics(4).then( <add> statistics.getStatistics("D").then( <ide> function(sumD){ <del> statistics.getStatistics(5).then( <add> statistics.getStatistics("E").then( <ide> function(sumE){ <del> statistics.getStatistics(6).then( <add> statistics.getStatistics("F").then( <ide> function(sumF){ <del> statistics.getStatistics(7).then( <add> statistics.getStatistics("G").then( <ide> function(sumG){ <del> statistics.getStatistics(8).then( <add> statistics.getStatistics("H").then( <ide> function(sumH){ <ide> var response = { <ide> A: {
Java
bsd-2-clause
20dd14ec83fbf5659e7e2aa865a9981ba0ba7371
0
TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2014 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package imagej.module; import imagej.module.process.ModulePostprocessor; import imagej.module.process.ModulePreprocessor; import imagej.module.process.PostprocessorPlugin; import imagej.module.process.PreprocessorPlugin; import imagej.service.ImageJService; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import org.scijava.Prioritized; import org.scijava.input.Accelerator; /** * Interface for service that tracks and executes available modules. * <p> * The module service keeps a master index of all modules known to the system. * At heart, a module is a {@link Runnable} piece of code, but with explicit * typed input and output parameters. * </p> * <p> * The module service has no innate ability to discover modules, and must be * explicitly told about them via the {@link #addModule} and {@link #addModules} * methods. * </p> * <p> * A <em>module</em> is distinct from a <em>plugin</em> in that plugins extend * ImageJ's functionality in some way, taking many forms, whereas modules are * always runnable code with typed inputs and outputs. There is a particular * type of plugin called a {@link imagej.command.Command} which is also a * module, but many plugins (e.g., {@link imagej.tool.Tool}s and * {@link imagej.display.Display}s) are not modules. * </p> * * @author Curtis Rueden * @see Module * @see org.scijava.plugin.PluginService */ public interface ModuleService extends ImageJService { /** Gets the index of available modules. */ ModuleIndex getIndex(); /** Manually registers a module with the module service. */ void addModule(ModuleInfo module); /** Manually unregisters a module with the module service. */ void removeModule(ModuleInfo module); /** Manually registers a list of modules with the module service. */ void addModules(Collection<? extends ModuleInfo> modules); /** Manually unregisters a list of modules with the module service. */ void removeModules(Collection<? extends ModuleInfo> modules); /** Gets the list of available modules. */ List<ModuleInfo> getModules(); /** * Gets the module for a given keyboard shortcut. * * @param acc the accelerator for which to search. * @return the module info for the corresponding module, or null. */ ModuleInfo getModuleForAccelerator(Accelerator acc); /** * Creates an instance of the given module. * <p> * If the module implements the {@link org.scijava.Contextual} interface, the * appropriate context is injected. Similarly, if the module implements the * {@link Prioritized} interface, the appropriate priority is injected. * </p> * <p> * Note that in the case of commands, this method does <em>not</em> do any * preprocessing on the command instances, so parameters will not be * auto-populated, initializers will not be executed, etc. * </p> */ Module createModule(ModuleInfo info); /** * Executes the given module. * * @param info The module to instantiate and run. * @param process If true, executes the module with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the module with no pre- or postprocessing. * @param inputs List of input parameter names and values. The expected order * is in pairs: an input name followed by its value, for each desired * input to populate. Leaving some inputs unpopulated is allowed. * Passing the name of an input that is not valid for the module, or * passing a value of a type incompatible with the associated input * parameter, will issue an error and ignore that name/value pair. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<Module> run(ModuleInfo info, boolean process, Object... inputs); /** * Executes the given module. * * @param info The module to instantiate and run. * @param process If true, executes the module with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the module with no pre- or postprocessing. * @param inputMap Table of input parameter values, with keys matching the * {@link ModuleInfo}'s input parameter names. Passing a value of a * type incompatible with the associated input parameter will issue * an error and ignore that value. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<Module> run(ModuleInfo info, boolean process, Map<String, Object> inputMap); /** * Executes the given module. * * @param info The module to instantiate and run. * @param pre List of preprocessing steps to perform. * @param post List of postprocessing steps to perform. * @param inputs List of input parameter names and values. The expected order * is in pairs: an input name followed by its value, for each desired * input to populate. Leaving some inputs unpopulated is allowed. * Passing the name of an input that is not valid for the module, or * passing a value of a type incompatible with the associated input * parameter, will issue an error and ignore that name/value pair. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<Module> run(ModuleInfo info, List<? extends ModulePreprocessor> pre, List<? extends ModulePostprocessor> post, Object... inputs); /** * Executes the given module. * * @param info The module to instantiate and run. * @param pre List of preprocessing steps to perform. * @param post List of postprocessing steps to perform. * @param inputMap Table of input parameter values, with keys matching the * {@link ModuleInfo}'s input parameter names. Passing a value of a * type incompatible with the associated input parameter will issue * an error and ignore that value. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<Module> run(ModuleInfo info, List<? extends ModulePreprocessor> pre, List<? extends ModulePostprocessor> post, Map<String, Object> inputMap); /** * Executes the given module. * * @param module The module to run. * @param process If true, executes the module with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the module with no pre- or postprocessing. * @param inputs List of input parameter names and values. The expected order * is in pairs: an input name followed by its value, for each desired * input to populate. Leaving some inputs unpopulated is allowed. * Passing the name of an input that is not valid for the module, or * passing a value of a type incompatible with the associated input * parameter, will issue an error and ignore that name/value pair. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ <M extends Module> Future<M> run(M module, boolean process, Object... inputs); /** * Executes the given module. * * @param module The module to run. * @param process If true, executes the module with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the module with no pre- or postprocessing. * @param inputMap Table of input parameter values, with keys matching the * {@link ModuleInfo}'s input parameter names. Passing a value of a * type incompatible with the associated input parameter will issue * an error and ignore that value. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ <M extends Module> Future<M> run(M module, boolean process, Map<String, Object> inputMap); /** * Executes the given module. * * @param module The module to run. * @param pre List of preprocessing steps to perform. * @param post List of postprocessing steps to perform. * @param inputs List of input parameter names and values. The expected order * is in pairs: an input name followed by its value, for each desired * input to populate. Leaving some inputs unpopulated is allowed. * Passing the name of an input that is not valid for the module, or * passing a value of a type incompatible with the associated input * parameter, will issue an error and ignore that name/value pair. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ <M extends Module> Future<M> run(M module, List<? extends ModulePreprocessor> pre, List<? extends ModulePostprocessor> post, Object... inputs); /** * Executes the given module. * * @param module The module to run. * @param pre List of preprocessing steps to perform. * @param post List of postprocessing steps to perform. * @param inputMap Table of input parameter values, with keys matching the * module's {@link ModuleInfo}'s input parameter names. Passing a * value of a type incompatible with the associated input parameter * will issue an error and ignore that value. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ <M extends Module> Future<M> run(M module, List<? extends ModulePreprocessor> pre, List<? extends ModulePostprocessor> post, Map<String, Object> inputMap); /** Blocks until the given module is finished executing. */ <M extends Module> M waitFor(Future<M> future); /** * Checks the given module for a solitary unresolved input of the given type, * returning the relevant {@link ModuleItem} if found, or null if not exactly * one unresolved input of that type. */ <T> ModuleItem<T> getSingleInput(Module module, Class<T> type); /** * Checks the given module for a solitary unresolved output of the given type, * returning the relevant {@link ModuleItem} if found, or null if not exactly * one unresolved output of that type. */ <T> ModuleItem<T> getSingleOutput(Module module, Class<T> type); }
core/core/src/main/java/imagej/module/ModuleService.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2014 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package imagej.module; import imagej.module.process.ModulePostprocessor; import imagej.module.process.ModulePreprocessor; import imagej.module.process.PostprocessorPlugin; import imagej.module.process.PreprocessorPlugin; import imagej.service.ImageJService; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import org.scijava.input.Accelerator; /** * Interface for service that tracks and executes available modules. * <p> * The module service keeps a master index of all modules known to the system. * At heart, a module is a {@link Runnable} piece of code, but with explicit * typed input and output parameters. * </p> * <p> * The module service has no innate ability to discover modules, and must be * explicitly told about them via the {@link #addModule} and {@link #addModules} * methods. * </p> * <p> * A <em>module</em> is distinct from a <em>plugin</em> in that plugins extend * ImageJ's functionality in some way, taking many forms, whereas modules are * always runnable code with typed inputs and outputs. There is a particular * type of plugin called a {@link imagej.command.Command} which is also a * module, but many plugins (e.g., {@link imagej.tool.Tool}s and * {@link imagej.display.Display}s) are not modules. * </p> * * @author Curtis Rueden * @see Module * @see org.scijava.plugin.PluginService */ public interface ModuleService extends ImageJService { /** Gets the index of available modules. */ ModuleIndex getIndex(); /** Manually registers a module with the module service. */ void addModule(ModuleInfo module); /** Manually unregisters a module with the module service. */ void removeModule(ModuleInfo module); /** Manually registers a list of modules with the module service. */ void addModules(Collection<? extends ModuleInfo> modules); /** Manually unregisters a list of modules with the module service. */ void removeModules(Collection<? extends ModuleInfo> modules); /** Gets the list of available modules. */ List<ModuleInfo> getModules(); /** * Gets the module for a given keyboard shortcut. * * @param acc the accelerator for which to search. * @return the module info for the corresponding module, or null. */ ModuleInfo getModuleForAccelerator(Accelerator acc); /** * Creates an instance of the given module. * <p> * If the module implements the {@link org.scijava.Contextual} interface, the * appropriate context is injected. Similarly, if the module implements the * {@link org.scijava.Prioritized} interface, the appropriate priority is injected. * </p> * <p> * Note that in the case of commands, this method does <em>not</em> do any * preprocessing on the command instances, so parameters will not be * auto-populated, initializers will not be executed, etc. * </p> */ Module createModule(ModuleInfo info); /** * Executes the given module. * * @param info The module to instantiate and run. * @param process If true, executes the module with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the module with no pre- or postprocessing. * @param inputs List of input parameter names and values. The expected order * is in pairs: an input name followed by its value, for each desired * input to populate. Leaving some inputs unpopulated is allowed. * Passing the name of an input that is not valid for the module, or * passing a value of a type incompatible with the associated input * parameter, will issue an error and ignore that name/value pair. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<Module> run(ModuleInfo info, boolean process, Object... inputs); /** * Executes the given module. * * @param info The module to instantiate and run. * @param process If true, executes the module with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the module with no pre- or postprocessing. * @param inputMap Table of input parameter values, with keys matching the * {@link ModuleInfo}'s input parameter names. Passing a value of a * type incompatible with the associated input parameter will issue * an error and ignore that value. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<Module> run(ModuleInfo info, boolean process, Map<String, Object> inputMap); /** * Executes the given module. * * @param info The module to instantiate and run. * @param pre List of preprocessing steps to perform. * @param post List of postprocessing steps to perform. * @param inputs List of input parameter names and values. The expected order * is in pairs: an input name followed by its value, for each desired * input to populate. Leaving some inputs unpopulated is allowed. * Passing the name of an input that is not valid for the module, or * passing a value of a type incompatible with the associated input * parameter, will issue an error and ignore that name/value pair. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<Module> run(ModuleInfo info, List<? extends ModulePreprocessor> pre, List<? extends ModulePostprocessor> post, Object... inputs); /** * Executes the given module. * * @param info The module to instantiate and run. * @param pre List of preprocessing steps to perform. * @param post List of postprocessing steps to perform. * @param inputMap Table of input parameter values, with keys matching the * {@link ModuleInfo}'s input parameter names. Passing a value of a * type incompatible with the associated input parameter will issue * an error and ignore that value. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ Future<Module> run(ModuleInfo info, List<? extends ModulePreprocessor> pre, List<? extends ModulePostprocessor> post, Map<String, Object> inputMap); /** * Executes the given module. * * @param module The module to run. * @param process If true, executes the module with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the module with no pre- or postprocessing. * @param inputs List of input parameter names and values. The expected order * is in pairs: an input name followed by its value, for each desired * input to populate. Leaving some inputs unpopulated is allowed. * Passing the name of an input that is not valid for the module, or * passing a value of a type incompatible with the associated input * parameter, will issue an error and ignore that name/value pair. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ <M extends Module> Future<M> run(M module, boolean process, Object... inputs); /** * Executes the given module. * * @param module The module to run. * @param process If true, executes the module with pre- and postprocessing * steps from all available {@link PreprocessorPlugin}s and * {@link PostprocessorPlugin}s in the plugin index; if false, * executes the module with no pre- or postprocessing. * @param inputMap Table of input parameter values, with keys matching the * {@link ModuleInfo}'s input parameter names. Passing a value of a * type incompatible with the associated input parameter will issue * an error and ignore that value. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ <M extends Module> Future<M> run(M module, boolean process, Map<String, Object> inputMap); /** * Executes the given module. * * @param module The module to run. * @param pre List of preprocessing steps to perform. * @param post List of postprocessing steps to perform. * @param inputs List of input parameter names and values. The expected order * is in pairs: an input name followed by its value, for each desired * input to populate. Leaving some inputs unpopulated is allowed. * Passing the name of an input that is not valid for the module, or * passing a value of a type incompatible with the associated input * parameter, will issue an error and ignore that name/value pair. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ <M extends Module> Future<M> run(M module, List<? extends ModulePreprocessor> pre, List<? extends ModulePostprocessor> post, Object... inputs); /** * Executes the given module. * * @param module The module to run. * @param pre List of preprocessing steps to perform. * @param post List of postprocessing steps to perform. * @param inputMap Table of input parameter values, with keys matching the * module's {@link ModuleInfo}'s input parameter names. Passing a * value of a type incompatible with the associated input parameter * will issue an error and ignore that value. * @return {@link Future} of the module instance being executed. Calling * {@link Future#get()} will block until execution is complete. */ <M extends Module> Future<M> run(M module, List<? extends ModulePreprocessor> pre, List<? extends ModulePostprocessor> post, Map<String, Object> inputMap); /** Blocks until the given module is finished executing. */ <M extends Module> M waitFor(Future<M> future); /** * Checks the given module for a solitary unresolved input of the given type, * returning the relevant {@link ModuleItem} if found, or null if not exactly * one unresolved input of that type. */ <T> ModuleItem<T> getSingleInput(Module module, Class<T> type); /** * Checks the given module for a solitary unresolved output of the given type, * returning the relevant {@link ModuleItem} if found, or null if not exactly * one unresolved output of that type. */ <T> ModuleItem<T> getSingleOutput(Module module, Class<T> type); }
ModuleService: tweak javadoc
core/core/src/main/java/imagej/module/ModuleService.java
ModuleService: tweak javadoc
<ide><path>ore/core/src/main/java/imagej/module/ModuleService.java <ide> import java.util.Map; <ide> import java.util.concurrent.Future; <ide> <add>import org.scijava.Prioritized; <ide> import org.scijava.input.Accelerator; <ide> <ide> /** <ide> * <p> <ide> * If the module implements the {@link org.scijava.Contextual} interface, the <ide> * appropriate context is injected. Similarly, if the module implements the <del> * {@link org.scijava.Prioritized} interface, the appropriate priority is injected. <add> * {@link Prioritized} interface, the appropriate priority is injected. <ide> * </p> <ide> * <p> <ide> * Note that in the case of commands, this method does <em>not</em> do any
JavaScript
mit
82d7d1fed5e90c69958f0feaf6d2fd1cbb2a5b09
0
terafin/mqtt-rules,terafin/mqtt-rules
const express = require('express') const _ = require('lodash') const logging = require('homeautomation-js-lib/logging.js') const utilities = require('./utilities.js') const moment = require('moment-timezone') const TIMEZONE = utilities.getCurrentTimeZone() const loader = require('./loading.js') require('homeautomation-js-lib/devices.js') var rules = null const port = process.env.API_PORT if (!_.isNil(port)) { // Express const app = express() app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*') res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') next() }) app.get('/reload/', function(req, res) { loader.reload() res.send('OK') }) app.get('/json/', function(req, res) { if (_.isNil(rules)) { res.send('[]') return } res.send(JSON.stringify(rules.get_configs())) }) app.get('/history-json/', function(req, res) { const history = global.getRuleHistory() if (_.isNil(history)) { res.send('[]') return } res.send(JSON.stringify(history)) }) app.get('/history/', function(req, res) { const history = global.getRuleHistory() if (_.isNil(history)) { res.send('[]') return } var historyHTML = '' historyHTML += '<!DOCTYPE html>' historyHTML += '<html>' historyHTML += '<head>' historyHTML += '<style>' historyHTML += 'table {' historyHTML += ' font-family: arial, sans-serif;' historyHTML += ' border-collapse: collapse;' historyHTML += ' width: 100%;' historyHTML += ' }' historyHTML += ' ' historyHTML += ' td, th {' historyHTML += ' border: 1px solid #dddddd;' historyHTML += ' text-align: left;' historyHTML += ' padding: 8px;' historyHTML += ' }' historyHTML += ' ' historyHTML += ' tr:nth-child(even) {' historyHTML += ' background-color: #dddddd;' historyHTML += ' }' historyHTML += '</style>' historyHTML += '</head>' historyHTML += '<body>' // "date": 1550355690, // "rule_name": "climate_venstar_venstar_home_away_mode", // "expression": "", // "valueOrExpression": "(/presence/home/elene > 0) ? 'auto' : 'off'", // "result": true, // "topic": "/environment/thermostat/study/mode/set", // "message": "off", // "options": { // "retain": false, // "qos": 2 // } historyHTML += '<table style="width:100%">' historyHTML += ' <tr>' historyHTML += ' <th>Action Date</th>' historyHTML += ' <th>Rule</th> ' historyHTML += ' <th>Trigger</th> ' historyHTML += ' <th>Message</th> ' historyHTML += ' <th>Trigger Date</th>' historyHTML += ' <th>Expression</th>' historyHTML += ' <th>Value or Expression</th>' historyHTML += ' <th>Result</th>' historyHTML += ' <th>Topic</th>' historyHTML += ' <th>Message</th>' historyHTML += ' <th>Options</th>' historyHTML += ' </tr>' history.forEach(item => { historyHTML += ' <tr>' historyHTML += ' <th>' + moment.unix(item.date).tz(TIMEZONE).format('DD.MM.YY-HH:mm:ss') + '</th>' historyHTML += ' <th>' + item.rule_name + '</th> ' historyHTML += ' <th>' + item.evaluate_job_data.reason + '</th> ' historyHTML += ' <th>' + item.evaluate_job_data.context_value[utilities.update_topic_for_expression(item.evaluate_job_data.topic)] + '</th> ' historyHTML += ' <th>' + moment.unix(item.evaluate_job_data.context_value.TRIGGER_TIME_UNIX).tz(TIMEZONE).format('DD.MM.YY-HH:mm:ss') + '</th>' if ( _.isNil(item.evaluate_job_data.rule.when) ) { historyHTML += ' <th></th>' } else { historyHTML += ' <th>' + item.evaluate_job_data.rule.when + '</th>' } historyHTML += ' <th>' + item.valueOrExpression + '</th>' historyHTML += ' <th>' + item.result + '</th>' historyHTML += ' <th>' + item.topic + '</th>' historyHTML += ' <th>' + item.message + '</th>' historyHTML += ' <th>' + JSON.stringify(item.options) + '</th>' historyHTML += ' </tr>' }) historyHTML += '</table>' historyHTML += '</body>' historyHTML += '</html>' res.send(historyHTML) }) app.listen(port, function() { logging.info('Rules API listening on port: ' + port) }) exports.updateRules = function(newRules) { rules = newRules } }
lib/api.js
const express = require('express') const _ = require('lodash') const logging = require('homeautomation-js-lib/logging.js') const utilities = require('./utilities.js') const moment = require('moment-timezone') const TIMEZONE = utilities.getCurrentTimeZone() const loader = require('./loading.js') require('homeautomation-js-lib/devices.js') var rules = null const port = process.env.API_PORT if (!_.isNil(port)) { // Express const app = express() app.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*') res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') next() }) app.get('/reload/', function(req, res) { loader.reload() res.send('OK') }) app.get('/json/', function(req, res) { if (_.isNil(rules)) { res.send('[]') return } res.send(JSON.stringify(rules.get_configs())) }) app.get('/history-json/', function(req, res) { const history = global.getRuleHistory() if (_.isNil(history)) { res.send('[]') return } res.send(JSON.stringify(history)) }) app.get('/history/', function(req, res) { const history = global.getRuleHistory() if (_.isNil(history)) { res.send('[]') return } var historyHTML = '' historyHTML += '<!DOCTYPE html>' historyHTML += '<html>' historyHTML += '<head>' historyHTML += '<style>' historyHTML += 'table {' historyHTML += ' font-family: arial, sans-serif;' historyHTML += ' border-collapse: collapse;' historyHTML += ' width: 100%;' historyHTML += ' }' historyHTML += ' ' historyHTML += ' td, th {' historyHTML += ' border: 1px solid #dddddd;' historyHTML += ' text-align: left;' historyHTML += ' padding: 8px;' historyHTML += ' }' historyHTML += ' ' historyHTML += ' tr:nth-child(even) {' historyHTML += ' background-color: #dddddd;' historyHTML += ' }' historyHTML += '</style>' historyHTML += '</head>' historyHTML += '<body>' // "date": 1550355690, // "rule_name": "climate_venstar_venstar_home_away_mode", // "expression": "", // "valueOrExpression": "(/presence/home/elene > 0) ? 'auto' : 'off'", // "result": true, // "topic": "/environment/thermostat/study/mode/set", // "message": "off", // "options": { // "retain": false, // "qos": 2 // } historyHTML += '<table style="width:100%">' historyHTML += ' <tr>' historyHTML += ' <th>Action Date</th>' historyHTML += ' <th>Rule</th> ' historyHTML += ' <th>Trigger</th> ' historyHTML += ' <th>Message</th> ' historyHTML += ' <th>Trigger Date</th>' historyHTML += ' <th>Expression</th>' historyHTML += ' <th>Value or Expression</th>' historyHTML += ' <th>Result</th>' historyHTML += ' <th>Topic</th>' historyHTML += ' <th>Message</th>' historyHTML += ' <th>Options</th>' historyHTML += ' </tr>' history.forEach(item => { historyHTML += ' <tr>' historyHTML += ' <th>' + moment.unix(item.date).tz(TIMEZONE).format('DD.MM.YY-HH:mm:ss') + '</th>' historyHTML += ' <th>' + item.rule_name + '</th> ' historyHTML += ' <th>' + item.evaluate_job_data.reason + '</th> ' historyHTML += ' <th>' + item.evaluate_job_data.context_value[utilities.update_topic_for_expression(item.evaluate_job_data.topic)] + '</th> ' historyHTML += ' <th>' + moment.unix(item.evaluate_job_data.context_value.TRIGGER_TIME_UNIX).tz(TIMEZONE).format('DD.MM.YY-HH:mm:ss') + '</th>' historyHTML += ' <th>' + item.when + '</th>' historyHTML += ' <th>' + item.valueOrExpression + '</th>' historyHTML += ' <th>' + item.result + '</th>' historyHTML += ' <th>' + item.topic + '</th>' historyHTML += ' <th>' + item.message + '</th>' historyHTML += ' <th>' + JSON.stringify(item.options) + '</th>' historyHTML += ' </tr>' }) historyHTML += '</table>' historyHTML += '</body>' historyHTML += '</html>' res.send(historyHTML) }) app.listen(port, function() { logging.info('Rules API listening on port: ' + port) }) exports.updateRules = function(newRules) { rules = newRules } }
Cleaning up the history here
lib/api.js
Cleaning up the history here
<ide><path>ib/api.js <ide> historyHTML += ' <th>' + item.evaluate_job_data.reason + '</th> ' <ide> historyHTML += ' <th>' + item.evaluate_job_data.context_value[utilities.update_topic_for_expression(item.evaluate_job_data.topic)] + '</th> ' <ide> historyHTML += ' <th>' + moment.unix(item.evaluate_job_data.context_value.TRIGGER_TIME_UNIX).tz(TIMEZONE).format('DD.MM.YY-HH:mm:ss') + '</th>' <del> historyHTML += ' <th>' + item.when + '</th>' <add> if ( _.isNil(item.evaluate_job_data.rule.when) ) { <add> historyHTML += ' <th></th>' <add> } else { <add> historyHTML += ' <th>' + item.evaluate_job_data.rule.when + '</th>' <add> <add> } <ide> historyHTML += ' <th>' + item.valueOrExpression + '</th>' <ide> historyHTML += ' <th>' + item.result + '</th>' <ide> historyHTML += ' <th>' + item.topic + '</th>'
Java
apache-2.0
aa5dc66e079f6a03679512bf9cbe95f0e9c55819
0
realityforge/replicant,realityforge/replicant
package org.realityforge.replicant.server.transport; import javax.websocket.Session; import org.realityforge.guiceyloops.shared.ValueUtil; import org.realityforge.replicant.server.ChannelAddress; import org.testng.annotations.Test; import static org.mockito.Mockito.*; import static org.testng.Assert.*; public class ReplicantSessionTest { @SuppressWarnings( "ConstantConditions" ) @Test public void basicOperation() { final Session webSocketSession = mock( Session.class ); final String sessionId = ValueUtil.randomString(); when( webSocketSession.getId() ).thenReturn( sessionId ); final ReplicantSession session = new ReplicantSession( webSocketSession ); assertEquals( session.getId(), sessionId ); assertEquals( session.getSubscriptions().size(), 0 ); final ChannelAddress cd1 = new ChannelAddress( 1, null ); assertNull( session.findSubscriptionEntry( cd1 ) ); assertFalse( session.isSubscriptionEntryPresent( cd1 ) ); try { session.getSubscriptionEntry( cd1 ); fail( "Expected to be unable to get non existent entry" ); } catch ( final IllegalStateException ise ) { assertEquals( ise.getMessage(), "Unable to locate subscription entry for 1" ); } final SubscriptionEntry entry = session.createSubscriptionEntry( cd1 ); assertEquals( entry.getAddress(), cd1 ); assertEquals( session.getSubscriptions().size(), 1 ); assertEquals( session.findSubscriptionEntry( cd1 ), entry ); assertEquals( session.getSubscriptionEntry( cd1 ), entry ); assertTrue( session.getSubscriptions().containsKey( cd1 ) ); assertTrue( session.getSubscriptions().containsValue( entry ) ); try { session.getSubscriptions().remove( cd1 ); fail( "Expected to be unable to delete subscription as it is a read-only set" ); } catch ( final UnsupportedOperationException uoe ) { //ignored } assertTrue( session.deleteSubscriptionEntry( entry ) ); assertFalse( session.deleteSubscriptionEntry( entry ) ); assertNull( session.findSubscriptionEntry( cd1 ) ); assertFalse( session.isSubscriptionEntryPresent( cd1 ) ); assertEquals( session.getSubscriptions().size(), 0 ); } @Test public void cacheKeys() { final ReplicantSession session = new ReplicantSession( mock( Session.class ) ); final ChannelAddress cd1 = new ChannelAddress( 1, null ); assertNull( session.getETag( cd1 ) ); session.setETag( cd1, "X" ); assertEquals( session.getETag( cd1 ), "X" ); } }
server/src/test/java/org/realityforge/replicant/server/transport/ReplicantSessionTest.java
package org.realityforge.replicant.server.transport; import javax.websocket.Session; import org.realityforge.guiceyloops.shared.ValueUtil; import org.realityforge.replicant.server.ChannelAddress; import org.testng.annotations.Test; import static org.mockito.Mockito.*; import static org.testng.Assert.*; public class ReplicantSessionTest { @SuppressWarnings( "ConstantConditions" ) @Test public void basicOperation() { final Session webSocketSession = mock( Session.class ); final String sessionId = ValueUtil.randomString(); when( webSocketSession.getId() ).thenReturn( sessionId ); final ReplicantSession session = new ReplicantSession( webSocketSession ); assertEquals( session.getId(), sessionId ); assertEquals( session.getSubscriptions().size(), 0 ); final ChannelAddress cd1 = new ChannelAddress( 1, null ); assertNull( session.findSubscriptionEntry( cd1 ) ); assertFalse( session.isSubscriptionEntryPresent( cd1 ) ); try { session.getSubscriptionEntry( cd1 ); fail( "Expected to be unable to get non existent entry" ); } catch ( final IllegalStateException ise ) { assertEquals( ise.getMessage(), "Unable to locate subscription entry for 1" ); } final SubscriptionEntry entry = session.createSubscriptionEntry( cd1 ); assertEquals( entry.getAddress(), cd1 ); assertEquals( session.getSubscriptions().size(), 1 ); assertEquals( session.findSubscriptionEntry( cd1 ), entry ); assertEquals( session.getSubscriptionEntry( cd1 ), entry ); assertTrue( session.getSubscriptions().containsKey( cd1 ) ); assertTrue( session.getSubscriptions().containsValue( entry ) ); try { session.getSubscriptions().remove( cd1 ); fail( "Expected to be unable to delete subscription as it is a read-only set" ); } catch ( final UnsupportedOperationException uoe ) { //ignored } assertTrue( session.deleteSubscriptionEntry( entry ) ); assertFalse( session.deleteSubscriptionEntry( entry ) ); assertNull( session.findSubscriptionEntry( cd1 ) ); assertFalse( session.isSubscriptionEntryPresent( cd1 ) ); assertEquals( session.getSubscriptions().size(), 0 ); } @SuppressWarnings( "ConstantConditions" ) @Test public void cacheKeys() { final ReplicantSession session = new ReplicantSession( mock( Session.class ) ); final ChannelAddress cd1 = new ChannelAddress( 1, null ); assertNull( session.getETag( cd1 ) ); session.setETag( cd1, "X" ); assertEquals( session.getETag( cd1 ), "X" ); } }
Remove unnecessary suppression
server/src/test/java/org/realityforge/replicant/server/transport/ReplicantSessionTest.java
Remove unnecessary suppression
<ide><path>erver/src/test/java/org/realityforge/replicant/server/transport/ReplicantSessionTest.java <ide> assertEquals( session.getSubscriptions().size(), 0 ); <ide> } <ide> <del> @SuppressWarnings( "ConstantConditions" ) <ide> @Test <ide> public void cacheKeys() <ide> {
JavaScript
agpl-3.0
2c3847affee52d4abf54fc1f466d336918f4f342
0
nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop,nrizzio/Signal-Desktop
/* global window: false */ /* global textsecure: false */ /* global WebAPI: false */ /* global libsignal: false */ /* global WebSocketResource: false */ /* global WebSocket: false */ /* global Event: false */ /* global dcodeIO: false */ /* global _: false */ /* global ContactBuffer: false */ /* global GroupBuffer: false */ /* global Worker: false */ /* eslint-disable more/no-then */ const WORKER_TIMEOUT = 60 * 1000; // one minute const _utilWorker = new Worker('js/util_worker.js'); const _jobs = Object.create(null); const _DEBUG = false; let _jobCounter = 0; function _makeJob(fnName) { _jobCounter += 1; const id = _jobCounter; if (_DEBUG) { window.log.info(`Worker job ${id} (${fnName}) started`); } _jobs[id] = { fnName, start: Date.now(), }; return id; } function _updateJob(id, data) { const { resolve, reject } = data; const { fnName, start } = _jobs[id]; _jobs[id] = { ..._jobs[id], ...data, resolve: value => { _removeJob(id); const end = Date.now(); window.log.info( `Worker job ${id} (${fnName}) succeeded in ${end - start}ms` ); return resolve(value); }, reject: error => { _removeJob(id); const end = Date.now(); window.log.info( `Worker job ${id} (${fnName}) failed in ${end - start}ms` ); return reject(error); }, }; } function _removeJob(id) { if (_DEBUG) { _jobs[id].complete = true; } else { delete _jobs[id]; } } function _getJob(id) { return _jobs[id]; } async function callWorker(fnName, ...args) { const jobId = _makeJob(fnName); return new Promise((resolve, reject) => { _utilWorker.postMessage([jobId, fnName, ...args]); _updateJob(jobId, { resolve, reject, args: _DEBUG ? args : null, }); setTimeout( () => reject(new Error(`Worker job ${jobId} (${fnName}) timed out`)), WORKER_TIMEOUT ); }); } _utilWorker.onmessage = e => { const [jobId, errorForDisplay, result] = e.data; const job = _getJob(jobId); if (!job) { throw new Error( `Received worker reply to job ${jobId}, but did not have it in our registry!` ); } const { resolve, reject, fnName } = job; if (errorForDisplay) { return reject( new Error( `Error received from worker job ${jobId} (${fnName}): ${errorForDisplay}` ) ); } return resolve(result); }; function MessageReceiver(username, password, signalingKey, options = {}) { this.count = 0; this.signalingKey = signalingKey; this.username = username; this.password = password; this.server = WebAPI.connect({ username, password }); if (!options.serverTrustRoot) { throw new Error('Server trust root is required!'); } this.serverTrustRoot = window.Signal.Crypto.base64ToArrayBuffer( options.serverTrustRoot ); const address = libsignal.SignalProtocolAddress.fromString(username); this.number = address.getName(); this.deviceId = address.getDeviceId(); this.pending = Promise.resolve(); if (options.retryCached) { this.pending = this.queueAllCached(); } } MessageReceiver.stringToArrayBuffer = string => Promise.resolve(dcodeIO.ByteBuffer.wrap(string, 'binary').toArrayBuffer()); MessageReceiver.arrayBufferToString = arrayBuffer => Promise.resolve(dcodeIO.ByteBuffer.wrap(arrayBuffer).toString('binary')); MessageReceiver.stringToArrayBufferBase64 = string => callWorker('stringToArrayBufferBase64', string); MessageReceiver.arrayBufferToStringBase64 = arrayBuffer => callWorker('arrayBufferToStringBase64', arrayBuffer); MessageReceiver.prototype = new textsecure.EventTarget(); MessageReceiver.prototype.extend({ constructor: MessageReceiver, connect() { if (this.calledClose) { return; } this.count = 0; if (this.hasConnected) { const ev = new Event('reconnect'); this.dispatchEvent(ev); } this.hasConnected = true; if (this.socket && this.socket.readyState !== WebSocket.CLOSED) { this.socket.close(); this.wsr.close(); } // initialize the socket and start listening for messages this.socket = this.server.getMessageSocket(); this.socket.onclose = this.onclose.bind(this); this.socket.onerror = this.onerror.bind(this); this.socket.onopen = this.onopen.bind(this); this.wsr = new WebSocketResource(this.socket, { handleRequest: this.handleRequest.bind(this), keepalive: { path: '/v1/keepalive', disconnect: true, }, }); // Because sometimes the socket doesn't properly emit its close event this._onClose = this.onclose.bind(this); this.wsr.addEventListener('close', this._onClose); // Ensures that an immediate 'empty' event from the websocket will fire only after // all cached envelopes are processed. this.incoming = [this.pending]; }, shutdown() { if (this.socket) { this.socket.onclose = null; this.socket.onerror = null; this.socket.onopen = null; this.socket = null; } if (this.wsr) { this.wsr.removeEventListener('close', this._onClose); this.wsr = null; } }, close() { window.log.info('MessageReceiver.close()'); this.calledClose = true; // Our WebSocketResource instance will close the socket and emit a 'close' event // if the socket doesn't emit one quickly enough. if (this.wsr) { this.wsr.close(3000, 'called close'); } return this.drain(); }, onopen() { window.log.info('websocket open'); }, onerror() { window.log.error('websocket error'); }, dispatchAndWait(event) { const promise = this.appPromise || Promise.resolve(); const appJobPromise = Promise.all(this.dispatchEvent(event)); const job = () => appJobPromise; this.appPromise = promise.then(job, job); return Promise.resolve(); }, onclose(ev) { window.log.info( 'websocket closed', ev.code, ev.reason || '', 'calledClose:', this.calledClose ); this.shutdown(); if (this.calledClose) { return Promise.resolve(); } if (ev.code === 3000) { return Promise.resolve(); } if (ev.code === 3001) { this.onEmpty(); } // possible 403 or network issue. Make an request to confirm return this.server .getDevices(this.number) .then(this.connect.bind(this)) // No HTTP error? Reconnect .catch(e => { const event = new Event('error'); event.error = e; return this.dispatchAndWait(event); }); }, handleRequest(request) { this.incoming = this.incoming || []; const lastPromise = _.last(this.incoming); // We do the message decryption here, instead of in the ordered pending queue, // to avoid exposing the time it took us to process messages through the time-to-ack. if (request.path !== '/api/v1/message') { window.log.info('got request', request.verb, request.path); request.respond(200, 'OK'); if (request.verb === 'PUT' && request.path === '/api/v1/queue/empty') { this.onEmpty(); } return; } let promise; const headers = request.headers || []; if (headers.includes('X-Signal-Key: true')) { promise = textsecure.crypto.decryptWebsocketMessage( request.body, this.signalingKey ); } else { promise = Promise.resolve(request.body.toArrayBuffer()); } promise = promise .then(plaintext => { const envelope = textsecure.protobuf.Envelope.decode(plaintext); // After this point, decoding errors are not the server's // fault, and we should handle them gracefully and tell the // user they received an invalid message if (this.isBlocked(envelope.source)) { return request.respond(200, 'OK'); } envelope.id = envelope.serverGuid || window.getGuid(); envelope.serverTimestamp = envelope.serverTimestamp ? envelope.serverTimestamp.toNumber() : null; return this.addToCache(envelope, plaintext).then( async () => { request.respond(200, 'OK'); // To ensure that we queue in the same order we receive messages await lastPromise; this.queueEnvelope(envelope); }, error => { request.respond(500, 'Failed to cache message'); window.log.error( 'handleRequest error trying to add message to cache:', error && error.stack ? error.stack : error ); } ); }) .catch(e => { request.respond(500, 'Bad encrypted websocket message'); window.log.error( 'Error handling incoming message:', e && e.stack ? e.stack : e ); const ev = new Event('error'); ev.error = e; return this.dispatchAndWait(ev); }); this.incoming.push(promise); }, addToQueue(task) { this.count += 1; this.pending = this.pending.then(task, task); const { count, pending } = this; const cleanup = () => { this.updateProgress(count); // We want to clear out the promise chain whenever possible because it could // lead to large memory usage over time: // https://github.com/nodejs/node/issues/6673#issuecomment-244331609 if (this.pending === pending) { this.pending = Promise.resolve(); } }; pending.then(cleanup, cleanup); return pending; }, onEmpty() { const { incoming } = this; this.incoming = []; const emitEmpty = () => { window.log.info("MessageReceiver: emitting 'empty' event"); const ev = new Event('empty'); this.dispatchAndWait(ev); }; const waitForApplication = async () => { window.log.info( "MessageReceiver: finished processing messages after 'empty', now waiting for application" ); const promise = this.appPromise || Promise.resolve(); this.appPromise = Promise.resolve(); // We don't await here because we don't this to gate future message processing promise.then(emitEmpty, emitEmpty); }; const waitForEmptyQueue = () => { // resetting count to zero so everything queued after this starts over again this.count = 0; this.addToQueue(waitForApplication); }; // We first wait for all recently-received messages (this.incoming) to be queued, // then we queue a task to wait for the application to finish its processing, then // finally we emit the 'empty' event to the queue. Promise.all(incoming).then(waitForEmptyQueue, waitForEmptyQueue); }, drain() { const { incoming } = this; this.incoming = []; const queueDispatch = () => this.addToQueue(() => { window.log.info('drained'); }); // This promise will resolve when there are no more messages to be processed. return Promise.all(incoming).then(queueDispatch, queueDispatch); }, updateProgress(count) { // count by 10s if (count % 10 !== 0) { return; } const ev = new Event('progress'); ev.count = count; this.dispatchEvent(ev); }, async queueAllCached() { const items = await this.getAllFromCache(); for (let i = 0, max = items.length; i < max; i += 1) { // eslint-disable-next-line no-await-in-loop await this.queueCached(items[i]); } }, async queueCached(item) { try { let envelopePlaintext = item.envelope; if (item.version === 2) { envelopePlaintext = await MessageReceiver.stringToArrayBufferBase64( envelopePlaintext ); } if (typeof envelopePlaintext === 'string') { envelopePlaintext = await MessageReceiver.stringToArrayBuffer( envelopePlaintext ); } const envelope = textsecure.protobuf.Envelope.decode(envelopePlaintext); envelope.id = envelope.serverGuid || item.id; envelope.source = envelope.source || item.source; envelope.sourceDevice = envelope.sourceDevice || item.sourceDevice; envelope.serverTimestamp = envelope.serverTimestamp || item.serverTimestamp; const { decrypted } = item; if (decrypted) { let payloadPlaintext = decrypted; if (item.version === 2) { payloadPlaintext = await MessageReceiver.stringToArrayBufferBase64( payloadPlaintext ); } if (typeof payloadPlaintext === 'string') { payloadPlaintext = await MessageReceiver.stringToArrayBuffer( payloadPlaintext ); } this.queueDecryptedEnvelope(envelope, payloadPlaintext); } else { this.queueEnvelope(envelope); } } catch (error) { window.log.error( 'queueCached error handling item', item.id, 'removing it. Error:', error && error.stack ? error.stack : error ); try { const { id } = item; await textsecure.storage.unprocessed.remove(id); } catch (deleteError) { window.log.error( 'queueCached error deleting item', item.id, 'Error:', deleteError && deleteError.stack ? deleteError.stack : deleteError ); } } }, getEnvelopeId(envelope) { if (envelope.source) { return `${envelope.source}.${ envelope.sourceDevice } ${envelope.timestamp.toNumber()} (${envelope.id})`; } return envelope.id; }, async getAllFromCache() { window.log.info('getAllFromCache'); const count = await textsecure.storage.unprocessed.getCount(); if (count > 1500) { await textsecure.storage.unprocessed.removeAll(); window.log.warn( `There were ${count} messages in cache. Deleted all instead of reprocessing` ); return []; } const items = await textsecure.storage.unprocessed.getAll(); window.log.info('getAllFromCache loaded', items.length, 'saved envelopes'); return Promise.all( _.map(items, async item => { const attempts = 1 + (item.attempts || 0); try { if (attempts >= 3) { window.log.warn( 'getAllFromCache final attempt for envelope', item.id ); await textsecure.storage.unprocessed.remove(item.id); } else { await textsecure.storage.unprocessed.updateAttempts( item.id, attempts ); } } catch (error) { window.log.error( 'getAllFromCache error updating item after load:', error && error.stack ? error.stack : error ); } return item; }) ); }, async addToCache(envelope, plaintext) { const { id } = envelope; const data = { id, version: 2, envelope: await MessageReceiver.arrayBufferToStringBase64(plaintext), timestamp: Date.now(), attempts: 1, }; return textsecure.storage.unprocessed.add(data); }, async updateCache(envelope, plaintext) { const { id } = envelope; const item = await textsecure.storage.unprocessed.get(id); if (!item) { window.log.error( `updateCache: Didn't find item ${id} in cache to update` ); return null; } item.source = envelope.source; item.sourceDevice = envelope.sourceDevice; item.serverTimestamp = envelope.serverTimestamp; if (item.version === 2) { item.decrypted = await MessageReceiver.arrayBufferToStringBase64( plaintext ); } else { item.decrypted = await MessageReceiver.arrayBufferToString(plaintext); } return textsecure.storage.unprocessed.addDecryptedData(item.id, item); }, removeFromCache(envelope) { const { id } = envelope; return textsecure.storage.unprocessed.remove(id); }, queueDecryptedEnvelope(envelope, plaintext) { const id = this.getEnvelopeId(envelope); window.log.info('queueing decrypted envelope', id); const task = this.handleDecryptedEnvelope.bind(this, envelope, plaintext); const taskWithTimeout = textsecure.createTaskWithTimeout( task, `queueEncryptedEnvelope ${id}` ); const promise = this.addToQueue(taskWithTimeout); return promise.catch(error => { window.log.error( 'queueDecryptedEnvelope error handling envelope', id, ':', error && error.stack ? error.stack : error ); }); }, queueEnvelope(envelope) { const id = this.getEnvelopeId(envelope); window.log.info('queueing envelope', id); const task = this.handleEnvelope.bind(this, envelope); const taskWithTimeout = textsecure.createTaskWithTimeout( task, `queueEnvelope ${id}` ); const promise = this.addToQueue(taskWithTimeout); return promise.catch(error => { window.log.error( 'queueEnvelope error handling envelope', id, ':', error && error.stack ? error.stack : error ); }); }, // Same as handleEnvelope, just without the decryption step. Necessary for handling // messages which were successfully decrypted, but application logic didn't finish // processing. handleDecryptedEnvelope(envelope, plaintext) { // No decryption is required for delivery receipts, so the decrypted field of // the Unprocessed model will never be set if (envelope.content) { return this.innerHandleContentMessage(envelope, plaintext); } else if (envelope.legacyMessage) { return this.innerHandleLegacyMessage(envelope, plaintext); } this.removeFromCache(envelope); throw new Error('Received message with no content and no legacyMessage'); }, handleEnvelope(envelope) { if (envelope.type === textsecure.protobuf.Envelope.Type.RECEIPT) { return this.onDeliveryReceipt(envelope); } if (envelope.content) { return this.handleContentMessage(envelope); } else if (envelope.legacyMessage) { return this.handleLegacyMessage(envelope); } this.removeFromCache(envelope); throw new Error('Received message with no content and no legacyMessage'); }, getStatus() { if (this.socket) { return this.socket.readyState; } else if (this.hasConnected) { return WebSocket.CLOSED; } return -1; }, onDeliveryReceipt(envelope) { return new Promise((resolve, reject) => { const ev = new Event('delivery'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.deliveryReceipt = { timestamp: envelope.timestamp.toNumber(), source: envelope.source, sourceDevice: envelope.sourceDevice, }; this.dispatchAndWait(ev).then(resolve, reject); }); }, unpad(paddedData) { const paddedPlaintext = new Uint8Array(paddedData); let plaintext; for (let i = paddedPlaintext.length - 1; i >= 0; i -= 1) { if (paddedPlaintext[i] === 0x80) { plaintext = new Uint8Array(i); plaintext.set(paddedPlaintext.subarray(0, i)); plaintext = plaintext.buffer; break; } else if (paddedPlaintext[i] !== 0x00) { throw new Error('Invalid padding'); } } return plaintext; }, decrypt(envelope, ciphertext) { const { serverTrustRoot } = this; let promise; const address = new libsignal.SignalProtocolAddress( envelope.source, envelope.sourceDevice ); const ourNumber = textsecure.storage.user.getNumber(); const number = address.toString().split('.')[0]; const options = {}; // No limit on message keys if we're communicating with our other devices if (ourNumber === number) { options.messageKeysLimit = false; } const sessionCipher = new libsignal.SessionCipher( textsecure.storage.protocol, address, options ); const secretSessionCipher = new window.Signal.Metadata.SecretSessionCipher( textsecure.storage.protocol ); const me = { number: ourNumber, deviceId: parseInt(textsecure.storage.user.getDeviceId(), 10), }; switch (envelope.type) { case textsecure.protobuf.Envelope.Type.CIPHERTEXT: window.log.info('message from', this.getEnvelopeId(envelope)); promise = sessionCipher .decryptWhisperMessage(ciphertext) .then(this.unpad); break; case textsecure.protobuf.Envelope.Type.PREKEY_BUNDLE: window.log.info('prekey message from', this.getEnvelopeId(envelope)); promise = this.decryptPreKeyWhisperMessage( ciphertext, sessionCipher, address ); break; case textsecure.protobuf.Envelope.Type.UNIDENTIFIED_SENDER: window.log.info('received unidentified sender message'); promise = secretSessionCipher .decrypt( window.Signal.Metadata.createCertificateValidator(serverTrustRoot), ciphertext.toArrayBuffer(), Math.min(envelope.serverTimestamp || Date.now(), Date.now()), me ) .then( result => { const { isMe, sender, content } = result; // We need to drop incoming messages from ourself since server can't // do it for us if (isMe) { return { isMe: true }; } if (this.isBlocked(sender.getName())) { window.log.info( 'Dropping blocked message after sealed sender decryption' ); return { isBlocked: true }; } // Here we take this sender information and attach it back to the envelope // to make the rest of the app work properly. const originalSource = envelope.source; // eslint-disable-next-line no-param-reassign envelope.source = sender.getName(); // eslint-disable-next-line no-param-reassign envelope.sourceDevice = sender.getDeviceId(); // eslint-disable-next-line no-param-reassign envelope.unidentifiedDeliveryReceived = !originalSource; // Return just the content because that matches the signature of the other // decrypt methods used above. return this.unpad(content); }, error => { const { sender } = error || {}; if (sender) { const originalSource = envelope.source; if (this.isBlocked(sender.getName())) { window.log.info( 'Dropping blocked message with error after sealed sender decryption' ); return { isBlocked: true }; } // eslint-disable-next-line no-param-reassign envelope.source = sender.getName(); // eslint-disable-next-line no-param-reassign envelope.sourceDevice = sender.getDeviceId(); // eslint-disable-next-line no-param-reassign envelope.unidentifiedDeliveryReceived = !originalSource; throw error; } return this.removeFromCache(envelope).then(() => { throw error; }); } ); break; default: promise = Promise.reject(new Error('Unknown message type')); } return promise .then(plaintext => { const { isMe, isBlocked } = plaintext || {}; if (isMe || isBlocked) { this.removeFromCache(envelope); return null; } this.updateCache(envelope, plaintext).catch(error => { window.log.error( 'decrypt failed to save decrypted message contents to cache:', error && error.stack ? error.stack : error ); }); return plaintext; }) .catch(error => { let errorToThrow = error; if (error && error.message === 'Unknown identity key') { // create an error that the UI will pick up and ask the // user if they want to re-negotiate const buffer = dcodeIO.ByteBuffer.wrap(ciphertext); errorToThrow = new textsecure.IncomingIdentityKeyError( address.toString(), buffer.toArrayBuffer(), error.identityKey ); } const ev = new Event('error'); ev.error = errorToThrow; ev.proto = envelope; ev.confirm = this.removeFromCache.bind(this, envelope); const returnError = () => Promise.reject(errorToThrow); return this.dispatchAndWait(ev).then(returnError, returnError); }); }, async decryptPreKeyWhisperMessage(ciphertext, sessionCipher, address) { const padded = await sessionCipher.decryptPreKeyWhisperMessage(ciphertext); try { return this.unpad(padded); } catch (e) { if (e.message === 'Unknown identity key') { // create an error that the UI will pick up and ask the // user if they want to re-negotiate const buffer = dcodeIO.ByteBuffer.wrap(ciphertext); throw new textsecure.IncomingIdentityKeyError( address.toString(), buffer.toArrayBuffer(), e.identityKey ); } throw e; } }, handleSentMessage(envelope, sentContainer, msg) { const { destination, timestamp, expirationStartTimestamp, unidentifiedStatus, } = sentContainer; let p = Promise.resolve(); // eslint-disable-next-line no-bitwise if (msg.flags & textsecure.protobuf.DataMessage.Flags.END_SESSION) { p = this.handleEndSession(destination); } return p.then(() => this.processDecrypted(envelope, msg).then(message => { const groupId = message.group && message.group.id; const isBlocked = this.isGroupBlocked(groupId); const isMe = envelope.source === textsecure.storage.user.getNumber(); const isLeavingGroup = Boolean( message.group && message.group.type === textsecure.protobuf.GroupContext.Type.QUIT ); if (groupId && isBlocked && !(isMe && isLeavingGroup)) { window.log.warn( `Message ${this.getEnvelopeId( envelope )} ignored; destined for blocked group` ); return this.removeFromCache(envelope); } const ev = new Event('sent'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.data = { destination, timestamp: timestamp.toNumber(), device: envelope.sourceDevice, unidentifiedStatus, message, }; if (expirationStartTimestamp) { ev.data.expirationStartTimestamp = expirationStartTimestamp.toNumber(); } return this.dispatchAndWait(ev); }) ); }, handleDataMessage(envelope, msg) { window.log.info('data message from', this.getEnvelopeId(envelope)); let p = Promise.resolve(); // eslint-disable-next-line no-bitwise if (msg.flags & textsecure.protobuf.DataMessage.Flags.END_SESSION) { p = this.handleEndSession(envelope.source); } return p.then(() => this.processDecrypted(envelope, msg).then(message => { const groupId = message.group && message.group.id; const isBlocked = this.isGroupBlocked(groupId); const isMe = envelope.source === textsecure.storage.user.getNumber(); const isLeavingGroup = Boolean( message.group && message.group.type === textsecure.protobuf.GroupContext.Type.QUIT ); if (groupId && isBlocked && !(isMe && isLeavingGroup)) { window.log.warn( `Message ${this.getEnvelopeId( envelope )} ignored; destined for blocked group` ); return this.removeFromCache(envelope); } const ev = new Event('message'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.data = { source: envelope.source, sourceDevice: envelope.sourceDevice, timestamp: envelope.timestamp.toNumber(), receivedAt: envelope.receivedAt, unidentifiedDeliveryReceived: envelope.unidentifiedDeliveryReceived, message, }; return this.dispatchAndWait(ev); }) ); }, handleLegacyMessage(envelope) { return this.decrypt(envelope, envelope.legacyMessage).then(plaintext => { if (!plaintext) { window.log.warn('handleLegacyMessage: plaintext was falsey'); return null; } return this.innerHandleLegacyMessage(envelope, plaintext); }); }, innerHandleLegacyMessage(envelope, plaintext) { const message = textsecure.protobuf.DataMessage.decode(plaintext); return this.handleDataMessage(envelope, message); }, handleContentMessage(envelope) { return this.decrypt(envelope, envelope.content).then(plaintext => { if (!plaintext) { window.log.warn('handleContentMessage: plaintext was falsey'); return null; } return this.innerHandleContentMessage(envelope, plaintext); }); }, innerHandleContentMessage(envelope, plaintext) { const content = textsecure.protobuf.Content.decode(plaintext); if (content.syncMessage) { return this.handleSyncMessage(envelope, content.syncMessage); } else if (content.dataMessage) { return this.handleDataMessage(envelope, content.dataMessage); } else if (content.nullMessage) { return this.handleNullMessage(envelope, content.nullMessage); } else if (content.callMessage) { return this.handleCallMessage(envelope, content.callMessage); } else if (content.receiptMessage) { return this.handleReceiptMessage(envelope, content.receiptMessage); } else if (content.typingMessage) { return this.handleTypingMessage(envelope, content.typingMessage); } this.removeFromCache(envelope); throw new Error('Unsupported content message'); }, handleCallMessage(envelope) { window.log.info('call message from', this.getEnvelopeId(envelope)); this.removeFromCache(envelope); }, handleReceiptMessage(envelope, receiptMessage) { const results = []; if ( receiptMessage.type === textsecure.protobuf.ReceiptMessage.Type.DELIVERY ) { for (let i = 0; i < receiptMessage.timestamp.length; i += 1) { const ev = new Event('delivery'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.deliveryReceipt = { timestamp: receiptMessage.timestamp[i].toNumber(), source: envelope.source, sourceDevice: envelope.sourceDevice, }; results.push(this.dispatchAndWait(ev)); } } else if ( receiptMessage.type === textsecure.protobuf.ReceiptMessage.Type.READ ) { for (let i = 0; i < receiptMessage.timestamp.length; i += 1) { const ev = new Event('read'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.timestamp = envelope.timestamp.toNumber(); ev.read = { timestamp: receiptMessage.timestamp[i].toNumber(), reader: envelope.source, }; results.push(this.dispatchAndWait(ev)); } } return Promise.all(results); }, handleTypingMessage(envelope, typingMessage) { const ev = new Event('typing'); this.removeFromCache(envelope); if (envelope.timestamp && typingMessage.timestamp) { const envelopeTimestamp = envelope.timestamp.toNumber(); const typingTimestamp = typingMessage.timestamp.toNumber(); if (typingTimestamp !== envelopeTimestamp) { window.log.warn( `Typing message envelope timestamp (${envelopeTimestamp}) did not match typing timestamp (${typingTimestamp})` ); return null; } } ev.sender = envelope.source; ev.senderDevice = envelope.sourceDevice; ev.typing = { typingMessage, timestamp: typingMessage.timestamp ? typingMessage.timestamp.toNumber() : Date.now(), groupId: typingMessage.groupId ? typingMessage.groupId.toString('binary') : null, started: typingMessage.action === textsecure.protobuf.TypingMessage.Action.STARTED, stopped: typingMessage.action === textsecure.protobuf.TypingMessage.Action.STOPPED, }; return this.dispatchEvent(ev); }, handleNullMessage(envelope) { window.log.info('null message from', this.getEnvelopeId(envelope)); this.removeFromCache(envelope); }, handleSyncMessage(envelope, syncMessage) { if (envelope.source !== this.number) { throw new Error('Received sync message from another number'); } // eslint-disable-next-line eqeqeq if (envelope.sourceDevice == this.deviceId) { throw new Error('Received sync message from our own device'); } if (syncMessage.sent) { const sentMessage = syncMessage.sent; const to = sentMessage.message.group ? `group(${sentMessage.message.group.id.toBinary()})` : sentMessage.destination; window.log.info( 'sent message to', to, sentMessage.timestamp.toNumber(), 'from', this.getEnvelopeId(envelope) ); return this.handleSentMessage(envelope, sentMessage, sentMessage.message); } else if (syncMessage.contacts) { return this.handleContacts(envelope, syncMessage.contacts); } else if (syncMessage.groups) { return this.handleGroups(envelope, syncMessage.groups); } else if (syncMessage.blocked) { return this.handleBlocked(envelope, syncMessage.blocked); } else if (syncMessage.request) { window.log.info('Got SyncMessage Request'); return this.removeFromCache(envelope); } else if (syncMessage.read && syncMessage.read.length) { window.log.info('read messages from', this.getEnvelopeId(envelope)); return this.handleRead(envelope, syncMessage.read); } else if (syncMessage.verified) { return this.handleVerified(envelope, syncMessage.verified); } else if (syncMessage.configuration) { return this.handleConfiguration(envelope, syncMessage.configuration); } throw new Error('Got empty SyncMessage'); }, handleConfiguration(envelope, configuration) { window.log.info('got configuration sync message'); const ev = new Event('configuration'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.configuration = configuration; return this.dispatchAndWait(ev); }, handleVerified(envelope, verified) { const ev = new Event('verified'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.verified = { state: verified.state, destination: verified.destination, identityKey: verified.identityKey.toArrayBuffer(), }; return this.dispatchAndWait(ev); }, handleRead(envelope, read) { const results = []; for (let i = 0; i < read.length; i += 1) { const ev = new Event('readSync'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.timestamp = envelope.timestamp.toNumber(); ev.read = { timestamp: read[i].timestamp.toNumber(), sender: read[i].sender, }; results.push(this.dispatchAndWait(ev)); } return Promise.all(results); }, handleContacts(envelope, contacts) { window.log.info('contact sync'); const { blob } = contacts; // Note: we do not return here because we don't want to block the next message on // this attachment download and a lot of processing of that attachment. this.handleAttachment(blob).then(attachmentPointer => { const results = []; const contactBuffer = new ContactBuffer(attachmentPointer.data); let contactDetails = contactBuffer.next(); while (contactDetails !== undefined) { const ev = new Event('contact'); ev.contactDetails = contactDetails; results.push(this.dispatchAndWait(ev)); contactDetails = contactBuffer.next(); } const ev = new Event('contactsync'); results.push(this.dispatchAndWait(ev)); return Promise.all(results).then(() => { window.log.info('handleContacts: finished'); return this.removeFromCache(envelope); }); }); }, handleGroups(envelope, groups) { window.log.info('group sync'); const { blob } = groups; // Note: we do not return here because we don't want to block the next message on // this attachment download and a lot of processing of that attachment. this.handleAttachment(blob).then(attachmentPointer => { const groupBuffer = new GroupBuffer(attachmentPointer.data); let groupDetails = groupBuffer.next(); const promises = []; while (groupDetails !== undefined) { groupDetails.id = groupDetails.id.toBinary(); const ev = new Event('group'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.groupDetails = groupDetails; const promise = this.dispatchAndWait(ev).catch(e => { window.log.error('error processing group', e); }); groupDetails = groupBuffer.next(); promises.push(promise); } Promise.all(promises).then(() => { const ev = new Event('groupsync'); ev.confirm = this.removeFromCache.bind(this, envelope); return this.dispatchAndWait(ev); }); }); }, handleBlocked(envelope, blocked) { window.log.info('Setting these numbers as blocked:', blocked.numbers); textsecure.storage.put('blocked', blocked.numbers); const groupIds = _.map(blocked.groupIds, groupId => groupId.toBinary()); window.log.info( 'Setting these groups as blocked:', groupIds.map(groupId => `group(${groupId})`) ); textsecure.storage.put('blocked-groups', groupIds); return this.removeFromCache(envelope); }, isBlocked(number) { return textsecure.storage.get('blocked', []).indexOf(number) >= 0; }, isGroupBlocked(groupId) { return textsecure.storage.get('blocked-groups', []).indexOf(groupId) >= 0; }, cleanAttachment(attachment) { return { ..._.omit(attachment, 'thumbnail'), id: attachment.id.toString(), key: attachment.key ? attachment.key.toString('base64') : null, digest: attachment.digest ? attachment.digest.toString('base64') : null, }; }, async downloadAttachment(attachment) { const encrypted = await this.server.getAttachment(attachment.id); const { key, digest } = attachment; const data = await textsecure.crypto.decryptAttachment( encrypted, window.Signal.Crypto.base64ToArrayBuffer(key), window.Signal.Crypto.base64ToArrayBuffer(digest) ); return { ..._.omit(attachment, 'digest', 'key'), data, }; }, handleAttachment(attachment) { const cleaned = this.cleanAttachment(attachment); return this.downloadAttachment(cleaned); }, async handleEndSession(number) { window.log.info('got end session'); const deviceIds = await textsecure.storage.protocol.getDeviceIds(number); return Promise.all( deviceIds.map(deviceId => { const address = new libsignal.SignalProtocolAddress(number, deviceId); const sessionCipher = new libsignal.SessionCipher( textsecure.storage.protocol, address ); window.log.info('deleting sessions for', address.toString()); return sessionCipher.deleteAllSessionsForDevice(); }) ); }, processDecrypted(envelope, decrypted) { /* eslint-disable no-bitwise, no-param-reassign */ const FLAGS = textsecure.protobuf.DataMessage.Flags; // Now that its decrypted, validate the message and clean it up for consumer // processing // Note that messages may (generally) only perform one action and we ignore remaining // fields after the first action. if (decrypted.flags == null) { decrypted.flags = 0; } if (decrypted.expireTimer == null) { decrypted.expireTimer = 0; } if (decrypted.flags & FLAGS.END_SESSION) { decrypted.body = null; decrypted.attachments = []; decrypted.group = null; return Promise.resolve(decrypted); } else if (decrypted.flags & FLAGS.EXPIRATION_TIMER_UPDATE) { decrypted.body = null; decrypted.attachments = []; } else if (decrypted.flags & FLAGS.PROFILE_KEY_UPDATE) { decrypted.body = null; decrypted.attachments = []; } else if (decrypted.flags !== 0) { throw new Error('Unknown flags in message'); } const promises = []; if (decrypted.group !== null) { decrypted.group.id = decrypted.group.id.toBinary(); switch (decrypted.group.type) { case textsecure.protobuf.GroupContext.Type.UPDATE: decrypted.body = null; decrypted.attachments = []; break; case textsecure.protobuf.GroupContext.Type.QUIT: decrypted.body = null; decrypted.attachments = []; break; case textsecure.protobuf.GroupContext.Type.DELIVER: decrypted.group.name = null; decrypted.group.members = []; decrypted.group.avatar = null; break; default: this.removeFromCache(envelope); throw new Error('Unknown group message type'); } } const attachmentCount = decrypted.attachments.length; const ATTACHMENT_MAX = 32; if (attachmentCount > ATTACHMENT_MAX) { throw new Error( `Too many attachments: ${attachmentCount} included in one message, max is ${ATTACHMENT_MAX}` ); } // Here we go from binary to string/base64 in all AttachmentPointer digest/key fields if ( decrypted.group && decrypted.group.type === textsecure.protobuf.GroupContext.Type.UPDATE ) { if (decrypted.group.avatar !== null) { decrypted.group.avatar = this.cleanAttachment(decrypted.group.avatar); } } decrypted.attachments = (decrypted.attachments || []).map( this.cleanAttachment.bind(this) ); decrypted.preview = (decrypted.preview || []).map(item => { const { image } = item; if (!image) { return item; } return { ...item, image: this.cleanAttachment(image), }; }); decrypted.contact = (decrypted.contact || []).map(item => { const { avatar } = item; if (!avatar || !avatar.avatar) { return item; } return { ...item, avatar: { ...item.avatar, avatar: this.cleanAttachment(item.avatar.avatar), }, }; }); if (decrypted.quote && decrypted.quote.id) { decrypted.quote.id = decrypted.quote.id.toNumber(); } if (decrypted.quote) { decrypted.quote.attachments = (decrypted.quote.attachments || []).map( item => { const { thumbnail } = item; if (!thumbnail) { return item; } return { ...item, thumbnail: this.cleanAttachment(item.thumbnail), }; } ); } return Promise.all(promises).then(() => decrypted); /* eslint-enable no-bitwise, no-param-reassign */ }, }); window.textsecure = window.textsecure || {}; textsecure.MessageReceiver = function MessageReceiverWrapper( username, password, signalingKey, options ) { const messageReceiver = new MessageReceiver( username, password, signalingKey, options ); this.addEventListener = messageReceiver.addEventListener.bind( messageReceiver ); this.removeEventListener = messageReceiver.removeEventListener.bind( messageReceiver ); this.getStatus = messageReceiver.getStatus.bind(messageReceiver); this.close = messageReceiver.close.bind(messageReceiver); this.downloadAttachment = messageReceiver.downloadAttachment.bind( messageReceiver ); messageReceiver.connect(); }; textsecure.MessageReceiver.prototype = { constructor: textsecure.MessageReceiver, }; textsecure.MessageReceiver.stringToArrayBuffer = MessageReceiver.stringToArrayBuffer; textsecure.MessageReceiver.arrayBufferToString = MessageReceiver.arrayBufferToString; textsecure.MessageReceiver.stringToArrayBufferBase64 = MessageReceiver.stringToArrayBufferBase64; textsecure.MessageReceiver.arrayBufferToStringBase64 = MessageReceiver.arrayBufferToStringBase64;
libtextsecure/message_receiver.js
/* global window: false */ /* global textsecure: false */ /* global WebAPI: false */ /* global libsignal: false */ /* global WebSocketResource: false */ /* global WebSocket: false */ /* global Event: false */ /* global dcodeIO: false */ /* global _: false */ /* global ContactBuffer: false */ /* global GroupBuffer: false */ /* global Worker: false */ /* eslint-disable more/no-then */ const WORKER_TIMEOUT = 60 * 1000; // one minute const _utilWorker = new Worker('js/util_worker.js'); const _jobs = Object.create(null); const _DEBUG = false; let _jobCounter = 0; function _makeJob(fnName) { _jobCounter += 1; const id = _jobCounter; if (_DEBUG) { window.log.info(`Worker job ${id} (${fnName}) started`); } _jobs[id] = { fnName, start: Date.now(), }; return id; } function _updateJob(id, data) { const { resolve, reject } = data; const { fnName, start } = _jobs[id]; _jobs[id] = { ..._jobs[id], ...data, resolve: value => { _removeJob(id); const end = Date.now(); window.log.info( `Worker job ${id} (${fnName}) succeeded in ${end - start}ms` ); return resolve(value); }, reject: error => { _removeJob(id); const end = Date.now(); window.log.info( `Worker job ${id} (${fnName}) failed in ${end - start}ms` ); return reject(error); }, }; } function _removeJob(id) { if (_DEBUG) { _jobs[id].complete = true; } else { delete _jobs[id]; } } function _getJob(id) { return _jobs[id]; } async function callWorker(fnName, ...args) { const jobId = _makeJob(fnName); return new Promise((resolve, reject) => { _utilWorker.postMessage([jobId, fnName, ...args]); _updateJob(jobId, { resolve, reject, args: _DEBUG ? args : null, }); setTimeout( () => reject(new Error(`Worker job ${jobId} (${fnName}) timed out`)), WORKER_TIMEOUT ); }); } _utilWorker.onmessage = e => { const [jobId, errorForDisplay, result] = e.data; const job = _getJob(jobId); if (!job) { throw new Error( `Received worker reply to job ${jobId}, but did not have it in our registry!` ); } const { resolve, reject, fnName } = job; if (errorForDisplay) { return reject( new Error( `Error received from worker job ${jobId} (${fnName}): ${errorForDisplay}` ) ); } return resolve(result); }; function MessageReceiver(username, password, signalingKey, options = {}) { this.count = 0; this.signalingKey = signalingKey; this.username = username; this.password = password; this.server = WebAPI.connect({ username, password }); if (!options.serverTrustRoot) { throw new Error('Server trust root is required!'); } this.serverTrustRoot = window.Signal.Crypto.base64ToArrayBuffer( options.serverTrustRoot ); const address = libsignal.SignalProtocolAddress.fromString(username); this.number = address.getName(); this.deviceId = address.getDeviceId(); this.pending = Promise.resolve(); if (options.retryCached) { this.pending = this.queueAllCached(); } } MessageReceiver.stringToArrayBuffer = string => Promise.resolve(dcodeIO.ByteBuffer.wrap(string, 'binary').toArrayBuffer()); MessageReceiver.arrayBufferToString = arrayBuffer => Promise.resolve(dcodeIO.ByteBuffer.wrap(arrayBuffer).toString('binary')); MessageReceiver.stringToArrayBufferBase64 = string => callWorker('stringToArrayBufferBase64', string); MessageReceiver.arrayBufferToStringBase64 = arrayBuffer => callWorker('arrayBufferToStringBase64', arrayBuffer); MessageReceiver.prototype = new textsecure.EventTarget(); MessageReceiver.prototype.extend({ constructor: MessageReceiver, connect() { if (this.calledClose) { return; } this.count = 0; if (this.hasConnected) { const ev = new Event('reconnect'); this.dispatchEvent(ev); } this.hasConnected = true; if (this.socket && this.socket.readyState !== WebSocket.CLOSED) { this.socket.close(); this.wsr.close(); } // initialize the socket and start listening for messages this.socket = this.server.getMessageSocket(); this.socket.onclose = this.onclose.bind(this); this.socket.onerror = this.onerror.bind(this); this.socket.onopen = this.onopen.bind(this); this.wsr = new WebSocketResource(this.socket, { handleRequest: this.handleRequest.bind(this), keepalive: { path: '/v1/keepalive', disconnect: true, }, }); // Because sometimes the socket doesn't properly emit its close event this._onClose = this.onclose.bind(this); this.wsr.addEventListener('close', this._onClose); // Ensures that an immediate 'empty' event from the websocket will fire only after // all cached envelopes are processed. this.incoming = [this.pending]; }, shutdown() { if (this.socket) { this.socket.onclose = null; this.socket.onerror = null; this.socket.onopen = null; this.socket = null; } if (this.wsr) { this.wsr.removeEventListener('close', this._onClose); this.wsr = null; } }, close() { window.log.info('MessageReceiver.close()'); this.calledClose = true; // Our WebSocketResource instance will close the socket and emit a 'close' event // if the socket doesn't emit one quickly enough. if (this.wsr) { this.wsr.close(3000, 'called close'); } return this.drain(); }, onopen() { window.log.info('websocket open'); }, onerror() { window.log.error('websocket error'); }, dispatchAndWait(event) { const promise = this.appPromise || Promise.resolve(); const appJobPromise = Promise.all(this.dispatchEvent(event)); const job = () => appJobPromise; this.appPromise = promise.then(job, job); return Promise.resolve(); }, onclose(ev) { window.log.info( 'websocket closed', ev.code, ev.reason || '', 'calledClose:', this.calledClose ); this.shutdown(); if (this.calledClose) { return Promise.resolve(); } if (ev.code === 3000) { return Promise.resolve(); } if (ev.code === 3001) { this.onEmpty(); } // possible 403 or network issue. Make an request to confirm return this.server .getDevices(this.number) .then(this.connect.bind(this)) // No HTTP error? Reconnect .catch(e => { const event = new Event('error'); event.error = e; return this.dispatchAndWait(event); }); }, handleRequest(request) { this.incoming = this.incoming || []; const lastPromise = _.last(this.incoming); // We do the message decryption here, instead of in the ordered pending queue, // to avoid exposing the time it took us to process messages through the time-to-ack. if (request.path !== '/api/v1/message') { window.log.info('got request', request.verb, request.path); request.respond(200, 'OK'); if (request.verb === 'PUT' && request.path === '/api/v1/queue/empty') { this.onEmpty(); } return; } let promise; const headers = request.headers || []; if (headers.includes('X-Signal-Key: true')) { promise = textsecure.crypto.decryptWebsocketMessage( request.body, this.signalingKey ); } else { promise = Promise.resolve(request.body.toArrayBuffer()); } promise = promise .then(plaintext => { const envelope = textsecure.protobuf.Envelope.decode(plaintext); // After this point, decoding errors are not the server's // fault, and we should handle them gracefully and tell the // user they received an invalid message if (this.isBlocked(envelope.source)) { return request.respond(200, 'OK'); } envelope.id = envelope.serverGuid || window.getGuid(); envelope.serverTimestamp = envelope.serverTimestamp ? envelope.serverTimestamp.toNumber() : null; return this.addToCache(envelope, plaintext).then( async () => { request.respond(200, 'OK'); // To ensure that we queue in the same order we receive messages await lastPromise; this.queueEnvelope(envelope); }, error => { request.respond(500, 'Failed to cache message'); window.log.error( 'handleRequest error trying to add message to cache:', error && error.stack ? error.stack : error ); } ); }) .catch(e => { request.respond(500, 'Bad encrypted websocket message'); window.log.error( 'Error handling incoming message:', e && e.stack ? e.stack : e ); const ev = new Event('error'); ev.error = e; return this.dispatchAndWait(ev); }); this.incoming.push(promise); }, addToQueue(task) { this.count += 1; this.pending = this.pending.then(task, task); const { count, pending } = this; const cleanup = () => { this.updateProgress(count); // We want to clear out the promise chain whenever possible because it could // lead to large memory usage over time: // https://github.com/nodejs/node/issues/6673#issuecomment-244331609 if (this.pending === pending) { this.pending = Promise.resolve(); } }; pending.then(cleanup, cleanup); return pending; }, onEmpty() { const { incoming } = this; this.incoming = []; const emitEmpty = () => { window.log.info("MessageReceiver: emitting 'empty' event"); const ev = new Event('empty'); this.dispatchAndWait(ev); }; const waitForApplication = async () => { window.log.info( "MessageReceiver: finished processing messages after 'empty', now waiting for application" ); const promise = this.appPromise || Promise.resolve(); this.appPromise = Promise.resolve(); // We don't await here because we don't this to gate future message processing promise.then(emitEmpty, emitEmpty); }; const waitForEmptyQueue = () => { // resetting count to zero so everything queued after this starts over again this.count = 0; this.addToQueue(waitForApplication); }; // We first wait for all recently-received messages (this.incoming) to be queued, // then we queue a task to wait for the application to finish its processing, then // finally we emit the 'empty' event to the queue. Promise.all(incoming).then(waitForEmptyQueue, waitForEmptyQueue); }, drain() { const { incoming } = this; this.incoming = []; const queueDispatch = () => this.addToQueue(() => { window.log.info('drained'); }); // This promise will resolve when there are no more messages to be processed. return Promise.all(incoming).then(queueDispatch, queueDispatch); }, updateProgress(count) { // count by 10s if (count % 10 !== 0) { return; } const ev = new Event('progress'); ev.count = count; this.dispatchEvent(ev); }, async queueAllCached() { const items = await this.getAllFromCache(); for (let i = 0, max = items.length; i < max; i += 1) { // eslint-disable-next-line no-await-in-loop await this.queueCached(items[i]); } }, async queueCached(item) { try { let envelopePlaintext = item.envelope; if (item.version === 2) { envelopePlaintext = await MessageReceiver.stringToArrayBufferBase64( envelopePlaintext ); } if (typeof envelopePlaintext === 'string') { envelopePlaintext = await MessageReceiver.stringToArrayBuffer( envelopePlaintext ); } const envelope = textsecure.protobuf.Envelope.decode(envelopePlaintext); envelope.id = envelope.serverGuid || item.id; envelope.source = envelope.source || item.source; envelope.sourceDevice = envelope.sourceDevice || item.sourceDevice; envelope.serverTimestamp = envelope.serverTimestamp || item.serverTimestamp; const { decrypted } = item; if (decrypted) { let payloadPlaintext = decrypted; if (item.version === 2) { payloadPlaintext = await MessageReceiver.stringToArrayBufferBase64( payloadPlaintext ); } if (typeof payloadPlaintext === 'string') { payloadPlaintext = await MessageReceiver.stringToArrayBuffer( payloadPlaintext ); } this.queueDecryptedEnvelope(envelope, payloadPlaintext); } else { this.queueEnvelope(envelope); } } catch (error) { window.log.error( 'queueCached error handling item', item.id, 'removing it. Error:', error && error.stack ? error.stack : error ); try { const { id } = item; await textsecure.storage.unprocessed.remove(id); } catch (deleteError) { window.log.error( 'queueCached error deleting item', item.id, 'Error:', deleteError && deleteError.stack ? deleteError.stack : deleteError ); } } }, getEnvelopeId(envelope) { if (envelope.source) { return `${envelope.source}.${ envelope.sourceDevice } ${envelope.timestamp.toNumber()} (${envelope.id})`; } return envelope.id; }, async getAllFromCache() { window.log.info('getAllFromCache'); const count = await textsecure.storage.unprocessed.getCount(); if (count > 1500) { await textsecure.storage.unprocessed.removeAll(); window.log.warn( `There were ${count} messages in cache. Deleted all instead of reprocessing` ); return []; } const items = await textsecure.storage.unprocessed.getAll(); window.log.info('getAllFromCache loaded', items.length, 'saved envelopes'); return Promise.all( _.map(items, async item => { const attempts = 1 + (item.attempts || 0); try { if (attempts >= 3) { window.log.warn( 'getAllFromCache final attempt for envelope', item.id ); await textsecure.storage.unprocessed.remove(item.id); } else { await textsecure.storage.unprocessed.updateAttempts( item.id, attempts ); } } catch (error) { window.log.error( 'getAllFromCache error updating item after load:', error && error.stack ? error.stack : error ); } return item; }) ); }, async addToCache(envelope, plaintext) { const { id } = envelope; const data = { id, version: 2, envelope: await MessageReceiver.arrayBufferToStringBase64(plaintext), timestamp: Date.now(), attempts: 1, }; return textsecure.storage.unprocessed.add(data); }, async updateCache(envelope, plaintext) { const { id } = envelope; const item = await textsecure.storage.unprocessed.get(id); if (!item) { window.log.error( `updateCache: Didn't find item ${id} in cache to update` ); return null; } item.source = envelope.source; item.sourceDevice = envelope.sourceDevice; item.serverTimestamp = envelope.serverTimestamp; if (item.version === 2) { item.decrypted = await MessageReceiver.arrayBufferToStringBase64( plaintext ); } else { item.decrypted = await MessageReceiver.arrayBufferToString(plaintext); } return textsecure.storage.unprocessed.addDecryptedData(item.id, item); }, removeFromCache(envelope) { const { id } = envelope; return textsecure.storage.unprocessed.remove(id); }, queueDecryptedEnvelope(envelope, plaintext) { const id = this.getEnvelopeId(envelope); window.log.info('queueing decrypted envelope', id); const task = this.handleDecryptedEnvelope.bind(this, envelope, plaintext); const taskWithTimeout = textsecure.createTaskWithTimeout( task, `queueEncryptedEnvelope ${id}` ); const promise = this.addToQueue(taskWithTimeout); return promise.catch(error => { window.log.error( 'queueDecryptedEnvelope error handling envelope', id, ':', error && error.stack ? error.stack : error ); }); }, queueEnvelope(envelope) { const id = this.getEnvelopeId(envelope); window.log.info('queueing envelope', id); const task = this.handleEnvelope.bind(this, envelope); const taskWithTimeout = textsecure.createTaskWithTimeout( task, `queueEnvelope ${id}` ); const promise = this.addToQueue(taskWithTimeout); return promise.catch(error => { window.log.error( 'queueEnvelope error handling envelope', id, ':', error && error.stack ? error.stack : error ); }); }, // Same as handleEnvelope, just without the decryption step. Necessary for handling // messages which were successfully decrypted, but application logic didn't finish // processing. handleDecryptedEnvelope(envelope, plaintext) { // No decryption is required for delivery receipts, so the decrypted field of // the Unprocessed model will never be set if (envelope.content) { return this.innerHandleContentMessage(envelope, plaintext); } else if (envelope.legacyMessage) { return this.innerHandleLegacyMessage(envelope, plaintext); } this.removeFromCache(envelope); throw new Error('Received message with no content and no legacyMessage'); }, handleEnvelope(envelope) { if (envelope.type === textsecure.protobuf.Envelope.Type.RECEIPT) { return this.onDeliveryReceipt(envelope); } if (envelope.content) { return this.handleContentMessage(envelope); } else if (envelope.legacyMessage) { return this.handleLegacyMessage(envelope); } this.removeFromCache(envelope); throw new Error('Received message with no content and no legacyMessage'); }, getStatus() { if (this.socket) { return this.socket.readyState; } else if (this.hasConnected) { return WebSocket.CLOSED; } return -1; }, onDeliveryReceipt(envelope) { return new Promise((resolve, reject) => { const ev = new Event('delivery'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.deliveryReceipt = { timestamp: envelope.timestamp.toNumber(), source: envelope.source, sourceDevice: envelope.sourceDevice, }; this.dispatchAndWait(ev).then(resolve, reject); }); }, unpad(paddedData) { const paddedPlaintext = new Uint8Array(paddedData); let plaintext; for (let i = paddedPlaintext.length - 1; i >= 0; i -= 1) { if (paddedPlaintext[i] === 0x80) { plaintext = new Uint8Array(i); plaintext.set(paddedPlaintext.subarray(0, i)); plaintext = plaintext.buffer; break; } else if (paddedPlaintext[i] !== 0x00) { throw new Error('Invalid padding'); } } return plaintext; }, decrypt(envelope, ciphertext) { const { serverTrustRoot } = this; let promise; const address = new libsignal.SignalProtocolAddress( envelope.source, envelope.sourceDevice ); const ourNumber = textsecure.storage.user.getNumber(); const number = address.toString().split('.')[0]; const options = {}; // No limit on message keys if we're communicating with our other devices if (ourNumber === number) { options.messageKeysLimit = false; } const sessionCipher = new libsignal.SessionCipher( textsecure.storage.protocol, address, options ); const secretSessionCipher = new window.Signal.Metadata.SecretSessionCipher( textsecure.storage.protocol ); const me = { number: ourNumber, deviceId: parseInt(textsecure.storage.user.getDeviceId(), 10), }; switch (envelope.type) { case textsecure.protobuf.Envelope.Type.CIPHERTEXT: window.log.info('message from', this.getEnvelopeId(envelope)); promise = sessionCipher .decryptWhisperMessage(ciphertext) .then(this.unpad); break; case textsecure.protobuf.Envelope.Type.PREKEY_BUNDLE: window.log.info('prekey message from', this.getEnvelopeId(envelope)); promise = this.decryptPreKeyWhisperMessage( ciphertext, sessionCipher, address ); break; case textsecure.protobuf.Envelope.Type.UNIDENTIFIED_SENDER: window.log.info('received unidentified sender message'); promise = secretSessionCipher .decrypt( window.Signal.Metadata.createCertificateValidator(serverTrustRoot), ciphertext.toArrayBuffer(), Math.min(envelope.serverTimestamp || Date.now(), Date.now()), me ) .then( result => { const { isMe, sender, content } = result; // We need to drop incoming messages from ourself since server can't // do it for us if (isMe) { return { isMe: true }; } if (this.isBlocked(sender.getName())) { window.log.info( 'Dropping blocked message after sealed sender decryption' ); return { isBlocked: true }; } // Here we take this sender information and attach it back to the envelope // to make the rest of the app work properly. const originalSource = envelope.source; // eslint-disable-next-line no-param-reassign envelope.source = sender.getName(); // eslint-disable-next-line no-param-reassign envelope.sourceDevice = sender.getDeviceId(); // eslint-disable-next-line no-param-reassign envelope.unidentifiedDeliveryReceived = !originalSource; // Return just the content because that matches the signature of the other // decrypt methods used above. return this.unpad(content); }, error => { const { sender } = error || {}; if (sender) { const originalSource = envelope.source; if (this.isBlocked(sender.getName())) { window.log.info( 'Dropping blocked message with error after sealed sender decryption' ); return { isBlocked: true }; } // eslint-disable-next-line no-param-reassign envelope.source = sender.getName(); // eslint-disable-next-line no-param-reassign envelope.sourceDevice = sender.getDeviceId(); // eslint-disable-next-line no-param-reassign envelope.unidentifiedDeliveryReceived = !originalSource; throw error; } return this.removeFromCache(envelope).then(() => { throw error; }); } ); break; default: promise = Promise.reject(new Error('Unknown message type')); } return promise .then(plaintext => { const { isMe, isBlocked } = plaintext || {}; if (isMe || isBlocked) { return this.removeFromCache(envelope); } return this.updateCache(envelope, plaintext).then( () => plaintext, error => { window.log.error( 'decrypt failed to save decrypted message contents to cache:', error && error.stack ? error.stack : error ); return plaintext; } ); }) .catch(error => { let errorToThrow = error; if (error && error.message === 'Unknown identity key') { // create an error that the UI will pick up and ask the // user if they want to re-negotiate const buffer = dcodeIO.ByteBuffer.wrap(ciphertext); errorToThrow = new textsecure.IncomingIdentityKeyError( address.toString(), buffer.toArrayBuffer(), error.identityKey ); } const ev = new Event('error'); ev.error = errorToThrow; ev.proto = envelope; ev.confirm = this.removeFromCache.bind(this, envelope); const returnError = () => Promise.reject(errorToThrow); return this.dispatchAndWait(ev).then(returnError, returnError); }); }, async decryptPreKeyWhisperMessage(ciphertext, sessionCipher, address) { const padded = await sessionCipher.decryptPreKeyWhisperMessage(ciphertext); try { return this.unpad(padded); } catch (e) { if (e.message === 'Unknown identity key') { // create an error that the UI will pick up and ask the // user if they want to re-negotiate const buffer = dcodeIO.ByteBuffer.wrap(ciphertext); throw new textsecure.IncomingIdentityKeyError( address.toString(), buffer.toArrayBuffer(), e.identityKey ); } throw e; } }, handleSentMessage(envelope, sentContainer, msg) { const { destination, timestamp, expirationStartTimestamp, unidentifiedStatus, } = sentContainer; let p = Promise.resolve(); // eslint-disable-next-line no-bitwise if (msg.flags & textsecure.protobuf.DataMessage.Flags.END_SESSION) { p = this.handleEndSession(destination); } return p.then(() => this.processDecrypted(envelope, msg).then(message => { const groupId = message.group && message.group.id; const isBlocked = this.isGroupBlocked(groupId); const isMe = envelope.source === textsecure.storage.user.getNumber(); const isLeavingGroup = Boolean( message.group && message.group.type === textsecure.protobuf.GroupContext.Type.QUIT ); if (groupId && isBlocked && !(isMe && isLeavingGroup)) { window.log.warn( `Message ${this.getEnvelopeId( envelope )} ignored; destined for blocked group` ); return this.removeFromCache(envelope); } const ev = new Event('sent'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.data = { destination, timestamp: timestamp.toNumber(), device: envelope.sourceDevice, unidentifiedStatus, message, }; if (expirationStartTimestamp) { ev.data.expirationStartTimestamp = expirationStartTimestamp.toNumber(); } return this.dispatchAndWait(ev); }) ); }, handleDataMessage(envelope, msg) { window.log.info('data message from', this.getEnvelopeId(envelope)); let p = Promise.resolve(); // eslint-disable-next-line no-bitwise if (msg.flags & textsecure.protobuf.DataMessage.Flags.END_SESSION) { p = this.handleEndSession(envelope.source); } return p.then(() => this.processDecrypted(envelope, msg).then(message => { const groupId = message.group && message.group.id; const isBlocked = this.isGroupBlocked(groupId); const isMe = envelope.source === textsecure.storage.user.getNumber(); const isLeavingGroup = Boolean( message.group && message.group.type === textsecure.protobuf.GroupContext.Type.QUIT ); if (groupId && isBlocked && !(isMe && isLeavingGroup)) { window.log.warn( `Message ${this.getEnvelopeId( envelope )} ignored; destined for blocked group` ); return this.removeFromCache(envelope); } const ev = new Event('message'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.data = { source: envelope.source, sourceDevice: envelope.sourceDevice, timestamp: envelope.timestamp.toNumber(), receivedAt: envelope.receivedAt, unidentifiedDeliveryReceived: envelope.unidentifiedDeliveryReceived, message, }; return this.dispatchAndWait(ev); }) ); }, handleLegacyMessage(envelope) { return this.decrypt(envelope, envelope.legacyMessage).then(plaintext => { if (!plaintext) { window.log.warn('handleLegacyMessage: plaintext was falsey'); return null; } return this.innerHandleLegacyMessage(envelope, plaintext); }); }, innerHandleLegacyMessage(envelope, plaintext) { const message = textsecure.protobuf.DataMessage.decode(plaintext); return this.handleDataMessage(envelope, message); }, handleContentMessage(envelope) { return this.decrypt(envelope, envelope.content).then(plaintext => { if (!plaintext) { window.log.warn('handleContentMessage: plaintext was falsey'); return null; } return this.innerHandleContentMessage(envelope, plaintext); }); }, innerHandleContentMessage(envelope, plaintext) { const content = textsecure.protobuf.Content.decode(plaintext); if (content.syncMessage) { return this.handleSyncMessage(envelope, content.syncMessage); } else if (content.dataMessage) { return this.handleDataMessage(envelope, content.dataMessage); } else if (content.nullMessage) { return this.handleNullMessage(envelope, content.nullMessage); } else if (content.callMessage) { return this.handleCallMessage(envelope, content.callMessage); } else if (content.receiptMessage) { return this.handleReceiptMessage(envelope, content.receiptMessage); } else if (content.typingMessage) { return this.handleTypingMessage(envelope, content.typingMessage); } this.removeFromCache(envelope); throw new Error('Unsupported content message'); }, handleCallMessage(envelope) { window.log.info('call message from', this.getEnvelopeId(envelope)); this.removeFromCache(envelope); }, handleReceiptMessage(envelope, receiptMessage) { const results = []; if ( receiptMessage.type === textsecure.protobuf.ReceiptMessage.Type.DELIVERY ) { for (let i = 0; i < receiptMessage.timestamp.length; i += 1) { const ev = new Event('delivery'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.deliveryReceipt = { timestamp: receiptMessage.timestamp[i].toNumber(), source: envelope.source, sourceDevice: envelope.sourceDevice, }; results.push(this.dispatchAndWait(ev)); } } else if ( receiptMessage.type === textsecure.protobuf.ReceiptMessage.Type.READ ) { for (let i = 0; i < receiptMessage.timestamp.length; i += 1) { const ev = new Event('read'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.timestamp = envelope.timestamp.toNumber(); ev.read = { timestamp: receiptMessage.timestamp[i].toNumber(), reader: envelope.source, }; results.push(this.dispatchAndWait(ev)); } } return Promise.all(results); }, handleTypingMessage(envelope, typingMessage) { const ev = new Event('typing'); this.removeFromCache(envelope); if (envelope.timestamp && typingMessage.timestamp) { const envelopeTimestamp = envelope.timestamp.toNumber(); const typingTimestamp = typingMessage.timestamp.toNumber(); if (typingTimestamp !== envelopeTimestamp) { window.log.warn( `Typing message envelope timestamp (${envelopeTimestamp}) did not match typing timestamp (${typingTimestamp})` ); return null; } } ev.sender = envelope.source; ev.senderDevice = envelope.sourceDevice; ev.typing = { typingMessage, timestamp: typingMessage.timestamp ? typingMessage.timestamp.toNumber() : Date.now(), groupId: typingMessage.groupId ? typingMessage.groupId.toString('binary') : null, started: typingMessage.action === textsecure.protobuf.TypingMessage.Action.STARTED, stopped: typingMessage.action === textsecure.protobuf.TypingMessage.Action.STOPPED, }; return this.dispatchEvent(ev); }, handleNullMessage(envelope) { window.log.info('null message from', this.getEnvelopeId(envelope)); this.removeFromCache(envelope); }, handleSyncMessage(envelope, syncMessage) { if (envelope.source !== this.number) { throw new Error('Received sync message from another number'); } // eslint-disable-next-line eqeqeq if (envelope.sourceDevice == this.deviceId) { throw new Error('Received sync message from our own device'); } if (syncMessage.sent) { const sentMessage = syncMessage.sent; const to = sentMessage.message.group ? `group(${sentMessage.message.group.id.toBinary()})` : sentMessage.destination; window.log.info( 'sent message to', to, sentMessage.timestamp.toNumber(), 'from', this.getEnvelopeId(envelope) ); return this.handleSentMessage(envelope, sentMessage, sentMessage.message); } else if (syncMessage.contacts) { return this.handleContacts(envelope, syncMessage.contacts); } else if (syncMessage.groups) { return this.handleGroups(envelope, syncMessage.groups); } else if (syncMessage.blocked) { return this.handleBlocked(envelope, syncMessage.blocked); } else if (syncMessage.request) { window.log.info('Got SyncMessage Request'); return this.removeFromCache(envelope); } else if (syncMessage.read && syncMessage.read.length) { window.log.info('read messages from', this.getEnvelopeId(envelope)); return this.handleRead(envelope, syncMessage.read); } else if (syncMessage.verified) { return this.handleVerified(envelope, syncMessage.verified); } else if (syncMessage.configuration) { return this.handleConfiguration(envelope, syncMessage.configuration); } throw new Error('Got empty SyncMessage'); }, handleConfiguration(envelope, configuration) { window.log.info('got configuration sync message'); const ev = new Event('configuration'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.configuration = configuration; return this.dispatchAndWait(ev); }, handleVerified(envelope, verified) { const ev = new Event('verified'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.verified = { state: verified.state, destination: verified.destination, identityKey: verified.identityKey.toArrayBuffer(), }; return this.dispatchAndWait(ev); }, handleRead(envelope, read) { const results = []; for (let i = 0; i < read.length; i += 1) { const ev = new Event('readSync'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.timestamp = envelope.timestamp.toNumber(); ev.read = { timestamp: read[i].timestamp.toNumber(), sender: read[i].sender, }; results.push(this.dispatchAndWait(ev)); } return Promise.all(results); }, handleContacts(envelope, contacts) { window.log.info('contact sync'); const { blob } = contacts; // Note: we do not return here because we don't want to block the next message on // this attachment download and a lot of processing of that attachment. this.handleAttachment(blob).then(attachmentPointer => { const results = []; const contactBuffer = new ContactBuffer(attachmentPointer.data); let contactDetails = contactBuffer.next(); while (contactDetails !== undefined) { const ev = new Event('contact'); ev.contactDetails = contactDetails; results.push(this.dispatchAndWait(ev)); contactDetails = contactBuffer.next(); } const ev = new Event('contactsync'); results.push(this.dispatchAndWait(ev)); return Promise.all(results).then(() => { window.log.info('handleContacts: finished'); return this.removeFromCache(envelope); }); }); }, handleGroups(envelope, groups) { window.log.info('group sync'); const { blob } = groups; // Note: we do not return here because we don't want to block the next message on // this attachment download and a lot of processing of that attachment. this.handleAttachment(blob).then(attachmentPointer => { const groupBuffer = new GroupBuffer(attachmentPointer.data); let groupDetails = groupBuffer.next(); const promises = []; while (groupDetails !== undefined) { groupDetails.id = groupDetails.id.toBinary(); const ev = new Event('group'); ev.confirm = this.removeFromCache.bind(this, envelope); ev.groupDetails = groupDetails; const promise = this.dispatchAndWait(ev).catch(e => { window.log.error('error processing group', e); }); groupDetails = groupBuffer.next(); promises.push(promise); } Promise.all(promises).then(() => { const ev = new Event('groupsync'); ev.confirm = this.removeFromCache.bind(this, envelope); return this.dispatchAndWait(ev); }); }); }, handleBlocked(envelope, blocked) { window.log.info('Setting these numbers as blocked:', blocked.numbers); textsecure.storage.put('blocked', blocked.numbers); const groupIds = _.map(blocked.groupIds, groupId => groupId.toBinary()); window.log.info( 'Setting these groups as blocked:', groupIds.map(groupId => `group(${groupId})`) ); textsecure.storage.put('blocked-groups', groupIds); return this.removeFromCache(envelope); }, isBlocked(number) { return textsecure.storage.get('blocked', []).indexOf(number) >= 0; }, isGroupBlocked(groupId) { return textsecure.storage.get('blocked-groups', []).indexOf(groupId) >= 0; }, cleanAttachment(attachment) { return { ..._.omit(attachment, 'thumbnail'), id: attachment.id.toString(), key: attachment.key ? attachment.key.toString('base64') : null, digest: attachment.digest ? attachment.digest.toString('base64') : null, }; }, async downloadAttachment(attachment) { const encrypted = await this.server.getAttachment(attachment.id); const { key, digest } = attachment; const data = await textsecure.crypto.decryptAttachment( encrypted, window.Signal.Crypto.base64ToArrayBuffer(key), window.Signal.Crypto.base64ToArrayBuffer(digest) ); return { ..._.omit(attachment, 'digest', 'key'), data, }; }, handleAttachment(attachment) { const cleaned = this.cleanAttachment(attachment); return this.downloadAttachment(cleaned); }, async handleEndSession(number) { window.log.info('got end session'); const deviceIds = await textsecure.storage.protocol.getDeviceIds(number); return Promise.all( deviceIds.map(deviceId => { const address = new libsignal.SignalProtocolAddress(number, deviceId); const sessionCipher = new libsignal.SessionCipher( textsecure.storage.protocol, address ); window.log.info('deleting sessions for', address.toString()); return sessionCipher.deleteAllSessionsForDevice(); }) ); }, processDecrypted(envelope, decrypted) { /* eslint-disable no-bitwise, no-param-reassign */ const FLAGS = textsecure.protobuf.DataMessage.Flags; // Now that its decrypted, validate the message and clean it up for consumer // processing // Note that messages may (generally) only perform one action and we ignore remaining // fields after the first action. if (decrypted.flags == null) { decrypted.flags = 0; } if (decrypted.expireTimer == null) { decrypted.expireTimer = 0; } if (decrypted.flags & FLAGS.END_SESSION) { decrypted.body = null; decrypted.attachments = []; decrypted.group = null; return Promise.resolve(decrypted); } else if (decrypted.flags & FLAGS.EXPIRATION_TIMER_UPDATE) { decrypted.body = null; decrypted.attachments = []; } else if (decrypted.flags & FLAGS.PROFILE_KEY_UPDATE) { decrypted.body = null; decrypted.attachments = []; } else if (decrypted.flags !== 0) { throw new Error('Unknown flags in message'); } const promises = []; if (decrypted.group !== null) { decrypted.group.id = decrypted.group.id.toBinary(); switch (decrypted.group.type) { case textsecure.protobuf.GroupContext.Type.UPDATE: decrypted.body = null; decrypted.attachments = []; break; case textsecure.protobuf.GroupContext.Type.QUIT: decrypted.body = null; decrypted.attachments = []; break; case textsecure.protobuf.GroupContext.Type.DELIVER: decrypted.group.name = null; decrypted.group.members = []; decrypted.group.avatar = null; break; default: this.removeFromCache(envelope); throw new Error('Unknown group message type'); } } const attachmentCount = decrypted.attachments.length; const ATTACHMENT_MAX = 32; if (attachmentCount > ATTACHMENT_MAX) { throw new Error( `Too many attachments: ${attachmentCount} included in one message, max is ${ATTACHMENT_MAX}` ); } // Here we go from binary to string/base64 in all AttachmentPointer digest/key fields if ( decrypted.group && decrypted.group.type === textsecure.protobuf.GroupContext.Type.UPDATE ) { if (decrypted.group.avatar !== null) { decrypted.group.avatar = this.cleanAttachment(decrypted.group.avatar); } } decrypted.attachments = (decrypted.attachments || []).map( this.cleanAttachment.bind(this) ); decrypted.preview = (decrypted.preview || []).map(item => { const { image } = item; if (!image) { return item; } return { ...item, image: this.cleanAttachment(image), }; }); decrypted.contact = (decrypted.contact || []).map(item => { const { avatar } = item; if (!avatar || !avatar.avatar) { return item; } return { ...item, avatar: { ...item.avatar, avatar: this.cleanAttachment(item.avatar.avatar), }, }; }); if (decrypted.quote && decrypted.quote.id) { decrypted.quote.id = decrypted.quote.id.toNumber(); } if (decrypted.quote) { decrypted.quote.attachments = (decrypted.quote.attachments || []).map( item => { const { thumbnail } = item; if (!thumbnail) { return item; } return { ...item, thumbnail: this.cleanAttachment(item.thumbnail), }; } ); } return Promise.all(promises).then(() => decrypted); /* eslint-enable no-bitwise, no-param-reassign */ }, }); window.textsecure = window.textsecure || {}; textsecure.MessageReceiver = function MessageReceiverWrapper( username, password, signalingKey, options ) { const messageReceiver = new MessageReceiver( username, password, signalingKey, options ); this.addEventListener = messageReceiver.addEventListener.bind( messageReceiver ); this.removeEventListener = messageReceiver.removeEventListener.bind( messageReceiver ); this.getStatus = messageReceiver.getStatus.bind(messageReceiver); this.close = messageReceiver.close.bind(messageReceiver); this.downloadAttachment = messageReceiver.downloadAttachment.bind( messageReceiver ); messageReceiver.connect(); }; textsecure.MessageReceiver.prototype = { constructor: textsecure.MessageReceiver, }; textsecure.MessageReceiver.stringToArrayBuffer = MessageReceiver.stringToArrayBuffer; textsecure.MessageReceiver.arrayBufferToString = MessageReceiver.arrayBufferToString; textsecure.MessageReceiver.stringToArrayBufferBase64 = MessageReceiver.stringToArrayBufferBase64; textsecure.MessageReceiver.arrayBufferToStringBase64 = MessageReceiver.arrayBufferToStringBase64;
MessageReceiver: Don't wait for cache update to move forward
libtextsecure/message_receiver.js
MessageReceiver: Don't wait for cache update to move forward
<ide><path>ibtextsecure/message_receiver.js <ide> .then(plaintext => { <ide> const { isMe, isBlocked } = plaintext || {}; <ide> if (isMe || isBlocked) { <del> return this.removeFromCache(envelope); <add> this.removeFromCache(envelope); <add> return null; <ide> } <ide> <del> return this.updateCache(envelope, plaintext).then( <del> () => plaintext, <del> error => { <del> window.log.error( <del> 'decrypt failed to save decrypted message contents to cache:', <del> error && error.stack ? error.stack : error <del> ); <del> return plaintext; <del> } <del> ); <add> this.updateCache(envelope, plaintext).catch(error => { <add> window.log.error( <add> 'decrypt failed to save decrypted message contents to cache:', <add> error && error.stack ? error.stack : error <add> ); <add> }); <add> <add> return plaintext; <ide> }) <ide> .catch(error => { <ide> let errorToThrow = error;
JavaScript
mit
e0ce4b5b2f2bacbe731fe22844fcfd85fd988ee6
0
spark/winston-papertrail,kenperkins/winston-papertrail
/* * winston-papertrail.js: * * Transport for logging to Papertrail Service * www.papertrailapp.com * * (C) 2013 Ken Perkins * MIT LICENCE * */ var os = require('os'), net = require('net'), tls = require('tls'), syslogProducer = require('glossy').Produce, util = require('util'), winston = require('winston'); /** * Papertrail class * * @description constructor for the Papertrail transport * * @param {object} options options for your papertrail transport * * @param {string} options.host host for papertrail endpoint * * @param {Number} options.port port for papertrail endpoint * * @param {Boolean} [options.disableTls] disable TLS connections, enabled by default * * @param {string} [options.hostname] name for the logging hostname in Papertrail * * @param {string} [options.program] name for the logging program * * @param {string} [options.facility] syslog facility for log messages * * @param {string} [options.level] log level for your transport (info) * * @param {Function} [options.logFormat] function to format your log message before sending * * @param {Number} [options.attemptsBeforeDecay] how many reconnections should * be attempted before backing of (5) * * @param {Number} [options.maximumAttempts] maximum attempts before * disabling buffering (25) * * @param {Number} [options.connectionDelay] delay between * reconnection attempts in ms (1000) * * @param {Boolean} [options.handleExceptions] passed to base Transport (false) * * @param {Boolean} [options.colorize] enable colors in Papertrail (false) * * @param {Number} [options.maxDelayBetweenReconnection] when backing off, * what's the max time between * reconnections (ms) * * @param {Boolean} [options.inlineMeta] inline multi-line messages (false) * * @type {Function} */ var Papertrail = exports.Papertrail = function (options) { var self = this; self._KEEPALIVE_INTERVAL = 15 * 1000; options = options || {}; self.name = 'Papertrail'; self.level = options.level || 'info'; // Papertrail Service Host self.host = options.host; // Papertrail Service Port self.port = options.port; // Disable TLS connections (enabled by default) self.disableTls = typeof options.disableTls === 'boolean' ? options.disableTls : false; // Hostname of the current app self.hostname = options.hostname || os.hostname(); // Program is an affordance for Papertrail to name the source of log entries self.program = options.program || 'default'; // Syslog facility to log messages as to Papertrail self.facility = options.facility || 'daemon'; // Send ANSI color codes through to Papertrail self.colorize = options.colorize || false; // Format your log messages prior to delivery self.logFormat = options.logFormat || function (level, message) { return level + ' ' + message; }; // Number of attempts before decaying reconnection self.attemptsBeforeDecay = options.attemptsBeforeDecay || 5; // Maximum number of reconnection attempts before disabling buffer self.maximumAttempts = options.maximumAttempts || 25; // Delay between normal attempts self.connectionDelay = options.connectionDelay || 1000; // Handle Exceptions self.handleExceptions = options.handleExceptions || false; // Maximum delay between attempts self.maxDelayBetweenReconnection = options.maxDelayBetweenReconnection || 60000; // Maximum buffer size (default: 1MB) self.maxBufferSize = options.maxBufferSize || 1 * 1024 * 1024; // Inline meta flag self.inlineMeta = options.inlineMeta || false; self.producer = new syslogProducer({ facility: self.facility }); self.currentRetries = 0; self.totalRetries = 0; self.buffer = ''; self.loggingEnabled = true; self._shutdown = false; // Error out if we don't have a host or port if (!self.host || !self.port) { throw new Error('Missing required parameters: host and port'); } // Open the connection connectStream(); function cleanup() { self._erroring = true; try { if (self.socket) { self.socket.end(); self.socket = null; } } catch (e) { } try { if (self.stream) { //we're cleaning up, don't loop. self.stream.removeListener('end', connectStream); // self.stream.removeListener('error', onErrored); self.stream.end(); self.stream = null; } } catch (e) { } self._erroring = false; } function wireStreams() { self.stream.once('error', onErrored); // If we have the stream end, simply reconnect self.stream.once('end', connectStream); } // Opens a connection to Papertrail function connectStream() { // don't connect on either error or shutdown if (self._shutdown || self._erroring) { return; } cleanup(); try { if (self.disableTls) { self.stream = net.createConnection(self.port, self.host, onConnected); self.stream.setKeepAlive(true, self._KEEPALIVE_INTERVAL); wireStreams(); } else { var socket = net.createConnection(self.port, self.host, function () { socket.setKeepAlive(true, self._KEEPALIVE_INTERVAL); self.stream = tls.connect({ socket: socket, rejectUnauthorized: false }, onConnected); wireStreams(); }); socket.on('error', onErrored); self.socket = socket; } } catch (e) { onErrored(e); } } function onErrored(err) { // make sure we prevent simultaneous attempts to connect and handle errors self._erroring = true; self.emit('error', err); // We may be disconnected from the papertrail endpoint for any number of reasons; // i.e. inactivity, network problems, etc, and we need to be resilient against this // that said, we back off reconnection attempts in case Papertrail is truly down setTimeout(function () { // Increment our retry counts self.currentRetries++; self.totalRetries++; // Decay the retry rate exponentially up to max between attempts if ((self.connectionDelay < self.maxDelayBetweenReconnection) && (self.currentRetries >= self.attemptsBeforeDecay)) { self.connectionDelay = self.connectionDelay * 2; self.currentRetries = 0; } // Stop buffering messages after a fixed number of retries. // This is to keep the buffer from growing unbounded if (self.loggingEnabled && (self.totalRetries >= (self.maximumAttempts))) { self.loggingEnabled = false; self.emit('error', new Error('Max entries eclipsed, disabling buffering')); } // continue self._erroring = false; connectStream(); }, self.connectionDelay); } function onConnected() { // Reset our variables self.loggingEnabled = true; self.currentRetries = 0; self.totalRetries = 0; self.connectionDelay = options.connectionDelay || 1000; self.emit('connect', 'Connected to Papertrail at ' + self.host + ':' + self.port); // Did we get messages buffered if (self.buffer.length > 0) { self.stream.write(self.buffer); self.buffer = ''; } } }; // // // Inherit from `winston.Transport` so you can take advantage // of the base functionality and `.handleExceptions()`. // util.inherits(Papertrail, winston.Transport); // // Define a getter so that `winston.transports.Papertrail` // is available and thus backwards compatible. // winston.transports.Papertrail = Papertrail; /** * Papertrail.log * * @description Core logging method exposed to Winston. Metadata is optional. * * @param {String} level Level at which to log the message. * @param {String} msg Message to log * @param {String|object|Function} [meta] Optional metadata to attach * @param {Function} callback * @returns {*} */ Papertrail.prototype.log = function (level, msg, meta, callback) { var self = this; // make sure we handle when meta isn't provided if (typeof(meta) === 'function' && !callback) { callback = meta; meta = false; } if (meta && typeof meta === 'object' && (Object.keys(meta).length === 0) && (!util.isError(meta))) { meta = false; } // If the logging buffer is disabled, drop the message on the floor if (!this.loggingEnabled) { return callback(null, true); } var output = msg; // If we don't have a string for the message, // lets transform it before moving on if (typeof(output) !== 'string') { output = util.inspect(output, false, null, self.colorize); } if (meta) { if (typeof meta !== 'object') { output += ' ' + meta; } else if (meta) { if (this.inlineMeta) { output += ' ' + util.inspect(meta, false, null, self.colorize).replace(/[\n\t]\s*/gm, " "); } else { output += '\n' + util.inspect(meta, false, null, self.colorize); } } } this.sendMessage(this.hostname, this.program, level, output); callback(null, true); }; /** * Papertrail.sendMessage * * @description sending the message to the stream, or buffering if not connected * * @param {String} hostname Hostname of the source application. * @param {String} program Name of the source application * @param {String} level Log level of the message * @param {String} message The message to deliver */ Papertrail.prototype.sendMessage = function (hostname, program, level, message) { var self = this, lines = [], msg = '', gap = ''; // Only split if we actually have a message if (message) { lines = message.split('\n'); } else { lines = ['']; } // If the incoming message has multiple lines, break them and format each // line as it's own message for (var i = 0; i < lines.length; i++) { // don't send extra message if our message ends with a newline if ((lines[i].length === 0) && (i == lines.length - 1)) { break; } if (i == 1) { gap = ' '; } msg += self.producer.produce({ severity: level, host: hostname, appName: program, date: new Date(), message: self.logFormat(self.colorize ? winston.config.colorize(level) : level, gap + lines[i]) }) + '\r\n'; } if (this.stream && this.stream.writable) { this.stream.write(msg); } else if (this.loggingEnabled && this.buffer.length < this.maxBufferSize) { this.buffer += msg; } }; /** * Papertrail.close * * @description closes the underlying TLS connection and disables automatic * reconnection, allowing the process to exit */ Papertrail.prototype.close = function() { var self = this; self._shutdown = true; if (self.stream) { self.stream.end(); } // if there's no stream yet, that means we're still connecting // lets wire a connect handler, and then invoke close again else { self.on('connect', function() { self.close(); }); } };
lib/winston-papertrail.js
/* * winston-papertrail.js: * * Transport for logging to Papertrail Service * www.papertrailapp.com * * (C) 2013 Ken Perkins * MIT LICENCE * */ var os = require('os'), net = require('net'), tls = require('tls'), syslogProducer = require('glossy').Produce, util = require('util'), winston = require('winston'); /** * Papertrail class * * @description constructor for the Papertrail transport * * @param {object} options options for your papertrail transport * * @param {string} options.host host for papertrail endpoint * * @param {Number} options.port port for papertrail endpoint * * @param {Boolean} [options.disableTls] disable TLS connections, enabled by default * * @param {string} [options.hostname] name for the logging hostname in Papertrail * * @param {string} [options.program] name for the logging program * * @param {string} [options.facility] syslog facility for log messages * * @param {string} [options.level] log level for your transport (info) * * @param {Function} [options.logFormat] function to format your log message before sending * * @param {Number} [options.attemptsBeforeDecay] how many reconnections should * be attempted before backing of (5) * * @param {Number} [options.maximumAttempts] maximum attempts before * disabling buffering (25) * * @param {Number} [options.connectionDelay] delay between * reconnection attempts in ms (1000) * * @param {Boolean} [options.handleExceptions] passed to base Transport (false) * * @param {Boolean} [options.colorize] enable colors in Papertrail (false) * * @param {Number} [options.maxDelayBetweenReconnection] when backing off, * what's the max time between * reconnections (ms) * * @param {Boolean} [options.inlineMeta] inline multi-line messages (false) * * @type {Function} */ var Papertrail = exports.Papertrail = function (options) { var self = this; self._KEEPALIVE_INTERVAL = 15 * 1000; options = options || {}; self.name = 'Papertrail'; self.level = options.level || 'info'; // Papertrail Service Host self.host = options.host; // Papertrail Service Port self.port = options.port; // Disable TLS connections (enabled by default) self.disableTls = typeof options.disableTls === 'boolean' ? options.disableTls : false; // Hostname of the current app self.hostname = options.hostname || os.hostname(); // Program is an affordance for Papertrail to name the source of log entries self.program = options.program || 'default'; // Syslog facility to log messages as to Papertrail self.facility = options.facility || 'daemon'; // Send ANSI color codes through to Papertrail self.colorize = options.colorize || false; // Format your log messages prior to delivery self.logFormat = options.logFormat || function (level, message) { return level + ' ' + message; }; // Number of attempts before decaying reconnection self.attemptsBeforeDecay = options.attemptsBeforeDecay || 5; // Maximum number of reconnection attempts before disabling buffer self.maximumAttempts = options.maximumAttempts || 25; // Delay between normal attempts self.connectionDelay = options.connectionDelay || 1000; // Handle Exceptions self.handleExceptions = options.handleExceptions || false; // Maximum delay between attempts self.maxDelayBetweenReconnection = options.maxDelayBetweenReconnection || 60000; // Maximum buffer size (default: 1MB) self.maxBufferSize = options.maxBufferSize || 1 * 1024 * 1024; // Inline meta flag self.inlineMeta = options.inlineMeta || false; self.producer = new syslogProducer({ facility: self.facility }); self.currentRetries = 0; self.totalRetries = 0; self.buffer = ''; self.loggingEnabled = true; self._shutdown = false; // Error out if we don't have a host or port if (!self.host || !self.port) { throw new Error('Missing required parameters: host and port'); } // Open the connection connectStream(); function cleanup() { self._erroring = true; try { if (self.socket) { self.socket.end(); self.socket = null; } } catch (e) { } try { if (self.stream) { //we're cleaning up, don't loop. // self.stream.removeListener('end', connectStream); // self.stream.removeListener('error', onErrored); self.stream.end(); self.stream = null; } } catch (e) { } self._erroring = false; } function wireStreams() { self.stream.once('error', onErrored); // If we have the stream end, simply reconnect self.stream.once('end', connectStream); } // Opens a connection to Papertrail function connectStream() { // don't connect on either error or shutdown if (self._shutdown || self._erroring) { return; } cleanup(); try { if (self.disableTls) { self.stream = net.createConnection(self.port, self.host, onConnected); self.stream.setKeepAlive(true, self._KEEPALIVE_INTERVAL); wireStreams(); } else { var socket = net.createConnection(self.port, self.host, function () { socket.setKeepAlive(true, self._KEEPALIVE_INTERVAL); self.stream = tls.connect({ socket: socket, rejectUnauthorized: false }, onConnected); wireStreams(); }); socket.on('error', onErrored); self.socket = socket; } } catch (e) { onErrored(e); } } function onErrored(err) { // make sure we prevent simultaneous attempts to connect and handle errors self._erroring = true; self.emit('error', err); // We may be disconnected from the papertrail endpoint for any number of reasons; // i.e. inactivity, network problems, etc, and we need to be resilient against this // that said, we back off reconnection attempts in case Papertrail is truly down setTimeout(function () { // Increment our retry counts self.currentRetries++; self.totalRetries++; // Decay the retry rate exponentially up to max between attempts if ((self.connectionDelay < self.maxDelayBetweenReconnection) && (self.currentRetries >= self.attemptsBeforeDecay)) { self.connectionDelay = self.connectionDelay * 2; self.currentRetries = 0; } // Stop buffering messages after a fixed number of retries. // This is to keep the buffer from growing unbounded if (self.loggingEnabled && (self.totalRetries >= (self.maximumAttempts))) { self.loggingEnabled = false; self.emit('error', new Error('Max entries eclipsed, disabling buffering')); } // continue self._erroring = false; connectStream(); }, self.connectionDelay); } function onConnected() { // Reset our variables self.loggingEnabled = true; self.currentRetries = 0; self.totalRetries = 0; self.connectionDelay = options.connectionDelay || 1000; self.emit('connect', 'Connected to Papertrail at ' + self.host + ':' + self.port); // Did we get messages buffered if (self.buffer.length > 0) { self.stream.write(self.buffer); self.buffer = ''; } } }; // // // Inherit from `winston.Transport` so you can take advantage // of the base functionality and `.handleExceptions()`. // util.inherits(Papertrail, winston.Transport); // // Define a getter so that `winston.transports.Papertrail` // is available and thus backwards compatible. // winston.transports.Papertrail = Papertrail; /** * Papertrail.log * * @description Core logging method exposed to Winston. Metadata is optional. * * @param {String} level Level at which to log the message. * @param {String} msg Message to log * @param {String|object|Function} [meta] Optional metadata to attach * @param {Function} callback * @returns {*} */ Papertrail.prototype.log = function (level, msg, meta, callback) { var self = this; // make sure we handle when meta isn't provided if (typeof(meta) === 'function' && !callback) { callback = meta; meta = false; } if (meta && typeof meta === 'object' && (Object.keys(meta).length === 0) && (!util.isError(meta))) { meta = false; } // If the logging buffer is disabled, drop the message on the floor if (!this.loggingEnabled) { return callback(null, true); } var output = msg; // If we don't have a string for the message, // lets transform it before moving on if (typeof(output) !== 'string') { output = util.inspect(output, false, null, self.colorize); } if (meta) { if (typeof meta !== 'object') { output += ' ' + meta; } else if (meta) { if (this.inlineMeta) { output += ' ' + util.inspect(meta, false, null, self.colorize).replace(/[\n\t]\s*/gm, " "); } else { output += '\n' + util.inspect(meta, false, null, self.colorize); } } } this.sendMessage(this.hostname, this.program, level, output); callback(null, true); }; /** * Papertrail.sendMessage * * @description sending the message to the stream, or buffering if not connected * * @param {String} hostname Hostname of the source application. * @param {String} program Name of the source application * @param {String} level Log level of the message * @param {String} message The message to deliver */ Papertrail.prototype.sendMessage = function (hostname, program, level, message) { var self = this, lines = [], msg = '', gap = ''; // Only split if we actually have a message if (message) { lines = message.split('\n'); } else { lines = ['']; } // If the incoming message has multiple lines, break them and format each // line as it's own message for (var i = 0; i < lines.length; i++) { // don't send extra message if our message ends with a newline if ((lines[i].length === 0) && (i == lines.length - 1)) { break; } if (i == 1) { gap = ' '; } msg += self.producer.produce({ severity: level, host: hostname, appName: program, date: new Date(), message: self.logFormat(self.colorize ? winston.config.colorize(level) : level, gap + lines[i]) }) + '\r\n'; } if (this.stream && this.stream.writable) { this.stream.write(msg); } else if (this.loggingEnabled && this.buffer.length < this.maxBufferSize) { this.buffer += msg; } }; /** * Papertrail.close * * @description closes the underlying TLS connection and disables automatic * reconnection, allowing the process to exit */ Papertrail.prototype.close = function() { var self = this; self._shutdown = true; if (self.stream) { self.stream.end(); } // if there's no stream yet, that means we're still connecting // lets wire a connect handler, and then invoke close again else { self.on('connect', function() { self.close(); }); } };
lol j/k
lib/winston-papertrail.js
lol j/k
<ide><path>ib/winston-papertrail.js <ide> try { <ide> if (self.stream) { <ide> //we're cleaning up, don't loop. <del>// self.stream.removeListener('end', connectStream); <add> self.stream.removeListener('end', connectStream); <ide> // self.stream.removeListener('error', onErrored); <ide> <ide> self.stream.end();
Java
apache-2.0
10a8a3097c68d8234d2ac799c6f95828bac1cebc
0
Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces,Gigaspaces/xap-openspaces
package org.openspaces.admin.internal.admin; import com.gigaspaces.grid.gsm.PUDetails; import com.gigaspaces.grid.gsm.PUsDetails; import com.gigaspaces.jvm.JVMDetails; import com.gigaspaces.lrmi.nio.info.NIODetails; import com.gigaspaces.operatingsystem.OSDetails; import net.jini.core.discovery.LookupLocator; import org.openspaces.admin.gsc.GridServiceContainers; import org.openspaces.admin.gsm.GridServiceManager; import org.openspaces.admin.gsm.GridServiceManagers; import org.openspaces.admin.internal.discovery.DiscoveryService; import org.openspaces.admin.internal.gsc.DefaultGridServiceContainers; import org.openspaces.admin.internal.gsc.InternalGridServiceContainer; import org.openspaces.admin.internal.gsc.InternalGridServiceContainers; import org.openspaces.admin.internal.gsm.DefaultGridServiceManagers; import org.openspaces.admin.internal.gsm.InternalGridServiceManager; import org.openspaces.admin.internal.gsm.InternalGridServiceManagers; import org.openspaces.admin.internal.lus.DefaultLookupServices; import org.openspaces.admin.internal.lus.InternalLookupService; import org.openspaces.admin.internal.lus.InternalLookupServices; import org.openspaces.admin.internal.machine.DefaultMachine; import org.openspaces.admin.internal.machine.DefaultMachines; import org.openspaces.admin.internal.machine.InternalMachine; import org.openspaces.admin.internal.machine.InternalMachineAware; import org.openspaces.admin.internal.machine.InternalMachines; import org.openspaces.admin.internal.os.DefaultOperatingSystem; import org.openspaces.admin.internal.os.DefaultOperatingSystems; import org.openspaces.admin.internal.os.InternalOperatingSystem; import org.openspaces.admin.internal.os.InternalOperatingSystemInfoProvider; import org.openspaces.admin.internal.os.InternalOperatingSystems; import org.openspaces.admin.internal.pu.DefaultProcessingUnit; import org.openspaces.admin.internal.pu.DefaultProcessingUnits; import org.openspaces.admin.internal.pu.InternalProcessingUnit; import org.openspaces.admin.internal.pu.InternalProcessingUnits; import org.openspaces.admin.internal.transport.DefaultTransport; import org.openspaces.admin.internal.transport.DefaultTransports; import org.openspaces.admin.internal.transport.InternalTransport; import org.openspaces.admin.internal.transport.InternalTransportInfoProvider; import org.openspaces.admin.internal.transport.InternalTransports; import org.openspaces.admin.internal.vm.DefaultVirtualMachine; import org.openspaces.admin.internal.vm.DefaultVirtualMachines; import org.openspaces.admin.internal.vm.InternalVirtualMachine; import org.openspaces.admin.internal.vm.InternalVirtualMachineInfoProvider; import org.openspaces.admin.internal.vm.InternalVirtualMachines; import org.openspaces.admin.lus.LookupServices; import org.openspaces.admin.machine.Machines; import org.openspaces.admin.os.OperatingSystem; import org.openspaces.admin.pu.ProcessingUnit; import org.openspaces.admin.pu.ProcessingUnits; import org.openspaces.admin.transport.TransportDetails; import org.openspaces.admin.transport.Transports; import org.openspaces.admin.vm.VirtualMachine; import org.openspaces.admin.vm.VirtualMachines; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * @author kimchy */ public class DefaultAdmin implements InternalAdmin { private ScheduledThreadPoolExecutor scheduledExecutorService; private final DiscoveryService discoveryService; private final InternalLookupServices lookupServices = new DefaultLookupServices(); private final InternalMachines machines = new DefaultMachines(); private final InternalGridServiceManagers gridServiceManagers = new DefaultGridServiceManagers(); private final InternalGridServiceContainers gridServiceContainers = new DefaultGridServiceContainers(); private final InternalTransports transports = new DefaultTransports(); private final InternalOperatingSystems operatingSystems = new DefaultOperatingSystems(); private final InternalVirtualMachines virtualMachines = new DefaultVirtualMachines(); private final InternalProcessingUnits processingUnits = new DefaultProcessingUnits(); private volatile long scheduledProcessingUnitMonitorInterval = 1000; // default to one second private Future scheduledProcessingUnitMonitorFuture; private volatile boolean closed = false; public DefaultAdmin(String[] groups, LookupLocator[] locators) { this.discoveryService = new DiscoveryService(groups, locators, this); } // should be called once after construction public void begin() { discoveryService.start(); this.scheduledExecutorService = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5); scheduledProcessingUnitMonitorFuture = scheduledExecutorService.scheduleWithFixedDelay( new ScheduledProcessingUnitMonitor(), scheduledProcessingUnitMonitorInterval, scheduledProcessingUnitMonitorInterval, TimeUnit.MILLISECONDS); } public void setProcessingUnitMonitorInterval(long interval, TimeUnit timeUnit) { if (closed) { throw new IllegalStateException("Admin already closed"); } this.scheduledProcessingUnitMonitorInterval = timeUnit.toMillis(interval); if (scheduledProcessingUnitMonitorFuture != null) { // during initialization scheduledProcessingUnitMonitorFuture.cancel(false); scheduledProcessingUnitMonitorFuture = scheduledExecutorService.scheduleWithFixedDelay(new ScheduledProcessingUnitMonitor(), interval, interval, timeUnit); } } public void setSchedulerCorePoolSize(int coreThreads) { scheduledExecutorService.setCorePoolSize(coreThreads); } public void close() { if (closed) { return; } closed = true; discoveryService.stop(); scheduledExecutorService.shutdownNow(); } public LookupServices getLookupServices() { return this.lookupServices; } public GridServiceManagers getGridServiceManagers() { return this.gridServiceManagers; } public GridServiceContainers getGridServiceContainers() { return this.gridServiceContainers; } public Machines getMachines() { return this.machines; } public Transports getTransports() { return this.transports; } public VirtualMachines getVirtualMachines() { return this.virtualMachines; } public ProcessingUnits getProcessingUnits() { return this.processingUnits; } public synchronized void addLookupService(InternalLookupService lookupService, NIODetails nioDetails, OSDetails osDetails, JVMDetails jvmDetails) { InternalTransport transport = processTransportOnServiceAddition(lookupService, nioDetails); OperatingSystem operatingSystem = processOperatingSystemOnServiceAddition(lookupService, osDetails); VirtualMachine virtualMachine = processVirtualMachineOnServiceAddition(lookupService, jvmDetails); InternalMachine machine = processMachineOnServiceAddition(transport.getDetails(), transport, operatingSystem, virtualMachine, (InternalMachineAware) virtualMachine, lookupService); ((InternalLookupServices) machine.getLookupServices()).addLookupService(lookupService); lookupServices.addLookupService(lookupService); } public synchronized void removeLookupService(String uid) { InternalLookupService lookupService = lookupServices.removeLookupService(uid); if (lookupService != null) { processTransportOnServiceRemoval(lookupService, lookupService); processOperatingSystemOnServiceRemoval(lookupService, lookupService); processVirtualMachineOnServiceRemoval(lookupService, lookupService); ((InternalLookupServices) ((InternalMachine) lookupService.getMachine()).getLookupServices()).removeLookupService(uid); } } public synchronized void addGridServiceManager(InternalGridServiceManager gridServiceManager, NIODetails nioDetails, OSDetails osDetails, JVMDetails jvmDetails) { InternalTransport transport = processTransportOnServiceAddition(gridServiceManager, nioDetails); OperatingSystem operatingSystem = processOperatingSystemOnServiceAddition(gridServiceManager, osDetails); VirtualMachine virtualMachine = processVirtualMachineOnServiceAddition(gridServiceManager, jvmDetails); InternalMachine machine = processMachineOnServiceAddition(transport.getDetails(), transport, operatingSystem, virtualMachine, (InternalMachineAware) virtualMachine, gridServiceManager); ((InternalGridServiceManagers) machine.getGridServiceManagers()).addGridServiceManager(gridServiceManager); gridServiceManagers.addGridServiceManager(gridServiceManager); } public synchronized void removeGridServiceManager(String uid) { InternalGridServiceManager gridServiceManager = gridServiceManagers.removeGridServiceManager(uid); if (gridServiceManager != null) { processTransportOnServiceRemoval(gridServiceManager, gridServiceManager); processOperatingSystemOnServiceRemoval(gridServiceManager, gridServiceManager); processVirtualMachineOnServiceRemoval(gridServiceManager, gridServiceManager); ((InternalGridServiceManagers) ((InternalMachine) gridServiceManager.getMachine()).getGridServiceManagers()).removeGridServiceManager(uid); } } public synchronized void addGridServiceContainer(InternalGridServiceContainer gridServiceContainer, NIODetails nioDetails, OSDetails osDetails, JVMDetails jvmDetails) { InternalTransport transport = processTransportOnServiceAddition(gridServiceContainer, nioDetails); OperatingSystem operatingSystem = processOperatingSystemOnServiceAddition(gridServiceContainer, osDetails); VirtualMachine virtualMachine = processVirtualMachineOnServiceAddition(gridServiceContainer, jvmDetails); InternalMachine machine = processMachineOnServiceAddition(transport.getDetails(), transport, operatingSystem, virtualMachine, (InternalMachineAware) virtualMachine, gridServiceContainer); ((InternalGridServiceContainers) machine.getGridServiceContainers()).addGridServiceContainer(gridServiceContainer); gridServiceContainers.addGridServiceContainer(gridServiceContainer); } public synchronized void removeGridServiceContainer(String uid) { InternalGridServiceContainer gridServiceContainer = gridServiceContainers.removeGridServiceContainer(uid); if (gridServiceContainer != null) { processTransportOnServiceRemoval(gridServiceContainer, gridServiceContainer); processOperatingSystemOnServiceRemoval(gridServiceContainer, gridServiceContainer); processVirtualMachineOnServiceRemoval(gridServiceContainer, gridServiceContainer); ((InternalGridServiceContainers) ((InternalMachine) gridServiceContainer.getMachine()).getGridServiceContainers()).removeGridServiceContainer(uid); } } private InternalMachine processMachineOnServiceAddition(TransportDetails transportDetails, InternalTransport transport, OperatingSystem operatingSystem, VirtualMachine virtualMachine, InternalMachineAware ... machineAwares) { InternalMachine machine = (InternalMachine) machines.getMachineByHost(transportDetails.getLocalHostAddress()); if (machine == null) { machine = new DefaultMachine(transportDetails.getLocalHostAddress(), transportDetails.getLocalHostAddress()); machine.setOperatingSystem(operatingSystem); machines.addMachine(machine); } ((InternalTransports) machine.getTransports()).addTransport(transport); ((InternalVirtualMachines) machine.getVirtualMachines()).addVirtualMachine(virtualMachine); for (InternalMachineAware machineAware : machineAwares) { machineAware.setMachine(machine); } return machine; } private InternalVirtualMachine processVirtualMachineOnServiceAddition(InternalVirtualMachineInfoProvider vmProvider, JVMDetails jvmDetails) { InternalVirtualMachine virtualMachine = (InternalVirtualMachine) virtualMachines.getVirtualMachineByUID(jvmDetails.getUid()); if (virtualMachine == null) { virtualMachine = new DefaultVirtualMachine(jvmDetails); virtualMachines.addVirtualMachine(virtualMachine); } virtualMachine.addVirtualMachineInfoProvider(vmProvider); vmProvider.setVirtualMachine(virtualMachine); return virtualMachine; } private void processVirtualMachineOnServiceRemoval(InternalVirtualMachineInfoProvider vmProvider, InternalMachineAware machineAware) { InternalVirtualMachine virtualMachine = (InternalVirtualMachine) vmProvider.getVirtualMachine(); virtualMachine.removeVirtualMachineInfoProvider(vmProvider); if (!virtualMachine.hasVirtualMachineInfoProviders()) { virtualMachines.removeVirtualMachine(virtualMachine.getUID()); ((InternalVirtualMachines) machineAware.getMachine().getVirtualMachines()).removeVirtualMachine(virtualMachine.getUID()); } } private InternalTransport processTransportOnServiceAddition(InternalTransportInfoProvider txProvider, NIODetails nioDetails) { InternalTransport transport = (InternalTransport) transports.getTransportByHostAndPort(nioDetails.getHost(), nioDetails.getPort()); if (transport == null) { transport = new DefaultTransport(nioDetails); transports.addTransport(transport); } transport.addTransportInfoProvider(txProvider); txProvider.setTransport(transport); return transport; } private void processTransportOnServiceRemoval(InternalTransportInfoProvider txProvider, InternalMachineAware machineAware) { InternalTransport transport = ((InternalTransport) txProvider.getTransport()); transport.removeTransportInfoProvider(txProvider); if (!transport.hasTransportInfoProviders()) { transports.removeTransport(transport.getUID()); ((InternalTransports) machineAware.getMachine().getTransports()).removeTransport(transport.getUID()); } } private InternalOperatingSystem processOperatingSystemOnServiceAddition(InternalOperatingSystemInfoProvider osProvider, OSDetails osDetails) { InternalOperatingSystem os = (InternalOperatingSystem) operatingSystems.getByUID(osDetails.getUID()); if (os == null) { os = new DefaultOperatingSystem(osDetails); operatingSystems.addOperatingSystem(os); } os.addOperatingSystemInfoProvider(osProvider); osProvider.setOperatingSystem(os); return os; } private void processOperatingSystemOnServiceRemoval(InternalOperatingSystemInfoProvider osProvider, InternalMachineAware machineAware) { InternalOperatingSystem os = (InternalOperatingSystem) osProvider.getOperatingSystem(); os.removeOperatingSystemInfoProvider(osProvider); if (!os.hasOperatingSystemInfoProviders()) { operatingSystems.removeOperatingSystem(os.getUID()); ((InternalMachine) machineAware.getMachine()).setOperatingSystem(null); } } private class ScheduledProcessingUnitMonitor implements Runnable { public void run() { Map<String, Holder> holders = new HashMap<String, Holder>(); for (GridServiceManager gsm : gridServiceManagers) { try { PUsDetails pusDetails = ((InternalGridServiceManager) gsm).getGSM().getPUsDetails(); for (PUDetails detail : pusDetails.getDetails()) { Holder holder = holders.get(detail.getName()); if (holder == null) { holder = new Holder(); holder.name = detail.getName(); holders.put(holder.name, holder); } if (detail.isManaging()) { holder.detail = detail; holder.managingGSM = gsm; } else { holder.backupDetail = detail; holder.backupGSMs.put(gsm.getUID(), gsm); } } } catch (Exception e) { e.printStackTrace(); } } // first go over all of them and remove the ones needed for (ProcessingUnit processingUnit : processingUnits) { if (!holders.containsKey(processingUnit.getName())) { processingUnits.removeProcessingUnit(processingUnit.getName()); } } // now, go over and update what needed to be updated for (Holder holder : holders.values()) { PUDetails details = holder.detail; if (details == null) { details = holder.backupDetail; } boolean newProcessingUnit = false; InternalProcessingUnit processingUnit = (InternalProcessingUnit) processingUnits.getProcessingUnit(holder.name); if (processingUnit == null) { processingUnit = new DefaultProcessingUnit(details); newProcessingUnit = true; } else { boolean changed = processingUnit.setStatus(details.getStatus()); // changed for future events } if (!newProcessingUnit) { // handle managing GSM if (holder.managingGSM == null) { if (processingUnit.isManaged()) { // event since we no longer have a managing GSM processingUnit.setManagingGridServiceManager(null); } } else { if (!processingUnit.isManaged() || !processingUnit.getManagingGridServiceManager().getUID().equals(holder.managingGSM.getUID())) { // we changed managing GSM processingUnit.setManagingGridServiceManager(holder.managingGSM); // if it was in the backups, remove it from it if (processingUnit.getBackupGridServiceManager(holder.managingGSM.getUID()) != null) { processingUnit.removeBackupGridServiceManager(holder.managingGSM.getUID()); } } } // handle backup GSM removal for (GridServiceManager backupGSM : processingUnit.getBackupGridServiceManagers()) { if (!holder.backupGSMs.containsKey(backupGSM.getUID())) { processingUnit.removeBackupGridServiceManager(backupGSM.getUID()); } } // handle new backup GSMs for (GridServiceManager backupGSM : holder.backupGSMs.values()) { if (processingUnit.getBackupGridServiceManager(backupGSM.getUID()) == null) { processingUnit.addBackupGridServiceManager(backupGSM); } } } else { // we have a new processing unit processingUnit.setManagingGridServiceManager(holder.managingGSM); for (GridServiceManager backupGSM : holder.backupGSMs.values()) { processingUnit.addBackupGridServiceManager(backupGSM); } processingUnits.addProcessingUnit(processingUnit); } } } private class Holder { String name; PUDetails detail; PUDetails backupDetail; GridServiceManager managingGSM; Map<String, GridServiceManager> backupGSMs = new HashMap<String, GridServiceManager>(); } } }
src/main/src/org/openspaces/admin/internal/admin/DefaultAdmin.java
package org.openspaces.admin.internal.admin; import com.gigaspaces.grid.gsm.PUDetails; import com.gigaspaces.grid.gsm.PUsDetails; import com.gigaspaces.jvm.JVMDetails; import com.gigaspaces.lrmi.nio.info.NIODetails; import com.gigaspaces.operatingsystem.OSDetails; import net.jini.core.discovery.LookupLocator; import org.openspaces.admin.gsc.GridServiceContainers; import org.openspaces.admin.gsm.GridServiceManager; import org.openspaces.admin.gsm.GridServiceManagers; import org.openspaces.admin.internal.discovery.DiscoveryService; import org.openspaces.admin.internal.gsc.DefaultGridServiceContainers; import org.openspaces.admin.internal.gsc.InternalGridServiceContainer; import org.openspaces.admin.internal.gsc.InternalGridServiceContainers; import org.openspaces.admin.internal.gsm.DefaultGridServiceManagers; import org.openspaces.admin.internal.gsm.InternalGridServiceManager; import org.openspaces.admin.internal.gsm.InternalGridServiceManagers; import org.openspaces.admin.internal.lus.DefaultLookupServices; import org.openspaces.admin.internal.lus.InternalLookupService; import org.openspaces.admin.internal.lus.InternalLookupServices; import org.openspaces.admin.internal.machine.DefaultMachine; import org.openspaces.admin.internal.machine.DefaultMachines; import org.openspaces.admin.internal.machine.InternalMachine; import org.openspaces.admin.internal.machine.InternalMachineAware; import org.openspaces.admin.internal.machine.InternalMachines; import org.openspaces.admin.internal.os.DefaultOperatingSystem; import org.openspaces.admin.internal.os.DefaultOperatingSystems; import org.openspaces.admin.internal.os.InternalOperatingSystem; import org.openspaces.admin.internal.os.InternalOperatingSystemInfoProvider; import org.openspaces.admin.internal.os.InternalOperatingSystems; import org.openspaces.admin.internal.pu.DefaultProcessingUnit; import org.openspaces.admin.internal.pu.DefaultProcessingUnits; import org.openspaces.admin.internal.pu.InternalProcessingUnit; import org.openspaces.admin.internal.pu.InternalProcessingUnits; import org.openspaces.admin.internal.transport.DefaultTransport; import org.openspaces.admin.internal.transport.DefaultTransports; import org.openspaces.admin.internal.transport.InternalTransport; import org.openspaces.admin.internal.transport.InternalTransportInfoProvider; import org.openspaces.admin.internal.transport.InternalTransports; import org.openspaces.admin.internal.vm.DefaultVirtualMachine; import org.openspaces.admin.internal.vm.DefaultVirtualMachines; import org.openspaces.admin.internal.vm.InternalVirtualMachine; import org.openspaces.admin.internal.vm.InternalVirtualMachineInfoProvider; import org.openspaces.admin.internal.vm.InternalVirtualMachines; import org.openspaces.admin.lus.LookupServices; import org.openspaces.admin.machine.Machines; import org.openspaces.admin.os.OperatingSystem; import org.openspaces.admin.pu.ProcessingUnit; import org.openspaces.admin.pu.ProcessingUnits; import org.openspaces.admin.transport.TransportDetails; import org.openspaces.admin.transport.Transports; import org.openspaces.admin.vm.VirtualMachine; import org.openspaces.admin.vm.VirtualMachines; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @author kimchy */ public class DefaultAdmin implements InternalAdmin { private ScheduledExecutorService scheduledExecutorService; private final DiscoveryService discoveryService; private final InternalLookupServices lookupServices = new DefaultLookupServices(); private final InternalMachines machines = new DefaultMachines(); private final InternalGridServiceManagers gridServiceManagers = new DefaultGridServiceManagers(); private final InternalGridServiceContainers gridServiceContainers = new DefaultGridServiceContainers(); private final InternalTransports transports = new DefaultTransports(); private final InternalOperatingSystems operatingSystems = new DefaultOperatingSystems(); private final InternalVirtualMachines virtualMachines = new DefaultVirtualMachines(); private final InternalProcessingUnits processingUnits = new DefaultProcessingUnits(); private volatile long scheduledProcessingUnitMonitorInterval = 1000; // default to one second private Future scheduledProcessingUnitMonitorFuture; private volatile boolean closed = false; public DefaultAdmin(String[] groups, LookupLocator[] locators) { this.discoveryService = new DiscoveryService(groups, locators, this); } // should be called once after construction public void begin() { discoveryService.start(); this.scheduledExecutorService = Executors.newScheduledThreadPool(5); scheduledProcessingUnitMonitorFuture = scheduledExecutorService.scheduleWithFixedDelay( new ScheduledProcessingUnitMonitor(), scheduledProcessingUnitMonitorInterval, scheduledProcessingUnitMonitorInterval, TimeUnit.MILLISECONDS); } public void setProcessingUnitMonitorInterval(long interval, TimeUnit timeUnit) { if (closed) { throw new IllegalStateException("Admin already closed"); } this.scheduledProcessingUnitMonitorInterval = timeUnit.toMillis(interval); if (scheduledProcessingUnitMonitorFuture != null) { // during initialization scheduledProcessingUnitMonitorFuture.cancel(false); scheduledProcessingUnitMonitorFuture = scheduledExecutorService.scheduleWithFixedDelay(new ScheduledProcessingUnitMonitor(), interval, interval, timeUnit); } } public void close() { if (closed) { return; } closed = true; discoveryService.stop(); scheduledExecutorService.shutdownNow(); } public LookupServices getLookupServices() { return this.lookupServices; } public GridServiceManagers getGridServiceManagers() { return this.gridServiceManagers; } public GridServiceContainers getGridServiceContainers() { return this.gridServiceContainers; } public Machines getMachines() { return this.machines; } public Transports getTransports() { return this.transports; } public VirtualMachines getVirtualMachines() { return this.virtualMachines; } public ProcessingUnits getProcessingUnits() { return this.processingUnits; } public synchronized void addLookupService(InternalLookupService lookupService, NIODetails nioDetails, OSDetails osDetails, JVMDetails jvmDetails) { InternalTransport transport = processTransportOnServiceAddition(lookupService, nioDetails); OperatingSystem operatingSystem = processOperatingSystemOnServiceAddition(lookupService, osDetails); VirtualMachine virtualMachine = processVirtualMachineOnServiceAddition(lookupService, jvmDetails); InternalMachine machine = processMachineOnServiceAddition(transport.getDetails(), transport, operatingSystem, virtualMachine, (InternalMachineAware) virtualMachine, lookupService); ((InternalLookupServices) machine.getLookupServices()).addLookupService(lookupService); lookupServices.addLookupService(lookupService); } public synchronized void removeLookupService(String uid) { InternalLookupService lookupService = lookupServices.removeLookupService(uid); if (lookupService != null) { processTransportOnServiceRemoval(lookupService, lookupService); processOperatingSystemOnServiceRemoval(lookupService, lookupService); processVirtualMachineOnServiceRemoval(lookupService, lookupService); ((InternalLookupServices) ((InternalMachine) lookupService.getMachine()).getLookupServices()).removeLookupService(uid); } } public synchronized void addGridServiceManager(InternalGridServiceManager gridServiceManager, NIODetails nioDetails, OSDetails osDetails, JVMDetails jvmDetails) { InternalTransport transport = processTransportOnServiceAddition(gridServiceManager, nioDetails); OperatingSystem operatingSystem = processOperatingSystemOnServiceAddition(gridServiceManager, osDetails); VirtualMachine virtualMachine = processVirtualMachineOnServiceAddition(gridServiceManager, jvmDetails); InternalMachine machine = processMachineOnServiceAddition(transport.getDetails(), transport, operatingSystem, virtualMachine, (InternalMachineAware) virtualMachine, gridServiceManager); ((InternalGridServiceManagers) machine.getGridServiceManagers()).addGridServiceManager(gridServiceManager); gridServiceManagers.addGridServiceManager(gridServiceManager); } public synchronized void removeGridServiceManager(String uid) { InternalGridServiceManager gridServiceManager = gridServiceManagers.removeGridServiceManager(uid); if (gridServiceManager != null) { processTransportOnServiceRemoval(gridServiceManager, gridServiceManager); processOperatingSystemOnServiceRemoval(gridServiceManager, gridServiceManager); processVirtualMachineOnServiceRemoval(gridServiceManager, gridServiceManager); ((InternalGridServiceManagers) ((InternalMachine) gridServiceManager.getMachine()).getGridServiceManagers()).removeGridServiceManager(uid); } } public synchronized void addGridServiceContainer(InternalGridServiceContainer gridServiceContainer, NIODetails nioDetails, OSDetails osDetails, JVMDetails jvmDetails) { InternalTransport transport = processTransportOnServiceAddition(gridServiceContainer, nioDetails); OperatingSystem operatingSystem = processOperatingSystemOnServiceAddition(gridServiceContainer, osDetails); VirtualMachine virtualMachine = processVirtualMachineOnServiceAddition(gridServiceContainer, jvmDetails); InternalMachine machine = processMachineOnServiceAddition(transport.getDetails(), transport, operatingSystem, virtualMachine, (InternalMachineAware) virtualMachine, gridServiceContainer); ((InternalGridServiceContainers) machine.getGridServiceContainers()).addGridServiceContainer(gridServiceContainer); gridServiceContainers.addGridServiceContainer(gridServiceContainer); } public synchronized void removeGridServiceContainer(String uid) { InternalGridServiceContainer gridServiceContainer = gridServiceContainers.removeGridServiceContainer(uid); if (gridServiceContainer != null) { processTransportOnServiceRemoval(gridServiceContainer, gridServiceContainer); processOperatingSystemOnServiceRemoval(gridServiceContainer, gridServiceContainer); processVirtualMachineOnServiceRemoval(gridServiceContainer, gridServiceContainer); ((InternalGridServiceContainers) ((InternalMachine) gridServiceContainer.getMachine()).getGridServiceContainers()).removeGridServiceContainer(uid); } } private InternalMachine processMachineOnServiceAddition(TransportDetails transportDetails, InternalTransport transport, OperatingSystem operatingSystem, VirtualMachine virtualMachine, InternalMachineAware ... machineAwares) { InternalMachine machine = (InternalMachine) machines.getMachineByHost(transportDetails.getLocalHostAddress()); if (machine == null) { machine = new DefaultMachine(transportDetails.getLocalHostAddress(), transportDetails.getLocalHostAddress()); machine.setOperatingSystem(operatingSystem); machines.addMachine(machine); } ((InternalTransports) machine.getTransports()).addTransport(transport); ((InternalVirtualMachines) machine.getVirtualMachines()).addVirtualMachine(virtualMachine); for (InternalMachineAware machineAware : machineAwares) { machineAware.setMachine(machine); } return machine; } private InternalVirtualMachine processVirtualMachineOnServiceAddition(InternalVirtualMachineInfoProvider vmProvider, JVMDetails jvmDetails) { InternalVirtualMachine virtualMachine = (InternalVirtualMachine) virtualMachines.getVirtualMachineByUID(jvmDetails.getUid()); if (virtualMachine == null) { virtualMachine = new DefaultVirtualMachine(jvmDetails); virtualMachines.addVirtualMachine(virtualMachine); } virtualMachine.addVirtualMachineInfoProvider(vmProvider); vmProvider.setVirtualMachine(virtualMachine); return virtualMachine; } private void processVirtualMachineOnServiceRemoval(InternalVirtualMachineInfoProvider vmProvider, InternalMachineAware machineAware) { InternalVirtualMachine virtualMachine = (InternalVirtualMachine) vmProvider.getVirtualMachine(); virtualMachine.removeVirtualMachineInfoProvider(vmProvider); if (!virtualMachine.hasVirtualMachineInfoProviders()) { virtualMachines.removeVirtualMachine(virtualMachine.getUID()); ((InternalVirtualMachines) machineAware.getMachine().getVirtualMachines()).removeVirtualMachine(virtualMachine.getUID()); } } private InternalTransport processTransportOnServiceAddition(InternalTransportInfoProvider txProvider, NIODetails nioDetails) { InternalTransport transport = (InternalTransport) transports.getTransportByHostAndPort(nioDetails.getHost(), nioDetails.getPort()); if (transport == null) { transport = new DefaultTransport(nioDetails); transports.addTransport(transport); } transport.addTransportInfoProvider(txProvider); txProvider.setTransport(transport); return transport; } private void processTransportOnServiceRemoval(InternalTransportInfoProvider txProvider, InternalMachineAware machineAware) { InternalTransport transport = ((InternalTransport) txProvider.getTransport()); transport.removeTransportInfoProvider(txProvider); if (!transport.hasTransportInfoProviders()) { transports.removeTransport(transport.getUID()); ((InternalTransports) machineAware.getMachine().getTransports()).removeTransport(transport.getUID()); } } private InternalOperatingSystem processOperatingSystemOnServiceAddition(InternalOperatingSystemInfoProvider osProvider, OSDetails osDetails) { InternalOperatingSystem os = (InternalOperatingSystem) operatingSystems.getByUID(osDetails.getUID()); if (os == null) { os = new DefaultOperatingSystem(osDetails); operatingSystems.addOperatingSystem(os); } os.addOperatingSystemInfoProvider(osProvider); osProvider.setOperatingSystem(os); return os; } private void processOperatingSystemOnServiceRemoval(InternalOperatingSystemInfoProvider osProvider, InternalMachineAware machineAware) { InternalOperatingSystem os = (InternalOperatingSystem) osProvider.getOperatingSystem(); os.removeOperatingSystemInfoProvider(osProvider); if (!os.hasOperatingSystemInfoProviders()) { operatingSystems.removeOperatingSystem(os.getUID()); ((InternalMachine) machineAware.getMachine()).setOperatingSystem(null); } } private class ScheduledProcessingUnitMonitor implements Runnable { public void run() { Map<String, Holder> holders = new HashMap<String, Holder>(); for (GridServiceManager gsm : gridServiceManagers) { try { PUsDetails pusDetails = ((InternalGridServiceManager) gsm).getGSM().getPUsDetails(); for (PUDetails detail : pusDetails.getDetails()) { Holder holder = holders.get(detail.getName()); if (holder == null) { holder = new Holder(); holder.name = detail.getName(); holders.put(holder.name, holder); } if (detail.isManaging()) { holder.detail = detail; holder.managingGSM = gsm; } else { holder.backupDetail = detail; holder.backupGSMs.put(gsm.getUID(), gsm); } } } catch (Exception e) { e.printStackTrace(); } } // first go over all of them and remove the ones needed for (ProcessingUnit processingUnit : processingUnits) { if (!holders.containsKey(processingUnit.getName())) { processingUnits.removeProcessingUnit(processingUnit.getName()); } } // now, go over and update what needed to be updated for (Holder holder : holders.values()) { PUDetails details = holder.detail; if (details == null) { details = holder.backupDetail; } boolean newProcessingUnit = false; InternalProcessingUnit processingUnit = (InternalProcessingUnit) processingUnits.getProcessingUnit(holder.name); if (processingUnit == null) { processingUnit = new DefaultProcessingUnit(details); newProcessingUnit = true; } else { boolean changed = processingUnit.setStatus(details.getStatus()); // changed for future events } if (!newProcessingUnit) { // handle managing GSM if (holder.managingGSM == null) { if (processingUnit.isManaged()) { // event since we no longer have a managing GSM processingUnit.setManagingGridServiceManager(null); } } else { if (!processingUnit.isManaged() || !processingUnit.getManagingGridServiceManager().getUID().equals(holder.managingGSM.getUID())) { // we changed managing GSM processingUnit.setManagingGridServiceManager(holder.managingGSM); // if it was in the backups, remove it from it if (processingUnit.getBackupGridServiceManager(holder.managingGSM.getUID()) != null) { processingUnit.removeBackupGridServiceManager(holder.managingGSM.getUID()); } } } // handle backup GSM removal for (GridServiceManager backupGSM : processingUnit.getBackupGridServiceManagers()) { if (!holder.backupGSMs.containsKey(backupGSM.getUID())) { processingUnit.removeBackupGridServiceManager(backupGSM.getUID()); } } // handle new backup GSMs for (GridServiceManager backupGSM : holder.backupGSMs.values()) { if (processingUnit.getBackupGridServiceManager(backupGSM.getUID()) == null) { processingUnit.addBackupGridServiceManager(backupGSM); } } } else { // we have a new processing unit processingUnit.setManagingGridServiceManager(holder.managingGSM); for (GridServiceManager backupGSM : holder.backupGSMs.values()) { processingUnit.addBackupGridServiceManager(backupGSM); } processingUnits.addProcessingUnit(processingUnit); } } } private class Holder { String name; PUDetails detail; PUDetails backupDetail; GridServiceManager managingGSM; Map<String, GridServiceManager> backupGSMs = new HashMap<String, GridServiceManager>(); } } }
GS-6082 OpenSpaces Admin API added the ability to set the processing unit monitor interval svn path=/trunk/openspaces/; revision=44626 Former-commit-id: 0c0e181877da7a2fd6b5b0b47a5507482ccf6b42
src/main/src/org/openspaces/admin/internal/admin/DefaultAdmin.java
GS-6082
<ide><path>rc/main/src/org/openspaces/admin/internal/admin/DefaultAdmin.java <ide> import java.util.Map; <ide> import java.util.concurrent.Executors; <ide> import java.util.concurrent.Future; <del>import java.util.concurrent.ScheduledExecutorService; <add>import java.util.concurrent.ScheduledThreadPoolExecutor; <ide> import java.util.concurrent.TimeUnit; <ide> <ide> /** <ide> */ <ide> public class DefaultAdmin implements InternalAdmin { <ide> <del> private ScheduledExecutorService scheduledExecutorService; <add> private ScheduledThreadPoolExecutor scheduledExecutorService; <ide> <ide> private final DiscoveryService discoveryService; <ide> <ide> // should be called once after construction <ide> public void begin() { <ide> discoveryService.start(); <del> this.scheduledExecutorService = Executors.newScheduledThreadPool(5); <add> this.scheduledExecutorService = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5); <ide> scheduledProcessingUnitMonitorFuture = scheduledExecutorService.scheduleWithFixedDelay( <ide> new ScheduledProcessingUnitMonitor(), scheduledProcessingUnitMonitorInterval, scheduledProcessingUnitMonitorInterval, TimeUnit.MILLISECONDS); <ide> } <ide> scheduledProcessingUnitMonitorFuture.cancel(false); <ide> scheduledProcessingUnitMonitorFuture = scheduledExecutorService.scheduleWithFixedDelay(new ScheduledProcessingUnitMonitor(), interval, interval, timeUnit); <ide> } <add> } <add> <add> public void setSchedulerCorePoolSize(int coreThreads) { <add> scheduledExecutorService.setCorePoolSize(coreThreads); <ide> } <ide> <ide> public void close() {
Java
epl-1.0
3bb8c815768c3851b76c1a206e2be3ab1f51c9d0
0
windup/windup,mareknovotny/windup,jsight/windup,jsight/windup,mbriskar/windup,mbriskar/windup,mbriskar/windup,d-s/windup,johnsteele/windup,lincolnthree/windup,johnsteele/windup,OndraZizka/windup,OndraZizka/windup,lincolnthree/windup,sgilda/windup,OndraZizka/windup,Ladicek/windup,mbriskar/windup,mareknovotny/windup,Maarc/windup,d-s/windup,windup/windup,sgilda/windup,Maarc/windup,mareknovotny/windup,d-s/windup,bradsdavis/windup,jsight/windup,OndraZizka/windup,Maarc/windup,windup/windup,bradsdavis/windup,Ladicek/windup,windup/windup,Ladicek/windup,Maarc/windup,johnsteele/windup,mareknovotny/windup,sgilda/windup,lincolnthree/windup,lincolnthree/windup,jsight/windup,bradsdavis/windup,Ladicek/windup,johnsteele/windup,sgilda/windup,d-s/windup
package org.jboss.windup.graph; import java.io.File; import java.nio.file.Path; import java.util.UUID; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.io.FileUtils; import org.jboss.forge.furnace.services.Imported; import org.jboss.windup.graph.frames.TypeAwareFramedGraphQuery; import org.jboss.windup.graph.model.WindupVertexFrame; import org.jboss.windup.graph.service.GraphService; import org.jboss.windup.graph.service.Service; import org.jboss.windup.util.exception.WindupException; import com.thinkaurelius.titan.core.Cardinality; import com.thinkaurelius.titan.core.PropertyKey; import com.thinkaurelius.titan.core.TitanFactory; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.schema.TitanManagement; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.wrappers.batch.BatchGraph; import com.tinkerpop.blueprints.util.wrappers.event.EventGraph; import com.tinkerpop.frames.FramedGraph; import com.tinkerpop.frames.FramedGraphConfiguration; import com.tinkerpop.frames.FramedGraphFactory; import com.tinkerpop.frames.VertexFrame; import com.tinkerpop.frames.modules.FrameClassLoaderResolver; import com.tinkerpop.frames.modules.Module; import com.tinkerpop.frames.modules.gremlingroovy.GremlinGroovyModule; import com.tinkerpop.frames.modules.javahandler.JavaHandlerModule; public class GraphContextImpl implements GraphContext { private final GraphApiCompositeClassLoaderProvider classLoaderProvider; /** * Used to get access to all implemented {@link Service} classes. */ private final Imported<Service<? extends VertexFrame>> graphServices; private final GraphTypeRegistry graphTypeRegistry; private EventGraph<TitanGraph> eventGraph; private BatchGraph<TitanGraph> batch; private FramedGraph<EventGraph<TitanGraph>> framed; private Path graphDirectory; @Override public GraphTypeRegistry getGraphTypeRegistry() { return graphTypeRegistry; } @Override public void disconnectFromGraph() { this.eventGraph.getBaseGraph().shutdown(); this.eventGraph = null; this.batch = null; this.framed = null; } public EventGraph<TitanGraph> getGraph() { initGraphIfNeeded(); return eventGraph; } /** * Returns a graph suitable for batch processing. * * Note: This bypasses the event graph (thus no events will be fired for modifications to this graph) */ public BatchGraph<TitanGraph> getBatch() { initGraphIfNeeded(); return batch; } public FramedGraph<EventGraph<TitanGraph>> getFramed() { initGraphIfNeeded(); return framed; } public GraphContextImpl(Imported<Service<? extends VertexFrame>> graphServices, GraphTypeRegistry graphTypeRegistry, GraphApiCompositeClassLoaderProvider classLoaderProvider) { this.graphServices = graphServices; this.graphTypeRegistry = graphTypeRegistry; this.classLoaderProvider = classLoaderProvider; } @Override public void setGraphDirectory(Path graphDirectory) { if (this.eventGraph != null) { throw new WindupException("Error, attempting to set graph directory to: \"" + graphDirectory.toString() + "\", but the graph has already been initialized (with graph folder: \"" + this.graphDirectory.toString() + "\"! To change this, you must first disconnect from the graph!"); } this.graphDirectory = graphDirectory; } @Override public Path getGraphDirectory() { return graphDirectory; } private void initGraphIfNeeded() { if (eventGraph != null) { // graph is already initialized, just return return; } if (graphDirectory == null) { // just give it a default value setGraphDirectory(getDefaultGraphDirectory()); } FileUtils.deleteQuietly(graphDirectory.toFile()); Path lucene = graphDirectory.resolve("graphsearch"); Path berkeley = graphDirectory.resolve("titangraph"); // TODO: Externalize this. Configuration conf = new BaseConfiguration(); conf.setProperty("storage.directory", berkeley.toAbsolutePath().toString()); conf.setProperty("storage.backend", "berkeleyje"); conf.setProperty("index.search.backend", "lucene"); conf.setProperty("index.search.directory", lucene.toAbsolutePath().toString()); TitanGraph titanGraph = TitanFactory.open(conf); // TODO: This has to load dynamically. // E.g. get all Model classes and look for @Indexed - org.jboss.windup.graph.api.model.anno. String[] keys = new String[] { "namespaceURI", "schemaLocation", "publicId", "rootTagName", "systemId", "qualifiedName", "filePath", "mavenIdentifier", "packageName" }; TitanManagement mgmt = titanGraph.getManagementSystem(); for (String key : keys) { PropertyKey propKey = mgmt.makePropertyKey(key).dataType(String.class).cardinality(Cardinality.SINGLE) .make(); mgmt.buildIndex(key, Vertex.class).addKey(propKey).buildCompositeIndex(); // titanGraph.makeKey(key).dataType(String.class).indexed(Vertex.class).make(); } for (String key : new String[] { "archiveEntry" }) { PropertyKey propKey = mgmt.makePropertyKey(key).dataType(String.class).cardinality(Cardinality.SINGLE) .make(); mgmt.buildIndex(key, Vertex.class).addKey(propKey).buildMixedIndex("search"); } for (String key : new String[] { WindupVertexFrame.TYPE_PROP }) { PropertyKey propKey = mgmt.makePropertyKey(key).dataType(String.class).cardinality(Cardinality.LIST).make(); mgmt.buildIndex(key, Vertex.class).addKey(propKey).buildCompositeIndex(); } mgmt.commit(); this.eventGraph = new EventGraph<TitanGraph>(titanGraph); batch = new BatchGraph<TitanGraph>(titanGraph, 1000L); // Composite classloader final ClassLoader compositeClassLoader = classLoaderProvider.getCompositeClassLoader(); final AdjacentMapHandler frameMapHandler = new AdjacentMapHandler(); final FrameClassLoaderResolver fclr = new FrameClassLoaderResolver() { public ClassLoader resolveClassLoader(Class<?> frameType) { return compositeClassLoader; } }; final Module addModules = new Module() { @Override public Graph configure(Graph baseGraph, FramedGraphConfiguration config) { config.setFrameClassLoaderResolver(fclr); config.addMethodHandler(frameMapHandler); config.addMethodHandler(new WindupPropertyMethodHandler()); return baseGraph; } }; // Frames with all the features. FramedGraphFactory factory = new FramedGraphFactory( addModules, // Composite classloader new JavaHandlerModule(), // @JavaHandler graphTypeRegistry.build(), // Model classes new GremlinGroovyModule() // @Gremlin ); framed = factory.create(eventGraph); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public <T extends VertexFrame, S extends Service<T>> S getService(Class<T> type) { S closestMatch = null; for (Service<? extends VertexFrame> service : graphServices) { if (service.getType() == type) { closestMatch = (S) service; } else if (closestMatch == null && service.getType().isAssignableFrom(type)) { closestMatch = (S) service; } } if (closestMatch == null) { closestMatch = (S) new GraphService(this, type); } return closestMatch; } @Override public String toString() { return "GraphContext: " + getGraphDirectory().toString(); } @Override public TypeAwareFramedGraphQuery getQuery() { return new TypeAwareFramedGraphQuery(getFramed()); } /** * This is called if the user does not explicitly specify a graph directory */ private Path getDefaultGraphDirectory() { return new File(FileUtils.getTempDirectory(), "windupgraph_" + UUID.randomUUID().toString()).toPath(); } }
graph/impl/src/main/java/org/jboss/windup/graph/GraphContextImpl.java
package org.jboss.windup.graph; import java.io.File; import java.nio.file.Path; import java.util.UUID; import org.apache.commons.configuration.BaseConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.io.FileUtils; import org.jboss.forge.furnace.services.Imported; import org.jboss.windup.graph.frames.TypeAwareFramedGraphQuery; import org.jboss.windup.graph.model.WindupVertexFrame; import org.jboss.windup.graph.service.GraphService; import org.jboss.windup.graph.service.Service; import org.jboss.windup.util.exception.WindupException; import com.thinkaurelius.titan.core.Cardinality; import com.thinkaurelius.titan.core.PropertyKey; import com.thinkaurelius.titan.core.TitanFactory; import com.thinkaurelius.titan.core.TitanGraph; import com.thinkaurelius.titan.core.schema.TitanManagement; import com.tinkerpop.blueprints.Graph; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.wrappers.batch.BatchGraph; import com.tinkerpop.blueprints.util.wrappers.event.EventGraph; import com.tinkerpop.frames.FramedGraph; import com.tinkerpop.frames.FramedGraphConfiguration; import com.tinkerpop.frames.FramedGraphFactory; import com.tinkerpop.frames.VertexFrame; import com.tinkerpop.frames.modules.FrameClassLoaderResolver; import com.tinkerpop.frames.modules.Module; import com.tinkerpop.frames.modules.gremlingroovy.GremlinGroovyModule; import com.tinkerpop.frames.modules.javahandler.JavaHandlerModule; public class GraphContextImpl implements GraphContext { private final GraphApiCompositeClassLoaderProvider classLoaderProvider; /** * Used to get access to all implemented {@link Service} classes. */ private final Imported<Service<? extends VertexFrame>> graphServices; private final GraphTypeRegistry graphTypeRegistry; private EventGraph<TitanGraph> eventGraph; private BatchGraph<TitanGraph> batch; private FramedGraph<EventGraph<TitanGraph>> framed; private Path graphDirectory; @Override public GraphTypeRegistry getGraphTypeRegistry() { return graphTypeRegistry; } @Override public void disconnectFromGraph() { this.eventGraph.getBaseGraph().shutdown(); this.eventGraph = null; this.batch = null; this.framed = null; } public EventGraph<TitanGraph> getGraph() { initGraphIfNeeded(); return eventGraph; } /** * Returns a graph suitable for batch processing. * * Note: This bypasses the event graph (thus no events will be fired for modifications to this graph) */ public BatchGraph<TitanGraph> getBatch() { initGraphIfNeeded(); return batch; } public FramedGraph<EventGraph<TitanGraph>> getFramed() { initGraphIfNeeded(); return framed; } public GraphContextImpl(Imported<Service<? extends VertexFrame>> graphServices, GraphTypeRegistry graphTypeRegistry, GraphApiCompositeClassLoaderProvider classLoaderProvider) { this.graphServices = graphServices; this.graphTypeRegistry = graphTypeRegistry; this.classLoaderProvider = classLoaderProvider; } @Override public void setGraphDirectory(Path graphDirectory) { if (this.eventGraph != null) { throw new WindupException("Error, attempting to set graph directory to: \"" + graphDirectory.toString() + "\", but the graph has already been initialized (with graph folder: \"" + this.graphDirectory.toString() + "\"! To change this, you must first disconnect from the graph!"); } this.graphDirectory = graphDirectory; } @Override public Path getGraphDirectory() { return graphDirectory; } private void initGraphIfNeeded() { if (eventGraph != null) { // graph is already initialized, just return return; } if (graphDirectory == null) { // just give it a default value setGraphDirectory(getDefaultGraphDirectory()); } FileUtils.deleteQuietly(graphDirectory.toFile()); Path lucene = graphDirectory.resolve("graphsearch"); Path berkeley = graphDirectory.resolve("titangraph"); // TODO: Externalize this. Configuration conf = new BaseConfiguration(); conf.setProperty("storage.directory", berkeley.toAbsolutePath().toString()); conf.setProperty("storage.backend", "berkeleyje"); conf.setProperty("index.search.backend", "lucene"); conf.setProperty("index.search.directory", lucene.toAbsolutePath().toString()); conf.setProperty("index.search.local-mode", "true"); TitanGraph titanGraph = TitanFactory.open(conf); // TODO: This has to load dynamically. // E.g. get all Model classes and look for @Indexed - org.jboss.windup.graph.api.model.anno. String[] keys = new String[] { "namespaceURI", "schemaLocation", "publicId", "rootTagName", "systemId", "qualifiedName", "filePath", "mavenIdentifier", "packageName" }; TitanManagement mgmt = titanGraph.getManagementSystem(); for (String key : keys) { PropertyKey propKey = mgmt.makePropertyKey(key).dataType(String.class).cardinality(Cardinality.SINGLE) .make(); mgmt.buildIndex(key, Vertex.class).addKey(propKey).buildCompositeIndex(); // titanGraph.makeKey(key).dataType(String.class).indexed(Vertex.class).make(); } for (String key : new String[] { "archiveEntry" }) { PropertyKey propKey = mgmt.makePropertyKey(key).dataType(String.class).cardinality(Cardinality.SINGLE) .make(); mgmt.buildIndex(key, Vertex.class).addKey(propKey).buildMixedIndex("search"); } for (String key : new String[] { WindupVertexFrame.TYPE_PROP }) { PropertyKey propKey = mgmt.makePropertyKey(key).dataType(String.class).cardinality(Cardinality.LIST).make(); mgmt.buildIndex(key, Vertex.class).addKey(propKey).buildCompositeIndex(); } mgmt.commit(); this.eventGraph = new EventGraph<TitanGraph>(titanGraph); batch = new BatchGraph<TitanGraph>(titanGraph, 1000L); // Composite classloader final ClassLoader compositeClassLoader = classLoaderProvider.getCompositeClassLoader(); final AdjacentMapHandler frameMapHandler = new AdjacentMapHandler(); final FrameClassLoaderResolver fclr = new FrameClassLoaderResolver() { public ClassLoader resolveClassLoader(Class<?> frameType) { return compositeClassLoader; } }; final Module addModules = new Module() { @Override public Graph configure(Graph baseGraph, FramedGraphConfiguration config) { config.setFrameClassLoaderResolver(fclr); config.addMethodHandler(frameMapHandler); config.addMethodHandler(new WindupPropertyMethodHandler()); return baseGraph; } }; // Frames with all the features. FramedGraphFactory factory = new FramedGraphFactory( addModules, // Composite classloader new JavaHandlerModule(), // @JavaHandler graphTypeRegistry.build(), // Model classes new GremlinGroovyModule() // @Gremlin ); framed = factory.create(eventGraph); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public <T extends VertexFrame, S extends Service<T>> S getService(Class<T> type) { S closestMatch = null; for (Service<? extends VertexFrame> service : graphServices) { if (service.getType() == type) { closestMatch = (S) service; } else if (closestMatch == null && service.getType().isAssignableFrom(type)) { closestMatch = (S) service; } } if (closestMatch == null) { closestMatch = (S) new GraphService(this, type); } return closestMatch; } @Override public String toString() { return "GraphContext: " + getGraphDirectory().toString(); } @Override public TypeAwareFramedGraphQuery getQuery() { return new TypeAwareFramedGraphQuery(getFramed()); } /** * This is called if the user does not explicitly specify a graph directory */ private Path getDefaultGraphDirectory() { return new File(FileUtils.getTempDirectory(), "windupgraph_" + UUID.randomUUID().toString()).toPath(); } }
Fix for spurious exceptions during unit tests.
graph/impl/src/main/java/org/jboss/windup/graph/GraphContextImpl.java
Fix for spurious exceptions during unit tests.
<ide><path>raph/impl/src/main/java/org/jboss/windup/graph/GraphContextImpl.java <ide> <ide> conf.setProperty("index.search.backend", "lucene"); <ide> conf.setProperty("index.search.directory", lucene.toAbsolutePath().toString()); <del> conf.setProperty("index.search.local-mode", "true"); <ide> <ide> TitanGraph titanGraph = TitanFactory.open(conf); <ide>
Java
apache-2.0
3a8a4014c6b43b06eed79c420dfbc19f07a6de86
0
niqo01/android-times-square,niqo01/android-times-square
// Copyright 2012 Square, Inc. package com.squareup.timessquare; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Typeface; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.Toast; import com.squareup.timessquare.MonthCellDescriptor.RangeState; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import static java.util.Calendar.DATE; import static java.util.Calendar.DAY_OF_MONTH; import static java.util.Calendar.DAY_OF_WEEK; import static java.util.Calendar.HOUR_OF_DAY; import static java.util.Calendar.MILLISECOND; import static java.util.Calendar.MINUTE; import static java.util.Calendar.MONTH; import static java.util.Calendar.SECOND; import static java.util.Calendar.YEAR; /** * Android component to allow picking a date from a calendar view (a list of months). Must be * initialized after inflation with {@link #init(Date, Date)} and can be customized with any of the * {@link FluentInitializer} methods returned. The currently selected date can be retrieved with * {@link #getSelectedDate()}. */ public class CalendarPickerView extends ListView { public enum SelectionMode { /** * Only one date will be selectable. If there is already a selected date and you select a new * one, the old date will be unselected. */ SINGLE, /** Multiple dates will be selectable. Selecting an already-selected date will un-select it. */ MULTIPLE, /** * Allows you to select a date range. Previous selections are cleared when you either: * <ul> * <li>Have a range selected and select another date (even if it's in the current range).</li> * <li>Have one date selected and then select an earlier date.</li> * </ul> */ RANGE } private final CalendarPickerView.MonthAdapter adapter; private final List<List<List<MonthCellDescriptor>>> cells = new ArrayList<>(); final MonthView.Listener listener = new CellClickedListener(); final List<MonthDescriptor> months = new ArrayList<>(); final List<MonthCellDescriptor> selectedCells = new ArrayList<>(); MonthCellDescriptor previouslyUnSelectableCell; final List<MonthCellDescriptor> highlightedCells = new ArrayList<>(); final List<Calendar> selectedCals = new ArrayList<>(); final List<Calendar> highlightedCals = new ArrayList<>(); private Locale locale; private DateFormat monthNameFormat; private DateFormat weekdayNameFormat; private DateFormat fullDateFormat; private Calendar minCal; private Calendar maxCal; private Calendar monthCounter; private boolean displayOnly; SelectionMode selectionMode; Calendar today; private int dividerColor; private int dayBackgroundResId; private int dayTextColorResId; private int titleTextColor; private boolean displayHeader; private int headerTextColor; private Typeface titleTypeface; private Typeface dateTypeface; private OnDateSelectedListener dateListener; private DateSelectableFilter dateConfiguredListener; private OnInvalidDateSelectedListener invalidDateListener = new DefaultOnInvalidDateSelectedListener(); private CellClickInterceptor cellClickInterceptor; private List<CalendarCellDecorator> decorators; private DayViewAdapter dayViewAdapter = new DefaultDayViewAdapter(); public void setDecorators(List<CalendarCellDecorator> decorators) { this.decorators = decorators; if (null != adapter) { adapter.notifyDataSetChanged(); } } public List<CalendarCellDecorator> getDecorators() { return decorators; } public CalendarPickerView(Context context, AttributeSet attrs) { super(context, attrs); Resources res = context.getResources(); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CalendarPickerView); final int bg = a.getColor(R.styleable.CalendarPickerView_android_background, res.getColor(R.color.calendar_bg)); dividerColor = a.getColor(R.styleable.CalendarPickerView_tsquare_dividerColor, res.getColor(R.color.calendar_divider)); dayBackgroundResId = a.getResourceId(R.styleable.CalendarPickerView_tsquare_dayBackground, R.drawable.calendar_bg_selector); dayTextColorResId = a.getResourceId(R.styleable.CalendarPickerView_tsquare_dayTextColor, R.color.calendar_text_selector); titleTextColor = a.getColor(R.styleable.CalendarPickerView_tsquare_titleTextColor, res.getColor(R.color.calendar_text_active)); displayHeader = a.getBoolean(R.styleable.CalendarPickerView_tsquare_displayHeader, true); headerTextColor = a.getColor(R.styleable.CalendarPickerView_tsquare_headerTextColor, res.getColor(R.color.calendar_text_active)); a.recycle(); adapter = new MonthAdapter(); setDivider(null); setDividerHeight(0); setBackgroundColor(bg); setCacheColorHint(bg); locale = Locale.getDefault(); today = Calendar.getInstance(locale); minCal = Calendar.getInstance(locale); maxCal = Calendar.getInstance(locale); monthCounter = Calendar.getInstance(locale); monthNameFormat = new SimpleDateFormat(context.getString(R.string.month_name_format), locale); weekdayNameFormat = new SimpleDateFormat(context.getString(R.string.day_name_format), locale); fullDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); if (isInEditMode()) { Calendar nextYear = Calendar.getInstance(locale); nextYear.add(Calendar.YEAR, 1); init(new Date(), nextYear.getTime()) // .withSelectedDate(new Date()); } } /** * Both date parameters must be non-null and their {@link Date#getTime()} must not return 0. Time * of day will be ignored. For instance, if you pass in {@code minDate} as 11/16/2012 5:15pm and * {@code maxDate} as 11/16/2013 4:30am, 11/16/2012 will be the first selectable date and * 11/15/2013 will be the last selectable date ({@code maxDate} is exclusive). * <p> * This will implicitly set the {@link SelectionMode} to {@link SelectionMode#SINGLE}. If you * want a different selection mode, use {@link FluentInitializer#inMode(SelectionMode)} on the * {@link FluentInitializer} this method returns. * <p> * The calendar will be constructed using the given locale. This means that all names * (months, days) will be in the language of the locale and the weeks start with the day * specified by the locale. * * @param minDate Earliest selectable date, inclusive. Must be earlier than {@code maxDate}. * @param maxDate Latest selectable date, exclusive. Must be later than {@code minDate}. */ public FluentInitializer init(Date minDate, Date maxDate, Locale locale) { if (minDate == null || maxDate == null) { throw new IllegalArgumentException( "minDate and maxDate must be non-null. " + dbg(minDate, maxDate)); } if (minDate.after(maxDate)) { throw new IllegalArgumentException( "minDate must be before maxDate. " + dbg(minDate, maxDate)); } if (locale == null) { throw new IllegalArgumentException("Locale is null."); } // Make sure that all calendar instances use the same locale. this.locale = locale; today = Calendar.getInstance(locale); minCal = Calendar.getInstance(locale); maxCal = Calendar.getInstance(locale); monthCounter = Calendar.getInstance(locale); monthNameFormat = new SimpleDateFormat(getContext().getString(R.string.month_name_format), locale); for (MonthDescriptor month : months) { month.setLabel(monthNameFormat.format(month.getDate())); } weekdayNameFormat = new SimpleDateFormat(getContext().getString(R.string.day_name_format), locale); fullDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); this.selectionMode = SelectionMode.SINGLE; // Clear out any previously-selected dates/cells. selectedCals.clear(); selectedCells.clear(); highlightedCals.clear(); highlightedCells.clear(); // Clear previous state. cells.clear(); months.clear(); minCal.setTime(minDate); maxCal.setTime(maxDate); setMidnight(minCal); setMidnight(maxCal); displayOnly = false; // maxDate is exclusive: bump back to the previous day so if maxDate is the first of a month, // we don't accidentally include that month in the view. maxCal.add(MINUTE, -1); // Now iterate between minCal and maxCal and build up our list of months to show. monthCounter.setTime(minCal.getTime()); final int maxMonth = maxCal.get(MONTH); final int maxYear = maxCal.get(YEAR); while ((monthCounter.get(MONTH) <= maxMonth // Up to, including the month. || monthCounter.get(YEAR) < maxYear) // Up to the year. && monthCounter.get(YEAR) < maxYear + 1) { // But not > next yr. Date date = monthCounter.getTime(); MonthDescriptor month = new MonthDescriptor(monthCounter.get(MONTH), monthCounter.get(YEAR), date, monthNameFormat.format(date)); cells.add(getMonthCells(month, monthCounter)); Logr.d("Adding month %s", month); months.add(month); monthCounter.add(MONTH, 1); } validateAndUpdate(); return new FluentInitializer(); } /** * Both date parameters must be non-null and their {@link Date#getTime()} must not return 0. Time * of day will be ignored. For instance, if you pass in {@code minDate} as 11/16/2012 5:15pm and * {@code maxDate} as 11/16/2013 4:30am, 11/16/2012 will be the first selectable date and * 11/15/2013 will be the last selectable date ({@code maxDate} is exclusive). * <p> * This will implicitly set the {@link SelectionMode} to {@link SelectionMode#SINGLE}. If you * want a different selection mode, use {@link FluentInitializer#inMode(SelectionMode)} on the * {@link FluentInitializer} this method returns. * <p> * The calendar will be constructed using the default locale as returned by * {@link java.util.Locale#getDefault()}. If you wish the calendar to be constructed using a * different locale, use {@link #init(java.util.Date, java.util.Date, java.util.Locale)}. * * @param minDate Earliest selectable date, inclusive. Must be earlier than {@code maxDate}. * @param maxDate Latest selectable date, exclusive. Must be later than {@code minDate}. */ public FluentInitializer init(Date minDate, Date maxDate) { return init(minDate, maxDate, Locale.getDefault()); } public class FluentInitializer { /** Override the {@link SelectionMode} from the default ({@link SelectionMode#SINGLE}). */ public FluentInitializer inMode(SelectionMode mode) { selectionMode = mode; validateAndUpdate(); return this; } /** * Set an initially-selected date. The calendar will scroll to that date if it's not already * visible. */ public FluentInitializer withSelectedDate(Date selectedDates) { return withSelectedDates(Collections.singletonList(selectedDates)); } /** * Set multiple selected dates. This will throw an {@link IllegalArgumentException} if you * pass in multiple dates and haven't already called {@link #inMode(SelectionMode)}. */ public FluentInitializer withSelectedDates(Collection<Date> selectedDates) { if (selectionMode == SelectionMode.SINGLE && selectedDates.size() > 1) { throw new IllegalArgumentException("SINGLE mode can't be used with multiple selectedDates"); } if (selectionMode == SelectionMode.RANGE && selectedDates.size() > 2) { throw new IllegalArgumentException( "RANGE mode only allows two selectedDates. You tried to pass " + selectedDates.size()); } if (selectedDates != null) { for (Date date : selectedDates) { selectDate(date); } } scrollToSelectedDates(); validateAndUpdate(); return this; } public FluentInitializer withHighlightedDates(Collection<Date> dates) { highlightDates(dates); return this; } public FluentInitializer withHighlightedDate(Date date) { return withHighlightedDates(Collections.singletonList(date)); } @SuppressLint("SimpleDateFormat") public FluentInitializer setShortWeekdays(String[] newShortWeekdays) { DateFormatSymbols symbols = new DateFormatSymbols(locale); symbols.setShortWeekdays(newShortWeekdays); weekdayNameFormat = new SimpleDateFormat(getContext().getString(R.string.day_name_format), symbols); return this; } public FluentInitializer displayOnly() { displayOnly = true; return this; } } private void validateAndUpdate() { if (getAdapter() == null) { setAdapter(adapter); } adapter.notifyDataSetChanged(); } private void scrollToSelectedMonth(final int selectedIndex) { scrollToSelectedMonth(selectedIndex, false); } private void scrollToSelectedMonth(final int selectedIndex, final boolean smoothScroll) { post(new Runnable() { @Override public void run() { Logr.d("Scrolling to position %d", selectedIndex); if (smoothScroll) { smoothScrollToPosition(selectedIndex); } else { setSelection(selectedIndex); } } }); } private void scrollToSelectedDates() { Integer selectedIndex = null; Integer todayIndex = null; Calendar today = Calendar.getInstance(locale); for (int c = 0; c < months.size(); c++) { MonthDescriptor month = months.get(c); if (selectedIndex == null) { for (Calendar selectedCal : selectedCals) { if (sameMonth(selectedCal, month)) { selectedIndex = c; break; } } if (selectedIndex == null && todayIndex == null && sameMonth(today, month)) { todayIndex = c; } } } if (selectedIndex != null) { scrollToSelectedMonth(selectedIndex); } else if (todayIndex != null) { scrollToSelectedMonth(todayIndex); } } public boolean scrollToDate(Date date) { Integer selectedIndex = null; Calendar cal = Calendar.getInstance(locale); cal.setTime(date); for (int c = 0; c < months.size(); c++) { MonthDescriptor month = months.get(c); if (sameMonth(cal, month)) { selectedIndex = c; break; } } if (selectedIndex != null) { scrollToSelectedMonth(selectedIndex); return true; } return false; } /** * This method should only be called if the calendar is contained in a dialog, and it should only * be called once, right after the dialog is shown (using * {@link android.content.DialogInterface.OnShowListener} or * {@link android.app.DialogFragment#onStart()}). */ public void fixDialogDimens() { Logr.d("Fixing dimensions to h = %d / w = %d", getMeasuredHeight(), getMeasuredWidth()); // Fix the layout height/width after the dialog has been shown. getLayoutParams().height = getMeasuredHeight(); getLayoutParams().width = getMeasuredWidth(); // Post this runnable so it runs _after_ the dimen changes have been applied/re-measured. post(new Runnable() { @Override public void run() { Logr.d("Dimens are fixed: now scroll to the selected date"); scrollToSelectedDates(); } }); } /** * Set the typeface to be used for month titles. */ public void setTitleTypeface(Typeface titleTypeface) { this.titleTypeface = titleTypeface; validateAndUpdate(); } /** * Sets the typeface to be used within the date grid. */ public void setDateTypeface(Typeface dateTypeface) { this.dateTypeface = dateTypeface; validateAndUpdate(); } /** * Sets the typeface to be used for all text within this calendar. */ public void setTypeface(Typeface typeface) { setTitleTypeface(typeface); setDateTypeface(typeface); } /** * This method should only be called if the calendar is contained in a dialog, and it should only * be called when the screen has been rotated and the dialog should be re-measured. */ public void unfixDialogDimens() { Logr.d("Reset the fixed dimensions to allow for re-measurement"); // Fix the layout height/width after the dialog has been shown. getLayoutParams().height = LayoutParams.MATCH_PARENT; getLayoutParams().width = LayoutParams.MATCH_PARENT; requestLayout(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (months.isEmpty()) { throw new IllegalStateException( "Must have at least one month to display. Did you forget to call init()?"); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public Date getSelectedDate() { return (selectedCals.size() > 0 ? selectedCals.get(0).getTime() : null); } public List<Date> getSelectedDates() { List<Date> selectedDates = new ArrayList<>(); for (MonthCellDescriptor cal : selectedCells) { selectedDates.add(cal.getDate()); } Collections.sort(selectedDates); return selectedDates; } /** Returns a string summarizing what the client sent us for init() params. */ private static String dbg(Date minDate, Date maxDate) { return "minDate: " + minDate + "\nmaxDate: " + maxDate; } /** Clears out the hours/minutes/seconds/millis of a Calendar. */ static void setMidnight(Calendar cal) { cal.set(HOUR_OF_DAY, 0); cal.set(MINUTE, 0); cal.set(SECOND, 0); cal.set(MILLISECOND, 0); } private class CellClickedListener implements MonthView.Listener { @Override public void handleClick(MonthCellDescriptor cell) { Date clickedDate = cell.getDate(); if (cellClickInterceptor != null && cellClickInterceptor.onCellClicked(clickedDate)) { return; } if (!betweenDates(clickedDate, minCal, maxCal) || (!cell.isSelectable())) { if (invalidDateListener != null) { invalidDateListener.onInvalidDateSelected(clickedDate); } } else { boolean wasSelected = doSelectDate(clickedDate, cell); if (dateListener != null) { if (wasSelected) { dateListener.onDateSelected(clickedDate); } else { dateListener.onDateUnselected(clickedDate); } } } } } /** * Select a new date. Respects the {@link SelectionMode} this CalendarPickerView is configured * with: if you are in {@link SelectionMode#SINGLE}, the previously selected date will be * un-selected. In {@link SelectionMode#MULTIPLE}, the new date will be added to the list of * selected dates. * <p> * If the selection was made (selectable date, in range), the view will scroll to the newly * selected date if it's not already visible. * * @return - whether we were able to set the date */ public boolean selectDate(Date date) { return selectDate(date, false); } /** * Select a new date. Respects the {@link SelectionMode} this CalendarPickerView is configured * with: if you are in {@link SelectionMode#SINGLE}, the previously selected date will be * un-selected. In {@link SelectionMode#MULTIPLE}, the new date will be added to the list of * selected dates. * <p> * If the selection was made (selectable date, in range), the view will scroll to the newly * selected date if it's not already visible. * * @return - whether we were able to set the date */ public boolean selectDate(Date date, boolean smoothScroll) { validateDate(date); MonthCellWithMonthIndex monthCellWithMonthIndex = getMonthCellWithIndexByDate(date); if (monthCellWithMonthIndex == null || !isDateSelectable(date)) { return false; } boolean wasSelected = doSelectDate(date, monthCellWithMonthIndex.cell); if (wasSelected) { scrollToSelectedMonth(monthCellWithMonthIndex.monthIndex, smoothScroll); } return wasSelected; } private void validateDate(Date date) { if (date == null) { throw new IllegalArgumentException("Selected date must be non-null."); } if (date.before(minCal.getTime()) || date.after(maxCal.getTime())) { throw new IllegalArgumentException(String.format( "SelectedDate must be between minDate and maxDate." + "%nminDate: %s%nmaxDate: %s%nselectedDate: %s", minCal.getTime(), maxCal.getTime(), date)); } } private boolean doSelectDate(Date date, MonthCellDescriptor cell) { Calendar newlySelectedCal = Calendar.getInstance(locale); newlySelectedCal.setTime(date); // Sanitize input: clear out the hours/minutes/seconds/millis. setMidnight(newlySelectedCal); // Clear any remaining range state. for (MonthCellDescriptor selectedCell : selectedCells) { selectedCell.setRangeState(RangeState.NONE); } switch (selectionMode) { case RANGE: if (selectedCals.size() > 1) { // We've already got a range selected: clear the old one. clearOldSelections(); } else if (selectedCals.size() == 1 && newlySelectedCal.before(selectedCals.get(0))) { // We're moving the start of the range back in time: clear the old start date. clearOldSelections(); } else if (date != null && selectedCals.size() == 1) { checkForUnSelectableDate(newlySelectedCal); } break; case MULTIPLE: date = applyMultiSelect(date, newlySelectedCal); break; case SINGLE: clearOldSelections(); break; default: throw new IllegalStateException("Unknown selectionMode " + selectionMode); } if (date != null) { // Select a new cell. if (selectedCells.size() == 0 || !selectedCells.get(0).equals(cell)) { selectedCells.add(cell); cell.setSelected(true); } selectedCals.add(newlySelectedCal); if (selectionMode == SelectionMode.RANGE && selectedCells.size() == 1) { setLastDateSelectable(selectedCells.get(0).getDate()); } if (selectionMode == SelectionMode.RANGE && selectedCells.size() > 1) { // Select all days in between start and end. Date start = selectedCells.get(0).getDate(); Date end = selectedCells.get(1).getDate(); selectedCells.get(0).setRangeState(MonthCellDescriptor.RangeState.FIRST); selectedCells.get(1).setRangeState(MonthCellDescriptor.RangeState.LAST); if (previouslyUnSelectableCell != null && !previouslyUnSelectableCell.getDate().equals(end)) { previouslyUnSelectableCell.setSelectable(false); previouslyUnSelectableCell = null; } for (List<List<MonthCellDescriptor>> month : cells) { for (List<MonthCellDescriptor> week : month) { for (MonthCellDescriptor singleCell : week) { if (singleCell.getDate().after(start) && singleCell.getDate().before(end) && singleCell.isSelectable()) { singleCell.setSelected(true); singleCell.setRangeState(MonthCellDescriptor.RangeState.MIDDLE); selectedCells.add(singleCell); } } } } } } // Update the adapter. validateAndUpdate(); return date != null; } private void checkForUnSelectableDate(Calendar newlySelectedCal) { for (List<List<MonthCellDescriptor>> month : cells) { for (List<MonthCellDescriptor> week : month) { for (MonthCellDescriptor singleCell : week) { if (singleCell.getDate().after(selectedCals.get(0).getTime()) && singleCell.getDate().before(newlySelectedCal.getTime()) && ((!singleCell.isSelectable() && previouslyUnSelectableCell == null) || (singleCell.isSelectable() && previouslyUnSelectableCell.equals(singleCell))) && singleCell.isCurrentMonth()) { clearOldSelections(); return; } } } } } private void setLastDateSelectable(Date start) { for (List<List<MonthCellDescriptor>> month : cells) { for (List<MonthCellDescriptor> week : month) { for (MonthCellDescriptor singleCell : week) { if (singleCell.getDate().after(start) && !singleCell.isSelectable() && singleCell.isCurrentMonth()) { singleCell.setSelectable(true); previouslyUnSelectableCell = singleCell; return; } } } } } private void clearOldSelections() { if (previouslyUnSelectableCell != null) { previouslyUnSelectableCell.setSelectable(false); previouslyUnSelectableCell = null; } for (MonthCellDescriptor selectedCell : selectedCells) { // De-select the currently-selected cell. selectedCell.setSelected(false); if (dateListener != null) { Date selectedDate = selectedCell.getDate(); if (selectionMode == SelectionMode.RANGE) { int index = selectedCells.indexOf(selectedCell); if (index == 0 || index == selectedCells.size() - 1) { dateListener.onDateUnselected(selectedDate); } } else { dateListener.onDateUnselected(selectedDate); } } } selectedCells.clear(); selectedCals.clear(); } private Date applyMultiSelect(Date date, Calendar selectedCal) { for (MonthCellDescriptor selectedCell : selectedCells) { if (selectedCell.getDate().equals(date)) { // De-select the currently-selected cell. selectedCell.setSelected(false); selectedCells.remove(selectedCell); date = null; break; } } for (Calendar cal : selectedCals) { if (sameDate(cal, selectedCal)) { selectedCals.remove(cal); break; } } return date; } public void highlightDates(Collection<Date> dates) { for (Date date : dates) { validateDate(date); MonthCellWithMonthIndex monthCellWithMonthIndex = getMonthCellWithIndexByDate(date); if (monthCellWithMonthIndex != null) { Calendar newlyHighlightedCal = Calendar.getInstance(); newlyHighlightedCal.setTime(date); MonthCellDescriptor cell = monthCellWithMonthIndex.cell; highlightedCells.add(cell); highlightedCals.add(newlyHighlightedCal); cell.setHighlighted(true); } } validateAndUpdate(); } public void clearHighlightedDates() { for (MonthCellDescriptor cal : highlightedCells) { cal.setHighlighted(false); } highlightedCells.clear(); highlightedCals.clear(); validateAndUpdate(); } /** Hold a cell with a month-index. */ private static class MonthCellWithMonthIndex { public MonthCellDescriptor cell; public int monthIndex; public MonthCellWithMonthIndex(MonthCellDescriptor cell, int monthIndex) { this.cell = cell; this.monthIndex = monthIndex; } } /** Return cell and month-index (for scrolling) for a given Date. */ private MonthCellWithMonthIndex getMonthCellWithIndexByDate(Date date) { int index = 0; Calendar searchCal = Calendar.getInstance(locale); searchCal.setTime(date); Calendar actCal = Calendar.getInstance(locale); for (List<List<MonthCellDescriptor>> monthCells : cells) { for (List<MonthCellDescriptor> weekCells : monthCells) { for (MonthCellDescriptor actCell : weekCells) { actCal.setTime(actCell.getDate()); if (sameDate(actCal, searchCal) && actCell.isSelectable()) { return new MonthCellWithMonthIndex(actCell, index); } } } index++; } return null; } private class MonthAdapter extends BaseAdapter { private final LayoutInflater inflater; private MonthAdapter() { inflater = LayoutInflater.from(getContext()); } @Override public boolean isEnabled(int position) { // Disable selectability: each cell will handle that itself. return false; } @Override public int getCount() { return months.size(); } @Override public Object getItem(int position) { return months.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null || !monthView.getTag(R.id.day_view_adapter_class).equals(dayViewAdapter.getClass())) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today, dividerColor, dayBackgroundResId, dayTextColorResId, titleTextColor, displayHeader, headerTextColor, decorators, locale, dayViewAdapter); monthView.setTag(R.id.day_view_adapter_class, dayViewAdapter.getClass()); } else { monthView.setDecorators(decorators); } monthView.init(months.get(position), cells.get(position), displayOnly, titleTypeface, dateTypeface); return monthView; } } List<List<MonthCellDescriptor>> getMonthCells(MonthDescriptor month, Calendar startCal) { Calendar cal = Calendar.getInstance(locale); cal.setTime(startCal.getTime()); List<List<MonthCellDescriptor>> cells = new ArrayList<>(); cal.set(DAY_OF_MONTH, 1); int firstDayOfWeek = cal.get(DAY_OF_WEEK); int offset = cal.getFirstDayOfWeek() - firstDayOfWeek; if (offset > 0) { offset -= 7; } cal.add(Calendar.DATE, offset); Calendar minSelectedCal = minDate(selectedCals); Calendar maxSelectedCal = maxDate(selectedCals); while ((cal.get(MONTH) < month.getMonth() + 1 || cal.get(YEAR) < month.getYear()) // && cal.get(YEAR) <= month.getYear()) { Logr.d("Building week row starting at %s", cal.getTime()); List<MonthCellDescriptor> weekCells = new ArrayList<>(); cells.add(weekCells); for (int c = 0; c < 7; c++) { Date date = cal.getTime(); boolean isCurrentMonth = cal.get(MONTH) == month.getMonth(); boolean isSelected = isCurrentMonth && containsDate(selectedCals, cal); boolean isSelectable = isCurrentMonth && betweenDates(cal, minCal, maxCal) && isDateSelectable(date); boolean isToday = sameDate(cal, today); boolean isHighlighted = containsDate(highlightedCals, cal); int value = cal.get(DAY_OF_MONTH); MonthCellDescriptor.RangeState rangeState = MonthCellDescriptor.RangeState.NONE; if (selectedCals.size() > 1) { if (sameDate(minSelectedCal, cal)) { rangeState = MonthCellDescriptor.RangeState.FIRST; } else if (sameDate(maxDate(selectedCals), cal)) { rangeState = MonthCellDescriptor.RangeState.LAST; } else if (betweenDates(cal, minSelectedCal, maxSelectedCal)) { rangeState = MonthCellDescriptor.RangeState.MIDDLE; } } weekCells.add( new MonthCellDescriptor(date, isCurrentMonth, isSelectable, isSelected, isToday, isHighlighted, value, rangeState)); cal.add(DATE, 1); } } return cells; } private boolean containsDate(List<Calendar> selectedCals, Date date) { Calendar cal = Calendar.getInstance(locale); cal.setTime(date); return containsDate(selectedCals, cal); } private static boolean containsDate(List<Calendar> selectedCals, Calendar cal) { for (Calendar selectedCal : selectedCals) { if (sameDate(cal, selectedCal)) { return true; } } return false; } private static Calendar minDate(List<Calendar> selectedCals) { if (selectedCals == null || selectedCals.size() == 0) { return null; } Collections.sort(selectedCals); return selectedCals.get(0); } private static Calendar maxDate(List<Calendar> selectedCals) { if (selectedCals == null || selectedCals.size() == 0) { return null; } Collections.sort(selectedCals); return selectedCals.get(selectedCals.size() - 1); } private static boolean sameDate(Calendar cal, Calendar selectedDate) { return cal.get(MONTH) == selectedDate.get(MONTH) && cal.get(YEAR) == selectedDate.get(YEAR) && cal.get(DAY_OF_MONTH) == selectedDate.get(DAY_OF_MONTH); } private static boolean betweenDates(Calendar cal, Calendar minCal, Calendar maxCal) { final Date date = cal.getTime(); return betweenDates(date, minCal, maxCal); } static boolean betweenDates(Date date, Calendar minCal, Calendar maxCal) { final Date min = minCal.getTime(); return (date.equals(min) || date.after(min)) // >= minCal && date.before(maxCal.getTime()); // && < maxCal } private static boolean sameMonth(Calendar cal, MonthDescriptor month) { return (cal.get(MONTH) == month.getMonth() && cal.get(YEAR) == month.getYear()); } private boolean isDateSelectable(Date date) { return dateConfiguredListener == null || dateConfiguredListener.isDateSelectable(date); } public void setOnDateSelectedListener(OnDateSelectedListener listener) { dateListener = listener; } /** * Set a listener to react to user selection of a disabled date. * * @param listener the listener to set, or null for no reaction */ public void setOnInvalidDateSelectedListener(OnInvalidDateSelectedListener listener) { invalidDateListener = listener; } /** * Set a listener used to discriminate between selectable and unselectable dates. Set this to * disable arbitrary dates as they are rendered. * <p> * Important: set this before you call {@link #init(Date, Date)} methods. If called afterwards, * it will not be consistently applied. */ public void setDateSelectableFilter(DateSelectableFilter listener) { dateConfiguredListener = listener; } /** * Set an adapter used to initialize {@link CalendarCellView} with custom layout. * <p> * Important: set this before you call {@link #init(Date, Date)} methods. If called afterwards, * it will not be consistently applied. */ public void setCustomDayView(DayViewAdapter dayViewAdapter) { this.dayViewAdapter = dayViewAdapter; if (null != adapter) { adapter.notifyDataSetChanged(); } } /** Set a listener to intercept clicks on calendar cells. */ public void setCellClickInterceptor(CellClickInterceptor listener) { cellClickInterceptor = listener; } /** * Interface to be notified when a new date is selected or unselected. This will only be called * when the user initiates the date selection. If you call {@link #selectDate(Date)} this * listener will not be notified. * * @see #setOnDateSelectedListener(OnDateSelectedListener) */ public interface OnDateSelectedListener { void onDateSelected(Date date); void onDateUnselected(Date date); } /** * Interface to be notified when an invalid date is selected by the user. This will only be * called when the user initiates the date selection. If you call {@link #selectDate(Date)} this * listener will not be notified. * * @see #setOnInvalidDateSelectedListener(OnInvalidDateSelectedListener) */ public interface OnInvalidDateSelectedListener { void onInvalidDateSelected(Date date); } /** * Interface used for determining the selectability of a date cell when it is configured for * display on the calendar. * * @see #setDateSelectableFilter(DateSelectableFilter) */ public interface DateSelectableFilter { boolean isDateSelectable(Date date); } /** * Interface to be notified when a cell is clicked and possibly intercept the click. Return true * to intercept the click and prevent any selections from changing. * * @see #setCellClickInterceptor(CellClickInterceptor) */ public interface CellClickInterceptor { boolean onCellClicked(Date date); } private class DefaultOnInvalidDateSelectedListener implements OnInvalidDateSelectedListener { @Override public void onInvalidDateSelected(Date date) { String errMessage = getResources().getString(R.string.invalid_date, fullDateFormat.format(minCal.getTime()), fullDateFormat.format(maxCal.getTime())); Toast.makeText(getContext(), errMessage, Toast.LENGTH_SHORT).show(); } } }
library/src/main/java/com/squareup/timessquare/CalendarPickerView.java
// Copyright 2012 Square, Inc. package com.squareup.timessquare; import android.annotation.SuppressLint; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Typeface; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.Toast; import com.squareup.timessquare.MonthCellDescriptor.RangeState; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import static java.util.Calendar.DATE; import static java.util.Calendar.DAY_OF_MONTH; import static java.util.Calendar.DAY_OF_WEEK; import static java.util.Calendar.HOUR_OF_DAY; import static java.util.Calendar.MILLISECOND; import static java.util.Calendar.MINUTE; import static java.util.Calendar.MONTH; import static java.util.Calendar.SECOND; import static java.util.Calendar.YEAR; /** * Android component to allow picking a date from a calendar view (a list of months). Must be * initialized after inflation with {@link #init(Date, Date)} and can be customized with any of the * {@link FluentInitializer} methods returned. The currently selected date can be retrieved with * {@link #getSelectedDate()}. */ public class CalendarPickerView extends ListView { public enum SelectionMode { /** * Only one date will be selectable. If there is already a selected date and you select a new * one, the old date will be unselected. */ SINGLE, /** Multiple dates will be selectable. Selecting an already-selected date will un-select it. */ MULTIPLE, /** * Allows you to select a date range. Previous selections are cleared when you either: * <ul> * <li>Have a range selected and select another date (even if it's in the current range).</li> * <li>Have one date selected and then select an earlier date.</li> * </ul> */ RANGE } private final CalendarPickerView.MonthAdapter adapter; private final List<List<List<MonthCellDescriptor>>> cells = new ArrayList<>(); final MonthView.Listener listener = new CellClickedListener(); final List<MonthDescriptor> months = new ArrayList<>(); final List<MonthCellDescriptor> selectedCells = new ArrayList<>(); MonthCellDescriptor previouslyUnSelectableCell; final List<MonthCellDescriptor> highlightedCells = new ArrayList<>(); final List<Calendar> selectedCals = new ArrayList<>(); final List<Calendar> highlightedCals = new ArrayList<>(); private Locale locale; private DateFormat monthNameFormat; private DateFormat weekdayNameFormat; private DateFormat fullDateFormat; private Calendar minCal; private Calendar maxCal; private Calendar monthCounter; private boolean displayOnly; SelectionMode selectionMode; Calendar today; private int dividerColor; private int dayBackgroundResId; private int dayTextColorResId; private int titleTextColor; private boolean displayHeader; private int headerTextColor; private Typeface titleTypeface; private Typeface dateTypeface; private OnDateSelectedListener dateListener; private DateSelectableFilter dateConfiguredListener; private OnInvalidDateSelectedListener invalidDateListener = new DefaultOnInvalidDateSelectedListener(); private CellClickInterceptor cellClickInterceptor; private List<CalendarCellDecorator> decorators; private DayViewAdapter dayViewAdapter = new DefaultDayViewAdapter(); public void setDecorators(List<CalendarCellDecorator> decorators) { this.decorators = decorators; if (null != adapter) { adapter.notifyDataSetChanged(); } } public List<CalendarCellDecorator> getDecorators() { return decorators; } public CalendarPickerView(Context context, AttributeSet attrs) { super(context, attrs); Resources res = context.getResources(); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CalendarPickerView); final int bg = a.getColor(R.styleable.CalendarPickerView_android_background, res.getColor(R.color.calendar_bg)); dividerColor = a.getColor(R.styleable.CalendarPickerView_tsquare_dividerColor, res.getColor(R.color.calendar_divider)); dayBackgroundResId = a.getResourceId(R.styleable.CalendarPickerView_tsquare_dayBackground, R.drawable.calendar_bg_selector); dayTextColorResId = a.getResourceId(R.styleable.CalendarPickerView_tsquare_dayTextColor, R.color.calendar_text_selector); titleTextColor = a.getColor(R.styleable.CalendarPickerView_tsquare_titleTextColor, res.getColor(R.color.calendar_text_active)); displayHeader = a.getBoolean(R.styleable.CalendarPickerView_tsquare_displayHeader, true); headerTextColor = a.getColor(R.styleable.CalendarPickerView_tsquare_headerTextColor, res.getColor(R.color.calendar_text_active)); a.recycle(); adapter = new MonthAdapter(); setDivider(null); setDividerHeight(0); setBackgroundColor(bg); setCacheColorHint(bg); locale = Locale.getDefault(); today = Calendar.getInstance(locale); minCal = Calendar.getInstance(locale); maxCal = Calendar.getInstance(locale); monthCounter = Calendar.getInstance(locale); monthNameFormat = new SimpleDateFormat(context.getString(R.string.month_name_format), locale); weekdayNameFormat = new SimpleDateFormat(context.getString(R.string.day_name_format), locale); fullDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); if (isInEditMode()) { Calendar nextYear = Calendar.getInstance(locale); nextYear.add(Calendar.YEAR, 1); init(new Date(), nextYear.getTime()) // .withSelectedDate(new Date()); } } /** * Both date parameters must be non-null and their {@link Date#getTime()} must not return 0. Time * of day will be ignored. For instance, if you pass in {@code minDate} as 11/16/2012 5:15pm and * {@code maxDate} as 11/16/2013 4:30am, 11/16/2012 will be the first selectable date and * 11/15/2013 will be the last selectable date ({@code maxDate} is exclusive). * <p> * This will implicitly set the {@link SelectionMode} to {@link SelectionMode#SINGLE}. If you * want a different selection mode, use {@link FluentInitializer#inMode(SelectionMode)} on the * {@link FluentInitializer} this method returns. * <p> * The calendar will be constructed using the given locale. This means that all names * (months, days) will be in the language of the locale and the weeks start with the day * specified by the locale. * * @param minDate Earliest selectable date, inclusive. Must be earlier than {@code maxDate}. * @param maxDate Latest selectable date, exclusive. Must be later than {@code minDate}. */ public FluentInitializer init(Date minDate, Date maxDate, Locale locale) { if (minDate == null || maxDate == null) { throw new IllegalArgumentException( "minDate and maxDate must be non-null. " + dbg(minDate, maxDate)); } if (minDate.after(maxDate)) { throw new IllegalArgumentException( "minDate must be before maxDate. " + dbg(minDate, maxDate)); } if (locale == null) { throw new IllegalArgumentException("Locale is null."); } // Make sure that all calendar instances use the same locale. this.locale = locale; today = Calendar.getInstance(locale); minCal = Calendar.getInstance(locale); maxCal = Calendar.getInstance(locale); monthCounter = Calendar.getInstance(locale); monthNameFormat = new SimpleDateFormat(getContext().getString(R.string.month_name_format), locale); for (MonthDescriptor month : months) { month.setLabel(monthNameFormat.format(month.getDate())); } weekdayNameFormat = new SimpleDateFormat(getContext().getString(R.string.day_name_format), locale); fullDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale); this.selectionMode = SelectionMode.SINGLE; // Clear out any previously-selected dates/cells. selectedCals.clear(); selectedCells.clear(); highlightedCals.clear(); highlightedCells.clear(); // Clear previous state. cells.clear(); months.clear(); minCal.setTime(minDate); maxCal.setTime(maxDate); setMidnight(minCal); setMidnight(maxCal); displayOnly = false; // maxDate is exclusive: bump back to the previous day so if maxDate is the first of a month, // we don't accidentally include that month in the view. maxCal.add(MINUTE, -1); // Now iterate between minCal and maxCal and build up our list of months to show. monthCounter.setTime(minCal.getTime()); final int maxMonth = maxCal.get(MONTH); final int maxYear = maxCal.get(YEAR); while ((monthCounter.get(MONTH) <= maxMonth // Up to, including the month. || monthCounter.get(YEAR) < maxYear) // Up to the year. && monthCounter.get(YEAR) < maxYear + 1) { // But not > next yr. Date date = monthCounter.getTime(); MonthDescriptor month = new MonthDescriptor(monthCounter.get(MONTH), monthCounter.get(YEAR), date, monthNameFormat.format(date)); cells.add(getMonthCells(month, monthCounter)); Logr.d("Adding month %s", month); months.add(month); monthCounter.add(MONTH, 1); } validateAndUpdate(); return new FluentInitializer(); } /** * Both date parameters must be non-null and their {@link Date#getTime()} must not return 0. Time * of day will be ignored. For instance, if you pass in {@code minDate} as 11/16/2012 5:15pm and * {@code maxDate} as 11/16/2013 4:30am, 11/16/2012 will be the first selectable date and * 11/15/2013 will be the last selectable date ({@code maxDate} is exclusive). * <p> * This will implicitly set the {@link SelectionMode} to {@link SelectionMode#SINGLE}. If you * want a different selection mode, use {@link FluentInitializer#inMode(SelectionMode)} on the * {@link FluentInitializer} this method returns. * <p> * The calendar will be constructed using the default locale as returned by * {@link java.util.Locale#getDefault()}. If you wish the calendar to be constructed using a * different locale, use {@link #init(java.util.Date, java.util.Date, java.util.Locale)}. * * @param minDate Earliest selectable date, inclusive. Must be earlier than {@code maxDate}. * @param maxDate Latest selectable date, exclusive. Must be later than {@code minDate}. */ public FluentInitializer init(Date minDate, Date maxDate) { return init(minDate, maxDate, Locale.getDefault()); } public class FluentInitializer { /** Override the {@link SelectionMode} from the default ({@link SelectionMode#SINGLE}). */ public FluentInitializer inMode(SelectionMode mode) { selectionMode = mode; validateAndUpdate(); return this; } /** * Set an initially-selected date. The calendar will scroll to that date if it's not already * visible. */ public FluentInitializer withSelectedDate(Date selectedDates) { return withSelectedDates(Collections.singletonList(selectedDates)); } /** * Set multiple selected dates. This will throw an {@link IllegalArgumentException} if you * pass in multiple dates and haven't already called {@link #inMode(SelectionMode)}. */ public FluentInitializer withSelectedDates(Collection<Date> selectedDates) { if (selectionMode == SelectionMode.SINGLE && selectedDates.size() > 1) { throw new IllegalArgumentException("SINGLE mode can't be used with multiple selectedDates"); } if (selectionMode == SelectionMode.RANGE && selectedDates.size() > 2) { throw new IllegalArgumentException( "RANGE mode only allows two selectedDates. You tried to pass " + selectedDates.size()); } if (selectedDates != null) { for (Date date : selectedDates) { selectDate(date); } } scrollToSelectedDates(); validateAndUpdate(); return this; } public FluentInitializer withHighlightedDates(Collection<Date> dates) { highlightDates(dates); return this; } public FluentInitializer withHighlightedDate(Date date) { return withHighlightedDates(Collections.singletonList(date)); } @SuppressLint("SimpleDateFormat") public FluentInitializer setShortWeekdays(String[] newShortWeekdays) { DateFormatSymbols symbols = new DateFormatSymbols(locale); symbols.setShortWeekdays(newShortWeekdays); weekdayNameFormat = new SimpleDateFormat(getContext().getString(R.string.day_name_format), symbols); return this; } public FluentInitializer displayOnly() { displayOnly = true; return this; } } private void validateAndUpdate() { if (getAdapter() == null) { setAdapter(adapter); } adapter.notifyDataSetChanged(); } private void scrollToSelectedMonth(final int selectedIndex) { scrollToSelectedMonth(selectedIndex, false); } private void scrollToSelectedMonth(final int selectedIndex, final boolean smoothScroll) { post(new Runnable() { @Override public void run() { Logr.d("Scrolling to position %d", selectedIndex); if (smoothScroll) { smoothScrollToPosition(selectedIndex); } else { setSelection(selectedIndex); } } }); } private void scrollToSelectedDates() { Integer selectedIndex = null; Integer todayIndex = null; Calendar today = Calendar.getInstance(locale); for (int c = 0; c < months.size(); c++) { MonthDescriptor month = months.get(c); if (selectedIndex == null) { for (Calendar selectedCal : selectedCals) { if (sameMonth(selectedCal, month)) { selectedIndex = c; break; } } if (selectedIndex == null && todayIndex == null && sameMonth(today, month)) { todayIndex = c; } } } if (selectedIndex != null) { scrollToSelectedMonth(selectedIndex); } else if (todayIndex != null) { scrollToSelectedMonth(todayIndex); } } public boolean scrollToDate(Date date) { Integer selectedIndex = null; Calendar cal = Calendar.getInstance(locale); cal.setTime(date); for (int c = 0; c < months.size(); c++) { MonthDescriptor month = months.get(c); if (sameMonth(cal, month)) { selectedIndex = c; break; } } if (selectedIndex != null) { scrollToSelectedMonth(selectedIndex); return true; } return false; } /** * This method should only be called if the calendar is contained in a dialog, and it should only * be called once, right after the dialog is shown (using * {@link android.content.DialogInterface.OnShowListener} or * {@link android.app.DialogFragment#onStart()}). */ public void fixDialogDimens() { Logr.d("Fixing dimensions to h = %d / w = %d", getMeasuredHeight(), getMeasuredWidth()); // Fix the layout height/width after the dialog has been shown. getLayoutParams().height = getMeasuredHeight(); getLayoutParams().width = getMeasuredWidth(); // Post this runnable so it runs _after_ the dimen changes have been applied/re-measured. post(new Runnable() { @Override public void run() { Logr.d("Dimens are fixed: now scroll to the selected date"); scrollToSelectedDates(); } }); } /** * Set the typeface to be used for month titles. */ public void setTitleTypeface(Typeface titleTypeface) { this.titleTypeface = titleTypeface; validateAndUpdate(); } /** * Sets the typeface to be used within the date grid. */ public void setDateTypeface(Typeface dateTypeface) { this.dateTypeface = dateTypeface; validateAndUpdate(); } /** * Sets the typeface to be used for all text within this calendar. */ public void setTypeface(Typeface typeface) { setTitleTypeface(typeface); setDateTypeface(typeface); } /** * This method should only be called if the calendar is contained in a dialog, and it should only * be called when the screen has been rotated and the dialog should be re-measured. */ public void unfixDialogDimens() { Logr.d("Reset the fixed dimensions to allow for re-measurement"); // Fix the layout height/width after the dialog has been shown. getLayoutParams().height = LayoutParams.MATCH_PARENT; getLayoutParams().width = LayoutParams.MATCH_PARENT; requestLayout(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (months.isEmpty()) { throw new IllegalStateException( "Must have at least one month to display. Did you forget to call init()?"); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public Date getSelectedDate() { return (selectedCals.size() > 0 ? selectedCals.get(0).getTime() : null); } public List<Date> getSelectedDates() { List<Date> selectedDates = new ArrayList<>(); for (MonthCellDescriptor cal : selectedCells) { selectedDates.add(cal.getDate()); } Collections.sort(selectedDates); return selectedDates; } /** Returns a string summarizing what the client sent us for init() params. */ private static String dbg(Date minDate, Date maxDate) { return "minDate: " + minDate + "\nmaxDate: " + maxDate; } /** Clears out the hours/minutes/seconds/millis of a Calendar. */ static void setMidnight(Calendar cal) { cal.set(HOUR_OF_DAY, 0); cal.set(MINUTE, 0); cal.set(SECOND, 0); cal.set(MILLISECOND, 0); } private class CellClickedListener implements MonthView.Listener { @Override public void handleClick(MonthCellDescriptor cell) { Date clickedDate = cell.getDate(); if (cellClickInterceptor != null && cellClickInterceptor.onCellClicked(clickedDate)) { return; } if (!betweenDates(clickedDate, minCal, maxCal) || (!cell.isSelectable())) { if (invalidDateListener != null) { invalidDateListener.onInvalidDateSelected(clickedDate); } } else { boolean wasSelected = doSelectDate(clickedDate, cell); if (dateListener != null) { if (wasSelected) { dateListener.onDateSelected(clickedDate); } else { dateListener.onDateUnselected(clickedDate); } } } } } /** * Select a new date. Respects the {@link SelectionMode} this CalendarPickerView is configured * with: if you are in {@link SelectionMode#SINGLE}, the previously selected date will be * un-selected. In {@link SelectionMode#MULTIPLE}, the new date will be added to the list of * selected dates. * <p> * If the selection was made (selectable date, in range), the view will scroll to the newly * selected date if it's not already visible. * * @return - whether we were able to set the date */ public boolean selectDate(Date date) { return selectDate(date, false); } /** * Select a new date. Respects the {@link SelectionMode} this CalendarPickerView is configured * with: if you are in {@link SelectionMode#SINGLE}, the previously selected date will be * un-selected. In {@link SelectionMode#MULTIPLE}, the new date will be added to the list of * selected dates. * <p> * If the selection was made (selectable date, in range), the view will scroll to the newly * selected date if it's not already visible. * * @return - whether we were able to set the date */ public boolean selectDate(Date date, boolean smoothScroll) { validateDate(date); MonthCellWithMonthIndex monthCellWithMonthIndex = getMonthCellWithIndexByDate(date); if (monthCellWithMonthIndex == null || !isDateSelectable(date)) { return false; } boolean wasSelected = doSelectDate(date, monthCellWithMonthIndex.cell); if (wasSelected) { scrollToSelectedMonth(monthCellWithMonthIndex.monthIndex, smoothScroll); } return wasSelected; } private void validateDate(Date date) { if (date == null) { throw new IllegalArgumentException("Selected date must be non-null."); } if (date.before(minCal.getTime()) || date.after(maxCal.getTime())) { throw new IllegalArgumentException(String.format( "SelectedDate must be between minDate and maxDate." + "%nminDate: %s%nmaxDate: %s%nselectedDate: %s", minCal.getTime(), maxCal.getTime(), date)); } } private boolean doSelectDate(Date date, MonthCellDescriptor cell) { Calendar newlySelectedCal = Calendar.getInstance(locale); newlySelectedCal.setTime(date); // Sanitize input: clear out the hours/minutes/seconds/millis. setMidnight(newlySelectedCal); // Clear any remaining range state. for (MonthCellDescriptor selectedCell : selectedCells) { selectedCell.setRangeState(RangeState.NONE); } switch (selectionMode) { case RANGE: if (selectedCals.size() > 1) { // We've already got a range selected: clear the old one. clearOldSelections(); } else if (selectedCals.size() == 1 && newlySelectedCal.before(selectedCals.get(0))) { // We're moving the start of the range back in time: clear the old start date. clearOldSelections(); } else if (date != null && selectedCals.size() == 1) { checkForUnSelectableDate(newlySelectedCal); } break; case MULTIPLE: date = applyMultiSelect(date, newlySelectedCal); break; case SINGLE: clearOldSelections(); break; default: throw new IllegalStateException("Unknown selectionMode " + selectionMode); } if (date != null) { // Select a new cell. if (selectedCells.size() == 0 || !selectedCells.get(0).equals(cell)) { selectedCells.add(cell); cell.setSelected(true); } selectedCals.add(newlySelectedCal); if (selectionMode == SelectionMode.RANGE && selectedCells.size() == 1) { setLastDateSelectable(selectedCells.get(0).getDate()); } if (selectionMode == SelectionMode.RANGE && selectedCells.size() > 1) { // Select all days in between start and end. Date start = selectedCells.get(0).getDate(); Date end = selectedCells.get(1).getDate(); selectedCells.get(0).setRangeState(MonthCellDescriptor.RangeState.FIRST); selectedCells.get(1).setRangeState(MonthCellDescriptor.RangeState.LAST); for (List<List<MonthCellDescriptor>> month : cells) { for (List<MonthCellDescriptor> week : month) { for (MonthCellDescriptor singleCell : week) { if (singleCell.getDate().after(start) && singleCell.getDate().before(end) && singleCell.isSelectable()) { singleCell.setSelected(true); singleCell.setRangeState(MonthCellDescriptor.RangeState.MIDDLE); selectedCells.add(singleCell); } } } } } } // Update the adapter. validateAndUpdate(); return date != null; } private void checkForUnSelectableDate(Calendar newlySelectedCal) { for (List<List<MonthCellDescriptor>> month : cells) { for (List<MonthCellDescriptor> week : month) { for (MonthCellDescriptor singleCell : week) { if (singleCell.getDate().after(selectedCals.get(0).getTime()) && singleCell.getDate().before(newlySelectedCal.getTime()) && ((!singleCell.isSelectable() && previouslyUnSelectableCell == null) || (singleCell.isSelectable() && previouslyUnSelectableCell.equals(singleCell))) && singleCell.isCurrentMonth()) { clearOldSelections(); return; } } } } } private void setLastDateSelectable(Date start) { for (List<List<MonthCellDescriptor>> month : cells) { for (List<MonthCellDescriptor> week : month) { for (MonthCellDescriptor singleCell : week) { if (singleCell.getDate().after(start) && !singleCell.isSelectable() && singleCell.isCurrentMonth()) { singleCell.setSelectable(true); previouslyUnSelectableCell = singleCell; return; } } } } } private void clearOldSelections() { if (previouslyUnSelectableCell != null) { previouslyUnSelectableCell.setSelectable(false); previouslyUnSelectableCell = null; } for (MonthCellDescriptor selectedCell : selectedCells) { // De-select the currently-selected cell. selectedCell.setSelected(false); if (dateListener != null) { Date selectedDate = selectedCell.getDate(); if (selectionMode == SelectionMode.RANGE) { int index = selectedCells.indexOf(selectedCell); if (index == 0 || index == selectedCells.size() - 1) { dateListener.onDateUnselected(selectedDate); } } else { dateListener.onDateUnselected(selectedDate); } } } selectedCells.clear(); selectedCals.clear(); } private Date applyMultiSelect(Date date, Calendar selectedCal) { for (MonthCellDescriptor selectedCell : selectedCells) { if (selectedCell.getDate().equals(date)) { // De-select the currently-selected cell. selectedCell.setSelected(false); selectedCells.remove(selectedCell); date = null; break; } } for (Calendar cal : selectedCals) { if (sameDate(cal, selectedCal)) { selectedCals.remove(cal); break; } } return date; } public void highlightDates(Collection<Date> dates) { for (Date date : dates) { validateDate(date); MonthCellWithMonthIndex monthCellWithMonthIndex = getMonthCellWithIndexByDate(date); if (monthCellWithMonthIndex != null) { Calendar newlyHighlightedCal = Calendar.getInstance(); newlyHighlightedCal.setTime(date); MonthCellDescriptor cell = monthCellWithMonthIndex.cell; highlightedCells.add(cell); highlightedCals.add(newlyHighlightedCal); cell.setHighlighted(true); } } validateAndUpdate(); } public void clearHighlightedDates() { for (MonthCellDescriptor cal : highlightedCells) { cal.setHighlighted(false); } highlightedCells.clear(); highlightedCals.clear(); validateAndUpdate(); } /** Hold a cell with a month-index. */ private static class MonthCellWithMonthIndex { public MonthCellDescriptor cell; public int monthIndex; public MonthCellWithMonthIndex(MonthCellDescriptor cell, int monthIndex) { this.cell = cell; this.monthIndex = monthIndex; } } /** Return cell and month-index (for scrolling) for a given Date. */ private MonthCellWithMonthIndex getMonthCellWithIndexByDate(Date date) { int index = 0; Calendar searchCal = Calendar.getInstance(locale); searchCal.setTime(date); Calendar actCal = Calendar.getInstance(locale); for (List<List<MonthCellDescriptor>> monthCells : cells) { for (List<MonthCellDescriptor> weekCells : monthCells) { for (MonthCellDescriptor actCell : weekCells) { actCal.setTime(actCell.getDate()); if (sameDate(actCal, searchCal) && actCell.isSelectable()) { return new MonthCellWithMonthIndex(actCell, index); } } } index++; } return null; } private class MonthAdapter extends BaseAdapter { private final LayoutInflater inflater; private MonthAdapter() { inflater = LayoutInflater.from(getContext()); } @Override public boolean isEnabled(int position) { // Disable selectability: each cell will handle that itself. return false; } @Override public int getCount() { return months.size(); } @Override public Object getItem(int position) { return months.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { MonthView monthView = (MonthView) convertView; if (monthView == null || !monthView.getTag(R.id.day_view_adapter_class).equals(dayViewAdapter.getClass())) { monthView = MonthView.create(parent, inflater, weekdayNameFormat, listener, today, dividerColor, dayBackgroundResId, dayTextColorResId, titleTextColor, displayHeader, headerTextColor, decorators, locale, dayViewAdapter); monthView.setTag(R.id.day_view_adapter_class, dayViewAdapter.getClass()); } else { monthView.setDecorators(decorators); } monthView.init(months.get(position), cells.get(position), displayOnly, titleTypeface, dateTypeface); return monthView; } } List<List<MonthCellDescriptor>> getMonthCells(MonthDescriptor month, Calendar startCal) { Calendar cal = Calendar.getInstance(locale); cal.setTime(startCal.getTime()); List<List<MonthCellDescriptor>> cells = new ArrayList<>(); cal.set(DAY_OF_MONTH, 1); int firstDayOfWeek = cal.get(DAY_OF_WEEK); int offset = cal.getFirstDayOfWeek() - firstDayOfWeek; if (offset > 0) { offset -= 7; } cal.add(Calendar.DATE, offset); Calendar minSelectedCal = minDate(selectedCals); Calendar maxSelectedCal = maxDate(selectedCals); while ((cal.get(MONTH) < month.getMonth() + 1 || cal.get(YEAR) < month.getYear()) // && cal.get(YEAR) <= month.getYear()) { Logr.d("Building week row starting at %s", cal.getTime()); List<MonthCellDescriptor> weekCells = new ArrayList<>(); cells.add(weekCells); for (int c = 0; c < 7; c++) { Date date = cal.getTime(); boolean isCurrentMonth = cal.get(MONTH) == month.getMonth(); boolean isSelected = isCurrentMonth && containsDate(selectedCals, cal); boolean isSelectable = isCurrentMonth && betweenDates(cal, minCal, maxCal) && isDateSelectable(date); boolean isToday = sameDate(cal, today); boolean isHighlighted = containsDate(highlightedCals, cal); int value = cal.get(DAY_OF_MONTH); MonthCellDescriptor.RangeState rangeState = MonthCellDescriptor.RangeState.NONE; if (selectedCals.size() > 1) { if (sameDate(minSelectedCal, cal)) { rangeState = MonthCellDescriptor.RangeState.FIRST; } else if (sameDate(maxDate(selectedCals), cal)) { rangeState = MonthCellDescriptor.RangeState.LAST; } else if (betweenDates(cal, minSelectedCal, maxSelectedCal)) { rangeState = MonthCellDescriptor.RangeState.MIDDLE; } } weekCells.add( new MonthCellDescriptor(date, isCurrentMonth, isSelectable, isSelected, isToday, isHighlighted, value, rangeState)); cal.add(DATE, 1); } } return cells; } private boolean containsDate(List<Calendar> selectedCals, Date date) { Calendar cal = Calendar.getInstance(locale); cal.setTime(date); return containsDate(selectedCals, cal); } private static boolean containsDate(List<Calendar> selectedCals, Calendar cal) { for (Calendar selectedCal : selectedCals) { if (sameDate(cal, selectedCal)) { return true; } } return false; } private static Calendar minDate(List<Calendar> selectedCals) { if (selectedCals == null || selectedCals.size() == 0) { return null; } Collections.sort(selectedCals); return selectedCals.get(0); } private static Calendar maxDate(List<Calendar> selectedCals) { if (selectedCals == null || selectedCals.size() == 0) { return null; } Collections.sort(selectedCals); return selectedCals.get(selectedCals.size() - 1); } private static boolean sameDate(Calendar cal, Calendar selectedDate) { return cal.get(MONTH) == selectedDate.get(MONTH) && cal.get(YEAR) == selectedDate.get(YEAR) && cal.get(DAY_OF_MONTH) == selectedDate.get(DAY_OF_MONTH); } private static boolean betweenDates(Calendar cal, Calendar minCal, Calendar maxCal) { final Date date = cal.getTime(); return betweenDates(date, minCal, maxCal); } static boolean betweenDates(Date date, Calendar minCal, Calendar maxCal) { final Date min = minCal.getTime(); return (date.equals(min) || date.after(min)) // >= minCal && date.before(maxCal.getTime()); // && < maxCal } private static boolean sameMonth(Calendar cal, MonthDescriptor month) { return (cal.get(MONTH) == month.getMonth() && cal.get(YEAR) == month.getYear()); } private boolean isDateSelectable(Date date) { return dateConfiguredListener == null || dateConfiguredListener.isDateSelectable(date); } public void setOnDateSelectedListener(OnDateSelectedListener listener) { dateListener = listener; } /** * Set a listener to react to user selection of a disabled date. * * @param listener the listener to set, or null for no reaction */ public void setOnInvalidDateSelectedListener(OnInvalidDateSelectedListener listener) { invalidDateListener = listener; } /** * Set a listener used to discriminate between selectable and unselectable dates. Set this to * disable arbitrary dates as they are rendered. * <p> * Important: set this before you call {@link #init(Date, Date)} methods. If called afterwards, * it will not be consistently applied. */ public void setDateSelectableFilter(DateSelectableFilter listener) { dateConfiguredListener = listener; } /** * Set an adapter used to initialize {@link CalendarCellView} with custom layout. * <p> * Important: set this before you call {@link #init(Date, Date)} methods. If called afterwards, * it will not be consistently applied. */ public void setCustomDayView(DayViewAdapter dayViewAdapter) { this.dayViewAdapter = dayViewAdapter; if (null != adapter) { adapter.notifyDataSetChanged(); } } /** Set a listener to intercept clicks on calendar cells. */ public void setCellClickInterceptor(CellClickInterceptor listener) { cellClickInterceptor = listener; } /** * Interface to be notified when a new date is selected or unselected. This will only be called * when the user initiates the date selection. If you call {@link #selectDate(Date)} this * listener will not be notified. * * @see #setOnDateSelectedListener(OnDateSelectedListener) */ public interface OnDateSelectedListener { void onDateSelected(Date date); void onDateUnselected(Date date); } /** * Interface to be notified when an invalid date is selected by the user. This will only be * called when the user initiates the date selection. If you call {@link #selectDate(Date)} this * listener will not be notified. * * @see #setOnInvalidDateSelectedListener(OnInvalidDateSelectedListener) */ public interface OnInvalidDateSelectedListener { void onInvalidDateSelected(Date date); } /** * Interface used for determining the selectability of a date cell when it is configured for * display on the calendar. * * @see #setDateSelectableFilter(DateSelectableFilter) */ public interface DateSelectableFilter { boolean isDateSelectable(Date date); } /** * Interface to be notified when a cell is clicked and possibly intercept the click. Return true * to intercept the click and prevent any selections from changing. * * @see #setCellClickInterceptor(CellClickInterceptor) */ public interface CellClickInterceptor { boolean onCellClicked(Date date); } private class DefaultOnInvalidDateSelectedListener implements OnInvalidDateSelectedListener { @Override public void onInvalidDateSelected(Date date) { String errMessage = getResources().getString(R.string.invalid_date, fullDateFormat.format(minCal.getTime()), fullDateFormat.format(maxCal.getTime())); Toast.makeText(getContext(), errMessage, Toast.LENGTH_SHORT).show(); } } }
Fix selecting departure date right away
library/src/main/java/com/squareup/timessquare/CalendarPickerView.java
Fix selecting departure date right away
<ide><path>ibrary/src/main/java/com/squareup/timessquare/CalendarPickerView.java <ide> selectedCells.get(0).setRangeState(MonthCellDescriptor.RangeState.FIRST); <ide> selectedCells.get(1).setRangeState(MonthCellDescriptor.RangeState.LAST); <ide> <add> if (previouslyUnSelectableCell != null <add> && !previouslyUnSelectableCell.getDate().equals(end)) { <add> previouslyUnSelectableCell.setSelectable(false); <add> previouslyUnSelectableCell = null; <add> } <add> <ide> for (List<List<MonthCellDescriptor>> month : cells) { <ide> for (List<MonthCellDescriptor> week : month) { <ide> for (MonthCellDescriptor singleCell : week) {
Java
mit
7f8c873433cb45a23071bc79302afa77e505dcef
0
DovSnier/CSSTranslateMachine
/** * */ package com.dovsnier.interpreter; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.Writer; import com.dovsnier.bean.Attribute; import com.dovsnier.bean.DocumentBean; import com.dovsnier.bean.NodeBean; import com.dovsnier.bean.RootNodeBean; /** * <pre> * Interpreter * </pre> * * @author dovsnier * @version 1.0.0 * @since jdk 1.7 */ public class Interpreter extends AbstractInterpreter { private Writer writer = null; private Reader reader = null; private BufferedReader br = null; /* * @see com.dovsnier.interpreter.AbstractInterpreter#parseCssDocuments(java.lang.String) */ @Override public void parseCssDocuments(String path) { } /* * @see com.dovsnier.interpreter.AbstractInterpreter#parseCssDocument(java.lang.String, java.lang.String) */ @Override public void parseCssDocument(String path, String name) { String absolutePath = detectionParameterSuffix(path); String alias = name; File file = new File(absolutePath, name); DocumentBean document = null; RootNodeBean rootNode = null; NodeBean node = null; try { if (!file.exists()) { String msg = "the current " + absolutePath + name + " is not found exception."; throw new FileNotFoundException(msg); } else { document = new DocumentBean(); rootNode = new RootNodeBean(); document.setAlias(alias.substring(0, alias.lastIndexOf("."))); document.setRootNode(rootNode); } reader = new FileReader(file); br = new BufferedReader(reader); String lineData = ""; StringBuffer sbCache = new StringBuffer(); // TODO the handle parse css style sheet while (null != (lineData = br.readLine())) { if ("".equalsIgnoreCase(lineData)) { // TODO the current line is empty line that belong to text format category } else if (lineData.contains("{") && lineData.contains("}")) { // TODO the current line exist node bean with one or more, and need careful analysis } else if (lineData.contains("{") && !lineData.contains("}")) { // TODO the current line exist node bean that is not entire,and need continue ready node = new NodeBean(); String nodeName = lineData; nodeName = nodeName.replace("{", "").trim(); node.setNodeName(nodeName); } else if (!lineData.contains("{") && lineData.contains("}")) {// TODO the current line exist node bean that maybe is node bean ended symbol or item node bean ended symbol rootNode.getRootNode().add(node);// the add node to root node or not to item node // the add node to item node or not to root node } else if (!lineData.contains("{") && !lineData.contains("}")) {// TODO the current line exist node bean that maybe is node bean attribute or item node bean attribute if (lineData.contains(";")) { // these maybe is node bean attribute or item node bean attribute Attribute attribute = new Attribute(); String kvPair = lineData; kvPair = kvPair.replace(";", "").trim(); String[] kvContainer = kvPair.split(":"); if (null != kvContainer) { attribute.setKey(kvContainer[0].trim()); attribute.setValue(kvContainer[1].trim()); } else { } node.getAttribute().add(attribute); } } sbCache.append(lineData); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != br) { try { br.close(); if (null != reader) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } } private String detectionParameterSuffix(String path) { String absolutePath = path; String assertValue = path; assertValue = assertValue.substring(assertValue.length() - 1); if (!"\\".equals(assertValue)) { absolutePath += "\\"; } return absolutePath; } }
src/com/dovsnier/interpreter/Interpreter.java
/** * */ package com.dovsnier.interpreter; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.Writer; import com.dovsnier.bean.DocumentBean; import com.dovsnier.bean.RootNodeBean; /** * <pre> * Interpreter * </pre> * * @author dovsnier * @version 1.0.0 * @since jdk 1.7 */ public class Interpreter extends AbstractInterpreter { private Writer writer = null; private Reader reader = null; private BufferedReader br = null; /* * @see com.dovsnier.interpreter.AbstractInterpreter#parseCssDocuments(java.lang.String) */ @Override public void parseCssDocuments(String path) { } /* * @see com.dovsnier.interpreter.AbstractInterpreter#parseCssDocument(java.lang.String, java.lang.String) */ @Override public void parseCssDocument(String path, String name) { String absolutePath = detectionParameterSuffix(path); String alias = name; RootNodeBean rootNode; File file = new File(absolutePath, name); DocumentBean document = null; try { if (!file.exists()) { String msg = "the current " + absolutePath + name + " is not found exception."; throw new FileNotFoundException(msg); } else { document = new DocumentBean(); document.setAlias(alias.substring(0, alias.lastIndexOf("."))); rootNode = new RootNodeBean(); document.setRootNode(rootNode); } reader = new FileReader(file); br = new BufferedReader(reader); StringBuffer sb = new StringBuffer(); String lineData = ""; // TODO the handle parse css style sheet while (null != (lineData = br.readLine())) { sb.append(lineData); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != br) { try { br.close(); if (null != reader) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } } } } private String detectionParameterSuffix(String path) { String absolutePath = path; String assertValue = path; assertValue = assertValue.substring(assertValue.length() - 1); if (!"\\".equals(assertValue)) { absolutePath += "\\"; } return absolutePath; } }
the impl sample parse css style sheet function that maybe a lot have bug and so on.
src/com/dovsnier/interpreter/Interpreter.java
the impl sample parse css style sheet function that maybe a lot have bug and so on.
<ide><path>rc/com/dovsnier/interpreter/Interpreter.java <ide> import java.io.Reader; <ide> import java.io.Writer; <ide> <add>import com.dovsnier.bean.Attribute; <ide> import com.dovsnier.bean.DocumentBean; <add>import com.dovsnier.bean.NodeBean; <ide> import com.dovsnier.bean.RootNodeBean; <ide> <ide> /** <ide> public void parseCssDocument(String path, String name) { <ide> String absolutePath = detectionParameterSuffix(path); <ide> String alias = name; <del> RootNodeBean rootNode; <ide> File file = new File(absolutePath, name); <ide> DocumentBean document = null; <add> RootNodeBean rootNode = null; <add> NodeBean node = null; <ide> try { <ide> if (!file.exists()) { <ide> String msg = "the current " + absolutePath + name + " is not found exception."; <ide> throw new FileNotFoundException(msg); <ide> } else { <ide> document = new DocumentBean(); <add> rootNode = new RootNodeBean(); <ide> document.setAlias(alias.substring(0, alias.lastIndexOf("."))); <del> rootNode = new RootNodeBean(); <ide> document.setRootNode(rootNode); <ide> } <ide> reader = new FileReader(file); <ide> br = new BufferedReader(reader); <del> StringBuffer sb = new StringBuffer(); <ide> String lineData = ""; <add> StringBuffer sbCache = new StringBuffer(); <ide> // TODO the handle parse css style sheet <ide> while (null != (lineData = br.readLine())) { <del> sb.append(lineData); <add> if ("".equalsIgnoreCase(lineData)) { // TODO the current line is empty line that belong to text format category <add> } else if (lineData.contains("{") && lineData.contains("}")) { // TODO the current line exist node bean with one or more, and need careful analysis <add> } else if (lineData.contains("{") && !lineData.contains("}")) { // TODO the current line exist node bean that is not entire,and need continue ready <add> node = new NodeBean(); <add> String nodeName = lineData; <add> nodeName = nodeName.replace("{", "").trim(); <add> node.setNodeName(nodeName); <add> } else if (!lineData.contains("{") && lineData.contains("}")) {// TODO the current line exist node bean that maybe is node bean ended symbol or item node bean ended symbol <add> rootNode.getRootNode().add(node);// the add node to root node or not to item node <add> // the add node to item node or not to root node <add> } else if (!lineData.contains("{") && !lineData.contains("}")) {// TODO the current line exist node bean that maybe is node bean attribute or item node bean attribute <add> if (lineData.contains(";")) { // these maybe is node bean attribute or item node bean attribute <add> Attribute attribute = new Attribute(); <add> String kvPair = lineData; <add> kvPair = kvPair.replace(";", "").trim(); <add> String[] kvContainer = kvPair.split(":"); <add> if (null != kvContainer) { <add> attribute.setKey(kvContainer[0].trim()); <add> attribute.setValue(kvContainer[1].trim()); <add> } else { <add> } <add> node.getAttribute().add(attribute); <add> } <add> } <add> sbCache.append(lineData); <ide> } <ide> } catch (FileNotFoundException e) { <ide> e.printStackTrace();
Java
mpl-2.0
1fd15800d3c340e2f41c11132b7f08490a16f71e
0
amagdenko/oiosaml.java,amagdenko/oiosaml.java,amagdenko/oiosaml.java,amagdenko/oiosaml.java
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this * file except in compliance with the License. You may obtain * a copy of the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language governing * rights and limitations under the License. * * * The Original Code is OIOSAML Java Service Provider. * * The Initial Developer of the Original Code is Trifork A/S. Portions * created by Trifork A/S are Copyright (C) 2008 Danish National IT * and Telecom Agency (http://www.itst.dk). All Rights Reserved. * * Contributor(s): * Joakim Recht <[email protected]> * Rolf Njor Jensen <[email protected]> * */ package dk.itst.oiosaml.sp.model; import java.security.PublicKey; import javax.xml.crypto.dsig.XMLSignature; import org.apache.log4j.Logger; import org.opensaml.Configuration; import org.opensaml.common.SignableSAMLObject; import org.opensaml.ws.soap.soap11.Body; import org.opensaml.ws.soap.soap11.Envelope; import org.opensaml.xml.ElementExtensibleXMLObject; import org.opensaml.xml.Namespace; import org.opensaml.xml.XMLObject; import org.opensaml.xml.io.Marshaller; import org.opensaml.xml.io.MarshallingException; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.SecurityHelper; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.x509.BasicX509Credential; import org.opensaml.xml.signature.Signature; import org.opensaml.xml.signature.SignatureException; import org.opensaml.xml.signature.SignatureValidator; import org.opensaml.xml.signature.Signer; import org.opensaml.xml.util.Base64; import org.opensaml.xml.util.XMLHelper; import org.opensaml.xml.validation.ValidationException; import org.w3c.dom.Element; import dk.itst.oiosaml.common.SAMLUtil; import dk.itst.oiosaml.error.Layer; import dk.itst.oiosaml.error.WrappedException; /** * Base class for all SAML objects. * * This class defines default behavior, such as signature handling and serialization. * * @author Joakim Recht <[email protected]> * */ public class OIOSamlObject { private static final Logger log = Logger.getLogger(OIOSamlObject.class); private final XMLObject obj; public OIOSamlObject(XMLObject obj) { if (obj == null) throw new IllegalArgumentException("Object cannot be null"); this.obj = obj; } @Override public String toString() { return "Object: " + obj; } /** * Get an XML representation of the object. */ public String toXML() { Element e = SAMLUtil.marshallObject(obj); return XMLHelper.nodeToString(e); } /** * Sign the saml object. * * The effect of calling this method is that a new Signature element is created, and the object is marshalled. * If {@link #toXML()} is called, the XML will contain a valid signature. * * @param signingCredential The credential used for signing the object. */ public void sign(Credential signingCredential) { Signature signature = SAMLUtil.buildXMLObject(Signature.class); if (!(obj instanceof SignableSAMLObject)) { throw new IllegalStateException("Object of type " + obj.getClass() + " is not signable"); } // manually add the ds namespace, as it will be added to the inclusiveNamespaces element obj.addNamespace(new Namespace(XMLSignature.XMLNS, "ds")); signature.setSigningCredential(signingCredential); try { SecurityHelper.prepareSignatureParams(signature, signingCredential, null, null); } catch (SecurityException e) { throw new WrappedException(Layer.BUSINESS, e); } ((SignableSAMLObject)obj).setSignature(signature); try { Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(obj); if (marshaller == null) { throw new RuntimeException("No marshaller registered for " + obj.getElementQName() + ", unable to marshall in preperation for signing"); } marshaller.marshall(obj); Signer.signObject(signature); } catch (MarshallingException e) { log.error("Unable to marshall protocol message in preparation for signing", e); throw new WrappedException(Layer.BUSINESS, e); } catch (SignatureException e) { log.error("Unable to sign protocol message", e); throw new WrappedException(Layer.BUSINESS, e); } } /** * Encode the SAML object to a base64 encoded string. * * @return The XML representation encoded with base64. */ public String toBase64() { Element element = SAMLUtil.marshallObject(obj); String xml = XMLHelper.nodeToString(element); return Base64.encodeBytes(xml.getBytes(), Base64.DONT_BREAK_LINES); } /** * Check if the object has a signature. */ public boolean hasSignature() { if (!(obj instanceof SignableSAMLObject)) return false; return ((SignableSAMLObject)obj).getSignature() != null; } /** * Check that a given object has been signed correctly with a specific {@link PublicKey}. * * @return true, if the signableObject has been signed correctly with the given key. * Returns <code>false</code> if the object is not signed at all. */ public boolean verifySignature(PublicKey publicKey) { if (publicKey == null) { throw new IllegalArgumentException("Certificate cannot be null"); } Signature signature = null; if (obj instanceof SignableSAMLObject) { SignableSAMLObject signableObject = (SignableSAMLObject) obj; signature = signableObject.getSignature(); } else if (obj instanceof ElementExtensibleXMLObject){ signature = SAMLUtil.getFirstElement((ElementExtensibleXMLObject)obj, Signature.class); } if (signature == null) { log.warn("No signature present in object " + obj); return false; } BasicX509Credential credential = new BasicX509Credential(); credential.setPublicKey(publicKey); SignatureValidator validator = new SignatureValidator(credential); try { validator.validate(signature); return true; } catch (ValidationException e) { log.warn("The signature does not match the signature of the login site", e); return false; } } public String toSoapEnvelope() { Body body = SAMLUtil.buildXMLObject(Body.class); body.getUnknownXMLObjects().add(obj); // Build output... Envelope envelope = SAMLUtil.buildXMLObject(Envelope.class); envelope.setBody(body); Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(envelope); try { Element e = marshaller.marshall(envelope); return XMLHelper.nodeToString(e); } catch (MarshallingException e) { throw new WrappedException(Layer.CLIENT, e); } } }
sp/trunk/src/dk/itst/oiosaml/sp/model/OIOSamlObject.java
/* * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this * file except in compliance with the License. You may obtain * a copy of the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express * or implied. See the License for the specific language governing * rights and limitations under the License. * * * The Original Code is OIOSAML Java Service Provider. * * The Initial Developer of the Original Code is Trifork A/S. Portions * created by Trifork A/S are Copyright (C) 2008 Danish National IT * and Telecom Agency (http://www.itst.dk). All Rights Reserved. * * Contributor(s): * Joakim Recht <[email protected]> * Rolf Njor Jensen <[email protected]> * */ package dk.itst.oiosaml.sp.model; import java.security.PublicKey; import org.apache.log4j.Logger; import org.opensaml.Configuration; import org.opensaml.common.SignableSAMLObject; import org.opensaml.ws.soap.soap11.Body; import org.opensaml.ws.soap.soap11.Envelope; import org.opensaml.xml.ElementExtensibleXMLObject; import org.opensaml.xml.XMLObject; import org.opensaml.xml.io.Marshaller; import org.opensaml.xml.io.MarshallingException; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.SecurityHelper; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.x509.BasicX509Credential; import org.opensaml.xml.signature.Signature; import org.opensaml.xml.signature.SignatureException; import org.opensaml.xml.signature.SignatureValidator; import org.opensaml.xml.signature.Signer; import org.opensaml.xml.util.Base64; import org.opensaml.xml.util.XMLHelper; import org.opensaml.xml.validation.ValidationException; import org.w3c.dom.Element; import dk.itst.oiosaml.common.SAMLUtil; import dk.itst.oiosaml.error.Layer; import dk.itst.oiosaml.error.WrappedException; /** * Base class for all SAML objects. * * This class defines default behavior, such as signature handling and serialization. * * @author Joakim Recht <[email protected]> * */ public class OIOSamlObject { private static final Logger log = Logger.getLogger(OIOSamlObject.class); private final XMLObject obj; public OIOSamlObject(XMLObject obj) { if (obj == null) throw new IllegalArgumentException("Object cannot be null"); this.obj = obj; } @Override public String toString() { return "Object: " + obj; } /** * Get an XML representation of the object. */ public String toXML() { Element e = SAMLUtil.marshallObject(obj); return XMLHelper.nodeToString(e); } /** * Sign the saml object. * * The effect of calling this method is that a new Signature element is created, and the object is marshalled. * If {@link #toXML()} is called, the XML will contain a valid signature. * * @param signingCredential The credential used for signing the object. */ public void sign(Credential signingCredential) { Signature signature = SAMLUtil.buildXMLObject(Signature.class); if (!(obj instanceof SignableSAMLObject)) { throw new IllegalStateException("Object of type " + obj.getClass() + " is not signable"); } signature.setSigningCredential(signingCredential); try { SecurityHelper.prepareSignatureParams(signature, signingCredential, null, null); } catch (SecurityException e) { throw new WrappedException(Layer.BUSINESS, e); } ((SignableSAMLObject)obj).setSignature(signature); try { Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(obj); if (marshaller == null) { throw new RuntimeException("No marshaller registered for " + obj.getElementQName() + ", unable to marshall in preperation for signing"); } marshaller.marshall(obj); Signer.signObject(signature); } catch (MarshallingException e) { log.error("Unable to marshall protocol message in preparation for signing", e); throw new WrappedException(Layer.BUSINESS, e); } catch (SignatureException e) { log.error("Unable to sign protocol message", e); throw new WrappedException(Layer.BUSINESS, e); } } /** * Encode the SAML object to a base64 encoded string. * * @return The XML representation encoded with base64. */ public String toBase64() { Element element = SAMLUtil.marshallObject(obj); String xml = XMLHelper.nodeToString(element); return Base64.encodeBytes(xml.getBytes(), Base64.DONT_BREAK_LINES); } /** * Check if the object has a signature. */ public boolean hasSignature() { if (!(obj instanceof SignableSAMLObject)) return false; return ((SignableSAMLObject)obj).getSignature() != null; } /** * Check that a given object has been signed correctly with a specific {@link PublicKey}. * * @return true, if the signableObject has been signed correctly with the given key. * Returns <code>false</code> if the object is not signed at all. */ public boolean verifySignature(PublicKey publicKey) { if (publicKey == null) { throw new IllegalArgumentException("Certificate cannot be null"); } Signature signature = null; if (obj instanceof SignableSAMLObject) { SignableSAMLObject signableObject = (SignableSAMLObject) obj; signature = signableObject.getSignature(); } else if (obj instanceof ElementExtensibleXMLObject){ signature = SAMLUtil.getFirstElement((ElementExtensibleXMLObject)obj, Signature.class); } if (signature == null) { log.warn("No signature present in object " + obj); return false; } BasicX509Credential credential = new BasicX509Credential(); credential.setPublicKey(publicKey); SignatureValidator validator = new SignatureValidator(credential); try { validator.validate(signature); return true; } catch (ValidationException e) { log.warn("The signature does not match the signature of the login site", e); return false; } } public String toSoapEnvelope() { Body body = SAMLUtil.buildXMLObject(Body.class); body.getUnknownXMLObjects().add(obj); // Build output... Envelope envelope = SAMLUtil.buildXMLObject(Envelope.class); envelope.setBody(body); Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(envelope); try { Element e = marshaller.marshall(envelope); return XMLHelper.nodeToString(e); } catch (MarshallingException e) { throw new WrappedException(Layer.CLIENT, e); } } }
add ds namespace to top element to avoid signature checking problems
sp/trunk/src/dk/itst/oiosaml/sp/model/OIOSamlObject.java
add ds namespace to top element to avoid signature checking problems
<ide><path>p/trunk/src/dk/itst/oiosaml/sp/model/OIOSamlObject.java <ide> package dk.itst.oiosaml.sp.model; <ide> <ide> import java.security.PublicKey; <add> <add>import javax.xml.crypto.dsig.XMLSignature; <ide> <ide> import org.apache.log4j.Logger; <ide> import org.opensaml.Configuration; <ide> import org.opensaml.ws.soap.soap11.Body; <ide> import org.opensaml.ws.soap.soap11.Envelope; <ide> import org.opensaml.xml.ElementExtensibleXMLObject; <add>import org.opensaml.xml.Namespace; <ide> import org.opensaml.xml.XMLObject; <ide> import org.opensaml.xml.io.Marshaller; <ide> import org.opensaml.xml.io.MarshallingException; <ide> if (!(obj instanceof SignableSAMLObject)) { <ide> throw new IllegalStateException("Object of type " + obj.getClass() + " is not signable"); <ide> } <add> // manually add the ds namespace, as it will be added to the inclusiveNamespaces element <add> obj.addNamespace(new Namespace(XMLSignature.XMLNS, "ds")); <ide> <ide> signature.setSigningCredential(signingCredential); <ide> try {
Java
mit
0412583cb873917ece92ba16ca534baf6087aae6
0
jareddlc/OpenFit,aksalj/OpenFit
package com.solderbyte.openfit; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; import com.solderbyte.openfit.protocol.OpenFitNotificationProtocol; import com.solderbyte.openfit.util.OpenFitData; import com.solderbyte.openfit.util.OpenFitDataType; import com.solderbyte.openfit.util.OpenFitDataTypeAndString; import com.solderbyte.openfit.util.OpenFitTimeZoneUtil; import com.solderbyte.openfit.util.OpenFitVariableDataComposer; public class OpenFitApi { public static byte[] getReady() { //000400000003000000 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)0); oVariableDataComposer.writeInt(OpenFitData.SIZE_OF_INT); oVariableDataComposer.writeInt(3); return oVariableDataComposer.toByteArray(); } public static byte[] getUpdate() { OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte(OpenFitData.PORT_FOTA); oVariableDataComposer.writeInt(OpenFitData.SIZE_OF_INT); oVariableDataComposer.writeBytes("ODIN".getBytes()); //oVariableDataComposer.writeByte((byte)79); // O //oVariableDataComposer.writeByte((byte)68); // D //oVariableDataComposer.writeByte((byte)73); // I //oVariableDataComposer.writeByte((byte)78); // N return oVariableDataComposer.toByteArray(); } public static byte[] getUpdateFollowUp() { //640800000004020501 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte(OpenFitData.OPENFIT_DATA); oVariableDataComposer.writeInt(OpenFitData.SIZE_OF_DOUBLE); oVariableDataComposer.writeByte((byte)4); oVariableDataComposer.writeByte((byte)2); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeByte((byte)4); oVariableDataComposer.writeByte((byte)2); oVariableDataComposer.writeByte((byte)5); oVariableDataComposer.writeByte((byte)1); return oVariableDataComposer.toByteArray(); } public static byte[] getFotaCommand() { //4E020000000101 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte(OpenFitData.PORT_FOTA_COMMAND); oVariableDataComposer.writeInt(OpenFitData.SIZE_OF_SHORT); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeByte((byte)1); return oVariableDataComposer.toByteArray(); } public static byte[] getFindStart() { //05020000000100 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)5); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeByte((byte)OpenFitData.FIND_START); return oVariableDataComposer.toByteArray(); } public static byte[] getFindStop() { //05020000000101 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)5); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeByte((byte)OpenFitData.FIND_STOP); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaPrev() { //06020000000005 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.CONTROL); oVariableDataComposer.writeByte((byte)OpenFitData.REWIND); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaNext() { //06020000000004 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.CONTROL); oVariableDataComposer.writeByte((byte)OpenFitData.FORWARD); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaPlay() { //06020000000001 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.CONTROL); oVariableDataComposer.writeByte((byte)OpenFitData.PLAY); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaPause() { //06020000000002 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.CONTROL); oVariableDataComposer.writeByte((byte)OpenFitData.PAUSE); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaStop() { //06020000000003 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.CONTROL); oVariableDataComposer.writeByte((byte)OpenFitData.STOP); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaVolume() { //060200000001XX OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.VOLUME); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaSetVolume(byte vol) { //060200000001XX OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.VOLUME); oVariableDataComposer.writeByte((byte)vol); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaReqStart() { //060100000003 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(1); oVariableDataComposer.writeByte((byte)OpenFitData.REQUEST_START); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaReqStop() { //060100000004 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(1); oVariableDataComposer.writeByte((byte)OpenFitData.REQUEST_STOP); return oVariableDataComposer.toByteArray(); } //06020000000006 //06020000000007 public static byte[] getFitness() { OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)2); return oVariableDataComposer.toByteArray(); } public static byte[] getFitnessSync() { //02 //94000000 size of msg ? //02 type? //01000000 size? //ff //08000000 //32000000 size? 50 + 2? //000000000000 //00000070 //4c44214f //010000ff //ffffff00 //00000000 //000000ff //ffffffff //ffffffff //00000000 //00000000 //0a000000 //01000000 //c0b7c855 time stamp 1439217600 Monday, August 10, 2015 7:40:00 AM //00000000 //0a000000 //00000000 //00003b40 //00000000 //01000000 //46b5c855 time stamp 1439216966 Monday, August 10, 2015 7:29:26 AM //10270000 //00000000 //45b5c855 time stamp 1439216965 Monday, August 10, 2015 7:29:25 AM //23000000 size? 35 + 2? - 4? //00002a43 //00008242 //35e60200 //f1490200 //d1fb0100 //11980200 //22bf0200 //cd7fcf12 String str = "02940000000201000000ff0800000032000000000000000000000000704c44214f010000ffffffff0000000000000000ffffffffffffffffff00000000000000000a00000001000000c0b7c855000000000a0000000000000000003b40000000000100000046b5c855102700000000000045b5c8552300000000002a430000824235e60200f1490200d1fb01001198020022bf0200cd7fcf12"; return hexStringToByteArray(str); } public static byte[] getFitnessSyncRes() { //02080000000300000001000000 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)2); oVariableDataComposer.writeInt(8); oVariableDataComposer.writeInt(3); oVariableDataComposer.writeInt(1); return oVariableDataComposer.toByteArray(); } public static byte[] getFitnessHeartBeat() { //02050000000001000000 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)2); oVariableDataComposer.writeInt(5); oVariableDataComposer.writeByte((byte)0); oVariableDataComposer.writeInt(1); return oVariableDataComposer.toByteArray(); } public static byte[] getCurrentTimeInfo(boolean is24Hour) { //011E0000000141CB3555F8FFFFFF000000000101010201A01DFC5490D43556100E0000 //01 //1e000000 //01 //41cb3555 //f8ffffff //00000000 //01 //01 //01 //02 //01 //a01dfc54 //90d43556 //100e0000 // build time data int millis = (int)(System.currentTimeMillis() / 1000L); Calendar oCalendar = Calendar.getInstance(); TimeZone oTimeZone = oCalendar.getTimeZone(); int i = oTimeZone.getRawOffset() / 60000; int j = i / 60; int k = i % 60; Date oDate = oCalendar.getTime(); boolean inDaylightTime = oTimeZone.inDaylightTime(oDate); boolean useDaylightTime = oTimeZone.useDaylightTime(); long l = oCalendar.getTimeInMillis(); int m = (int)(OpenFitTimeZoneUtil.prevTransition(oTimeZone, l) / 1000L); int n = (int)(OpenFitTimeZoneUtil.nextTransition(oTimeZone, l) / 1000L); int dst = oTimeZone.getDSTSavings() / 1000; // write time data OpenFitVariableDataComposer oVDC = new OpenFitVariableDataComposer(); oVDC.writeByte((byte)1); oVDC.writeInt(millis); oVDC.writeInt(j); oVDC.writeInt(k); oVDC.writeByte(OpenFitData.TEXT_DATE_FORMAT_TYPE); //oVDC.writeBoolean(OpenFitData.IS_TIME_DISPLAY_24); oVDC.writeBoolean(is24Hour); oVDC.writeBoolean(inDaylightTime); oVDC.writeByte(OpenFitData.NUMBER_DATE_FORMAT_TYPE); oVDC.writeBoolean(useDaylightTime); oVDC.writeInt(m); oVDC.writeInt(n); oVDC.writeInt(dst); int length = oVDC.toByteArray().length; // write time byte array OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeInt(length); oVariableDataComposer.writeBytes(oVDC.toByteArray()); return oVariableDataComposer.toByteArray(); } public static byte[] getOpenFitWelcomeNotification() { //03 //71000000 = size of msg //04 = DATA_TYPE_MESSAGE //0400000000000000 = id //10 = sender name size + 2 //FF //FE //4F00700065006E00460069007400 = OpenFit //16 = sender number size + 2 //FF //FE //3500350035003100320033003400350036003700 = 5551234567 //10 = msg title + 2 //FF //FE //4E004F005400490054004C004500 = NOTITLE //28 = msg data + 2 //00 //FF //FE //570065006C0063006F006D006500200074006F0020004F00700065006E004600690074002100 = Welcome to OpenFit! //00 //5E0E8955 = time stamp List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, "OpenFit")); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, "5551234567")); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, "NOTITLE")); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.SHORT, "Welcome to OpenFit!")); long id = System.currentTimeMillis() / 1000L; byte[] msg = OpenFitNotificationProtocol.createNotificationProtocol(OpenFitData.DATA_TYPE_MESSAGE, id, mDataList, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)3); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenNotification(String sender, String number, String title, String message, long id) { //03 //71000000 = size of msg //04 = DATA_TYPE_MESSAGE //0400000000000000 = id //10 = sender name size + 2 //FF //FE //4F00700065006E00460069007400 = OpenFit //16 = sender number size + 2 //FF //FE //3500350035003100320033003400350036003700 = 5551234567 //10 = msg title + 2 //FF //FE //4E004F005400490054004C004500 = NOTITLE //28 = msg data + 2 //00 //FF //FE //570065006C0063006F006D006500200074006F0020004F00700065006E004600690074002100 = Welcome to OpenFit! //00 //5E0E8955 = time stamp if(sender == null || sender.isEmpty()) { sender = "OpenFit"; } if(number == null || number.isEmpty()) { number = "OpenFit"; } if(title == null || title.isEmpty()) { title = "OpenFit Title"; } if(message == null || message.isEmpty()) { message = "OpenFit Message"; } List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, sender)); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, number)); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, trimTitle(title))); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.SHORT, trimMessage(message))); byte[] msg = OpenFitNotificationProtocol.createNotificationProtocol(OpenFitData.DATA_TYPE_MESSAGE, id, mDataList, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)3); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenEmail(String sender, String number, String title, String message, long id) { if(sender == null || sender.isEmpty()) { sender = "OpenFit"; } if(number == null || number.isEmpty()) { number = "OpenFit"; } if(title == null || title.isEmpty()) { title = "OpenFit Title"; } if(message == null || message.isEmpty()) { message = "OpenFit Email"; } List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, sender)); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, number)); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, trimTitle(title))); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.SHORT, trimMessage(message))); byte[] msg = OpenFitNotificationProtocol.createEmailProtocol(OpenFitData.DATA_TYPE_EMAIL, id, mDataList, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)3); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenIncomingCall(String sender, String number, long id) { //09 //30000000 = size of msg //00 = DATA_TYPE_INCOMING_CALL //fb73770c4f010000 = id //00 = call flag //0a = size + 2 //ff //fe //48006f006d006500 = sender //16 = size + 2 //ff //fe //0000000000000000000000000000000000000000 = phone number //5fc0c555 if(sender == null || sender.isEmpty()) { sender = "OpenFit"; } if(number == null || number.isEmpty()) { number = "OpenFit"; } List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, sender)); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, number)); byte[] msg = OpenFitNotificationProtocol.createIncomingCallProtocol(OpenFitData.DATA_TYPE_INCOMING_CALL, id, mDataList, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)9); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenRejectCall() { //090600000003013FE1CA55 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)9); oVariableDataComposer.writeInt(6); oVariableDataComposer.writeByte((byte)3); oVariableDataComposer.writeByte((byte)1); return oVariableDataComposer.toByteArray(); } public static byte[] getOpenIncomingCallEnd() { //090100000002 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)9); oVariableDataComposer.writeInt(1); oVariableDataComposer.writeByte((byte)2); return oVariableDataComposer.toByteArray(); } public static byte[] getOpenMediaTrack(String track) { //06 //26000000 //02 //24 = size + 2 //ff //fe //44006100660074002000500075006e006b0020002d00200046007200650073006800 = track name byte[] msg = OpenFitNotificationProtocol.createMediaTrackProtocol(OpenFitData.DATA_TYPE_MEDIATRACK, track); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)6); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenAlarm(long id) { //0a //1e000000 = size of mg //01 = msg type //0100000000000000 = msg id //0c = size of string //ff //fe //41006c00610072006d00 = string //c1040000 = little endian odd time stamp //00000000 = snooze = false List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, "Alarm")); Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR); int minute = c.get(Calendar.MINUTE); String timeString = Integer.toString(hour)+Integer.toString(minute); int time = Integer.parseInt(timeString); byte[] msg = OpenFitNotificationProtocol.createAlarmProtocol(OpenFitData.DATA_TYPE_ALARMCLOCK, id, mDataList, time); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)10); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenAlarmClear() { //0a0100000000 clear from phone OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)10); oDatacomposer.writeInt(1); oDatacomposer.writeByte((byte)0); return oDatacomposer.toByteArray(); } public static byte[] getOpenAlarmCleared() { //0A020000000300 clear from gear OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)10); oDatacomposer.writeInt(2); oDatacomposer.writeByte((byte)3); oDatacomposer.writeByte((byte)0); return oDatacomposer.toByteArray(); } public static byte[] getOpenAlarmSnoozed() { //0A020000000301 snooze from gear OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)10); oDatacomposer.writeInt(2); oDatacomposer.writeByte((byte)3); oDatacomposer.writeByte((byte)1); return oDatacomposer.toByteArray(); } public static byte[] getOpenWeather(String weather, String icon, long id) { int i = getOpenWeatherIcon(icon); byte[] msg = OpenFitNotificationProtocol.createWeatherProtocol(OpenFitData.DATA_TYPE_WEATHER, id, weather, i, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)3); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenWeatherClock(String location, String temp, String unit, String icon) { //01 //3d000000 //09 //14 = size + 2? //ff //fe //4e0069006500640065007200720061006400 = city name //06 //40060000 //01 = units 01 C, 00 F //00 //c944e055 = time stamp //06 //98080000 //14050000 //06000000 //00000000 //00 //0600 //00000000 //00000000 List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, location)); float t = Float.parseFloat(temp); int tempInt = Math.round(t); if(tempInt < 10) { tempInt = tempInt * 1000; } else if(tempInt < 100) { tempInt = tempInt * 100; } else if(tempInt < 1000) { tempInt = tempInt * 10; } int tempUnit = 1; if(unit.contains("F")) { tempUnit = 0; } int i = getOpenWeatherClockIcon(icon); byte[] msg = OpenFitNotificationProtocol.createWeatherClockProtocol(9, mDataList, tempInt, tempUnit, i, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)1); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static int getOpenWeatherIcon(String icon) { int i = 0; if(icon == null) { icon = "01"; } if(icon.contains("01")) { i = OpenFitData.WEATHER_TYPE_SUNNY; } else if(icon.contains("02")) { i = OpenFitData.WEATHER_TYPE_MOSTLY_CLEAR; } else if(icon.contains("03")) { i = OpenFitData.WEATHER_TYPE_MOSTLY_CLOUDY; } else if(icon.contains("04")) { i = OpenFitData.WEATHER_TYPE_MOSTLY_CLOUDY; } else if(icon.contains("09")) { i = OpenFitData.WEATHER_TYPE_HEAVY_RAIN; } else if(icon.contains("10")) { i = OpenFitData.WEATHER_TYPE_PARTLY_SUNNY_SHOWERS; } else if(icon.contains("11")) { i = OpenFitData.WEATHER_TYPE_THUNDERSTORMS; } else if(icon.contains("13")) { i = OpenFitData.WEATHER_TYPE_SNOW; } else if(icon.contains("50")) { i = OpenFitData.WEATHER_TYPE_FOG; } return i; } public static int getOpenWeatherClockIcon(String icon) { int i = 0; if(icon == null) { icon = "01"; } if(icon.contains("01")) { i = OpenFitData.WEATHER_CLOCK_SUNNY; } else if(icon.contains("02")) { i = OpenFitData.WEATHER_CLOCK_CLEAR; } else if(icon.contains("03")) { i = OpenFitData.WEATHER_CLOCK_MOSTLY_CLOUDY; } else if(icon.contains("04")) { i = OpenFitData.WEATHER_CLOCK_MOSTLY_CLOUDY; } else if(icon.contains("09")) { i = OpenFitData.WEATHER_CLOCK_SHOWERS; } else if(icon.contains("10")) { i = OpenFitData.WEATHER_CLOCK_PARTLY_SUNNY_SHOWERS; } else if(icon.contains("11")) { i = OpenFitData.WEATHER_CLOCK_THUNDERSTORMS; } else if(icon.contains("13")) { i = OpenFitData.WEATHER_CLOCK_SNOW; } else if(icon.contains("50")) { i = OpenFitData.WEATHER_CLOCK_FOG; } return i; } public static String trimTitle(String s) { s = s.substring(0, Math.min(s.length(), 50)); return s; } public static String trimMessage(String s) { s = s.substring(0, Math.min(s.length(), 250)); return s; } public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for(int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; } public static String hexStringToString(String hex){ StringBuilder sb = new StringBuilder(); StringBuilder temp = new StringBuilder(); for(int i=0; i<hex.length()-1; i+=2 ) { String output = hex.substring(i, (i + 2)); int decimal = Integer.parseInt(output, 16); sb.append((char)decimal); temp.append(decimal); } return sb.toString(); } final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String byteArrayToHexString(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public static int[] byteArrayToIntArray(byte[] bArray) { int[] iarray = new int[bArray.length]; int i = 0; for(byte b : bArray) { iarray[i++] = b & 0xff; } return iarray; } }
src/com/solderbyte/openfit/OpenFitApi.java
package com.solderbyte.openfit; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.TimeZone; import com.solderbyte.openfit.protocol.OpenFitNotificationProtocol; import com.solderbyte.openfit.util.OpenFitData; import com.solderbyte.openfit.util.OpenFitDataType; import com.solderbyte.openfit.util.OpenFitDataTypeAndString; import com.solderbyte.openfit.util.OpenFitTimeZoneUtil; import com.solderbyte.openfit.util.OpenFitVariableDataComposer; public class OpenFitApi { public static byte[] getReady() { //000400000003000000 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)0); oVariableDataComposer.writeInt(OpenFitData.SIZE_OF_INT); oVariableDataComposer.writeInt(3); return oVariableDataComposer.toByteArray(); } public static byte[] getUpdate() { OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte(OpenFitData.PORT_FOTA); oVariableDataComposer.writeInt(OpenFitData.SIZE_OF_INT); oVariableDataComposer.writeBytes("ODIN".getBytes()); //oVariableDataComposer.writeByte((byte)79); // O //oVariableDataComposer.writeByte((byte)68); // D //oVariableDataComposer.writeByte((byte)73); // I //oVariableDataComposer.writeByte((byte)78); // N return oVariableDataComposer.toByteArray(); } public static byte[] getUpdateFollowUp() { //640800000004020501 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte(OpenFitData.OPENFIT_DATA); oVariableDataComposer.writeInt(OpenFitData.SIZE_OF_DOUBLE); oVariableDataComposer.writeByte((byte)4); oVariableDataComposer.writeByte((byte)2); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeByte((byte)4); oVariableDataComposer.writeByte((byte)2); oVariableDataComposer.writeByte((byte)5); oVariableDataComposer.writeByte((byte)1); return oVariableDataComposer.toByteArray(); } public static byte[] getFotaCommand() { //4E020000000101 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte(OpenFitData.PORT_FOTA_COMMAND); oVariableDataComposer.writeInt(OpenFitData.SIZE_OF_SHORT); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeByte((byte)1); return oVariableDataComposer.toByteArray(); } public static byte[] getFindStart() { //05020000000100 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)5); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeByte((byte)OpenFitData.FIND_START); return oVariableDataComposer.toByteArray(); } public static byte[] getFindStop() { //05020000000101 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)5); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeByte((byte)OpenFitData.FIND_STOP); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaPrev() { //06020000000005 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.CONTROL); oVariableDataComposer.writeByte((byte)OpenFitData.REWIND); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaNext() { //06020000000004 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.CONTROL); oVariableDataComposer.writeByte((byte)OpenFitData.FORWARD); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaPlay() { //06020000000001 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.CONTROL); oVariableDataComposer.writeByte((byte)OpenFitData.PLAY); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaPause() { //06020000000002 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.CONTROL); oVariableDataComposer.writeByte((byte)OpenFitData.PAUSE); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaStop() { //06020000000003 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.CONTROL); oVariableDataComposer.writeByte((byte)OpenFitData.STOP); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaVolume() { //060200000001XX OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.VOLUME); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaSetVolume(byte vol) { //060200000001XX OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(2); oVariableDataComposer.writeByte((byte)OpenFitData.VOLUME); oVariableDataComposer.writeByte((byte)vol); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaReqStart() { //060100000003 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(1); oVariableDataComposer.writeByte((byte)OpenFitData.REQUEST_START); return oVariableDataComposer.toByteArray(); } public static byte[] getMediaReqStop() { //060100000004 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)6); oVariableDataComposer.writeInt(1); oVariableDataComposer.writeByte((byte)OpenFitData.REQUEST_STOP); return oVariableDataComposer.toByteArray(); } //06020000000006 //06020000000007 public static byte[] getFitness() { OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)2); return oVariableDataComposer.toByteArray(); } public static byte[] getFitnessSync() { //02 //94000000 size of msg ? //02 type? //01000000 size? //ff //08000000 //32000000 size? 50 + 2? //000000000000 //00000070 //4c44214f //010000ff //ffffff00 //00000000 //000000ff //ffffffff //ffffffff //00000000 //00000000 //0a000000 //01000000 //c0b7c855 time stamp 1439217600 Monday, August 10, 2015 7:40:00 AM //00000000 //0a000000 //00000000 //00003b40 //00000000 //01000000 //46b5c855 time stamp 1439216966 Monday, August 10, 2015 7:29:26 AM //10270000 //00000000 //45b5c855 time stamp 1439216965 Monday, August 10, 2015 7:29:25 AM //23000000 size? 35 + 2? - 4? //00002a43 //00008242 //35e60200 //f1490200 //d1fb0100 //11980200 //22bf0200 //cd7fcf12 String str = "02940000000201000000ff0800000032000000000000000000000000704c44214f010000ffffffff0000000000000000ffffffffffffffffff00000000000000000a00000001000000c0b7c855000000000a0000000000000000003b40000000000100000046b5c855102700000000000045b5c8552300000000002a430000824235e60200f1490200d1fb01001198020022bf0200cd7fcf12"; return hexStringToByteArray(str); } public static byte[] getFitnessSyncRes() { //02080000000300000001000000 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)2); oVariableDataComposer.writeInt(8); oVariableDataComposer.writeInt(3); oVariableDataComposer.writeInt(1); return oVariableDataComposer.toByteArray(); } public static byte[] getFitnessHeartBeat() { //02050000000001000000 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)2); oVariableDataComposer.writeInt(5); oVariableDataComposer.writeByte((byte)0); oVariableDataComposer.writeInt(1); return oVariableDataComposer.toByteArray(); } public static byte[] getCurrentTimeInfo(boolean is24Hour) { //011E0000000141CB3555F8FFFFFF000000000101010201A01DFC5490D43556100E0000 //01 //1e000000 //01 //41cb3555 //f8ffffff //00000000 //01 //01 //01 //02 //01 //a01dfc54 //90d43556 //100e0000 // build time data int millis = (int)(System.currentTimeMillis() / 1000L); Calendar oCalendar = Calendar.getInstance(); TimeZone oTimeZone = oCalendar.getTimeZone(); int i = oTimeZone.getRawOffset() / 60000; int j = i / 60; int k = i % 60; Date oDate = oCalendar.getTime(); boolean inDaylightTime = oTimeZone.inDaylightTime(oDate); boolean useDaylightTime = oTimeZone.useDaylightTime(); long l = oCalendar.getTimeInMillis(); int m = (int)(OpenFitTimeZoneUtil.prevTransition(oTimeZone, l) / 1000L); int n = (int)(OpenFitTimeZoneUtil.nextTransition(oTimeZone, l) / 1000L); int dst = oTimeZone.getDSTSavings() / 1000; // write time data OpenFitVariableDataComposer oVDC = new OpenFitVariableDataComposer(); oVDC.writeByte((byte)1); oVDC.writeInt(millis); oVDC.writeInt(j); oVDC.writeInt(k); oVDC.writeByte(OpenFitData.TEXT_DATE_FORMAT_TYPE); //oVDC.writeBoolean(OpenFitData.IS_TIME_DISPLAY_24); oVDC.writeBoolean(is24Hour); oVDC.writeBoolean(inDaylightTime); oVDC.writeByte(OpenFitData.NUMBER_DATE_FORMAT_TYPE); oVDC.writeBoolean(useDaylightTime); oVDC.writeInt(m); oVDC.writeInt(n); oVDC.writeInt(dst); int length = oVDC.toByteArray().length; // write time byte array OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)1); oVariableDataComposer.writeInt(length); oVariableDataComposer.writeBytes(oVDC.toByteArray()); return oVariableDataComposer.toByteArray(); } public static byte[] getOpenFitWelcomeNotification() { //03 //71000000 = size of msg //04 = DATA_TYPE_MESSAGE //0400000000000000 = id //10 = sender name size + 2 //FF //FE //4F00700065006E00460069007400 = OpenFit //16 = sender number size + 2 //FF //FE //3500350035003100320033003400350036003700 = 5551234567 //10 = msg title + 2 //FF //FE //4E004F005400490054004C004500 = NOTITLE //28 = msg data + 2 //00 //FF //FE //570065006C0063006F006D006500200074006F0020004F00700065006E004600690074002100 = Welcome to OpenFit! //00 //5E0E8955 = time stamp List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, "OpenFit")); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, "5551234567")); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, "NOTITLE")); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.SHORT, "Welcome to OpenFit!")); long id = System.currentTimeMillis() / 1000L; byte[] msg = OpenFitNotificationProtocol.createNotificationProtocol(OpenFitData.DATA_TYPE_MESSAGE, id, mDataList, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)3); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenNotification(String sender, String number, String title, String message, long id) { //03 //71000000 = size of msg //04 = DATA_TYPE_MESSAGE //0400000000000000 = id //10 = sender name size + 2 //FF //FE //4F00700065006E00460069007400 = OpenFit //16 = sender number size + 2 //FF //FE //3500350035003100320033003400350036003700 = 5551234567 //10 = msg title + 2 //FF //FE //4E004F005400490054004C004500 = NOTITLE //28 = msg data + 2 //00 //FF //FE //570065006C0063006F006D006500200074006F0020004F00700065006E004600690074002100 = Welcome to OpenFit! //00 //5E0E8955 = time stamp if(sender == null || sender.isEmpty()) { sender = "OpenFit"; } if(number == null || number.isEmpty()) { number = "OpenFit"; } if(title == null || title.isEmpty()) { title = "OpenFit Title"; } if(message == null || message.isEmpty()) { message = "OpenFit Message"; } List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, sender)); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, number)); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, trimTitle(title))); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.SHORT, trimMessage(message))); byte[] msg = OpenFitNotificationProtocol.createNotificationProtocol(OpenFitData.DATA_TYPE_MESSAGE, id, mDataList, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)3); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenEmail(String sender, String number, String title, String message, long id) { if(sender == null || sender.isEmpty()) { sender = "OpenFit"; } if(number == null || number.isEmpty()) { number = "OpenFit"; } if(title == null || title.isEmpty()) { title = "OpenFit Title"; } if(message == null || message.isEmpty()) { message = "OpenFit Email"; } List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, sender)); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, number)); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, trimTitle(title))); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.SHORT, trimMessage(message))); byte[] msg = OpenFitNotificationProtocol.createEmailProtocol(OpenFitData.DATA_TYPE_EMAIL, id, mDataList, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)3); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenIncomingCall(String sender, String number, long id) { //09 //30000000 = size of msg //00 = DATA_TYPE_INCOMING_CALL //fb73770c4f010000 = id //00 = call flag //0a = size + 2 //ff //fe //48006f006d006500 = sender //16 = size + 2 //ff //fe //0000000000000000000000000000000000000000 = phone number //5fc0c555 if(sender == null || sender.isEmpty()) { sender = "OpenFit"; } if(number == null || number.isEmpty()) { number = "OpenFit"; } List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, sender)); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, number)); byte[] msg = OpenFitNotificationProtocol.createIncomingCallProtocol(OpenFitData.DATA_TYPE_INCOMING_CALL, id, mDataList, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)9); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenRejectCall() { //090600000003013FE1CA55 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)9); oVariableDataComposer.writeInt(6); oVariableDataComposer.writeByte((byte)3); oVariableDataComposer.writeByte((byte)1); return oVariableDataComposer.toByteArray(); } public static byte[] getOpenIncomingCallEnd() { //090100000002 OpenFitVariableDataComposer oVariableDataComposer = new OpenFitVariableDataComposer(); oVariableDataComposer.writeByte((byte)9); oVariableDataComposer.writeInt(1); oVariableDataComposer.writeByte((byte)2); return oVariableDataComposer.toByteArray(); } public static byte[] getOpenMediaTrack(String track) { //06 //26000000 //02 //24 = size + 2 //ff //fe //44006100660074002000500075006e006b0020002d00200046007200650073006800 = track name byte[] msg = OpenFitNotificationProtocol.createMediaTrackProtocol(OpenFitData.DATA_TYPE_MEDIATRACK, track); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)6); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenAlarm(long id) { //0a //1e000000 = size of mg //01 = msg type //0100000000000000 = msg id //0c = size of string //ff //fe //41006c00610072006d00 = string //c1040000 = little endian odd time stamp //00000000 = snooze = false List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, "Alarm")); Calendar c = Calendar.getInstance(); int hour = c.get(Calendar.HOUR); int minute = c.get(Calendar.MINUTE); String timeString = Integer.toString(hour)+Integer.toString(minute); int time = Integer.parseInt(timeString); byte[] msg = OpenFitNotificationProtocol.createAlarmProtocol(OpenFitData.DATA_TYPE_ALARMCLOCK, id, mDataList, time); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)10); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenAlarmClear() { //0a0100000000 clear from phone OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)10); oDatacomposer.writeInt(1); oDatacomposer.writeByte((byte)0); return oDatacomposer.toByteArray(); } public static byte[] getOpenAlarmCleared() { //0A020000000300 clear from gear OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)10); oDatacomposer.writeInt(2); oDatacomposer.writeByte((byte)3); oDatacomposer.writeByte((byte)0); return oDatacomposer.toByteArray(); } public static byte[] getOpenAlarmSnoozed() { //0A020000000301 snooze from gear OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)10); oDatacomposer.writeInt(2); oDatacomposer.writeByte((byte)3); oDatacomposer.writeByte((byte)1); return oDatacomposer.toByteArray(); } public static byte[] getOpenWeather(String weather, String icon, long id) { int i = getOpenWeatherIcon(icon); byte[] msg = OpenFitNotificationProtocol.createWeatherProtocol(OpenFitData.DATA_TYPE_WEATHER, id, weather, i, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)3); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static byte[] getOpenWeatherClock(String location, String temp, String unit, String icon) { //01 //3d000000 //09 //14 = size + 2? //ff //fe //4e0069006500640065007200720061006400 = city name //06 //40060000 //01 = units 01 C, 00 F //00 //c944e055 = time stamp //06 //98080000 //14050000 //06000000 //00000000 //00 //0600 //00000000 //00000000 List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, location)); int tempInt = Integer.parseInt(temp); if(tempInt < 10) { tempInt = tempInt * 1000; } else if(tempInt < 100) { tempInt = tempInt * 100; } else if(tempInt < 1000) { tempInt = tempInt * 10; } int tempUnit = 1; if(unit.contains("F")) { tempUnit = 0; } int i = getOpenWeatherClockIcon(icon); byte[] msg = OpenFitNotificationProtocol.createWeatherClockProtocol(9, mDataList, tempInt, tempUnit, i, System.currentTimeMillis()); OpenFitVariableDataComposer oDatacomposer = new OpenFitVariableDataComposer(); oDatacomposer.writeByte((byte)1); oDatacomposer.writeInt(msg.length); oDatacomposer.writeBytes(msg); return oDatacomposer.toByteArray(); } public static int getOpenWeatherIcon(String icon) { int i = 0; if(icon == null) { icon = "01"; } if(icon.contains("01")) { i = OpenFitData.WEATHER_TYPE_SUNNY; } else if(icon.contains("02")) { i = OpenFitData.WEATHER_TYPE_MOSTLY_CLEAR; } else if(icon.contains("03")) { i = OpenFitData.WEATHER_TYPE_MOSTLY_CLOUDY; } else if(icon.contains("04")) { i = OpenFitData.WEATHER_TYPE_MOSTLY_CLOUDY; } else if(icon.contains("09")) { i = OpenFitData.WEATHER_TYPE_HEAVY_RAIN; } else if(icon.contains("10")) { i = OpenFitData.WEATHER_TYPE_PARTLY_SUNNY_SHOWERS; } else if(icon.contains("11")) { i = OpenFitData.WEATHER_TYPE_THUNDERSTORMS; } else if(icon.contains("13")) { i = OpenFitData.WEATHER_TYPE_SNOW; } else if(icon.contains("50")) { i = OpenFitData.WEATHER_TYPE_FOG; } return i; } public static int getOpenWeatherClockIcon(String icon) { int i = 0; if(icon == null) { icon = "01"; } if(icon.contains("01")) { i = OpenFitData.WEATHER_CLOCK_SUNNY; } else if(icon.contains("02")) { i = OpenFitData.WEATHER_CLOCK_CLEAR; } else if(icon.contains("03")) { i = OpenFitData.WEATHER_CLOCK_MOSTLY_CLOUDY; } else if(icon.contains("04")) { i = OpenFitData.WEATHER_CLOCK_MOSTLY_CLOUDY; } else if(icon.contains("09")) { i = OpenFitData.WEATHER_CLOCK_SHOWERS; } else if(icon.contains("10")) { i = OpenFitData.WEATHER_CLOCK_PARTLY_SUNNY_SHOWERS; } else if(icon.contains("11")) { i = OpenFitData.WEATHER_CLOCK_THUNDERSTORMS; } else if(icon.contains("13")) { i = OpenFitData.WEATHER_CLOCK_SNOW; } else if(icon.contains("50")) { i = OpenFitData.WEATHER_CLOCK_FOG; } return i; } public static String trimTitle(String s) { s = s.substring(0, Math.min(s.length(), 50)); return s; } public static String trimMessage(String s) { s = s.substring(0, Math.min(s.length(), 250)); return s; } public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for(int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; } public static String hexStringToString(String hex){ StringBuilder sb = new StringBuilder(); StringBuilder temp = new StringBuilder(); for(int i=0; i<hex.length()-1; i+=2 ) { String output = hex.substring(i, (i + 2)); int decimal = Integer.parseInt(output, 16); sb.append((char)decimal); temp.append(decimal); } return sb.toString(); } final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); public static String byteArrayToHexString(byte[] bytes) { char[] hexChars = new char[bytes.length * 2]; for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); } public static int[] byteArrayToIntArray(byte[] bArray) { int[] iarray = new int[bArray.length]; int i = 0; for(byte b : bArray) { iarray[i++] = b & 0xff; } return iarray; } }
Fix WeatherClock
src/com/solderbyte/openfit/OpenFitApi.java
Fix WeatherClock
<ide><path>rc/com/solderbyte/openfit/OpenFitApi.java <ide> List<OpenFitDataTypeAndString> mDataList = new ArrayList<OpenFitDataTypeAndString>(); <ide> mDataList.add(new OpenFitDataTypeAndString(OpenFitDataType.BYTE, location)); <ide> <del> int tempInt = Integer.parseInt(temp); <add> float t = Float.parseFloat(temp); <add> int tempInt = Math.round(t); <ide> if(tempInt < 10) { <ide> tempInt = tempInt * 1000; <ide> }
Java
bsd-3-clause
bad28c6fe02ca6d1272d3e6a0c88b6613bca6a09
0
HVA-FRC-3824/betaBot2016,HVA-FRC-3824/betaBot2016
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc3824.BetaBot.commands; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc3824.BetaBot.Robot; /** * */ public class ShootBoulderInGoal extends Command { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS private double m_ShooterAngle; private double m_ShooterWheelSpeed; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS private Timer m_Timer; private boolean isShooterPositionOut; // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR public ShootBoulderInGoal(double ShooterAngle, double ShooterWheelSpeed) { // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING m_ShooterAngle = ShooterAngle; m_ShooterWheelSpeed = ShooterWheelSpeed; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.shooter); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES m_Timer = new Timer(); } // Called just before this Command runs the first time protected void initialize() { Robot.shooter.setShooterElevationEnabled(true); Robot.shooter.setShooterElevationSetpoint(m_ShooterAngle); Robot.shooter.ShooterWheelControl(m_ShooterWheelSpeed, 0); isShooterPositionOut = false; m_Timer.reset(); m_Timer.start(); } // Called repeatedly when this Command is scheduled to run protected void execute() { if (!isShooterPositionOut && (m_Timer.get() >= 0.5)) { Robot.shooter.ShooterShootBallControl(true); isShooterPositionOut = true; } } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return isShooterPositionOut && (m_Timer.get() >= 0.5 + 0.2); } // Called once after isFinished returns true protected void end() { Robot.shooter.ShooterShootBallControl(false); m_Timer.stop(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { end(); } }
src/org/usfirst/frc3824/BetaBot/commands/ShootBoulderInGoal.java
// RobotBuilder Version: 2.0 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // Java from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. package org.usfirst.frc3824.BetaBot.commands; import edu.wpi.first.wpilibj.command.Command; import org.usfirst.frc3824.BetaBot.Robot; /** * */ public class ShootBoulderInGoal extends Command { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS private double m_ShooterAngle; private double m_ShooterWheelSpeed; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR public ShootBoulderInGoal(double ShooterAngle, double ShooterWheelSpeed) { // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING m_ShooterAngle = ShooterAngle; m_ShooterWheelSpeed = ShooterWheelSpeed; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES requires(Robot.shooter); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
Created Shoot boulder in Goal Command
src/org/usfirst/frc3824/BetaBot/commands/ShootBoulderInGoal.java
Created Shoot boulder in Goal Command
<ide><path>rc/org/usfirst/frc3824/BetaBot/commands/ShootBoulderInGoal.java <ide> <ide> package org.usfirst.frc3824.BetaBot.commands; <ide> <add>import edu.wpi.first.wpilibj.Timer; <ide> import edu.wpi.first.wpilibj.command.Command; <ide> import org.usfirst.frc3824.BetaBot.Robot; <ide> <ide> <ide> // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS <ide> <add> private Timer m_Timer; <add> private boolean isShooterPositionOut; <add> <ide> // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR <ide> public ShootBoulderInGoal(double ShooterAngle, double ShooterWheelSpeed) <ide> { <ide> requires(Robot.shooter); <ide> <ide> // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES <add> <add> m_Timer = new Timer(); <ide> } <del> <add> <ide> // Called just before this Command runs the first time <ide> protected void initialize() <ide> { <del> <add> Robot.shooter.setShooterElevationEnabled(true); <add> Robot.shooter.setShooterElevationSetpoint(m_ShooterAngle); <add> Robot.shooter.ShooterWheelControl(m_ShooterWheelSpeed, 0); <add> <add> isShooterPositionOut = false; <add> <add> m_Timer.reset(); <add> m_Timer.start(); <ide> } <ide> <ide> // Called repeatedly when this Command is scheduled to run <ide> protected void execute() <ide> { <del> <add> if (!isShooterPositionOut && (m_Timer.get() >= 0.5)) <add> { <add> Robot.shooter.ShooterShootBallControl(true); <add> isShooterPositionOut = true; <add> } <ide> } <ide> <ide> // Make this return true when this Command no longer needs to run execute() <ide> protected boolean isFinished() <del> { <del> return false; <add> { <add> return isShooterPositionOut && (m_Timer.get() >= 0.5 + 0.2); <ide> } <ide> <ide> // Called once after isFinished returns true <ide> protected void end() <ide> { <del> <add> Robot.shooter.ShooterShootBallControl(false); <add> m_Timer.stop(); <ide> } <ide> <ide> // Called when another command which requires one or more of the same <ide> // subsystems is scheduled to run <ide> protected void interrupted() <ide> { <del> <add> end(); <ide> } <ide> }
Java
apache-2.0
6ca1df08e13a6461fb663cde7f2c534ec3aea70d
0
adligo/models_core.adligo.org
package org.adligo.models.core.client; import org.adligo.i.util.client.AppenderFactory; import org.adligo.i.util.client.I_Appender; import org.adligo.models.core.client.ids.I_StorageIdentifier; import org.adligo.models.core.client.ids.StorageIdentifierValidator; import org.adligo.models.core.client.ids.VersionValidator; public class ChangeableMutant implements I_ChangeableMutant { /** * */ private static final long serialVersionUID = 1L; private I_StorageIdentifier id; private Integer version; private I_StorageInfo storageInfo; public ChangeableMutant() {} public ChangeableMutant(I_Changeable p) throws InvalidParameterException { setId(p.getId()); setVersion(p.getVersion()); setStorageInfo(p.getStorageInfo()); } public I_StorageIdentifier getId() { return id; } public void setId(I_StorageIdentifier p) throws InvalidParameterException { StorageIdentifierValidator.validateId(p, this.getClass(), I_IdentifiableMutant.SET_ID); id = p; } public Integer getVersion() { return version; } public void setVersion(Integer p) throws InvalidParameterException { this.version = VersionValidator.validate(p); } /* (non-Javadoc) * @see com.adligo.models.accounting.client.assets.I_Purchase#getStorageInfo() */ public I_StorageInfo getStorageInfo() { return storageInfo; } /* (non-Javadoc) * @see com.adligo.models.accounting.client.assets.I_PurchaseMutant#setStorageInfo(org.adligo.models.core.client.I_StorageInfo) */ public void setStorageInfo(I_StorageInfo p) throws InvalidParameterException { if (p == null) { throw new InvalidParameterException("ChangeableMutant does NOT allow null storage info.", SET_STORAGE_INFO); } storageInfo = p; } public String toString() { I_Appender app = AppenderFactory.create(); toString(ChangeableMutant.class, app); return app.toString(); } /** * client calls must append their own square brace at the end ] * to allow for extension. * * @param app */ public void toString(Class<?> ic, I_Appender app) { app.append("" + ic.getSimpleName() + " [id=" + id + ", version=" + version + ", storageInfo=" + storageInfo); } public void isValid() throws ValidationException { StorableValidator.validate(this, I_Validateable.IS_VALID); try { ChangeableMutant other = new ChangeableMutant(this); } catch (InvalidParameterException e) { throw new ValidationException(e.getMessage(), I_Validateable.IS_VALID, e); } } public boolean isStored() throws ValidationException { return StorableValidator.validate(this, I_Storable.IS_STORED); } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((storageInfo == null) ? 0 : storageInfo.hashCode()); result = prime * result + ((version == null) ? 0 : version.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ChangeableMutant other = (ChangeableMutant) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (storageInfo == null) { if (other.storageInfo != null) return false; } else if (!storageInfo.equals(other.storageInfo)) return false; if (version == null) { if (other.version != null) return false; } else if (!version.equals(other.version)) return false; return true; } }
src/org/adligo/models/core/client/ChangeableMutant.java
package org.adligo.models.core.client; import org.adligo.models.core.client.ids.I_StorageIdentifier; import org.adligo.models.core.client.ids.StorageIdentifierValidator; import org.adligo.models.core.client.ids.VersionValidator; public class ChangeableMutant implements I_ChangeableMutant { /** * */ private static final long serialVersionUID = 1L; private I_StorageIdentifier id; private Integer version; private I_StorageInfo storageInfo; public ChangeableMutant() {} public ChangeableMutant(I_Changeable p) throws InvalidParameterException { setId(p.getId()); setVersion(p.getVersion()); setStorageInfo(p.getStorageInfo()); } public I_StorageIdentifier getId() { return id; } public void setId(I_StorageIdentifier p) throws InvalidParameterException { StorageIdentifierValidator.validateId(p, this.getClass(), I_IdentifiableMutant.SET_ID); id = p; } public Integer getVersion() { return version; } public void setVersion(Integer p) throws InvalidParameterException { this.version = VersionValidator.validate(p); } /* (non-Javadoc) * @see com.adligo.models.accounting.client.assets.I_Purchase#getStorageInfo() */ public I_StorageInfo getStorageInfo() { return storageInfo; } /* (non-Javadoc) * @see com.adligo.models.accounting.client.assets.I_PurchaseMutant#setStorageInfo(org.adligo.models.core.client.I_StorageInfo) */ public void setStorageInfo(I_StorageInfo p) throws InvalidParameterException { if (p == null) { throw new InvalidParameterException("ChangeableMutant does NOT allow null storage info.", SET_STORAGE_INFO); } storageInfo = p; } @Override public boolean isStored() throws ValidationException { // TODO Auto-generated method stub return false; } }
missed some methods
src/org/adligo/models/core/client/ChangeableMutant.java
missed some methods
<ide><path>rc/org/adligo/models/core/client/ChangeableMutant.java <ide> package org.adligo.models.core.client; <ide> <add>import org.adligo.i.util.client.AppenderFactory; <add>import org.adligo.i.util.client.I_Appender; <ide> import org.adligo.models.core.client.ids.I_StorageIdentifier; <ide> import org.adligo.models.core.client.ids.StorageIdentifierValidator; <ide> import org.adligo.models.core.client.ids.VersionValidator; <ide> storageInfo = p; <ide> } <ide> <del> @Override <add> <add> public String toString() { <add> I_Appender app = AppenderFactory.create(); <add> toString(ChangeableMutant.class, app); <add> return app.toString(); <add> } <add> /** <add> * client calls must append their own square brace at the end ] <add> * to allow for extension. <add> * <add> * @param app <add> */ <add> public void toString(Class<?> ic, I_Appender app) { <add> app.append("" + ic.getSimpleName() + " [id=" + id + ", version=" + version <add> + ", storageInfo=" + storageInfo); <add> } <add> <add> public void isValid() throws ValidationException { <add> StorableValidator.validate(this, I_Validateable.IS_VALID); <add> try { <add> ChangeableMutant other = new ChangeableMutant(this); <add> } catch (InvalidParameterException e) { <add> throw new ValidationException(e.getMessage(), I_Validateable.IS_VALID, e); <add> } <add> } <add> <ide> public boolean isStored() throws ValidationException { <del> // TODO Auto-generated method stub <del> return false; <add> return StorableValidator.validate(this, I_Storable.IS_STORED); <add> } <add> <add> public int hashCode() { <add> final int prime = 31; <add> int result = 1; <add> result = prime * result + ((id == null) ? 0 : id.hashCode()); <add> result = prime * result <add> + ((storageInfo == null) ? 0 : storageInfo.hashCode()); <add> result = prime * result + ((version == null) ? 0 : version.hashCode()); <add> return result; <add> } <add> <add> public boolean equals(Object obj) { <add> if (this == obj) <add> return true; <add> if (obj == null) <add> return false; <add> if (getClass() != obj.getClass()) <add> return false; <add> ChangeableMutant other = (ChangeableMutant) obj; <add> if (id == null) { <add> if (other.id != null) <add> return false; <add> } else if (!id.equals(other.id)) <add> return false; <add> if (storageInfo == null) { <add> if (other.storageInfo != null) <add> return false; <add> } else if (!storageInfo.equals(other.storageInfo)) <add> return false; <add> if (version == null) { <add> if (other.version != null) <add> return false; <add> } else if (!version.equals(other.version)) <add> return false; <add> return true; <ide> } <ide> }
Java
agpl-3.0
ed4094909c46c39f3f6d31b3d3e73a8b476cdddd
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
5fe35bda-2e62-11e5-9284-b827eb9e62be
hello.java
5fddf910-2e62-11e5-9284-b827eb9e62be
5fe35bda-2e62-11e5-9284-b827eb9e62be
hello.java
5fe35bda-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>5fddf910-2e62-11e5-9284-b827eb9e62be <add>5fe35bda-2e62-11e5-9284-b827eb9e62be
Java
apache-2.0
3e0c9ea3c8e178d9d857c558b3dd0b30968d9e42
0
apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc,apache/incubator-shardingsphere,apache/incubator-shardingsphere,leeyazhou/sharding-jdbc
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.shardingproxy.frontend.postgresql; import com.google.common.base.Strings; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import lombok.RequiredArgsConstructor; import org.apache.shardingsphere.shardingproxy.frontend.common.FrontendHandler; import org.apache.shardingsphere.shardingproxy.frontend.common.executor.CommandExecutorSelector; import org.apache.shardingsphere.shardingproxy.frontend.mysql.CommandExecutor; import org.apache.shardingsphere.shardingproxy.runtime.ChannelRegistry; import org.apache.shardingsphere.shardingproxy.runtime.GlobalRegistry; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.PostgreSQLPacketPayload; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.generic.ReadyForQuery; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.handshake.AuthenticationOK; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.handshake.PostgreSQLConnectionIdGenerator; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.handshake.SSLNegative; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.handshake.StartupMessage; /** * PostgreSQL frontend handler. * * @author zhangyonglun */ @RequiredArgsConstructor public final class PostgreSQLFrontendHandler extends FrontendHandler { private static final int SSL_REQUEST_PAYLOAD_LENGTH = 8; private static final int SSL_REQUEST_CODE = 80877103; private static final String DATABASE_NAME_KEYWORD = "database"; @Override protected void handshake(final ChannelHandlerContext context) { int connectionId = PostgreSQLConnectionIdGenerator.getInstance().nextId(); ChannelRegistry.getInstance().putConnectionId(context.channel().id().asShortText(), connectionId); getBackendConnection().setConnectionId(connectionId); } @Override protected void auth(final ChannelHandlerContext context, final ByteBuf message) { if (SSL_REQUEST_PAYLOAD_LENGTH == message.markReaderIndex().readInt() && SSL_REQUEST_CODE == message.readInt()) { setAuthorized(false); context.writeAndFlush(new SSLNegative()); return; } message.resetReaderIndex(); try (PostgreSQLPacketPayload payload = new PostgreSQLPacketPayload(message)) { StartupMessage startupMessage = new StartupMessage(payload); String databaseName = startupMessage.getParametersMap().get(DATABASE_NAME_KEYWORD); if (!Strings.isNullOrEmpty(databaseName) && !GlobalRegistry.getInstance().schemaExists(databaseName)) { // TODO send an error message return; } getBackendConnection().setCurrentSchema(databaseName); // TODO send a md5 authentication request message context.write(new AuthenticationOK(true)); context.writeAndFlush(new ReadyForQuery()); } } @Override protected void executeCommand(final ChannelHandlerContext context, final ByteBuf message) { CommandExecutorSelector.getExecutor(getBackendConnection().getTransactionType(), context.channel().id()).execute(new CommandExecutor(context, message, this)); } @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { if (context.channel().isWritable()) { synchronized (this) { this.notifyAll(); } } } }
sharding-proxy-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/postgresql/PostgreSQLFrontendHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.shardingproxy.frontend.postgresql; import com.google.common.base.Strings; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import lombok.RequiredArgsConstructor; import org.apache.shardingsphere.shardingproxy.frontend.common.FrontendHandler; import org.apache.shardingsphere.shardingproxy.frontend.common.executor.CommandExecutorSelector; import org.apache.shardingsphere.shardingproxy.frontend.mysql.CommandExecutor; import org.apache.shardingsphere.shardingproxy.runtime.ChannelRegistry; import org.apache.shardingsphere.shardingproxy.runtime.GlobalRegistry; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.PostgreSQLPacketPayload; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.generic.ReadyForQuery; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.handshake.AuthenticationOK; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.handshake.PostgreSQLConnectionIdGenerator; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.handshake.SSLNegative; import org.apache.shardingsphere.shardingproxy.transport.postgresql.packet.handshake.StartupMessage; /** * PostgreSQL frontend handler. * * @author zhangyonglun */ @RequiredArgsConstructor public final class PostgreSQLFrontendHandler extends FrontendHandler { @Override protected void handshake(final ChannelHandlerContext context) { int connectionId = PostgreSQLConnectionIdGenerator.getInstance().nextId(); ChannelRegistry.getInstance().putConnectionId(context.channel().id().asShortText(), connectionId); getBackendConnection().setConnectionId(connectionId); } @Override protected void auth(final ChannelHandlerContext context, final ByteBuf message) { if (8 == message.markReaderIndex().readInt() && 80877103 == message.readInt()) { setAuthorized(false); context.writeAndFlush(new SSLNegative()); return; } message.resetReaderIndex(); try (PostgreSQLPacketPayload payload = new PostgreSQLPacketPayload(message)) { StartupMessage startupMessage = new StartupMessage(payload); String databaseName = startupMessage.getParametersMap().get("database"); if (!Strings.isNullOrEmpty(databaseName) && !GlobalRegistry.getInstance().schemaExists(databaseName)) { // TODO send an error message return; } getBackendConnection().setCurrentSchema(databaseName); // TODO send a md5 authentication request message context.write(new AuthenticationOK(true)); context.writeAndFlush(new ReadyForQuery()); } } @Override protected void executeCommand(final ChannelHandlerContext context, final ByteBuf message) { CommandExecutorSelector.getExecutor(getBackendConnection().getTransactionType(), context.channel().id()).execute(new CommandExecutor(context, message, this)); } @Override public void channelWritabilityChanged(final ChannelHandlerContext context) { if (context.channel().isWritable()) { synchronized (this) { this.notifyAll(); } } } }
#1517, refine constant
sharding-proxy-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/postgresql/PostgreSQLFrontendHandler.java
#1517, refine constant
<ide><path>harding-proxy-postgresql/src/main/java/org/apache/shardingsphere/shardingproxy/frontend/postgresql/PostgreSQLFrontendHandler.java <ide> @RequiredArgsConstructor <ide> public final class PostgreSQLFrontendHandler extends FrontendHandler { <ide> <add> private static final int SSL_REQUEST_PAYLOAD_LENGTH = 8; <add> <add> private static final int SSL_REQUEST_CODE = 80877103; <add> <add> private static final String DATABASE_NAME_KEYWORD = "database"; <add> <ide> @Override <ide> protected void handshake(final ChannelHandlerContext context) { <ide> int connectionId = PostgreSQLConnectionIdGenerator.getInstance().nextId(); <ide> <ide> @Override <ide> protected void auth(final ChannelHandlerContext context, final ByteBuf message) { <del> if (8 == message.markReaderIndex().readInt() && 80877103 == message.readInt()) { <add> if (SSL_REQUEST_PAYLOAD_LENGTH == message.markReaderIndex().readInt() && SSL_REQUEST_CODE == message.readInt()) { <ide> setAuthorized(false); <ide> context.writeAndFlush(new SSLNegative()); <ide> return; <ide> message.resetReaderIndex(); <ide> try (PostgreSQLPacketPayload payload = new PostgreSQLPacketPayload(message)) { <ide> StartupMessage startupMessage = new StartupMessage(payload); <del> String databaseName = startupMessage.getParametersMap().get("database"); <add> String databaseName = startupMessage.getParametersMap().get(DATABASE_NAME_KEYWORD); <ide> if (!Strings.isNullOrEmpty(databaseName) && !GlobalRegistry.getInstance().schemaExists(databaseName)) { <ide> // TODO send an error message <ide> return;
Java
mit
0d2165ea372579e069287fbbd0ff11d41d5125c6
0
gini/gini-sdk-android,gini/gini-sdk-android,gini/gini-sdk-android
package net.gini.android.authorization; import android.net.Uri; import com.android.volley.RequestQueue; import com.android.volley.toolbox.JsonObjectRequest; import net.gini.android.RequestTaskCompletionSource; import net.gini.android.authorization.requests.BearerJsonObjectRequest; import net.gini.android.authorization.requests.TokenRequest; import net.gini.android.requests.BearerLocationRequest; import net.gini.android.requests.RetryPolicyFactory; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import bolts.Continuation; import bolts.Task; import static com.android.volley.Request.Method.GET; import static com.android.volley.Request.Method.POST; import static com.android.volley.Request.Method.PUT; /** * The UserCenterAPIManager is responsible for communication with the Gini User Center API. This includes handling HTTP * related error handling. */ public class UserCenterAPICommunicator { final private RequestQueue mRequestQueue; final private String mBaseUrl; final private String mClientId; final private String mClientSecret; final private RetryPolicyFactory mRetryPolicyFactory; public UserCenterAPICommunicator(final RequestQueue requestQueue, final String baseUrl, final String clientId, final String clientSecret, final RetryPolicyFactory retryPolicyFactory) { mRequestQueue = requestQueue; mBaseUrl = baseUrl; mClientId = clientId; mClientSecret = clientSecret; this.mRetryPolicyFactory = retryPolicyFactory; } /** * Logs in this client to the Gini User Center API. Uses the instance's client credentials to identify the client. * * Please note that this is used to login the client (in other words: the app) and not a Gini user. Please do not * mix the different sessions. * * @return A task which will resolve to a JSONObject representing the API's response, which is a valid access token * for the Gini User Center API. */ public Task<JSONObject> loginClient() { // Build and execute the request. final RequestTaskCompletionSource<JSONObject> completionSource = RequestTaskCompletionSource.newCompletionSource(); final String url = mBaseUrl + "oauth/token?grant_type=client_credentials"; TokenRequest loginRequest = new TokenRequest(mClientId, mClientSecret, url, null, completionSource, completionSource, mRetryPolicyFactory.newRetryPolicy()); mRequestQueue.add(loginRequest); return completionSource.getTask(); } /** * Logs in a Gini user. * * @param userCredentials The user's credentials. * @return A task which will resolve to a JSONObject representing the API's response, which is a valid access token * for the Gini API. */ public Task<JSONObject> loginUser(UserCredentials userCredentials) { // Build and execute the request. final RequestTaskCompletionSource<JSONObject> completionSource = RequestTaskCompletionSource.newCompletionSource(); final String url = mBaseUrl + "oauth/token?grant_type=password"; final HashMap<String, String> data = new HashMap<String, String>(); data.put("username", userCredentials.getUsername()); data.put("password", userCredentials.getPassword()); TokenRequest loginRequest = new TokenRequest(mClientId, mClientSecret, url, data, completionSource, completionSource, mRetryPolicyFactory.newRetryPolicy()); mRequestQueue.add(loginRequest); return completionSource.getTask(); } /** * Creates a new Gini user. * * @param userCredentials The user's credentials. * @param userCenterApiSession A valid session to do requests to the Gini User Center API. * * @return A task which will resolve to a JSONObject representing the API's response, which * is a user information. * @throws JSONException If the user credentials can't be JSON serialized. */ public Task<Uri> createUser(final UserCredentials userCredentials, Session userCenterApiSession) throws JSONException { final RequestTaskCompletionSource<Uri> completionSource = RequestTaskCompletionSource.newCompletionSource(); final String url = mBaseUrl + "api/users"; final JSONObject data = new JSONObject() {{ put("email", userCredentials.getUsername()); put("password", userCredentials.getPassword()); }}; BearerLocationRequest request = new BearerLocationRequest(POST, url, data, userCenterApiSession, completionSource, completionSource, mRetryPolicyFactory.newRetryPolicy()); mRequestQueue.add(request); return completionSource.getTask(); } public Task<JSONObject> getUserInfo(Uri userUri, Session userCenterApiSession) { final RequestTaskCompletionSource<JSONObject> completionSource = RequestTaskCompletionSource.newCompletionSource(); final BearerJsonObjectRequest request = new BearerJsonObjectRequest(GET, userUri.toString(), null, userCenterApiSession, completionSource, completionSource, mRetryPolicyFactory.newRetryPolicy()); mRequestQueue.add(request); return completionSource.getTask(); } // Visible for testing Task<JSONObject> getGiniApiSessionTokenInfo(final Session giniApiSession) { final RequestTaskCompletionSource<JSONObject> completionSource = RequestTaskCompletionSource.newCompletionSource(); final String url = mBaseUrl + "oauth/check_token?token=" + giniApiSession.getAccessToken(); final JsonObjectRequest request = new JsonObjectRequest(POST, url, null, completionSource, completionSource); mRequestQueue.add(request); return completionSource.getTask(); } public Task<String> getUserId(final Session giniAPISession) { return getGiniApiSessionTokenInfo(giniAPISession) .onSuccessTask(new Continuation<JSONObject, Task<String>>() { @Override public Task<String> then(Task<JSONObject> task) throws Exception { String userId = ""; try { userId = task.getResult().getString("user_name"); } catch (JSONException e) { return Task.forError(e); } return Task.forResult(userId); } }); } public Task<JSONObject> updateEmail(final String userId, final String newEmail, final String oldEmail, final Session userCenterApiSession) throws JSONException { final RequestTaskCompletionSource<JSONObject> completionSource = RequestTaskCompletionSource.newCompletionSource(); final String url = mBaseUrl + "api/users/" + userId; final JSONObject data = new JSONObject() {{ put("oldEmail", oldEmail); put("email", newEmail); }}; final BearerJsonObjectRequest request = new BearerJsonObjectRequest(PUT, url, data, userCenterApiSession, completionSource, completionSource, mRetryPolicyFactory.newRetryPolicy()); mRequestQueue.add(request); return completionSource.getTask(); } }
ginisdk/src/main/java/net/gini/android/authorization/UserCenterAPICommunicator.java
package net.gini.android.authorization; import android.net.Uri; import com.android.volley.RequestQueue; import com.android.volley.toolbox.JsonObjectRequest; import net.gini.android.RequestTaskCompletionSource; import net.gini.android.authorization.requests.BearerJsonObjectRequest; import net.gini.android.authorization.requests.TokenRequest; import net.gini.android.requests.BearerLocationRequest; import net.gini.android.requests.RetryPolicyFactory; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import bolts.Continuation; import bolts.Task; import static com.android.volley.Request.Method.GET; import static com.android.volley.Request.Method.POST; /** * The UserCenterAPIManager is responsible for communication with the Gini User Center API. This includes handling HTTP * related error handling. */ public class UserCenterAPICommunicator { final private RequestQueue mRequestQueue; final private String mBaseUrl; final private String mClientId; final private String mClientSecret; final private RetryPolicyFactory mRetryPolicyFactory; public UserCenterAPICommunicator(final RequestQueue requestQueue, final String baseUrl, final String clientId, final String clientSecret, final RetryPolicyFactory retryPolicyFactory) { mRequestQueue = requestQueue; mBaseUrl = baseUrl; mClientId = clientId; mClientSecret = clientSecret; this.mRetryPolicyFactory = retryPolicyFactory; } /** * Logs in this client to the Gini User Center API. Uses the instance's client credentials to identify the client. * * Please note that this is used to login the client (in other words: the app) and not a Gini user. Please do not * mix the different sessions. * * @return A task which will resolve to a JSONObject representing the API's response, which is a valid access token * for the Gini User Center API. */ public Task<JSONObject> loginClient() { // Build and execute the request. final RequestTaskCompletionSource<JSONObject> completionSource = RequestTaskCompletionSource.newCompletionSource(); final String url = mBaseUrl + "oauth/token?grant_type=client_credentials"; TokenRequest loginRequest = new TokenRequest(mClientId, mClientSecret, url, null, completionSource, completionSource, mRetryPolicyFactory.newRetryPolicy()); mRequestQueue.add(loginRequest); return completionSource.getTask(); } /** * Logs in a Gini user. * * @param userCredentials The user's credentials. * @return A task which will resolve to a JSONObject representing the API's response, which is a valid access token * for the Gini API. */ public Task<JSONObject> loginUser(UserCredentials userCredentials) { // Build and execute the request. final RequestTaskCompletionSource<JSONObject> completionSource = RequestTaskCompletionSource.newCompletionSource(); final String url = mBaseUrl + "oauth/token?grant_type=password"; final HashMap<String, String> data = new HashMap<String, String>(); data.put("username", userCredentials.getUsername()); data.put("password", userCredentials.getPassword()); TokenRequest loginRequest = new TokenRequest(mClientId, mClientSecret, url, data, completionSource, completionSource, mRetryPolicyFactory.newRetryPolicy()); mRequestQueue.add(loginRequest); return completionSource.getTask(); } /** * Creates a new Gini user. * * @param userCredentials The user's credentials. * @param userCenterApiSession A valid session to do requests to the Gini User Center API. * * @return A task which will resolve to a JSONObject representing the API's response, which * is a user information. * @throws JSONException If the user credentials can't be JSON serialized. */ public Task<Uri> createUser(final UserCredentials userCredentials, Session userCenterApiSession) throws JSONException { final RequestTaskCompletionSource<Uri> completionSource = RequestTaskCompletionSource.newCompletionSource(); final String url = mBaseUrl + "api/users"; final JSONObject data = new JSONObject() {{ put("email", userCredentials.getUsername()); put("password", userCredentials.getPassword()); }}; BearerLocationRequest request = new BearerLocationRequest(POST, url, data, userCenterApiSession, completionSource, completionSource, mRetryPolicyFactory.newRetryPolicy()); mRequestQueue.add(request); return completionSource.getTask(); } public Task<JSONObject> getUserInfo(Uri userUri, Session userCenterApiSession) { final RequestTaskCompletionSource<JSONObject> completionSource = RequestTaskCompletionSource.newCompletionSource(); final BearerJsonObjectRequest request = new BearerJsonObjectRequest(GET, userUri.toString(), null, userCenterApiSession, completionSource, completionSource, mRetryPolicyFactory.newRetryPolicy()); mRequestQueue.add(request); return completionSource.getTask(); } // Visible for testing Task<JSONObject> getGiniApiSessionTokenInfo(final Session giniApiSession) { final RequestTaskCompletionSource<JSONObject> completionSource = RequestTaskCompletionSource.newCompletionSource(); final String url = mBaseUrl + "oauth/check_token?token=" + giniApiSession.getAccessToken(); final JsonObjectRequest request = new JsonObjectRequest(POST, url, null, completionSource, completionSource); mRequestQueue.add(request); return completionSource.getTask(); } public Task<String> getUserId(final Session giniAPISession) { return getGiniApiSessionTokenInfo(giniAPISession) .onSuccessTask(new Continuation<JSONObject, Task<String>>() { @Override public Task<String> then(Task<JSONObject> task) throws Exception { String userId = ""; try { userId = task.getResult().getString("user_name"); } catch (JSONException e) { return Task.forError(e); } return Task.forResult(userId); } }); } public Task<JSONObject> updateEmail(final String userId, final String newEmail, final String oldEmail, final Session userCenterApiSession) throws JSONException { final RequestTaskCompletionSource<JSONObject> completionSource = RequestTaskCompletionSource.newCompletionSource(); final String url = mBaseUrl + "api/users/" + userId; final JSONObject data = new JSONObject() {{ put("oldEmail", oldEmail); put("email", newEmail); }}; final BearerJsonObjectRequest request = new BearerJsonObjectRequest(POST, url, data, userCenterApiSession, completionSource, completionSource, mRetryPolicyFactory.newRetryPolicy()); mRequestQueue.add(request); return completionSource.getTask(); } }
Fixed http method
ginisdk/src/main/java/net/gini/android/authorization/UserCenterAPICommunicator.java
Fixed http method
<ide><path>inisdk/src/main/java/net/gini/android/authorization/UserCenterAPICommunicator.java <ide> <ide> import static com.android.volley.Request.Method.GET; <ide> import static com.android.volley.Request.Method.POST; <add>import static com.android.volley.Request.Method.PUT; <ide> <ide> <ide> /** <ide> put("email", newEmail); <ide> }}; <ide> final BearerJsonObjectRequest request = <del> new BearerJsonObjectRequest(POST, url, data, userCenterApiSession, completionSource, <add> new BearerJsonObjectRequest(PUT, url, data, userCenterApiSession, completionSource, <ide> completionSource, mRetryPolicyFactory.newRetryPolicy()); <ide> mRequestQueue.add(request); <ide>
Java
apache-2.0
015b0d4e2e0b406cabe57d48b07d5c3aa656f5c7
0
ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop
package it.unibz.inf.ontop.iq.transform.impl; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; import it.unibz.inf.ontop.injection.IntermediateQueryFactory; import it.unibz.inf.ontop.iq.*; import it.unibz.inf.ontop.iq.node.ConstructionNode; import it.unibz.inf.ontop.iq.node.DistinctNode; import it.unibz.inf.ontop.iq.transform.NoNullValueEnforcer; import it.unibz.inf.ontop.model.term.*; import it.unibz.inf.ontop.substitution.ImmutableSubstitution; import it.unibz.inf.ontop.substitution.SubstitutionFactory; import it.unibz.inf.ontop.utils.ImmutableCollectors; import java.util.Map; import java.util.Optional; public class NoNullValuesEnforcerImpl implements NoNullValueEnforcer { private final IntermediateQueryFactory iQFactory; private final TermFactory termFactory; private final SubstitutionFactory substitutionFactory; @Inject private NoNullValuesEnforcerImpl(IntermediateQueryFactory iQFactory, TermFactory termFactory, SubstitutionFactory substitutionFactory) { this.iQFactory = iQFactory; this.termFactory = termFactory; this.substitutionFactory = substitutionFactory; } @Override public IQ transform(IQ originalQuery) { IQTree tree = originalQuery.getTree(); Optional<ImmutableExpression> condition = termFactory.getConjunction( tree.getVariables().stream() .map(termFactory::getDBIsNotNull)); IQTree newTree = condition .map(iQFactory::createFilterNode) .map(n -> iQFactory.createUnaryIQTree(n, tree)) .map(t -> t.normalizeForOptimization(originalQuery.getVariableGenerator())) .map(this::declareTopVariablesNotNull) .orElse(tree); return newTree.equals(tree) ? originalQuery : iQFactory.createIQ(originalQuery.getProjectionAtom(), newTree); } /** * Now that the filter has been inserted, we have the guarantee that the top variables are not nullable. * * Few functions like NULLIF can be simplified when they are declared as not able to produce a NULL. * Not that such a simplification cannot always be performed using VariableNullability information (insufficient for NULLIF). * * For instance * CONSTRUCT s,p,o s/RDF(a,IRI), p/RDF("http://ex.org/p", IRI), o/RDF(NULLIF(b, 0),xsd:integer) * T1(a,b) * * becoming after inserting and pushing down the filter * CONSTRUCT s,p,o s/RDF(a,IRI), p/RDF("http://ex.org/p", IRI), o/RDF(NULLIF(b, 0),xsd:integer) * FILTER NOT(NON_STRICT_EQ(b, 0)) * T1(a,b) * * Can be simplified as (by declaring "o" as non-null) * CONSTRUCT s,p,o s/RDF(a,IRI), p/RDF("http://ex.org/p", IRI), o/RDF(b,xsd:integer) * FILTER NOT(NON_STRICT_EQ(b, 0)) * T1(a,b) * * DESIGN NOTE: * In a bottom-up manner, NULLIF(b,0) would instead require to known that "b" is non-null *and different from 0* * to simplify itself. Such information is only partially provided by the VariableNullability data structure. */ protected IQTree declareTopVariablesNotNull(IQTree tree) { NotNullTopVariablePropagator transformer = new NotNullTopVariablePropagator(iQFactory, substitutionFactory, tree.getVariables()); return transformer.transform(tree); } protected static class NotNullTopVariablePropagator extends DefaultNonRecursiveIQTreeTransformer { protected final IntermediateQueryFactory iqFactory; protected final ImmutableSet<Variable> nonNullVariables; private final SubstitutionFactory substitutionFactory; protected NotNullTopVariablePropagator(IntermediateQueryFactory iqFactory, SubstitutionFactory substitutionFactory, ImmutableSet<Variable> nonNullVariables) { this.iqFactory = iqFactory; this.substitutionFactory = substitutionFactory; this.nonNullVariables = nonNullVariables; } @Override public IQTree transformConstruction(IQTree tree, ConstructionNode rootNode, IQTree child) { ImmutableSubstitution<ImmutableTerm> initialSubstitution = rootNode.getSubstitution(); ImmutableMap<Variable, FunctionalTermSimplification> updatedEntryMap = initialSubstitution.getFunctionalTermFragment().getImmutableMap().entrySet().stream() .filter(e -> nonNullVariables.contains(e.getKey())) .collect(ImmutableCollectors.toMap( Map.Entry::getKey, e -> e.getValue().simplifyAsGuaranteedToBeNonNull() )); ImmutableMap<Variable, ImmutableTerm> newSubstitutionMap = initialSubstitution.getImmutableMap().entrySet().stream() .map(e -> Optional.ofNullable(updatedEntryMap.get(e.getKey())) .map(s -> Maps.immutableEntry(e.getKey(), s.getSimplifiedTerm())) .orElse(e)) .collect(ImmutableCollectors.toMap()); ConstructionNode newConstructionNode = initialSubstitution.getImmutableMap().equals(newSubstitutionMap) ? rootNode : iqFactory.createConstructionNode(rootNode.getVariables(), substitutionFactory.getSubstitution(newSubstitutionMap)); ImmutableSet<Variable> simplifiableChildVariables = Sets.union( Sets.difference(rootNode.getVariables(), initialSubstitution.getDomain()), updatedEntryMap.values().stream() .flatMap(s -> s.getSimplifiableVariables().stream()) .collect(ImmutableCollectors.toSet())) .immutableCopy(); // "Recursive" IQTree newChild = simplifiableChildVariables.isEmpty() ? child : (new NotNullTopVariablePropagator(iqFactory, substitutionFactory, simplifiableChildVariables)).transform(child); if (newConstructionNode == rootNode && newChild == child) return tree; return iqFactory.createUnaryIQTree(newConstructionNode, newChild); } /** * Propagates */ @Override public IQTree transformDistinct(IQTree tree, DistinctNode rootNode, IQTree child) { IQTree newChild = this.transform(child); return newChild.equals(child) ? tree : iqFactory.createUnaryIQTree(rootNode, newChild); } } }
core/model/src/main/java/it/unibz/inf/ontop/iq/transform/impl/NoNullValuesEnforcerImpl.java
package it.unibz.inf.ontop.iq.transform.impl; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; import it.unibz.inf.ontop.injection.IntermediateQueryFactory; import it.unibz.inf.ontop.iq.*; import it.unibz.inf.ontop.iq.node.ConstructionNode; import it.unibz.inf.ontop.iq.node.DistinctNode; import it.unibz.inf.ontop.iq.transform.NoNullValueEnforcer; import it.unibz.inf.ontop.model.term.*; import it.unibz.inf.ontop.substitution.ImmutableSubstitution; import it.unibz.inf.ontop.substitution.SubstitutionFactory; import it.unibz.inf.ontop.utils.ImmutableCollectors; import java.util.Map; import java.util.Optional; public class NoNullValuesEnforcerImpl implements NoNullValueEnforcer { private final IntermediateQueryFactory iQFactory; private final TermFactory termFactory; private final SubstitutionFactory substitutionFactory; @Inject private NoNullValuesEnforcerImpl(IntermediateQueryFactory iQFactory, TermFactory termFactory, SubstitutionFactory substitutionFactory) { this.iQFactory = iQFactory; this.termFactory = termFactory; this.substitutionFactory = substitutionFactory; } @Override public IQ transform(IQ originalQuery) { IQTree tree = originalQuery.getTree(); Optional<ImmutableExpression> condition = termFactory.getConjunction( tree.getVariables().stream() .map(termFactory::getDBIsNotNull)); IQTree newTree = condition .map(iQFactory::createFilterNode) .map(n -> iQFactory.createUnaryIQTree(n, tree)) .map(t -> t.normalizeForOptimization(originalQuery.getVariableGenerator())) .map(this::declareTopVariablesNotNull) .orElse(tree); return newTree.equals(tree) ? originalQuery : iQFactory.createIQ(originalQuery.getProjectionAtom(), newTree); } /** * Now that the filter has been inserted, we have the guarantee that the top variables are not nullable. * * Few functions like NULLIF can be simplified when they are declared as not able to produce a NULL. * Not that such a simplification cannot always be performed using VariableNullability information (insufficient for NULLIF). * * For instance * CONSTRUCT s,p,o s/RDF(a,IRI), p/RDF("http://ex.org/p", IRI), o/RDF(NULLIF(b, 0),xsd:integer) * T1(a,b) * * becoming after inserting and pushing down the filter * CONSTRUCT s,p,o s/RDF(a,IRI), p/RDF("http://ex.org/p", IRI), o/RDF(NULLIF(b, 0),xsd:integer) * FILTER NOT(NON_STRICT_EQ(b, 0)) * T1(a,b) * * Can be simplified as (by declaring "o" as non-null) * CONSTRUCT s,p,o s/RDF(a,IRI), p/RDF("http://ex.org/p", IRI), o/RDF(b,xsd:integer) * FILTER NOT(NON_STRICT_EQ(b, 0)) * T1(a,b) * * DESIGN NOTE: * In a bottom-up manner, NULLIF(b,0) would instead require to known that "b" is non-null *and different from 0* * to simplify itself. Such information is only partially provided by the VariableNullability data structure. */ protected IQTree declareTopVariablesNotNull(IQTree tree) { NotNullTopVariablePropagator transformer = new NotNullTopVariablePropagator(iQFactory, substitutionFactory, tree.getVariables()); return transformer.transform(tree); } protected static class NotNullTopVariablePropagator extends DefaultNonRecursiveIQTreeTransformer { protected final IntermediateQueryFactory iqFactory; protected final ImmutableSet<Variable> nonNullVariables; private final SubstitutionFactory substitutionFactory; protected NotNullTopVariablePropagator(IntermediateQueryFactory iqFactory, SubstitutionFactory substitutionFactory, ImmutableSet<Variable> nonNullVariables) { this.iqFactory = iqFactory; this.substitutionFactory = substitutionFactory; this.nonNullVariables = nonNullVariables; } @Override public IQTree transformConstruction(IQTree tree, ConstructionNode rootNode, IQTree child) { ImmutableSubstitution<ImmutableTerm> initialSubstitution = rootNode.getSubstitution(); ImmutableMap<Variable, FunctionalTermSimplification> updatedEntryMap = initialSubstitution.getFunctionalTermFragment().getImmutableMap().entrySet().stream() .filter(e -> nonNullVariables.contains(e.getKey())) .collect(ImmutableCollectors.toMap( Map.Entry::getKey, e -> e.getValue().simplifyAsGuaranteedToBeNonNull() )); ImmutableMap<Variable, ImmutableTerm> newSubstitutionMap = initialSubstitution.getImmutableMap().entrySet().stream() .map(e -> Optional.ofNullable(updatedEntryMap.get(e.getKey())) .map(s -> Maps.immutableEntry(e.getKey(), s.getSimplifiedTerm())) .orElse(e)) .collect(ImmutableCollectors.toMap()); ConstructionNode newConstructionNode = initialSubstitution.getImmutableMap().equals(newSubstitutionMap) ? rootNode : iqFactory.createConstructionNode(rootNode.getVariables(), substitutionFactory.getSubstitution(newSubstitutionMap)); ImmutableSet<Variable> simplifiableChildVariables = Sets.union( Sets.difference(rootNode.getVariables(), initialSubstitution.getDomain()), updatedEntryMap.values().stream() .flatMap(s -> s.getSimplifiableVariables().stream()) .collect(ImmutableCollectors.toSet())) .immutableCopy(); // "Recursive" IQTree newChild = simplifiableChildVariables.isEmpty() ? child : (new NotNullTopVariablePropagator(iqFactory, substitutionFactory, simplifiableChildVariables)).transform(child); return iqFactory.createUnaryIQTree(newConstructionNode, newChild); } /** * Propagates */ @Override public IQTree transformDistinct(IQTree tree, DistinctNode rootNode, IQTree child) { IQTree newChild = this.transform(child); return newChild.equals(child) ? tree : iqFactory.createUnaryIQTree(rootNode, newChild); } } }
Minor optimization added to NoNullValuesEnforcerImpl.
core/model/src/main/java/it/unibz/inf/ontop/iq/transform/impl/NoNullValuesEnforcerImpl.java
Minor optimization added to NoNullValuesEnforcerImpl.
<ide><path>ore/model/src/main/java/it/unibz/inf/ontop/iq/transform/impl/NoNullValuesEnforcerImpl.java <ide> ? child <ide> : (new NotNullTopVariablePropagator(iqFactory, substitutionFactory, simplifiableChildVariables)).transform(child); <ide> <add> if (newConstructionNode == rootNode && newChild == child) <add> return tree; <add> <ide> return iqFactory.createUnaryIQTree(newConstructionNode, newChild); <ide> } <ide>
Java
mit
003a4f3e65c6c52f59ea27454133efd6caf4e780
0
jenkinsci/analysis-core-plugin,amuniz/analysis-core-plugin,stephenc/analysis-core-plugin,amuniz/analysis-core-plugin,jenkinsci/warnings-plugin,jenkinsci/warnings-plugin,kohsuke/analysis-core-plugin,recena/analysis-core-plugin,stephenc/analysis-core-plugin,stephenc/analysis-core-plugin,jenkinsci/analysis-core-plugin,recena/analysis-core-plugin,jenkinsci/analysis-core-plugin,stephenc/analysis-core-plugin,kohsuke/analysis-core-plugin,recena/analysis-core-plugin,kohsuke/analysis-core-plugin,jenkinsci/warnings-plugin,amuniz/analysis-core-plugin,amuniz/analysis-core-plugin,jenkinsci/analysis-core-plugin,recena/analysis-core-plugin
package hudson.plugins.analysis.graph; import org.joda.time.LocalDate; /** * Graph label showing the build date. * * @author Ulli Hafner */ public class LocalDateLabel implements Comparable<LocalDateLabel> { private final LocalDate date; /** * Creates a new instance of {@link LocalDateLabel}. * * @param date * the date of the build */ public LocalDateLabel(final LocalDate date) { this.date = date; } /** {@inheritDoc} */ public int compareTo(final LocalDateLabel o) { return date.compareTo(o.date); } /** {@inheritDoc} */ @Override public String toString() { return date.toString("MM-dd"); } /** {@inheritDoc} */ @Override public int hashCode() { int prime = 31; int result = 1; result = prime * result + ((date == null) ? 0 : date.hashCode()); return result; } /** {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } LocalDateLabel other = (LocalDateLabel)obj; if (date == null) { if (other.date != null) { return false; } } else if (!date.equals(other.date)) { return false; } return true; } }
src/main/java/hudson/plugins/analysis/graph/LocalDateLabel.java
package hudson.plugins.analysis.graph; import org.joda.time.LocalDate; /** * Graph label showing the build date. * * @author Ulli Hafner */ public class LocalDateLabel implements Comparable<LocalDateLabel> { private final LocalDate date; /** * Creates a new instance of {@link LocalDateLabel}. * * @param date * the date of the build */ public LocalDateLabel(final LocalDate date) { this.date = date; } /** {@inheritDoc} */ public int compareTo(final LocalDateLabel o) { return date.compareTo(o.date); } /** {@inheritDoc} */ @Override public String toString() { return date.toString("MM-dd"); } }
Added equals.
src/main/java/hudson/plugins/analysis/graph/LocalDateLabel.java
Added equals.
<ide><path>rc/main/java/hudson/plugins/analysis/graph/LocalDateLabel.java <ide> public String toString() { <ide> return date.toString("MM-dd"); <ide> } <add> <add> /** {@inheritDoc} */ <add> @Override <add> public int hashCode() { <add> int prime = 31; <add> int result = 1; <add> result = prime * result + ((date == null) ? 0 : date.hashCode()); <add> return result; <add> } <add> <add> /** {@inheritDoc} */ <add> @Override <add> public boolean equals(final Object obj) { <add> if (this == obj) { <add> return true; <add> } <add> if (obj == null) { <add> return false; <add> } <add> if (getClass() != obj.getClass()) { <add> return false; <add> } <add> LocalDateLabel other = (LocalDateLabel)obj; <add> if (date == null) { <add> if (other.date != null) { <add> return false; <add> } <add> } <add> else if (!date.equals(other.date)) { <add> return false; <add> } <add> return true; <add> } <ide> } <ide>
Java
apache-2.0
008bc5f68a3d58d69f2929c7a5482565e3561526
0
mlhartme/stool,mlhartme/stool,mlhartme/stool,mlhartme/stool,mlhartme/stool
/* * Copyright 1&1 Internet AG, https://github.com/1and1/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oneandone.stool.cli.command; import net.oneandone.stool.cli.AuthenticationException; import net.oneandone.stool.cli.Client; import net.oneandone.stool.cli.Globals; import net.oneandone.stool.cli.Context; import net.oneandone.stool.core.Configuration; import java.io.IOException; public class ConfigContext extends ClientCommand { private final boolean offline; private final boolean quiet; private final String setOpt; public ConfigContext(Globals globals, boolean offline, boolean quiet, String setOpt) { super(globals); this.offline = offline; this.quiet = quiet; this.setOpt = setOpt; } public void run() throws Exception { Configuration configuration; Context old; String oldName; Context found; String current; configuration = globals.configuration(); if (setOpt == null) { if (quiet) { console.info.println(configuration.currentContext().name); } else { found = configuration.currentContextOpt(); current = found == null ? null : found.name; for (String name : configuration.contexts.keySet()) { console.info.print(name.equals(current) ? "=> " : " "); console.info.println(name); } } } else { found = configuration.contextLookup(setOpt); if (found == null) { throw new IOException(setOpt + ": context not found, available contexts: " + configuration.contexts.keySet()); } old = configuration.currentContextOpt(); oldName = old == null ? "(none)" : old.name; if (oldName.equals(setOpt)) { console.info.println("not changed: " + oldName); } else { configuration.setCurrentContext(setOpt); configuration.save(globals.configurationYaml()); console.info.println("changed " + oldName + " -> " + setOpt); if (!offline) { check(found); } } } } private void check(Context context) throws Exception { Client client; client = context.connect(globals.getWorld(), globals.configuration(), globals.caller()); try { // check if we need authentication; CAUTION: don't use version because it doesn't need credentials client.list("arbitraryStageNameFilter"); } catch (AuthenticationException e) { console.info.println("authentication required"); console.verbose.println(e); e.printStackTrace(console.verbose); new Auth(globals, false).run(); } console.verbose.println("server info: " + globals.configuration().currentContext().connect(globals.getWorld(), globals.configuration(), globals.caller()).version()); } }
src/main/java/net/oneandone/stool/cli/command/ConfigContext.java
/* * Copyright 1&1 Internet AG, https://github.com/1and1/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oneandone.stool.cli.command; import net.oneandone.stool.cli.AuthenticationException; import net.oneandone.stool.cli.Client; import net.oneandone.stool.cli.Globals; import net.oneandone.stool.cli.Context; import net.oneandone.stool.core.Configuration; import java.io.IOException; public class ConfigContext extends ClientCommand { private final boolean offline; private final boolean quiet; private final String setOpt; public ConfigContext(Globals globals, boolean offline, boolean quiet, String setOpt) { super(globals); this.offline = offline; this.quiet = quiet; this.setOpt = setOpt; } public void run() throws Exception { Configuration configuration; Context old; String oldName; Context found; String current; configuration = globals.configuration(); if (setOpt == null) { if (quiet) { console.info.println(configuration.currentContext().name); } else { found = configuration.currentContextOpt(); current = found == null ? null : found.name; for (String name : configuration.contexts.keySet()) { console.info.print(name.equals(current) ? "=> " : " "); console.info.println(name); } } } else { found = configuration.contextLookup(setOpt); if (found == null) { throw new IOException(setOpt + ": context not found, available contexts: " + configuration.contexts.keySet()); } old = configuration.currentContextOpt(); oldName = old == null ? "(none)" : old.name; if (oldName.equals(setOpt)) { console.info.println("not changed: " + oldName); } else { configuration.setCurrentContext(setOpt); configuration.save(globals.configurationYaml()); console.info.println("changed " + oldName + " -> " + setOpt); if (!offline) { check(found); } } } } private void check(Context context) throws Exception { Client client; client = context.connect(globals.getWorld(), globals.configuration(), globals.caller()); try { // check if we need authentication; CAUTION: don't use version because it doesn't need credentials client.list("arbitraryStageNameFilter"); } catch (AuthenticationException e) { console.info.println("authentication required: " + e); console.verbose.println(e); e.printStackTrace(console.verbose); new Auth(globals, false).run(); } console.verbose.println("server info: " + globals.configuration().currentContext().connect(globals.getWorld(), globals.configuration(), globals.caller()).version()); } }
output tweaks
src/main/java/net/oneandone/stool/cli/command/ConfigContext.java
output tweaks
<ide><path>rc/main/java/net/oneandone/stool/cli/command/ConfigContext.java <ide> // check if we need authentication; CAUTION: don't use version because it doesn't need credentials <ide> client.list("arbitraryStageNameFilter"); <ide> } catch (AuthenticationException e) { <del> console.info.println("authentication required: " + e); <add> console.info.println("authentication required"); <ide> console.verbose.println(e); <ide> e.printStackTrace(console.verbose); <ide> new Auth(globals, false).run();
Java
apache-2.0
5986075e0a836bd292424ed36b0ba3d9d6dcbdb0
0
ruspl-afed/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,ruspl-afed/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2016 Serge Rieder ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 2) * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jkiss.dbeaver.ui.controls.resultset.panel; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.*; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBIcon; import org.jkiss.dbeaver.model.DBPImage; import org.jkiss.dbeaver.model.data.DBDAttributeBinding; import org.jkiss.dbeaver.model.data.aggregate.IAggregateFunction; import org.jkiss.dbeaver.registry.functions.AggregateFunctionDescriptor; import org.jkiss.dbeaver.registry.functions.FunctionsRegistry; import org.jkiss.dbeaver.ui.DBeaverIcons; import org.jkiss.dbeaver.ui.UIIcon; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.controls.resultset.*; import java.util.*; import java.util.List; /** * RSV value view panel */ public class AggregateColumnsPanel implements IResultSetPanel { private static final Log log = Log.getLog(AggregateColumnsPanel.class); public static final String PANEL_ID = "column-aggregate"; private IResultSetPresentation presentation; private Tree aggregateTable; private boolean groupByColumns; private boolean runServerQueries; public AggregateColumnsPanel() { } @Override public String getPanelTitle() { return "Aggregate"; } @Override public DBPImage getPanelImage() { return UIIcon.APACHE; } @Override public String getPanelDescription() { return "Aggregate columns"; } @Override public Control createContents(IResultSetPresentation presentation, Composite parent) { this.presentation = presentation; this.aggregateTable = new Tree(parent, SWT.SINGLE); this.aggregateTable.setHeaderVisible(true); this.aggregateTable.setLinesVisible(true); new TreeColumn(this.aggregateTable, SWT.LEFT).setText("Function"); new TreeColumn(this.aggregateTable, SWT.RIGHT).setText("Value"); if (this.presentation instanceof ISelectionProvider) { ((ISelectionProvider) this.presentation).addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { refresh(); } }); } return this.aggregateTable; } @Override public void activatePanel(IContributionManager contributionManager) { fillToolBar(contributionManager); refresh(); } @Override public void deactivatePanel() { } @Override public void refresh() { aggregateTable.removeAll(); if (this.presentation instanceof ISelectionProvider) { ISelection selection = ((ISelectionProvider) presentation).getSelection(); if (selection instanceof IResultSetSelection) { aggregateSelection((IResultSetSelection)selection); } } UIUtils.packColumns(aggregateTable, true, null); } private void aggregateSelection(IResultSetSelection selection) { List<AggregateFunctionDescriptor> functions = new ArrayList<>(FunctionsRegistry.getInstance().getFunctions()); Collections.sort(functions, new Comparator<AggregateFunctionDescriptor>() { @Override public int compare(AggregateFunctionDescriptor o1, AggregateFunctionDescriptor o2) { return o1.getLabel().compareTo(o2.getLabel()); } }); ResultSetModel model = presentation.getController().getModel(); for (AggregateFunctionDescriptor funcDesc : functions) { try { int valueCount = 0; IAggregateFunction func = funcDesc.createFunction(); for (Iterator iter = selection.iterator(); iter.hasNext(); ) { Object element = iter.next(); DBDAttributeBinding attr = selection.getElementAttribute(element); ResultSetRow row = selection.getElementRow(element); Object cellValue = model.getCellValue(attr, row); if (cellValue instanceof Number) { func.accumulate((Number) cellValue); valueCount++; } } TreeItem funcItem = new TreeItem(aggregateTable, SWT.NONE); funcItem.setText(0, funcDesc.getLabel()); funcItem.setImage(0, DBeaverIcons.getImage(funcDesc.getIcon())); if (valueCount > 0) { Number result = func.getResult(valueCount); if (result != null) { funcItem.setText(1, result.toString()); } } } catch (Exception e) { log.error(e); } } } public void clearValue() { aggregateTable.removeAll(); } private void fillToolBar(IContributionManager contributionManager) { contributionManager.add(new Separator()); contributionManager.add(new Action("Group by columns", IAction.AS_CHECK_BOX) { { setImageDescriptor(DBeaverIcons.getImageDescriptor(DBIcon.TREE_COLUMN)); } @Override public boolean isChecked() { return groupByColumns; } @Override public void run() { groupByColumns = !groupByColumns; refresh(); } }); } }
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/controls/resultset/panel/AggregateColumnsPanel.java
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2016 Serge Rieder ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License (version 2) * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.jkiss.dbeaver.ui.controls.resultset.panel; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IContributionManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.*; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.DBIcon; import org.jkiss.dbeaver.model.DBPImage; import org.jkiss.dbeaver.model.data.DBDAttributeBinding; import org.jkiss.dbeaver.model.data.aggregate.*; import org.jkiss.dbeaver.registry.functions.AggregateFunctionDescriptor; import org.jkiss.dbeaver.registry.functions.FunctionsRegistry; import org.jkiss.dbeaver.ui.DBeaverIcons; import org.jkiss.dbeaver.ui.UIIcon; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.controls.resultset.*; import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * RSV value view panel */ public class AggregateColumnsPanel implements IResultSetPanel { private static final Log log = Log.getLog(AggregateColumnsPanel.class); public static final String PANEL_ID = "column-aggregate"; private IResultSetPresentation presentation; private Tree aggregateTable; private boolean groupByColumns; private boolean runServerQueries; public AggregateColumnsPanel() { } @Override public String getPanelTitle() { return "Aggregate"; } @Override public DBPImage getPanelImage() { return UIIcon.APACHE; } @Override public String getPanelDescription() { return "Aggregate columns"; } @Override public Control createContents(IResultSetPresentation presentation, Composite parent) { this.presentation = presentation; this.aggregateTable = new Tree(parent, SWT.SINGLE); this.aggregateTable.setHeaderVisible(true); this.aggregateTable.setLinesVisible(true); new TreeColumn(this.aggregateTable, SWT.LEFT).setText("Function"); new TreeColumn(this.aggregateTable, SWT.RIGHT).setText("Value"); if (this.presentation instanceof ISelectionProvider) { ((ISelectionProvider) this.presentation).addSelectionChangedListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { refresh(); } }); } return this.aggregateTable; } @Override public void activatePanel(IContributionManager contributionManager) { fillToolBar(contributionManager); refresh(); } @Override public void deactivatePanel() { } @Override public void refresh() { aggregateTable.removeAll(); if (this.presentation instanceof ISelectionProvider) { ISelection selection = ((ISelectionProvider) presentation).getSelection(); if (selection instanceof IResultSetSelection) { aggregateSelection((IResultSetSelection)selection); } } UIUtils.packColumns(aggregateTable, true, null); } private void aggregateSelection(IResultSetSelection selection) { List<AggregateFunctionDescriptor> functions = new ArrayList<>(FunctionsRegistry.getInstance().getFunctions()); functions.sort(new Comparator<AggregateFunctionDescriptor>() { @Override public int compare(AggregateFunctionDescriptor o1, AggregateFunctionDescriptor o2) { return o1.getLabel().compareTo(o2.getLabel()); } }); ResultSetModel model = presentation.getController().getModel(); for (AggregateFunctionDescriptor funcDesc : functions) { try { int valueCount = 0; IAggregateFunction func = funcDesc.createFunction(); for (Iterator iter = selection.iterator(); iter.hasNext(); ) { Object element = iter.next(); DBDAttributeBinding attr = selection.getElementAttribute(element); ResultSetRow row = selection.getElementRow(element); Object cellValue = model.getCellValue(attr, row); if (cellValue instanceof Number) { func.accumulate((Number) cellValue); valueCount++; } } TreeItem funcItem = new TreeItem(aggregateTable, SWT.NONE); funcItem.setText(0, funcDesc.getLabel()); funcItem.setImage(0, DBeaverIcons.getImage(funcDesc.getIcon())); if (valueCount > 0) { Number result = func.getResult(valueCount); if (result != null) { funcItem.setText(1, result.toString()); } } } catch (Exception e) { log.error(e); } } } public void clearValue() { aggregateTable.removeAll(); } private void fillToolBar(IContributionManager contributionManager) { contributionManager.add(new Separator()); contributionManager.add(new Action("Group by columns", IAction.AS_CHECK_BOX) { { setImageDescriptor(DBeaverIcons.getImageDescriptor(DBIcon.TREE_COLUMN)); } @Override public boolean isChecked() { return groupByColumns; } @Override public void run() { groupByColumns = !groupByColumns; refresh(); } }); } }
#188 Aggregate panels fix (jre7)
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/controls/resultset/panel/AggregateColumnsPanel.java
#188 Aggregate panels fix (jre7)
<ide><path>lugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/controls/resultset/panel/AggregateColumnsPanel.java <ide> import org.jkiss.dbeaver.model.DBIcon; <ide> import org.jkiss.dbeaver.model.DBPImage; <ide> import org.jkiss.dbeaver.model.data.DBDAttributeBinding; <del>import org.jkiss.dbeaver.model.data.aggregate.*; <add>import org.jkiss.dbeaver.model.data.aggregate.IAggregateFunction; <ide> import org.jkiss.dbeaver.registry.functions.AggregateFunctionDescriptor; <ide> import org.jkiss.dbeaver.registry.functions.FunctionsRegistry; <ide> import org.jkiss.dbeaver.ui.DBeaverIcons; <ide> import org.jkiss.dbeaver.ui.UIUtils; <ide> import org.jkiss.dbeaver.ui.controls.resultset.*; <ide> <del>import java.util.ArrayList; <del>import java.util.Comparator; <del>import java.util.Iterator; <add>import java.util.*; <ide> import java.util.List; <ide> <ide> /** <ide> <ide> private void aggregateSelection(IResultSetSelection selection) { <ide> List<AggregateFunctionDescriptor> functions = new ArrayList<>(FunctionsRegistry.getInstance().getFunctions()); <del> functions.sort(new Comparator<AggregateFunctionDescriptor>() { <add> Collections.sort(functions, new Comparator<AggregateFunctionDescriptor>() { <ide> @Override <ide> public int compare(AggregateFunctionDescriptor o1, AggregateFunctionDescriptor o2) { <ide> return o1.getLabel().compareTo(o2.getLabel());
Java
mit
6e2fe687e96ef224cd4ff302e965294fdd6500ab
0
tkob/yokohamaunit,tkob/yokohamaunit
package yokohama.unit.translator; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import lombok.SneakyThrows; import org.apache.bcel.Constants; import org.apache.bcel.generic.AnnotationEntryGen; import org.apache.bcel.generic.ArrayType; import org.apache.bcel.generic.BranchInstruction; import org.apache.bcel.generic.ClassGen; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.InstructionConstants; import org.apache.bcel.generic.InstructionFactory; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.LocalVariableGen; import org.apache.bcel.generic.MethodGen; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.PUSH; import org.apache.bcel.generic.ReferenceType; import org.apache.bcel.generic.Type; import org.apache.commons.collections4.ListUtils; import yokohama.unit.ast.Kind; import yokohama.unit.ast_junit.CatchClause; import yokohama.unit.ast_junit.CompilationUnit; import yokohama.unit.ast_junit.InvokeExpr; import yokohama.unit.ast_junit.IsNotStatement; import yokohama.unit.ast_junit.IsStatement; import yokohama.unit.ast_junit.Statement; import yokohama.unit.ast_junit.TestMethod; import yokohama.unit.ast_junit.Var; import yokohama.unit.ast_junit.VarDeclVisitor; import yokohama.unit.ast_junit.VarInitStatement; import yokohama.unit.util.Pair; public class BcelJUnitAstCompiler implements JUnitAstCompiler { public static class CaughtExceptionVarVisitor { public static List<Pair<yokohama.unit.ast_junit.Type, String>> sortedSet(Stream<Pair<yokohama.unit.ast_junit.Type, String>> i) { return i.collect(Collectors.toSet()) .stream() .sorted((o1, o2) -> o1.getSecond().compareTo(o2.getSecond())) .collect(Collectors.toList()); } public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitTestMethod(TestMethod testMethod) { return visitStatements(testMethod.getStatements()); } public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitStatements(List<Statement> statements) { return statements.stream().flatMap(this::visitStatement); } public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitStatement(Statement statement) { return statement.accept( isStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty(), isNotStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty(), varInitStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty(), tryStatement -> Stream.concat( visitStatements(tryStatement.getTryStatements()), Stream.concat( tryStatement.getCatchClauses().stream().flatMap(this::visitCatchClause), visitStatements(tryStatement.getFinallyStatements()))), ifStatement -> Stream.concat( visitStatements(ifStatement.getThen()), visitStatements(ifStatement.getOtherwise()))); } public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitCatchClause(CatchClause catchClause) { return Stream.concat( Stream.of( new Pair<>( catchClause.getClassType().toType(), catchClause.getVar().getName())), visitStatements(catchClause.getStatements())); } } @Override public boolean compile( Path docyPath, CompilationUnit ast, String className, String packageName, List<String> classPath, Optional<Path> dest, List<String> javacArgs) { ClassGen cg = new ClassGen( packageName.equals("") ? className : packageName + "." + className, "java.lang.Object", // super class docyPath.getFileName().toString(), // source file name Constants.ACC_PUBLIC | Constants.ACC_SUPER, null // implemented interfaces ); // set class file version to Java 1.5 cg.setMajor(49); cg.setMinor(0); ConstantPoolGen cp = cg.getConstantPool(); // cg creates constant pool cg.addEmptyConstructor(Constants.ACC_PUBLIC); for (TestMethod testMethod : ast.getClassDecl().getTestMethods()) { visitTestMethod(testMethod, cg, cp); } try { Path classFilePath = makeClassFilePath(dest, packageName, className); cg.getJavaClass().dump(classFilePath.toFile()); } catch(java.io.IOException e) { System.err.println(e); } return true; } public Path makeClassFilePath(Optional<Path> dest, String packageName, String className) { Path classFile = (dest.isPresent() ? dest.get(): Paths.get(".")) .resolve(Paths.get(packageName.replace('.', '/'))) .resolve(className + ".class"); return classFile; } private void visitTestMethod(TestMethod testMethod, ClassGen cg, ConstantPoolGen cp) { InstructionList il = new InstructionList(); MethodGen mg = new MethodGen(Constants.ACC_PUBLIC, // access flags Type.VOID, // return type of a test method is always void Type.NO_ARGS, new String[]{}, // test methods have no arguments testMethod.getName(), cg.getClassName(), il, cp); AnnotationEntryGen ag = new AnnotationEntryGen( new ObjectType("org.junit.Test"), Arrays.asList(), true, cp); mg.addAnnotationEntry(ag); InstructionFactory factory = new InstructionFactory(cg); Map<String, LocalVariableGen> locals = new HashMap<>(); List<Pair<yokohama.unit.ast_junit.Type, String>> varDecls = VarDeclVisitor.sortedSet(new VarDeclVisitor().visitTestMethod(testMethod)); List<Pair<yokohama.unit.ast_junit.Type, String>> caughtExVars = CaughtExceptionVarVisitor.sortedSet(new CaughtExceptionVarVisitor().visitTestMethod(testMethod)); for (Pair<yokohama.unit.ast_junit.Type,String> pair : ListUtils.union(varDecls, caughtExVars)) { yokohama.unit.ast_junit.Type type = pair.getFirst(); String name = pair.getSecond(); if (locals.containsKey(name)) throw new RuntimeException("duplicate local variable: " + name); LocalVariableGen lv = mg.addLocalVariable(name, typeOf(type), null, null); locals.put(name, lv); } for (Statement statement : testMethod.getStatements()) { visitStatement(statement, locals, mg, il, factory, cp); } il.append(InstructionConstants.RETURN); mg.setMaxStack(); cg.addMethod(mg.getMethod()); il.dispose(); } private void visitStatement( Statement statement, Map<String, LocalVariableGen> locals, MethodGen mg, InstructionList il, InstructionFactory factory, ConstantPoolGen cp) { statement.<Void>accept( isStatement -> { visitIsStatement(isStatement, locals, il, factory, cp); return null; }, isNotStatement -> { visitIsNotStatement(isNotStatement, locals, il, factory, cp); return null; }, varInitStatement -> { visitVarInitStatement(varInitStatement, locals, il, factory, cp); return null; }, tryStatement -> { InstructionHandle startTry = il.append(InstructionFactory.NOP); for (Statement s : tryStatement.getTryStatements()) { visitStatement(s, locals, mg, il, factory, cp); } InstructionHandle endTry = il.append(InstructionFactory.NOP); BranchInstruction goto_ = InstructionFactory.createBranchInstruction(Constants.GOTO, null); il.append(goto_); List<BranchInstruction> catchExits = new ArrayList<>(); for (CatchClause catchClause : tryStatement.getCatchClauses()) { LocalVariableGen ex = locals.get(catchClause.getVar().getName()); InstructionHandle startCatch = il.append( InstructionFactory.createStore(ex.getType(), ex.getIndex())); mg.addExceptionHandler( startTry, endTry, startCatch, (ObjectType)typeOf(catchClause.getClassType().toType())); for (Statement s : catchClause.getStatements()) { this.visitStatement(s, locals, mg, il, factory, cp); } BranchInstruction exitCatch = InstructionFactory.createBranchInstruction(Constants.GOTO, null); il.append(exitCatch); catchExits.add(exitCatch); } InstructionHandle startFinally = il.append(InstructionFactory.NOP); for (Statement s : tryStatement.getFinallyStatements()) { visitStatement(s, locals, mg, il, factory, cp); } goto_.setTarget(startFinally); for (BranchInstruction bi : catchExits) { bi.setTarget(startFinally); } return null; }, ifStatement -> { LocalVariableGen lv = locals.get(ifStatement.getCond().getName()); il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex())); // if BranchInstruction ifeq = InstructionFactory.createBranchInstruction(Constants.IFEQ, null); il.append(ifeq); // then for (Statement thenStatement : ifStatement.getThen()) { visitStatement(thenStatement, locals, mg, il, factory, cp); } BranchInstruction goto_ = InstructionFactory.createBranchInstruction(Constants.GOTO, null); il.append(goto_); // else InstructionHandle else_ = il.append(InstructionFactory.NOP); for (Statement elseStatement : ifStatement.getOtherwise()) { visitStatement(elseStatement, locals, mg, il, factory, cp); } InstructionHandle fi = il.append(InstructionFactory.NOP); // tie the knot ifeq.setTarget(else_); goto_.setTarget(fi); return null; } ); } private void visitIsStatement( IsStatement isStatement, Map<String, LocalVariableGen> locals, InstructionList il, InstructionFactory factory, ConstantPoolGen cp) { LocalVariableGen subject = locals.get(isStatement.getSubject().getName()); LocalVariableGen complement = locals.get(isStatement.getComplement().getName()); il.append(InstructionFactory.createLoad(subject.getType(), subject.getIndex())); il.append(InstructionFactory.createLoad(complement.getType(), complement.getIndex())); il.append( factory.createInvoke( "org.junit.Assert", "assertThat", Type.VOID, new Type[] { Type.OBJECT, new ObjectType("org.hamcrest.Matcher") }, Constants.INVOKESTATIC)); } private void visitIsNotStatement( IsNotStatement isNotStatement, Map<String, LocalVariableGen> locals, InstructionList il, InstructionFactory factory, ConstantPoolGen cp) { LocalVariableGen subject = locals.get(isNotStatement.getSubject().getName()); LocalVariableGen complement = locals.get(isNotStatement.getComplement().getName()); il.append(InstructionFactory.createLoad(subject.getType(), subject.getIndex())); il.append(InstructionFactory.createLoad(complement.getType(), complement.getIndex())); il.append( factory.createInvoke( "org.hamcrest.CoreMatchers", "not", new ObjectType("org.hamcrest.Matcher"), new Type[] { complement.getType() }, Constants.INVOKESTATIC)); il.append( factory.createInvoke( "org.junit.Assert", "assertThat", Type.VOID, new Type[] { Type.OBJECT, new ObjectType("org.hamcrest.Matcher") }, Constants.INVOKESTATIC)); } @SneakyThrows(ClassNotFoundException.class) private void visitVarInitStatement( VarInitStatement varInitStatement, Map<String, LocalVariableGen> locals, InstructionList il, InstructionFactory factory, ConstantPoolGen cp) { LocalVariableGen var = locals.get(varInitStatement.getName()); Type type = typeOf(varInitStatement.getType()); Type fromType = varInitStatement.getValue().<Type>accept( varExpr -> { LocalVariableGen from = locals.get(varExpr.getName()); il.append(InstructionFactory.createLoad(from.getType(), from.getIndex())); return from.getType(); }, instanceOfMatcherExpr -> { il.append(new PUSH(cp, new ObjectType(instanceOfMatcherExpr.getClassName()))); il.append(factory.createInvoke( "org.hamcrest.CoreMatchers", "instanceOf", new ObjectType("org.hamcrest.Matcher"), new Type[] { new ObjectType("java.lang.Class") }, Constants.INVOKESTATIC)); return new ObjectType("org.hamcrest.Matcher"); }, nullValueMatcherExpr -> { il.append(factory.createInvoke( "org.hamcrest.CoreMatchers", "nullValue", new ObjectType("org.hamcrest.Matcher"), Type.NO_ARGS, Constants.INVOKESTATIC)); return new ObjectType("org.hamcrest.Matcher"); }, equalToMatcherExpr -> { Var operand = equalToMatcherExpr.getOperand(); LocalVariableGen lv = locals.get(operand.getName()); il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex())); il.append(factory.createInvoke( "org.hamcrest.CoreMatchers", "is", new ObjectType("org.hamcrest.Matcher"), new Type[] { lv.getType() }, Constants.INVOKESTATIC)); return new ObjectType("org.hamcrest.Matcher"); }, newExpr -> { il.append(factory.createNew(newExpr.getType())); il.append(InstructionConstants.DUP); il.append(factory.createInvoke( newExpr.getType(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); return new ObjectType(newExpr.getType()); }, strLitExpr -> { il.append(new PUSH(cp, strLitExpr.getText())); return Type.STRING; }, nullExpr -> { il.append(InstructionConstants.ACONST_NULL); return Type.NULL; }, invokeExpr -> { Type returnType = typeOf(invokeExpr.getReturnType()); // first push target object LocalVariableGen object = locals.get(invokeExpr.getObject().getName()); il.append(InstructionFactory.createLoad(object.getType(), object.getIndex())); // push arguments for (Var arg : invokeExpr.getArgs()) { LocalVariableGen lv = locals.get(arg.getName()); il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex())); } // then call method il.append(factory.createInvoke( object.getType().toString(), // TODO: ? invokeExpr.getMethodName(), returnType, invokeExpr.getArgTypes().stream() .map(BcelJUnitAstCompiler::typeOf) .collect(Collectors.toList()) .toArray(new Type[]{}), invokeExpr.getInstruction() == InvokeExpr.Instruction.VIRTUAL ? Constants.INVOKEVIRTUAL : Constants.INVOKEINTERFACE)); return returnType; }, invokeStaticExpr -> { Type returnType = typeOf(invokeStaticExpr.getReturnType()); for (Var arg : invokeStaticExpr.getArgs()) { LocalVariableGen lv = locals.get(arg.getName()); il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex())); } il.append(factory.createInvoke( invokeStaticExpr.getClazz().getText(), invokeStaticExpr.getMethodName(), returnType, invokeStaticExpr.getArgTypes().stream() .map(BcelJUnitAstCompiler::typeOf) .collect(Collectors.toList()) .toArray(new Type[]{}), Constants.INVOKESTATIC)); return returnType; }, intLitExpr -> { il.append(new PUSH(cp, intLitExpr.getValue())); return Type.INT; }, classLitExpr -> { yokohama.unit.ast_junit.Type type_ = classLitExpr.getType(); il.append(new PUSH(cp, new ObjectType( type_.getDims() > 0 /* this is strange since BCEL has ArrayType apart from ObjectType, but there is no PUSH constructor in BCEL which takes ArrayType. */ ? type_.getFieldDescriptor() : type_.getText()))); return Type.CLASS; }, equalOpExpr -> { LocalVariableGen lhs = locals.get(equalOpExpr.getLhs().getName()); il.append(InstructionFactory.createLoad(lhs.getType(), lhs.getIndex())); LocalVariableGen rhs = locals.get(equalOpExpr.getRhs().getName()); il.append(InstructionFactory.createLoad(rhs.getType(), rhs.getIndex())); // if BranchInstruction if_acmpne = InstructionFactory.createBranchInstruction(Constants.IF_ACMPNE, null); il.append(if_acmpne); // then il.append(new PUSH(cp, true)); BranchInstruction goto_ = InstructionFactory.createBranchInstruction(Constants.GOTO, null); il.append(goto_); // else InstructionHandle else_ = il.append(new PUSH(cp, false)); InstructionHandle endIf = il.append(InstructionFactory.NOP); // tie the knot if_acmpne.setTarget(else_); goto_.setTarget(endIf); return Type.BOOLEAN; }); if (fromType instanceof ReferenceType && type instanceof ReferenceType) { ReferenceType fromType_ = (ReferenceType)fromType; ReferenceType type_ = (ReferenceType)type; if (!fromType_.isAssignmentCompatibleWith(type_)) { il.append(factory.createCheckCast(type_)); } } il.append(InstructionFactory.createStore(var.getType(), var.getIndex())); } static Type typeOf(yokohama.unit.ast_junit.Type type) { int dims = type.getDims(); if (dims == 0) { return type.getNonArrayType().accept( primitiveType -> { Kind kind = primitiveType.getKind(); switch (kind) { case BOOLEAN: return Type.BOOLEAN; case BYTE: return Type.BYTE; case SHORT: return Type.SHORT; case INT: return Type.INT; case LONG: return Type.LONG; case CHAR: return Type.CHAR; case FLOAT: return Type.FLOAT; case DOUBLE: return Type.DOUBLE; } throw new RuntimeException("should not reach here"); }, classType -> new ObjectType(classType.getText())); } else { return new ArrayType( typeOf(new yokohama.unit.ast_junit.Type(type.getNonArrayType() , 0)), dims); } } }
src/main/java/yokohama/unit/translator/BcelJUnitAstCompiler.java
package yokohama.unit.translator; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; import lombok.SneakyThrows; import org.apache.bcel.Constants; import org.apache.bcel.generic.AnnotationEntryGen; import org.apache.bcel.generic.ArrayType; import org.apache.bcel.generic.BranchInstruction; import org.apache.bcel.generic.ClassGen; import org.apache.bcel.generic.ConstantPoolGen; import org.apache.bcel.generic.InstructionConstants; import org.apache.bcel.generic.InstructionFactory; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.LocalVariableGen; import org.apache.bcel.generic.MethodGen; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.PUSH; import org.apache.bcel.generic.ReferenceType; import org.apache.bcel.generic.Type; import org.apache.commons.collections4.ListUtils; import yokohama.unit.ast.Kind; import yokohama.unit.ast_junit.CatchClause; import yokohama.unit.ast_junit.CompilationUnit; import yokohama.unit.ast_junit.InvokeExpr; import yokohama.unit.ast_junit.IsNotStatement; import yokohama.unit.ast_junit.IsStatement; import yokohama.unit.ast_junit.Statement; import yokohama.unit.ast_junit.TestMethod; import yokohama.unit.ast_junit.Var; import yokohama.unit.ast_junit.VarDeclVisitor; import yokohama.unit.ast_junit.VarInitStatement; import yokohama.unit.util.Pair; public class BcelJUnitAstCompiler implements JUnitAstCompiler { public static class CaughtExceptionVarVisitor { public static List<Pair<yokohama.unit.ast_junit.Type, String>> sortedSet(Stream<Pair<yokohama.unit.ast_junit.Type, String>> i) { return i.collect(Collectors.toSet()) .stream() .sorted((o1, o2) -> o1.getSecond().compareTo(o2.getSecond())) .collect(Collectors.toList()); } public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitTestMethod(TestMethod testMethod) { return visitStatements(testMethod.getStatements()); } public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitStatements(List<Statement> statements) { return statements.stream().flatMap(this::visitStatement); } public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitStatement(Statement statement) { return statement.accept( isStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty(), isNotStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty(), varInitStatement -> Stream.<Pair<yokohama.unit.ast_junit.Type, String>>empty(), tryStatement -> Stream.concat( visitStatements(tryStatement.getTryStatements()), Stream.concat( tryStatement.getCatchClauses().stream().flatMap(this::visitCatchClause), visitStatements(tryStatement.getFinallyStatements()))), ifStatement -> Stream.concat( visitStatements(ifStatement.getThen()), visitStatements(ifStatement.getOtherwise()))); } public Stream<Pair<yokohama.unit.ast_junit.Type, String>> visitCatchClause(CatchClause catchClause) { return Stream.concat( Stream.of( new Pair<>( catchClause.getClassType().toType(), catchClause.getVar().getName())), visitStatements(catchClause.getStatements())); } } @Override public boolean compile( Path docyPath, CompilationUnit ast, String className, String packageName, List<String> classPath, Optional<Path> dest, List<String> javacArgs) { ClassGen cg = new ClassGen( packageName.equals("") ? className : packageName + "." + className, "java.lang.Object", // super class docyPath.getFileName().toString(), // source file name Constants.ACC_PUBLIC | Constants.ACC_SUPER, null // implemented interfaces ); // set class file version to Java 1.6 cg.setMajor(49); cg.setMinor(0); ConstantPoolGen cp = cg.getConstantPool(); // cg creates constant pool cg.addEmptyConstructor(Constants.ACC_PUBLIC); for (TestMethod testMethod : ast.getClassDecl().getTestMethods()) { visitTestMethod(testMethod, cg, cp); } try { Path classFilePath = makeClassFilePath(dest, packageName, className); cg.getJavaClass().dump(classFilePath.toFile()); } catch(java.io.IOException e) { System.err.println(e); } return true; } public Path makeClassFilePath(Optional<Path> dest, String packageName, String className) { Path classFile = (dest.isPresent() ? dest.get(): Paths.get(".")) .resolve(Paths.get(packageName.replace('.', '/'))) .resolve(className + ".class"); return classFile; } private void visitTestMethod(TestMethod testMethod, ClassGen cg, ConstantPoolGen cp) { InstructionList il = new InstructionList(); MethodGen mg = new MethodGen(Constants.ACC_PUBLIC, // access flags Type.VOID, // return type of a test method is always void Type.NO_ARGS, new String[]{}, // test methods have no arguments testMethod.getName(), cg.getClassName(), il, cp); AnnotationEntryGen ag = new AnnotationEntryGen( new ObjectType("org.junit.Test"), Arrays.asList(), true, cp); mg.addAnnotationEntry(ag); InstructionFactory factory = new InstructionFactory(cg); Map<String, LocalVariableGen> locals = new HashMap<>(); List<Pair<yokohama.unit.ast_junit.Type, String>> varDecls = VarDeclVisitor.sortedSet(new VarDeclVisitor().visitTestMethod(testMethod)); List<Pair<yokohama.unit.ast_junit.Type, String>> caughtExVars = CaughtExceptionVarVisitor.sortedSet(new CaughtExceptionVarVisitor().visitTestMethod(testMethod)); for (Pair<yokohama.unit.ast_junit.Type,String> pair : ListUtils.union(varDecls, caughtExVars)) { yokohama.unit.ast_junit.Type type = pair.getFirst(); String name = pair.getSecond(); if (locals.containsKey(name)) throw new RuntimeException("duplicate local variable: " + name); LocalVariableGen lv = mg.addLocalVariable(name, typeOf(type), null, null); locals.put(name, lv); } for (Statement statement : testMethod.getStatements()) { visitStatement(statement, locals, mg, il, factory, cp); } il.append(InstructionConstants.RETURN); mg.setMaxStack(); cg.addMethod(mg.getMethod()); il.dispose(); } private void visitStatement( Statement statement, Map<String, LocalVariableGen> locals, MethodGen mg, InstructionList il, InstructionFactory factory, ConstantPoolGen cp) { statement.<Void>accept( isStatement -> { visitIsStatement(isStatement, locals, il, factory, cp); return null; }, isNotStatement -> { visitIsNotStatement(isNotStatement, locals, il, factory, cp); return null; }, varInitStatement -> { visitVarInitStatement(varInitStatement, locals, il, factory, cp); return null; }, tryStatement -> { InstructionHandle startTry = il.append(InstructionFactory.NOP); for (Statement s : tryStatement.getTryStatements()) { visitStatement(s, locals, mg, il, factory, cp); } InstructionHandle endTry = il.append(InstructionFactory.NOP); BranchInstruction goto_ = InstructionFactory.createBranchInstruction(Constants.GOTO, null); il.append(goto_); List<BranchInstruction> catchExits = new ArrayList<>(); for (CatchClause catchClause : tryStatement.getCatchClauses()) { LocalVariableGen ex = locals.get(catchClause.getVar().getName()); InstructionHandle startCatch = il.append( InstructionFactory.createStore(ex.getType(), ex.getIndex())); mg.addExceptionHandler( startTry, endTry, startCatch, (ObjectType)typeOf(catchClause.getClassType().toType())); for (Statement s : catchClause.getStatements()) { this.visitStatement(s, locals, mg, il, factory, cp); } BranchInstruction exitCatch = InstructionFactory.createBranchInstruction(Constants.GOTO, null); il.append(exitCatch); catchExits.add(exitCatch); } InstructionHandle startFinally = il.append(InstructionFactory.NOP); for (Statement s : tryStatement.getFinallyStatements()) { visitStatement(s, locals, mg, il, factory, cp); } goto_.setTarget(startFinally); for (BranchInstruction bi : catchExits) { bi.setTarget(startFinally); } return null; }, ifStatement -> { LocalVariableGen lv = locals.get(ifStatement.getCond().getName()); il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex())); // if BranchInstruction ifeq = InstructionFactory.createBranchInstruction(Constants.IFEQ, null); il.append(ifeq); // then for (Statement thenStatement : ifStatement.getThen()) { visitStatement(thenStatement, locals, mg, il, factory, cp); } BranchInstruction goto_ = InstructionFactory.createBranchInstruction(Constants.GOTO, null); il.append(goto_); // else InstructionHandle else_ = il.append(InstructionFactory.NOP); for (Statement elseStatement : ifStatement.getOtherwise()) { visitStatement(elseStatement, locals, mg, il, factory, cp); } InstructionHandle fi = il.append(InstructionFactory.NOP); // tie the knot ifeq.setTarget(else_); goto_.setTarget(fi); return null; } ); } private void visitIsStatement( IsStatement isStatement, Map<String, LocalVariableGen> locals, InstructionList il, InstructionFactory factory, ConstantPoolGen cp) { LocalVariableGen subject = locals.get(isStatement.getSubject().getName()); LocalVariableGen complement = locals.get(isStatement.getComplement().getName()); il.append(InstructionFactory.createLoad(subject.getType(), subject.getIndex())); il.append(InstructionFactory.createLoad(complement.getType(), complement.getIndex())); il.append( factory.createInvoke( "org.junit.Assert", "assertThat", Type.VOID, new Type[] { Type.OBJECT, new ObjectType("org.hamcrest.Matcher") }, Constants.INVOKESTATIC)); } private void visitIsNotStatement( IsNotStatement isNotStatement, Map<String, LocalVariableGen> locals, InstructionList il, InstructionFactory factory, ConstantPoolGen cp) { LocalVariableGen subject = locals.get(isNotStatement.getSubject().getName()); LocalVariableGen complement = locals.get(isNotStatement.getComplement().getName()); il.append(InstructionFactory.createLoad(subject.getType(), subject.getIndex())); il.append(InstructionFactory.createLoad(complement.getType(), complement.getIndex())); il.append( factory.createInvoke( "org.hamcrest.CoreMatchers", "not", new ObjectType("org.hamcrest.Matcher"), new Type[] { complement.getType() }, Constants.INVOKESTATIC)); il.append( factory.createInvoke( "org.junit.Assert", "assertThat", Type.VOID, new Type[] { Type.OBJECT, new ObjectType("org.hamcrest.Matcher") }, Constants.INVOKESTATIC)); } @SneakyThrows(ClassNotFoundException.class) private void visitVarInitStatement( VarInitStatement varInitStatement, Map<String, LocalVariableGen> locals, InstructionList il, InstructionFactory factory, ConstantPoolGen cp) { LocalVariableGen var = locals.get(varInitStatement.getName()); Type type = typeOf(varInitStatement.getType()); Type fromType = varInitStatement.getValue().<Type>accept( varExpr -> { LocalVariableGen from = locals.get(varExpr.getName()); il.append(InstructionFactory.createLoad(from.getType(), from.getIndex())); return from.getType(); }, instanceOfMatcherExpr -> { il.append(new PUSH(cp, new ObjectType(instanceOfMatcherExpr.getClassName()))); il.append(factory.createInvoke( "org.hamcrest.CoreMatchers", "instanceOf", new ObjectType("org.hamcrest.Matcher"), new Type[] { new ObjectType("java.lang.Class") }, Constants.INVOKESTATIC)); return new ObjectType("org.hamcrest.Matcher"); }, nullValueMatcherExpr -> { il.append(factory.createInvoke( "org.hamcrest.CoreMatchers", "nullValue", new ObjectType("org.hamcrest.Matcher"), Type.NO_ARGS, Constants.INVOKESTATIC)); return new ObjectType("org.hamcrest.Matcher"); }, equalToMatcherExpr -> { Var operand = equalToMatcherExpr.getOperand(); LocalVariableGen lv = locals.get(operand.getName()); il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex())); il.append(factory.createInvoke( "org.hamcrest.CoreMatchers", "is", new ObjectType("org.hamcrest.Matcher"), new Type[] { lv.getType() }, Constants.INVOKESTATIC)); return new ObjectType("org.hamcrest.Matcher"); }, newExpr -> { il.append(factory.createNew(newExpr.getType())); il.append(InstructionConstants.DUP); il.append(factory.createInvoke( newExpr.getType(), "<init>", Type.VOID, Type.NO_ARGS, Constants.INVOKESPECIAL)); return new ObjectType(newExpr.getType()); }, strLitExpr -> { il.append(new PUSH(cp, strLitExpr.getText())); return Type.STRING; }, nullExpr -> { il.append(InstructionConstants.ACONST_NULL); return Type.NULL; }, invokeExpr -> { Type returnType = typeOf(invokeExpr.getReturnType()); // first push target object LocalVariableGen object = locals.get(invokeExpr.getObject().getName()); il.append(InstructionFactory.createLoad(object.getType(), object.getIndex())); // push arguments for (Var arg : invokeExpr.getArgs()) { LocalVariableGen lv = locals.get(arg.getName()); il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex())); } // then call method il.append(factory.createInvoke( object.getType().toString(), // TODO: ? invokeExpr.getMethodName(), returnType, invokeExpr.getArgTypes().stream() .map(BcelJUnitAstCompiler::typeOf) .collect(Collectors.toList()) .toArray(new Type[]{}), invokeExpr.getInstruction() == InvokeExpr.Instruction.VIRTUAL ? Constants.INVOKEVIRTUAL : Constants.INVOKEINTERFACE)); return returnType; }, invokeStaticExpr -> { Type returnType = typeOf(invokeStaticExpr.getReturnType()); for (Var arg : invokeStaticExpr.getArgs()) { LocalVariableGen lv = locals.get(arg.getName()); il.append(InstructionFactory.createLoad(lv.getType(), lv.getIndex())); } il.append(factory.createInvoke( invokeStaticExpr.getClazz().getText(), invokeStaticExpr.getMethodName(), returnType, invokeStaticExpr.getArgTypes().stream() .map(BcelJUnitAstCompiler::typeOf) .collect(Collectors.toList()) .toArray(new Type[]{}), Constants.INVOKESTATIC)); return returnType; }, intLitExpr -> { il.append(new PUSH(cp, intLitExpr.getValue())); return Type.INT; }, classLitExpr -> { yokohama.unit.ast_junit.Type type_ = classLitExpr.getType(); il.append(new PUSH(cp, new ObjectType( type_.getDims() > 0 /* this is strange since BCEL has ArrayType apart from ObjectType, but there is no PUSH constructor in BCEL which takes ArrayType. */ ? type_.getFieldDescriptor() : type_.getText()))); return Type.CLASS; }, equalOpExpr -> { LocalVariableGen lhs = locals.get(equalOpExpr.getLhs().getName()); il.append(InstructionFactory.createLoad(lhs.getType(), lhs.getIndex())); LocalVariableGen rhs = locals.get(equalOpExpr.getRhs().getName()); il.append(InstructionFactory.createLoad(rhs.getType(), rhs.getIndex())); // if BranchInstruction if_acmpne = InstructionFactory.createBranchInstruction(Constants.IF_ACMPNE, null); il.append(if_acmpne); // then il.append(new PUSH(cp, true)); BranchInstruction goto_ = InstructionFactory.createBranchInstruction(Constants.GOTO, null); il.append(goto_); // else InstructionHandle else_ = il.append(new PUSH(cp, false)); InstructionHandle endIf = il.append(InstructionFactory.NOP); // tie the knot if_acmpne.setTarget(else_); goto_.setTarget(endIf); return Type.BOOLEAN; }); if (fromType instanceof ReferenceType && type instanceof ReferenceType) { ReferenceType fromType_ = (ReferenceType)fromType; ReferenceType type_ = (ReferenceType)type; if (!fromType_.isAssignmentCompatibleWith(type_)) { il.append(factory.createCheckCast(type_)); } } il.append(InstructionFactory.createStore(var.getType(), var.getIndex())); } static Type typeOf(yokohama.unit.ast_junit.Type type) { int dims = type.getDims(); if (dims == 0) { return type.getNonArrayType().accept( primitiveType -> { Kind kind = primitiveType.getKind(); switch (kind) { case BOOLEAN: return Type.BOOLEAN; case BYTE: return Type.BYTE; case SHORT: return Type.SHORT; case INT: return Type.INT; case LONG: return Type.LONG; case CHAR: return Type.CHAR; case FLOAT: return Type.FLOAT; case DOUBLE: return Type.DOUBLE; } throw new RuntimeException("should not reach here"); }, classType -> new ObjectType(classType.getText())); } else { return new ArrayType( typeOf(new yokohama.unit.ast_junit.Type(type.getNonArrayType() , 0)), dims); } } }
Fix comment
src/main/java/yokohama/unit/translator/BcelJUnitAstCompiler.java
Fix comment
<ide><path>rc/main/java/yokohama/unit/translator/BcelJUnitAstCompiler.java <ide> Constants.ACC_PUBLIC | Constants.ACC_SUPER, <ide> null // implemented interfaces <ide> ); <del> // set class file version to Java 1.6 <add> // set class file version to Java 1.5 <ide> cg.setMajor(49); <ide> cg.setMinor(0); <ide>
Java
apache-2.0
91d92e74509d3d2b92faf242941c336deef2a540
0
gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle,gradle/gradle
subprojects/core/src/main/java/org/gradle/testfixtures/internal/TestBuildRootBuildOperationType.java
/* * Copyright 2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.testfixtures.internal; import org.gradle.internal.operations.BuildOperationType; public interface TestBuildRootBuildOperationType extends BuildOperationType<TestBuildRootBuildOperationType.Details, TestBuildRootBuildOperationType.Result> { String DISPLAY_NAME = "Build in progress for ProjectBuilder"; interface Details { Details INSTANCE = new Details() {}; } interface Result { Result INSTANCE = new Result() {}; } }
Remove unused class after merge
subprojects/core/src/main/java/org/gradle/testfixtures/internal/TestBuildRootBuildOperationType.java
Remove unused class after merge
<ide><path>ubprojects/core/src/main/java/org/gradle/testfixtures/internal/TestBuildRootBuildOperationType.java <del>/* <del> * Copyright 2022 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.gradle.testfixtures.internal; <del> <del>import org.gradle.internal.operations.BuildOperationType; <del> <del>public interface TestBuildRootBuildOperationType extends BuildOperationType<TestBuildRootBuildOperationType.Details, TestBuildRootBuildOperationType.Result> { <del> <del> String DISPLAY_NAME = "Build in progress for ProjectBuilder"; <del> <del> interface Details { <del> Details INSTANCE = new Details() {}; <del> } <del> <del> interface Result { <del> Result INSTANCE = new Result() {}; <del> } <del>}
JavaScript
apache-2.0
72b161ec15a474625553bd4f6245e3676bbbd595
0
EasonYi/incubator-zeppelin,onkarshedge/incubator-zeppelin,Madhuka/incubator-zeppelin,rlugojr/incubator-zeppelin,astroshim/zeppelin,PeinYu/incubator-zeppelin,Leemoonsoo/incubator-zeppelin,wary/zeppelin,jhsbeat/incubator-zeppelin,mwkang/zeppelin,onkarshedge/incubator-zeppelin,sohaibiftikhar/zeppelin,apache/incubator-zeppelin,benoyantony/zeppelin,DataScienceX/incubator-zeppelin,datalayer/zeppelin-R,r-kamath/incubator-zeppelin,Nova-Boy/zeppelin,chilang/zeppelin,Peaceful-learner/incubator-zeppelin,elbamos/Zeppelin-With-R,doanduyhai/incubator-zeppelin,dsdinter/incubator-zeppelin,almacro/zeppelin-derived,vipul1409/zeppelin,joroKr21/incubator-zeppelin,1ambda/zeppelin,blrunner/incubator-zeppelin,yu74n/zeppelin,namanmishra91/zeppelin,jongyoul/zeppelin,issaclee/silkroad,pellmont/zeppelin,galleon/incubator-zeppelin,RPCMoritz/incubator-zeppelin,brigade/incubator-zeppelin,kidaa/incubator-zeppelin,mahantheshhv/incubator-zeppelin,onkarshedge/incubator-zeppelin,Madhuka/incubator-zeppelin,chiwanpark/incubator-zeppelin,tinkoff-dwh/zeppelin,YuanGunGun/zeppelin,igorborojevic/incubator-zeppelin,mfelgamal/zeppelin,issaclee/silkroad,prabhjyotsingh/incubator-zeppelin,sctincman/zeppelin,r-kamath/zeppelin,Peaceful-learner/incubator-zeppelin,tillrohrmann/incubator-zeppelin,Leemoonsoo/incubator-zeppelin,SachinJanani/zeppelin,sergeymazin/zeppelin,soralee/zeppelin,apache/zeppelin,Madhuka/incubator-zeppelin,vardancse/incubator-zeppelin,opsun/incubator-zeppelin,keedio/incubator-zeppelin,omegapointresearch/incubator-zeppelin,MikeTYChen/incubator-zeppelin,anthonycorbacho/incubator-zeppelin,igorborojevic/incubator-zeppelin,vgmartinez/incubator-zeppelin,rconline/zeppelin,rozza/incubator-zeppelin,volumeint/zeppelin,sravan-s/zeppelin,fazlan-nazeem/incubator-zeppelin,huangchaosuper/incubator-zeppelin,cquptEthan/incubator-zeppelin,elbamos/Zeppelin-With-R,volumeint/zeppelin,rozza/incubator-zeppelin,kabong009/incubator-zeppelin,mwpenny/zeppelin-esri,kidaa/incubator-zeppelin,Leemoonsoo/incubator-zeppelin,yu74n/zeppelin,cquptEthan/incubator-zeppelin,prabhjyotsingh/zeppelin,catap/incubator-zeppelin,RamVenkatesh/incubator-zeppelin,fogbeam/zeppelin_mirror,cris83/incubator-zeppelin,mahantheshhv/incubator-zeppelin,prasadwagle/incubator-zeppelin,Yingmin-Li/incubator-zeppelin,raysteam/zeppelin,mahantheshhv/incubator-zeppelin,swakrish/incubator-zeppelin,fogbeam/zeppelin_mirror,wary/zeppelin,datalayer/zeppelin-R,EasonYi/incubator-zeppelin,r-kamath/zeppelin,prasadwagle/incubator-zeppelin,prasadwagle/incubator-zeppelin,kcompher/incubator-zeppelin,sohaibiftikhar/zeppelin,chiwanpark/incubator-zeppelin,debugger87/incubator-zeppelin,YuanGunGun/zeppelin,hboutemy/incubator-zeppelin,jyt109/incubator-zeppelin,cris11/incubator-zeppelin,cjmatta/incubator-zeppelin,Solution-Global/zeppelin,eranwitkon/incubator-zeppelin,Flipkart/incubator-zeppelin,jhshin9/incubator-zeppelin,mahantheshhv/incubator-zeppelin,sagarkulkarni3592/incubator-zeppelin,myrtleTree33/zeppelin,vipul1409/zeppelin,minahlee/incubator-zeppelin,cris11/incubator-zeppelin,chiwanpark/incubator-zeppelin,spacewalkman/incubator-zeppelin,xuyanhui/incubator-zeppelin,leancloud/zeppelin,ravicodder/incubator-zeppelin,tillrohrmann/incubator-zeppelin,tinkoff-dwh/zeppelin,fazlan-nazeem/incubator-zeppelin,yu74n/zeppelin,benoyantony/zeppelin,datalayer/zeppelin-R,xuyanhui/incubator-zeppelin,soralee/zeppelin,jhsbeat/incubator-zeppelin,felixcheung/incubator-zeppelin,vrajat/incubator-zeppelin,jlagarden/zeppelin,mwpenny/zeppelin-esri,vipul1409/zeppelin,EasonYi/incubator-zeppelin,fogbeam/zeppelin_mirror,dsdinter/incubator-zeppelin,sravan-s/zeppelin,apache/zeppelin,keedio/incubator-zeppelin,hboutemy/incubator-zeppelin,tillrohrmann/incubator-zeppelin,issaclee/silkroad,SachinJanani/zeppelin,leonardofoderaro/incubator-zeppelin,mfelgamal/zeppelin,suvam97/zeppelin,catap/incubator-zeppelin,datalayer/zeppelin,cfries/zeppelin,pellmont/zeppelin,apache/zeppelin,lresende/incubator-zeppelin,jongyoul/zeppelin,cjmatta/incubator-zeppelin,benoyantony/zeppelin,caofangkun/incubator-zeppelin,Altiscale/incubator-zeppelin,VipinRathor/zeppelin,Yingmin-Li/incubator-zeppelin,lresende/incubator-zeppelin,omegapointresearch/incubator-zeppelin,joroKr21/incubator-zeppelin,cris11/incubator-zeppelin,karuppayya/zeppelin,IceKhan13/zeppelin,ravicodder/incubator-zeppelin,blrunner/incubator-zeppelin,suvam97/zeppelin,RamVenkatesh/incubator-zeppelin,omegapointresearch/incubator-zeppelin,mfelgamal/zeppelin,hammertank/zeppelin,herval/zeppelin,AlexanderShoshin/zeppelin,wary/zeppelin,debugger87/incubator-zeppelin,apache/zeppelin,datalayer/zeppelin,Nova-Boy/zeppelin,Nova-Boy/zeppelin,ankurmitujjain/incubator-zeppelin,raysteam/zeppelin,HeartSaVioR/incubator-zeppelin,volumeint/zeppelin,myrtleTree33/zeppelin,openthings/zeppelin,apache/incubator-zeppelin,yorek/zeppelin,anthonycorbacho/incubator-zeppelin,tribbloid/incubator-zeppelin,yorek/zeppelin,bloomer1/incubator-zeppelin,rerngvit/incubator-zeppelin,IceKhan13/zeppelin,astroshim/incubator-zeppelin,minahlee/incubator-zeppelin,vipul1409/zeppelin,tzolov/incubator-zeppelin,jlagarden/zeppelin,YuanGunGun/zeppelin,lobamba/zeppelin,rerngvit/incubator-zeppelin,rconline/zeppelin,zjffdu/zeppelin,prabhjyotsingh/zeppelin,yorek/zeppelin,Madhuka/incubator-zeppelin,fazlan-nazeem/incubator-zeppelin,almacro/zeppelin-derived,dirceusemighini/incubator-zeppelin,rconline/zeppelin,herval/zeppelin,TelekomAustriaGroup/incubator-zeppelin,sohaibiftikhar/zeppelin,nkconnor/magellan,jyt109/incubator-zeppelin,Leemoonsoo/zeppelin,mfelgamal/zeppelin,djoelz/incubator-zeppelin,almacro/zeppelin-derived,onkarshedge/incubator-zeppelin,vrlo/zeppelin,wary/zeppelin,sagarkulkarni3592/incubator-zeppelin,openthings/zeppelin,suvam97/zeppelin,zetaris/zeppelin,vrlo/zeppelin,HeartSaVioR/incubator-zeppelin,MikeTYChen/incubator-zeppelin,huangchaosuper/incubator-zeppelin,datalayer/zeppelin-R,r-kamath/incubator-zeppelin,cris83/incubator-zeppelin,cfries/zeppelin,jlagarden/zeppelin,PeinYu/incubator-zeppelin,vgmartinez/incubator-zeppelin,bloomer1/incubator-zeppelin,mwpenny/zeppelin-esri,debugger87/incubator-zeppelin,digitalreasoning/incubator-zeppelin,leancloud/zeppelin,jlagarden/zeppelin,VipinRathor/zeppelin,prabhjyotsingh/zeppelin,mross-pivotal/incubator-zeppelin,ibtawfik/incubator-zeppelin,SachinJanani/zeppelin,rajeshkp/incubator-zeppelin,openthings/zeppelin,debugger87/incubator-zeppelin,jhsbeat/incubator-zeppelin,vrlo/zeppelin,hkropp/incubator-zeppelin,rozza/incubator-zeppelin,chilang/zeppelin,RPCMoritz/incubator-zeppelin,zjffdu/zeppelin,nkconnor/magellan,raysteam/zeppelin,lobamba/zeppelin,optimizely/incubator-zeppelin,zjffdu/zeppelin,jongyoul/zeppelin,vgmartinez/incubator-zeppelin,dirceusemighini/incubator-zeppelin,samuel-pt/incubator-zeppelin,SachinJanani/zeppelin,Leemoonsoo/incubator-zeppelin,sergeymazin/zeppelin,blrunner/incubator-zeppelin,wakamori/incubator-zeppelin,datalayer/zeppelin-datalayer,datalayer/zeppelin-R,nikste/incubator-zeppelin,fogbeam/fogbeam_zeppelin,catap/incubator-zeppelin,radicalbit/incubator-zeppelin,datalayer/zeppelin-datalayer,datalayer/zeppelin,tillrohrmann/incubator-zeppelin,doanduyhai/incubator-zeppelin,r-kamath/incubator-zeppelin,tinkoff-dwh/zeppelin,tillrohrmann/incubator-zeppelin,wakamori/incubator-zeppelin,IceKhan13/zeppelin,wary/zeppelin,rlugojr/incubator-zeppelin,debugger87/incubator-zeppelin,eranwitkon/incubator-zeppelin,piyush-mukati/incubator-zeppelin,joroKr21/incubator-zeppelin,raysteam/zeppelin,RPCMoritz/incubator-zeppelin,optimizely/incubator-zeppelin,TelekomAustriaGroup/incubator-zeppelin,namanmishra91/zeppelin,volumeint/zeppelin,astroshim/incubator-zeppelin,minahlee/zeppelin,vrajat/incubator-zeppelin,ankurmitujjain/incubator-zeppelin,elbamos/Zeppelin-With-R,granturing/incubator-zeppelin,jlagarden/zeppelin,joroKr21/incubator-zeppelin,Solution-Global/zeppelin,YuanGunGun/zeppelin,Nova-Boy/zeppelin,Madhuka/incubator-zeppelin,cfries/zeppelin,kabong009/incubator-zeppelin,mfelgamal/zeppelin,spacewalkman/incubator-zeppelin,anthonycorbacho/incubator-zeppelin,rookalkar/incubator-zeppelin,SarunasG/zeppelin-oidc,nkconnor/magellan,mwpenny/zeppelin-esri,swakrish/incubator-zeppelin,sagarkulkarni3592/incubator-zeppelin,rlugojr/incubator-zeppelin,tzolov/incubator-zeppelin,minahlee/zeppelin,chilang/zeppelin,prabhjyotsingh/incubator-zeppelin,minahlee/incubator-zeppelin,MikeTYChen/incubator-zeppelin,kcompher/incubator-zeppelin,joroKr21/incubator-zeppelin,djoelz/incubator-zeppelin,jongyoul/incubator-zeppelin,datalayer/zeppelin,suvam97/zeppelin,anthonycorbacho/incubator-zeppelin,leonardofoderaro/incubator-zeppelin,cris11/incubator-zeppelin,brigade/incubator-zeppelin,benoyantony/zeppelin,dsdinter/incubator-zeppelin,sergeymazin/zeppelin,hkropp/incubator-zeppelin,hboutemy/incubator-zeppelin,dirceusemighini/incubator-zeppelin,herval/zeppelin,rozza/incubator-zeppelin,wary/zeppelin,dsdinter/incubator-zeppelin,nikste/incubator-zeppelin,astroshim/incubator-zeppelin,issaclee/silkroad,doanduyhai/incubator-zeppelin,huangchaosuper/incubator-zeppelin,yu74n/zeppelin,Altiscale/incubator-zeppelin,namanmishra91/zeppelin,sravan-s/zeppelin,jongyoul/zeppelin,hkropp/incubator-zeppelin,astroshim/zeppelin,caofangkun/incubator-zeppelin,astroshim/zeppelin,cfries/zeppelin,BabbleGrabble/incubator-zeppelin-oauth2,hammertank/zeppelin,openthings/zeppelin,pellmont/zeppelin,karuppayya/zeppelin,Leemoonsoo/zeppelin,ravicodder/incubator-zeppelin,granturing/incubator-zeppelin,jlagarden/zeppelin,datalayer/zeppelin,keedio/incubator-zeppelin,benoyantony/zeppelin,optimizely/incubator-zeppelin,eranwitkon/incubator-zeppelin,Nova-Boy/zeppelin,sctincman/zeppelin,nikste/incubator-zeppelin,prasadwagle/incubator-zeppelin,Altiscale/incubator-zeppelin,myrtleTree33/zeppelin,mfelgamal/zeppelin,SarunasG/zeppelin-oidc,TelekomAustriaGroup/incubator-zeppelin,blrunner/incubator-zeppelin,rerngvit/incubator-zeppelin,ibtawfik/incubator-zeppelin,jongyoul/incubator-zeppelin,rerngvit/incubator-zeppelin,fogbeam/fogbeam_zeppelin,bloomer1/incubator-zeppelin,wakamori/incubator-zeppelin,vipul1409/zeppelin,TelekomAustriaGroup/incubator-zeppelin,ReeceRobinson/incubator-zeppelin,rajeshkp/incubator-zeppelin,swakrish/incubator-zeppelin,brigade/incubator-zeppelin,r-kamath/incubator-zeppelin,soralee/zeppelin,lresende/incubator-zeppelin,pellmont/zeppelin,hkropp/incubator-zeppelin,radicalbit/incubator-zeppelin,eranwitkon/incubator-zeppelin,rookalkar/incubator-zeppelin,astroshim/incubator-zeppelin,cris83/incubator-zeppelin,pellmont/zeppelin,joroKr21/incubator-zeppelin,EasonYi/incubator-zeppelin,Leemoonsoo/zeppelin,vgmartinez/incubator-zeppelin,myrtleTree33/zeppelin,spacewalkman/incubator-zeppelin,lresende/incubator-zeppelin,felixcheung/incubator-zeppelin,sctincman/zeppelin,VipinRathor/zeppelin,nikste/incubator-zeppelin,apache/zeppelin,ravicodder/incubator-zeppelin,rerngvit/incubator-zeppelin,almacro/zeppelin-derived,rlugojr/incubator-zeppelin,mwkang/zeppelin,tzolov/incubator-zeppelin,ravicodder/incubator-zeppelin,AlexanderShoshin/zeppelin,anthonycorbacho/incubator-zeppelin,soralee/zeppelin,optimizely/incubator-zeppelin,rlugojr/incubator-zeppelin,wakamori/incubator-zeppelin,sctincman/zeppelin,pellmont/zeppelin,ReeceRobinson/incubator-zeppelin,spacewalkman/incubator-zeppelin,openthings/zeppelin,sohaibiftikhar/zeppelin,1ambda/zeppelin,kidaa/incubator-zeppelin,minahlee/zeppelin,namanmishra91/zeppelin,almacro/zeppelin-derived,chiwanpark/incubator-zeppelin,opsun/incubator-zeppelin,ankurmitujjain/incubator-zeppelin,BabbleGrabble/incubator-zeppelin-oauth2,radicalbit/incubator-zeppelin,r-kamath/incubator-zeppelin,prasadwagle/incubator-zeppelin,jhshin9/incubator-zeppelin,jongyoul/incubator-zeppelin,jyt109/incubator-zeppelin,wakamori/incubator-zeppelin,raysteam/zeppelin,PeinYu/incubator-zeppelin,vrlo/zeppelin,galleon/incubator-zeppelin,tzolov/incubator-zeppelin,sravan-s/zeppelin,leancloud/zeppelin,jhshin9/incubator-zeppelin,IceKhan13/zeppelin,omegapointresearch/incubator-zeppelin,hammertank/zeppelin,zetaris/zeppelin,igorborojevic/incubator-zeppelin,BabbleGrabble/incubator-zeppelin-oauth2,leonardofoderaro/incubator-zeppelin,Leemoonsoo/incubator-zeppelin,ReeceRobinson/incubator-zeppelin,rajeshkp/incubator-zeppelin,djoelz/incubator-zeppelin,prabhjyotsingh/incubator-zeppelin,granturing/incubator-zeppelin,Madhuka/incubator-zeppelin,caofangkun/incubator-zeppelin,vrajat/incubator-zeppelin,hammertank/zeppelin,jongyoul/incubator-zeppelin,TelekomAustriaGroup/incubator-zeppelin,rconline/zeppelin,keedio/incubator-zeppelin,Peaceful-learner/incubator-zeppelin,apache/incubator-zeppelin,namanmishra91/zeppelin,tinkoff-dwh/zeppelin,vipul1409/zeppelin,volumeint/zeppelin,dirceusemighini/incubator-zeppelin,galleon/incubator-zeppelin,astroshim/zeppelin,SarunasG/zeppelin-oidc,yu74n/zeppelin,SachinJanani/zeppelin,r-kamath/zeppelin,prabhjyotsingh/zeppelin,AntoineAugusti/incubator-zeppelin,SarunasG/zeppelin-oidc,DataScienceX/incubator-zeppelin,chilang/zeppelin,EasonYi/incubator-zeppelin,Solution-Global/zeppelin,kabong009/incubator-zeppelin,datalayer/zeppelin-datalayer,kcompher/incubator-zeppelin,omegapointresearch/incubator-zeppelin,dsdinter/incubator-zeppelin,zetaris/zeppelin,cquptEthan/incubator-zeppelin,SachinJanani/zeppelin,cris11/incubator-zeppelin,lobamba/zeppelin,samuel-pt/incubator-zeppelin,benoyantony/zeppelin,felixcheung/incubator-zeppelin,sohaibiftikhar/zeppelin,mahantheshhv/incubator-zeppelin,r-kamath/zeppelin,granturing/incubator-zeppelin,fogbeam/fogbeam_zeppelin,SarunasG/zeppelin-oidc,YuanGunGun/zeppelin,minahlee/zeppelin,lresende/incubator-zeppelin,cquptEthan/incubator-zeppelin,sergeymazin/zeppelin,swakrish/incubator-zeppelin,brigade/incubator-zeppelin,ravicodder/incubator-zeppelin,jongyoul/zeppelin,soralee/zeppelin,rerngvit/incubator-zeppelin,piyush-mukati/incubator-zeppelin,mross-pivotal/incubator-zeppelin,RPCMoritz/incubator-zeppelin,apache/zeppelin,catap/incubator-zeppelin,tribbloid/incubator-zeppelin,radicalbit/incubator-zeppelin,fazlan-nazeem/incubator-zeppelin,leonardofoderaro/incubator-zeppelin,rohit2b/incubator-zeppelin,kcompher/incubator-zeppelin,igorborojevic/incubator-zeppelin,lobamba/zeppelin,minahlee/zeppelin,DataScienceX/incubator-zeppelin,RamVenkatesh/incubator-zeppelin,bloomer1/incubator-zeppelin,HeartSaVioR/incubator-zeppelin,fazlan-nazeem/incubator-zeppelin,raysteam/zeppelin,leancloud/zeppelin,lobamba/zeppelin,prasadwagle/incubator-zeppelin,caofangkun/incubator-zeppelin,BabbleGrabble/incubator-zeppelin-oauth2,rookalkar/incubator-zeppelin,cquptEthan/incubator-zeppelin,pravin-dsilva/zeppelin,apache/incubator-zeppelin,Solution-Global/zeppelin,doanduyhai/incubator-zeppelin,radicalbit/incubator-zeppelin,minahlee/zeppelin,onkarshedge/incubator-zeppelin,yorek/zeppelin,PeinYu/incubator-zeppelin,minahlee/zeppelin,Flipkart/incubator-zeppelin,volumeint/zeppelin,nkconnor/magellan,tinkoff-dwh/zeppelin,Flipkart/incubator-zeppelin,chilang/zeppelin,sergeymazin/zeppelin,astroshim/incubator-zeppelin,huangchaosuper/incubator-zeppelin,rerngvit/incubator-zeppelin,huangchaosuper/incubator-zeppelin,rohit2b/incubator-zeppelin,soralee/zeppelin,yu74n/zeppelin,samuel-pt/incubator-zeppelin,PeinYu/incubator-zeppelin,AntoineAugusti/incubator-zeppelin,zjffdu/zeppelin,prabhjyotsingh/zeppelin,optimizely/incubator-zeppelin,digitalreasoning/incubator-zeppelin,Yingmin-Li/incubator-zeppelin,HeartSaVioR/incubator-zeppelin,elbamos/Zeppelin-With-R,caofangkun/incubator-zeppelin,kcompher/incubator-zeppelin,zjffdu/zeppelin,zjffdu/zeppelin,YuanGunGun/zeppelin,mwpenny/zeppelin-esri,herval/zeppelin,kabong009/incubator-zeppelin,IceKhan13/zeppelin,ibtawfik/incubator-zeppelin,openthings/zeppelin,fogbeam/zeppelin_mirror,Altiscale/incubator-zeppelin,sctincman/zeppelin,rohit2b/incubator-zeppelin,suvam97/zeppelin,granturing/incubator-zeppelin,vardancse/incubator-zeppelin,jyt109/incubator-zeppelin,astroshim/incubator-zeppelin,apache/zeppelin,spacewalkman/incubator-zeppelin,jongyoul/incubator-zeppelin,rconline/zeppelin,sctincman/zeppelin,VipinRathor/zeppelin,pravin-dsilva/zeppelin,sohaibiftikhar/zeppelin,radicalbit/incubator-zeppelin,swakrish/incubator-zeppelin,r-kamath/incubator-zeppelin,VipinRathor/zeppelin,ankurmitujjain/incubator-zeppelin,hboutemy/incubator-zeppelin,almacro/zeppelin-derived,digitalreasoning/incubator-zeppelin,galleon/incubator-zeppelin,rozza/incubator-zeppelin,digitalreasoning/incubator-zeppelin,zetaris/zeppelin,anthonycorbacho/incubator-zeppelin,Nova-Boy/zeppelin,ankurmitujjain/incubator-zeppelin,eranwitkon/incubator-zeppelin,herval/zeppelin,1ambda/zeppelin,suvam97/zeppelin,YuanGunGun/zeppelin,nkconnor/magellan,Yingmin-Li/incubator-zeppelin,ibtawfik/incubator-zeppelin,doanduyhai/incubator-zeppelin,pravin-dsilva/zeppelin,Peaceful-learner/incubator-zeppelin,sohaibiftikhar/zeppelin,joroKr21/incubator-zeppelin,astroshim/zeppelin,datalayer/zeppelin-datalayer,BabbleGrabble/incubator-zeppelin-oauth2,Solution-Global/zeppelin,chiwanpark/incubator-zeppelin,suvam97/zeppelin,vgmartinez/incubator-zeppelin,digitalreasoning/incubator-zeppelin,apache/incubator-zeppelin,vardancse/incubator-zeppelin,issaclee/silkroad,sravan-s/zeppelin,rookalkar/incubator-zeppelin,pravin-dsilva/zeppelin,Leemoonsoo/zeppelin,AntoineAugusti/incubator-zeppelin,AlexanderShoshin/zeppelin,Leemoonsoo/zeppelin,rlugojr/incubator-zeppelin,lresende/incubator-zeppelin,AntoineAugusti/incubator-zeppelin,mross-pivotal/incubator-zeppelin,DataScienceX/incubator-zeppelin,anthonycorbacho/incubator-zeppelin,sravan-s/zeppelin,vrajat/incubator-zeppelin,issaclee/silkroad,samuel-pt/incubator-zeppelin,karuppayya/zeppelin,minahlee/incubator-zeppelin,1ambda/zeppelin,cjmatta/incubator-zeppelin,jlagarden/zeppelin,jhshin9/incubator-zeppelin,Altiscale/incubator-zeppelin,yorek/zeppelin,VipinRathor/zeppelin,digitalreasoning/incubator-zeppelin,AlexanderShoshin/zeppelin,rohit2b/incubator-zeppelin,sagarkulkarni3592/incubator-zeppelin,1ambda/zeppelin,xuyanhui/incubator-zeppelin,r-kamath/incubator-zeppelin,datalayer/zeppelin,Peaceful-learner/incubator-zeppelin,hammertank/zeppelin,cjmatta/incubator-zeppelin,Flipkart/incubator-zeppelin,mross-pivotal/incubator-zeppelin,blrunner/incubator-zeppelin,Yingmin-Li/incubator-zeppelin,myrtleTree33/zeppelin,leonardofoderaro/incubator-zeppelin,AlexanderShoshin/zeppelin,Altiscale/incubator-zeppelin,herval/zeppelin,pellmont/zeppelin,fogbeam/fogbeam_zeppelin,granturing/incubator-zeppelin,HeartSaVioR/incubator-zeppelin,cjmatta/incubator-zeppelin,yu74n/zeppelin,sravan-s/zeppelin,tribbloid/incubator-zeppelin,Leemoonsoo/zeppelin,vipul1409/zeppelin,tinkoff-dwh/zeppelin,1ambda/zeppelin,1ambda/zeppelin,raysteam/zeppelin,rookalkar/incubator-zeppelin,tzolov/incubator-zeppelin,tribbloid/incubator-zeppelin,mwkang/zeppelin,jhshin9/incubator-zeppelin,joroKr21/incubator-zeppelin,hkropp/incubator-zeppelin,minahlee/incubator-zeppelin,RamVenkatesh/incubator-zeppelin,zetaris/zeppelin,IceKhan13/zeppelin,Leemoonsoo/zeppelin,spacewalkman/incubator-zeppelin,r-kamath/zeppelin,MikeTYChen/incubator-zeppelin,bloomer1/incubator-zeppelin,Leemoonsoo/incubator-zeppelin,herval/zeppelin,cquptEthan/incubator-zeppelin,brigade/incubator-zeppelin,ravicodder/incubator-zeppelin,openthings/zeppelin,prasadwagle/incubator-zeppelin,piyush-mukati/incubator-zeppelin,fazlan-nazeem/incubator-zeppelin,zetaris/zeppelin,sergeymazin/zeppelin,mwkang/zeppelin,jongyoul/zeppelin,mwpenny/zeppelin-esri,spacewalkman/incubator-zeppelin,yorek/zeppelin,astroshim/zeppelin,jhsbeat/incubator-zeppelin,karuppayya/zeppelin,mross-pivotal/incubator-zeppelin,igorborojevic/incubator-zeppelin,cjmatta/incubator-zeppelin,HeartSaVioR/incubator-zeppelin,jongyoul/incubator-zeppelin,Solution-Global/zeppelin,wakamori/incubator-zeppelin,prabhjyotsingh/incubator-zeppelin,Flipkart/incubator-zeppelin,IceKhan13/zeppelin,radicalbit/incubator-zeppelin,rajeshkp/incubator-zeppelin,AlexanderShoshin/zeppelin,yorek/zeppelin,Madhuka/incubator-zeppelin,Leemoonsoo/zeppelin,samuel-pt/incubator-zeppelin,vardancse/incubator-zeppelin,galleon/incubator-zeppelin,cfries/zeppelin,vrlo/zeppelin,brigade/incubator-zeppelin,rohit2b/incubator-zeppelin,ankurmitujjain/incubator-zeppelin,tillrohrmann/incubator-zeppelin,RPCMoritz/incubator-zeppelin,SarunasG/zeppelin-oidc,elbamos/Zeppelin-With-R,onkarshedge/incubator-zeppelin,vrlo/zeppelin,doanduyhai/incubator-zeppelin,felixcheung/incubator-zeppelin,MikeTYChen/incubator-zeppelin,igorborojevic/incubator-zeppelin,optimizely/incubator-zeppelin,SachinJanani/zeppelin,apache/incubator-zeppelin,cfries/zeppelin,vrajat/incubator-zeppelin,vgmartinez/incubator-zeppelin,rajeshkp/incubator-zeppelin,blrunner/incubator-zeppelin,namanmishra91/zeppelin,prabhjyotsingh/zeppelin,swakrish/incubator-zeppelin,jhsbeat/incubator-zeppelin,rconline/zeppelin,fogbeam/zeppelin_mirror,lobamba/zeppelin,onkarshedge/incubator-zeppelin,chilang/zeppelin,zjffdu/zeppelin,fogbeam/zeppelin_mirror,cris83/incubator-zeppelin,kabong009/incubator-zeppelin,granturing/incubator-zeppelin,lobamba/zeppelin,nikste/incubator-zeppelin,jyt109/incubator-zeppelin,pravin-dsilva/zeppelin,cquptEthan/incubator-zeppelin,sagarkulkarni3592/incubator-zeppelin,sergeymazin/zeppelin,benoyantony/zeppelin,datalayer/zeppelin-R,prabhjyotsingh/incubator-zeppelin,RamVenkatesh/incubator-zeppelin,datalayer/zeppelin,dirceusemighini/incubator-zeppelin,fogbeam/zeppelin_mirror,tinkoff-dwh/zeppelin,prabhjyotsingh/zeppelin,r-kamath/zeppelin,ReeceRobinson/incubator-zeppelin,SarunasG/zeppelin-oidc,nikste/incubator-zeppelin,AlexanderShoshin/zeppelin,pravin-dsilva/zeppelin,astroshim/zeppelin,sagarkulkarni3592/incubator-zeppelin,felixcheung/incubator-zeppelin,karuppayya/zeppelin,karuppayya/zeppelin,Nova-Boy/zeppelin,cris11/incubator-zeppelin,namanmishra91/zeppelin,hammertank/zeppelin,elbamos/Zeppelin-With-R,volumeint/zeppelin,TelekomAustriaGroup/incubator-zeppelin,hboutemy/incubator-zeppelin,mwpenny/zeppelin-esri,optimizely/incubator-zeppelin,tribbloid/incubator-zeppelin,opsun/incubator-zeppelin,jongyoul/zeppelin,piyush-mukati/incubator-zeppelin,hammertank/zeppelin,mwkang/zeppelin,catap/incubator-zeppelin,AntoineAugusti/incubator-zeppelin,djoelz/incubator-zeppelin,cris83/incubator-zeppelin,tzolov/incubator-zeppelin,lresende/incubator-zeppelin,VipinRathor/zeppelin,cfries/zeppelin,hkropp/incubator-zeppelin,doanduyhai/incubator-zeppelin,RamVenkatesh/incubator-zeppelin,kidaa/incubator-zeppelin,keedio/incubator-zeppelin,piyush-mukati/incubator-zeppelin,opsun/incubator-zeppelin,ReeceRobinson/incubator-zeppelin,digitalreasoning/incubator-zeppelin,karuppayya/zeppelin,brigade/incubator-zeppelin,opsun/incubator-zeppelin,tillrohrmann/incubator-zeppelin,elbamos/Zeppelin-With-R,xuyanhui/incubator-zeppelin,cris83/incubator-zeppelin,wary/zeppelin,pravin-dsilva/zeppelin,ibtawfik/incubator-zeppelin,Solution-Global/zeppelin,fogbeam/fogbeam_zeppelin,rconline/zeppelin,vrajat/incubator-zeppelin,chilang/zeppelin,sctincman/zeppelin,mwkang/zeppelin,prabhjyotsingh/incubator-zeppelin,MikeTYChen/incubator-zeppelin,zetaris/zeppelin,samuel-pt/incubator-zeppelin,r-kamath/zeppelin,ankurmitujjain/incubator-zeppelin,sagarkulkarni3592/incubator-zeppelin,vrlo/zeppelin,kidaa/incubator-zeppelin,mwkang/zeppelin,djoelz/incubator-zeppelin,xuyanhui/incubator-zeppelin,mfelgamal/zeppelin,vardancse/incubator-zeppelin,soralee/zeppelin,DataScienceX/incubator-zeppelin
/* global $:false, jQuery:false, ace:false, confirm:false, d3:false, nv:false*/ /*jshint loopfunc: true, unused:false */ /* Copyright 2014 NFLabs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * @ngdoc function * @name zeppelinWebApp.controller:ParagraphCtrl * @description * # ParagraphCtrl * Controller of the paragraph, manage everything related to the paragraph * * @author anthonycorbacho */ angular.module('zeppelinWebApp') .controller('ParagraphCtrl', function($scope, $rootScope, $route, $window, $element, $routeParams, $location, $timeout) { $scope.paragraph = null; $scope.editor = null; var editorMode = {scala: 'ace/mode/scala', sql: 'ace/mode/sql', markdown: 'ace/mode/markdown'}; // Controller init $scope.init = function(newParagraph) { $scope.paragraph = newParagraph; $scope.chart = {}; $scope.colWidthOption = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]; $scope.showTitleEditor = false; if (!$scope.paragraph.config) { $scope.paragraph.config = {}; } initializeDefault(); if (!$scope.lastData) { $scope.lastData = {}; } if ($scope.getResultType() === 'TABLE') { $scope.lastData.settings = jQuery.extend(true, {}, $scope.paragraph.settings); $scope.lastData.config = jQuery.extend(true, {}, $scope.paragraph.config); $scope.loadTableData($scope.paragraph.result); $scope.setGraphMode($scope.getGraphMode(), false, false); } else if ($scope.getResultType() === 'HTML') { $scope.renderHtml(); } }; $scope.renderHtml = function() { var retryRenderer = function(){ if($('#p'+$scope.paragraph.id+'_html').length){ try { $('#p'+$scope.paragraph.id+'_html').html($scope.paragraph.result.msg); } catch(err) { console.log('HTML rendering error %o', err); } } else { $timeout(retryRenderer,10); } }; $timeout(retryRenderer); }; var initializeDefault = function(){ var config = $scope.paragraph.config; if (!config.looknfeel) { config.looknfeel = 'default'; } if (!config.colWidth) { config.colWidth = 12; } if(!config.graph){ config.graph = {}; } if (!config.graph.mode) { config.graph.mode = 'table'; } if (!config.graph.height) { config.graph.height = 300; } if (!config.graph.optionOpen) { config.graph.optionOpen = false; } if (!config.graph.keys) { config.graph.keys = []; } if (!config.graph.values) { config.graph.values = []; } if (!config.graph.groups) { config.graph.groups = []; } }; $scope.getIframeDimensions = function () { if ($scope.asIframe) { var paragraphid = '#' + $routeParams.paragraphId + '_container'; var height = $(paragraphid).height(); return height; } return 0; }; $scope.$watch($scope.getIframeDimensions, function (newValue, oldValue) { if ($scope.asIframe && newValue) { var message = {}; message.height = newValue; message.url = $location.$$absUrl; $window.parent.postMessage(angular.toJson(message), '*'); } }); // TODO: this may have impact on performance when there are many paragraphs in a note. $rootScope.$on('updateParagraph', function(event, data) { if (data.paragraph.id === $scope.paragraph.id && ( data.paragraph.dateCreated !== $scope.paragraph.dateCreated || data.paragraph.dateFinished !== $scope.paragraph.dateFinished || data.paragraph.dateStarted !== $scope.paragraph.dateStarted || data.paragraph.status !== $scope.paragraph.status || data.paragraph.jobName !== $scope.paragraph.jobName || data.paragraph.title !== $scope.paragraph.title || data.paragraph.errorMessage !== $scope.paragraph.errorMessage || !angular.equals(data.paragraph.settings, $scope.lastData.settings) || !angular.equals(data.paragraph.config, $scope.lastData.config) ) ) { // store original data for comparison $scope.lastData.settings = jQuery.extend(true, {}, data.paragraph.settings); $scope.lastData.config = jQuery.extend(true, {}, data.paragraph.config); var oldType = $scope.getResultType(); var newType = $scope.getResultType(data.paragraph); var oldGraphMode = $scope.getGraphMode(); var newGraphMode = $scope.getGraphMode(data.paragraph); var resultRefreshed = (data.paragraph.dateFinished !== $scope.paragraph.dateFinished); //console.log("updateParagraph oldData %o, newData %o. type %o -> %o, mode %o -> %o", $scope.paragraph, data, oldType, newType, oldGraphMode, newGraphMode); if ($scope.paragraph.text !== data.paragraph.text) { if ($scope.dirtyText) { // check if editor has local update if ($scope.dirtyText === data.paragraph.text ) { // when local update is the same from remote, clear local update $scope.paragraph.text = data.paragraph.text; $scope.dirtyText = undefined; } else { // if there're local update, keep it. $scope.paragraph.text = $scope.dirtyText; } } else { $scope.paragraph.text = data.paragraph.text; } } /** push the rest */ $scope.paragraph.aborted = data.paragraph.aborted; $scope.paragraph.dateCreated = data.paragraph.dateCreated; $scope.paragraph.dateFinished = data.paragraph.dateFinished; $scope.paragraph.dateStarted = data.paragraph.dateStarted; $scope.paragraph.errorMessage = data.paragraph.errorMessage; $scope.paragraph.jobName = data.paragraph.jobName; $scope.paragraph.title = data.paragraph.title; $scope.paragraph.status = data.paragraph.status; $scope.paragraph.result = data.paragraph.result; $scope.paragraph.settings = data.paragraph.settings; if (!$scope.asIframe) { $scope.paragraph.config = data.paragraph.config; initializeDefault(); } else { data.paragraph.config.editorHide = true; data.paragraph.config.tableHide = false; $scope.paragraph.config = data.paragraph.config; } if (newType==='TABLE') { $scope.loadTableData($scope.paragraph.result); if (oldType!=='TABLE' || resultRefreshed) { clearUnknownColsFromGraphOption(); selectDefaultColsForGraphOption(); } /** User changed the chart type? */ if (oldGraphMode !== newGraphMode) { $scope.setGraphMode(newGraphMode, false, false); } else { $scope.setGraphMode(newGraphMode, false, true); } } else if (newType==='HTML') { $scope.renderHtml(); } } }); $scope.isRunning = function(){ if($scope.paragraph.status==='RUNNING' || $scope.paragraph.status==='PENDING') { return true; } else { return false; } }; $scope.cancelParagraph = function() { console.log('Cancel %o', $scope.paragraph.id); var data = {op: 'CANCEL_PARAGRAPH', data: {id: $scope.paragraph.id }}; $rootScope.$emit('sendNewEvent', data); }; $scope.runParagraph = function(data) { var parapgraphData = {op: 'RUN_PARAGRAPH', data: { id: $scope.paragraph.id, title: $scope.paragraph.title, paragraph: data, config: $scope.paragraph.config, params: $scope.paragraph.settings.params } }; $rootScope.$emit('sendNewEvent', parapgraphData); }; $scope.moveUp = function() { $rootScope.$emit('moveParagraphUp', $scope.paragraph.id); }; $scope.moveDown = function() { $rootScope.$emit('moveParagraphDown', $scope.paragraph.id); }; $scope.insertNew = function() { $rootScope.$emit('insertParagraph', $scope.paragraph.id); }; $scope.removeParagraph = function() { var result = confirm('Do you want to delete this paragraph?'); if (result) { console.log('Remove paragraph'); var paragraphData = {op: 'PARAGRAPH_REMOVE', data: {id: $scope.paragraph.id}}; $rootScope.$emit('sendNewEvent', paragraphData); } }; $scope.toggleEditor = function() { if ($scope.paragraph.config.editorHide) { $scope.openEditor(); } else { $scope.closeEditor(); } }; $scope.closeEditor = function() { console.log('close the note'); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.editorHide = true; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.openEditor = function() { console.log('open the note'); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.editorHide = false; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.closeTable = function() { console.log('close the output'); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.tableHide = true; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.openTable = function() { console.log('open the output'); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.tableHide = false; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.showTitle = function() { var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.title = true; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.hideTitle = function() { var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.title = false; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.setTitle = function() { var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.columnWidthClass = function(n){ if($scope.asIframe){ return 'col-md-12'; } else { return 'col-md-' + n; } } $scope.changeColWidth = function() { var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.toggleGraphOption = function() { var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); if (newConfig.graph.optionOpen) { newConfig.graph.optionOpen = false; } else { newConfig.graph.optionOpen = true; } var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.toggleOutput = function() { var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.tableHide = !newConfig.tableHide; var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.loadForm = function(formulaire, params) { var value = formulaire.defaultValue; if (params[formulaire.name]) { value = params[formulaire.name]; } if (value === '') { value = formulaire.options[0].value; } $scope.paragraph.settings.params[formulaire.name] = value; }; $scope.aceChanged = function() { $scope.dirtyText = $scope.editor.getSession().getValue(); }; $scope.aceLoaded = function(_editor) { var langTools = ace.require('ace/ext/language_tools'); var Range = ace.require('ace/range').Range; $scope.editor = _editor; if (_editor.container.id !== '{{paragraph.id}}_editor') { $scope.editor.renderer.setShowGutter(false); $scope.editor.setHighlightActiveLine(false); $scope.editor.focus(); var hight = $scope.editor.getSession().getScreenLength() * $scope.editor.renderer.lineHeight + $scope.editor.renderer.scrollBar.getWidth(); setEditorHeight(_editor.container.id, hight); $scope.editor.getSession().setUseWrapMode(true); if (navigator.appVersion.indexOf('Mac') !== -1 ) { $scope.editor.setKeyboardHandler('ace/keyboard/emacs'); } else if (navigator.appVersion.indexOf('Win') !== -1 || navigator.appVersion.indexOf('X11') !== -1 || navigator.appVersion.indexOf('Linux') !== -1) { // not applying emacs key binding while the binding override Ctrl-v. default behavior of paste text on windows. } $scope.editor.setOptions({ enableBasicAutocompletion: true, enableSnippets: false, enableLiveAutocompletion:false }); var remoteCompleter = { getCompletions : function(editor, session, pos, prefix, callback) { if (!$scope.editor.isFocused() ){ return;} var buf = session.getTextRange(new Range(0, 0, pos.row, pos.column)); $rootScope.$emit('sendNewEvent', { op : 'COMPLETION', data : { id : $scope.paragraph.id, buf : buf, cursor : buf.length } }); $rootScope.$on('completionList', function(event, data) { if (data.completions) { var completions = []; for(var c in data.completions){ var v = data.completions[c]; completions.push({ name:v, value:v, score:300 }); } callback(null, completions); } }); } }; langTools.addCompleter(remoteCompleter); $scope.editor.on('focus', function(){ var el = $('#' + $scope.paragraph.id + '_paragraphColumn'); el.addClass('focused'); }); $scope.editor.on('blur', function(){ var el = $('#' + $scope.paragraph.id + '_paragraphColumn'); el.removeClass('focused'); }); $scope.editor.getSession().on('change', function(e, editSession) { hight = editSession.getScreenLength() * $scope.editor.renderer.lineHeight + $scope.editor.renderer.scrollBar.getWidth(); setEditorHeight(_editor.container.id, hight); $scope.editor.resize(); }); var code = $scope.editor.getSession().getValue(); if ( String(code).startsWith('%sql')) { $scope.editor.getSession().setMode(editorMode.sql); } else if ( String(code).startsWith('%md')) { $scope.editor.getSession().setMode(editorMode.markdown); } else { $scope.editor.getSession().setMode(editorMode.scala); } $scope.editor.commands.addCommand({ name: 'run', bindKey: {win: 'Shift-Enter', mac: 'Shift-Enter'}, exec: function(editor) { var editorValue = editor.getValue(); if (editorValue) { $scope.runParagraph(editorValue); } }, readOnly: false }); // autocomplete on '.' /* $scope.editor.commands.on("afterExec", function(e, t) { if (e.command.name == "insertstring" && e.args == "." ) { var all = e.editor.completers; //e.editor.completers = [remoteCompleter]; e.editor.execCommand("startAutocomplete"); //e.editor.completers = all; } }); */ // autocomplete on 'ctrl+.' $scope.editor.commands.bindKey('ctrl-.', 'startAutocomplete'); $scope.editor.commands.bindKey('ctrl-space', null); // handle cursor moves $scope.editor.keyBinding.origOnCommandKey = $scope.editor.keyBinding.onCommandKey; $scope.editor.keyBinding.onCommandKey = function(e, hashId, keyCode) { if($scope.editor.completer && $scope.editor.completer.activated) { // if autocompleter is active } else { var numRows; var currentRow; if(keyCode===38 || (keyCode===80 && e.ctrlKey)){ // UP numRows = $scope.editor.getSession().getLength(); currentRow = $scope.editor.getCursorPosition().row; if(currentRow===0){ // move focus to previous paragraph $rootScope.$emit('moveFocusToPreviousParagraph', $scope.paragraph.id); } } else if(keyCode===40 || (keyCode===78 && e.ctrlKey)){ // DOWN numRows = $scope.editor.getSession().getLength(); currentRow = $scope.editor.getCursorPosition().row; if(currentRow === numRows-1){ // move focus to next paragraph $rootScope.$emit('moveFocusToNextParagraph', $scope.paragraph.id); } } } this.origOnCommandKey(e, hashId, keyCode); }; } }; var setEditorHeight = function(id, height) { $('#' + id).height(height.toString() + 'px'); }; $scope.getEditorValue = function() { return $scope.editor.getValue(); }; $scope.getProgress = function(){ return ($scope.currentProgress) ? $scope.currentProgress : 0; }; $scope.getExecutionTime = function() { var pdata = $scope.paragraph; var timeMs = Date.parse(pdata.dateFinished) - Date.parse(pdata.dateStarted); return 'Took ' + (timeMs/1000) + ' seconds'; }; $rootScope.$on('updateProgress', function(event, data) { if (data.id === $scope.paragraph.id) { $scope.currentProgress = data.progress; } }); $rootScope.$on('focusParagraph', function(event, paragraphId){ if ($scope.paragraph.id === paragraphId) { $scope.editor.focus(); $('body').scrollTo('#'+paragraphId+'_editor', 300, {offset:-60}); } }); $rootScope.$on('runParagraph', function(event){ $scope.runParagraph($scope.editor.getValue()); }); $rootScope.$on('openEditor', function(event){ $scope.openEditor(); }); $rootScope.$on('closeEditor', function(event){ $scope.closeEditor(); }); $rootScope.$on('openTable', function(event){ $scope.openTable(); }); $rootScope.$on('closeTable', function(event){ $scope.closeTable(); }); $scope.getResultType = function(paragraph){ var pdata = (paragraph) ? paragraph : $scope.paragraph; if (pdata.result && pdata.result.type) { return pdata.result.type; } else { return 'TEXT'; } }; $scope.getBase64ImageSrc = function(base64Data) { return 'data:image/png;base64,'+base64Data; }; $scope.getGraphMode = function(paragraph){ var pdata = (paragraph) ? paragraph : $scope.paragraph; if (pdata.config.graph && pdata.config.graph.mode) { return pdata.config.graph.mode; } else { return 'table'; } }; $scope.loadTableData = function(result) { if (!result) { return; } if (result.type === 'TABLE') { var columnNames = []; var rows = []; var array = []; var textRows = result.msg.split('\n'); result.comment = ''; var comment = false; for (var i = 0; i < textRows.length; i++) { var textRow = textRows[i]; if (comment) { result.comment += textRow; continue; } if (textRow === '') { if (rows.length>0) { comment = true; } continue; } var textCols = textRow.split('\t'); var cols = []; var cols2 = []; for (var j = 0; j < textCols.length; j++) { var col = textCols[j]; if (i === 0) { columnNames.push({name:col, index:j, aggr:'sum'}); } else { cols.push(col); cols2.push({key: (columnNames[i]) ? columnNames[i].name: undefined, value: col}); } } if (i !== 0) { rows.push(cols); array.push(cols2); } } result.msgTable = array; result.columnNames = columnNames; result.rows = rows; } }; $scope.setGraphMode = function(type, emit, refresh) { if (emit) { setNewMode(type); } else { clearUnknownColsFromGraphOption(); // set graph height var height = $scope.paragraph.config.graph.height; $('#p'+$scope.paragraph.id+'_graph').height(height); if (!type || type === 'table') { setTable($scope.paragraph.result, refresh); } else if (type === 'multiBarChart') { setD3Chart(type, $scope.paragraph.result, refresh); } else if (type === 'pieChart') { setD3Chart(type, $scope.paragraph.result, refresh); } else if (type === 'stackedAreaChart') { setD3Chart(type, $scope.paragraph.result, refresh); } else if (type === 'lineChart') { setD3Chart(type, $scope.paragraph.result, refresh); } } }; var setNewMode = function(newMode) { var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); // graph options newConfig.graph.mode = newMode; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; var commitParagraph = function(title, text, config, params) { var parapgraphData = { op: 'COMMIT_PARAGRAPH', data: { id: $scope.paragraph.id, title : title, paragraph: text, params: params, config: config }}; $rootScope.$emit('sendNewEvent', parapgraphData); }; var setTable = function(type, data, refresh) { var getTableContentFormat = function(d) { if (isNaN(d)) { if(d.length>'%html'.length && '%html '===d.substring(0, '%html '.length)) { return 'html'; } else { return ''; } } else { return ''; } }; var formatTableContent = function(d) { if (isNaN(d)) { var f = getTableContentFormat(d); if(f !=='') { return d.substring(f.length+2); } else { return d; } } else { var dStr = d.toString(); var splitted = dStr.split('.'); var formatted = splitted[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); if (splitted.length>1) { formatted+= '.'+splitted[1]; } return formatted; } }; var renderTable = function(){ var html = ''; html += '<table class="table table-hover table-condensed">'; html += ' <thead>'; html += ' <tr style="background-color: #F6F6F6; font-weight: bold;">'; for (var c in $scope.paragraph.result.columnNames) { html += '<th>'+$scope.paragraph.result.columnNames[c].name+'</th>'; } html += ' </tr>'; html += ' </thead>'; for (var r in $scope.paragraph.result.msgTable) { var row = $scope.paragraph.result.msgTable[r]; html += ' <tr>'; for (var index in row) { var v = row[index].value; if(getTableContentFormat(v) !== 'html') { v = v.replace(/[\u00A0-\u9999<>\&]/gim, function(i) { return '&#'+i.charCodeAt(0)+';'; }); } html += ' <td>'+formatTableContent(v)+'</td>'; } html += ' </tr>'; } html += '</table>'; $('#p' + $scope.paragraph.id + '_table').html(html); $('#p' + $scope.paragraph.id + '_table').perfectScrollbar(); // set table height var height = $scope.paragraph.config.graph.height; $('#p'+$scope.paragraph.id+'_table').height(height); }; var retryRenderer = function(){ if($('#p'+$scope.paragraph.id+'_table').length){ try { renderTable(); } catch(err) { console.log('Chart drawing error %o', err); } } else { $timeout(retryRenderer,10); } }; $timeout(retryRenderer); }; var setD3Chart = function(type, data, refresh) { if (!$scope.chart[type]) { var chart = nv.models[type](); $scope.chart[type] = chart; } var p = pivot(data); var xColIndexes = $scope.paragraph.config.graph.keys; var yColIndexes = $scope.paragraph.config.graph.values; var d3g = []; // select yColumns. if (type==='pieChart') { var d = pivotDataToD3ChartFormat(p, true).d3g; $scope.chart[type].x(function(d){ return d.label;}) .y(function(d){ return d.value;}); if ( d.length > 0 ) { for ( var i=0; i<d[0].values.length ; i++) { var e = d[0].values[i]; d3g.push({ label : e.x, value : e.y }); } } } else if (type==='multiBarChart') { d3g = pivotDataToD3ChartFormat(p, true).d3g; $scope.chart[type].yAxis.axisLabelDistance(50); } else { var pivotdata = pivotDataToD3ChartFormat(p, false, true); var xLabels = pivotdata.xLabels; d3g = pivotdata.d3g; $scope.chart[type].xAxis.tickFormat(function(d) { if (xLabels[d] && (isNaN(parseFloat(xLabels[d])) || !isFinite(xLabels[d]))) { // to handle string type xlabel return xLabels[d]; } else { return d; } }); $scope.chart[type].yAxis.axisLabelDistance(50); $scope.chart[type].useInteractiveGuideline(true); // for better UX and performance issue. (https://github.com/novus/nvd3/issues/691) $scope.chart[type].forceY([0]); // force y-axis minimum to 0 for line chart. } var renderChart = function(){ if (!refresh) { // TODO force destroy previous chart } var height = $scope.paragraph.config.graph.height; var animationDuration = 300; var numberOfDataThreshold = 150; // turn off animation when dataset is too large. (for performance issue) // still, since dataset is large, the chart content sequentially appears like animated. try { if (d3g[0].values.length > numberOfDataThreshold) { animationDuration = 0; } } catch(ignoreErr) { } var chartEl = d3.select('#p'+$scope.paragraph.id+'_'+type+' svg') .attr('height', $scope.paragraph.config.graph.height) .datum(d3g) .transition() .duration(animationDuration) .call($scope.chart[type]); d3.select('#p'+$scope.paragraph.id+'_'+type+' svg').style.height = height+'px'; nv.utils.windowResize($scope.chart[type].update); }; var retryRenderer = function(){ if($('#p'+$scope.paragraph.id+'_'+type+' svg').length!==0){ try { renderChart(); } catch(err) { console.log('Chart drawing error %o', err); } } else { $timeout(retryRenderer,10); } }; $timeout(retryRenderer); }; var setPieChart = function(data, refresh) { var xColIndex = 0; var yColIndexes = []; var d3g = []; // select yColumns. for (var colIndex = 0; colIndex < data.columnNames.length; colIndex++) { if (colIndex !== xColIndex) { yColIndexes.push(colIndex); } } for (var rowIndex = 0; rowIndex < data.rows.length; rowIndex++) { var row = data.rows[rowIndex]; var xVar = row[xColIndex]; var yVar = row[yColIndexes[0]]; d3g.push({ label: isNaN(xVar) ? xVar : parseFloat(xVar), value: parseFloat(yVar) }); } if ($scope.d3.pieChart.data === null || !refresh) { $scope.d3.pieChart.data = d3g; $scope.d3.pieChart.options.chart.height = $scope.paragraph.config.graph.height; if ($scope.d3.pieChart.api) { $scope.d3.pieChart.api.updateWithOptions($scope.d3.pieChart.options); } } else { if ($scope.d3.pieChart.api) { $scope.d3.pieChart.api.updateWithData(d3g); } } }; $scope.isGraphMode = function(graphName) { if ($scope.getResultType() === 'TABLE' && $scope.getGraphMode()===graphName) { return true; } else { return false; } }; $scope.onGraphOptionChange = function() { clearUnknownColsFromGraphOption(); $scope.setGraphMode($scope.paragraph.config.graph.mode, true, false); }; $scope.removeGraphOptionKeys = function(idx) { $scope.paragraph.config.graph.keys.splice(idx, 1); clearUnknownColsFromGraphOption(); $scope.setGraphMode($scope.paragraph.config.graph.mode, true, false); }; $scope.removeGraphOptionValues = function(idx) { $scope.paragraph.config.graph.values.splice(idx, 1); clearUnknownColsFromGraphOption(); $scope.setGraphMode($scope.paragraph.config.graph.mode, true, false); }; $scope.removeGraphOptionGroups = function(idx) { $scope.paragraph.config.graph.groups.splice(idx, 1); clearUnknownColsFromGraphOption(); $scope.setGraphMode($scope.paragraph.config.graph.mode, true, false); }; $scope.setGraphOptionValueAggr = function(idx, aggr) { $scope.paragraph.config.graph.values[idx].aggr = aggr; clearUnknownColsFromGraphOption(); $scope.setGraphMode($scope.paragraph.config.graph.mode, true, false); }; /* Clear unknown columns from graph option */ var clearUnknownColsFromGraphOption = function() { var unique = function(list) { for (var i = 0; i<list.length; i++) { for (var j=i+1; j<list.length; j++) { if (angular.equals(list[i], list[j])) { list.splice(j, 1); } } } }; var removeUnknown = function(list) { for (var i = 0; i<list.length; i++) { // remove non existing column var found = false; for (var j=0; j<$scope.paragraph.result.columnNames.length; j++) { var a = list[i]; var b = $scope.paragraph.result.columnNames[j]; if (a.index === b.index && a.name === b.name) { found = true; break; } } if (!found) { list.splice(i, 1); } } }; unique($scope.paragraph.config.graph.keys); removeUnknown($scope.paragraph.config.graph.keys); removeUnknown($scope.paragraph.config.graph.values); unique($scope.paragraph.config.graph.groups); removeUnknown($scope.paragraph.config.graph.groups); }; /* select default key and value if there're none selected */ var selectDefaultColsForGraphOption = function() { if ($scope.paragraph.config.graph.keys.length===0 && $scope.paragraph.result.columnNames.length > 0) { $scope.paragraph.config.graph.keys.push($scope.paragraph.result.columnNames[0]); } if ($scope.paragraph.config.graph.values.length===0 && $scope.paragraph.result.columnNames.length > 1) { $scope.paragraph.config.graph.values.push($scope.paragraph.result.columnNames[1]); } }; var pivot = function(data) { var keys = $scope.paragraph.config.graph.keys; var groups = $scope.paragraph.config.graph.groups; var values = $scope.paragraph.config.graph.values; var aggrFunc = { sum : function(a,b) { var varA = (a!==undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0; var varB = (b!==undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0; return varA+varB; }, count : function(a,b) { var varA = (a!==undefined) ? a : 0; var varB = (b!==undefined) ? 1 : 0; return varA+varB; }, min : function(a,b) { var varA = (a!==undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0; var varB = (b!==undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0; return Math.min(varA,varB); }, max : function(a,b) { var varA = (a!==undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0; var varB = (b!==undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0; return Math.max(varA,varB); }, avg : function(a,b,c) { var varA = (a!==undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0; var varB = (b!==undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0; return varA+varB; } }; var aggrFuncDiv = { sum : false, count : false, min : false, max : false, avg : true }; var schema = {}; var rows = {}; for (var i=0; i < data.rows.length; i++) { var row = data.rows[i]; var newRow = {}; var s = schema; var p = rows; for (var k=0; k < keys.length; k++) { var key = keys[k]; // add key to schema if (!s[key.name]) { s[key.name] = { order : k, index : key.index, type : 'key', children : {} }; } s = s[key.name].children; // add key to row var keyKey = row[key.index]; if (!p[keyKey]) { p[keyKey] = {}; } p = p[keyKey]; } for (var g=0; g < groups.length; g++) { var group = groups[g]; var groupKey = row[group.index]; // add group to schema if (!s[groupKey]) { s[groupKey] = { order : g, index : group.index, type : 'group', children : {} }; } s = s[groupKey].children; // add key to row if (!p[groupKey]) { p[groupKey] = {}; } p = p[groupKey]; } for (var v=0; v < values.length; v++) { var value = values[v]; var valueKey = value.name+'('+value.aggr+')'; // add value to schema if (!s[valueKey]) { s[valueKey] = { type : 'value', order : v, index : value.index }; } // add value to row if (!p[valueKey]) { p[valueKey] = { value : row[value.index], count: 1 }; } else { p[valueKey] = { value : aggrFunc[value.aggr](p[valueKey].value, row[value.index], p[valueKey].count+1), count : (aggrFuncDiv[value.aggr]) ? p[valueKey].count+1 : p[valueKey].count }; } } } //console.log("schema=%o, rows=%o", schema, rows); return { schema : schema, rows : rows }; }; var pivotDataToD3ChartFormat = function(data, allowTextXAxis, fillMissingValues) { // construct d3 data var d3g = []; var schema = data.schema; var rows = data.rows; var values = $scope.paragraph.config.graph.values; var concat = function(o, n) { if(!o) { return n; } else { return o+'.'+n; } }; var getSchemaUnderKey = function(key, s) { for (var c in key.children) { s[c] = {}; getSchemaUnderKey(key.children[c], s[c]); } } var traverse = function(sKey, s, rKey, r, func, rowName, rowValue, colName) { //console.log("TRAVERSE sKey=%o, s=%o, rKey=%o, r=%o, rowName=%o, rowValue=%o, colName=%o", sKey, s, rKey, r, rowName, rowValue, colName); if (s.type==='key') { rowName = concat(rowName, sKey); rowValue = concat(rowValue, rKey); } else if(s.type==='group') { colName = concat(colName, sKey); } else if(s.type==='value' && sKey===rKey) { colName = concat(colName, rKey); func(rowName, rowValue, colName, r); } for (var c in s.children) { if (fillMissingValues && s.children[c].type==='group' && r[c]===undefined) { var cs={}; getSchemaUnderKey(s.children[c], cs); traverse(c, s.children[c], c, cs, func, rowName, rowValue, colName); continue; } for (var j in r) { if (s.children[c].type==='key' || c===j) { traverse(c, s.children[c], j, r[j], func, rowName, rowValue, colName); } } } }; var keys = $scope.paragraph.config.graph.keys; var groups = $scope.paragraph.config.graph.groups; var values = $scope.paragraph.config.graph.values; var valueOnly = (keys.length===0 && groups.length===0 && values.length>0); var sKey = Object.keys(schema)[0]; var rowNameIndex = {}; var rowIdx = 0; var colNameIndex = {}; var colIdx = 0; var rowIndexValue = {}; for (var k in rows) { traverse(sKey, schema[sKey], k, rows[k], function(rowName, rowValue, colName, value){ //console.log("RowName=%o, row=%o, col=%o, value=%o", rowName, rowValue, colName, value); if (rowNameIndex[rowValue]===undefined) { rowIndexValue[rowIdx] = rowValue; rowNameIndex[rowValue] = rowIdx++; } if (colNameIndex[colName]===undefined) { colNameIndex[colName] = colIdx++; } var i = colNameIndex[colName]; if (valueOnly) { i = 0; } if(!d3g[i]){ d3g[i] = { values : [], key : (valueOnly) ? 'values' : colName }; } var xVar = isNaN(rowValue) ? ((allowTextXAxis) ? rowValue : rowNameIndex[rowValue]) : parseFloat(rowValue); var yVar = 0; if(xVar===undefined) { xVar = colName; } if(value!==undefined) { yVar = isNaN(value.value) ? 0 : parseFloat(value.value) / parseFloat(value.count); } d3g[i].values.push({ x : xVar, y : yVar }); }); } // clear aggregation name, if possible var namesWithoutAggr = {}; // TODO - This part could use som refactoring - Weird if/else with similar actions and variable names for(var colName in colNameIndex) { var withoutAggr = colName.substring(0, colName.lastIndexOf('(')); if (!namesWithoutAggr[withoutAggr]) { namesWithoutAggr[withoutAggr] = 1; } else { namesWithoutAggr[withoutAggr]++; } } if (valueOnly) { for (var valueIndex = 0; valueIndex < d3g[0].values.length; valueIndex++) { var colName = d3g[0].values[valueIndex].x; if (!colName) { continue; } var withoutAggr = colName.substring(0, colName.lastIndexOf('(')); if (namesWithoutAggr[withoutAggr] <= 1 ) { d3g[0].values[valueIndex].x = withoutAggr; } } } else { for (var d3gIndex = 0; d3gIndex < d3g.length; d3gIndex++) { var colName = d3g[d3gIndex].key; var withoutAggr = colName.substring(0, colName.lastIndexOf('(')); if (namesWithoutAggr[withoutAggr] <= 1 ) { d3g[d3gIndex].key = withoutAggr; } } // use group name instead of group.value as a column name, if there're only one group and one value selected. if (groups.length === 1 && values.length === 1) { for (d3gIndex = 0; d3gIndex < d3g.length; d3gIndex++) { var colName = d3g[d3gIndex].key; colName = colName.split('.')[0]; d3g[d3gIndex].key = colName; } } } return { xLabels : rowIndexValue, d3g : d3g }; }; $scope.setGraphHeight = function() { var height = $('#p'+$scope.paragraph.id+'_graph').height(); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.graph.height = height; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; /** Utility function */ if (typeof String.prototype.startsWith !== 'function') { String.prototype.startsWith = function(str) { return this.slice(0, str.length) === str; }; } $scope.goToSingleParagraph = function () { var noteId = $route.current.pathParams.noteId; var redirectToUrl = location.protocol + '//' + location.host + '/#/notebook/' + noteId + '/paragraph/' + $scope.paragraph.id+'?asIframe'; $window.open(redirectToUrl); }; });
zeppelin-web/app/scripts/controllers/paragraph.js
/* global $:false, jQuery:false, ace:false, confirm:false, d3:false, nv:false*/ /*jshint loopfunc: true, unused:false */ /* Copyright 2014 NFLabs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * @ngdoc function * @name zeppelinWebApp.controller:ParagraphCtrl * @description * # ParagraphCtrl * Controller of the paragraph, manage everything related to the paragraph * * @author anthonycorbacho */ angular.module('zeppelinWebApp') .controller('ParagraphCtrl', function($scope, $rootScope, $route, $window, $element, $routeParams, $location, $timeout) { $scope.paragraph = null; $scope.editor = null; var editorMode = {scala: 'ace/mode/scala', sql: 'ace/mode/sql', markdown: 'ace/mode/markdown'}; // Controller init $scope.init = function(newParagraph) { $scope.paragraph = newParagraph; $scope.chart = {}; $scope.colWidthOption = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]; $scope.showTitleEditor = false; if (!$scope.paragraph.config) { $scope.paragraph.config = {}; } initializeDefault(); if (!$scope.lastData) { $scope.lastData = {}; } if ($scope.getResultType() === 'TABLE') { $scope.lastData.settings = jQuery.extend(true, {}, $scope.paragraph.settings); $scope.lastData.config = jQuery.extend(true, {}, $scope.paragraph.config); $scope.loadTableData($scope.paragraph.result); $scope.setGraphMode($scope.getGraphMode(), false, false); } else if ($scope.getResultType() === 'HTML') { $scope.renderHtml(); } }; $scope.renderHtml = function() { var retryRenderer = function(){ if($('#p'+$scope.paragraph.id+'_html').length){ try { $('#p'+$scope.paragraph.id+'_html').html($scope.paragraph.result.msg); } catch(err) { console.log('HTML rendering error %o', err); } } else { $timeout(retryRenderer,10); } }; $timeout(retryRenderer); }; var initializeDefault = function(){ var config = $scope.paragraph.config; if (!config.looknfeel) { config.looknfeel = 'default'; } if (!config.colWidth) { config.colWidth = 12; } if(!config.graph){ config.graph = {}; } if (!config.graph.mode) { config.graph.mode = 'table'; } if (!config.graph.height) { config.graph.height = 300; } if (!config.graph.optionOpen) { config.graph.optionOpen = false; } if (!config.graph.keys) { config.graph.keys = []; } if (!config.graph.values) { config.graph.values = []; } if (!config.graph.groups) { config.graph.groups = []; } }; $scope.getIframeDimensions = function () { if ($scope.asIframe) { var paragraphid = '#' + $routeParams.paragraphId + '_container'; var height = $(paragraphid).height(); return height; } return 0; }; $scope.$watch($scope.getIframeDimensions, function (newValue, oldValue) { if ($scope.asIframe && newValue) { var message = {}; message.height = newValue; message.url = $location.$$absUrl; $window.parent.postMessage(angular.toJson(message), '*'); } }); // TODO: this may have impact on performance when there are many paragraphs in a note. $rootScope.$on('updateParagraph', function(event, data) { if (data.paragraph.id === $scope.paragraph.id && ( data.paragraph.dateCreated !== $scope.paragraph.dateCreated || data.paragraph.dateFinished !== $scope.paragraph.dateFinished || data.paragraph.dateStarted !== $scope.paragraph.dateStarted || data.paragraph.status !== $scope.paragraph.status || data.paragraph.jobName !== $scope.paragraph.jobName || data.paragraph.title !== $scope.paragraph.title || data.paragraph.errorMessage !== $scope.paragraph.errorMessage || !angular.equals(data.paragraph.settings, $scope.lastData.settings) || !angular.equals(data.paragraph.config, $scope.lastData.config) ) ) { // store original data for comparison $scope.lastData.settings = jQuery.extend(true, {}, data.paragraph.settings); $scope.lastData.config = jQuery.extend(true, {}, data.paragraph.config); var oldType = $scope.getResultType(); var newType = $scope.getResultType(data.paragraph); var oldGraphMode = $scope.getGraphMode(); var newGraphMode = $scope.getGraphMode(data.paragraph); var resultRefreshed = (data.paragraph.dateFinished !== $scope.paragraph.dateFinished); //console.log("updateParagraph oldData %o, newData %o. type %o -> %o, mode %o -> %o", $scope.paragraph, data, oldType, newType, oldGraphMode, newGraphMode); if ($scope.paragraph.text !== data.paragraph.text) { if ($scope.dirtyText) { // check if editor has local update if ($scope.dirtyText === data.paragraph.text ) { // when local update is the same from remote, clear local update $scope.paragraph.text = data.paragraph.text; $scope.dirtyText = undefined; } else { // if there're local update, keep it. $scope.paragraph.text = $scope.dirtyText; } } else { $scope.paragraph.text = data.paragraph.text; } } /** push the rest */ $scope.paragraph.aborted = data.paragraph.aborted; $scope.paragraph.dateCreated = data.paragraph.dateCreated; $scope.paragraph.dateFinished = data.paragraph.dateFinished; $scope.paragraph.dateStarted = data.paragraph.dateStarted; $scope.paragraph.errorMessage = data.paragraph.errorMessage; $scope.paragraph.jobName = data.paragraph.jobName; $scope.paragraph.title = data.paragraph.title; $scope.paragraph.status = data.paragraph.status; $scope.paragraph.result = data.paragraph.result; $scope.paragraph.settings = data.paragraph.settings; if (!$scope.asIframe) { $scope.paragraph.config = data.paragraph.config; initializeDefault(); } else { data.paragraph.config.editorHide = true; data.paragraph.config.tableHide = false; $scope.paragraph.config = data.paragraph.config; } if (newType==='TABLE') { $scope.loadTableData($scope.paragraph.result); if (oldType!=='TABLE' || resultRefreshed) { clearUnknownColsFromGraphOption(); selectDefaultColsForGraphOption(); } /** User changed the chart type? */ if (oldGraphMode !== newGraphMode) { $scope.setGraphMode(newGraphMode, false, false); } else { $scope.setGraphMode(newGraphMode, false, true); } } else if (newType==='HTML') { $scope.renderHtml(); } } }); $scope.isRunning = function(){ if($scope.paragraph.status==='RUNNING' || $scope.paragraph.status==='PENDING') { return true; } else { return false; } }; $scope.cancelParagraph = function() { console.log('Cancel %o', $scope.paragraph.id); var data = {op: 'CANCEL_PARAGRAPH', data: {id: $scope.paragraph.id }}; $rootScope.$emit('sendNewEvent', data); }; $scope.runParagraph = function(data) { var parapgraphData = {op: 'RUN_PARAGRAPH', data: { id: $scope.paragraph.id, title: $scope.paragraph.title, paragraph: data, config: $scope.paragraph.config, params: $scope.paragraph.settings.params } }; $rootScope.$emit('sendNewEvent', parapgraphData); }; $scope.moveUp = function() { $rootScope.$emit('moveParagraphUp', $scope.paragraph.id); }; $scope.moveDown = function() { $rootScope.$emit('moveParagraphDown', $scope.paragraph.id); }; $scope.insertNew = function() { $rootScope.$emit('insertParagraph', $scope.paragraph.id); }; $scope.removeParagraph = function() { var result = confirm('Do you want to delete this paragraph?'); if (result) { console.log('Remove paragraph'); var paragraphData = {op: 'PARAGRAPH_REMOVE', data: {id: $scope.paragraph.id}}; $rootScope.$emit('sendNewEvent', paragraphData); } }; $scope.toggleEditor = function() { if ($scope.paragraph.config.editorHide) { $scope.openEditor(); } else { $scope.closeEditor(); } }; $scope.closeEditor = function() { console.log('close the note'); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.editorHide = true; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.openEditor = function() { console.log('open the note'); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.editorHide = false; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.closeTable = function() { console.log('close the output'); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.tableHide = true; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.openTable = function() { console.log('open the output'); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.tableHide = false; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.showTitle = function() { var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.title = true; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.hideTitle = function() { var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.title = false; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.setTitle = function() { var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.columnWidthClass = function(n){ if($scope.asIframe){ return 'col-md-12'; } else { return 'col-md-' + n; } } $scope.changeColWidth = function() { var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.toggleGraphOption = function() { var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); if (newConfig.graph.optionOpen) { newConfig.graph.optionOpen = false; } else { newConfig.graph.optionOpen = true; } var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.toggleOutput = function() { var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.tableHide = !newConfig.tableHide; var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; $scope.loadForm = function(formulaire, params) { var value = formulaire.defaultValue; if (params[formulaire.name]) { value = params[formulaire.name]; } if (value === '') { value = formulaire.options[0].value; } $scope.paragraph.settings.params[formulaire.name] = value; }; $scope.aceChanged = function() { $scope.dirtyText = $scope.editor.getSession().getValue(); }; $scope.aceLoaded = function(_editor) { var langTools = ace.require('ace/ext/language_tools'); var Range = ace.require('ace/range').Range; $scope.editor = _editor; if (_editor.container.id !== '{{paragraph.id}}_editor') { $scope.editor.renderer.setShowGutter(false); $scope.editor.setHighlightActiveLine(false); $scope.editor.focus(); var hight = $scope.editor.getSession().getScreenLength() * $scope.editor.renderer.lineHeight + $scope.editor.renderer.scrollBar.getWidth(); setEditorHeight(_editor.container.id, hight); $scope.editor.getSession().setUseWrapMode(true); if (navigator.appVersion.indexOf('Mac') !== -1 ) { $scope.editor.setKeyboardHandler('ace/keyboard/emacs'); } else if (navigator.appVersion.indexOf('Win') !== -1 || navigator.appVersion.indexOf('X11') !== -1 || navigator.appVersion.indexOf('Linux') !== -1) { // not applying emacs key binding while the binding override Ctrl-v. default behavior of paste text on windows. } $scope.editor.setOptions({ enableBasicAutocompletion: true, enableSnippets: false, enableLiveAutocompletion:false }); var remoteCompleter = { getCompletions : function(editor, session, pos, prefix, callback) { if (!$scope.editor.isFocused() ){ return;} var buf = session.getTextRange(new Range(0, 0, pos.row, pos.column)); $rootScope.$emit('sendNewEvent', { op : 'COMPLETION', data : { id : $scope.paragraph.id, buf : buf, cursor : buf.length } }); $rootScope.$on('completionList', function(event, data) { if (data.completions) { var completions = []; for(var c in data.completions){ var v = data.completions[c]; completions.push({ name:v, value:v, score:300 }); } callback(null, completions); } }); } }; langTools.addCompleter(remoteCompleter); $scope.editor.on('focus', function(){ var el = $('#' + $scope.paragraph.id + '_paragraphColumn'); el.addClass('focused'); }); $scope.editor.on('blur', function(){ var el = $('#' + $scope.paragraph.id + '_paragraphColumn'); el.removeClass('focused'); }); $scope.editor.getSession().on('change', function(e, editSession) { hight = editSession.getScreenLength() * $scope.editor.renderer.lineHeight + $scope.editor.renderer.scrollBar.getWidth(); setEditorHeight(_editor.container.id, hight); $scope.editor.resize(); }); var code = $scope.editor.getSession().getValue(); if ( String(code).startsWith('%sql')) { $scope.editor.getSession().setMode(editorMode.sql); } else if ( String(code).startsWith('%md')) { $scope.editor.getSession().setMode(editorMode.markdown); } else { $scope.editor.getSession().setMode(editorMode.scala); } $scope.editor.commands.addCommand({ name: 'run', bindKey: {win: 'Shift-Enter', mac: 'Shift-Enter'}, exec: function(editor) { var editorValue = editor.getValue(); if (editorValue) { $scope.runParagraph(editorValue); } }, readOnly: false }); // autocomplete on '.' /* $scope.editor.commands.on("afterExec", function(e, t) { if (e.command.name == "insertstring" && e.args == "." ) { var all = e.editor.completers; //e.editor.completers = [remoteCompleter]; e.editor.execCommand("startAutocomplete"); //e.editor.completers = all; } }); */ // autocomplete on 'ctrl+.' $scope.editor.commands.bindKey('ctrl-.', 'startAutocomplete'); $scope.editor.commands.bindKey('ctrl-space', null); // handle cursor moves $scope.editor.keyBinding.origOnCommandKey = $scope.editor.keyBinding.onCommandKey; $scope.editor.keyBinding.onCommandKey = function(e, hashId, keyCode) { if($scope.editor.completer && $scope.editor.completer.activated) { // if autocompleter is active } else { var numRows; var currentRow; if(keyCode===38 || (keyCode===80 && e.ctrlKey)){ // UP numRows = $scope.editor.getSession().getLength(); currentRow = $scope.editor.getCursorPosition().row; if(currentRow===0){ // move focus to previous paragraph $rootScope.$emit('moveFocusToPreviousParagraph', $scope.paragraph.id); } } else if(keyCode===40 || (keyCode===78 && e.ctrlKey)){ // DOWN numRows = $scope.editor.getSession().getLength(); currentRow = $scope.editor.getCursorPosition().row; if(currentRow === numRows-1){ // move focus to next paragraph $rootScope.$emit('moveFocusToNextParagraph', $scope.paragraph.id); } } } this.origOnCommandKey(e, hashId, keyCode); }; } }; var setEditorHeight = function(id, height) { $('#' + id).height(height.toString() + 'px'); }; $scope.getEditorValue = function() { return $scope.editor.getValue(); }; $scope.getProgress = function(){ return ($scope.currentProgress) ? $scope.currentProgress : 0; }; $scope.getExecutionTime = function() { var pdata = $scope.paragraph; var timeMs = Date.parse(pdata.dateFinished) - Date.parse(pdata.dateStarted); return 'Took ' + (timeMs/1000) + ' seconds'; }; $rootScope.$on('updateProgress', function(event, data) { if (data.id === $scope.paragraph.id) { $scope.currentProgress = data.progress; } }); $rootScope.$on('focusParagraph', function(event, paragraphId){ if ($scope.paragraph.id === paragraphId) { $scope.editor.focus(); $('body').scrollTo('#'+paragraphId+'_editor', 300, {offset:-60}); } }); $rootScope.$on('runParagraph', function(event){ $scope.runParagraph($scope.editor.getValue()); }); $rootScope.$on('openEditor', function(event){ $scope.openEditor(); }); $rootScope.$on('closeEditor', function(event){ $scope.closeEditor(); }); $rootScope.$on('openTable', function(event){ $scope.openTable(); }); $rootScope.$on('closeTable', function(event){ $scope.closeTable(); }); $scope.getResultType = function(paragraph){ var pdata = (paragraph) ? paragraph : $scope.paragraph; if (pdata.result && pdata.result.type) { return pdata.result.type; } else { return 'TEXT'; } }; $scope.getBase64ImageSrc = function(base64Data) { return 'data:image/png;base64,'+base64Data; }; $scope.getGraphMode = function(paragraph){ var pdata = (paragraph) ? paragraph : $scope.paragraph; if (pdata.config.graph && pdata.config.graph.mode) { return pdata.config.graph.mode; } else { return 'table'; } }; $scope.loadTableData = function(result) { if (!result) { return; } if (result.type === 'TABLE') { var columnNames = []; var rows = []; var array = []; var textRows = result.msg.split('\n'); result.comment = ''; var comment = false; for (var i = 0; i < textRows.length; i++) { var textRow = textRows[i]; if (comment) { result.comment += textRow; continue; } if (textRow === '') { if (rows.length>0) { comment = true; } continue; } var textCols = textRow.split('\t'); var cols = []; var cols2 = []; for (var j = 0; j < textCols.length; j++) { var col = textCols[j]; if (i === 0) { columnNames.push({name:col, index:j, aggr:'sum'}); } else { cols.push(col); cols2.push({key: (columnNames[i]) ? columnNames[i].name: undefined, value: col}); } } if (i !== 0) { rows.push(cols); array.push(cols2); } } result.msgTable = array; result.columnNames = columnNames; result.rows = rows; } }; $scope.setGraphMode = function(type, emit, refresh) { if (emit) { setNewMode(type); } else { clearUnknownColsFromGraphOption(); // set graph height var height = $scope.paragraph.config.graph.height; $('#p'+$scope.paragraph.id+'_graph').height(height); if (!type || type === 'table') { setTable($scope.paragraph.result, refresh); } else if (type === 'multiBarChart') { setD3Chart(type, $scope.paragraph.result, refresh); } else if (type === 'pieChart') { setD3Chart(type, $scope.paragraph.result, refresh); } else if (type === 'stackedAreaChart') { setD3Chart(type, $scope.paragraph.result, refresh); } else if (type === 'lineChart') { setD3Chart(type, $scope.paragraph.result, refresh); } } }; var setNewMode = function(newMode) { var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); // graph options newConfig.graph.mode = newMode; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; var commitParagraph = function(title, text, config, params) { var parapgraphData = { op: 'COMMIT_PARAGRAPH', data: { id: $scope.paragraph.id, title : title, paragraph: text, params: params, config: config }}; $rootScope.$emit('sendNewEvent', parapgraphData); }; var setTable = function(type, data, refresh) { var getTableContentFormat = function(d) { if (isNaN(d)) { if(d.length>'%html'.length && '%html '===d.substring(0, '%html '.length)) { return 'html'; } else { return ''; } } else { return ''; } }; var formatTableContent = function(d) { if (isNaN(d)) { var f = getTableContentFormat(d); if(f !=='') { return d.substring(f.length+2); } else { return d; } } else { var dStr = d.toString(); var splitted = dStr.split('.'); var formatted = splitted[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); if (splitted.length>1) { formatted+= '.'+splitted[1]; } return formatted; } }; var renderTable = function(){ var html = ''; html += '<table class="table table-hover table-condensed">'; html += ' <thead>'; html += ' <tr style="background-color: #F6F6F6; font-weight: bold;">'; for (var c in $scope.paragraph.result.columnNames) { html += '<th>'+$scope.paragraph.result.columnNames[c].name+'</th>'; } html += ' </tr>'; html += ' </thead>'; for (var r in $scope.paragraph.result.msgTable) { var row = $scope.paragraph.result.msgTable[r]; html += ' <tr>'; for (var index in row) { var v = row[index].value; if(getTableContentFormat(v) !== 'html') { v = v.replace(/[\u00A0-\u9999<>\&]/gim, function(i) { return '&#'+i.charCodeAt(0)+';'; }); } html += ' <td>'+formatTableContent(v)+'</td>'; } html += ' </tr>'; } html += '</table>'; $('#p' + $scope.paragraph.id + '_table').html(html); $('#p' + $scope.paragraph.id + '_table').perfectScrollbar(); // set table height var height = $scope.paragraph.config.graph.height; $('#p'+$scope.paragraph.id+'_table').height(height); }; var retryRenderer = function(){ if($('#p'+$scope.paragraph.id+'_table').length){ try { renderTable(); } catch(err) { console.log('Chart drawing error %o', err); } } else { $timeout(retryRenderer,10); } }; $timeout(retryRenderer); }; var setD3Chart = function(type, data, refresh) { if (!$scope.chart[type]) { var chart = nv.models[type](); $scope.chart[type] = chart; } var p = pivot(data); var xColIndexes = $scope.paragraph.config.graph.keys; var yColIndexes = $scope.paragraph.config.graph.values; var d3g = []; // select yColumns. if (type==='pieChart') { var d = pivotDataToD3ChartFormat(p, true).d3g; $scope.chart[type].x(function(d){ return d.label;}) .y(function(d){ return d.value;}); if ( d.length > 0 ) { for ( var i=0; i<d[0].values.length ; i++) { var e = d[0].values[i]; d3g.push({ label : e.x, value : e.y }); } } } else if (type==='multiBarChart') { d3g = pivotDataToD3ChartFormat(p, true).d3g; $scope.chart[type].yAxis.axisLabelDistance(50); } else { var pivotdata = pivotDataToD3ChartFormat(p); var xLabels = pivotdata.xLabels; d3g = pivotdata.d3g; $scope.chart[type].xAxis.tickFormat(function(d) { if (xLabels[d] && (isNaN(parseFloat(xLabels[d])) || !isFinite(xLabels[d]))) { // to handle string type xlabel return xLabels[d]; } else { return d; } }); $scope.chart[type].yAxis.axisLabelDistance(50); $scope.chart[type].useInteractiveGuideline(true); // for better UX and performance issue. (https://github.com/novus/nvd3/issues/691) $scope.chart[type].forceY([0]); // force y-axis minimum to 0 for line chart. } var renderChart = function(){ if (!refresh) { // TODO force destroy previous chart } var height = $scope.paragraph.config.graph.height; var animationDuration = 300; var numberOfDataThreshold = 150; // turn off animation when dataset is too large. (for performance issue) // still, since dataset is large, the chart content sequentially appears like animated. try { if (d3g[0].values.length > numberOfDataThreshold) { animationDuration = 0; } } catch(ignoreErr) { } var chartEl = d3.select('#p'+$scope.paragraph.id+'_'+type+' svg') .attr('height', $scope.paragraph.config.graph.height) .datum(d3g) .transition() .duration(animationDuration) .call($scope.chart[type]); d3.select('#p'+$scope.paragraph.id+'_'+type+' svg').style.height = height+'px'; nv.utils.windowResize($scope.chart[type].update); }; var retryRenderer = function(){ if($('#p'+$scope.paragraph.id+'_'+type+' svg').length!==0){ try { renderChart(); } catch(err) { console.log('Chart drawing error %o', err); } } else { $timeout(retryRenderer,10); } }; $timeout(retryRenderer); }; var setPieChart = function(data, refresh) { var xColIndex = 0; var yColIndexes = []; var d3g = []; // select yColumns. for (var colIndex = 0; colIndex < data.columnNames.length; colIndex++) { if (colIndex !== xColIndex) { yColIndexes.push(colIndex); } } for (var rowIndex = 0; rowIndex < data.rows.length; rowIndex++) { var row = data.rows[rowIndex]; var xVar = row[xColIndex]; var yVar = row[yColIndexes[0]]; d3g.push({ label: isNaN(xVar) ? xVar : parseFloat(xVar), value: parseFloat(yVar) }); } if ($scope.d3.pieChart.data === null || !refresh) { $scope.d3.pieChart.data = d3g; $scope.d3.pieChart.options.chart.height = $scope.paragraph.config.graph.height; if ($scope.d3.pieChart.api) { $scope.d3.pieChart.api.updateWithOptions($scope.d3.pieChart.options); } } else { if ($scope.d3.pieChart.api) { $scope.d3.pieChart.api.updateWithData(d3g); } } }; $scope.isGraphMode = function(graphName) { if ($scope.getResultType() === 'TABLE' && $scope.getGraphMode()===graphName) { return true; } else { return false; } }; $scope.onGraphOptionChange = function() { clearUnknownColsFromGraphOption(); $scope.setGraphMode($scope.paragraph.config.graph.mode, true, false); }; $scope.removeGraphOptionKeys = function(idx) { $scope.paragraph.config.graph.keys.splice(idx, 1); clearUnknownColsFromGraphOption(); $scope.setGraphMode($scope.paragraph.config.graph.mode, true, false); }; $scope.removeGraphOptionValues = function(idx) { $scope.paragraph.config.graph.values.splice(idx, 1); clearUnknownColsFromGraphOption(); $scope.setGraphMode($scope.paragraph.config.graph.mode, true, false); }; $scope.removeGraphOptionGroups = function(idx) { $scope.paragraph.config.graph.groups.splice(idx, 1); clearUnknownColsFromGraphOption(); $scope.setGraphMode($scope.paragraph.config.graph.mode, true, false); }; $scope.setGraphOptionValueAggr = function(idx, aggr) { $scope.paragraph.config.graph.values[idx].aggr = aggr; clearUnknownColsFromGraphOption(); $scope.setGraphMode($scope.paragraph.config.graph.mode, true, false); }; /* Clear unknown columns from graph option */ var clearUnknownColsFromGraphOption = function() { var unique = function(list) { for (var i = 0; i<list.length; i++) { for (var j=i+1; j<list.length; j++) { if (angular.equals(list[i], list[j])) { list.splice(j, 1); } } } }; var removeUnknown = function(list) { for (var i = 0; i<list.length; i++) { // remove non existing column var found = false; for (var j=0; j<$scope.paragraph.result.columnNames.length; j++) { var a = list[i]; var b = $scope.paragraph.result.columnNames[j]; if (a.index === b.index && a.name === b.name) { found = true; break; } } if (!found) { list.splice(i, 1); } } }; unique($scope.paragraph.config.graph.keys); removeUnknown($scope.paragraph.config.graph.keys); removeUnknown($scope.paragraph.config.graph.values); unique($scope.paragraph.config.graph.groups); removeUnknown($scope.paragraph.config.graph.groups); }; /* select default key and value if there're none selected */ var selectDefaultColsForGraphOption = function() { if ($scope.paragraph.config.graph.keys.length===0 && $scope.paragraph.result.columnNames.length > 0) { $scope.paragraph.config.graph.keys.push($scope.paragraph.result.columnNames[0]); } if ($scope.paragraph.config.graph.values.length===0 && $scope.paragraph.result.columnNames.length > 1) { $scope.paragraph.config.graph.values.push($scope.paragraph.result.columnNames[1]); } }; var pivot = function(data) { var keys = $scope.paragraph.config.graph.keys; var groups = $scope.paragraph.config.graph.groups; var values = $scope.paragraph.config.graph.values; var aggrFunc = { sum : function(a,b) { var varA = (a!==undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0; var varB = (b!==undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0; return varA+varB; }, count : function(a,b) { var varA = (a!==undefined) ? a : 0; var varB = (b!==undefined) ? 1 : 0; return varA+varB; }, min : function(a,b) { var varA = (a!==undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0; var varB = (b!==undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0; return Math.min(varA,varB); }, max : function(a,b) { var varA = (a!==undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0; var varB = (b!==undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0; return Math.max(varA,varB); }, avg : function(a,b,c) { var varA = (a!==undefined) ? (isNaN(a) ? 1 : parseFloat(a)) : 0; var varB = (b!==undefined) ? (isNaN(b) ? 1 : parseFloat(b)) : 0; return varA+varB; } }; var aggrFuncDiv = { sum : false, count : false, min : false, max : false, avg : true }; var schema = {}; var rows = {}; for (var i=0; i < data.rows.length; i++) { var row = data.rows[i]; var newRow = {}; var s = schema; var p = rows; for (var k=0; k < keys.length; k++) { var key = keys[k]; // add key to schema if (!s[key.name]) { s[key.name] = { order : k, index : key.index, type : 'key', children : {} }; } s = s[key.name].children; // add key to row var keyKey = row[key.index]; if (!p[keyKey]) { p[keyKey] = {}; } p = p[keyKey]; } for (var g=0; g < groups.length; g++) { var group = groups[g]; var groupKey = row[group.index]; // add group to schema if (!s[groupKey]) { s[groupKey] = { order : g, index : group.index, type : 'group', children : {} }; } s = s[groupKey].children; // add key to row if (!p[groupKey]) { p[groupKey] = {}; } p = p[groupKey]; } for (var v=0; v < values.length; v++) { var value = values[v]; var valueKey = value.name+'('+value.aggr+')'; // add value to schema if (!s[valueKey]) { s[valueKey] = { type : 'value', order : v, index : value.index }; } // add value to row if (!p[valueKey]) { p[valueKey] = { value : row[value.index], count: 1 }; } else { p[valueKey] = { value : aggrFunc[value.aggr](p[valueKey].value, row[value.index], p[valueKey].count+1), count : (aggrFuncDiv[value.aggr]) ? p[valueKey].count+1 : p[valueKey].count }; } } } //console.log("schema=%o, rows=%o", schema, rows); return { schema : schema, rows : rows }; }; var pivotDataToD3ChartFormat = function(data, allowTextXAxis) { // construct d3 data var d3g = []; var schema = data.schema; var rows = data.rows; var values = $scope.paragraph.config.graph.values; var d = {}; var concat = function(o, n) { if(!o) { return n; } else { return o+'.'+n; } }; var traverse = function(sKey, s, rKey, r, func, rowName, rowValue, colName) { //console.log("TRAVERSE sKey=%o, s=%o, rKey=%o, r=%o, rowName=%o, rowValue=%o, colName=%o", sKey, s, rKey, r, rowName, rowValue, colName); if (s.type==='key') { rowName = concat(rowName, sKey); rowValue = concat(rowValue, rKey); } else if(s.type==='group') { colName = concat(colName, sKey); } else if(s.type==='value') { colName = concat(colName, rKey); func(rowName, rowValue, colName, r); } for (var c in s.children) { if (s.type==='group' && sKey!==rKey) { traverse(c, s.children[c], c, undefined, func, rowName, rowValue, colName); continue; } for (var j in r) { traverse(c, s.children[c], j, r[j], func, rowName, rowValue, colName); } } }; var keys = $scope.paragraph.config.graph.keys; var groups = $scope.paragraph.config.graph.groups; var values = $scope.paragraph.config.graph.values; var valueOnly = (keys.length===0 && groups.length===0 && values.length>0); var sKey = Object.keys(schema)[0]; var rowNameIndex = {}; var rowIdx = 0; var colNameIndex = {}; var colIdx = 0; var rowIndexValue = {}; for (var k in rows) { traverse(sKey, schema[sKey], k, rows[k], function(rowName, rowValue, colName, value){ //console.log("RowName=%o, row=%o, col=%o, value=%o", rowName, rowValue, colName, value); if (rowNameIndex[rowValue]===undefined) { rowIndexValue[rowIdx] = rowValue; rowNameIndex[rowValue] = rowIdx++; } if (colNameIndex[colName]===undefined) { colNameIndex[colName] = colIdx++; } var i = colNameIndex[colName]; if (valueOnly) { i = 0; } if(!d3g[i]){ d3g[i] = { values : [], key : (valueOnly) ? 'values' : colName }; } var xVar = isNaN(rowValue) ? ((allowTextXAxis) ? rowValue : rowNameIndex[rowValue]) : parseFloat(rowValue); var yVar = 0; if(xVar===undefined){ xVar = colName; } if(value!==undefined){ yVar = isNaN(value.value) ? 0 : parseFloat(value.value) / parseFloat(value.count); } d3g[i].values.push({ x : xVar, y : yVar }); }); } // clear aggregation name, if possible var namesWithoutAggr = {}; // TODO - This part could use som refactoring - Weird if/else with similar actions and variable names for(var colName in colNameIndex) { var withoutAggr = colName.substring(0, colName.lastIndexOf('(')); if (!namesWithoutAggr[withoutAggr]) { namesWithoutAggr[withoutAggr] = 1; } else { namesWithoutAggr[withoutAggr]++; } } if (valueOnly) { for (var valueIndex = 0; valueIndex < d3g[0].values.length; valueIndex++) { var colName = d3g[0].values[valueIndex].x; if (!colName) { continue; } var withoutAggr = colName.substring(0, colName.lastIndexOf('(')); if (namesWithoutAggr[withoutAggr] <= 1 ) { d3g[0].values[valueIndex].x = withoutAggr; } } } else { for (var d3gIndex = 0; d3gIndex < d3g.length; d3gIndex++) { var colName = d3g[d3gIndex].key; var withoutAggr = colName.substring(0, colName.lastIndexOf('(')); if (namesWithoutAggr[withoutAggr] <= 1 ) { d3g[d3gIndex].key = withoutAggr; } } // use group name instead of group.value as a column name, if there're only one group and one value selected. if (groups.length === 1 && values.length === 1) { for (d3gIndex = 0; d3gIndex < d3g.length; d3gIndex++) { var colName = d3g[d3gIndex].key; colName = colName.split('.')[0]; d3g[d3gIndex].key = colName; } } } return { xLabels : rowIndexValue, d3g : d3g }; }; $scope.setGraphHeight = function() { var height = $('#p'+$scope.paragraph.id+'_graph').height(); var newParams = jQuery.extend(true, {}, $scope.paragraph.settings.params); var newConfig = jQuery.extend(true, {}, $scope.paragraph.config); newConfig.graph.height = height; commitParagraph($scope.paragraph.title, $scope.paragraph.text, newConfig, newParams); }; /** Utility function */ if (typeof String.prototype.startsWith !== 'function') { String.prototype.startsWith = function(str) { return this.slice(0, str.length) === str; }; } $scope.goToSingleParagraph = function () { var noteId = $route.current.pathParams.noteId; var redirectToUrl = location.protocol + '//' + location.host + '/#/notebook/' + noteId + '/paragraph/' + $scope.paragraph.id+'?asIframe'; $window.open(redirectToUrl); }; });
Fix d3 data formmating for chart drawing
zeppelin-web/app/scripts/controllers/paragraph.js
Fix d3 data formmating for chart drawing
<ide><path>eppelin-web/app/scripts/controllers/paragraph.js <ide> d3g = pivotDataToD3ChartFormat(p, true).d3g; <ide> $scope.chart[type].yAxis.axisLabelDistance(50); <ide> } else { <del> var pivotdata = pivotDataToD3ChartFormat(p); <add> var pivotdata = pivotDataToD3ChartFormat(p, false, true); <ide> var xLabels = pivotdata.xLabels; <ide> d3g = pivotdata.d3g; <ide> $scope.chart[type].xAxis.tickFormat(function(d) { <ide> }; <ide> }; <ide> <del> var pivotDataToD3ChartFormat = function(data, allowTextXAxis) { <add> var pivotDataToD3ChartFormat = function(data, allowTextXAxis, fillMissingValues) { <ide> // construct d3 data <ide> var d3g = []; <ide> <ide> var rows = data.rows; <ide> var values = $scope.paragraph.config.graph.values; <ide> <del> var d = {}; <ide> var concat = function(o, n) { <ide> if(!o) { <ide> return n; <ide> } <ide> }; <ide> <add> var getSchemaUnderKey = function(key, s) { <add> for (var c in key.children) { <add> s[c] = {}; <add> getSchemaUnderKey(key.children[c], s[c]); <add> } <add> } <add> <ide> var traverse = function(sKey, s, rKey, r, func, rowName, rowValue, colName) { <ide> //console.log("TRAVERSE sKey=%o, s=%o, rKey=%o, r=%o, rowName=%o, rowValue=%o, colName=%o", sKey, s, rKey, r, rowName, rowValue, colName); <ide> <ide> rowValue = concat(rowValue, rKey); <ide> } else if(s.type==='group') { <ide> colName = concat(colName, sKey); <del> } else if(s.type==='value') { <add> } else if(s.type==='value' && sKey===rKey) { <ide> colName = concat(colName, rKey); <ide> func(rowName, rowValue, colName, r); <ide> } <ide> <ide> for (var c in s.children) { <del> if (s.type==='group' && sKey!==rKey) { <del> traverse(c, s.children[c], c, undefined, func, rowName, rowValue, colName); <add> if (fillMissingValues && s.children[c].type==='group' && r[c]===undefined) { <add> var cs={}; <add> getSchemaUnderKey(s.children[c], cs); <add> traverse(c, s.children[c], c, cs, func, rowName, rowValue, colName); <ide> continue; <ide> } <ide> <ide> for (var j in r) { <del> traverse(c, s.children[c], j, r[j], func, rowName, rowValue, colName); <add> if (s.children[c].type==='key' || c===j) { <add> traverse(c, s.children[c], j, r[j], func, rowName, rowValue, colName); <add> } <ide> } <ide> } <ide> }; <ide> <ide> var xVar = isNaN(rowValue) ? ((allowTextXAxis) ? rowValue : rowNameIndex[rowValue]) : parseFloat(rowValue); <ide> var yVar = 0; <del> if(xVar===undefined){ xVar = colName; } <del> if(value!==undefined){ <del> yVar = isNaN(value.value) ? 0 : parseFloat(value.value) / parseFloat(value.count); <add> if(xVar===undefined) { xVar = colName; } <add> if(value!==undefined) { <add> yVar = isNaN(value.value) ? 0 : parseFloat(value.value) / parseFloat(value.count); <ide> } <ide> d3g[i].values.push({ <ide> x : xVar,
JavaScript
apache-2.0
a2b9f7b422335fee7b2182e675de381aa9ee0cb5
0
Vbitz/Engine2D,Vbitz/Engine2D,Vbitz/Engine2D,Vbitz/Engine2D,Vbitz/Engine2D
// Engine2D Javascript API Documentation // Correct as of 18th Jan 2014 this.global = this; // Global object exposed as global /** @namespace */ global.console = {}; /** * Low level logging function that prints obj at level * * @param {string} level - The level to log at can be "warning"|"verbose"|"error"|"raw"|"log" * @param {...*} obj - The value to print, internaly the values will be joined with spaces * @internal */ global.console._log = function (level, obj) {}; /** * Hide all output on the EngineUI console */ global.console.clear = function () {}; /** * Toggle the EngineUI console */ global.console.toggle = function () {}; /** * Derived off global.console._log, prints with a user loglevel * @param {...*} obj - The value to print, internaly the values will be joined with spaces */ global.console.log = function (obj) {}; /** * Derived off global.console._log, prints with a warning loglevel * @param {...*} obj - The value to print, internaly the values will be joined with spaces */ global.console.warn = function (obj) {}; /** * Derived off global.console._log, prints with a error loglevel * @param {...*} obj - The value to print, internaly the values will be joined with spaces */ global.console.error = function (obj) {}; /** * Derived off global.console._log, prints with a verbose loglevel * @param {...*} obj - The value to print, internaly the values will be joined with spaces */ global.console.verbose = function (obj) {}; /** * Derived off global.console._log, prints without using the Logger interface directly to the system console * @param {...*} obj - The value to print, internaly the values will be joined with spaces */ global.console.writeRaw = function (obj) {}; /** @namespace */ global.sys = {}; /** * Returns an array of command line arguments passed to the engine * @return {string[]} */ global.sys.argv = function () {}; /** * Load and execute a javascript file from the filesystem * Requires that core.script.autoReload == true * @param {string} filename - The filename of the script to load without the .js extention * @param {boolean} persists - Should this file be automaticly reloaded? */ global.sys.runFile = function (filename, persists) {}; /** * @callback DrawFunction */ /** * Calls func each frame so drawing can be performed * @deprecated In favor of the "draw" event * @param {DrawFunction} func */ global.sys.drawFunc = function (func) {}; /** * @callback KeyboardFunction * @param {null} _ - Always "" * @param {string} char - The key pressed/released * @param {boolean} press - True if the key was pressed otherwise false */ /** * Calls func whenever a key is pressed * @deprecated In favor of the "input" event * @param {KeyboardFunction} func */ global.sys.keyboardFunc = function (func) {}; /** * @callback EventCallback * @param {Object} args - Event Arguments */ /** * Registers func to be called when event is emited * @param {string} event * @param {string} id - A unique ID to assoiate with the function * @param {Object} [filter] - Filter events to not execute if 1 of the values does not match the emited arguments * @param {EventCallback} func */ global.sys.on = function (event, id, filter, func) {}; /** * Emits event to all listening handlers with args * @param {string} event * @param {Object} [args] */ global.sys.emit = function (event, args) {}; /** * Disables any event with id * @param {string} id */ global.sys.clearEvent = function (id) {}; /** * Returns the number of seconds since the engine started with at least milisecond accuracy * @return {number} */ global.sys.microtime = function () {}; /** * @typedef {Object} HeapStats * @property {number} heapLimit The maximum size of the heap * @property {number} heapTotalSize The total size of the heap * @property {number} heapTotalExecSize The total amount of execuatable memory in the heap * @property {number} heapUsed The used amount of heap space */ /** * Returns a object containing current heap statistics from V8 * @return {HeapStats} */ global.sys.heapStats = function () {}; /** * @typedef {Object} MemoryStats * @property {number} totalVirtual The amount of virtual memory in use by the system * @property {number} totalVirtualFree The amount of free virtual memory avalible for processes on the system * @property {number} myVirtualUsed The amount of virtual memory in use by the Engine * @property {number} totalPhysical The total amount of physical memory installed in the system * @property {number} totalPhysicalFree How much free memory the system has * @property {number} myPhysicalUsed How much physical memory the Engine is using */ /** * Returns a object of current system memory stats * @return {MemoryStats} */ global.sys.memoryStats = function () {}; /** * Dumps a stacktrace to the console, this won't relyably show which C++ function called the script */ global.sys.trace = function () {}; /** * Exits the engine after the frame ends */ global.sys.exit = function () {}; /** * @typedef {Object} OpenGLVersion * @property {number} major The major version of OpenGL * @property {number} minor The minor version of OpenGL * @property {number} rev The revision of OpenGL */ /** * Returns a object contining the current OpenGL version * @return {OpenGLVersion} */ global.sys.getGLVersion = function () {}; /** * Returns true if the OpenGL extention is avalibe to current instance of the Engine * @param {strirg} extention * @return {Boolean} */ global.sys.hasExtention = function (extention) {}; /** * Returns a list of all OpenGL extentions supported in the current instance of the Engine * @return {string[]} */ global.sys.getExtentions = function () {}; /** * Returns the maximum texture size supported by the Graphics Card installed in the system * @return {number} */ global.sys.getMaxTextureSize = function () {}; /** * Save a screenshot at the end of the frame to path * requires that fs.configDir has been called beforehand * @param {string} path */ global.sys.saveScreenshot = function (path) {}; /** * Resizes the current window to width by height * @param {number} width * @param {number} height */ global.sys.resizeWindow = function (width, height) {}; /** * Toggles the window into fullscreen mode * @deprecated Crashes OpenGL 3.x due to a bug in the Engine */ global.sys.toggleFullscreen = function () {}; /** * Closes and reopens the window resetting any render paramters * @deprecated Crashes OpenGL 3.x due to a bug in the Engine */ global.sys.restartRenderer = function () {}; /** * Returns the last timespan zone took in seconds * @param {string} zone * @return {number} */ global.sys.getProfilerTime = function (zone) {}; /** * Returns a list of all profiler zones in this session * @return {string[]} */ global.sys.getProfilerZones = function () {}; /** * @callback TimingFuncion */ /** * Time how long it takes for func to execute using the profiler * Requires core.debug.profiler * @param {string} name - A label to use for the results * @param {TimingFuncion} func */ global.sys.perf = function () {}; /** * Time how long it takes for func to execute * @param {string} name - A label to use for the results * @param {TimingFuncion} func */ global.sys.time = function (name, func) {}; /** * Sets and Gets config paramters * @example <caption>Without any arguments it prints a list of all configs</caption> * sys.config(); * @example <caption>Just passing a key returns the current value</caption> * var startingWidth = sys.config("core.window.width"); * @example <caption>Passing a value sets key=value</caption> * sys.config("core.runOnIdle", true); * @param {string} key * @param {string|boolean|number} value */ global.sys.config = function (key, value) {}; /** * Manuly invokes the garbage collector. */ global.sys.gc = function () {}; /** * Captures profiling results for frames and then writes them in CSV format to filename, fs.configDir has be called beforehand. * @example * fs.configDir("example"); * sys.profile(100, "profileResults.csv"); * @param {number} frames * @param {string} filename */ global.sys.profile = function (frames, filename) {}; /** * Changes enables or disables maximum profile zone time. A warning will be printed if this time is exceaded. * @example * sys.profileSet("Frame", false); // Disable frametime performace warnings * @param {string} profileZone - The zone to modify * @param {number|boolean} maxTime - The maximum time in seconds that the zone can take before printing a warning, pass false to disable */ global.sys.profileSet = function (profileZone, maxTime) {}; /** * Forces lib/boot.js to be reloaded at the start of the next frame */ global.sys.reloadRootScript = function () {}; /** * Forces script to be reloaded at the start of the next frame * @example * function lose() { * sys.forceReload("script/game.js"); // Restart the game when the player loses * } * @param {string} script - The filename of the script to reload including the extention */ global.sys.forceReload = function (script) {}; /** * @typedef {object} VersionInfo * @property {string} openGL The OpenGL version currently in use * @property {string} glew The version of GLEW the engine was compiled with * @property {string} v8 The version of V8 the engine was compiled with * @property {string} engine The release version identifyer for the engine * @property {string} glfw The version of GLFW compiled into the engine * @property {string} glsl The version of GLSL currently in use with OpenGL */ /** * Returns a {@link VersionInfo} object specifying the versions in use currently * @return {VersionInfo} */ global.sys.version = function () {}; /** * Shows a platform dependent MessageBox * @param {string} title * @param {string} msg * @param {boolean} modal - Should the code block until the box is closed */ global.sys.msgBox = function (title, msg, modal) {}; /** * Open filename with the default handler for the format * @example * sys.shell("http://vbitz.com/"); // Open vbitz.com with the default web browser * @param {string} filename */ global.sys.shell = function (filename) {}; /** * The current platform the engine is running on, the value can be "Windows"|"Darwin (OSX)"|"Linux" * @type {String} */ global.sys.platform = ""; /** * Is the engine running in developer mode. Developer mode allows arbitiry code execution and enables the console and profiler * @type {Boolean} */ global.sys.devMode = false; /** * Has the OpenGL context been created yet? * @type {Boolean} */ global.sys.preload = false; /** * The number of processers installed in the system. * @type {Number} */ global.sys.numProcessers = 0; /** * The username of the currently logged in user. * @type {String} */ global.sys.username = ""; /** * The width of the Engine viewpoint * @type {Number} */ global.sys.screenWidth = 0; /** * The height of the Engine viewpoint * @type {Number} */ global.sys.screenHeight = 0; /** * The number of seconds since the last frame. * @type {Number} */ global.sys.deltaTime = 0; /** @namespace */ global.fs = {}; /** * Returns the content of the file mounted at path. * @param {string} filename * @param {boolean} [raw] - If true the function will return a raw byte array * @return {string|number[]} */ global.fs.readFile = function (filename, raw) {}; /** * Writes content to filename mounted on PhysFS * @param {string} filename * @param {string} content */ global.fs.writeFile = function (filename, content) {}; /** * Returns true if filename exists. * @param {string} filename * @return {boolean} */ global.fs.fileExists = function (filename) {}; /** * Returns the filesize of filename in bytes * @param {string} filename * @return {number} */ global.fs.fileSize = function (filename) {}; /** * Mounts archivePath to mountPath on PhysFS. filetypes supported by archivePath including .zip and .7z * @param {string} archivePath * @param {string} mountPath */ global.fs.mountFile = function (archivePath, mountPath) {}; /** * Set's up a directory under the user's local profile to write files to. This function must be called before any files can be writen. * @param {string} appName - The name of the directory, this should be a unique application name */ global.fs.configDir = function (appName) {}; /** * Create's a new directory at path. * @param {string} path */ global.fs.mkdir = function (path) {}; /** @namespace */ global.draw = {}; /** * Draw a rectange with the current color at x,y, w, h in size * @param {number} x * @param {number} y * @param {number} w * @param {number} h */ global.draw.rect = function (x, y, w, h) {}; /** * Draw a rectange outline with the current color at x,y, w, h in size * @param {number} x * @param {number} y * @param {number} w * @param {number} h */ global.draw.grid = function (x, y, w, h) {}; /** * Draw a rectange filled with a left/right or up/down gradient specifyed by col1 and col2 at x,y, w, h in size * @param {number} x * @param {number} y * @param {number} w * @param {number} h * @param {number} col1 - Specifyed as a number with the format 0xrrggbb * @param {number} col2 - Specifyed as a number with the format 0xrrggbb * @param {boolean} orientation - true for up/down and false for left/right */ global.draw.grad = function (x, y, w, h, col1, col2, orientation) {}; /** * Draw circular primatives including pie slices, doughnuts and circles * @param {number} x * @param {number} y * @param {number} radius * @param {number} [innerRadius] - Set to radius to draw a regular circle, radius by default * @param {number} [numberOfSides] - The number of vertex's at the edge of the circle, radius * 5 by default * @param {number} [startPos] - Start persent of the circle, 0.0 by default * @param {number} [endPos] - End persent of the circle, 1.0 by default * @param {number} [fillStyle] - Fill the inside of the circle or draw a line strip at the edge */ global.draw.circle = function (x, y, radius, innerRadius, numberOfSides, startPos, endPos, fillStyle) {}; /** * Draw a line from x0, y0 to x1, y1 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 */ global.draw.line = function (x0, y0, x1, y1) {}; /** * Draw a cubic benzier curve from x0, y0, to x3, y3 through x1, y1 and x2, y2 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 */ global.draw.curve = function (x0, y0, x1, y1, x2, y2, x3, y3) {}; /** * Set's predefined colors for use in draw.setColor * @param {string|Object} name * @param {number} color * @example <caption>Used with 2 arguments draw.colorPalette accepts a string and a color</caption> * draw.colorPalette("blue", 0x0000ff); * @example <caption>Used with 1 object draw.colorPalette set's each string to a color value</caption> * draw.colorPalette({ * "red": 0xff0000, * "green": 0x00ff00, * "blue": 0x0000ff * }); */ global.draw.colorPalette = function (name, color) {}; /** * Set's the current drawing color to r, g, b * @param {number} r - The red value between 0.0 and 1.0 * @param {number} g - The green value between 0.0 and 1.0 * @param {number} b - The blue value between 0.0 and 1.0 */ global.draw.setColorF = function (r, g, b) {}; /** * @typedef {Object} Color * @property {number} r The red value between 0.0 and 1.0 * @property {number} g The green value between 0.0 and 1.0 * @property {number} b The blue value between 0.0 and 1.0 */ /** * Set's the current drawing color * @param {string|number|Color} color * @example <caption>Passing a string set's the color to a predefined color</caption> * draw.setColor("red"); * @example <caption>Passing a number in the format 0xrrggbb set's the color to that value</caption> * draw.setColor(0xff0000); * @example <caption>Passing a {@link Color} set's it to the value inside color</caption> * draw.setColor({r: 1.0, g: 0.0, b: 0.0}) */ global.draw.setColor = function (color) {}; /** * Set's the current drawing color to r, g, b * @param {number} r - The red value between 0 and 255 * @param {number} g - The green value between 0 and 255 * @param {number} b - The blue value between 0 and 255 */ global.draw.setColorI = function (r, g, b) {}; /** * Set's the background clear color * @param {string|number} color - Same argument format as {@link global.draw.setColor} without support for {@link Color} */ global.draw.clearColor = function (color) {}; /** * Returns a {@link Color} from the HSV values * @param {number} h - The Hue Component between 0 and 360 * @param {number} s - The Saturation Component between 0.0f and 1.0f * @param {number} v - The Value Component between 0.0f and 1.0f * @return {Color} */ global.draw.getRGBFromHSV = function (h, s, v) {}; /** * Prints str at x, y using the current font * @param {number} x * @param {number} y * @param {string} str */ global.draw.print = function (x, y, str) {}; /** * Returns the width of str in pixels * @param {string} str * @return {number} */ global.draw.getStringWidth = function (str) {}; /** * @typedef {number} TextureID */ /** * Renders the image specifyed by texId at x, y sized at w, h * @param {TextureID} texId * @param {number} x * @param {number} y * @param {number} w * @param {number} h */ global.draw.draw = function (texId, x, y, w, h) {}; /** * Renders a segment of the image specifyed by texId at x, y sized at w, h * @param {TextureID} texId * @param {number} x * @param {number} y * @param {number} w * @param {number} h * @param {number} xSub * @param {number} ySub * @param {number} wSub * @param {number} hSub */ global.draw.drawSub = function (texId, x, y, w, h, xSub, ySub, wSub, hSub) {}; /** * Loads filename as a image, most file formats are supported using FreeImage * @param {string} filename * @return {TextureID} */ global.draw.openImage = function (filename) {}; /** * @typedef {number[]} Image * Image is optimised for loading using {@link global.draw.createImage} * @property {number} width The width of the image * @property {number} height The height of the image */ /** * Loads filename as a image returning the raw pixel array * @param {string} filename * @return {Image} */ global.draw.getImageArray = function (filename) {}; /** * Returns a {@link Image} with width * height pixels * @param {number} w * @param {number} h * @return {Image} */ global.draw.createImageArray = function (w, h) {}; /** * Converts a {@link Image} into a {@link TextureID} * @param {Image|number[]} arr - {@link Image} is strongly prefered to number[] * @param {number} w - The width of the Image to create * @param {number} h - The height of the Image to create * @return {TextureID} */ global.draw.createImage = function (arr, w, h) {}; /** * Save texId to filename, requires fs.configDir to be called before hand * @param {TextureID} texId * @param {string} filename */ global.draw.saveImage = function (texId, filename) {}; /** * Delete's texId from the system's graphics memory * @param {TextureID} texId */ global.draw.freeImage = function (texId) {}; /** * Returns true if texId is valid * @param {TextureID} texId * @return {Boolean} */ global.draw.isTexture = function (texId) {}; /** * Reset the current camera positon * @deprecated Not avalible on OpenGL 3.3 yet */ global.draw.cameraReset = function () {}; /** * Pans the camera by x, y * @deprecated Not avalible on OpenGL 3.3 yet * @param {number} x * @param {number} y */ global.draw.cameraPan = function (x, y) {}; /** * Zooms the camera by factor f * @deprecated Not avalible on OpenGL 3.3 yet * @param {number} f */ global.draw.cameraZoom = function (f) {}; /** * Rotates the camera by r degrees * @deprecated Not avalible on OpenGL 3.3 yet * @param {number} r */ global.draw.cameraRotate = function (r) {}; /** * Set's the current font to prettyName, size. The font will be loaded if it does not exist * @param {string} prettyName * @param {number} size */ global.draw.setFont = function (prettyName, size) {}; /** * Load a .ttf font file. The font is not loaded until setFont is called at least once * @param {string} prettyName * @param {string} filename */ global.draw.loadFont = function (prettyName, filename) {}; /** * Returns true if the font pointed to by prettyName is loaded * @param {string} prettyName * @return {Boolean} */ global.draw.isFontLoaded = function (prettyName) {}; /** * Returns the number of verts rendered this frame * @return {number} */ global.draw.getVerts = function () {}; /** * Should offscreen objects be rendered * @deprecated Not Implamented * @param {boolean} draw */ global.draw.setDrawOffscreen = function (draw) {}; /** * Set's the point to center drawing around * @param {number} x * @param {number} y */ global.draw.setCenter = function (x, y) {}; /** @namespace */ global.input = {}; /** * Returns true if key is pressed * @param {string} key * @return {boolean} */ global.input.keyDown = function (key) {}; /** * The X postion of the mouse * @type {Number} */ global.input.mouseX = 0; /** * The Y postion of the mouse * @type {Number} */ global.input.mouseY = 0; /** * The Left mouse button state * @type {Boolean} */ global.input.leftMouseButton = false; /** * The Middle mouse button state * @type {Boolean} */ global.input.middleMouseButton = false; /** * The Right mouse button state * @type {Boolean} */ global.input.rightMouseButton = false; /** @namespace */ global.mod = {}; /** * @typedef {number} ModuleID */ /** * Open a module at filename * @param {string} filename - The real filename path to the module without a extention * @return {ModuleID} */ global.mod.open = function (filename) {}; /** * Call a paramterless method exported by the module defined by id * @param {ModuleID} id * @param {string} method */ global.mod.call = function (id, method) {}; /** * db is powered by sqlite3 and uses SQL syntax for statements * @type {Object} */ global.db = {}; /** * Opens or creates a sqlite3 database at filename * @param {string} filename */ global.db.open = function (filename) {}; /** * Executes a statement * @param {string} statement - A valid SQL statement * @return {[type]} */ global.db.exec = function (statement) {}; /** * Executes a statement and returns the responce as a table * @param {string} statement - A valid SQL statement * @return {Object[]} */ global.db.execPrepare = function (statement) {}; /** * Currently only defined if Developer Mode is enabled * @namespace */ global.unsafe = {}; global.unsafe.getNumberAddress = function () {}; global.unsafe.getNative = function () {}; global.unsafe.call = function () {}; global.unsafe.malloc = function () {}; global.unsafe.free = function () {}; global.unsafe.addressOf = function () {}; global.unsafe.mprotect = function () {}; global.unsafe.getPageSize = function () {};
doc/api.js
// Engine2D Javascript API Documentation // Correct as of 14th Jan 2014 this.global = this; // Global object exposed as global /** @namespace */ global.console = {}; /** * Low level logging function that prints obj at level * * @param {string} level - The level to log at can be "warning"|"verbose"|"error"|"raw"|"log" * @param {...*} obj - The value to print, internaly the values will be joined with spaces * @internal */ global.console._log = function (level, obj) {}; /** * Hide all output on the EngineUI console */ global.console.clear = function () {}; /** * Toggle the EngineUI console */ global.console.toggle = function () {}; /** * Derived off global.console._log, prints with a user loglevel * @param {...*} obj - The value to print, internaly the values will be joined with spaces */ global.console.log = function (obj) {}; /** * Derived off global.console._log, prints with a warning loglevel * @param {...*} obj - The value to print, internaly the values will be joined with spaces */ global.console.warn = function (obj) {}; /** * Derived off global.console._log, prints with a error loglevel * @param {...*} obj - The value to print, internaly the values will be joined with spaces */ global.console.error = function (obj) {}; /** * Derived off global.console._log, prints with a verbose loglevel * @param {...*} obj - The value to print, internaly the values will be joined with spaces */ global.console.verbose = function (obj) {}; /** * Derived off global.console._log, prints without using the Logger interface directly to the system console * @param {...*} obj - The value to print, internaly the values will be joined with spaces */ global.console.writeRaw = function (obj) {}; /** @namespace */ global.sys = {}; /** * Returns an array of command line arguments passed to the engine * @return {string[]} */ global.sys.argv = function () {}; /** * Load and execute a javascript file from the filesystem * Requires that core.script.autoReload == true * @param {string} filename - The filename of the script to load without the .js extention * @param {boolean} persists - Should this file be automaticly reloaded? */ global.sys.runFile = function (filename, persists) {}; /** * @callback DrawFunction */ /** * Calls func each frame so drawing can be performed * @deprecated In favor of the "draw" event * @param {DrawFunction} func */ global.sys.drawFunc = function (func) {}; /** * @callback KeyboardFunction * @param {null} _ - Always "" * @param {string} char - The key pressed/released * @param {boolean} press - True if the key was pressed otherwise false */ /** * Calls func whenever a key is pressed * @deprecated In favor of the "input" event * @param {KeyboardFunction} func */ global.sys.keyboardFunc = function (func) {}; /** * @callback EventCallback * @param {Object} args - Event Arguments */ /** * Registers func to be called when event is emited * @param {string} event * @param {string} id - A unique ID to assoiate with the function * @param {Object} [filter] - Filter events to not execute if 1 of the values does not match the emited arguments * @param {EventCallback} func */ global.sys.on = function (event, id, filter, func) {}; /** * Emits event to all listening handlers with args * @param {string} event * @param {Object} [args] */ global.sys.emit = function (event, args) {}; /** * Disables any event with id * @param {string} id */ global.sys.clearEvent = function (id) {}; /** * Returns the number of seconds since the engine started with at least milisecond accuracy * @return {number} */ global.sys.microtime = function () {}; /** * @typedef {Object} HeapStats * @property {number} heapLimit The maximum size of the heap * @property {number} heapTotalSize The total size of the heap * @property {number} heapTotalExecSize The total amount of execuatable memory in the heap * @property {number} heapUsed The used amount of heap space */ /** * Returns a object containing current heap statistics from V8 * @return {HeapStats} */ global.sys.heapStats = function () {}; /** * @typedef {Object} MemoryStats * @property {number} totalVirtual The amount of virtual memory in use by the system * @property {number} totalVirtualFree The amount of free virtual memory avalible for processes on the system * @property {number} myVirtualUsed The amount of virtual memory in use by the Engine * @property {number} totalPhysical The total amount of physical memory installed in the system * @property {number} totalPhysicalFree How much free memory the system has * @property {number} myPhysicalUsed How much physical memory the Engine is using */ /** * Returns a object of current system memory stats * @return {MemoryStats} */ global.sys.memoryStats = function () {}; /** * Dumps a stacktrace to the console, this won't relyably show which C++ function called the script */ global.sys.trace = function () {}; /** * Exits the engine after the frame ends */ global.sys.exit = function () {}; /** * @typedef {Object} OpenGLVersion * @property {number} major The major version of OpenGL * @property {number} minor The minor version of OpenGL * @property {number} rev The revision of OpenGL */ /** * Returns a object contining the current OpenGL version * @return {OpenGLVersion} */ global.sys.getGLVersion = function () {}; /** * Returns true if the OpenGL extention is avalibe to current instance of the Engine * @param {strirg} extention * @return {Boolean} */ global.sys.hasExtention = function (extention) {}; /** * Returns a list of all OpenGL extentions supported in the current instance of the Engine * @return {string[]} */ global.sys.getExtentions = function () {}; /** * Returns the maximum texture size supported by the Graphics Card installed in the system * @return {number} */ global.sys.getMaxTextureSize = function () {}; /** * Save a screenshot at the end of the frame to path * requires that fs.configDir has been called beforehand * @param {string} path */ global.sys.saveScreenshot = function (path) {}; /** * Resizes the current window to width by height * @param {number} width * @param {number} height */ global.sys.resizeWindow = function (width, height) {}; /** * Toggles the window into fullscreen mode * @deprecated Crashes OpenGL 3.x due to a bug in the Engine */ global.sys.toggleFullscreen = function () {}; /** * Closes and reopens the window resetting any render paramters * @deprecated Crashes OpenGL 3.x due to a bug in the Engine */ global.sys.restartRenderer = function () {}; /** * Returns the last timespan zone took in seconds * @param {string} zone * @return {number} */ global.sys.getProfilerTime = function (zone) {}; /** * Returns a list of all profiler zones in this session * @return {string[]} */ global.sys.getProfilerZones = function () {}; /** * @callback TimingFuncion */ /** * Time how long it takes for func to execute using the profiler * Requires core.debug.profiler * @param {string} name - A label to use for the results * @param {TimingFuncion} func */ global.sys.perf = function () {}; /** * Time how long it takes for func to execute * @param {string} name - A label to use for the results * @param {TimingFuncion} func */ global.sys.time = function (name, func) {}; /** * Sets and Gets config paramters * @example <caption>Without any arguments it prints a list of all configs</caption> * sys.config(); * @example <caption>Just passing a key returns the current value</caption> * var startingWidth = sys.config("core.window.width"); * @example <caption>Passing a value sets key=value</caption> * sys.config("core.runOnIdle", true); * @param {string} key * @param {string|boolean|number} value */ global.sys.config = function (key, value) {}; /** * Manuly invokes the garbage collector. */ global.sys.gc = function () {}; /** * Captures profiling results for frames and then writes them in CSV format to filename, fs.configDir has be called beforehand. * @example * fs.configDir("example"); * sys.profile(100, "profileResults.csv"); * @param {number} frames * @param {string} filename */ global.sys.profile = function (frames, filename) {}; /** * Changes enables or disables maximum profile zone time. A warning will be printed if this time is exceaded. * @example * sys.profileSet("Frame", false); // Disable frametime performace warnings * @param {string} profileZone - The zone to modify * @param {number|boolean} maxTime - The maximum time in seconds that the zone can take before printing a warning, pass false to disable */ global.sys.profileSet = function (profileZone, maxTime) {}; /** * Forces lib/boot.js to be reloaded at the start of the next frame */ global.sys.reloadRootScript = function () {}; /** * Forces script to be reloaded at the start of the next frame * @example * function lose() { * sys.forceReload("script/game.js"); // Restart the game when the player loses * } * @param {string} script - The filename of the script to reload including the extention */ global.sys.forceReload = function (script) {}; /** * @typedef {object} VersionInfo * @property {string} openGL The OpenGL version currently in use * @property {string} glew The version of GLEW the engine was compiled with * @property {string} v8 The version of V8 the engine was compiled with * @property {string} engine The release version identifyer for the engine * @property {string} glfw The version of GLFW compiled into the engine * @property {string} glsl The version of GLSL currently in use with OpenGL */ /** * Returns a {@link VersionInfo} object specifying the versions in use currently * @return {VersionInfo} */ global.sys.version = function () {}; /** * Shows a platform dependent MessageBox * @param {string} title * @param {string} msg * @param {boolean} modal - Should the code block until the box is closed */ global.sys.msgBox = function (title, msg, modal) {}; /** * Open filename with the default handler for the format * @example * sys.shell("http://vbitz.com/"); // Open vbitz.com with the default web browser * @param {string} filename */ global.sys.shell = function (filename) {}; /** * The current platform the engine is running on, the value can be "Windows"|"Darwin (OSX)"|"Linux" * @type {String} */ global.sys.platform = ""; /** * Is the engine running in developer mode. Developer mode allows arbitiry code execution and enables the console and profiler * @type {Boolean} */ global.sys.devMode = false; /** * Has the OpenGL context been created yet? * @type {Boolean} */ global.sys.preload = false; /** * The number of processers installed in the system. * @type {Number} */ global.sys.numProcessers = 0; /** * The username of the currently logged in user. * @type {String} */ global.sys.username = ""; /** * The width of the Engine viewpoint * @type {Number} */ global.sys.screenWidth = 0; /** * The height of the Engine viewpoint * @type {Number} */ global.sys.screenHeight = 0; /** * The number of seconds since the last frame. * @type {Number} */ global.sys.deltaTime = 0; /** @namespace */ global.fs = {}; /** * Returns the content of the file mounted at path. * @param {string} filename * @param {boolean} [raw] - If true the function will return a raw byte array * @return {string|number[]} */ global.fs.readFile = function (filename, raw) {}; /** * Writes content to filename mounted on PhysFS * @param {string} filename * @param {string} content */ global.fs.writeFile = function (filename, content) {}; /** * Returns true if filename exists. * @param {string} filename * @return {boolean} */ global.fs.fileExists = function (filename) {}; /** * Returns the filesize of filename in bytes * @param {string} filename * @return {number} */ global.fs.fileSize = function (filename) {}; /** * Mounts archivePath to mountPath on PhysFS. filetypes supported by archivePath including .zip and .7z * @param {string} archivePath * @param {string} mountPath */ global.fs.mountFile = function (archivePath, mountPath) {}; /** * Set's up a directory under the user's local profile to write files to. This function must be called before any files can be writen. * @param {string} appName - The name of the directory, this should be a unique application name */ global.fs.configDir = function (appName) {}; /** * Create's a new directory at path. * @param {string} path */ global.fs.mkdir = function (path) {}; /** @namespace */ global.draw = {}; /** * Draw a rectange with the current color at x,y, w, h in size * @param {number} x * @param {number} y * @param {number} w * @param {number} h */ global.draw.rect = function (x, y, w, h) {}; /** * Draw a rectange outline with the current color at x,y, w, h in size * @param {number} x * @param {number} y * @param {number} w * @param {number} h */ global.draw.grid = function (x, y, w, h) {}; /** * Draw a rectange filled with a left/right or up/down gradient specifyed by col1 and col2 at x,y, w, h in size * @param {number} x * @param {number} y * @param {number} w * @param {number} h * @param {number} col1 - Specifyed as a number with the format 0xrrggbb * @param {number} col2 - Specifyed as a number with the format 0xrrggbb * @param {boolean} orientation - true for up/down and false for left/right */ global.draw.grad = function (x, y, w, h, col1, col2, orientation) {}; /** * Draw circular primatives including pie slices, doughnuts and circles * @param {number} x * @param {number} y * @param {number} radius * @param {number} [innerRadius] - Set to radius to draw a regular circle, radius by default * @param {number} [numberOfSides] - The number of vertex's at the edge of the circle, radius * 5 by default * @param {number} [startPos] - Start persent of the circle, 0.0 by default * @param {number} [endPos] - End persent of the circle, 1.0 by default * @param {number} [fillStyle] - Fill the inside of the circle or draw a line strip at the edge */ global.draw.circle = function (x, y, radius, innerRadius, numberOfSides, startPos, endPos, fillStyle) {}; /** * Draw a line from x0, y0 to x1, y1 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 */ global.draw.line = function (x0, y0, x1, y1) {}; /** * Draw a cubic benzier curve from x0, y0, to x3, y3 through x1, y1 and x2, y2 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 */ global.draw.curve = function (x0, y0, x1, y1, x2, y2, x3, y3) {}; /** * Set's predefined colors for use in draw.setColor * @param {string|Object} name * @param {number} color * @example <caption>Used with 2 arguments draw.colorPalette accepts a string and a color</caption> * draw.colorPalette("blue", 0x0000ff); * @example <caption>Used with 1 object draw.colorPalette set's each string to a color value</caption> * draw.colorPalette({ * "red": 0xff0000, * "green": 0x00ff00, * "blue": 0x0000ff * }); */ global.draw.colorPalette = function (name, color) {}; /** * Set's the current drawing color to r, g, b * @param {number} r - The red value between 0.0 and 1.0 * @param {number} g - The green value between 0.0 and 1.0 * @param {number} b - The blue value between 0.0 and 1.0 */ global.draw.setColorF = function (r, g, b) {}; /** * @typedef {Object} Color * @property {number} r The red value between 0.0 and 1.0 * @property {number} g The green value between 0.0 and 1.0 * @property {number} b The blue value between 0.0 and 1.0 */ /** * Set's the current drawing color * @param {string|number|Color} color * @example <caption>Passing a string set's the color to a predefined color</caption> * draw.setColor("red"); * @example <caption>Passing a number in the format 0xrrggbb set's the color to that value</caption> * draw.setColor(0xff0000); * @example <caption>Passing a {@link Color} set's it to the value inside color</caption> * draw.setColor({r: 1.0, g: 0.0, b: 0.0}) */ global.draw.setColor = function (color) {}; /** * Set's the current drawing color to r, g, b * @param {number} r - The red value between 0 and 255 * @param {number} g - The green value between 0 and 255 * @param {number} b - The blue value between 0 and 255 */ global.draw.setColorI = function (r, g, b) {}; /** * Set's the background clear color * @param {string|number} color - Same argument format as {@link global.draw.setColor} without support for {@link Color} */ global.draw.clearColor = function (color) {}; /** * Returns a {@link Color} from the HSV values * @param {number} h - The Hue Component between 0 and 360 * @param {number} s - The Saturation Component between 0.0f and 1.0f * @param {number} v - The Value Component between 0.0f and 1.0f * @return {Color} */ global.draw.getRGBFromHSV = function (h, s, v) {}; /** * Prints str at x, y using the current font * @param {number} x * @param {number} y * @param {string} str */ global.draw.print = function (x, y, str) {}; /** * Returns the width of str in pixels * @param {string} str * @return {number} */ global.draw.getStringWidth = function (str) {}; /** * @typedef {number} TextureID */ /** * Renders the image specifyed by texId at x, y sized at w, h * @param {TextureID} texId * @param {number} x * @param {number} y * @param {number} w * @param {number} h */ global.draw.draw = function (texId, x, y, w, h) {}; /** * Renders a segment of the image specifyed by texId at x, y sized at w, h * @param {TextureID} texId * @param {number} x * @param {number} y * @param {number} w * @param {number} h * @param {number} xSub * @param {number} ySub * @param {number} wSub * @param {number} hSub */ global.draw.drawSub = function (texId, x, y, w, h, xSub, ySub, wSub, hSub) {}; /** * Loads filename as a image, most file formats are supported using FreeImage * @param {string} filename * @return {TextureID} */ global.draw.openImage = function (filename) {}; /** * @typedef {number[]} Image * Image is optimised for loading using {@link global.draw.createImage} * @property {number} width The width of the image * @property {number} height The height of the image */ /** * Loads filename as a image returning the raw pixel array * @param {string} filename * @return {Image} */ global.draw.getImageArray = function (filename) {}; /** * Returns a {@link Image} with width * height pixels * @param {number} w * @param {number} h * @return {Image} */ global.draw.createImageArray = function (w, h) {}; /** * Converts a {@link Image} into a {@link TextureID} * @param {Image|number[]} arr - {@link Image} is strongly prefered to number[] * @param {number} w - The width of the Image to create * @param {number} h - The height of the Image to create * @return {TextureID} */ global.draw.createImage = function (arr, w, h) {}; /** * Save texId to filename, requires fs.configDir to be called before hand * @param {TextureID} texId * @param {string} filename */ global.draw.saveImage = function (texId, filename) {}; /** * Delete's texId from the system's graphics memory * @param {TextureID} texId */ global.draw.freeImage = function (texId) {}; /** * Returns true if texId is valid * @param {TextureID} texId * @return {Boolean} */ global.draw.isTexture = function (texId) {}; /** * Reset the current camera positon * @deprecated Not avalible on OpenGL 3.3 yet */ global.draw.cameraReset = function () {}; /** * Pans the camera by x, y * @deprecated Not avalible on OpenGL 3.3 yet * @param {number} x * @param {number} y */ global.draw.cameraPan = function (x, y) {}; /** * Zooms the camera by factor f * @deprecated Not avalible on OpenGL 3.3 yet * @param {number} f */ global.draw.cameraZoom = function (f) {}; /** * Rotates the camera by r degrees * @deprecated Not avalible on OpenGL 3.3 yet * @param {number} r */ global.draw.cameraRotate = function (r) {}; /** * Set's the current font to prettyName, size. The font will be loaded if it does not exist * @param {string} prettyName * @param {number} size */ global.draw.setFont = function (prettyName, size) {}; /** * Load a .ttf font file. The font is not loaded until setFont is called at least once * @param {string} prettyName * @param {string} filename */ global.draw.loadFont = function (prettyName, filename) {}; /** * Returns true if the font pointed to by prettyName is loaded * @param {string} prettyName * @return {Boolean} */ global.draw.isFontLoaded = function (prettyName) {}; /** * Returns the number of verts rendered this frame * @return {number} */ global.draw.getVerts = function () {}; /** * Should offscreen objects be rendered * @deprecated Not Implamented * @param {boolean} draw */ global.draw.setDrawOffscreen = function (draw) {}; /** * Set's the point to center drawing around * @param {number} x * @param {number} y */ global.draw.setCenter = function (x, y) {}; /** @namespace */ global.input = {}; /** * Returns true if key is pressed * @param {string} key * @return {boolean} */ global.input.keyDown = function (key) {}; /** * The X postion of the mouse * @type {Number} */ global.input.mouseX = 0; /** * The Y postion of the mouse * @type {Number} */ global.input.mouseY = 0; /** * The Left mouse button state * @type {Boolean} */ global.input.leftMouseButton = false; /** * The Middle mouse button state * @type {Boolean} */ global.input.middleMouseButton = false; /** * The Right mouse button state * @type {Boolean} */ global.input.rightMouseButton = false; /** @namespace */ global.mod = {}; global.mod.open = function () {}; global.mod.call = function () {}; /** @namespace */ global.db = {}; global.db.open = function () {}; global.db.exec = function () {}; global.db.execPrepare = function () {}; /** Currently only defined if Developer Mode is enabled * @namespace */ global.unsafe = {}; global.unsafe.getNumberAddress = function () {}; global.unsafe.getNative = function () {}; global.unsafe.call = function () {}; global.unsafe.malloc = function () {}; global.unsafe.free = function () {}; global.unsafe.addressOf = function () {}; global.unsafe.mprotect = function () {}; global.unsafe.getPageSize = function () {};
Documented mod and db modules
doc/api.js
Documented mod and db modules
<ide><path>oc/api.js <ide> // Engine2D Javascript API Documentation <del>// Correct as of 14th Jan 2014 <add>// Correct as of 18th Jan 2014 <ide> <ide> this.global = this; // Global object exposed as global <ide> <ide> /** @namespace */ <ide> global.mod = {}; <ide> <del>global.mod.open = function () {}; <del>global.mod.call = function () {}; <del> <del>/** @namespace */ <add>/** <add> * @typedef {number} ModuleID <add> */ <add> <add>/** <add> * Open a module at filename <add> * @param {string} filename - The real filename path to the module without a extention <add> * @return {ModuleID} <add> */ <add>global.mod.open = function (filename) {}; <add> <add>/** <add> * Call a paramterless method exported by the module defined by id <add> * @param {ModuleID} id <add> * @param {string} method <add> */ <add>global.mod.call = function (id, method) {}; <add> <add>/** <add> * db is powered by sqlite3 and uses SQL syntax for statements <add> * @type {Object} <add> */ <ide> global.db = {}; <ide> <del>global.db.open = function () {}; <del>global.db.exec = function () {}; <del>global.db.execPrepare = function () {}; <del> <del>/** Currently only defined if Developer Mode is enabled <add>/** <add> * Opens or creates a sqlite3 database at filename <add> * @param {string} filename <add> */ <add>global.db.open = function (filename) {}; <add> <add>/** <add> * Executes a statement <add> * @param {string} statement - A valid SQL statement <add> * @return {[type]} <add> */ <add>global.db.exec = function (statement) {}; <add> <add>/** <add> * Executes a statement and returns the responce as a table <add> * @param {string} statement - A valid SQL statement <add> * @return {Object[]} <add> */ <add>global.db.execPrepare = function (statement) {}; <add> <add>/** <add> * Currently only defined if Developer Mode is enabled <ide> * @namespace <ide> */ <ide> global.unsafe = {};
JavaScript
mit
eda9517bba33919bfab5b0de8e3591fba865cccc
0
fateevv/basisjs,tyanas/basisjs,smelukov/basisjs,basisjs/basisjs,tyanas/basisjs,fateevv/basisjs,smelukov/basisjs,smelukov/basisjs,fateevv/basisjs,istrel/basisjs,istrel/basisjs,basisjs/basisjs,basisjs/basisjs,istrel/basisjs,tyanas/basisjs
var document = global.document; var getComputedStyle = global.getComputedStyle; var HEIGHT = 150; var WIDTH = 150; var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var baselineCache = {}; canvas.width = WIDTH; canvas.height = HEIGHT; function getTop(font, baseline){ ctx.font = font; ctx.clearRect(0, 0, WIDTH, HEIGHT); ctx.textBaseline = baseline; ctx.fillText('x', 0, HEIGHT); var width = ctx.measureText('x').width; // getImageData with source width == 0 returns an error. // covering that case if (!width) return 0; var image = ctx.getImageData(0, 0, width, HEIGHT); var count = image.width * image.height * 4; var data = image.data; var line = 'unknown'; for (var i = 3; i < count; i += 4) if (data[i]) return Math.floor(i / (image.width * 4)); } module.exports = function getBaseline(text){ var font = getComputedStyle(text.parentNode).font; if (font in baselineCache) return baselineCache[font]; var baseline = getTop(font, 'alphabetic') - getTop(font, 'bottom'); baselineCache[font] = baseline; return baselineCache[font]; };
src/devpanel/inspector/utils/baseline.js
var document = global.document; var getComputedStyle = global.getComputedStyle; var HEIGHT = 150; var WIDTH = 150; var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var baselineCache = {}; canvas.width = WIDTH; canvas.height = HEIGHT; function getTop(font, baseline){ ctx.font = font; ctx.clearRect(0, 0, WIDTH, HEIGHT); ctx.textBaseline = baseline; ctx.fillText('x', 0, HEIGHT); var width = ctx.measureText('x').width; if (!width) return 0; var image = ctx.getImageData(0, 0, width, HEIGHT); var count = image.width * image.height * 4; var data = image.data; var line = 'unknown'; for (var i = 3; i < count; i += 4) if (data[i]) return Math.floor(i / (image.width * 4)); } module.exports = function getBaseline(text){ var font = getComputedStyle(text.parentNode).font; if (font in baselineCache) return baselineCache[font]; var baseline = getTop(font, 'alphabetic') - getTop(font, 'bottom'); baselineCache[font] = baseline; return baselineCache[font]; };
inspector.utils.baseline: comment added
src/devpanel/inspector/utils/baseline.js
inspector.utils.baseline: comment added
<ide><path>rc/devpanel/inspector/utils/baseline.js <ide> <ide> var width = ctx.measureText('x').width; <ide> <add> // getImageData with source width == 0 returns an error. <add> // covering that case <ide> if (!width) <ide> return 0; <ide>
Java
apache-2.0
7dd70e7e75f36daf5d0ad24363af63cd18bb69cf
0
MatthewTamlin/Spyglass
package com.matthewtamlin.spyglass.library.core; import android.content.Context; import android.content.res.TypedArray; import android.os.Looper; import android.util.AttributeSet; import android.view.View; import com.matthewtamlin.spyglass.library.default_adapters.DefaultAdapter; import com.matthewtamlin.spyglass.library.handler_adapters.HandlerAdapter; import com.matthewtamlin.spyglass.library.util.AnnotationUtil; import com.matthewtamlin.spyglass.library.util.ValidationUtil; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull; import static com.matthewtamlin.spyglass.library.util.AdapterUtil.getDefaultAdapter; import static com.matthewtamlin.spyglass.library.util.AdapterUtil.getHandlerAdapter; import static com.matthewtamlin.spyglass.library.util.AnnotationUtil.getDefaultAnnotation; import static com.matthewtamlin.spyglass.library.util.AnnotationUtil.getHandlerAnnotation; import static com.matthewtamlin.spyglass.library.util.ValidationUtil.validateField; import static com.matthewtamlin.spyglass.library.util.ValidationUtil.validateMethod; public class Spyglass { private View view; private Context context; private TypedArray attrSource; private Spyglass(final Builder builder) { this.view = builder.view; this.context = builder.context; this.attrSource = view.getContext().obtainStyledAttributes( builder.attributeSet, builder.styleableRes, builder.defStyleAttr, builder.defStyleRes); } public void applyAttributesTo(final View view) { checkNotNull(view, "Argument \'view\' cannot be null."); checkMainThread(); for (final Field f : view.getClass().getDeclaredFields()) { validateField(f); processField(f); } for (final Method m : view.getClass().getDeclaredMethods()) { validateMethod(m); processMethod(m); } } private void checkMainThread() { if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalThreadException("Spyglasses must only be touched by the UI thread."); } } private void processField(final Field field, final View view) { field.setAccessible(true); final Annotation handlerAnnotation = getHandlerAnnotation(field); if (handlerAnnotation != null) { final HandlerAdapter<?, Annotation> handlerAdapter = getHandlerAdapter(field); if (handlerAdapter.attributeValueIsAvailable(attrSource, handlerAnnotation)) { final Object value = handlerAdapter.getAttributeValue( attrSource, handlerAnnotation); // Assign value to field } else { final Annotation defaultAnnotation = getDefaultAnnotation(field); if (defaultAnnotation != null) { final DefaultAdapter<?, Annotation> defaultAdapter = getDefaultAdapter(field); final Object defaultValue = defaultAdapter.getDefault( defaultAnnotation, view.getContext()); // Assign value to field } else if (handlerAdapter.attributeIsMandatory(handlerAnnotation)) { // throw exception } } } } private void processMethod(final Method method, final View view) { method.setAccessible(true); final Annotation handlerAnnotation = getHandlerAnnotation(method); if (handlerAnnotation != null) { final HandlerAdapter<?, Annotation> handlerAdapter = getHandlerAdapter(method); if (handlerAdapter.attributeValueIsAvailable(attrSource, handlerAnnotation)) { final Object value = handlerAdapter.getAttributeValue( attrSource, handlerAnnotation); // call method } else { final Annotation defaultAnnotation = getDefaultAnnotation(method); if (defaultAnnotation != null) { final DefaultAdapter<?, Annotation> defaultAdapter = getDefaultAdapter(method); final Object defaultValue = defaultAdapter.getDefault( defaultAnnotation, view.getContext()); // call method } else if (handlerAdapter.attributeIsMandatory(handlerAnnotation)) { // throw exception } } } } public static Builder builder(final View view) { return new Builder(view); } public static class Builder { private View view; private Context context; private int styleableRes[]; private AttributeSet attributeSet; private int defStyleAttr; private int defStyleRes; private Builder(final View view) { this.view = checkNotNull(view, "Argument 'view' cannot be null."); } public void withContext(final Context context) { this.context = context; } public void withStyleableResource(final int[] styleableRes) { this.styleableRes = styleableRes; } public void withAttributeSet(final AttributeSet attributeSet) { this.attributeSet = attributeSet; } public void withDefStyleAttr(final int defStyleAttr) { this.defStyleAttr = defStyleAttr; } public void withDefStyleRes(final int defStyleRes) { this.defStyleRes = defStyleRes; } public Spyglass build() { checkNotNull(styleableRes, new InvalidBuilderStateException("Unable to build " + "Spyglass without a styleable resource. Call method withStyleableRes(int[]) " + "before calling build()")); checkNotNull(context, new InvalidBuilderStateException("Unable to build Spyglass " + "without a context. Call method withContext(Context) before calling build().")); return new Spyglass(this); } } }
library/src/main/java/com/matthewtamlin/spyglass/library/core/Spyglass.java
package com.matthewtamlin.spyglass.library.core; import android.content.res.TypedArray; import android.os.Looper; import android.util.AttributeSet; import android.view.View; import com.matthewtamlin.spyglass.library.default_adapters.DefaultAdapter; import com.matthewtamlin.spyglass.library.handler_adapters.HandlerAdapter; import com.matthewtamlin.spyglass.library.util.AnnotationUtil; import com.matthewtamlin.spyglass.library.util.ValidationUtil; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.Method; import static com.matthewtamlin.java_utilities.checkers.NullChecker.checkNotNull; import static com.matthewtamlin.spyglass.library.util.AdapterUtil.getDefaultAdapter; import static com.matthewtamlin.spyglass.library.util.AdapterUtil.getHandlerAdapter; import static com.matthewtamlin.spyglass.library.util.AnnotationUtil.getDefaultAnnotation; import static com.matthewtamlin.spyglass.library.util.AnnotationUtil.getHandlerAnnotation; import static com.matthewtamlin.spyglass.library.util.ValidationUtil.validateField; import static com.matthewtamlin.spyglass.library.util.ValidationUtil.validateMethod; public class Spyglass { private View view; private TypedArray attrSource; private Spyglass(final Builder builder) { this.view = builder.view; this.attrSource = view.getContext().obtainStyledAttributes( builder.attributeSet, builder.styleableRes, builder.defStyleAttr, builder.defStyleRes); } public void applyAttributesTo(final View view) { checkNotNull(view, "Argument \'view\' cannot be null."); checkMainThread(); for (final Field f : view.getClass().getDeclaredFields()) { validateField(f); processField(f); } for (final Method m : view.getClass().getDeclaredMethods()) { validateMethod(m); processMethod(m); } } private void checkMainThread() { if (Looper.myLooper() != Looper.getMainLooper()) { throw new IllegalThreadException("Spyglasses must only be touched by the UI thread."); } } private void processField(final Field field, final View view) { field.setAccessible(true); final Annotation handlerAnnotation = getHandlerAnnotation(field); if (handlerAnnotation != null) { final HandlerAdapter<?, Annotation> handlerAdapter = getHandlerAdapter(field); if (handlerAdapter.attributeValueIsAvailable(attrSource, handlerAnnotation)) { final Object value = handlerAdapter.getAttributeValue( attrSource, handlerAnnotation); // Assign value to field } else { final Annotation defaultAnnotation = getDefaultAnnotation(field); if (defaultAnnotation != null) { final DefaultAdapter<?, Annotation> defaultAdapter = getDefaultAdapter(field); final Object defaultValue = defaultAdapter.getDefault( defaultAnnotation, view.getContext()); // Assign value to field } else if (handlerAdapter.attributeIsMandatory(handlerAnnotation)) { // throw exception } } } } private void processMethod(final Method method, final View view) { method.setAccessible(true); final Annotation handlerAnnotation = getHandlerAnnotation(method); if (handlerAnnotation != null) { final HandlerAdapter<?, Annotation> handlerAdapter = getHandlerAdapter(method); if (handlerAdapter.attributeValueIsAvailable(attrSource, handlerAnnotation)) { final Object value = handlerAdapter.getAttributeValue( attrSource, handlerAnnotation); // call method } else { final Annotation defaultAnnotation = getDefaultAnnotation(method); if (defaultAnnotation != null) { final DefaultAdapter<?, Annotation> defaultAdapter = getDefaultAdapter(method); final Object defaultValue = defaultAdapter.getDefault( defaultAnnotation, view.getContext()); // call method } else if (handlerAdapter.attributeIsMandatory(handlerAnnotation)) { // throw exception } } } } public static Builder builder(final View view) { return new Builder(view); } public static class Builder { private View view; private int styleableRes[]; private AttributeSet attributeSet; private int defStyleAttr; private int defStyleRes; private Builder(final View view) { this.view = checkNotNull(view, "Argument 'view' cannot be null."); } public void withStyleableResource(final int[] styleableRes) { this.styleableRes = styleableRes; } public void withAttributeSet(final AttributeSet attributeSet) { this.attributeSet = attributeSet; } public void withDefStyleAttr(final int defStyleAttr) { this.defStyleAttr = defStyleAttr; } public void withDefStyleRes(final int defStyleRes) { this.defStyleRes = defStyleRes; } public Spyglass build() { checkNotNull(styleableRes, new InvalidBuilderStateException("Unable to build " + "Spyglass without a styleable resource. Call method withStyleableRes(int[]) " + "before calling build()")); return new Spyglass(this); } } }
Added context to builder and Spyglass
library/src/main/java/com/matthewtamlin/spyglass/library/core/Spyglass.java
Added context to builder and Spyglass
<ide><path>ibrary/src/main/java/com/matthewtamlin/spyglass/library/core/Spyglass.java <ide> package com.matthewtamlin.spyglass.library.core; <ide> <add>import android.content.Context; <ide> import android.content.res.TypedArray; <ide> import android.os.Looper; <ide> import android.util.AttributeSet; <ide> public class Spyglass { <ide> private View view; <ide> <add> private Context context; <add> <ide> private TypedArray attrSource; <ide> <ide> private Spyglass(final Builder builder) { <ide> this.view = builder.view; <add> <add> this.context = builder.context; <ide> <ide> this.attrSource = view.getContext().obtainStyledAttributes( <ide> builder.attributeSet, <ide> public static class Builder { <ide> private View view; <ide> <add> private Context context; <add> <ide> private int styleableRes[]; <ide> <ide> private AttributeSet attributeSet; <ide> <ide> private Builder(final View view) { <ide> this.view = checkNotNull(view, "Argument 'view' cannot be null."); <add> } <add> <add> public void withContext(final Context context) { <add> this.context = context; <ide> } <ide> <ide> public void withStyleableResource(final int[] styleableRes) { <ide> "Spyglass without a styleable resource. Call method withStyleableRes(int[]) " + <ide> "before calling build()")); <ide> <add> checkNotNull(context, new InvalidBuilderStateException("Unable to build Spyglass " + <add> "without a context. Call method withContext(Context) before calling build().")); <add> <ide> return new Spyglass(this); <ide> } <ide> }
Java
mit
6fd8b305984ac5faab01f3670dba740a84f16752
0
gems-uff/prov-viewer
/* * The MIT License * * Copyright 2017 Kohwalter. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package br.uff.ic.provviewer.GUI; import br.uff.ic.provviewer.EdgeType; import br.uff.ic.provviewer.GraphFrame; import static br.uff.ic.provviewer.GraphFrame.StatusFilterBox; import br.uff.ic.utility.graph.Edge; import br.uff.ic.provviewer.Stroke.EdgeStroke; import br.uff.ic.provviewer.Stroke.VertexStroke; import br.uff.ic.provviewer.Variables; import br.uff.ic.utility.graph.AgentVertex; import br.uff.ic.provviewer.Vertex.ColorScheme.VertexPainter; import br.uff.ic.utility.graph.EntityVertex; import br.uff.ic.utility.graph.Vertex; import br.uff.ic.provviewer.Vertex.VertexShape; import br.uff.ic.utility.graph.ActivityVertex; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.util.Pair; import edu.uci.ics.jung.visualization.Layer; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.CrossoverScalingControl; import edu.uci.ics.jung.visualization.control.ScalingControl; import edu.uci.ics.jung.visualization.picking.PickedState; import edu.uci.ics.jung.visualization.util.PredicatedParallelEdgeIndexFunction; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Point2D; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.swing.JComboBox; import javax.swing.JFrame; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.Transformer; /** * Class responsible for main (GUI) graph functions * @author Kohwalter */ public class GuiFunctions { /** * Method to define the vertex shape using the default shapes * @param variables */ public static void VertexShape(Variables variables) { variables.view.getRenderContext().setVertexShapeTransformer(new VertexShape(variables.config.vertexSize)); } /** * Method to define the vertex shape * @param variables * @param isVertexSizeBasedOnGraphs */ // public static void VertexShape(Variables variables, boolean isVertexSizeBasedOnGraphs) { //// variables.view.getRenderContext().setVertexShapeTransformer(new VertexShape(variables.config.vertexSize, isVertexSizeBasedOnGraphs)); // variables.view.getRenderContext().setVertexShapeTransformer(new VertexShape(variables.config.vertexSize, "Timestamp", variables.graph.getVertices())); // variables.view.repaint(); // } public static void VertexShape(Variables variables, String selectedMode, String attribute) { variables.view.getRenderContext().setVertexShapeTransformer(new VertexShape(variables.config.vertexSize, selectedMode, attribute, variables.graph.getVertices())); variables.view.repaint(); } /** * Method to define the vertex and edge borders/stroke * @param variables */ public static void Stroke(final Variables variables) { // Vertex Stroke Transformer<Object, Stroke> nodeStrokeTransformer = new Transformer<Object, Stroke>() { @Override public Stroke transform(Object v) { return VertexStroke.VertexStroke(v, variables.view, variables.layout, variables); } }; variables.view.getRenderContext().setVertexStrokeTransformer(nodeStrokeTransformer); // Change Stroke color Transformer<Object, Paint> drawPaint = new Transformer<Object, Paint>() { @Override public Paint transform(Object v) { if(variables.highlightVertexOutliers) { if(v instanceof Vertex) { float value = ((Vertex) v).getAttributeValueFloat(variables.outliersThresholds.attributeName); if(value < variables.outliersThresholds.lowerThreshold || value > variables.outliersThresholds.upperThreshold) { return new Color(255, 0, 0); } } } // if(v instanceof Vertex) { // float value = ((Vertex) v).getAttributeValueFloat("Cluster"); // if( value != value) // return new Color(0, 0, 0); // else // return Utils.getColor((int) ((Vertex) v).getAttributeValueFloat("Cluster")); // } return Color.BLACK; } }; variables.view.getRenderContext().setVertexDrawPaintTransformer(drawPaint); // Edge Stroke variables.ComputeEdgeTypeValues(); Transformer<Edge, Stroke> edgeStrokeTransformer = new Transformer<Edge, Stroke>() { @Override public Stroke transform(Edge e) { return EdgeStroke.StrokeByType(e, variables); } }; variables.view.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer); } /** * Method to display labels for vertices * @param variables * @param agentLabel interface check-box state agent label * @param activityLabel interface check-box state activity label * @param entityLabel interface check-box state for entity label * @param timeLabel interface check-box state for time label * @param showID interface check-box state for ID label */ public static void VertexLabel(final Variables variables, final boolean agentLabel, final boolean activityLabel, final boolean entityLabel, final boolean timeLabel, final boolean showID) { variables.view.getRenderContext().setVertexLabelTransformer(new Transformer<Object, String>() { @Override public String transform(Object v) { String font = "<html><font size=\"4\", font color=\"blue\">"; if (v instanceof Graph) { boolean hasActivity = false; boolean hasAgent = false; String agentName = ""; String activityName = ""; String entityName = ""; // boolean hasEntity = false; for (Object vertex : ((Graph) v).getVertices()) { if (vertex instanceof AgentVertex && agentLabel) { return font + ((Vertex) vertex).getLabel(); } if (vertex instanceof ActivityVertex) { hasActivity = true; activityName = ((Vertex)vertex).getLabel(); } if (vertex instanceof AgentVertex) { hasAgent = true; agentName = ((Vertex)vertex).getLabel(); } if (vertex instanceof EntityVertex) { entityName = ((Vertex)vertex).getLabel(); } } if(hasAgent && agentLabel) return font + agentName + " (Summarized)"; if(hasActivity && activityLabel) return font + activityName + " (Summarized)"; if(entityLabel) return font + entityName + " (Summarized)"; if(showID) { Map<String, String> ids = new HashMap<>(); GraphVertexGetID(ids, v); return font + ids.values().toString(); } } // Agent if (v instanceof AgentVertex && agentLabel) { return font + ((Vertex) v).getLabel(); } // Entity // Label + Time else if ((v instanceof EntityVertex) && entityLabel && timeLabel) { return font + String.valueOf((int) ((Vertex) v).getTime()) + " : " + ((Vertex) v).getLabel(); } // Time else if ((v instanceof EntityVertex) && timeLabel) { return font + String.valueOf((int) ((Vertex) v).getTime()); } // Label else if ((v instanceof EntityVertex) && entityLabel) { return font + ((Vertex) v).getLabel(); } // Activity // Label + Time else if ((v instanceof ActivityVertex) && activityLabel && timeLabel) { return font + String.valueOf((int) ((Vertex) v).getTime()) + " : " + ((Vertex) v).getLabel(); } // Time else if ((v instanceof ActivityVertex) && timeLabel) { return font + String.valueOf((int) ((Vertex) v).getTime()); } // Label else if ((v instanceof ActivityVertex) && activityLabel) { return font + ((Vertex) v).getLabel(); } else if(showID) return font + ((Vertex) v).getID(); return ""; } private void GraphVertexGetID(Map<String, String> ids, Object v) { Collection vertices = ((Graph) v).getVertices(); for (Object vertex : vertices) { if (!(vertex instanceof Graph)) { ids.put(((Vertex) vertex).getID(), ((Vertex) vertex).getID()); } else GraphVertexGetID(ids, vertex); } } }); } /** * Method to enable mouse interactions * @param variables */ public static void MouseInteraction(Variables variables) { // via mouse Commands: t for translate, p for picking variables.view.setGraphMouse(variables.mouse); variables.view.addKeyListener(variables.mouse.getModeKeyListener()); } /** * Method to pan the camera to the first vertex in the graph * @param variables */ public static void PanCameraToFirstVertex(Variables variables) { Vertex first = (Vertex) variables.layout.getGraph().getVertices().iterator().next(); variables.view.getGraphLayout(); Point2D q = variables.view.getGraphLayout().transform(first); Point2D lvc = variables.view.getRenderContext().getMultiLayerTransformer().inverseTransform(variables.view.getCenter()); final double dx = (lvc.getX() - q.getX()); final double dy = (lvc.getY() - q.getY()); variables.view.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).translate(dx, dy); } /** * Method to scale back the camera zoom * @param variables */ public static void ScaleView(Variables variables) { // variables.view = new VisualizationViewer<>(variables.layout); final ScalingControl scaler = new CrossoverScalingControl(); scaler.scale(variables.view, 1 / 2.1f, variables.view.getCenter()); } /** * Method to initialize the View * @param variables * @param Layouts is the GUI layout chooser * @param graphFrame is the tool's main frame */ public static void SetView(final Variables variables, JComboBox Layouts, JFrame graphFrame) { // Choosing layout if (variables.initLayout) { variables.config.Initialize(variables); variables.newLayout(variables.config.defaultLayout); // variables.layout = new Timeline_Layout<>(variables.graph, variables); variables.view = new VisualizationViewer<>(variables.layout); // Layouts.setSelectedItem(variables.config.defaultLayout); variables.initLayout = false; } ScaleView(variables); PanCameraToFirstVertex(variables); variables.initGraphCollapser(); final PredicatedParallelEdgeIndexFunction eif = PredicatedParallelEdgeIndexFunction.getInstance(); eif.setPredicate(new Predicate() { @Override public boolean evaluate(Object e) { return variables.exclusions.contains(e); } }); variables.view.getRenderContext().setParallelEdgeIndexFunction(eif); variables.view.setBackground(Color.white); graphFrame.getContentPane().add(variables.view, BorderLayout.CENTER); } /** * Method to paint vertices and edges according to their values * @param variables */ public static void GraphPaint(final Variables variables) { // Vertex Paint VertexPainter.VertexPainter("Prov", variables.view, variables); StatusFilterBox.setSelectedItem("Prov"); // Edge Paint Transformer edgePainter = new Transformer<Edge, Paint>() { @Override public Paint transform(Edge edge) { if(GraphFrame.useEdgeTypeColor.isSelected()){ for(EdgeType e : variables.config.edgetype) { if(e.type.equalsIgnoreCase(edge.getType())) { return e.edgeColor; } } } PickedState<Object> picked_state = variables.view.getPickedVertexState(); if(!picked_state.getPicked().isEmpty()) { for( Object v : picked_state.getPicked()) { Pair endpoints = variables.layout.getGraph().getEndpoints(edge); if(endpoints.getFirst().equals(v)) { return edge.getColor(variables); } else if(endpoints.getSecond().equals(v)) { return edge.getColor(variables); } } return new Color(edge.getColor(variables).getRed(), edge.getColor(variables).getGreen(), edge.getColor(variables).getBlue(), 50); } return edge.getColor(variables); } }; variables.view.getRenderContext().setEdgeDrawPaintTransformer(edgePainter); variables.view.getRenderContext().setArrowDrawPaintTransformer(edgePainter); variables.view.getRenderContext().setArrowFillPaintTransformer(edgePainter); } }
src/main/java/br/uff/ic/provviewer/GUI/GuiFunctions.java
/* * The MIT License * * Copyright 2017 Kohwalter. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package br.uff.ic.provviewer.GUI; import br.uff.ic.provviewer.EdgeType; import br.uff.ic.provviewer.GraphFrame; import static br.uff.ic.provviewer.GraphFrame.StatusFilterBox; import br.uff.ic.utility.graph.Edge; import br.uff.ic.provviewer.Stroke.EdgeStroke; import br.uff.ic.provviewer.Stroke.VertexStroke; import br.uff.ic.provviewer.Variables; import br.uff.ic.utility.graph.AgentVertex; import br.uff.ic.provviewer.Vertex.ColorScheme.VertexPainter; import br.uff.ic.utility.graph.EntityVertex; import br.uff.ic.utility.graph.Vertex; import br.uff.ic.provviewer.Vertex.VertexShape; import br.uff.ic.utility.GraphUtils; import br.uff.ic.utility.Utils; import br.uff.ic.utility.graph.ActivityVertex; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.util.Pair; import edu.uci.ics.jung.visualization.Layer; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.CrossoverScalingControl; import edu.uci.ics.jung.visualization.control.ScalingControl; import edu.uci.ics.jung.visualization.picking.PickedState; import edu.uci.ics.jung.visualization.util.PredicatedParallelEdgeIndexFunction; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Paint; import java.awt.Stroke; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.swing.JComboBox; import javax.swing.JFrame; import org.apache.commons.collections15.Predicate; import org.apache.commons.collections15.Transformer; /** * Class responsible for main (GUI) graph functions * @author Kohwalter */ public class GuiFunctions { /** * Method to define the vertex shape using the default shapes * @param variables */ public static void VertexShape(Variables variables) { variables.view.getRenderContext().setVertexShapeTransformer(new VertexShape(variables.config.vertexSize)); } /** * Method to define the vertex shape * @param variables * @param isVertexSizeBasedOnGraphs */ // public static void VertexShape(Variables variables, boolean isVertexSizeBasedOnGraphs) { //// variables.view.getRenderContext().setVertexShapeTransformer(new VertexShape(variables.config.vertexSize, isVertexSizeBasedOnGraphs)); // variables.view.getRenderContext().setVertexShapeTransformer(new VertexShape(variables.config.vertexSize, "Timestamp", variables.graph.getVertices())); // variables.view.repaint(); // } public static void VertexShape(Variables variables, String selectedMode, String attribute) { variables.view.getRenderContext().setVertexShapeTransformer(new VertexShape(variables.config.vertexSize, selectedMode, attribute, variables.graph.getVertices())); variables.view.repaint(); } /** * Method to define the vertex and edge borders/stroke * @param variables */ public static void Stroke(final Variables variables) { // Vertex Stroke Transformer<Object, Stroke> nodeStrokeTransformer = new Transformer<Object, Stroke>() { @Override public Stroke transform(Object v) { return VertexStroke.VertexStroke(v, variables.view, variables.layout, variables); } }; variables.view.getRenderContext().setVertexStrokeTransformer(nodeStrokeTransformer); // Change Stroke color Transformer<Object, Paint> drawPaint = new Transformer<Object, Paint>() { @Override public Paint transform(Object v) { if(variables.highlightVertexOutliers) { if(v instanceof Vertex) { float value = ((Vertex) v).getAttributeValueFloat(variables.outliersThresholds.attributeName); if(value < variables.outliersThresholds.lowerThreshold || value > variables.outliersThresholds.upperThreshold) { return new Color(255, 0, 0); } } } // if(v instanceof Vertex) { // float value = ((Vertex) v).getAttributeValueFloat("Cluster"); // if( value != value) // return new Color(0, 0, 0); // else // return Utils.getColor((int) ((Vertex) v).getAttributeValueFloat("Cluster")); // } return Color.BLACK; } }; variables.view.getRenderContext().setVertexDrawPaintTransformer(drawPaint); // Edge Stroke variables.ComputeEdgeTypeValues(); Transformer<Edge, Stroke> edgeStrokeTransformer = new Transformer<Edge, Stroke>() { @Override public Stroke transform(Edge e) { return EdgeStroke.StrokeByType(e, variables); } }; variables.view.getRenderContext().setEdgeStrokeTransformer(edgeStrokeTransformer); } /** * Method to display labels for vertices * @param variables * @param agentLabel interface check-box state agent label * @param activityLabel interface check-box state activity label * @param entityLabel interface check-box state for entity label * @param timeLabel interface check-box state for time label * @param showID interface check-box state for ID label */ public static void VertexLabel(final Variables variables, final boolean agentLabel, final boolean activityLabel, final boolean entityLabel, final boolean timeLabel, final boolean showID) { variables.view.getRenderContext().setVertexLabelTransformer(new Transformer<Object, String>() { @Override public String transform(Object v) { String font = "<html><font size=\"4\", font color=\"blue\">"; if (v instanceof Graph) { boolean hasActivity = false; boolean hasAgent = false; String agentName = ""; String activityName = ""; String entityName = ""; // boolean hasEntity = false; for (Object vertex : ((Graph) v).getVertices()) { if (vertex instanceof AgentVertex && agentLabel) { return font + ((Vertex) vertex).getLabel(); } if (vertex instanceof ActivityVertex) { hasActivity = true; activityName = ((Vertex)vertex).getLabel(); } if (vertex instanceof AgentVertex) { hasAgent = true; agentName = ((Vertex)vertex).getLabel(); } if (vertex instanceof EntityVertex) { entityName = ((Vertex)vertex).getLabel(); } } if(hasAgent && agentLabel) return font + agentName + " (Summarized)"; if(hasActivity && activityLabel) return font + activityName + " (Summarized)"; if(entityLabel) return font + entityName + " (Summarized)"; if(showID) { Map<String, String> ids = new HashMap<>(); GraphVertexGetID(ids, v); return font + ids.values().toString(); } } // Agent if (v instanceof AgentVertex && agentLabel) { return font + ((Vertex) v).getLabel(); } // Entity // Label + Time else if ((v instanceof EntityVertex) && entityLabel && timeLabel) { return font + String.valueOf((int) ((Vertex) v).getTime()) + " : " + ((Vertex) v).getLabel(); } // Time else if ((v instanceof EntityVertex) && timeLabel) { return font + String.valueOf((int) ((Vertex) v).getTime()); } // Label else if ((v instanceof EntityVertex) && entityLabel) { return font + ((Vertex) v).getLabel(); } // Activity // Label + Time else if ((v instanceof ActivityVertex) && activityLabel && timeLabel) { return font + String.valueOf((int) ((Vertex) v).getTime()) + " : " + ((Vertex) v).getLabel(); } // Time else if ((v instanceof ActivityVertex) && timeLabel) { return font + String.valueOf((int) ((Vertex) v).getTime()); } // Label else if ((v instanceof ActivityVertex) && activityLabel) { return font + ((Vertex) v).getLabel(); } else if(showID) return font + ((Vertex) v).getID(); return ""; } private void GraphVertexGetID(Map<String, String> ids, Object v) { Collection vertices = ((Graph) v).getVertices(); for (Object vertex : vertices) { if (!(vertex instanceof Graph)) { ids.put(((Vertex) vertex).getID(), ((Vertex) vertex).getID()); } else GraphVertexGetID(ids, vertex); } } }); } /** * Method to enable mouse interactions * @param variables */ public static void MouseInteraction(Variables variables) { // via mouse Commands: t for translate, p for picking variables.view.setGraphMouse(variables.mouse); variables.view.addKeyListener(variables.mouse.getModeKeyListener()); } /** * Method to pan the camera to the first vertex in the graph * @param variables */ public static void PanCameraToFirstVertex(Variables variables) { Vertex first = (Vertex) variables.layout.getGraph().getVertices().iterator().next(); variables.view.getGraphLayout(); Point2D q = variables.view.getGraphLayout().transform(first); Point2D lvc = variables.view.getRenderContext().getMultiLayerTransformer().inverseTransform(variables.view.getCenter()); final double dx = (lvc.getX() - q.getX()); final double dy = (lvc.getY() - q.getY()); variables.view.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).translate(dx, dy); } /** * Method to scale back the camera zoom * @param variables */ public static void ScaleView(Variables variables) { // variables.view = new VisualizationViewer<>(variables.layout); final ScalingControl scaler = new CrossoverScalingControl(); scaler.scale(variables.view, 1 / 2.1f, variables.view.getCenter()); } /** * Method to initialize the View * @param variables * @param Layouts is the GUI layout chooser * @param graphFrame is the tool's main frame */ public static void SetView(final Variables variables, JComboBox Layouts, JFrame graphFrame) { // Choosing layout if (variables.initLayout) { variables.config.Initialize(variables); variables.newLayout(variables.config.defaultLayout); // variables.layout = new Timeline_Layout<>(variables.graph, variables); variables.view = new VisualizationViewer<>(variables.layout); // Layouts.setSelectedItem(variables.config.defaultLayout); variables.initLayout = false; } ScaleView(variables); PanCameraToFirstVertex(variables); variables.initGraphCollapser(); final PredicatedParallelEdgeIndexFunction eif = PredicatedParallelEdgeIndexFunction.getInstance(); eif.setPredicate(new Predicate() { @Override public boolean evaluate(Object e) { return variables.exclusions.contains(e); } }); variables.view.getRenderContext().setParallelEdgeIndexFunction(eif); variables.view.setBackground(Color.white); graphFrame.getContentPane().add(variables.view, BorderLayout.CENTER); } /** * Method to paint vertices and edges according to their values * @param variables */ public static void GraphPaint(final Variables variables) { // Vertex Paint VertexPainter.VertexPainter("Prov", variables.view, variables); StatusFilterBox.setSelectedItem("Prov"); // Edge Paint Transformer edgePainter = new Transformer<Edge, Paint>() { @Override public Paint transform(Edge edge) { if(GraphFrame.useEdgeTypeColor.isSelected()){ for(EdgeType e : variables.config.edgetype) { if(e.type.equalsIgnoreCase(edge.getType())) { return e.edgeColor; } } } PickedState<Object> picked_state = variables.view.getPickedVertexState(); if(!picked_state.getPicked().isEmpty()) { for( Object v : picked_state.getPicked()) { Pair endpoints = variables.layout.getGraph().getEndpoints(edge); if(endpoints.getFirst().equals(v)) { return edge.getColor(variables); } else if(endpoints.getSecond().equals(v)) { return edge.getColor(variables); } } return new Color(edge.getColor(variables).getRed(), edge.getColor(variables).getGreen(), edge.getColor(variables).getBlue(), 50); } return edge.getColor(variables); } }; variables.view.getRenderContext().setEdgeDrawPaintTransformer(edgePainter); variables.view.getRenderContext().setArrowDrawPaintTransformer(edgePainter); variables.view.getRenderContext().setArrowFillPaintTransformer(edgePainter); } }
Removed imports
src/main/java/br/uff/ic/provviewer/GUI/GuiFunctions.java
Removed imports
<ide><path>rc/main/java/br/uff/ic/provviewer/GUI/GuiFunctions.java <ide> import br.uff.ic.utility.graph.EntityVertex; <ide> import br.uff.ic.utility.graph.Vertex; <ide> import br.uff.ic.provviewer.Vertex.VertexShape; <del>import br.uff.ic.utility.GraphUtils; <del>import br.uff.ic.utility.Utils; <ide> import br.uff.ic.utility.graph.ActivityVertex; <ide> import edu.uci.ics.jung.graph.Graph; <ide> import edu.uci.ics.jung.graph.util.Pair; <ide> import java.awt.Paint; <ide> import java.awt.Stroke; <ide> import java.awt.geom.Point2D; <del>import java.util.ArrayList; <ide> import java.util.Collection; <ide> import java.util.HashMap; <ide> import java.util.Map;
JavaScript
mit
5658a073bcbd5a5e96d0e9943d3e627b46ad5f82
0
ColorfulCakeChen/query-submit-canvas,ColorfulCakeChen/query-submit-canvas
//import * as Weights from "../Weights.js"; export { ShuffleInfo, ConcatGather, SplitConcat, Layer }; /** * The information for channel shuffler. * * * @member {number[]} concatenatedShape * An array of integer describes the shape of the concatenated apply()'s input tensor (tensor3d or tensor1d). * For example, if apply() will be called with an array of image (i.e. array of tensor3d), concatenatedShape * should be [ height, width, totalChannelCount ]. Another example, if the input will be an array of tensor1d, * concatenatedShape should be [ totalChannelCount ]. No matter which example, the totalChannelCount should * always be the total sum of the last dimension size of all tensors in the apply()'s input array. * * @member {number} outputGroupCount * If greater than 1, the input tensor3d list (after concatenated) will be shuffled and then splitted into so * many group. The ( totalChannelCount / outputGroupCount ) should be an integer. If less or equal than 1 (or null), * the output tensor3d list will just be an array with only one tensor3d which is the concatenation of all the * input tensor3d list (i.e. no shuffle and split). * * * @member {number} lastAxisId * The last axis id of apply()'s input tensor. It will be ( concatenatedShape.length - 1 ). * * @member {number} totalChannelCount * The total channel count when all the apply()'s input tensor concatenated. It will be the value of the last * element of concatenatedShape (i.e. concatenatedShape[ lastAxisId ]). * * @member {number} channelCountPerGroup * There will be so many channels in one (output) group. * * @member {number[]} intermediateShape * Before shuffling, the apply()'s (concatenated) input wiil be reshaped to this intermediateShape. * * @member {number[]} transposePermutation * After reshaped to intermediateShape, the (concatenated) input will be transposed according to this * transposePermutation (i.e. shuffle them). */ class ShuffleInfo { constructor( concatenatedShape, outputGroupCount ) { outputGroupCount = Math.trunc( outputGroupCount || 1 ); if ( outputGroupCount < 1 ) outputGroupCount = 1; // At least one (means: no shuffle and split (concatenate only)). this.concatenatedShape = concatenatedShape; this.outputGroupCount = outputGroupCount; let lastAxisId = this.lastAxisId = concatenatedShape.length - 1; let totalChannelCount = this.totalChannelCount = concatenatedShape[ lastAxisId ]; // The channel count of every output group. (It should be an integer.) let channelCountPerGroup = this.channelCountPerGroup = totalChannelCount / outputGroupCount; // The shape before transpose. For example, if concatenatedShape is [ h, w, c ], the intermediateShape will be // [ h, w, outputGroupCount, channelCountPerGroup ]. The last dimension is splitted into two dimensions. let intermediateShape = this.intermediateShape = concatenatedShape.slice( 0, lastAxisId ); intermediateShape.push( outputGroupCount, channelCountPerGroup ); // The axis permutation of transpose. // // For example, if the intermediateShape is [ h, w, outputGroupCount, channelCountPerGroup ]. Its // axis permutation will be [ 0, 1, 3, 2 ] so that the last two dimensions will be swapped. let transposePermutation = this.transposePermutation = new Array( intermediateShape.keys() ); { let last1 = transposePermutation.pop(); let last2 = transposePermutation.pop(); transposePermutation.push( last1, last2 ); } } /** * Permute the input tensor by reshape-transpose-reshape. * * @param {tf.tensor} concatenatedTensor * An single tensor (not array) to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor} * A shuffled tensor. Its size is the same as concatenatedTensor but its last dimension is shuffled. */ reshapeTransposeReshape( concatenatedTensor ) { return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshape", () => { return concatenatedTensor .reshape( this.intermediateShape ) .transpose( this.transposePermutation ) .reshape( this.concatenatedShape ); }); } /** * Permute and split the input tensor by reshape-transpose-reshape-split. * * @param {tf.tensor} concatenatedTensor * An single tensor (not array) to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor[]} * An array of shuffled tensors. Their total channel count is the same as concatenatedTensor, but their * last dimensions are shuffled. */ reshapeTransposeReshapeSplit( concatenatedTensor ) { return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshapeSplit", () => { return concatenatedTensor .reshape( this.intermediateShape ) .transpose( this.transposePermutation ) .reshape( this.concatenatedShape ) .split( this.outputGroupCount, this.lastAxisId ); }); } /** * Concatenate and permute the input tensor by concat-reshape-transpose-reshape. * * @param {tf.tensor[]} tensorArray * An array of tensors to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor} * A shuffled tensor. Its total channel count is the same as concatenated tensorArray, but their * last dimensions are shuffled. */ concatReshapeTransposeReshape( tensorArray ) { return tf.tidy( "ChannelShuffler.ShuffleInfo.concatReshapeTransposeReshape", () => { return tf.concat( tensorArray, this.lastAxisId ) .reshape( this.intermediateShape ) .transpose( this.transposePermutation ) .reshape( this.concatenatedShape ); }); } /** * Concatenate, permute and split the input tensor by concat-reshape-transpose-reshape-split. * * @param {tf.tensor[]} tensorArray * An array of tensors to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor[]} * An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their * last dimensions are shuffled. */ concatReshapeTransposeReshapeSplit( tensorArray ) { return tf.tidy( "ChannelShuffler.ShuffleInfo.concatReshapeTransposeReshapeSplit", () => { return tf.concat( tensorArray, this.lastAxisId ) .reshape( this.intermediateShape ) .transpose( this.transposePermutation ) .reshape( this.concatenatedShape ) .split( this.outputGroupCount, this.lastAxisId ); }); } } /** * Implement the channel shuffler by tf.concat() and tf.gather(). * * When outputGroupCount is small (e.g. 2), this is be faster than concat-reshape-transpose-reshape-split because * the total operations (and memory access) are smaller. * * The extra cost is a pre-built channel index look up table (with tensor1d). * * * @member {ShuffleInfo} shuffleInfo * The information calculated from init()'s concatenatedShape and outputGroupCount. * * @member {tf.tensor1d[]} shuffledChannelIndicesTensor1dArray * The look up table for tf.gather()'s channel index. This table is composed of tensor1d so should be released * by calling disposeTensors(). */ class ConcatGather { /** * * @param {number[]} concatenatedShape * Used to calculate shuffleInfo. * * @param {number} outputGroupCount * Used to calculate shuffleInfo. * * @see ShuffleInfo */ init( concatenatedShape, outputGroupCount ) { disposeTensors(); // So that distinguishable if re-initialization failed. this.shuffleInfo = new ShuffleInfo( concatenatedShape, outputGroupCount ); // Build shuffled channel index table (as an array of tf.tensor1d). // // It can be used by algorithm ConcatGather(). // They should be integers so that can be used as tf.gather()'s index. try { this.shuffledChannelIndicesTensor1dArray = tf.tidy( "ChannelShuffler.ConcatGather.init.shuffledChannelIndicesTensor1dArray", () => { //let channelIndices = tf.linspace( 0, totalChannelCount - 1, totalChannelCount ).toInt(); let channelIndices = tf.range(0, this.shuffleInfo.totalChannelCount, 1, "int32"); let channelIndicesShuffleInfo = new ShuffleInfo( channelIndices.shape, outputGroupCount ); return channelIndicesShuffleInfo.reshapeTransposeReshapeSplit( channelIndices ); }); } catch ( e ) { return false; // e.g. out of (GPU) memory. } return true; } /** Release tf.tensor. */ disposeTensors() { if ( this.shuffledChannelIndicesTensor1dArray ) { tf.dispose( this.shuffledChannelIndicesTensor1dArray ); this.shuffledChannelIndicesTensor1dArray = null; } } /** * Permute and split the input tensor by gather. * * @param {tf.tensor} concatenatedTensor * An single tensor (not array) to be processed. It should conform to this.shuffleInfo.concatenatedShape. * * @return {tf.tensor[]} * An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their * last dimensions are shuffled. */ gather( concatenatedTensor ) { return tf.tidy( "ChannelShuffler.ConcatGather.gather", () => { // shuffle and split by gather (one operation achieves two operations). let shuffledSplitedTensorArray = this.shuffledChannelIndicesTensor1dArray.map( shuffledChannelIndicesTensor1d => concatenatedTensor.gather( shuffledChannelIndicesTensor1d, this.shuffleInfo.lastAxisId ) }); return shuffledSplitedTensorArray; }); } /** * Concatenate, permute and split the input tensor by concat-gather. * * @param {tf.tensor[]} tensorArray * An array of tensors to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor[]} * An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their * last dimensions are shuffled. */ concatGather( tensorArray ) { return tf.tidy( "ChannelShuffler.ConcatGather.concatGather", () => { let concatenatedTensor = tf.concat( tensorArray, this.shuffleInfo.lastAxisId ); // shuffle and split by gather (one operation achieves two operations). let shuffledSplitedTensorArray = this.shuffledChannelIndicesTensor1dArray.map( shuffledChannelIndicesTensor1d => concatenatedTensor.gather( shuffledChannelIndicesTensor1d, this.shuffleInfo.lastAxisId ); }); return shuffledSplitedTensorArray; }); } } /** * Implement the channel shuffler by tf.split() and tf.concat(). * * It seems slower than concat-gather and concat-reshape-transpose-reshape-split. Perhaps the total operations * (and memory access) are too much (e.g. releasing many single channel temporary tensors). * * The extra cost is a pre-built channel index look up table (with integers, not tensor1d). * * * @member {ShuffleInfo} shuffleInfo * The information calculated from init()'s concatenatedShape and outputGroupCount. * * @member {number[][]} shuffledChannelIndicesArray * The look up table for tf.gather()'s channel index. This table is composed of array of integers. */ class SplitConcat { /** * * @param {number[]} concatenatedShape * Used to calculate shuffleInfo. * * @param {number} outputGroupCount * Used to calculate shuffleInfo. * * @see ConcatGather */ init( concatenatedShape, outputGroupCount ) { let concatGather = new ConcatGather(); let initOk = concatGather.init( concatenatedShape, outputGroupCount ); try { if ( initOk ) { // Shuffled channel indices (one dimension) for SplitConcat() this.shuffledChannelIndicesArray = new Array( concatGather.shuffledChannelIndicesTensor1dArray.length ); concatGather.shuffledChannelIndicesTensor1dArray.map( ( shuffledChannelIndicesTensor1d, i ) => { this.shuffledChannelIndicesArray[ i ] = shuffledChannelIndicesTensor1d.dataSync(); }); this.shuffleInfo = concatGather.shuffleInfo; // Need the shuffle info. } } finally { concatGather.disposeTensors(); // Always release the look up table (with tensor1d). } return initOk; } /** * Concatenate, permute and split the input tensor by split-concat-gather. * * @param {tf.tensor[]} tensorArray * An array of tensors to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor[]} * An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their * last dimensions are shuffled. */ splitConcat( tensorArray ) { return tf.tidy( "ChannelShuffler.SplitConcat.splitConcat", () => { // Become local variables for reducing access time. let lastAxisId = this.shuffleInfo.lastAxisId; let channelCountPerGroup = this.shuffleInfo.channelCountPerGroup; // Every element will be a single channel tensor3d. let singleChannelTensorArray = new Array( this.shuffleInfo.totalChannelCount ); // Pre-allocate memory for speeding up. singleChannelTensorArray.length = 0; // Empty the array. // Split every group (a multiple channels tensor3d) into many single channel tensor3d. for ( let tensor of tensorArray ) { singleChannelTensorArray.push( ...tensor.split( channelCountPerGroup, lastAxisId ) ); } // An array for many single channel tensor3d of one group. (re-used multiple times to reduce memory re-allocation.) let tensorArrayForOneGroup = new Array( channelCountPerGroup ); // shuffle and split by concat (one operation achieves two operations). return this.shuffledChannelIndicesArray.map( ( shuffledChannelIndices ) => { shuffledChannelIndices.forEach( ( channelIndex, i ) => { tensorArrayForOneGroup[ i ] = singleChannelTensorArray[ channelIndex ]; }); return tf.concat( tensorArrayForOneGroup, lastAxisId ); }); }); } } //!!! // named as Pipe.ChannelShuffler ? /** * An channel shuffler accepts a list of tensor3d with same size (height, width, channel) and outputs a shuffled * (re-grouped) list tensor3d. * * Usually, the output tensor3d list length will be the same as input tensor3d list. Even more, the size of * every output tensor3d will also be the same as input tensor3d. However, the order of the tensor3d's channels * (the 3rd dimension) are different. * * This is the Channel-Shuffle operation of the ShuffleNetV2 neural network. * * * * * @member {ShuffleInfo} shuffleInfo * The information calculated from init()'s concatenatedShape and outputGroupCount. */ class Layer { /** * * @param {number[]} concatenatedShape * Used to calculate shuffleInfo. * * @param {number} outputGroupCount * Used to calculate shuffleInfo. * * @see Info */ init( concatenatedShape, outputGroupCount ) { //!!! ...unfinished... disposeTensors(); this.concatGather = new ConcatGather(); let initOk = this.concatGather.init( concatenatedShape, outputGroupCount ); return initOk; } /** Release tf.tensor. */ disposeTensors() { if ( this.concatGather ) { this.concatGather.disposeTensors(); this.concatGather = null; } } /** * Process the input and produce output by this neural network layer. * * The group count (i.e. element count) of input tensor3d list can be different from the group count * (i.e. element count) of output tensor3d list * * If there are more than one tensor3d in the input tensor3d array, they will be concatenated. * * If need split, then need shuffle before split. * * @param {Array of tf.tensor3d} inputTensor3DArray * A list of tensor3D (e.g. height-width-color for color image, or 1-width-1 for text) data. The sum of all the * 3rd dimension (i.e. the channel dimension) of every input tensor3d should be the same as this.totalChannelCount. * * @return {Array of tf.tensor3d} outputTensor3DArray * The output as a list of tensor3D. Return null, if failed (e.g. out of GPU memory). */ apply( inputTensor3DArray, outputTensor3DArray ) { const outputTensor3DArray = tf.tidy( "ChannelShuffler.Layer.apply", () => { try { // Concatenate all into one tensor3d. let dataTensor3d; if ( inputTensor3DArray.length > 1 ) dataTensor3d = tf.concat( inputTensor3DArray ); else dataTensor3d = inputTensor3DArray[ 0 ]; // There is only one tensor3d, use it directly instead of concatenating. // If there is only one output group, there is not necessary to shuffle (and split). if ( this.outputGroupCount == 1 ) return [ dataTensor3d ]; //!!! ...unfinished... return } catch ( e ) { } }); return outputTensor3DArray; } /** @return Return true, if two array of tensor are equal by value. */ static isTensorArrayEqual( tensorArray1, tensorArray2 ) { if ( tensorArray1 === tensorArray2 ) return true; if ( tensorArray1 == null || tensorArray2 == null ) return false; if ( tensorArray1.length !== tensorArray2.length ) return false; for ( let i = 0; i < tensorArray1.length; ++i ) { if ( !tensorArray1[ i ].equal( tensorArray2[ i ] ) ) return false; } return true; } }
CNN/Layer/ChannelShuffler.js
//import * as Weights from "../Weights.js"; export { ShuffleInfo, ConcatGather, SplitConcat, Layer }; /** * The information for channel shuffler. * * * @member {number[]} concatenatedShape * An array of integer describes the shape of the concatenated apply()'s input tensor (tensor3d or tensor1d). * For example, if apply() will be called with an array of image (i.e. array of tensor3d), concatenatedShape * should be [ height, width, totalChannelCount ]. Another example, if the input will be an array of tensor1d, * concatenatedShape should be [ totalChannelCount ]. No matter which example, the totalChannelCount should * always be the total sum of the last dimension size of all tensors in the apply()'s input array. * * @member {number} outputGroupCount * If greater than 1, the input tensor3d list (after concatenated) will be shuffled and then splitted into so * many group. The ( totalChannelCount / outputGroupCount ) should be an integer. If less or equal than 1 (or null), * the output tensor3d list will just be an array with only one tensor3d which is the concatenation of all the * input tensor3d list (i.e. no shuffle and split). * * * @member {number} lastAxisId * The last axis id of apply()'s input tensor. It will be ( concatenatedShape.length - 1 ). * * @member {number} totalChannelCount * The total channel count when all the apply()'s input tensor concatenated. It will be the value of the last * element of concatenatedShape (i.e. concatenatedShape[ lastAxisId ]). * * @member {number} channelCountPerGroup * There will be so many channels in one (output) group. * * @member {number[]} intermediateShape * Before shuffling, the apply()'s (concatenated) input wiil be reshaped to this intermediateShape. * * @member {number[]} transposePermutation * After reshaped to intermediateShape, the (concatenated) input will be transposed according to this * transposePermutation (i.e. shuffle them). */ class ShuffleInfo { constructor( concatenatedShape, outputGroupCount ) { outputGroupCount = Math.trunc( outputGroupCount || 1 ); if ( outputGroupCount < 1 ) outputGroupCount = 1; // At least one (means: no shuffle and split (concatenate only)). this.concatenatedShape = concatenatedShape; this.outputGroupCount = outputGroupCount; let lastAxisId = this.lastAxisId = concatenatedShape.length - 1; let totalChannelCount = this.totalChannelCount = concatenatedShape[ lastAxisId ]; // The channel count of every output group. (It should be an integer.) let channelCountPerGroup = this.channelCountPerGroup = totalChannelCount / outputGroupCount; // The shape before transpose. For example, if concatenatedShape is [ h, w, c ], the intermediateShape will be // [ h, w, outputGroupCount, channelCountPerGroup ]. The last dimension is splitted into two dimensions. let intermediateShape = this.intermediateShape = concatenatedShape.slice( 0, lastAxisId ); intermediateShape.push( outputGroupCount, channelCountPerGroup ); // The axis permutation of transpose. // // For example, if the intermediateShape is [ h, w, outputGroupCount, channelCountPerGroup ]. Its // axis permutation will be [ 0, 1, 3, 2 ] so that the last two dimensions will be swapped. let transposePermutation = this.transposePermutation = new Array( intermediateShape.keys() ); { let last1 = transposePermutation.pop(); let last2 = transposePermutation.pop(); transposePermutation.push( last1, last2 ); } } /** * Permute the input tensor by reshape-transpose-reshape. * * @param {tf.tensor} concatenatedTensor * An single tensor (not array) to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor} * A shuffled tensor. Its size is the same as concatenatedTensor but its last dimension is shuffled. */ reshapeTransposeReshape( concatenatedTensor ) { return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshape", () => { return concatenatedTensor .reshape( this.intermediateShape ) .transpose( this.transposePermutation ) .reshape( this.concatenatedShape ); }); } /** * Permute and split the input tensor by reshape-transpose-reshape-split. * * @param {tf.tensor} concatenatedTensor * An single tensor (not array) to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor[]} * An array of shuffled tensors. Their total channel count is the same as concatenatedTensor, but their * last dimensions are shuffled. */ reshapeTransposeReshapeSplit( concatenatedTensor ) { return tf.tidy( "ChannelShuffler.ShuffleInfo.reshapeTransposeReshapeSplit", () => { return concatenatedTensor .reshape( this.intermediateShape ) .transpose( this.transposePermutation ) .reshape( this.concatenatedShape ) .split( this.outputGroupCount, this.lastAxisId ); }); } /** * Concatenate and permute the input tensor by concat-reshape-transpose-reshape. * * @param {tf.tensor[]} tensorArray * An array of tensors to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor} * A shuffled tensor. Its total channel count is the same as concatenated tensorArray, but their * last dimensions are shuffled. */ concatReshapeTransposeReshape( tensorArray ) { return tf.tidy( "ChannelShuffler.ShuffleInfo.concatReshapeTransposeReshape", () => { return tf.concat( tensorArray, this.lastAxisId ) .reshape( this.intermediateShape ) .transpose( this.transposePermutation ) .reshape( this.concatenatedShape ); }); } /** * Concatenate, permute and split the input tensor by concat-reshape-transpose-reshape-split. * * @param {tf.tensor[]} tensorArray * An array of tensors to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor[]} * An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their * last dimensions are shuffled. */ concatReshapeTransposeReshapeSplit( tensorArray ) { return tf.tidy( "ChannelShuffler.ShuffleInfo.concatReshapeTransposeReshapeSplit", () => { return tf.concat( tensorArray, this.lastAxisId ) .reshape( this.intermediateShape ) .transpose( this.transposePermutation ) .reshape( this.concatenatedShape ) .split( this.outputGroupCount, this.lastAxisId ); }); } } /** * Implement the channel shuffler by tf.concat() and tf.gather(). * * When outputGroupCount is small (e.g. 2), this is be faster than concat-reshape-transpose-reshape-split because * the total operations (and memory access) are smaller. * * The extra cost is a pre-built channel index look up table (with tensor1d). * * * @member {ShuffleInfo} shuffleInfo * The information calculated from init()'s concatenatedShape and outputGroupCount. * * @member {tf.tensor1d[]} shuffledChannelIndicesTensor1dArray * The look up table for tf.gather()'s channel index. This table is composed of tensor1d so should be released * by calling disposeTensors(). */ class ConcatGather { /** * * @param {number[]} concatenatedShape * Used to calculate shuffleInfo. * * @param {number} outputGroupCount * Used to calculate shuffleInfo. * * @see ShuffleInfo */ init( concatenatedShape, outputGroupCount ) { disposeTensors(); // So that distinguishable if re-initialization failed. this.shuffleInfo = new ShuffleInfo( concatenatedShape, outputGroupCount ); // Build shuffled channel index table (as an array of tf.tensor1d). // // It can be used by algorithm ConcatGather(). // They should be integers so that can be used as tf.gather()'s index. try { this.shuffledChannelIndicesTensor1dArray = tf.tidy( "ChannelShuffler.ConcatGather.init.shuffledChannelIndicesTensor1dArray", () => { //let channelIndices = tf.linspace( 0, totalChannelCount - 1, totalChannelCount ).toInt(); let channelIndices = tf.range(0, this.shuffleInfo.totalChannelCount, 1, "int32"); let channelIndicesShuffleInfo = new ShuffleInfo( channelIndices.shape, outputGroupCount ); return channelIndicesShuffleInfo.reshapeTransposeReshapeSplit( channelIndices ); }); } catch ( e ) { return false; // e.g. out of (GPU) memory. } return true; } /** Release tf.tensor. */ disposeTensors() { if ( this.shuffledChannelIndicesTensor1dArray ) { tf.dispose( this.shuffledChannelIndicesTensor1dArray ); this.shuffledChannelIndicesTensor1dArray = null; } } /** * Permute and split the input tensor by gather. * * @param {tf.tensor} concatenatedTensor * An single tensor (not array) to be processed. It should conform to this.shuffleInfo.concatenatedShape. * * @return {tf.tensor[]} * An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their * last dimensions are shuffled. */ gather( concatenatedTensor ) { return tf.tidy( "ChannelShuffler.ConcatGather.gather", () => { // shuffle and split by gather (one operation achieves two operations). let shuffledSplitedTensorArray = this.shuffledChannelIndicesTensor1dArray.map( shuffledChannelIndicesTensor1d => concatenatedTensor.gather( shuffledChannelIndicesTensor1d, this.shuffleInfo.lastAxisId ); }); return shuffledSplitedTensorArray; }); } /** * Concatenate, permute and split the input tensor by concat-gather. * * @param {tf.tensor[]} tensorArray * An array of tensors to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor[]} * An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their * last dimensions are shuffled. */ concatGather( tensorArray ) { return tf.tidy( "ChannelShuffler.ConcatGather.concatGather", () => { let concatenatedTensor = tf.concat( tensorArray, this.shuffleInfo.lastAxisId ); // shuffle and split by gather (one operation achieves two operations). let shuffledSplitedTensorArray = this.shuffledChannelIndicesTensor1dArray.map( shuffledChannelIndicesTensor1d => concatenatedTensor.gather( shuffledChannelIndicesTensor1d, this.shuffleInfo.lastAxisId ); }); return shuffledSplitedTensorArray; }); } } /** * Implement the channel shuffler by tf.split() and tf.concat(). * * It seems slower than concat-gather and concat-reshape-transpose-reshape-split. Perhaps the total operations * (and memory access) are too much (e.g. releasing many single channel temporary tensors). * * The extra cost is a pre-built channel index look up table (with integers, not tensor1d). * * * @member {ShuffleInfo} shuffleInfo * The information calculated from init()'s concatenatedShape and outputGroupCount. * * @member {number[][]} shuffledChannelIndicesArray * The look up table for tf.gather()'s channel index. This table is composed of array of integers. */ class SplitConcat { /** * * @param {number[]} concatenatedShape * Used to calculate shuffleInfo. * * @param {number} outputGroupCount * Used to calculate shuffleInfo. * * @see ConcatGather */ init( concatenatedShape, outputGroupCount ) { let concatGather = new ConcatGather(); let initOk = concatGather.init( concatenatedShape, outputGroupCount ); try { if ( initOk ) { // Shuffled channel indices (one dimension) for SplitConcat() this.shuffledChannelIndicesArray = new Array( concatGather.shuffledChannelIndicesTensor1dArray.length ); concatGather.shuffledChannelIndicesTensor1dArray.map( ( shuffledChannelIndicesTensor1d, i ) => { this.shuffledChannelIndicesArray[ i ] = shuffledChannelIndicesTensor1d.dataSync(); }); this.shuffleInfo = concatGather.shuffleInfo; // Need the shuffle info. } } finally { concatGather.disposeTensors(); // Always release the look up table (with tensor1d). } return initOk; } /** * Concatenate, permute and split the input tensor by split-concat-gather. * * @param {tf.tensor[]} tensorArray * An array of tensors to be processed. It should conform to this.concatenatedShape. * * @return {tf.tensor[]} * An array of shuffled tensors. Their total channel count is the same as concatenated tensorArray, but their * last dimensions are shuffled. */ splitConcat( tensorArray ) { return tf.tidy( "ChannelShuffler.SplitConcat.splitConcat", () => { // Become local variables for reducing access time. let lastAxisId = this.shuffleInfo.lastAxisId; let channelCountPerGroup = this.shuffleInfo.channelCountPerGroup; // Every element will be a single channel tensor3d. let singleChannelTensorArray = new Array( this.shuffleInfo.totalChannelCount ); // Pre-allocate memory for speeding up. singleChannelTensorArray.length = 0; // Empty the array. // Split every group (a multiple channels tensor3d) into many single channel tensor3d. for ( let tensor of tensorArray ) { singleChannelTensorArray.push( ...tensor.split( channelCountPerGroup, lastAxisId ) ); } // An array for many single channel tensor3d of one group. (re-used multiple times to reduce memory re-allocation.) let tensorArrayForOneGroup = new Array( channelCountPerGroup ); // shuffle and split by concat (one operation achieves two operations). return this.shuffledChannelIndicesArray.map( ( shuffledChannelIndices ) => { shuffledChannelIndices.forEach( ( channelIndex, i ) => { tensorArrayForOneGroup[ i ] = singleChannelTensorArray[ channelIndex ]; }); return tf.concat( tensorArrayForOneGroup, lastAxisId ); }); }); } } //!!! // named as Pipe.ChannelShuffler ? /** * An channel shuffler accepts a list of tensor3d with same size (height, width, channel) and outputs a shuffled * (re-grouped) list tensor3d. * * Usually, the output tensor3d list length will be the same as input tensor3d list. Even more, the size of * every output tensor3d will also be the same as input tensor3d. However, the order of the tensor3d's channels * (the 3rd dimension) are different. * * This is the Channel-Shuffle operation of the ShuffleNetV2 neural network. * * * * * @member {ShuffleInfo} shuffleInfo * The information calculated from init()'s concatenatedShape and outputGroupCount. */ class Layer { /** * * @param {number[]} concatenatedShape * Used to calculate shuffleInfo. * * @param {number} outputGroupCount * Used to calculate shuffleInfo. * * @see Info */ init( concatenatedShape, outputGroupCount ) { //!!! ...unfinished... disposeTensors(); this.concatGather = new ConcatGather(); let initOk = this.concatGather.init( concatenatedShape, outputGroupCount ); return initOk; } /** Release tf.tensor. */ disposeTensors() { if ( this.concatGather ) { this.concatGather.disposeTensors(); this.concatGather = null; } } /** * Process the input and produce output by this neural network layer. * * The group count (i.e. element count) of input tensor3d list can be different from the group count * (i.e. element count) of output tensor3d list * * If there are more than one tensor3d in the input tensor3d array, they will be concatenated. * * If need split, then need shuffle before split. * * @param {Array of tf.tensor3d} inputTensor3DArray * A list of tensor3D (e.g. height-width-color for color image, or 1-width-1 for text) data. The sum of all the * 3rd dimension (i.e. the channel dimension) of every input tensor3d should be the same as this.totalChannelCount. * * @return {Array of tf.tensor3d} outputTensor3DArray * The output as a list of tensor3D. Return null, if failed (e.g. out of GPU memory). */ apply( inputTensor3DArray, outputTensor3DArray ) { const outputTensor3DArray = tf.tidy( "ChannelShuffler.Layer.apply", () => { try { // Concatenate all into one tensor3d. let dataTensor3d; if ( inputTensor3DArray.length > 1 ) dataTensor3d = tf.concat( inputTensor3DArray ); else dataTensor3d = inputTensor3DArray[ 0 ]; // There is only one tensor3d, use it directly instead of concatenating. // If there is only one output group, there is not necessary to shuffle (and split). if ( this.outputGroupCount == 1 ) return [ dataTensor3d ]; //!!! ...unfinished... return } catch ( e ) { } }); return outputTensor3DArray; } /** @return Return true, if two array of tensor are equal by value. */ static isTensorArrayEqual( tensorArray1, tensorArray2 ) { if ( tensorArray1 === tensorArray2 ) return true; if ( tensorArray1 == null || tensorArray2 == null ) return false; if ( tensorArray1.length !== tensorArray2.length ) return false; for ( let i = 0; i < tensorArray1.length; ++i ) { if ( !tensorArray1[ i ].equal( tensorArray2[ i ] ) ) return false; } return true; } }
Update ChannelShuffler.js
CNN/Layer/ChannelShuffler.js
Update ChannelShuffler.js
<ide><path>NN/Layer/ChannelShuffler.js <ide> // shuffle and split by gather (one operation achieves two operations). <ide> let shuffledSplitedTensorArray = this.shuffledChannelIndicesTensor1dArray.map( <ide> shuffledChannelIndicesTensor1d => <del> concatenatedTensor.gather( shuffledChannelIndicesTensor1d, this.shuffleInfo.lastAxisId ); <add> concatenatedTensor.gather( shuffledChannelIndicesTensor1d, this.shuffleInfo.lastAxisId ) <ide> }); <ide> return shuffledSplitedTensorArray; <ide> });
Java
agpl-3.0
6eba97053bbdb65da1e33f4f0ee8fa7d23ed9e31
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
801d0000-2e61-11e5-9284-b827eb9e62be
hello.java
801790a2-2e61-11e5-9284-b827eb9e62be
801d0000-2e61-11e5-9284-b827eb9e62be
hello.java
801d0000-2e61-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>801790a2-2e61-11e5-9284-b827eb9e62be <add>801d0000-2e61-11e5-9284-b827eb9e62be
JavaScript
agpl-3.0
50e880356bcaab46800bdef69ed535334a437c3b
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
c343de48-2e62-11e5-9284-b827eb9e62be
helloWorld.js
c33e5450-2e62-11e5-9284-b827eb9e62be
c343de48-2e62-11e5-9284-b827eb9e62be
helloWorld.js
c343de48-2e62-11e5-9284-b827eb9e62be
<ide><path>elloWorld.js <del>c33e5450-2e62-11e5-9284-b827eb9e62be <add>c343de48-2e62-11e5-9284-b827eb9e62be
Java
mit
56f722b2824e6c87bbfef4319107cbbd6d7daf31
0
pirinda/sba10
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sba.lib; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.math.RoundingMode; import java.sql.Blob; import java.sql.SQLException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.TimeZone; import java.util.Vector; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * * @author Sergio Flores */ public abstract class DLibUtils { public static final DecimalFormat DecimalFormatInteger = new DecimalFormat("#,##0"); public static final DecimalFormat DecimalFormatIntegerRaw = new DecimalFormat("#0"); public static final DecimalFormat DecimalFormatCalendarDay = new DecimalFormat("00"); public static final DecimalFormat DecimalFormatCalendarMonth = new DecimalFormat("00"); public static final DecimalFormat DecimalFormatCalendarYear = new DecimalFormat("0000"); public static final DecimalFormat DecimalFormatValue0D = new DecimalFormat("#,##0"); public static final DecimalFormat DecimalFormatValue2D = new DecimalFormat("#,##0.00"); public static final DecimalFormat DecimalFormatValue4D = new DecimalFormat("#,##0.0000"); public static final DecimalFormat DecimalFormatValue8D = new DecimalFormat("#,##0.00000000"); public static final DecimalFormat DecimalFormatPercentage0D = new DecimalFormat("#,##0%"); public static final DecimalFormat DecimalFormatPercentage2D = new DecimalFormat("#,##0.00%"); public static final DecimalFormat DecimalFormatPercentage4D = new DecimalFormat("#,##0.0000%"); public static final DecimalFormat DecimalFormatPercentage8D = new DecimalFormat("#,##0.00000000%"); public static final DecimalFormat DecimalNumberFormat = new DecimalFormat(DLibUtils.textRepeat("0", DLibConsts.LEN_NUM)); public static final DecimalFormat DecimalReferenceFormat = new DecimalFormat(DLibUtils.textRepeat("0", DLibConsts.LEN_REF_NUM)); public static final DecimalFormat RoundingDecimalFormat = new DecimalFormat(); public static final SimpleDateFormat DateFormatDate = new SimpleDateFormat("dd/MM/yyyy"); public static final SimpleDateFormat DateFormatDateShort = new SimpleDateFormat("dd/MM/yy"); public static final SimpleDateFormat DateFormatDateLong = new SimpleDateFormat("dd 'de' MMMM 'de' yyyy"); public static final SimpleDateFormat DateFormatDateYearMonth = new SimpleDateFormat("yyyy-MM"); public static final SimpleDateFormat DateFormatDateYear = new SimpleDateFormat("yyyy"); public static final SimpleDateFormat DateFormatDatetime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); public static final SimpleDateFormat DateFormatDatetimeTimeZone = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss Z"); public static final SimpleDateFormat DateFormatTime = new SimpleDateFormat("HH:mm:ss"); public static final SimpleDateFormat DbmsDateFormatDate = new SimpleDateFormat("yyyy-MM-dd"); public static final SimpleDateFormat DbmsDateFormatDatetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static final SimpleDateFormat DbmsDateFormatTime = new SimpleDateFormat("HH:mm:ss"); public static final SimpleDateFormat CsvFormatDate = new SimpleDateFormat("yyyy/MM/dd"); public static final SimpleDateFormat CsvFormatDatetime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public static final SimpleDateFormat CsvFormatTime = new SimpleDateFormat("HH:mm:ss"); public static final SimpleDateFormat FileDateFormatDatetime = new SimpleDateFormat("yyyyMMdd HHmmss"); public static final SimpleDateFormat IsoFormatDatetime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); public static final HashMap<Character, String> XmlEntityNamesMap = new HashMap<>(); public static final HashMap<Character, String> HtmlEntityNamesMap = new HashMap<>(); public static final char[] RandomKeyChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '9' }; // 62 choices, but 63 characters actually: the last one must be repeated private static final double MAX_VALUE = 999999999.99; // 999,999,999.99 static { RoundingDecimalFormat.setRoundingMode(RoundingMode.HALF_UP); XmlEntityNamesMap.put('"', "&quot;"); XmlEntityNamesMap.put('&', "&amp;"); XmlEntityNamesMap.put('\'', "&apos;"); XmlEntityNamesMap.put('<', "&lt;"); XmlEntityNamesMap.put('>', "&gt;"); HtmlEntityNamesMap.put('"', "&quot;"); HtmlEntityNamesMap.put('&', "&amp;"); HtmlEntityNamesMap.put('<', "&lt;"); HtmlEntityNamesMap.put('>', "&gt;"); HtmlEntityNamesMap.put('¡', "&iexcl;"); HtmlEntityNamesMap.put('¢', "&cent;"); HtmlEntityNamesMap.put('£', "&pound;"); HtmlEntityNamesMap.put('¤', "&curren;"); HtmlEntityNamesMap.put('¥', "&yen;"); HtmlEntityNamesMap.put('¦', "&brvbar;"); HtmlEntityNamesMap.put('§', "&sect;"); HtmlEntityNamesMap.put('¨', "&uml;"); HtmlEntityNamesMap.put('©', "&copy;"); HtmlEntityNamesMap.put('ª', "&ordf;"); HtmlEntityNamesMap.put('«', "&laquo;"); HtmlEntityNamesMap.put('¬', "&not;"); HtmlEntityNamesMap.put('®', "&reg;"); HtmlEntityNamesMap.put('¯', "&macr;"); HtmlEntityNamesMap.put('°', "&deg;"); HtmlEntityNamesMap.put('±', "&plusmn;"); HtmlEntityNamesMap.put('²', "&sup2;"); HtmlEntityNamesMap.put('³', "&sup3;"); HtmlEntityNamesMap.put('´', "&acute;"); HtmlEntityNamesMap.put('µ', "&micro;"); HtmlEntityNamesMap.put('¶', "&para;"); HtmlEntityNamesMap.put('·', "&middot;"); HtmlEntityNamesMap.put('¸', "&cedil;"); HtmlEntityNamesMap.put('¹', "&sup1;"); HtmlEntityNamesMap.put('º', "&ordm;"); HtmlEntityNamesMap.put('»', "&raquo;"); HtmlEntityNamesMap.put('¼', "&frac14;"); HtmlEntityNamesMap.put('½', "&frac12;"); HtmlEntityNamesMap.put('¾', "&frac34;"); HtmlEntityNamesMap.put('¿', "&iquest;"); HtmlEntityNamesMap.put('À', "&Agrave;"); HtmlEntityNamesMap.put('Á', "&Aacute;"); HtmlEntityNamesMap.put('Â', "&Acirc;"); HtmlEntityNamesMap.put('Ã', "&Atilde;"); HtmlEntityNamesMap.put('Ä', "&Auml;"); HtmlEntityNamesMap.put('Å', "&Aring;"); HtmlEntityNamesMap.put('Æ', "&AElig;"); HtmlEntityNamesMap.put('Ç', "&Ccedil;"); HtmlEntityNamesMap.put('È', "&Egrave;"); HtmlEntityNamesMap.put('É', "&Eacute;"); HtmlEntityNamesMap.put('Ê', "&Ecirc;"); HtmlEntityNamesMap.put('Ë', "&Euml;"); HtmlEntityNamesMap.put('Ì', "&Igrave;"); HtmlEntityNamesMap.put('Í', "&Iacute;"); HtmlEntityNamesMap.put('Î', "&Icirc;"); HtmlEntityNamesMap.put('Ï', "&Iuml;"); HtmlEntityNamesMap.put('Ð', "&ETH;"); HtmlEntityNamesMap.put('Ñ', "&Ntilde;"); HtmlEntityNamesMap.put('Ò', "&Ograve;"); HtmlEntityNamesMap.put('Ó', "&Oacute;"); HtmlEntityNamesMap.put('Ô', "&Ocirc;"); HtmlEntityNamesMap.put('Õ', "&Otilde;"); HtmlEntityNamesMap.put('Ö', "&Ouml;"); HtmlEntityNamesMap.put('×', "&times;"); HtmlEntityNamesMap.put('Ø', "&Oslash;"); HtmlEntityNamesMap.put('Ù', "&Ugrave;"); HtmlEntityNamesMap.put('Ú', "&Uacute;"); HtmlEntityNamesMap.put('Û', "&Ucirc;"); HtmlEntityNamesMap.put('Ü', "&Uuml;"); HtmlEntityNamesMap.put('Ý', "&Yacute;"); HtmlEntityNamesMap.put('Þ', "&THORN;"); HtmlEntityNamesMap.put('ß', "&szlig;"); HtmlEntityNamesMap.put('à', "&agrave;"); HtmlEntityNamesMap.put('á', "&aacute;"); HtmlEntityNamesMap.put('â', "&acirc;"); HtmlEntityNamesMap.put('ã', "&atilde;"); HtmlEntityNamesMap.put('ä', "&auml;"); HtmlEntityNamesMap.put('å', "&aring;"); HtmlEntityNamesMap.put('æ', "&aelig;"); HtmlEntityNamesMap.put('ç', "&ccedil;"); HtmlEntityNamesMap.put('è', "&egrave;"); HtmlEntityNamesMap.put('é', "&eacute;"); HtmlEntityNamesMap.put('ê', "&ecirc;"); HtmlEntityNamesMap.put('ë', "&euml;"); HtmlEntityNamesMap.put('ì', "&igrave;"); HtmlEntityNamesMap.put('í', "&iacute;"); HtmlEntityNamesMap.put('î', "&icirc;"); HtmlEntityNamesMap.put('ï', "&iuml;"); HtmlEntityNamesMap.put('ð', "&eth;"); HtmlEntityNamesMap.put('ñ', "&ntilde;"); HtmlEntityNamesMap.put('ò', "&ograve;"); HtmlEntityNamesMap.put('ó', "&oacute;"); HtmlEntityNamesMap.put('ô', "&ocirc;"); HtmlEntityNamesMap.put('õ', "&otilde;"); HtmlEntityNamesMap.put('ö', "&ouml;"); HtmlEntityNamesMap.put('÷', "&divide;"); HtmlEntityNamesMap.put('ø', "&oslash;"); HtmlEntityNamesMap.put('ù', "&ugrave;"); HtmlEntityNamesMap.put('ú', "&uacute;"); HtmlEntityNamesMap.put('û', "&ucirc;"); HtmlEntityNamesMap.put('ü', "&uuml;"); HtmlEntityNamesMap.put('ý', "&yacute;"); HtmlEntityNamesMap.put('þ', "&thorn;"); HtmlEntityNamesMap.put('ÿ', "&yuml;"); HtmlEntityNamesMap.put('€', "&euro;"); } // Time Zones: public static void restoreDateFormats(final TimeZone zone) { DateFormatDate.setTimeZone(zone); DateFormatDateShort.setTimeZone(zone); DateFormatDatetime.setTimeZone(zone); DateFormatDatetimeTimeZone.setTimeZone(zone); DateFormatTime.setTimeZone(zone); DbmsDateFormatDate.setTimeZone(zone); DbmsDateFormatDatetime.setTimeZone(zone); DbmsDateFormatTime.setTimeZone(zone); CsvFormatDate.setTimeZone(zone); CsvFormatDatetime.setTimeZone(zone); CsvFormatTime.setTimeZone(zone); FileDateFormatDatetime.setTimeZone(zone); } public static TimeZone createTimeZone(TimeZone zoneDefault, TimeZone zoneNew) { TimeZone zone = null; if (zoneDefault.getRawOffset() == zoneNew.getRawOffset()) { zone = zoneDefault; } else { zone = zoneNew; zone.setRawOffset(zoneNew.getRawOffset() + zoneDefault.getDSTSavings()); } return zone; } // Numbers in Spanish: private static final String MONEY_SPA_ZERO = "CERO"; private static final String MONEY_SPA_HUNDRED = "CIEN"; private static final String MONEY_SPA_THOUSAND_SNG = "MIL"; private static final String MONEY_SPA_THOUSAND_PLR = "MIL"; private static final String MONEY_SPA_MILLION_SNG = "MILLÓN"; private static final String MONEY_SPA_MILLION_PLR = "MILLONES"; private static final String[] masSpaUnits00 = { "UN", "DOS", "TRES", "CUATRO", "CINCO", "SEIS", "SIETE", "OCHO", "NUEVE" }; private static final String[] masSpaUnits10 = { "ONCE", "DOCE", "TRECE", "CATORCE", "QUINCE", "DIECISÉIS", "DIECISIETE", "DIECIOCHO", "DIECINUEVE" }; private static final String[] masSpaUnits20 = { "VEINTIÚN", "VEINTIDÓS", "VEINTITRÉS", "VEINTICUATRO", "VEINTICINCO", "VEINTISÉIS", "VEINTISIETE", "VEINTIOCHO", "VEINTINUEVE" }; private static final String[] masSpaTens = { "DIEZ", "VEINTE", "TREINTA", "CUARENTA", "CINCUENTA", "SESENTA", "SETENTA", "OCHENTA", "NOVENTA" }; private static final String[] masSpaHundreds = { "CIENTO", "DOSCIENTOS", "TRESCIENTOS", "CUATROCIENTOS", "QUINIENTOS", "SEISCIENTOS", "SETECIENTOS", "OCHOCIENTOS", "NOVECIENTOS" }; // Numbers in English: private static final String MONEY_ENG_ZERO = "ZERO"; private static final String MONEY_ENG_HUNDRED = "HUNDRED"; private static final String MONEY_ENG_THOUSAND = "THOUSAND"; private static final String MONEY_ENG_MILLION = "MILLION"; private static final String[] masEngUnits00 = { "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" }; private static final String[] masEngUnits10 = { "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTTEEN", "NINETEEN" }; private static final String[] masEngTens = { "TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY" }; public static DecimalFormat getDecimalFormat() { return DecimalFormatValue8D; } public static DecimalFormat getDecimalFormatAmount() { return DecimalFormatValue2D; } public static DecimalFormat getDecimalFormatAmountUnitary() { return DecimalFormatValue8D; } public static DecimalFormat getDecimalFormatExchangeRate() { return DecimalFormatValue4D; } public static DecimalFormat getDecimalFormatQuantity() { return DecimalFormatValue4D; } public static DecimalFormat getDecimalFormatPercentage() { return DecimalFormatPercentage8D; } public static DecimalFormat getDecimalFormatPercentageTax() { return DecimalFormatPercentage4D; } public static DecimalFormat getDecimalFormatPercentageDiscount() { return DecimalFormatPercentage4D; } public static boolean compareKeys(final int[] a, final int[] b) { if (a == null && b == null) { return true; } if (a == null && b != null || a != null && b == null) { return false; } else if (a.length == b.length) { for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } return false; } public static boolean compareKeys(final Object a, final Object b) { Object[] aoKeyA = null; Object[] aoKeyB = null; if (a == null && b == null) { return true; } if (a == null && b != null || a != null && b == null) { return false; } if (a.getClass() == int[].class && b.getClass() == int[].class) { return compareKeys((int[]) a, (int[]) b); } else if (a.getClass() == Object[].class && b.getClass() == Object[].class ) { aoKeyA = (Object[]) a; aoKeyB = (Object[]) b; if (aoKeyA.length == aoKeyB.length) { for (int i = 0; i < aoKeyA.length; i++) { if (aoKeyA[i] instanceof Number && aoKeyB[i] instanceof Number) { if (((Number) aoKeyA[i]).doubleValue() != ((Number) aoKeyB[i]).doubleValue()) { return false; } } else if (aoKeyA[i] instanceof String && aoKeyB[i] instanceof String) { if (((String) aoKeyA[i]).compareTo((String) aoKeyB[i]) != 0) { return false; } } else if (aoKeyA[i] instanceof java.util.Date && aoKeyB[i] instanceof java.util.Date) { if (((java.util.Date) aoKeyA[i]).compareTo((java.util.Date) aoKeyB[i]) != 0) { return false; } } else if (aoKeyA[i] != aoKeyB[i]) { return false; } } return true; } } return false; } public static boolean belongsTo(final String value, final String[] array) { for (String current : array) { if (current.equals(value)) { return true; } } return false; } public static boolean belongsTo(final int val, final int[] valArray) { boolean belongs = false; for (int curVal : valArray) { if (val == curVal) { belongs = true; break; } } return belongs; } public static boolean belongsTo(final int[] key, final int[][] keyArray) { boolean belongs = false; for (int[] curKey : keyArray) { if (compareKeys(key, curKey)) { belongs = true; break; } } return belongs; } public static int[] cloneKey(final int[] key) { int[] clonedKey = null; if (key != null) { clonedKey = new int[key.length]; for (int i = 0; i < key.length; i++) { clonedKey[i] = key[i]; } } return clonedKey; } public static Object[] cloneKey(final Object[] key) { Object[] clonedKey = null; if (key != null) { clonedKey = new Object[key.length]; for (int i = 0; i < key.length; i++) { clonedKey[i] = key[i]; } } return clonedKey; } public static int parseInt(final String text) { int value = 0; try { value = Integer.parseInt(text.trim().replaceAll(",", "").replaceAll("%", "")); } catch (NumberFormatException e) { } return value; } public static long parseLong(final String text) { long value = 0; try { value = Long.parseLong(text.trim().replaceAll(",", "").replaceAll("%", "")); } catch (NumberFormatException e) { } return value; } public static float parseFloat(final String text) { float value = 0; try { value = Float.parseFloat(text.trim().replaceAll(",", "").replaceAll("%", "")); } catch (NumberFormatException e) { } return value; } public static double parseDouble(final String text) { double value = 0; try { value = Double.parseDouble(text.trim().replaceAll(",", "").replaceAll("%", "")); } catch (NumberFormatException e) { } return value; } public static double round(final double value, final int decimals) { //return Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals); this method has inconsistencies, e.g. 0.04615 rounded to 4 decimals results in 0.0461 instead of 0.0462! RoundingDecimalFormat.setMaximumFractionDigits(decimals); return parseDouble(RoundingDecimalFormat.format(value)); } public static double roundAmount(final double value) { return round(value, getDecimalFormatAmount().getMaximumFractionDigits()); } public static boolean compareAmount(final double a, final double b) { return roundAmount(Math.abs(a - b)) < 0.01; } public static String textKey(final int[] key) { String textKey = ""; for (int id : key) { textKey += (textKey.length() == 0 ? "" : "-") + id; } return textKey; } public static String textRepeat(final String text, final int times) { String repeatedText = ""; for (int i = 0; i < times; i++) { repeatedText += text; } return repeatedText; } public static String textTrim(final String text) { String trimmedText = text.trim(); while(trimmedText.indexOf(" ") != -1) { trimmedText = trimmedText.replaceAll(" ", " "); } return trimmedText; } public static String[] textsTrim(final String[] texts) { String[] trimmedTexts = new String[texts.length]; for (int i = 0; i < texts.length; i++) { trimmedTexts[i] = textTrim(texts[i]); } return trimmedTexts; } public static String textLeft(final String text, final int count) { return text.length() <= count ? text : text.substring(0, count); } public static String textRight(final String text, final int count) { return text.length() <= count ? text : text.substring(text.length() - count, text.length()); } public static String textToAscii(final String text) { String ascii = textTrim(text); ascii = ascii.replaceAll("á", "a"); ascii = ascii.replaceAll("é", "e"); ascii = ascii.replaceAll("í", "i"); ascii = ascii.replaceAll("ó", "o"); ascii = ascii.replaceAll("ú", "u"); ascii = ascii.replaceAll("Á", "A"); ascii = ascii.replaceAll("É", "E"); ascii = ascii.replaceAll("Í", "I"); ascii = ascii.replaceAll("Ó", "O"); ascii = ascii.replaceAll("Ú", "U"); ascii = ascii.replaceAll("ä", "a"); ascii = ascii.replaceAll("ë", "e"); ascii = ascii.replaceAll("ï", "i"); ascii = ascii.replaceAll("ö", "o"); ascii = ascii.replaceAll("ü", "u"); ascii = ascii.replaceAll("Ä", "A"); ascii = ascii.replaceAll("Ë", "E"); ascii = ascii.replaceAll("Ï", "I"); ascii = ascii.replaceAll("Ö", "O"); ascii = ascii.replaceAll("Ü", "U"); ascii = ascii.replaceAll("à", "a"); ascii = ascii.replaceAll("è", "e"); ascii = ascii.replaceAll("ì", "i"); ascii = ascii.replaceAll("ò", "o"); ascii = ascii.replaceAll("ù", "u"); ascii = ascii.replaceAll("À", "A"); ascii = ascii.replaceAll("È", "E"); ascii = ascii.replaceAll("Ì", "I"); ascii = ascii.replaceAll("Ò", "O"); ascii = ascii.replaceAll("Ù", "U"); ascii = ascii.replaceAll("â", "a"); ascii = ascii.replaceAll("ê", "e"); ascii = ascii.replaceAll("î", "i"); ascii = ascii.replaceAll("ô", "o"); ascii = ascii.replaceAll("û", "u"); ascii = ascii.replaceAll("Â", "A"); ascii = ascii.replaceAll("Ê", "E"); ascii = ascii.replaceAll("Î", "I"); ascii = ascii.replaceAll("Ô", "O"); ascii = ascii.replaceAll("Û", "U"); ascii = ascii.replaceAll("ý", "y"); ascii = ascii.replaceAll("Ý", "Y"); ascii = ascii.replaceAll("ñ", "n"); ascii = ascii.replaceAll("Ñ", "N"); return ascii; } public static String textToXml(final String text) { String entity = ""; String textAux = textTrim(text); String xml = ""; for (Character c : textAux.toCharArray()) { entity = XmlEntityNamesMap.get(c); xml += entity == null ? c : entity; } return xml; } public static String textToHtml(final String text) { String entity = ""; String textAux = textTrim(text); String html = ""; for (Character c : textAux.toCharArray()) { entity = HtmlEntityNamesMap.get(c); html += entity == null ? c : entity; } return html; } public static String textToSql(final String text) { String sql = textTrim(text); sql = sql.replaceAll("'", "''"); return sql; } public static String textProperCase(final String text) { boolean spaceFound = true; char[] charArray = textTrim(text).toLowerCase().toCharArray(); for (int i = 0; i < charArray.length; i++) { if (spaceFound) { charArray[i] = ("" + charArray[i]).toUpperCase().toCharArray()[0]; spaceFound = false; } else if (charArray[i] == ' ') { spaceFound = true; } } return new String(charArray); } public static String[] textExplode(final String text, final String separator) { int pos = 0; int index = 0; Vector<String> strings = new Vector<String>(); do { index = separator.length() == 0 ? -1 : text.indexOf(separator, pos); if (index == -1) { strings.add(text.substring(pos)); } else { strings.add(text.substring(pos, index)); pos = index + 1; } } while (index != -1); return strings.toArray(new String[strings.size()]); } public static int[] textExplodeAsIntArray(final String text, final String separator) { String[] textArray = textExplode(text, separator); int[] intArray = new int[textArray.length]; for (int i = 0; i < textArray.length; i++) { intArray[i] = parseInt(textArray[i]); } return intArray; } public static String textImplode(final String[] texts, final String separator) { String text = ""; for (String string : texts) { text += (text.isEmpty() ? "" : separator) + string; } return text; } public static String validateSafePath(final String path) throws Exception { String text = new String("\\/:*?\"<>|"); char[] chars = text.toCharArray(); for (char c : chars) { if (path.contains("" + c)) { throw new Exception("No se permiten los caracteres: " + text); } } return path; } /** * Generates random key of requested length made up with characters A-Z, a-z, 0-9, and '+' and '-'. * @param length Requested length. * @return Random key. */ public static String generateRandomKey(final int length) { String key = ""; for (int i = 0; i < length; i++) { key += RandomKeyChars[(int) (Math.random() / (1d / (RandomKeyChars.length - 1)))]; } return key; } public static ImageIcon convertBlobToImageIcon(final Blob blob) throws SQLException, IOException { int i = 0; int bytesRead = 0; int bytesReadTotal = 0; byte[] buffer = new byte[1024]; byte[] bufferImageIcon = new byte[1024 * 1024]; InputStream is = blob.getBinaryStream(); while ((bytesRead = is.read(buffer)) != -1) { for (i = 0; i < bytesRead; i++) { bufferImageIcon[bytesReadTotal + i] = buffer[i]; } bytesReadTotal += bytesRead; } return new ImageIcon(bufferImageIcon); } public static byte[] convertBlobToBytes(final Blob blob) throws SQLException, IOException { InputStream is = blob.getBinaryStream(); DataInputStream dis = new DataInputStream(is); byte[] bytes = new byte[dis.available()]; dis.readFully(bytes); dis.close(); return bytes; } public static void printException(final String object, final Exception exception) { System.err.println("[" + object + "] " + exception); } public static void printException(final Object object, final Exception exception) { System.err.println("[" + object.getClass().getName() + "] " + exception); } public static void printSqlQuery(final String object, final String sql) { System.err.println("Current SQL query in [" + object + "]:"); System.err.println("[" + sql + "]"); } public static void printSqlQuery(final Object object, final String sql) { System.err.println("Current SQL query in [" + object.getClass().getName() + "]:"); System.err.println("[" + sql + "]"); } public static void showException(final String object, final Exception exception) { DLibUtils.printException(object, exception); JOptionPane.showMessageDialog(null, (exception.getMessage() == null ? exception : exception.getMessage()) + "\n\n[" + exception.getClass().getName() + " en " + object + "]", "Exception", JOptionPane.WARNING_MESSAGE); } public static void showException(final Object object, final Exception exception) { DLibUtils.printException(object, exception); JOptionPane.showMessageDialog(null, (exception.getMessage() == null ? exception : exception.getMessage()) + "\n\n[" + exception.getClass().getName() + " en " + object.getClass().getName() + "]", "Exception", JOptionPane.WARNING_MESSAGE); } /** Translates a value to its text representation. */ private static String translateValueToTexHundreds(final int value, final String languageIso639) { int integer; int remaining; String sText = ""; String sBlank = ""; if (languageIso639.compareTo(DLibConsts.LAN_ISO639_ES) == 0) { if (value == 100) { sText = MONEY_SPA_HUNDRED; } else { remaining = value; // Hundreds: integer = value / 100; if (integer > 0) { sText += masSpaHundreds[integer - 1]; remaining -= integer * 100; sBlank = " "; } // Tenths: if (remaining >= 11 && remaining <= 19) { sText += sBlank + masSpaUnits10[remaining - 10 - 1]; } else if (remaining >= 21 && remaining <= 29) { sText += sBlank + masSpaUnits20[remaining - 20 - 1]; } else { integer = remaining / 10; if (integer > 0) { sText += sBlank + masSpaTens[integer - 1]; remaining -= integer * 10; sBlank = " Y "; } integer = remaining; if (integer > 0) { sText += sBlank + masSpaUnits00[integer - 1]; } } } } else if (languageIso639.compareTo(DLibConsts.LAN_ISO639_EN) == 0) { remaining = value; // Hundreds: integer = value / 100; if (integer > 0) { sText += masEngUnits00[integer - 1] + " " + MONEY_ENG_HUNDRED; remaining -= integer * 100; sBlank = " "; } // Tenths: if (remaining >= 11 && remaining <= 19) { sText += sBlank + masEngUnits10[remaining - 10 - 1]; } else { integer = remaining / 10; if (integer > 0) { sText += sBlank + masEngTens[integer - 1]; remaining -= integer * 10; sBlank = "-"; } integer = remaining; if (integer > 0) { sText += sBlank + masEngUnits00[integer - 1]; } } } return sText; } /** Translates a value to its text representation. */ public static String translateValueToText(final double value, final int decs, final String languageIso639, final String curSingular, final String curPlural, final String curPrefix, final String curSuffix) { int integer = 0; double remaining = 0; String sDecs = ""; String sText = ""; String sBlank = ""; DecimalFormat formatDecs = new DecimalFormat("." + DLibUtils.textRepeat("0", decs)); if (value > MAX_VALUE) { sText = "(ERROR: value greater than" + MAX_VALUE + ")"; } else { if (languageIso639.compareTo(DLibConsts.LAN_ISO639_ES) == 0) { remaining = value; sText = "("; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_MILLION_SNG : MONEY_SPA_MILLION_PLR); remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_THOUSAND_SNG : MONEY_SPA_THOUSAND_PLR); remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } // Currency: if ((int) value == 0) { sText += MONEY_SPA_ZERO + " " + curPlural; } else if ((int) value == 1) { sText += " " + curSingular; } else { sText += " " + curPlural; } sDecs = formatDecs.format(value); sText += " " + sDecs.substring(sDecs.lastIndexOf(".") + 1) + "/1" + DLibUtils.textRepeat("0", decs) + " " + curSuffix + ")"; } else if (languageIso639.compareTo(DLibConsts.LAN_ISO639_EN) == 0) { remaining = value; sText = "("; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_MILLION; remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_THOUSAND; remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } // Currency: if ((int) value == 0) { sText += MONEY_ENG_ZERO + " " + curPlural; } else if ((int) value == 1) { sText += " " + curSingular; } else { sText += " " + curPlural; } sDecs = formatDecs.format(value); sText += " " + sDecs.substring(sDecs.lastIndexOf(".") + 1) + "/1" + DLibUtils.textRepeat("0", decs) + " " + curSuffix + ")"; } else { sText = "(ERROR: Not supported language.)"; } } return sText; } /** Translates units to its text representation. */ public static String translateUnitsToText(final double units, final int decs, final String languageIso639, final String unitSingular, final String unitPlural) { int integer = 0; double remaining = 0; double remainingDecs = 0; String sDecs = ""; String sText = ""; String sBlank = ""; DecimalFormat formatDecs = new DecimalFormat("." + DLibUtils.textRepeat("0", decs)); if (units > MAX_VALUE) { sText = "(ERROR: value grater than " + MAX_VALUE + ")"; } else { if (languageIso639.compareTo(DLibConsts.LAN_ISO639_EN) == 0) { // 1. Integer units. remaining = units; sText = "("; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_MILLION_SNG : MONEY_SPA_MILLION_PLR); remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_THOUSAND_SNG : MONEY_SPA_THOUSAND_PLR); remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } // 2. Decimal units. if ((int) units == 0 && units != 0d) { sText += MONEY_SPA_ZERO; } sDecs = formatDecs.format(units); sDecs = sDecs.substring(sDecs.lastIndexOf(".") + 1); remaining = parseDouble(sDecs); remainingDecs = remaining; while ((int) remainingDecs >= 10 && (int) remainingDecs % 10 == 0) { remainingDecs /= 10; } if (remaining > 0) { sText += " PUNTO "; for (int i = 0; i < sDecs.length() - ("" + ((int) remaining)).length(); i++) { sText += MONEY_SPA_ZERO + " "; } remaining = remainingDecs; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_MILLION_SNG : MONEY_SPA_MILLION_PLR); remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_THOUSAND_SNG : MONEY_SPA_THOUSAND_PLR); remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } } // Final text: if (units == 0d) { sText += MONEY_SPA_ZERO + " " + unitPlural; } else if (units == 1d) { sText += " " + unitSingular; } else { sText += " " + unitPlural; } sText += ")"; } else if (languageIso639.compareTo(DLibConsts.LAN_ISO639_ES) == 0) { // 1. Integer units. remaining = units; sText = "("; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_MILLION; remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_THOUSAND; remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } // 2. Decimal units. if ((int) units == 0 && units != 0d) { sText += MONEY_ENG_ZERO; } sDecs = formatDecs.format(units); sDecs = sDecs.substring(sDecs.lastIndexOf(".") + 1); remaining = parseDouble(sDecs); remainingDecs = remaining; while ((int) remainingDecs >= 10 && (int) remainingDecs % 10 == 0) { remainingDecs /= 10; } if (remaining > 0) { sText += " DOT "; for (int i = 0; i < sDecs.length() - ("" + ((int) remaining)).length(); i++) { sText += MONEY_ENG_ZERO + " "; } remaining = remainingDecs; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_MILLION; remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_THOUSAND; remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } } // Final text: if (units == 0d) { sText += MONEY_ENG_ZERO + " " + unitPlural; } else if (units == 1d) { sText += " " + unitSingular; } else { sText += " " + unitPlural; } sText += ")"; } else { sText = "(ERROR: Not supported language.)"; } } return sText; } public static void launch(final String command) { try { Runtime.getRuntime().exec(command); } catch (IOException e) { showException(DLibUtils.class.getName(), e); } catch (Exception e) { showException(DLibUtils.class.getName(), e); } } public static void launchCalculator() { launch("calc.exe"); } public static void launchFile(final String filePath) { try { Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler \"" + filePath + "\""); } catch (IOException e) { showException(DLibUtils.class.getName(), e); } catch (Exception e) { showException(DLibUtils.class.getName(), e); } } public static void invoke(Object target, Method method, Object[] args) throws IllegalAccessException, Exception { if (args == null) { method.invoke(target); } else { switch (args.length) { case 0: method.invoke(target); break; case 1: method.invoke(target, args[0]); break; case 2: method.invoke(target, args[0], args[1]); break; case 3: method.invoke(target, args[0], args[1], args[2]); break; case 4: method.invoke(target, args[0], args[1], args[2], args[3]); break; case 5: method.invoke(target, args[0], args[1], args[2], args[3], args[4]); break; case 6: method.invoke(target, args[0], args[1], args[2], args[3], args[4], args[5]); break; default: throw new Exception(DLibConsts.ERR_MSG_ARGS_MANY); } } } /** * Zip a text in byte array format. * * @param text text to zip. * @return text in byte array format. * @throws Exception */ public static byte[] zip(String text) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(text.length()); GZIPOutputStream gzip = new GZIPOutputStream(bos); gzip.write(text.getBytes()); gzip.close(); byte[] textZip = bos.toByteArray(); bos.close(); return textZip; } /** * Unzip a byte array in a string * * @param array byte array to unzip. * @return text as string. * @throws Exception */ public static String unzip(byte[] array) throws Exception { String line = ""; ByteArrayInputStream bis = new ByteArrayInputStream(array); GZIPInputStream gzip = new GZIPInputStream(bis); BufferedReader br = new BufferedReader(new InputStreamReader(gzip, "UTF-8")); StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } br.close(); gzip.close(); bis.close(); return sb.toString(); } }
src/sba/lib/DLibUtils.java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package sba.lib; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.math.RoundingMode; import java.sql.Blob; import java.sql.SQLException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.TimeZone; import java.util.Vector; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * * @author Sergio Flores */ public abstract class DLibUtils { public static final DecimalFormat DecimalFormatInteger = new DecimalFormat("#,##0"); public static final DecimalFormat DecimalFormatIntegerRaw = new DecimalFormat("#0"); public static final DecimalFormat DecimalFormatCalendarDay = new DecimalFormat("00"); public static final DecimalFormat DecimalFormatCalendarMonth = new DecimalFormat("00"); public static final DecimalFormat DecimalFormatCalendarYear = new DecimalFormat("0000"); public static final DecimalFormat DecimalFormatValue0D = new DecimalFormat("#,##0"); public static final DecimalFormat DecimalFormatValue2D = new DecimalFormat("#,##0.00"); public static final DecimalFormat DecimalFormatValue4D = new DecimalFormat("#,##0.0000"); public static final DecimalFormat DecimalFormatValue8D = new DecimalFormat("#,##0.00000000"); public static final DecimalFormat DecimalFormatPercentage0D = new DecimalFormat("#,##0%"); public static final DecimalFormat DecimalFormatPercentage2D = new DecimalFormat("#,##0.00%"); public static final DecimalFormat DecimalFormatPercentage4D = new DecimalFormat("#,##0.0000%"); public static final DecimalFormat DecimalFormatPercentage8D = new DecimalFormat("#,##0.00000000%"); public static final DecimalFormat DecimalNumberFormat = new DecimalFormat(DLibUtils.textRepeat("0", DLibConsts.LEN_NUM)); public static final DecimalFormat DecimalReferenceFormat = new DecimalFormat(DLibUtils.textRepeat("0", DLibConsts.LEN_REF_NUM)); public static final DecimalFormat RoundingDecimalFormat = new DecimalFormat(); public static final SimpleDateFormat DateFormatDate = new SimpleDateFormat("dd/MM/yyyy"); public static final SimpleDateFormat DateFormatDateShort = new SimpleDateFormat("dd/MM/yy"); public static final SimpleDateFormat DateFormatDateLong = new SimpleDateFormat("dd 'de' MMMM 'de' yyyy"); public static final SimpleDateFormat DateFormatDateYearMonth = new SimpleDateFormat("yyyy-MM"); public static final SimpleDateFormat DateFormatDateYear = new SimpleDateFormat("yyyy"); public static final SimpleDateFormat DateFormatDatetime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); public static final SimpleDateFormat DateFormatDatetimeTimeZone = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss Z"); public static final SimpleDateFormat DateFormatTime = new SimpleDateFormat("HH:mm:ss"); public static final SimpleDateFormat DbmsDateFormatDate = new SimpleDateFormat("yyyy-MM-dd"); public static final SimpleDateFormat DbmsDateFormatDatetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static final SimpleDateFormat DbmsDateFormatTime = new SimpleDateFormat("HH:mm:ss"); public static final SimpleDateFormat CsvFormatDate = new SimpleDateFormat("yyyy/MM/dd"); public static final SimpleDateFormat CsvFormatDatetime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); public static final SimpleDateFormat CsvFormatTime = new SimpleDateFormat("HH:mm:ss"); public static final SimpleDateFormat FileDateFormatDatetime = new SimpleDateFormat("yyyyMMdd HHmmss"); public static final HashMap<Character, String> XmlEntityNamesMap = new HashMap<>(); public static final HashMap<Character, String> HtmlEntityNamesMap = new HashMap<>(); public static final char[] RandomKeyChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '9' }; // 62 choices, but 63 characters actually: the last one must be repeated private static final double MAX_VALUE = 999999999.99; // 999,999,999.99 static { RoundingDecimalFormat.setRoundingMode(RoundingMode.HALF_UP); XmlEntityNamesMap.put('"', "&quot;"); XmlEntityNamesMap.put('&', "&amp;"); XmlEntityNamesMap.put('\'', "&apos;"); XmlEntityNamesMap.put('<', "&lt;"); XmlEntityNamesMap.put('>', "&gt;"); HtmlEntityNamesMap.put('"', "&quot;"); HtmlEntityNamesMap.put('&', "&amp;"); HtmlEntityNamesMap.put('<', "&lt;"); HtmlEntityNamesMap.put('>', "&gt;"); HtmlEntityNamesMap.put('¡', "&iexcl;"); HtmlEntityNamesMap.put('¢', "&cent;"); HtmlEntityNamesMap.put('£', "&pound;"); HtmlEntityNamesMap.put('¤', "&curren;"); HtmlEntityNamesMap.put('¥', "&yen;"); HtmlEntityNamesMap.put('¦', "&brvbar;"); HtmlEntityNamesMap.put('§', "&sect;"); HtmlEntityNamesMap.put('¨', "&uml;"); HtmlEntityNamesMap.put('©', "&copy;"); HtmlEntityNamesMap.put('ª', "&ordf;"); HtmlEntityNamesMap.put('«', "&laquo;"); HtmlEntityNamesMap.put('¬', "&not;"); HtmlEntityNamesMap.put('®', "&reg;"); HtmlEntityNamesMap.put('¯', "&macr;"); HtmlEntityNamesMap.put('°', "&deg;"); HtmlEntityNamesMap.put('±', "&plusmn;"); HtmlEntityNamesMap.put('²', "&sup2;"); HtmlEntityNamesMap.put('³', "&sup3;"); HtmlEntityNamesMap.put('´', "&acute;"); HtmlEntityNamesMap.put('µ', "&micro;"); HtmlEntityNamesMap.put('¶', "&para;"); HtmlEntityNamesMap.put('·', "&middot;"); HtmlEntityNamesMap.put('¸', "&cedil;"); HtmlEntityNamesMap.put('¹', "&sup1;"); HtmlEntityNamesMap.put('º', "&ordm;"); HtmlEntityNamesMap.put('»', "&raquo;"); HtmlEntityNamesMap.put('¼', "&frac14;"); HtmlEntityNamesMap.put('½', "&frac12;"); HtmlEntityNamesMap.put('¾', "&frac34;"); HtmlEntityNamesMap.put('¿', "&iquest;"); HtmlEntityNamesMap.put('À', "&Agrave;"); HtmlEntityNamesMap.put('Á', "&Aacute;"); HtmlEntityNamesMap.put('Â', "&Acirc;"); HtmlEntityNamesMap.put('Ã', "&Atilde;"); HtmlEntityNamesMap.put('Ä', "&Auml;"); HtmlEntityNamesMap.put('Å', "&Aring;"); HtmlEntityNamesMap.put('Æ', "&AElig;"); HtmlEntityNamesMap.put('Ç', "&Ccedil;"); HtmlEntityNamesMap.put('È', "&Egrave;"); HtmlEntityNamesMap.put('É', "&Eacute;"); HtmlEntityNamesMap.put('Ê', "&Ecirc;"); HtmlEntityNamesMap.put('Ë', "&Euml;"); HtmlEntityNamesMap.put('Ì', "&Igrave;"); HtmlEntityNamesMap.put('Í', "&Iacute;"); HtmlEntityNamesMap.put('Î', "&Icirc;"); HtmlEntityNamesMap.put('Ï', "&Iuml;"); HtmlEntityNamesMap.put('Ð', "&ETH;"); HtmlEntityNamesMap.put('Ñ', "&Ntilde;"); HtmlEntityNamesMap.put('Ò', "&Ograve;"); HtmlEntityNamesMap.put('Ó', "&Oacute;"); HtmlEntityNamesMap.put('Ô', "&Ocirc;"); HtmlEntityNamesMap.put('Õ', "&Otilde;"); HtmlEntityNamesMap.put('Ö', "&Ouml;"); HtmlEntityNamesMap.put('×', "&times;"); HtmlEntityNamesMap.put('Ø', "&Oslash;"); HtmlEntityNamesMap.put('Ù', "&Ugrave;"); HtmlEntityNamesMap.put('Ú', "&Uacute;"); HtmlEntityNamesMap.put('Û', "&Ucirc;"); HtmlEntityNamesMap.put('Ü', "&Uuml;"); HtmlEntityNamesMap.put('Ý', "&Yacute;"); HtmlEntityNamesMap.put('Þ', "&THORN;"); HtmlEntityNamesMap.put('ß', "&szlig;"); HtmlEntityNamesMap.put('à', "&agrave;"); HtmlEntityNamesMap.put('á', "&aacute;"); HtmlEntityNamesMap.put('â', "&acirc;"); HtmlEntityNamesMap.put('ã', "&atilde;"); HtmlEntityNamesMap.put('ä', "&auml;"); HtmlEntityNamesMap.put('å', "&aring;"); HtmlEntityNamesMap.put('æ', "&aelig;"); HtmlEntityNamesMap.put('ç', "&ccedil;"); HtmlEntityNamesMap.put('è', "&egrave;"); HtmlEntityNamesMap.put('é', "&eacute;"); HtmlEntityNamesMap.put('ê', "&ecirc;"); HtmlEntityNamesMap.put('ë', "&euml;"); HtmlEntityNamesMap.put('ì', "&igrave;"); HtmlEntityNamesMap.put('í', "&iacute;"); HtmlEntityNamesMap.put('î', "&icirc;"); HtmlEntityNamesMap.put('ï', "&iuml;"); HtmlEntityNamesMap.put('ð', "&eth;"); HtmlEntityNamesMap.put('ñ', "&ntilde;"); HtmlEntityNamesMap.put('ò', "&ograve;"); HtmlEntityNamesMap.put('ó', "&oacute;"); HtmlEntityNamesMap.put('ô', "&ocirc;"); HtmlEntityNamesMap.put('õ', "&otilde;"); HtmlEntityNamesMap.put('ö', "&ouml;"); HtmlEntityNamesMap.put('÷', "&divide;"); HtmlEntityNamesMap.put('ø', "&oslash;"); HtmlEntityNamesMap.put('ù', "&ugrave;"); HtmlEntityNamesMap.put('ú', "&uacute;"); HtmlEntityNamesMap.put('û', "&ucirc;"); HtmlEntityNamesMap.put('ü', "&uuml;"); HtmlEntityNamesMap.put('ý', "&yacute;"); HtmlEntityNamesMap.put('þ', "&thorn;"); HtmlEntityNamesMap.put('ÿ', "&yuml;"); HtmlEntityNamesMap.put('€', "&euro;"); } // Time Zones: public static void restoreDateFormats(final TimeZone zone) { DateFormatDate.setTimeZone(zone); DateFormatDateShort.setTimeZone(zone); DateFormatDatetime.setTimeZone(zone); DateFormatDatetimeTimeZone.setTimeZone(zone); DateFormatTime.setTimeZone(zone); DbmsDateFormatDate.setTimeZone(zone); DbmsDateFormatDatetime.setTimeZone(zone); DbmsDateFormatTime.setTimeZone(zone); CsvFormatDate.setTimeZone(zone); CsvFormatDatetime.setTimeZone(zone); CsvFormatTime.setTimeZone(zone); FileDateFormatDatetime.setTimeZone(zone); } public static TimeZone createTimeZone(TimeZone zoneDefault, TimeZone zoneNew) { TimeZone zone = null; if (zoneDefault.getRawOffset() == zoneNew.getRawOffset()) { zone = zoneDefault; } else { zone = zoneNew; zone.setRawOffset(zoneNew.getRawOffset() + zoneDefault.getDSTSavings()); } return zone; } // Numbers in Spanish: private static final String MONEY_SPA_ZERO = "CERO"; private static final String MONEY_SPA_HUNDRED = "CIEN"; private static final String MONEY_SPA_THOUSAND_SNG = "MIL"; private static final String MONEY_SPA_THOUSAND_PLR = "MIL"; private static final String MONEY_SPA_MILLION_SNG = "MILLÓN"; private static final String MONEY_SPA_MILLION_PLR = "MILLONES"; private static final String[] masSpaUnits00 = { "UN", "DOS", "TRES", "CUATRO", "CINCO", "SEIS", "SIETE", "OCHO", "NUEVE" }; private static final String[] masSpaUnits10 = { "ONCE", "DOCE", "TRECE", "CATORCE", "QUINCE", "DIECISÉIS", "DIECISIETE", "DIECIOCHO", "DIECINUEVE" }; private static final String[] masSpaUnits20 = { "VEINTIÚN", "VEINTIDÓS", "VEINTITRÉS", "VEINTICUATRO", "VEINTICINCO", "VEINTISÉIS", "VEINTISIETE", "VEINTIOCHO", "VEINTINUEVE" }; private static final String[] masSpaTens = { "DIEZ", "VEINTE", "TREINTA", "CUARENTA", "CINCUENTA", "SESENTA", "SETENTA", "OCHENTA", "NOVENTA" }; private static final String[] masSpaHundreds = { "CIENTO", "DOSCIENTOS", "TRESCIENTOS", "CUATROCIENTOS", "QUINIENTOS", "SEISCIENTOS", "SETECIENTOS", "OCHOCIENTOS", "NOVECIENTOS" }; // Numbers in English: private static final String MONEY_ENG_ZERO = "ZERO"; private static final String MONEY_ENG_HUNDRED = "HUNDRED"; private static final String MONEY_ENG_THOUSAND = "THOUSAND"; private static final String MONEY_ENG_MILLION = "MILLION"; private static final String[] masEngUnits00 = { "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" }; private static final String[] masEngUnits10 = { "ELEVEN", "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN", "EIGHTTEEN", "NINETEEN" }; private static final String[] masEngTens = { "TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY", "SIXTY", "SEVENTY", "EIGHTY", "NINETY" }; public static DecimalFormat getDecimalFormat() { return DecimalFormatValue8D; } public static DecimalFormat getDecimalFormatAmount() { return DecimalFormatValue2D; } public static DecimalFormat getDecimalFormatAmountUnitary() { return DecimalFormatValue8D; } public static DecimalFormat getDecimalFormatExchangeRate() { return DecimalFormatValue4D; } public static DecimalFormat getDecimalFormatQuantity() { return DecimalFormatValue4D; } public static DecimalFormat getDecimalFormatPercentage() { return DecimalFormatPercentage8D; } public static DecimalFormat getDecimalFormatPercentageTax() { return DecimalFormatPercentage4D; } public static DecimalFormat getDecimalFormatPercentageDiscount() { return DecimalFormatPercentage4D; } public static boolean compareKeys(final int[] a, final int[] b) { if (a == null && b == null) { return true; } if (a == null && b != null || a != null && b == null) { return false; } else if (a.length == b.length) { for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } return false; } public static boolean compareKeys(final Object a, final Object b) { Object[] aoKeyA = null; Object[] aoKeyB = null; if (a == null && b == null) { return true; } if (a == null && b != null || a != null && b == null) { return false; } if (a.getClass() == int[].class && b.getClass() == int[].class) { return compareKeys((int[]) a, (int[]) b); } else if (a.getClass() == Object[].class && b.getClass() == Object[].class ) { aoKeyA = (Object[]) a; aoKeyB = (Object[]) b; if (aoKeyA.length == aoKeyB.length) { for (int i = 0; i < aoKeyA.length; i++) { if (aoKeyA[i] instanceof Number && aoKeyB[i] instanceof Number) { if (((Number) aoKeyA[i]).doubleValue() != ((Number) aoKeyB[i]).doubleValue()) { return false; } } else if (aoKeyA[i] instanceof String && aoKeyB[i] instanceof String) { if (((String) aoKeyA[i]).compareTo((String) aoKeyB[i]) != 0) { return false; } } else if (aoKeyA[i] instanceof java.util.Date && aoKeyB[i] instanceof java.util.Date) { if (((java.util.Date) aoKeyA[i]).compareTo((java.util.Date) aoKeyB[i]) != 0) { return false; } } else if (aoKeyA[i] != aoKeyB[i]) { return false; } } return true; } } return false; } public static boolean belongsTo(final String value, final String[] array) { for (String current : array) { if (current.equals(value)) { return true; } } return false; } public static boolean belongsTo(final int val, final int[] valArray) { boolean belongs = false; for (int curVal : valArray) { if (val == curVal) { belongs = true; break; } } return belongs; } public static boolean belongsTo(final int[] key, final int[][] keyArray) { boolean belongs = false; for (int[] curKey : keyArray) { if (compareKeys(key, curKey)) { belongs = true; break; } } return belongs; } public static int[] cloneKey(final int[] key) { int[] clonedKey = null; if (key != null) { clonedKey = new int[key.length]; for (int i = 0; i < key.length; i++) { clonedKey[i] = key[i]; } } return clonedKey; } public static Object[] cloneKey(final Object[] key) { Object[] clonedKey = null; if (key != null) { clonedKey = new Object[key.length]; for (int i = 0; i < key.length; i++) { clonedKey[i] = key[i]; } } return clonedKey; } public static int parseInt(final String text) { int value = 0; try { value = Integer.parseInt(text.trim().replaceAll(",", "").replaceAll("%", "")); } catch (NumberFormatException e) { } return value; } public static long parseLong(final String text) { long value = 0; try { value = Long.parseLong(text.trim().replaceAll(",", "").replaceAll("%", "")); } catch (NumberFormatException e) { } return value; } public static float parseFloat(final String text) { float value = 0; try { value = Float.parseFloat(text.trim().replaceAll(",", "").replaceAll("%", "")); } catch (NumberFormatException e) { } return value; } public static double parseDouble(final String text) { double value = 0; try { value = Double.parseDouble(text.trim().replaceAll(",", "").replaceAll("%", "")); } catch (NumberFormatException e) { } return value; } public static double round(final double value, final int decimals) { //return Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals); this method has inconsistencies, e.g. 0.04615 rounded to 4 decimals results in 0.0461 instead of 0.0462! RoundingDecimalFormat.setMaximumFractionDigits(decimals); return parseDouble(RoundingDecimalFormat.format(value)); } public static double roundAmount(final double value) { return round(value, getDecimalFormatAmount().getMaximumFractionDigits()); } public static boolean compareAmount(final double a, final double b) { return roundAmount(Math.abs(a - b)) < 0.01; } public static String textKey(final int[] key) { String textKey = ""; for (int id : key) { textKey += (textKey.length() == 0 ? "" : "-") + id; } return textKey; } public static String textRepeat(final String text, final int times) { String repeatedText = ""; for (int i = 0; i < times; i++) { repeatedText += text; } return repeatedText; } public static String textTrim(final String text) { String trimmedText = text.trim(); while(trimmedText.indexOf(" ") != -1) { trimmedText = trimmedText.replaceAll(" ", " "); } return trimmedText; } public static String[] textsTrim(final String[] texts) { String[] trimmedTexts = new String[texts.length]; for (int i = 0; i < texts.length; i++) { trimmedTexts[i] = textTrim(texts[i]); } return trimmedTexts; } public static String textLeft(final String text, final int count) { return text.length() <= count ? text : text.substring(0, count); } public static String textRight(final String text, final int count) { return text.length() <= count ? text : text.substring(text.length() - count, text.length()); } public static String textToAscii(final String text) { String ascii = textTrim(text); ascii = ascii.replaceAll("á", "a"); ascii = ascii.replaceAll("é", "e"); ascii = ascii.replaceAll("í", "i"); ascii = ascii.replaceAll("ó", "o"); ascii = ascii.replaceAll("ú", "u"); ascii = ascii.replaceAll("Á", "A"); ascii = ascii.replaceAll("É", "E"); ascii = ascii.replaceAll("Í", "I"); ascii = ascii.replaceAll("Ó", "O"); ascii = ascii.replaceAll("Ú", "U"); ascii = ascii.replaceAll("ä", "a"); ascii = ascii.replaceAll("ë", "e"); ascii = ascii.replaceAll("ï", "i"); ascii = ascii.replaceAll("ö", "o"); ascii = ascii.replaceAll("ü", "u"); ascii = ascii.replaceAll("Ä", "A"); ascii = ascii.replaceAll("Ë", "E"); ascii = ascii.replaceAll("Ï", "I"); ascii = ascii.replaceAll("Ö", "O"); ascii = ascii.replaceAll("Ü", "U"); ascii = ascii.replaceAll("à", "a"); ascii = ascii.replaceAll("è", "e"); ascii = ascii.replaceAll("ì", "i"); ascii = ascii.replaceAll("ò", "o"); ascii = ascii.replaceAll("ù", "u"); ascii = ascii.replaceAll("À", "A"); ascii = ascii.replaceAll("È", "E"); ascii = ascii.replaceAll("Ì", "I"); ascii = ascii.replaceAll("Ò", "O"); ascii = ascii.replaceAll("Ù", "U"); ascii = ascii.replaceAll("â", "a"); ascii = ascii.replaceAll("ê", "e"); ascii = ascii.replaceAll("î", "i"); ascii = ascii.replaceAll("ô", "o"); ascii = ascii.replaceAll("û", "u"); ascii = ascii.replaceAll("Â", "A"); ascii = ascii.replaceAll("Ê", "E"); ascii = ascii.replaceAll("Î", "I"); ascii = ascii.replaceAll("Ô", "O"); ascii = ascii.replaceAll("Û", "U"); ascii = ascii.replaceAll("ý", "y"); ascii = ascii.replaceAll("Ý", "Y"); ascii = ascii.replaceAll("ñ", "n"); ascii = ascii.replaceAll("Ñ", "N"); return ascii; } public static String textToXml(final String text) { String entity = ""; String textAux = textTrim(text); String xml = ""; for (Character c : textAux.toCharArray()) { entity = XmlEntityNamesMap.get(c); xml += entity == null ? c : entity; } return xml; } public static String textToHtml(final String text) { String entity = ""; String textAux = textTrim(text); String html = ""; for (Character c : textAux.toCharArray()) { entity = HtmlEntityNamesMap.get(c); html += entity == null ? c : entity; } return html; } public static String textToSql(final String text) { String sql = textTrim(text); sql = sql.replaceAll("'", "''"); return sql; } public static String textProperCase(final String text) { boolean spaceFound = true; char[] charArray = textTrim(text).toLowerCase().toCharArray(); for (int i = 0; i < charArray.length; i++) { if (spaceFound) { charArray[i] = ("" + charArray[i]).toUpperCase().toCharArray()[0]; spaceFound = false; } else if (charArray[i] == ' ') { spaceFound = true; } } return new String(charArray); } public static String[] textExplode(final String text, final String separator) { int pos = 0; int index = 0; Vector<String> strings = new Vector<String>(); do { index = separator.length() == 0 ? -1 : text.indexOf(separator, pos); if (index == -1) { strings.add(text.substring(pos)); } else { strings.add(text.substring(pos, index)); pos = index + 1; } } while (index != -1); return strings.toArray(new String[strings.size()]); } public static int[] textExplodeAsIntArray(final String text, final String separator) { String[] textArray = textExplode(text, separator); int[] intArray = new int[textArray.length]; for (int i = 0; i < textArray.length; i++) { intArray[i] = parseInt(textArray[i]); } return intArray; } public static String textImplode(final String[] texts, final String separator) { String text = ""; for (String string : texts) { text += (text.isEmpty() ? "" : separator) + string; } return text; } public static String validateSafePath(final String path) throws Exception { String text = new String("\\/:*?\"<>|"); char[] chars = text.toCharArray(); for (char c : chars) { if (path.contains("" + c)) { throw new Exception("No se permiten los caracteres: " + text); } } return path; } /** * Generates random key of requested length made up with characters A-Z, a-z, 0-9, and '+' and '-'. * @param length Requested length. * @return Random key. */ public static String generateRandomKey(final int length) { String key = ""; for (int i = 0; i < length; i++) { key += RandomKeyChars[(int) (Math.random() / (1d / (RandomKeyChars.length - 1)))]; } return key; } public static ImageIcon convertBlobToImageIcon(final Blob blob) throws SQLException, IOException { int i = 0; int bytesRead = 0; int bytesReadTotal = 0; byte[] buffer = new byte[1024]; byte[] bufferImageIcon = new byte[1024 * 1024]; InputStream is = blob.getBinaryStream(); while ((bytesRead = is.read(buffer)) != -1) { for (i = 0; i < bytesRead; i++) { bufferImageIcon[bytesReadTotal + i] = buffer[i]; } bytesReadTotal += bytesRead; } return new ImageIcon(bufferImageIcon); } public static byte[] convertBlobToBytes(final Blob blob) throws SQLException, IOException { InputStream is = blob.getBinaryStream(); DataInputStream dis = new DataInputStream(is); byte[] bytes = new byte[dis.available()]; dis.readFully(bytes); dis.close(); return bytes; } public static void printException(final String object, final Exception exception) { System.err.println("[" + object + "] " + exception); } public static void printException(final Object object, final Exception exception) { System.err.println("[" + object.getClass().getName() + "] " + exception); } public static void printSqlQuery(final String object, final String sql) { System.err.println("Current SQL query in [" + object + "]:"); System.err.println("[" + sql + "]"); } public static void printSqlQuery(final Object object, final String sql) { System.err.println("Current SQL query in [" + object.getClass().getName() + "]:"); System.err.println("[" + sql + "]"); } public static void showException(final String object, final Exception exception) { DLibUtils.printException(object, exception); JOptionPane.showMessageDialog(null, (exception.getMessage() == null ? exception : exception.getMessage()) + "\n\n[" + exception.getClass().getName() + " en " + object + "]", "Exception", JOptionPane.WARNING_MESSAGE); } public static void showException(final Object object, final Exception exception) { DLibUtils.printException(object, exception); JOptionPane.showMessageDialog(null, (exception.getMessage() == null ? exception : exception.getMessage()) + "\n\n[" + exception.getClass().getName() + " en " + object.getClass().getName() + "]", "Exception", JOptionPane.WARNING_MESSAGE); } /** Translates a value to its text representation. */ private static String translateValueToTexHundreds(final int value, final String languageIso639) { int integer; int remaining; String sText = ""; String sBlank = ""; if (languageIso639.compareTo(DLibConsts.LAN_ISO639_ES) == 0) { if (value == 100) { sText = MONEY_SPA_HUNDRED; } else { remaining = value; // Hundreds: integer = value / 100; if (integer > 0) { sText += masSpaHundreds[integer - 1]; remaining -= integer * 100; sBlank = " "; } // Tenths: if (remaining >= 11 && remaining <= 19) { sText += sBlank + masSpaUnits10[remaining - 10 - 1]; } else if (remaining >= 21 && remaining <= 29) { sText += sBlank + masSpaUnits20[remaining - 20 - 1]; } else { integer = remaining / 10; if (integer > 0) { sText += sBlank + masSpaTens[integer - 1]; remaining -= integer * 10; sBlank = " Y "; } integer = remaining; if (integer > 0) { sText += sBlank + masSpaUnits00[integer - 1]; } } } } else if (languageIso639.compareTo(DLibConsts.LAN_ISO639_EN) == 0) { remaining = value; // Hundreds: integer = value / 100; if (integer > 0) { sText += masEngUnits00[integer - 1] + " " + MONEY_ENG_HUNDRED; remaining -= integer * 100; sBlank = " "; } // Tenths: if (remaining >= 11 && remaining <= 19) { sText += sBlank + masEngUnits10[remaining - 10 - 1]; } else { integer = remaining / 10; if (integer > 0) { sText += sBlank + masEngTens[integer - 1]; remaining -= integer * 10; sBlank = "-"; } integer = remaining; if (integer > 0) { sText += sBlank + masEngUnits00[integer - 1]; } } } return sText; } /** Translates a value to its text representation. */ public static String translateValueToText(final double value, final int decs, final String languageIso639, final String curSingular, final String curPlural, final String curPrefix, final String curSuffix) { int integer = 0; double remaining = 0; String sDecs = ""; String sText = ""; String sBlank = ""; DecimalFormat formatDecs = new DecimalFormat("." + DLibUtils.textRepeat("0", decs)); if (value > MAX_VALUE) { sText = "(ERROR: value greater than" + MAX_VALUE + ")"; } else { if (languageIso639.compareTo(DLibConsts.LAN_ISO639_ES) == 0) { remaining = value; sText = "("; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_MILLION_SNG : MONEY_SPA_MILLION_PLR); remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_THOUSAND_SNG : MONEY_SPA_THOUSAND_PLR); remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } // Currency: if ((int) value == 0) { sText += MONEY_SPA_ZERO + " " + curPlural; } else if ((int) value == 1) { sText += " " + curSingular; } else { sText += " " + curPlural; } sDecs = formatDecs.format(value); sText += " " + sDecs.substring(sDecs.lastIndexOf(".") + 1) + "/1" + DLibUtils.textRepeat("0", decs) + " " + curSuffix + ")"; } else if (languageIso639.compareTo(DLibConsts.LAN_ISO639_EN) == 0) { remaining = value; sText = "("; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_MILLION; remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_THOUSAND; remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } // Currency: if ((int) value == 0) { sText += MONEY_ENG_ZERO + " " + curPlural; } else if ((int) value == 1) { sText += " " + curSingular; } else { sText += " " + curPlural; } sDecs = formatDecs.format(value); sText += " " + sDecs.substring(sDecs.lastIndexOf(".") + 1) + "/1" + DLibUtils.textRepeat("0", decs) + " " + curSuffix + ")"; } else { sText = "(ERROR: Not supported language.)"; } } return sText; } /** Translates units to its text representation. */ public static String translateUnitsToText(final double units, final int decs, final String languageIso639, final String unitSingular, final String unitPlural) { int integer = 0; double remaining = 0; double remainingDecs = 0; String sDecs = ""; String sText = ""; String sBlank = ""; DecimalFormat formatDecs = new DecimalFormat("." + DLibUtils.textRepeat("0", decs)); if (units > MAX_VALUE) { sText = "(ERROR: value grater than " + MAX_VALUE + ")"; } else { if (languageIso639.compareTo(DLibConsts.LAN_ISO639_EN) == 0) { // 1. Integer units. remaining = units; sText = "("; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_MILLION_SNG : MONEY_SPA_MILLION_PLR); remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_THOUSAND_SNG : MONEY_SPA_THOUSAND_PLR); remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } // 2. Decimal units. if ((int) units == 0 && units != 0d) { sText += MONEY_SPA_ZERO; } sDecs = formatDecs.format(units); sDecs = sDecs.substring(sDecs.lastIndexOf(".") + 1); remaining = parseDouble(sDecs); remainingDecs = remaining; while ((int) remainingDecs >= 10 && (int) remainingDecs % 10 == 0) { remainingDecs /= 10; } if (remaining > 0) { sText += " PUNTO "; for (int i = 0; i < sDecs.length() - ("" + ((int) remaining)).length(); i++) { sText += MONEY_SPA_ZERO + " "; } remaining = remainingDecs; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_MILLION_SNG : MONEY_SPA_MILLION_PLR); remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + (integer == 1 ? MONEY_SPA_THOUSAND_SNG : MONEY_SPA_THOUSAND_PLR); remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } } // Final text: if (units == 0d) { sText += MONEY_SPA_ZERO + " " + unitPlural; } else if (units == 1d) { sText += " " + unitSingular; } else { sText += " " + unitPlural; } sText += ")"; } else if (languageIso639.compareTo(DLibConsts.LAN_ISO639_ES) == 0) { // 1. Integer units. remaining = units; sText = "("; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_MILLION; remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_THOUSAND; remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } // 2. Decimal units. if ((int) units == 0 && units != 0d) { sText += MONEY_ENG_ZERO; } sDecs = formatDecs.format(units); sDecs = sDecs.substring(sDecs.lastIndexOf(".") + 1); remaining = parseDouble(sDecs); remainingDecs = remaining; while ((int) remainingDecs >= 10 && (int) remainingDecs % 10 == 0) { remainingDecs /= 10; } if (remaining > 0) { sText += " DOT "; for (int i = 0; i < sDecs.length() - ("" + ((int) remaining)).length(); i++) { sText += MONEY_ENG_ZERO + " "; } remaining = remainingDecs; // Millions: integer = (int) (remaining / 1000000.0); if (integer > 0) { sText += translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_MILLION; remaining -= integer * 1000000.0; sBlank = " "; } // Thousands: integer = (int) (remaining / 1000.0); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639) + " " + MONEY_ENG_THOUSAND; remaining -= integer * 1000.0; sBlank = " "; } // Units: integer = (int) (remaining); if (integer > 0) { sText += sBlank + translateValueToTexHundreds(integer, languageIso639); } } // Final text: if (units == 0d) { sText += MONEY_ENG_ZERO + " " + unitPlural; } else if (units == 1d) { sText += " " + unitSingular; } else { sText += " " + unitPlural; } sText += ")"; } else { sText = "(ERROR: Not supported language.)"; } } return sText; } public static void launch(final String command) { try { Runtime.getRuntime().exec(command); } catch (IOException e) { showException(DLibUtils.class.getName(), e); } catch (Exception e) { showException(DLibUtils.class.getName(), e); } } public static void launchCalculator() { launch("calc.exe"); } public static void launchFile(final String filePath) { try { Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler \"" + filePath + "\""); } catch (IOException e) { showException(DLibUtils.class.getName(), e); } catch (Exception e) { showException(DLibUtils.class.getName(), e); } } public static void invoke(Object target, Method method, Object[] args) throws IllegalAccessException, Exception { if (args == null) { method.invoke(target); } else { switch (args.length) { case 0: method.invoke(target); break; case 1: method.invoke(target, args[0]); break; case 2: method.invoke(target, args[0], args[1]); break; case 3: method.invoke(target, args[0], args[1], args[2]); break; case 4: method.invoke(target, args[0], args[1], args[2], args[3]); break; case 5: method.invoke(target, args[0], args[1], args[2], args[3], args[4]); break; case 6: method.invoke(target, args[0], args[1], args[2], args[3], args[4], args[5]); break; default: throw new Exception(DLibConsts.ERR_MSG_ARGS_MANY); } } } /** * Zip a text in byte array format. * * @param text text to zip. * @return text in byte array format. * @throws Exception */ public static byte[] zip(String text) throws Exception { ByteArrayOutputStream bos = new ByteArrayOutputStream(text.length()); GZIPOutputStream gzip = new GZIPOutputStream(bos); gzip.write(text.getBytes()); gzip.close(); byte[] textZip = bos.toByteArray(); bos.close(); return textZip; } /** * Unzip a byte array in a string * * @param array byte array to unzip. * @return text as string. * @throws Exception */ public static String unzip(byte[] array) throws Exception { String line = ""; ByteArrayInputStream bis = new ByteArrayInputStream(array); GZIPInputStream gzip = new GZIPInputStream(bis); BufferedReader br = new BufferedReader(new InputStreamReader(gzip, "UTF-8")); StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } br.close(); gzip.close(); bis.close(); return sb.toString(); } }
Adición de miembro a DLibUtils para formateador de fechas-hora ISO.
src/sba/lib/DLibUtils.java
Adición de miembro a DLibUtils para formateador de fechas-hora ISO.
<ide><path>rc/sba/lib/DLibUtils.java <ide> public static final SimpleDateFormat CsvFormatDatetime = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); <ide> public static final SimpleDateFormat CsvFormatTime = new SimpleDateFormat("HH:mm:ss"); <ide> public static final SimpleDateFormat FileDateFormatDatetime = new SimpleDateFormat("yyyyMMdd HHmmss"); <add> public static final SimpleDateFormat IsoFormatDatetime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); <ide> public static final HashMap<Character, String> XmlEntityNamesMap = new HashMap<>(); <ide> public static final HashMap<Character, String> HtmlEntityNamesMap = new HashMap<>(); <ide> public static final char[] RandomKeyChars = new char[] {
Java
apache-2.0
2b3f6616db93e81dfa8ab59abdb772d3e0b9a20b
0
lastaflute/lastaflute-example-harbor,lastaflute/lastaflute-example-harbor,lastaflute/lastaflute-example-harbor,lastaflute/lastaflute-example-harbor,lastaflute/lastaflute-example-harbor,lastaflute/lastaflute-example-harbor
/* * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.docksidestage.mylasta.action; import org.docksidestage.mylasta.action.HarborLabels; import org.lastaflute.core.message.UserMessage; /** * The keys for message. * @author FreeGen */ public class HarborMessages extends HarborLabels { /** The serial version UID for object serialization. (Default) */ private static final long serialVersionUID = 1L; /** The key of the message: must be false */ public static final String CONSTRAINTS_AssertFalse_MESSAGE = "{constraints.AssertFalse.message}"; /** The key of the message: must be true */ public static final String CONSTRAINTS_AssertTrue_MESSAGE = "{constraints.AssertTrue.message}"; /** The key of the message: must be less than ${inclusive == true ? 'or equal to ' : ''}{value} */ public static final String CONSTRAINTS_DecimalMax_MESSAGE = "{constraints.DecimalMax.message}"; /** The key of the message: must be greater than ${inclusive == true ? 'or equal to ' : ''}{value} */ public static final String CONSTRAINTS_DecimalMin_MESSAGE = "{constraints.DecimalMin.message}"; /** The key of the message: numeric value out of bounds (&lt;{integer} digits&gt;.&lt;{fraction} digits&gt; expected) */ public static final String CONSTRAINTS_Digits_MESSAGE = "{constraints.Digits.message}"; /** The key of the message: must be in the future */ public static final String CONSTRAINTS_Future_MESSAGE = "{constraints.Future.message}"; /** The key of the message: must be less than or equal to {value} */ public static final String CONSTRAINTS_Max_MESSAGE = "{constraints.Max.message}"; /** The key of the message: must be greater than or equal to {value} */ public static final String CONSTRAINTS_Min_MESSAGE = "{constraints.Min.message}"; /** The key of the message: may not be null */ public static final String CONSTRAINTS_NotNull_MESSAGE = "{constraints.NotNull.message}"; /** The key of the message: must be null */ public static final String CONSTRAINTS_Null_MESSAGE = "{constraints.Null.message}"; /** The key of the message: must be in the past */ public static final String CONSTRAINTS_Past_MESSAGE = "{constraints.Past.message}"; /** The key of the message: invalid format */ public static final String CONSTRAINTS_Pattern_MESSAGE = "{constraints.Pattern.message}"; /** The key of the message: size must be between {min} and {max} */ public static final String CONSTRAINTS_Size_MESSAGE = "{constraints.Size.message}"; /** The key of the message: invalid credit card number */ public static final String CONSTRAINTS_CreditCardNumber_MESSAGE = "{constraints.CreditCardNumber.message}"; /** The key of the message: invalid {type} barcode */ public static final String CONSTRAINTS_EAN_MESSAGE = "{constraints.EAN.message}"; /** The key of the message: not a well-formed email address */ public static final String CONSTRAINTS_Email_MESSAGE = "{constraints.Email.message}"; /** The key of the message: length must be between {min} and {max} */ public static final String CONSTRAINTS_Length_MESSAGE = "{constraints.Length.message}"; /** The key of the message: The check digit for ${value} is invalid, Luhn Modulo 10 checksum failed */ public static final String CONSTRAINTS_LuhnCheck_MESSAGE = "{constraints.LuhnCheck.message}"; /** The key of the message: The check digit for ${value} is invalid, Modulo 10 checksum failed */ public static final String CONSTRAINTS_Mod10Check_MESSAGE = "{constraints.Mod10Check.message}"; /** The key of the message: The check digit for ${value} is invalid, Modulo 11 checksum failed */ public static final String CONSTRAINTS_Mod11Check_MESSAGE = "{constraints.Mod11Check.message}"; /** The key of the message: The check digit for ${value} is invalid, ${modType} checksum failed */ public static final String CONSTRAINTS_ModCheck_MESSAGE = "{constraints.ModCheck.message}"; /** The key of the message: may not be empty */ public static final String CONSTRAINTS_NotBlank_MESSAGE = "{constraints.NotBlank.message}"; /** The key of the message: may not be empty */ public static final String CONSTRAINTS_NotEmpty_MESSAGE = "{constraints.NotEmpty.message}"; /** The key of the message: script expression "{script}" didn't evaluate to true */ public static final String CONSTRAINTS_ParametersScriptAssert_MESSAGE = "{constraints.ParametersScriptAssert.message}"; /** The key of the message: must be between {min} and {max} */ public static final String CONSTRAINTS_Range_MESSAGE = "{constraints.Range.message}"; /** The key of the message: may have unsafe html content */ public static final String CONSTRAINTS_SafeHtml_MESSAGE = "{constraints.SafeHtml.message}"; /** The key of the message: script expression "{script}" didn't evaluate to true */ public static final String CONSTRAINTS_ScriptAssert_MESSAGE = "{constraints.ScriptAssert.message}"; /** The key of the message: must be a valid URL */ public static final String CONSTRAINTS_URL_MESSAGE = "{constraints.URL.message}"; /** The key of the message: is required */ public static final String CONSTRAINTS_Required_MESSAGE = "{constraints.Required.message}"; /** The key of the message: should be {propertyType} */ public static final String CONSTRAINTS_TypeAny_MESSAGE = "{constraints.TypeAny.message}"; /** The key of the message: should be number */ public static final String CONSTRAINTS_TypeInteger_MESSAGE = "{constraints.TypeInteger.message}"; /** The key of the message: should be number */ public static final String CONSTRAINTS_TypeLong_MESSAGE = "{constraints.TypeLong.message}"; /** The key of the message: should be date */ public static final String CONSTRAINTS_TypeLocalDate_MESSAGE = "{constraints.TypeLocalDate.message}"; /** The key of the message: should be date-time */ public static final String CONSTRAINTS_TypeLocalDateTime_MESSAGE = "{constraints.TypeLocalDateTime.message}"; /** The key of the message: should be boolean */ public static final String CONSTRAINTS_TypeBoolean_MESSAGE = "{constraints.TypeBoolean.message}"; /** The key of the message: could not login */ public static final String ERRORS_LOGIN_FAILURE = "{errors.login.failure}"; /** The key of the message: retry because of illegal transition */ public static final String ERRORS_APP_ILLEGAL_TRANSITION = "{errors.app.illegal.transition}"; /** The key of the message: others might be deleted, so retry */ public static final String ERRORS_APP_DB_ALREADY_DELETED = "{errors.app.db.already.deleted}"; /** The key of the message: others might be updated, so retry */ public static final String ERRORS_APP_DB_ALREADY_UPDATED = "{errors.app.db.already.updated}"; /** The key of the message: already existing data, so retry */ public static final String ERRORS_APP_DB_ALREADY_EXISTS = "{errors.app.db.already.exists}"; /** The key of the message: double submit might be requested */ public static final String ERRORS_APP_DOUBLE_SUBMIT_REQUEST = "{errors.app.double.submit.request}"; /** The key of the message: the account already exists so input others */ public static final String ERRORS_SIGNUP_ACCOUNT_ALREADY_EXISTS = "{errors.signup.account.already.exists}"; /** * Add the created action message for the key 'constraints.AssertFalse.message' with parameters. * <pre> * message: must be false * comment: --------------- * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsAssertFalseMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_AssertFalse_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.AssertTrue.message' with parameters. * <pre> * message: must be true * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsAssertTrueMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_AssertTrue_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.DecimalMax.message' with parameters. * <pre> * message: must be less than ${inclusive == true ? 'or equal to ' : ''}{value} * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsDecimalMaxMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_DecimalMax_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.DecimalMin.message' with parameters. * <pre> * message: must be greater than ${inclusive == true ? 'or equal to ' : ''}{value} * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsDecimalMinMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_DecimalMin_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.Digits.message' with parameters. * <pre> * message: numeric value out of bounds (&lt;{integer} digits&gt;.&lt;{fraction} digits&gt; expected) * </pre> * @param property The property name for the message. (NotNull) * @param integer The parameter integer for message. (NotNull) * @param fraction The parameter fraction for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsDigitsMessage(String property, String integer, String fraction) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Digits_MESSAGE, integer, fraction)); return this; } /** * Add the created action message for the key 'constraints.Future.message' with parameters. * <pre> * message: must be in the future * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsFutureMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Future_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Max.message' with parameters. * <pre> * message: must be less than or equal to {value} * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsMaxMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Max_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.Min.message' with parameters. * <pre> * message: must be greater than or equal to {value} * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsMinMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Min_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.NotNull.message' with parameters. * <pre> * message: may not be null * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsNotNullMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_NotNull_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Null.message' with parameters. * <pre> * message: must be null * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsNullMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Null_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Past.message' with parameters. * <pre> * message: must be in the past * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsPastMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Past_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Pattern.message' with parameters. * <pre> * message: invalid format * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsPatternMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Pattern_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Size.message' with parameters. * <pre> * message: size must be between {min} and {max} * </pre> * @param property The property name for the message. (NotNull) * @param min The parameter min for message. (NotNull) * @param max The parameter max for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsSizeMessage(String property, String min, String max) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Size_MESSAGE, min, max)); return this; } /** * Add the created action message for the key 'constraints.CreditCardNumber.message' with parameters. * <pre> * message: invalid credit card number * comment: ------------------- * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsCreditCardNumberMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_CreditCardNumber_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.EAN.message' with parameters. * <pre> * message: invalid {type} barcode * </pre> * @param property The property name for the message. (NotNull) * @param type The parameter type for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsEanMessage(String property, String type) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_EAN_MESSAGE, type)); return this; } /** * Add the created action message for the key 'constraints.Email.message' with parameters. * <pre> * message: not a well-formed email address * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsEmailMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Email_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Length.message' with parameters. * <pre> * message: length must be between {min} and {max} * </pre> * @param property The property name for the message. (NotNull) * @param min The parameter min for message. (NotNull) * @param max The parameter max for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsLengthMessage(String property, String min, String max) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Length_MESSAGE, min, max)); return this; } /** * Add the created action message for the key 'constraints.LuhnCheck.message' with parameters. * <pre> * message: The check digit for ${value} is invalid, Luhn Modulo 10 checksum failed * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsLuhnCheckMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_LuhnCheck_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.Mod10Check.message' with parameters. * <pre> * message: The check digit for ${value} is invalid, Modulo 10 checksum failed * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsMod10CheckMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Mod10Check_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.Mod11Check.message' with parameters. * <pre> * message: The check digit for ${value} is invalid, Modulo 11 checksum failed * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsMod11CheckMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Mod11Check_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.ModCheck.message' with parameters. * <pre> * message: The check digit for ${value} is invalid, ${modType} checksum failed * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @param modType The parameter modType for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsModCheckMessage(String property, String value, String modType) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_ModCheck_MESSAGE, value, modType)); return this; } /** * Add the created action message for the key 'constraints.NotBlank.message' with parameters. * <pre> * message: may not be empty * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsNotBlankMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_NotBlank_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.NotEmpty.message' with parameters. * <pre> * message: may not be empty * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsNotEmptyMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_NotEmpty_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.ParametersScriptAssert.message' with parameters. * <pre> * message: script expression "{script}" didn't evaluate to true * </pre> * @param property The property name for the message. (NotNull) * @param script The parameter script for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsParametersScriptAssertMessage(String property, String script) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_ParametersScriptAssert_MESSAGE, script)); return this; } /** * Add the created action message for the key 'constraints.Range.message' with parameters. * <pre> * message: must be between {min} and {max} * </pre> * @param property The property name for the message. (NotNull) * @param min The parameter min for message. (NotNull) * @param max The parameter max for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsRangeMessage(String property, String min, String max) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Range_MESSAGE, min, max)); return this; } /** * Add the created action message for the key 'constraints.SafeHtml.message' with parameters. * <pre> * message: may have unsafe html content * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsSafeHtmlMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_SafeHtml_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.ScriptAssert.message' with parameters. * <pre> * message: script expression "{script}" didn't evaluate to true * </pre> * @param property The property name for the message. (NotNull) * @param script The parameter script for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsScriptAssertMessage(String property, String script) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_ScriptAssert_MESSAGE, script)); return this; } /** * Add the created action message for the key 'constraints.URL.message' with parameters. * <pre> * message: must be a valid URL * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsUrlMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_URL_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Required.message' with parameters. * <pre> * message: is required * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsRequiredMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Required_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.TypeAny.message' with parameters. * <pre> * message: should be {propertyType} * </pre> * @param property The property name for the message. (NotNull) * @param propertyType The parameter propertyType for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeAnyMessage(String property, String propertyType) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeAny_MESSAGE, propertyType)); return this; } /** * Add the created action message for the key 'constraints.TypeInteger.message' with parameters. * <pre> * message: should be number * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeIntegerMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeInteger_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.TypeLong.message' with parameters. * <pre> * message: should be number * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeLongMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeLong_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.TypeLocalDate.message' with parameters. * <pre> * message: should be date * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeLocalDateMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeLocalDate_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.TypeLocalDateTime.message' with parameters. * <pre> * message: should be date-time * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeLocalDateTimeMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeLocalDateTime_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.TypeBoolean.message' with parameters. * <pre> * message: should be boolean * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeBooleanMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeBoolean_MESSAGE)); return this; } /** * Add the created action message for the key 'errors.login.failure' with parameters. * <pre> * message: could not login * comment: - - - - - - - - - -/ * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsLoginFailure(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_LOGIN_FAILURE)); return this; } /** * Add the created action message for the key 'errors.app.illegal.transition' with parameters. * <pre> * message: retry because of illegal transition * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsAppIllegalTransition(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_APP_ILLEGAL_TRANSITION)); return this; } /** * Add the created action message for the key 'errors.app.db.already.deleted' with parameters. * <pre> * message: others might be deleted, so retry * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsAppDbAlreadyDeleted(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_APP_DB_ALREADY_DELETED)); return this; } /** * Add the created action message for the key 'errors.app.db.already.updated' with parameters. * <pre> * message: others might be updated, so retry * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsAppDbAlreadyUpdated(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_APP_DB_ALREADY_UPDATED)); return this; } /** * Add the created action message for the key 'errors.app.db.already.exists' with parameters. * <pre> * message: already existing data, so retry * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsAppDbAlreadyExists(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_APP_DB_ALREADY_EXISTS)); return this; } /** * Add the created action message for the key 'errors.app.double.submit.request' with parameters. * <pre> * message: double submit might be requested * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsAppDoubleSubmitRequest(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_APP_DOUBLE_SUBMIT_REQUEST)); return this; } /** * Add the created action message for the key 'errors.signup.account.already.exists' with parameters. * <pre> * message: the account already exists so input others * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsSignupAccountAlreadyExists(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_SIGNUP_ACCOUNT_ALREADY_EXISTS)); return this; } }
src/main/java/org/docksidestage/mylasta/action/HarborMessages.java
/* * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.docksidestage.mylasta.action; import org.docksidestage.mylasta.action.HarborLabels; import org.lastaflute.core.message.UserMessage; /** * The keys for message. * @author FreeGen */ public class HarborMessages extends HarborLabels { /** The serial version UID for object serialization. (Default) */ private static final long serialVersionUID = 1L; /** The key of the message: must be false */ public static final String CONSTRAINTS_AssertFalse_MESSAGE = "{constraints.AssertFalse.message}"; /** The key of the message: must be true */ public static final String CONSTRAINTS_AssertTrue_MESSAGE = "{constraints.AssertTrue.message}"; /** The key of the message: must be less than ${inclusive == true ? 'or equal to ' : ''}{value} */ public static final String CONSTRAINTS_DecimalMax_MESSAGE = "{constraints.DecimalMax.message}"; /** The key of the message: must be greater than ${inclusive == true ? 'or equal to ' : ''}{value} */ public static final String CONSTRAINTS_DecimalMin_MESSAGE = "{constraints.DecimalMin.message}"; /** The key of the message: numeric value out of bounds (&lt;{integer} digits&gt;.&lt;{fraction} digits&gt; expected) */ public static final String CONSTRAINTS_Digits_MESSAGE = "{constraints.Digits.message}"; /** The key of the message: must be in the future */ public static final String CONSTRAINTS_Future_MESSAGE = "{constraints.Future.message}"; /** The key of the message: must be less than or equal to {value} */ public static final String CONSTRAINTS_Max_MESSAGE = "{constraints.Max.message}"; /** The key of the message: must be greater than or equal to {value} */ public static final String CONSTRAINTS_Min_MESSAGE = "{constraints.Min.message}"; /** The key of the message: may not be null */ public static final String CONSTRAINTS_NotNull_MESSAGE = "{constraints.NotNull.message}"; /** The key of the message: must be null */ public static final String CONSTRAINTS_Null_MESSAGE = "{constraints.Null.message}"; /** The key of the message: must be in the past */ public static final String CONSTRAINTS_Past_MESSAGE = "{constraints.Past.message}"; /** The key of the message: must match "{regexp}" */ public static final String CONSTRAINTS_Pattern_MESSAGE = "{constraints.Pattern.message}"; /** The key of the message: size must be between {min} and {max} */ public static final String CONSTRAINTS_Size_MESSAGE = "{constraints.Size.message}"; /** The key of the message: invalid credit card number */ public static final String CONSTRAINTS_CreditCardNumber_MESSAGE = "{constraints.CreditCardNumber.message}"; /** The key of the message: invalid {type} barcode */ public static final String CONSTRAINTS_EAN_MESSAGE = "{constraints.EAN.message}"; /** The key of the message: not a well-formed email address */ public static final String CONSTRAINTS_Email_MESSAGE = "{constraints.Email.message}"; /** The key of the message: length must be between {min} and {max} */ public static final String CONSTRAINTS_Length_MESSAGE = "{constraints.Length.message}"; /** The key of the message: The check digit for ${value} is invalid, Luhn Modulo 10 checksum failed */ public static final String CONSTRAINTS_LuhnCheck_MESSAGE = "{constraints.LuhnCheck.message}"; /** The key of the message: The check digit for ${value} is invalid, Modulo 10 checksum failed */ public static final String CONSTRAINTS_Mod10Check_MESSAGE = "{constraints.Mod10Check.message}"; /** The key of the message: The check digit for ${value} is invalid, Modulo 11 checksum failed */ public static final String CONSTRAINTS_Mod11Check_MESSAGE = "{constraints.Mod11Check.message}"; /** The key of the message: The check digit for ${value} is invalid, ${modType} checksum failed */ public static final String CONSTRAINTS_ModCheck_MESSAGE = "{constraints.ModCheck.message}"; /** The key of the message: may not be empty */ public static final String CONSTRAINTS_NotBlank_MESSAGE = "{constraints.NotBlank.message}"; /** The key of the message: may not be empty */ public static final String CONSTRAINTS_NotEmpty_MESSAGE = "{constraints.NotEmpty.message}"; /** The key of the message: script expression "{script}" didn't evaluate to true */ public static final String CONSTRAINTS_ParametersScriptAssert_MESSAGE = "{constraints.ParametersScriptAssert.message}"; /** The key of the message: must be between {min} and {max} */ public static final String CONSTRAINTS_Range_MESSAGE = "{constraints.Range.message}"; /** The key of the message: may have unsafe html content */ public static final String CONSTRAINTS_SafeHtml_MESSAGE = "{constraints.SafeHtml.message}"; /** The key of the message: script expression "{script}" didn't evaluate to true */ public static final String CONSTRAINTS_ScriptAssert_MESSAGE = "{constraints.ScriptAssert.message}"; /** The key of the message: must be a valid URL */ public static final String CONSTRAINTS_URL_MESSAGE = "{constraints.URL.message}"; /** The key of the message: is required */ public static final String CONSTRAINTS_Required_MESSAGE = "{constraints.Required.message}"; /** The key of the message: should be {propertyType} */ public static final String CONSTRAINTS_TypeAny_MESSAGE = "{constraints.TypeAny.message}"; /** The key of the message: should be number */ public static final String CONSTRAINTS_TypeInteger_MESSAGE = "{constraints.TypeInteger.message}"; /** The key of the message: should be number */ public static final String CONSTRAINTS_TypeLong_MESSAGE = "{constraints.TypeLong.message}"; /** The key of the message: should be date */ public static final String CONSTRAINTS_TypeLocalDate_MESSAGE = "{constraints.TypeLocalDate.message}"; /** The key of the message: should be date-time */ public static final String CONSTRAINTS_TypeLocalDateTime_MESSAGE = "{constraints.TypeLocalDateTime.message}"; /** The key of the message: should be boolean */ public static final String CONSTRAINTS_TypeBoolean_MESSAGE = "{constraints.TypeBoolean.message}"; /** The key of the message: could not login */ public static final String ERRORS_LOGIN_FAILURE = "{errors.login.failure}"; /** The key of the message: retry because of illegal transition */ public static final String ERRORS_APP_ILLEGAL_TRANSITION = "{errors.app.illegal.transition}"; /** The key of the message: others might be deleted, so retry */ public static final String ERRORS_APP_DB_ALREADY_DELETED = "{errors.app.db.already.deleted}"; /** The key of the message: others might be updated, so retry */ public static final String ERRORS_APP_DB_ALREADY_UPDATED = "{errors.app.db.already.updated}"; /** The key of the message: already existing data, so retry */ public static final String ERRORS_APP_DB_ALREADY_EXISTS = "{errors.app.db.already.exists}"; /** The key of the message: double submit might be requested */ public static final String ERRORS_APP_DOUBLE_SUBMIT_REQUEST = "{errors.app.double.submit.request}"; /** The key of the message: the account already exists so input others */ public static final String ERRORS_SIGNUP_ACCOUNT_ALREADY_EXISTS = "{errors.signup.account.already.exists}"; /** * Add the created action message for the key 'constraints.AssertFalse.message' with parameters. * <pre> * message: must be false * comment: --------------- * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsAssertFalseMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_AssertFalse_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.AssertTrue.message' with parameters. * <pre> * message: must be true * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsAssertTrueMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_AssertTrue_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.DecimalMax.message' with parameters. * <pre> * message: must be less than ${inclusive == true ? 'or equal to ' : ''}{value} * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsDecimalMaxMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_DecimalMax_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.DecimalMin.message' with parameters. * <pre> * message: must be greater than ${inclusive == true ? 'or equal to ' : ''}{value} * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsDecimalMinMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_DecimalMin_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.Digits.message' with parameters. * <pre> * message: numeric value out of bounds (&lt;{integer} digits&gt;.&lt;{fraction} digits&gt; expected) * </pre> * @param property The property name for the message. (NotNull) * @param integer The parameter integer for message. (NotNull) * @param fraction The parameter fraction for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsDigitsMessage(String property, String integer, String fraction) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Digits_MESSAGE, integer, fraction)); return this; } /** * Add the created action message for the key 'constraints.Future.message' with parameters. * <pre> * message: must be in the future * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsFutureMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Future_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Max.message' with parameters. * <pre> * message: must be less than or equal to {value} * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsMaxMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Max_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.Min.message' with parameters. * <pre> * message: must be greater than or equal to {value} * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsMinMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Min_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.NotNull.message' with parameters. * <pre> * message: may not be null * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsNotNullMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_NotNull_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Null.message' with parameters. * <pre> * message: must be null * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsNullMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Null_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Past.message' with parameters. * <pre> * message: must be in the past * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsPastMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Past_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Pattern.message' with parameters. * <pre> * message: must match "{regexp}" * </pre> * @param property The property name for the message. (NotNull) * @param regexp The parameter regexp for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsPatternMessage(String property, String regexp) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Pattern_MESSAGE, regexp)); return this; } /** * Add the created action message for the key 'constraints.Size.message' with parameters. * <pre> * message: size must be between {min} and {max} * </pre> * @param property The property name for the message. (NotNull) * @param min The parameter min for message. (NotNull) * @param max The parameter max for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsSizeMessage(String property, String min, String max) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Size_MESSAGE, min, max)); return this; } /** * Add the created action message for the key 'constraints.CreditCardNumber.message' with parameters. * <pre> * message: invalid credit card number * comment: ------------------- * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsCreditCardNumberMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_CreditCardNumber_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.EAN.message' with parameters. * <pre> * message: invalid {type} barcode * </pre> * @param property The property name for the message. (NotNull) * @param type The parameter type for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsEanMessage(String property, String type) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_EAN_MESSAGE, type)); return this; } /** * Add the created action message for the key 'constraints.Email.message' with parameters. * <pre> * message: not a well-formed email address * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsEmailMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Email_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Length.message' with parameters. * <pre> * message: length must be between {min} and {max} * </pre> * @param property The property name for the message. (NotNull) * @param min The parameter min for message. (NotNull) * @param max The parameter max for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsLengthMessage(String property, String min, String max) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Length_MESSAGE, min, max)); return this; } /** * Add the created action message for the key 'constraints.LuhnCheck.message' with parameters. * <pre> * message: The check digit for ${value} is invalid, Luhn Modulo 10 checksum failed * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsLuhnCheckMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_LuhnCheck_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.Mod10Check.message' with parameters. * <pre> * message: The check digit for ${value} is invalid, Modulo 10 checksum failed * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsMod10CheckMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Mod10Check_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.Mod11Check.message' with parameters. * <pre> * message: The check digit for ${value} is invalid, Modulo 11 checksum failed * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsMod11CheckMessage(String property, String value) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Mod11Check_MESSAGE, value)); return this; } /** * Add the created action message for the key 'constraints.ModCheck.message' with parameters. * <pre> * message: The check digit for ${value} is invalid, ${modType} checksum failed * </pre> * @param property The property name for the message. (NotNull) * @param value The parameter value for message. (NotNull) * @param modType The parameter modType for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsModCheckMessage(String property, String value, String modType) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_ModCheck_MESSAGE, value, modType)); return this; } /** * Add the created action message for the key 'constraints.NotBlank.message' with parameters. * <pre> * message: may not be empty * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsNotBlankMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_NotBlank_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.NotEmpty.message' with parameters. * <pre> * message: may not be empty * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsNotEmptyMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_NotEmpty_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.ParametersScriptAssert.message' with parameters. * <pre> * message: script expression "{script}" didn't evaluate to true * </pre> * @param property The property name for the message. (NotNull) * @param script The parameter script for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsParametersScriptAssertMessage(String property, String script) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_ParametersScriptAssert_MESSAGE, script)); return this; } /** * Add the created action message for the key 'constraints.Range.message' with parameters. * <pre> * message: must be between {min} and {max} * </pre> * @param property The property name for the message. (NotNull) * @param min The parameter min for message. (NotNull) * @param max The parameter max for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsRangeMessage(String property, String min, String max) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Range_MESSAGE, min, max)); return this; } /** * Add the created action message for the key 'constraints.SafeHtml.message' with parameters. * <pre> * message: may have unsafe html content * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsSafeHtmlMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_SafeHtml_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.ScriptAssert.message' with parameters. * <pre> * message: script expression "{script}" didn't evaluate to true * </pre> * @param property The property name for the message. (NotNull) * @param script The parameter script for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsScriptAssertMessage(String property, String script) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_ScriptAssert_MESSAGE, script)); return this; } /** * Add the created action message for the key 'constraints.URL.message' with parameters. * <pre> * message: must be a valid URL * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsUrlMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_URL_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.Required.message' with parameters. * <pre> * message: is required * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsRequiredMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Required_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.TypeAny.message' with parameters. * <pre> * message: should be {propertyType} * </pre> * @param property The property name for the message. (NotNull) * @param propertyType The parameter propertyType for message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeAnyMessage(String property, String propertyType) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeAny_MESSAGE, propertyType)); return this; } /** * Add the created action message for the key 'constraints.TypeInteger.message' with parameters. * <pre> * message: should be number * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeIntegerMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeInteger_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.TypeLong.message' with parameters. * <pre> * message: should be number * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeLongMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeLong_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.TypeLocalDate.message' with parameters. * <pre> * message: should be date * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeLocalDateMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeLocalDate_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.TypeLocalDateTime.message' with parameters. * <pre> * message: should be date-time * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeLocalDateTimeMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeLocalDateTime_MESSAGE)); return this; } /** * Add the created action message for the key 'constraints.TypeBoolean.message' with parameters. * <pre> * message: should be boolean * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addConstraintsTypeBooleanMessage(String property) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_TypeBoolean_MESSAGE)); return this; } /** * Add the created action message for the key 'errors.login.failure' with parameters. * <pre> * message: could not login * comment: - - - - - - - - - -/ * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsLoginFailure(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_LOGIN_FAILURE)); return this; } /** * Add the created action message for the key 'errors.app.illegal.transition' with parameters. * <pre> * message: retry because of illegal transition * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsAppIllegalTransition(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_APP_ILLEGAL_TRANSITION)); return this; } /** * Add the created action message for the key 'errors.app.db.already.deleted' with parameters. * <pre> * message: others might be deleted, so retry * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsAppDbAlreadyDeleted(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_APP_DB_ALREADY_DELETED)); return this; } /** * Add the created action message for the key 'errors.app.db.already.updated' with parameters. * <pre> * message: others might be updated, so retry * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsAppDbAlreadyUpdated(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_APP_DB_ALREADY_UPDATED)); return this; } /** * Add the created action message for the key 'errors.app.db.already.exists' with parameters. * <pre> * message: already existing data, so retry * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsAppDbAlreadyExists(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_APP_DB_ALREADY_EXISTS)); return this; } /** * Add the created action message for the key 'errors.app.double.submit.request' with parameters. * <pre> * message: double submit might be requested * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsAppDoubleSubmitRequest(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_APP_DOUBLE_SUBMIT_REQUEST)); return this; } /** * Add the created action message for the key 'errors.signup.account.already.exists' with parameters. * <pre> * message: the account already exists so input others * </pre> * @param property The property name for the message. (NotNull) * @return this. (NotNull) */ public HarborMessages addErrorsSignupAccountAlreadyExists(String property) { assertPropertyNotNull(property); add(property, new UserMessage(ERRORS_SIGNUP_ACCOUNT_ALREADY_EXISTS)); return this; } }
constraints.Pattern.message = invalid format
src/main/java/org/docksidestage/mylasta/action/HarborMessages.java
constraints.Pattern.message = invalid format
<ide><path>rc/main/java/org/docksidestage/mylasta/action/HarborMessages.java <ide> /** The key of the message: must be in the past */ <ide> public static final String CONSTRAINTS_Past_MESSAGE = "{constraints.Past.message}"; <ide> <del> /** The key of the message: must match "{regexp}" */ <add> /** The key of the message: invalid format */ <ide> public static final String CONSTRAINTS_Pattern_MESSAGE = "{constraints.Pattern.message}"; <ide> <ide> /** The key of the message: size must be between {min} and {max} */ <ide> /** <ide> * Add the created action message for the key 'constraints.Pattern.message' with parameters. <ide> * <pre> <del> * message: must match "{regexp}" <del> * </pre> <del> * @param property The property name for the message. (NotNull) <del> * @param regexp The parameter regexp for message. (NotNull) <del> * @return this. (NotNull) <del> */ <del> public HarborMessages addConstraintsPatternMessage(String property, String regexp) { <del> assertPropertyNotNull(property); <del> add(property, new UserMessage(CONSTRAINTS_Pattern_MESSAGE, regexp)); <add> * message: invalid format <add> * </pre> <add> * @param property The property name for the message. (NotNull) <add> * @return this. (NotNull) <add> */ <add> public HarborMessages addConstraintsPatternMessage(String property) { <add> assertPropertyNotNull(property); <add> add(property, new UserMessage(CONSTRAINTS_Pattern_MESSAGE)); <ide> return this; <ide> } <ide>
Java
agpl-3.0
741059e4ca81873561ce834d5b5101bbdc067f05
0
lolski/grakn,graknlabs/grakn,graknlabs/grakn,lolski/grakn,lolski/grakn,graknlabs/grakn,graknlabs/grakn,lolski/grakn
/* * Copyright (C) 2020 Grakn Labs * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ package grakn.core.query; import grakn.core.common.exception.GraknException; import grakn.core.common.iterator.ResourceIterator; import grakn.core.common.parameters.Options; import grakn.core.concept.answer.ConceptMap; import grakn.core.concept.answer.ConceptMapGroup; import grakn.core.concept.answer.Numeric; import grakn.core.concept.answer.NumericGroup; import grakn.core.concept.thing.Attribute; import grakn.core.pattern.Disjunction; import grakn.core.reasoner.Reasoner; import graql.lang.common.GraqlArg; import graql.lang.common.GraqlToken; import graql.lang.pattern.variable.Reference; import graql.lang.pattern.variable.UnboundVariable; import graql.lang.query.GraqlMatch; import graql.lang.query.builder.Sortable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import static grakn.common.collection.Collections.set; import static grakn.core.common.exception.ErrorMessage.Internal.ILLEGAL_OPERATION; import static grakn.core.common.exception.ErrorMessage.Internal.ILLEGAL_STATE; import static grakn.core.common.exception.ErrorMessage.Internal.UNRECOGNISED_VALUE; import static grakn.core.common.exception.ErrorMessage.ThingRead.AGGREGATE_ATTRIBUTE_NOT_NUMBER; import static grakn.core.common.exception.ErrorMessage.ThingRead.INVALID_THING_CASTING; import static grakn.core.common.exception.ErrorMessage.ThingRead.SORT_ATTRIBUTE_NOT_COMPARABLE; import static grakn.core.common.exception.ErrorMessage.ThingRead.SORT_VARIABLE_NOT_ATTRIBUTE; import static grakn.core.common.iterator.Iterators.iterate; import static grakn.core.query.Matcher.Aggregator.aggregator; import static java.lang.Math.sqrt; import static java.util.stream.Collectors.groupingBy; public class Matcher { private final Reasoner reasoner; private final GraqlMatch query; private final Disjunction disjunction; private final Options.Query options; public Matcher(Reasoner reasoner, GraqlMatch query, Options.Query options) { this.reasoner = reasoner; this.query = query; this.disjunction = Disjunction.create(query.conjunction().normalise()); this.options = options; } public static Matcher create(Reasoner reasoner, GraqlMatch query, Options.Query options) { return new Matcher(reasoner, query, options); } public static Matcher.Aggregator create(Reasoner reasoner, GraqlMatch.Aggregate query, Options.Query options) { Matcher matcher = new Matcher(reasoner, query.query(), options); return new Aggregator(matcher, query); } public static Matcher.Group create(Reasoner reasoner, GraqlMatch.Group query, Options.Query options) { Matcher matcher = new Matcher(reasoner, query.query(), options); return new Group(matcher, query); } public static Matcher.Group.Aggregator create(Reasoner reasoner, GraqlMatch.Group.Aggregate query, Options.Query options) { Matcher matcher = new Matcher(reasoner, query.group().query(), options); Group group = new Group(matcher, query.group()); return new Group.Aggregator(group, query); } public ResourceIterator<ConceptMap> execute(boolean isParallel) { return filter(reasoner.execute(disjunction, isParallel)); } private ResourceIterator<ConceptMap> filter(ResourceIterator<ConceptMap> answers) { if (!query.filter().isEmpty()) { Set<Reference.Name> vars = iterate(query.filter()).map(f -> f.reference().asName()).toSet(); answers = answers.map(a -> a.filter(vars)).distinct(); } if (query.sort().isPresent()) answers = sort(answers, query.sort().get()); if (query.offset().isPresent()) answers = answers.offset(query.offset().get()); if (query.limit().isPresent()) answers = answers.limit(query.limit().get()); return answers; } private ResourceIterator<ConceptMap> sort(ResourceIterator<ConceptMap> answers, Sortable.Sorting sorting) { // TODO: Replace this temporary implementation of Graql Match Sort query with a native sorting traversal Reference.Name var = sorting.var().reference().asName(); Comparator<ConceptMap> comparator = (answer1, answer2) -> { Attribute att1, att2; try { att1 = answer1.get(var).asAttribute(); att2 = answer2.get(var).asAttribute(); } catch (GraknException e) { if (e.code().isPresent() || e.code().get().equals(INVALID_THING_CASTING.code())) { throw GraknException.of(SORT_VARIABLE_NOT_ATTRIBUTE, var); } else { throw e; } } if (!att1.getType().getValueType().comparables().contains(att2.getType().getValueType())) { throw GraknException.of(SORT_ATTRIBUTE_NOT_COMPARABLE, var); } if (att1.isString()) { return att1.asString().getValue().compareToIgnoreCase(att2.asString().getValue()); } else if (att1.isBoolean()) { return att1.asBoolean().getValue().compareTo(att2.asBoolean().getValue()); } else if (att1.isLong() && att2.isLong()) { return att1.asLong().getValue().compareTo(att2.asLong().getValue()); } else if (att1.isDouble() || att2.isDouble()) { Double double1 = att1.isLong() ? att1.asLong().getValue() : att1.asDouble().getValue(); Double double2 = att2.isLong() ? att2.asLong().getValue() : att2.asDouble().getValue(); return double1.compareTo(double2); } else if (att1.isDateTime()) { return (att1.asDateTime().getValue()).compareTo(att2.asDateTime().getValue()); } else { throw GraknException.of(ILLEGAL_STATE); } }; comparator = (sorting.order() == GraqlArg.Order.DESC) ? comparator.reversed() : comparator; return iterate(answers.stream().sorted(comparator).iterator()); } public static class Aggregator { private final Matcher matcher; private final GraqlMatch.Aggregate query; public Aggregator(Matcher matcher, GraqlMatch.Aggregate query) { this.matcher = matcher; this.query = query; } public Numeric execute(boolean isParallel) { ResourceIterator<ConceptMap> answers = matcher.execute(isParallel); GraqlToken.Aggregate.Method method = query.method(); UnboundVariable var = query.var(); return aggregate(answers, method, var); } static Numeric aggregate(ResourceIterator<ConceptMap> answers, GraqlToken.Aggregate.Method method, UnboundVariable var) { return answers.stream().collect(aggregator(method, var)); } static Collector<ConceptMap, ?, Numeric> aggregator(GraqlToken.Aggregate.Method method, UnboundVariable var) { Collector<ConceptMap, ?, Numeric> aggregator; switch (method) { case COUNT: aggregator = count(); break; case MAX: aggregator = max(var); break; case MEAN: aggregator = mean(var); break; case MEDIAN: aggregator = median(var); break; case MIN: aggregator = min(var); break; case STD: aggregator = std(var); break; case SUM: aggregator = sum(var); break; default: throw GraknException.of(UNRECOGNISED_VALUE); } return aggregator; } static Collector<ConceptMap, ?, Numeric> count() { return new Collector<ConceptMap, Accumulator<Long>, Numeric>() { @Override public Supplier<Accumulator<Long>> supplier() { return () -> new Accumulator<>(0L, Long::sum); } @Override public BiConsumer<Accumulator<Long>, ConceptMap> accumulator() { return (sum, answer) -> sum.accept(1L); } @Override public BinaryOperator<Accumulator<Long>> combiner() { return (sum1, sum2) -> { sum1.accept(sum2.value); return sum1; }; } @Override public Function<Accumulator<Long>, Numeric> finisher() { return sum -> Numeric.ofLong(sum.value); } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> max(UnboundVariable var) { return new Collector<ConceptMap, OptionalAccumulator<Numeric>, Numeric>() { @Override public Supplier<OptionalAccumulator<Numeric>> supplier() { return () -> new OptionalAccumulator<>(BinaryOperator.maxBy(NumericComparator.natural())); } @Override public BiConsumer<OptionalAccumulator<Numeric>, ConceptMap> accumulator() { return (max, answer) -> max.accept(numeric(answer, var)); } @Override public BinaryOperator<OptionalAccumulator<Numeric>> combiner() { return (max1, max2) -> { if (max2.present) max1.accept(max2.value); return max1; }; } @Override public Function<OptionalAccumulator<Numeric>, Numeric> finisher() { return max -> { if (max.present) return max.value; else return Numeric.ofNaN(); }; } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> mean(UnboundVariable var) { return new Collector<ConceptMap, Double[], Numeric>() { @Override public Supplier<Double[]> supplier() { return () -> new Double[]{0.0, 0.0}; } @Override public BiConsumer<Double[], ConceptMap> accumulator() { return (acc, answer) -> { acc[0] += numeric(answer, var).asNumber().doubleValue(); acc[1]++; }; } @Override public BinaryOperator<Double[]> combiner() { return (acc1, acc2) -> { acc1[0] += acc2[0]; acc1[1] += acc2[1]; return acc1; }; } @Override public Function<Double[], Numeric> finisher() { return acc -> { if (acc[1] == 0) return Numeric.ofNaN(); else return Numeric.ofDouble(acc[0] / acc[1]); }; } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> median(UnboundVariable var) { return new Collector<ConceptMap, MedianCalculator, Numeric>() { @Override public Supplier<MedianCalculator> supplier() { return MedianCalculator::new; } @Override public BiConsumer<MedianCalculator, ConceptMap> accumulator() { return (medianFinder, answer) -> medianFinder.accumulate(numeric(answer, var)); } @Override public BinaryOperator<MedianCalculator> combiner() { return (t, u) -> { throw GraknException.of(ILLEGAL_OPERATION); }; } @Override public Function<MedianCalculator, Numeric> finisher() { return MedianCalculator::median; } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> min(UnboundVariable var) { return new Collector<ConceptMap, OptionalAccumulator<Numeric>, Numeric>() { @Override public Supplier<OptionalAccumulator<Numeric>> supplier() { return () -> new OptionalAccumulator<>(BinaryOperator.minBy(NumericComparator.natural())); } @Override public BiConsumer<OptionalAccumulator<Numeric>, ConceptMap> accumulator() { return (min, answer) -> min.accept(numeric(answer, var)); } @Override public BinaryOperator<OptionalAccumulator<Numeric>> combiner() { return (min1, min2) -> { if (min2.present) min1.accept(min2.value); return min1; }; } @Override public Function<OptionalAccumulator<Numeric>, Numeric> finisher() { return min -> { if (min.present) return min.value; else return Numeric.ofNaN(); }; } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> std(UnboundVariable var) { return new Collector<ConceptMap, STDCalculator, Numeric>() { @Override public Supplier<STDCalculator> supplier() { return STDCalculator::new; } @Override public BiConsumer<STDCalculator, ConceptMap> accumulator() { return (acc, answer) -> acc.accumulate(numeric(answer, var).asNumber().doubleValue()); } @Override public BinaryOperator<STDCalculator> combiner() { return (t, u) -> { throw GraknException.of(ILLEGAL_OPERATION); }; } @Override public Function<STDCalculator, Numeric> finisher() { return STDCalculator::std; } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> sum(UnboundVariable var) { return new Collector<ConceptMap, OptionalAccumulator<Numeric>, Numeric>() { @Override public Supplier<OptionalAccumulator<Numeric>> supplier() { return () -> new OptionalAccumulator<>(Aggregator::sum); } @Override public BiConsumer<OptionalAccumulator<Numeric>, ConceptMap> accumulator() { return (sum, answer) -> sum.accept(numeric(answer, var)); } @Override public BinaryOperator<OptionalAccumulator<Numeric>> combiner() { return (sum1, sum2) -> { if (sum2.present) sum1.accept(sum2.value); return sum1; }; } @Override public Function<OptionalAccumulator<Numeric>, Numeric> finisher() { return sum -> { if (sum.present) return sum.value; else return Numeric.ofNaN(); }; } @Override public Set<Characteristics> characteristics() { return set(); } }; } private static Numeric numeric(ConceptMap answer, UnboundVariable var) { Attribute attribute = answer.get(var).asAttribute(); if (attribute.isLong()) return Numeric.ofLong(attribute.asLong().getValue()); else if (attribute.isDouble()) return Numeric.ofDouble(attribute.asDouble().getValue()); else throw GraknException.of(AGGREGATE_ATTRIBUTE_NOT_NUMBER, var); } private static Numeric sum(Numeric x, Numeric y) { // This method is necessary because Number doesn't support '+' because java! if (x.isLong() && y.isLong()) return Numeric.ofLong(x.asLong() + y.asLong()); else if (x.isLong()) return Numeric.ofDouble(x.asLong() + y.asDouble()); else if (y.isLong()) return Numeric.ofDouble(x.asDouble() + y.asLong()); else return Numeric.ofDouble(x.asDouble() + y.asDouble()); } private static class MedianCalculator { PriorityQueue<Numeric> maxHeap; //lower half PriorityQueue<Numeric> minHeap; //higher half MedianCalculator() { maxHeap = new PriorityQueue<>(Collections.reverseOrder()); minHeap = new PriorityQueue<>(); } void accumulate(Numeric numeric) { maxHeap.offer(numeric); minHeap.offer(maxHeap.poll()); if (maxHeap.size() < minHeap.size()) { maxHeap.offer(minHeap.poll()); } } Numeric median() { if (maxHeap.isEmpty() && minHeap.isEmpty()) { return Numeric.ofNaN(); } else if (maxHeap.size() == minHeap.size()) { return Numeric.ofDouble(sum(maxHeap.peek(), minHeap.peek()).asNumber().doubleValue() / 2); } else if (maxHeap.peek() == null) { return Numeric.ofNaN(); } else { return maxHeap.peek(); } } } /** * Online algorithm to calculate unbiased sample standard deviation * https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm * // TODO: We may find a faster algorithm that does not cost so much as the division in the loop */ private static class STDCalculator { long n = 0; double mean = 0d, M2 = 0d; void accumulate(double value) { n += 1; double delta = value - mean; mean += delta / (double) n; double delta2 = value - mean; M2 += delta * delta2; } Numeric std() { if (n < 2) return Numeric.ofNaN(); else return Numeric.ofDouble(sqrt(M2 / (double) (n - 1))); } } private static class NumericComparator implements Comparator<Numeric> { static NumericComparator natural = new NumericComparator(); public static Comparator<Numeric> natural() { return natural; } @Override public int compare(Numeric a, Numeric b) { return Double.compare(a.asNumber().doubleValue(), b.asNumber().doubleValue()); } } private static class Accumulator<T> implements Consumer<T> { T value; private BinaryOperator<T> op; Accumulator(T init, BinaryOperator<T> op) { value = init; this.op = op; } @Override public void accept(T t) { value = op.apply(value, t); } } private static class OptionalAccumulator<T> implements Consumer<T> { T value = null; boolean present = false; private BinaryOperator<T> op; OptionalAccumulator(BinaryOperator<T> op) { this.op = op; } @Override public void accept(T t) { if (present) { value = op.apply(value, t); } else { value = t; present = true; } } } } public static class Group { private final Matcher matcher; private final GraqlMatch.Group query; public Group(Matcher matcher, GraqlMatch.Group query) { this.matcher = matcher; this.query = query; } public ResourceIterator<ConceptMapGroup> execute(boolean isParallel) { // TODO: Replace this temporary implementation of Graql Match Group query with a native grouping traversal List<ConceptMapGroup> answerGroups = new ArrayList<>(); matcher.execute(isParallel).stream().collect(groupingBy(a -> a.get(query.var()))) .forEach((o, cm) -> answerGroups.add(new ConceptMapGroup(o, cm))); return iterate(answerGroups); } public static class Aggregator { private final Group group; private final GraqlMatch.Group.Aggregate query; public Aggregator(Group group, GraqlMatch.Group.Aggregate query) { this.group = group; this.query = query; } public ResourceIterator<NumericGroup> execute(boolean isParallel) { // TODO: Replace this temporary implementation of Graql Match Group query with a native grouping traversal List<NumericGroup> numericGroups = new ArrayList<>(); group.matcher.execute(isParallel).stream() .collect(groupingBy(a -> a.get(query.group().var()), aggregator(query.method(), query.var()))) .forEach((o, n) -> numericGroups.add(new NumericGroup(o, n))); return iterate(numericGroups); } } } }
query/Matcher.java
/* * Copyright (C) 2020 Grakn Labs * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ package grakn.core.query; import grakn.core.common.exception.GraknException; import grakn.core.common.iterator.ResourceIterator; import grakn.core.common.parameters.Options; import grakn.core.concept.answer.ConceptMap; import grakn.core.concept.answer.ConceptMapGroup; import grakn.core.concept.answer.Numeric; import grakn.core.concept.answer.NumericGroup; import grakn.core.concept.thing.Attribute; import grakn.core.pattern.Disjunction; import grakn.core.reasoner.Reasoner; import graql.lang.common.GraqlArg; import graql.lang.common.GraqlToken; import graql.lang.pattern.variable.Reference; import graql.lang.pattern.variable.UnboundVariable; import graql.lang.query.GraqlMatch; import graql.lang.query.builder.Sortable; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import static grakn.common.collection.Collections.set; import static grakn.core.common.exception.ErrorMessage.Internal.ILLEGAL_OPERATION; import static grakn.core.common.exception.ErrorMessage.Internal.ILLEGAL_STATE; import static grakn.core.common.exception.ErrorMessage.Internal.UNRECOGNISED_VALUE; import static grakn.core.common.exception.ErrorMessage.ThingRead.AGGREGATE_ATTRIBUTE_NOT_NUMBER; import static grakn.core.common.exception.ErrorMessage.ThingRead.INVALID_THING_CASTING; import static grakn.core.common.exception.ErrorMessage.ThingRead.SORT_ATTRIBUTE_NOT_COMPARABLE; import static grakn.core.common.exception.ErrorMessage.ThingRead.SORT_VARIABLE_NOT_ATTRIBUTE; import static grakn.core.common.iterator.Iterators.iterate; import static grakn.core.query.Matcher.Aggregator.aggregator; import static java.lang.Math.sqrt; import static java.util.stream.Collectors.groupingBy; public class Matcher { private final Reasoner reasoner; private final GraqlMatch query; private final Disjunction disjunction; private final Options.Query options; public Matcher(Reasoner reasoner, GraqlMatch query, Options.Query options) { this.reasoner = reasoner; this.query = query; this.disjunction = Disjunction.create(query.conjunction().normalise()); this.options = options; } public static Matcher create(Reasoner reasoner, GraqlMatch query, Options.Query options) { return new Matcher(reasoner, query, options); } public static Matcher.Aggregator create(Reasoner reasoner, GraqlMatch.Aggregate query, Options.Query options) { Matcher matcher = new Matcher(reasoner, query.query(), options); return new Aggregator(matcher, query); } public static Matcher.Group create(Reasoner reasoner, GraqlMatch.Group query, Options.Query options) { Matcher matcher = new Matcher(reasoner, query.query(), options); return new Group(matcher, query); } public static Matcher.Group.Aggregator create(Reasoner reasoner, GraqlMatch.Group.Aggregate query, Options.Query options) { Matcher matcher = new Matcher(reasoner, query.group().query(), options); Group group = new Group(matcher, query.group()); return new Group.Aggregator(group, query); } public ResourceIterator<ConceptMap> execute(boolean isParallel) { return filter(reasoner.execute(disjunction, isParallel)); } private ResourceIterator<ConceptMap> filter(ResourceIterator<ConceptMap> answers) { if (!query.filter().isEmpty()) { Set<Reference.Name> vars = iterate(query.filter()).map(f -> f.reference().asName()).toSet(); answers = answers.map(a -> a.filter(vars)).distinct(); } if (query.sort().isPresent()) answers = sort(answers, query.sort().get()); if (query.offset().isPresent()) answers = answers.offset(query.offset().get()); if (query.limit().isPresent()) answers = answers.limit(query.limit().get()); return answers; } private ResourceIterator<ConceptMap> sort(ResourceIterator<ConceptMap> answers, Sortable.Sorting sorting) { // TODO: Replace this temporary implementation of Graql Match Sort query with a native sorting traversal Reference.Name var = sorting.var().reference().asName(); Comparator<ConceptMap> comparator = (answer1, answer2) -> { Attribute att1, att2; try { att1 = answer1.get(var).asAttribute(); att2 = answer2.get(var).asAttribute(); } catch (GraknException e) { if (e.code().isPresent() || e.code().get().equals(INVALID_THING_CASTING.code())) { throw GraknException.of(SORT_VARIABLE_NOT_ATTRIBUTE, var); } else { throw e; } } if (!att1.getType().getValueType().comparables().contains(att2.getType().getValueType())) { throw GraknException.of(SORT_ATTRIBUTE_NOT_COMPARABLE, var); } if (att1.isString()) { return att1.asString().getValue().compareToIgnoreCase(att2.asString().getValue()); } else if (att1.isBoolean()) { return att1.asBoolean().getValue().compareTo(att2.asBoolean().getValue()); } else if (att1.isLong() && att2.isLong()) { return att1.asLong().getValue().compareTo(att2.asLong().getValue()); } else if (att1.isDouble() || att2.isDouble()) { Double double1 = att1.isLong() ? att1.asLong().getValue() : att1.asDouble().getValue(); Double double2 = att2.isLong() ? att2.asLong().getValue() : att2.asDouble().getValue(); return double1.compareTo(double2); } else if (att1.isDateTime()) { return (att1.asDateTime().getValue()).compareTo(att2.asDateTime().getValue()); } else { throw GraknException.of(ILLEGAL_STATE); } }; comparator = (sorting.order() == GraqlArg.Order.DESC) ? comparator.reversed() : comparator; return iterate(answers.stream().sorted(comparator).iterator()); } public static class Aggregator { private final Matcher matcher; private final GraqlMatch.Aggregate query; public Aggregator(Matcher matcher, GraqlMatch.Aggregate query) { this.matcher = matcher; this.query = query; } public Numeric execute(boolean isParallel) { ResourceIterator<ConceptMap> answers = matcher.execute(isParallel); GraqlToken.Aggregate.Method method = query.method(); UnboundVariable var = query.var(); return aggregate(answers, method, var); } static Numeric aggregate(ResourceIterator<ConceptMap> answers, GraqlToken.Aggregate.Method method, UnboundVariable var) { return answers.stream().collect(aggregator(method, var)); } static Collector<ConceptMap, ?, Numeric> aggregator(GraqlToken.Aggregate.Method method, UnboundVariable var) { Collector<ConceptMap, ?, Numeric> aggregator; switch (method) { case COUNT: aggregator = count(); break; case MAX: aggregator = max(var); break; case MEAN: aggregator = mean(var); break; case MEDIAN: aggregator = median(var); break; case MIN: aggregator = min(var); break; case STD: aggregator = std(var); break; case SUM: aggregator = sum(var); break; default: throw GraknException.of(UNRECOGNISED_VALUE); } return aggregator; } static Collector<ConceptMap, ?, Numeric> count() { return new Collector<ConceptMap, OptionalAccumulator<Long>, Numeric>() { @Override public Supplier<OptionalAccumulator<Long>> supplier() { return () -> new OptionalAccumulator<>(Long::sum); } @Override public BiConsumer<OptionalAccumulator<Long>, ConceptMap> accumulator() { return (sum, answer) -> sum.accept(1L); } @Override public BinaryOperator<OptionalAccumulator<Long>> combiner() { return (sum1, sum2) -> { if (sum2.present) sum1.accept(sum2.value); return sum1; }; } @Override public Function<OptionalAccumulator<Long>, Numeric> finisher() { return sum -> { if (sum.present) return Numeric.ofLong(sum.value); else return Numeric.ofLong(0); }; } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> max(UnboundVariable var) { return new Collector<ConceptMap, OptionalAccumulator<Numeric>, Numeric>() { @Override public Supplier<OptionalAccumulator<Numeric>> supplier() { return () -> new OptionalAccumulator<>(BinaryOperator.maxBy(NumericComparator.natural())); } @Override public BiConsumer<OptionalAccumulator<Numeric>, ConceptMap> accumulator() { return (max, answer) -> max.accept(numeric(answer, var)); } @Override public BinaryOperator<OptionalAccumulator<Numeric>> combiner() { return (max1, max2) -> { if (max2.present) max1.accept(max2.value); return max1; }; } @Override public Function<OptionalAccumulator<Numeric>, Numeric> finisher() { return max -> { if (max.present) return max.value; else return Numeric.ofNaN(); }; } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> mean(UnboundVariable var) { return new Collector<ConceptMap, Double[], Numeric>() { @Override public Supplier<Double[]> supplier() { return () -> new Double[]{0.0, 0.0}; } @Override public BiConsumer<Double[], ConceptMap> accumulator() { return (acc, answer) -> { acc[0] += numeric(answer, var).asNumber().doubleValue(); acc[1]++; }; } @Override public BinaryOperator<Double[]> combiner() { return (acc1, acc2) -> { acc1[0] += acc2[0]; acc1[1] += acc2[1]; return acc1; }; } @Override public Function<Double[], Numeric> finisher() { return acc -> { if (acc[1] == 0) return Numeric.ofNaN(); else return Numeric.ofDouble(acc[0] / acc[1]); }; } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> median(UnboundVariable var) { return new Collector<ConceptMap, MedianCalculator, Numeric>() { @Override public Supplier<MedianCalculator> supplier() { return MedianCalculator::new; } @Override public BiConsumer<MedianCalculator, ConceptMap> accumulator() { return (medianFinder, answer) -> medianFinder.accumulate(numeric(answer, var)); } @Override public BinaryOperator<MedianCalculator> combiner() { return (t, u) -> { throw GraknException.of(ILLEGAL_OPERATION); }; } @Override public Function<MedianCalculator, Numeric> finisher() { return MedianCalculator::median; } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> min(UnboundVariable var) { return new Collector<ConceptMap, OptionalAccumulator<Numeric>, Numeric>() { @Override public Supplier<OptionalAccumulator<Numeric>> supplier() { return () -> new OptionalAccumulator<>(BinaryOperator.minBy(NumericComparator.natural())); } @Override public BiConsumer<OptionalAccumulator<Numeric>, ConceptMap> accumulator() { return (min, answer) -> min.accept(numeric(answer, var)); } @Override public BinaryOperator<OptionalAccumulator<Numeric>> combiner() { return (min1, min2) -> { if (min2.present) min1.accept(min2.value); return min1; }; } @Override public Function<OptionalAccumulator<Numeric>, Numeric> finisher() { return min -> { if (min.present) return min.value; else return Numeric.ofNaN(); }; } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> std(UnboundVariable var) { return new Collector<ConceptMap, STDCalculator, Numeric>() { @Override public Supplier<STDCalculator> supplier() { return STDCalculator::new; } @Override public BiConsumer<STDCalculator, ConceptMap> accumulator() { return (acc, answer) -> acc.accumulate(numeric(answer, var).asNumber().doubleValue()); } @Override public BinaryOperator<STDCalculator> combiner() { return (t, u) -> { throw GraknException.of(ILLEGAL_OPERATION); }; } @Override public Function<STDCalculator, Numeric> finisher() { return STDCalculator::std; } @Override public Set<Characteristics> characteristics() { return set(); } }; } static Collector<ConceptMap, ?, Numeric> sum(UnboundVariable var) { return new Collector<ConceptMap, OptionalAccumulator<Numeric>, Numeric>() { @Override public Supplier<OptionalAccumulator<Numeric>> supplier() { return () -> new OptionalAccumulator<>(Aggregator::sum); } @Override public BiConsumer<OptionalAccumulator<Numeric>, ConceptMap> accumulator() { return (sum, answer) -> sum.accept(numeric(answer, var)); } @Override public BinaryOperator<OptionalAccumulator<Numeric>> combiner() { return (sum1, sum2) -> { if (sum2.present) sum1.accept(sum2.value); return sum1; }; } @Override public Function<OptionalAccumulator<Numeric>, Numeric> finisher() { return sum -> { if (sum.present) return sum.value; else return Numeric.ofNaN(); }; } @Override public Set<Characteristics> characteristics() { return set(); } }; } private static Numeric numeric(ConceptMap answer, UnboundVariable var) { Attribute attribute = answer.get(var).asAttribute(); if (attribute.isLong()) return Numeric.ofLong(attribute.asLong().getValue()); else if (attribute.isDouble()) return Numeric.ofDouble(attribute.asDouble().getValue()); else throw GraknException.of(AGGREGATE_ATTRIBUTE_NOT_NUMBER, var); } private static Numeric sum(Numeric x, Numeric y) { // This method is necessary because Number doesn't support '+' because java! if (x.isLong() && y.isLong()) return Numeric.ofLong(x.asLong() + y.asLong()); else if (x.isLong()) return Numeric.ofDouble(x.asLong() + y.asDouble()); else if (y.isLong()) return Numeric.ofDouble(x.asDouble() + y.asLong()); else return Numeric.ofDouble(x.asDouble() + y.asDouble()); } private static class MedianCalculator { PriorityQueue<Numeric> maxHeap; //lower half PriorityQueue<Numeric> minHeap; //higher half MedianCalculator() { maxHeap = new PriorityQueue<>(Collections.reverseOrder()); minHeap = new PriorityQueue<>(); } void accumulate(Numeric numeric) { maxHeap.offer(numeric); minHeap.offer(maxHeap.poll()); if (maxHeap.size() < minHeap.size()) { maxHeap.offer(minHeap.poll()); } } Numeric median() { if (maxHeap.isEmpty() && minHeap.isEmpty()) { return Numeric.ofNaN(); } else if (maxHeap.size() == minHeap.size()) { return Numeric.ofDouble(sum(maxHeap.peek(), minHeap.peek()).asNumber().doubleValue() / 2); } else if (maxHeap.peek() == null) { return Numeric.ofNaN(); } else { return maxHeap.peek(); } } } /** * Online algorithm to calculate unbiased sample standard deviation * https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm * // TODO: We may find a faster algorithm that does not cost so much as the division in the loop */ private static class STDCalculator { long n = 0; double mean = 0d, M2 = 0d; void accumulate(double value) { n += 1; double delta = value - mean; mean += delta / (double) n; double delta2 = value - mean; M2 += delta * delta2; } Numeric std() { if (n < 2) return Numeric.ofNaN(); else return Numeric.ofDouble(sqrt(M2 / (double) (n - 1))); } } private static class NumericComparator implements Comparator<Numeric> { static NumericComparator natural = new NumericComparator(); public static Comparator<Numeric> natural() { return natural; } @Override public int compare(Numeric a, Numeric b) { return Double.compare(a.asNumber().doubleValue(), b.asNumber().doubleValue()); } } private static class OptionalAccumulator<T> implements Consumer<T> { T value = null; boolean present = false; private BinaryOperator<T> op; OptionalAccumulator(BinaryOperator<T> op) { this.op = op; } @Override public void accept(T t) { if (present) { value = op.apply(value, t); } else { value = t; present = true; } } } } public static class Group { private final Matcher matcher; private final GraqlMatch.Group query; public Group(Matcher matcher, GraqlMatch.Group query) { this.matcher = matcher; this.query = query; } public ResourceIterator<ConceptMapGroup> execute(boolean isParallel) { // TODO: Replace this temporary implementation of Graql Match Group query with a native grouping traversal List<ConceptMapGroup> answerGroups = new ArrayList<>(); matcher.execute(isParallel).stream().collect(groupingBy(a -> a.get(query.var()))) .forEach((o, cm) -> answerGroups.add(new ConceptMapGroup(o, cm))); return iterate(answerGroups); } public static class Aggregator { private final Group group; private final GraqlMatch.Group.Aggregate query; public Aggregator(Group group, GraqlMatch.Group.Aggregate query) { this.group = group; this.query = query; } public ResourceIterator<NumericGroup> execute(boolean isParallel) { // TODO: Replace this temporary implementation of Graql Match Group query with a native grouping traversal List<NumericGroup> numericGroups = new ArrayList<>(); group.matcher.execute(isParallel).stream() .collect(groupingBy(a -> a.get(query.group().var()), aggregator(query.method(), query.var()))) .forEach((o, n) -> numericGroups.add(new NumericGroup(o, n))); return iterate(numericGroups); } } } }
Simplify aggregate count collector implementation
query/Matcher.java
Simplify aggregate count collector implementation
<ide><path>uery/Matcher.java <ide> } <ide> <ide> static Collector<ConceptMap, ?, Numeric> count() { <del> return new Collector<ConceptMap, OptionalAccumulator<Long>, Numeric>() { <del> <del> @Override <del> public Supplier<OptionalAccumulator<Long>> supplier() { <del> return () -> new OptionalAccumulator<>(Long::sum); <del> } <del> <del> @Override <del> public BiConsumer<OptionalAccumulator<Long>, ConceptMap> accumulator() { <add> return new Collector<ConceptMap, Accumulator<Long>, Numeric>() { <add> <add> @Override <add> public Supplier<Accumulator<Long>> supplier() { <add> return () -> new Accumulator<>(0L, Long::sum); <add> } <add> <add> @Override <add> public BiConsumer<Accumulator<Long>, ConceptMap> accumulator() { <ide> return (sum, answer) -> sum.accept(1L); <ide> } <ide> <ide> @Override <del> public BinaryOperator<OptionalAccumulator<Long>> combiner() { <add> public BinaryOperator<Accumulator<Long>> combiner() { <ide> return (sum1, sum2) -> { <del> if (sum2.present) sum1.accept(sum2.value); <add> sum1.accept(sum2.value); <ide> return sum1; <ide> }; <ide> } <ide> <ide> @Override <del> public Function<OptionalAccumulator<Long>, Numeric> finisher() { <del> return sum -> { <del> if (sum.present) return Numeric.ofLong(sum.value); <del> else return Numeric.ofLong(0); <del> }; <add> public Function<Accumulator<Long>, Numeric> finisher() { <add> return sum -> Numeric.ofLong(sum.value); <ide> } <ide> <ide> @Override <ide> } <ide> } <ide> <add> private static class Accumulator<T> implements Consumer<T> { <add> T value; <add> private BinaryOperator<T> op; <add> <add> Accumulator(T init, BinaryOperator<T> op) { <add> value = init; <add> this.op = op; <add> } <add> <add> @Override <add> public void accept(T t) { <add> value = op.apply(value, t); <add> } <add> } <add> <ide> private static class OptionalAccumulator<T> implements Consumer<T> { <ide> T value = null; <ide> boolean present = false;
Java
apache-2.0
971c09b3b764b1040f866db5a32ffeb13d92c84c
0
pawanpal01/biodata,mh11/biodata,j-coll/biodata,opencb/biodata
package org.opencb.biodata.models.variant.avro; import htsjdk.tribble.index.IndexFactory; import htsjdk.variant.variantcontext.LazyGenotypesContext; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.vcf.VCFFileReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.avro.file.CodecFactory; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.DataFileWriter; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificDatumWriter; import org.opencb.biodata.models.variant.avro.CaddScore; import org.opencb.biodata.models.variant.avro.ConsequenceType; import org.opencb.biodata.models.variant.avro.ConsequenceTypeEntry; import org.opencb.biodata.models.variant.avro.ExpressionValue; import org.opencb.biodata.models.variant.avro.Genotype; import org.opencb.biodata.models.variant.avro.PopulationFrequency; import org.opencb.biodata.models.variant.avro.Score; import org.opencb.biodata.models.variant.avro.Variant; import org.opencb.biodata.models.variant.avro.VariantAnnotation; import org.opencb.biodata.models.variant.avro.VariantHardyWeinbergStats; import org.opencb.biodata.models.variant.avro.VariantSourceEntry; import org.opencb.biodata.models.variant.avro.VariantStats; import org.opencb.biodata.models.variant.avro.Xref; import org.opencb.biodata.models.variant.avro.AvroToVariantContextBean; import static org.opencb.biodata.models.variant.avro.VariantType.*; /** * @author Pawan Pal & Kalyan * */ public class VariantContextToVariantConverter { private String studyID; private String filedID; public VariantContextToVariantConverter(){ } public VariantContextToVariantConverter(String studyID,String fieldID) { this.studyID=studyID; this.filedID=fieldID; } /* * (non-Javadoc) * * @see * com.avroidl.service.IVariantHtsjdkVCFReader#readVCFFile(java.lang.String, * java.lang.String) */ public void readVCFFile(String vcfFilePath, String outputAvroFilePath) throws FileNotFoundException { /* * VCF input file path */ String vcfPath = vcfFilePath; /* * Avro output file path */ String outputAvroPath = outputAvroFilePath; /* * Create VCFFileReader object */ @SuppressWarnings("resource") VCFFileReader vcfFileReader = new VCFFileReader(new File(vcfPath)); Iterator<VariantContext> itr = vcfFileReader.iterator(); /* * List for variant */ List<Variant> variantList = new ArrayList<Variant>(); try { while (itr.hasNext()) { VariantContext variantContext = itr.next(); Variant variant = convert(variantContext); variantList.add(variant); } /* * method writeHtsjdkDataIntoAvro to write VCF data into AVRO format */ writeHtsjdkDataIntoAvro(variantList, outputAvroPath); } catch (Exception e) { System.out.println("Error message" + e.getLocalizedMessage()); } } public Variant convert(VariantContext variantContext){ Variant variant = new Variant(); /* * set reference parameter */ variant.setReference(variantContext.getReference().toString()); /* * set alternate parameter */ String alternateAllelString =variantContext .getAlternateAlleles().toString().substring(1, variantContext.getAlternateAlleles().toString().length() - 1); String[] alternateAllelArray = alternateAllelString.split(","); String alternate = null; if (alternateAllelArray.length >= 2) { alternate = getAlternateAllele(alternateAllelString); } else { alternate = alternateAllelString; } variant.setAlternate(alternate); /* * set variant type parameter */ variant.setVariantType(getEnumFromString(org.opencb.biodata.models.variant.avro.VariantType.class, variantContext .getType().toString())); /* * set chromosome, start and end type parameter */ variant.setChromosome(variantContext.getContig()); variant.setStart(variantContext.getStart()); variant.setEnd(variantContext.getEnd()); /* * set id parameter */ Set<String> id = new HashSet<String>(); String[] getId = variantContext.getID().split(","); if (getId.length > 1) for (String refId : getId) { id.add(refId); } /* * set length parameter */ variant.setLength(variantContext.getStart() - variantContext.getEnd() == 0 ? 1 : variantContext .getEnd() - variantContext.getStart() + 1); /* * set variantSourceEntry fields */ Map<CharSequence, VariantSourceEntry> sourceEntry = new HashMap<CharSequence, VariantSourceEntry>(); VariantSourceEntry variantSourceEntry = new VariantSourceEntry(); // For time being setting the hard coded values for FiledID and // Study ID variantSourceEntry.setFileId("123"); variantSourceEntry.setStudyId("23"); /* * set secondary alternate */ List<CharSequence> secondaryAlternateAlleleList = new ArrayList<CharSequence>(); if (alternateAllelString.split(",").length >= 2) { secondaryAlternateAlleleList = getSecondaryAlternateAllele(alternateAllelString); } else { secondaryAlternateAlleleList.add("null"); } variantSourceEntry.setSecondaryAlternates(secondaryAlternateAlleleList); /* * set variant format */ String[] str = ((LazyGenotypesContext) variantContext .getGenotypes()).getUnparsedGenotypeData().toString() .split("\t"); variantSourceEntry.setFormat(str[0]); /* * set sample data parameters Eg: GT:GQ:GQX:DP:DPF:AD * 1/1:63:29:22:7:0,22 */ Map<CharSequence, Map<CharSequence, CharSequence>> sampledataMap = new HashMap<CharSequence, Map<CharSequence, CharSequence>>(); Map<CharSequence, CharSequence> sampledata = new HashMap<CharSequence, CharSequence>(); if (str[0].split(":").length == str[1].split(":").length) { sampledata = getSampleDataMap(str[0], str[1]); } else { // this case will never occur sampledata.put("error", "error"); } sampledataMap.put(variantContext.getSampleNames().toString(), sampledata); variantSourceEntry.setSamplesData(sampledataMap); /* * set default cohort */ variantSourceEntry.DEFAULT_COHORT = "50"; /* * set cohortStats fields. Putting hard coded values for time * being as these value will not be getting from HTSJDK * currently. */ Map<CharSequence, VariantStats> cohortStats = new HashMap<CharSequence, VariantStats>(); cohortStats.put( "2", setVariantStatsParams( setVariantHardyWeinbergStatsParams(), variantContext)); variantSourceEntry.setCohortStats(cohortStats); /* * set attribute fields. Putting hard coded values for time being * as these value will not be getting from HTSJDK currently. */ Map<CharSequence, CharSequence> attributeMapNew = new HashMap<CharSequence, CharSequence>(); Map<String, Object> attributeMap = variantContext.getAttributes(); for(Map.Entry<String, Object> attr : attributeMap.entrySet()){ attributeMapNew.put(attr.getKey(), attr.getValue().toString()); } variantSourceEntry.setAttributes(attributeMapNew); sourceEntry.put("11", variantSourceEntry); /* * set parameter for HGVS Putting hard coded values for time * being as these value will not be getting from HTSJDK * currently. */ Map<CharSequence, List<CharSequence>> hgvsMap = new HashMap<CharSequence, List<CharSequence>>(); List<CharSequence> hgvsList = new ArrayList<CharSequence>(); hgvsList.add("HGVS"); hgvsMap.put("11", hgvsList); variant.setHgvs(hgvsMap); variant.setSourceEntries(sourceEntry); /* * set parameter for ids */ String[] idArray = variantContext.getID().split(","); List<CharSequence> idList=new ArrayList<>(); for( int idArrayIndex = 0; idArrayIndex <= idArray.length - 1; idArrayIndex++) { idList.add(idArray[idArrayIndex]); } variant.setIds(idList); /* * set VariantAnnotation parameters */ variant.setAnnotation(setVaraintAnnotationParams()); return variant; } /** * method to set Consequence Type Parameters * @return consequenceTypeList */ public List<ConsequenceType> setConsequenceTypeParams(){ List<ConsequenceType> consequenceTypeList = new ArrayList<>(); ConsequenceType consequenceType = new ConsequenceType(); consequenceType.setAaChange(null); consequenceType.setAaPosition(null); consequenceType.setBiotype(null); consequenceType.setCDnaPosition(null); consequenceType.setCdsPosition(null); consequenceType.setCodon(null); consequenceType.setEnsemblGeneId(null); consequenceType.setEnsemblTranscriptId(null); /* * set ExpressionValues list type parameter */ List<ExpressionValue> expressionValueList = new ArrayList<>(); ExpressionValue expressionValue = new ExpressionValue(); expressionValue.setExpression(getEnumFromString( org.opencb.biodata.models.variant.avro.Expression.class, "UP")); /*expressionValue.setExperimentalFactor(null); expressionValue.setExperimentId(null); expressionValue.setExpression(null); expressionValue.setFactorValue(null); expressionValue.setPvalue(null); expressionValue.setTechnologyPlatform(null);*/ expressionValueList.add(expressionValue); consequenceType.setExpressionValues(expressionValueList); consequenceType.setFunctionalDescription(null); consequenceType.setGeneName(null); /* * set ProteinSubstitutionScores list type parameter */ List<Score> proteinSubstitutionScoreList = new ArrayList<>(); Score score = new Score(); score.setDescription(null); score.setScore(null); score.setSource(null); proteinSubstitutionScoreList.add(score); consequenceType.setProteinSubstitutionScores(proteinSubstitutionScoreList); /* * set SoTerms list type parameter */ List<ConsequenceTypeEntry> consequenceTypeEntryList = new ArrayList<>(); ConsequenceTypeEntry consequenceTypeEntry = new ConsequenceTypeEntry(); consequenceTypeEntry.setSoAccession(null); consequenceTypeEntry.setSoName(null); consequenceTypeEntryList.add(consequenceTypeEntry); consequenceType.setSoTerms(consequenceTypeEntryList); consequenceType.setStrand(null); /* * Add consequenceType final bean to list */ consequenceTypeList.add(consequenceType); return consequenceTypeList; } /** * method to set Population Frequency Parameters * @return populationFrequencyList */ public List<PopulationFrequency> setPopulationFrequencyParams(){ List<PopulationFrequency> populationFrequencyList = new ArrayList<>(); PopulationFrequency populationFrequency = new PopulationFrequency(); populationFrequency.setAltAllele(null); populationFrequency.setAltAlleleFreq(null); populationFrequency.setAltHomGenotypeFreq(null); populationFrequency.setHetGenotypeFreq(null); populationFrequency.setPop(null); populationFrequency.setRefAllele(null); populationFrequency.setRefAlleleFreq(null); populationFrequency.setRefHomGenotypeFreq(null); populationFrequency.setStudy(null); populationFrequency.setSuperPop(null); populationFrequencyList.add(populationFrequency); return populationFrequencyList; } /** * method to set Varaint Annotation Parameters * @return variantAnnotation */ public VariantAnnotation setVaraintAnnotationParams(){ VariantAnnotation variantAnnotation = new VariantAnnotation(); /* * set AdditionalAttributes map type parameter */ Map<CharSequence, CharSequence> additionalAttributesMap = new HashMap(); //additionalAttributesMap.put(null, null); variantAnnotation.setAdditionalAttributes(additionalAttributesMap); /* * set AlternateAllele parameter */ variantAnnotation.setAlternateAllele(null); /* * set CaddScore list type parameter */ List<CaddScore> caddScoreList = new ArrayList<>(); CaddScore caddScore = new CaddScore(); /*caddScore.setCScore(null); caddScore.setRawScore(null); caddScore.setTranscriptId(null);*/ caddScoreList.add(caddScore); variantAnnotation.setCaddScore(caddScoreList); /* * set Chromosome parameter */ variantAnnotation.setChromosome(null); /* * set Clinical map type parameter */ Map<CharSequence, CharSequence> clinicalMap = new HashMap<>(); //clinicalMap.put(null, null); variantAnnotation.setClinical(clinicalMap); /* * set ConsequenceTypes list type parameter */ variantAnnotation.setConsequenceTypes(setConsequenceTypeParams()); /* * set ConservationScores list type parameter */ List<Score> conservationScoreList = new ArrayList<>(); Score score = new Score(); /*score.setDescription(null); score.setScore(null); score.setSource(null); */ conservationScoreList.add(score); variantAnnotation.setConservationScores(conservationScoreList); variantAnnotation.setEnd(0); /* * set GeneDrugInteraction map of list type parameter */ Map<CharSequence, List<CharSequence>> geneDrugInteractionMap = new HashMap<>(); List<CharSequence> geneDrugInteractionList = new ArrayList<>(); //geneDrugInteractionList.add("AAA"); //geneDrugInteractionMap.put("000", geneDrugInteractionList); variantAnnotation.setGeneDrugInteraction(geneDrugInteractionMap); /* * set Hgvs list type parameter */ List<CharSequence> hgvsList = new ArrayList<>(); //hgvsList.add(null); variantAnnotation.setHgvs(hgvsList); variantAnnotation.setId(null); /* * set PopulationFrequencies list type parameter */ variantAnnotation.setPopulationFrequencies(setPopulationFrequencyParams()); variantAnnotation.setReferenceAllele(null); variantAnnotation.setStart(0); /* * set Xref list type parameter */ List<Xref> xrefsList = new ArrayList<>(); Xref xref = new Xref(); /*xref.setId(null); xref.setSrc(null);*/ xrefsList.add(xref); variantAnnotation.setXrefs(xrefsList); /* * return variantAnnotation bean */ return variantAnnotation; } /** * get sample data * @param keyString * @param valueString * @return */ public static Map<CharSequence, CharSequence> getSampleDataMap( String keyString, String valueString) { String keyArray[] = keyString.split(":"); String valueArray[] = valueString.split(":"); Map<CharSequence, CharSequence> sampleDataMap = new HashMap<CharSequence, CharSequence>(); for (int i = 0; i < keyArray.length; i++) { sampleDataMap.put(keyArray[i], valueArray[i]); } return sampleDataMap; } /** * method to get alternate allele * @return alternateAlleleString */ public static String getAlternateAllele(String alternateAllele) { //System.out.print("insdie method " + alternateAllele); StringBuffer secondaryAllelString = new StringBuffer(); String secondaryAllelArrayTemp[] = alternateAllele.trim().split(","); if (secondaryAllelArrayTemp.length > 1) { for (int i = 0; i < secondaryAllelArrayTemp.length; i++) { if (i == 0) { secondaryAllelString.append(secondaryAllelArrayTemp[i] .toString().trim()); break; } } } //System.out.println(secondaryAllelString.toString()); return secondaryAllelString.toString().trim(); } /** * method to get secondary allele * @param secondaryAllele * @return secondaryAllelArrayList */ public static List<CharSequence> getSecondaryAlternateAllele( String secondaryAllele) { CharSequence secondaryAllelArray[] = null; StringBuffer secondaryAlleleString = new StringBuffer(); CharSequence secondaryAlleleArrayTemp[] = secondaryAllele.trim().split(","); if (secondaryAlleleArrayTemp.length >= 2) { for (int i = 1; i < secondaryAlleleArrayTemp.length; i++) { secondaryAlleleString.append(secondaryAlleleArrayTemp[i] .toString().trim()); secondaryAlleleString.append(","); } } secondaryAllelArray = secondaryAlleleString.substring(0, secondaryAlleleString.length() - 1).split(","); return Arrays.asList(secondaryAllelArray); } /** * method to set Variant Stats Parameters * @param variantHardyWeinbergStats * @param variantContext * @return variantStats */ private VariantStats setVariantStatsParams( VariantHardyWeinbergStats variantHardyWeinbergStats, VariantContext variantContext) { VariantStats variantStats = new VariantStats(); variantStats.setAltAllele("aa"); variantStats.setAltAlleleCount(1); variantStats.setAltAlleleFreq(2.1f); variantStats.setCasesPercentDominant(3.1f); variantStats.setCasesPercentRecessive(5.1f); variantStats.setControlsPercentDominant(1.0f); variantStats.setControlsPercentRecessive(3.1f); variantStats.setMaf(4f); variantStats.setMafAllele("ss"); variantStats.setMendelianErrors(4); variantStats.setMgf(3f); variantStats.setMgfGenotype("AA"); variantStats.setMissingAlleles(3); variantStats.setMissingGenotypes(3); variantStats.setNumSamples(4); variantStats.setPassedFilters(true); variantStats.setQuality((float) variantContext.getPhredScaledQual()); variantStats.setRefAllele("SS"); variantStats.setRefAlleleCount(4); variantStats.setRefAlleleFreq(2f); variantStats.setHw(variantHardyWeinbergStats); variantStats.setVariantType(getEnumFromString( org.opencb.biodata.models.variant.avro.VariantType.class, variantContext.getType() .toString())); return variantStats; } /** * method to set VariantHardyWeinberg Stats Parameters * @return variantHardyWeinbergStats */ private VariantHardyWeinbergStats setVariantHardyWeinbergStatsParams() { VariantHardyWeinbergStats variantHardyWeinbergStats = new VariantHardyWeinbergStats(); variantHardyWeinbergStats.setChi2(1f); variantHardyWeinbergStats.setEAa00(2f); variantHardyWeinbergStats.setEAa10(3f); variantHardyWeinbergStats.setEAA11(4f); variantHardyWeinbergStats.setN(1); variantHardyWeinbergStats.setNAa00(2); variantHardyWeinbergStats.setNAa10(3); variantHardyWeinbergStats.setNAA11(4); variantHardyWeinbergStats.setP(1f); variantHardyWeinbergStats.setQ(2f); return variantHardyWeinbergStats; } /** * method which will write data into Avro format * @param vcfBean * @param outputAvroFilePath * @throws FileNotFoundException */ public void writeHtsjdkDataIntoAvro(List<Variant> vcfBean, String outputAvroFilePath) throws FileNotFoundException { if (outputAvroFilePath.isEmpty()) { throw new FileNotFoundException( "Output file path is empty or null..."); } try { FileOutputStream outputStream = new FileOutputStream( outputAvroFilePath); DatumWriter<Variant> vcfDatumWriter = new SpecificDatumWriter<Variant>( Variant.class); DataFileWriter<Variant> vcfdataFileWriter = new DataFileWriter<Variant>( vcfDatumWriter); Variant variant = new Variant(); vcfdataFileWriter.setCodec(CodecFactory.snappyCodec()); vcfdataFileWriter.create(variant.getSchema(), outputStream); for (Variant variantAvro : vcfBean) { vcfdataFileWriter.append(variantAvro); } vcfdataFileWriter.flush(); vcfdataFileWriter.close(); outputStream.close(); } catch (Exception e) { System.out.println("Error :: " + e); } } /** * Method to convert avro data to variantContext * @return * @throws IOException */ public void convertToVariantContext(String avroFilePath, String contextFilePath) throws IOException{ /* * Read avro file and set value to the bean */ DatumReader<Variant> variantDatumReader = new SpecificDatumReader<Variant>(Variant.class); DataFileReader<Variant> variantDataFileReader = new DataFileReader<Variant>(new File(avroFilePath), variantDatumReader); Variant readAvro = null; File file = new File(contextFilePath); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); while (variantDataFileReader.hasNext()) { AvroToVariantContextBean avroToVariantContextBean = new AvroToVariantContextBean(); readAvro = variantDataFileReader.next(readAvro); /* * Set chromosome */ avroToVariantContextBean.setChrom(readAvro.getChromosome().toString()); /* * Set position */ int pos= readAvro.getStart(); int position = 0; if ((readAvro.getLength()) == 1){ position = pos; avroToVariantContextBean.setPos(position); }else { position = pos-1; avroToVariantContextBean.setPos(position); } /* * Set reference */ avroToVariantContextBean.setRef(readAvro.getReference().toString()); //get parameters from variant source entry List<CharSequence> secondaryAltList = new ArrayList<CharSequence>(); String secondaryAlt = ""; String format = ""; String filter = ""; String quality = ""; String sample = ""; String info = ""; for(Map.Entry<CharSequence, VariantSourceEntry> srcEntry: readAvro.getSourceEntries().entrySet()){ //get secondary alternate secondaryAltList = srcEntry.getValue().getSecondaryAlternates(); for(CharSequence secAlt : secondaryAltList){ if(secAlt.toString().equals("null")){ secondaryAlt = ""; }else{ secondaryAlt = secAlt.toString(); } } //get format format = srcEntry.getValue().getFormat().toString(); //get filter for(Entry<CharSequence, VariantStats> qual : srcEntry.getValue().getCohortStats().entrySet()){ if(qual.getValue().getPassedFilters().toString().equals("true")){ filter = "Pass"; }else{ filter = "Fail"; } } //get quality for(Entry<CharSequence, VariantStats> qual : srcEntry.getValue().getCohortStats().entrySet()){ quality = qual.getValue().getQuality().toString(); } //get sample for(Entry<CharSequence, Map<CharSequence, CharSequence>> smpl : srcEntry.getValue().getSamplesData().entrySet()){ sample = smpl.getValue().toString(); } //get attributes Map<CharSequence, CharSequence> attributeMap = srcEntry.getValue().getAttributes(); for(Map.Entry<CharSequence, CharSequence> attribute : attributeMap.entrySet()){ info += attribute.getKey()+"="+attribute.getValue()+";"; info=info.substring(0, info.length()-1); } } /* * Set alternate */ String alternate = readAvro.getAlternate().toString()+","+ secondaryAlt; alternate=alternate.substring(0, alternate.length()-1); avroToVariantContextBean.setAlt(alternate); /* * set format */ avroToVariantContextBean.setFormat(format); /* * set filter */ avroToVariantContextBean.setFilter(filter); /* * set quality */ avroToVariantContextBean.setQual(quality); /* * set sample */ avroToVariantContextBean.setSample1(sample); /* * set id */ List<CharSequence> idList = readAvro.getIds(); String ids = ""; for(CharSequence idStr : idList){ ids=ids+idStr+","; } ids=ids.substring(0, ids.length()-1); avroToVariantContextBean.setId(ids); /* * set info */ avroToVariantContextBean.setInfo(info); /*System.out.println(avroToVariantContextBean.getChrom() +" "+ avroToVariantContextBean.getPos() +" "+ avroToVariantContextBean.getId() +" "+ avroToVariantContextBean.getRef() +" "+ avroToVariantContextBean.getAlt() +" "+ avroToVariantContextBean.getQual() +" "+ avroToVariantContextBean.getFilter() +" "+ avroToVariantContextBean.getInfo() +" "+ avroToVariantContextBean.getFormat() +" "+ avroToVariantContextBean.getSample1() );*/ bw.write(avroToVariantContextBean.getChrom() +"\t"+ avroToVariantContextBean.getPos() +"\t"+ avroToVariantContextBean.getId() +"\t"+ avroToVariantContextBean.getRef() +"\t"+ avroToVariantContextBean.getAlt() +"\t"+ avroToVariantContextBean.getQual() +"\t"+ avroToVariantContextBean.getFilter() +"\t"+ avroToVariantContextBean.getInfo() +"\t"+ avroToVariantContextBean.getFormat() +"\t"+ avroToVariantContextBean.getSample1()); bw.write("\n"); } bw.close(); variantDataFileReader.close(); } /** * @param variantType * @param string * @return */ public static <VariantType extends Enum<VariantType>> VariantType getEnumFromString( Class<VariantType> variantType, String string) { if (variantType != null && string != null) { try { return Enum.valueOf(variantType, string.trim().toUpperCase()); } catch (IllegalArgumentException e) { } } return null; } }
biodata-models/src/main/java/org/opencb/biodata/models/variant/avro/VariantContextToVariantConverter.java
package org.opencb.biodata.models.variant.avro; import htsjdk.tribble.index.IndexFactory; import htsjdk.variant.variantcontext.LazyGenotypesContext; import htsjdk.variant.variantcontext.VariantContext; import htsjdk.variant.vcf.VCFFileReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.apache.avro.file.CodecFactory; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.DataFileWriter; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.avro.specific.SpecificDatumReader; import org.apache.avro.specific.SpecificDatumWriter; import org.opencb.biodata.models.variant.avro.CaddScore; import org.opencb.biodata.models.variant.avro.ConsequenceType; import org.opencb.biodata.models.variant.avro.ConsequenceTypeEntry; import org.opencb.biodata.models.variant.avro.ExpressionValue; import org.opencb.biodata.models.variant.avro.Genotype; import org.opencb.biodata.models.variant.avro.PopulationFrequency; import org.opencb.biodata.models.variant.avro.Score; import org.opencb.biodata.models.variant.avro.Variant; import org.opencb.biodata.models.variant.avro.VariantAnnotation; import org.opencb.biodata.models.variant.avro.VariantHardyWeinbergStats; import org.opencb.biodata.models.variant.avro.VariantSourceEntry; import org.opencb.biodata.models.variant.avro.VariantStats; import org.opencb.biodata.models.variant.avro.Xref; import org.opencb.biodata.models.variant.avro.AvroToVariantContextBean; import static org.opencb.biodata.models.variant.avro.VariantType.*; /** * @author Pawan Pal & Kalyan * */ public class VariantContextToVariantConverter { private String studyID; private String filedID; public VariantContextToVariantConverter(){ } public VariantContextToVariantConverter(String studyID,String fieldID) { this.studyID=studyID; this.filedID=fieldID; } /* * (non-Javadoc) * * @see * com.avroidl.service.IVariantHtsjdkVCFReader#readVCFFile(java.lang.String, * java.lang.String) */ public void readVCFFile(String vcfFilePath, String outputAvroFilePath) throws FileNotFoundException { /* * VCF input file path */ String vcfPath = vcfFilePath; /* * Avro output file path */ String outputAvroPath = outputAvroFilePath; /* * Create VCFFileReader object */ @SuppressWarnings("resource") VCFFileReader vcfFileReader = new VCFFileReader(new File(vcfPath)); Iterator<VariantContext> itr = vcfFileReader.iterator(); /* * List for variant */ List<Variant> variantList = new ArrayList<Variant>(); try { while (itr.hasNext()) { Variant variant = new Variant(); VariantContext variantContext = itr.next(); variant = convert(variantContext,variant); variantList.add(variant); } /* * method writeHtsjdkDataIntoAvro to write VCF data into AVRO format */ writeHtsjdkDataIntoAvro(variantList, outputAvroPath); } catch (Exception e) { System.out.println("Error message" + e.getLocalizedMessage()); } } public Variant convert(VariantContext variantContext, Variant variant){ /* * set reference parameter */ variant.setReference(variantContext.getReference().toString()); /* * set alternate parameter */ String alternateAllelString =variantContext .getAlternateAlleles().toString().substring(1, variantContext.getAlternateAlleles().toString().length() - 1); String[] alternateAllelArray = alternateAllelString.split(","); String alternate = null; if (alternateAllelArray.length >= 2) { alternate = getAlternateAllele(alternateAllelString); } else { alternate = alternateAllelString; } variant.setAlternate(alternate); /* * set variant type parameter */ variant.setVariantType(getEnumFromString(org.opencb.biodata.models.variant.avro.VariantType.class, variantContext .getType().toString())); /* * set chromosome, start and end type parameter */ variant.setChromosome(variantContext.getContig()); variant.setStart(variantContext.getStart()); variant.setEnd(variantContext.getEnd()); /* * set id parameter */ Set<String> id = new HashSet<String>(); String[] getId = variantContext.getID().split(","); if (getId.length > 1) for (String refId : getId) { id.add(refId); } /* * set length parameter */ variant.setLength(variantContext.getStart() - variantContext.getEnd() == 0 ? 1 : variantContext .getEnd() - variantContext.getStart() + 1); /* * set variantSourceEntry fields */ Map<CharSequence, VariantSourceEntry> sourceEntry = new HashMap<CharSequence, VariantSourceEntry>(); VariantSourceEntry variantSourceEntry = new VariantSourceEntry(); // For time being setting the hard coded values for FiledID and // Study ID variantSourceEntry.setFileId("123"); variantSourceEntry.setStudyId("23"); /* * set secondary alternate */ List<CharSequence> secondaryAlternateAlleleList = new ArrayList<CharSequence>(); if (alternateAllelString.split(",").length >= 2) { secondaryAlternateAlleleList = getSecondaryAlternateAllele(alternateAllelString); } else { secondaryAlternateAlleleList.add("null"); } variantSourceEntry.setSecondaryAlternates(secondaryAlternateAlleleList); /* * set variant format */ String[] str = ((LazyGenotypesContext) variantContext .getGenotypes()).getUnparsedGenotypeData().toString() .split("\t"); variantSourceEntry.setFormat(str[0]); /* * set sample data parameters Eg: GT:GQ:GQX:DP:DPF:AD * 1/1:63:29:22:7:0,22 */ Map<CharSequence, Map<CharSequence, CharSequence>> sampledataMap = new HashMap<CharSequence, Map<CharSequence, CharSequence>>(); Map<CharSequence, CharSequence> sampledata = new HashMap<CharSequence, CharSequence>(); if (str[0].split(":").length == str[1].split(":").length) { sampledata = getSampleDataMap(str[0], str[1]); } else { // this case will never occur sampledata.put("error", "error"); } sampledataMap.put(variantContext.getSampleNames().toString(), sampledata); variantSourceEntry.setSamplesData(sampledataMap); /* * set default cohort */ variantSourceEntry.DEFAULT_COHORT = "50"; /* * set cohortStats fields. Putting hard coded values for time * being as these value will not be getting from HTSJDK * currently. */ Map<CharSequence, VariantStats> cohortStats = new HashMap<CharSequence, VariantStats>(); cohortStats.put( "2", setVariantStatsParams( setVariantHardyWeinbergStatsParams(), variantContext)); variantSourceEntry.setCohortStats(cohortStats); /* * set attribute fields. Putting hard coded values for time being * as these value will not be getting from HTSJDK currently. */ Map<CharSequence, CharSequence> attributeMapNew = new HashMap<CharSequence, CharSequence>(); Map<String, Object> attributeMap = variantContext.getAttributes(); for(Map.Entry<String, Object> attr : attributeMap.entrySet()){ attributeMapNew.put(attr.getKey(), attr.getValue().toString()); } variantSourceEntry.setAttributes(attributeMapNew); sourceEntry.put("11", variantSourceEntry); /* * set parameter for HGVS Putting hard coded values for time * being as these value will not be getting from HTSJDK * currently. */ Map<CharSequence, List<CharSequence>> hgvsMap = new HashMap<CharSequence, List<CharSequence>>(); List<CharSequence> hgvsList = new ArrayList<CharSequence>(); hgvsList.add("HGVS"); hgvsMap.put("11", hgvsList); variant.setHgvs(hgvsMap); variant.setSourceEntries(sourceEntry); /* * set parameter for ids */ String[] idArray = variantContext.getID().split(","); List<CharSequence> idList=new ArrayList<>(); for( int idArrayIndex = 0; idArrayIndex <= idArray.length - 1; idArrayIndex++) { idList.add(idArray[idArrayIndex]); } variant.setIds(idList); /* * set VariantAnnotation parameters */ variant.setAnnotation(setVaraintAnnotationParams()); return variant; } /** * method to set Consequence Type Parameters * @return consequenceTypeList */ public List<ConsequenceType> setConsequenceTypeParams(){ List<ConsequenceType> consequenceTypeList = new ArrayList<>(); ConsequenceType consequenceType = new ConsequenceType(); consequenceType.setAaChange(null); consequenceType.setAaPosition(null); consequenceType.setBiotype(null); consequenceType.setCDnaPosition(null); consequenceType.setCdsPosition(null); consequenceType.setCodon(null); consequenceType.setEnsemblGeneId(null); consequenceType.setEnsemblTranscriptId(null); /* * set ExpressionValues list type parameter */ List<ExpressionValue> expressionValueList = new ArrayList<>(); ExpressionValue expressionValue = new ExpressionValue(); expressionValue.setExpression(getEnumFromString( org.opencb.biodata.models.variant.avro.Expression.class, "UP")); /*expressionValue.setExperimentalFactor(null); expressionValue.setExperimentId(null); expressionValue.setExpression(null); expressionValue.setFactorValue(null); expressionValue.setPvalue(null); expressionValue.setTechnologyPlatform(null);*/ expressionValueList.add(expressionValue); consequenceType.setExpressionValues(expressionValueList); consequenceType.setFunctionalDescription(null); consequenceType.setGeneName(null); /* * set ProteinSubstitutionScores list type parameter */ List<Score> proteinSubstitutionScoreList = new ArrayList<>(); Score score = new Score(); score.setDescription(null); score.setScore(null); score.setSource(null); proteinSubstitutionScoreList.add(score); consequenceType.setProteinSubstitutionScores(proteinSubstitutionScoreList); /* * set SoTerms list type parameter */ List<ConsequenceTypeEntry> consequenceTypeEntryList = new ArrayList<>(); ConsequenceTypeEntry consequenceTypeEntry = new ConsequenceTypeEntry(); consequenceTypeEntry.setSoAccession(null); consequenceTypeEntry.setSoName(null); consequenceTypeEntryList.add(consequenceTypeEntry); consequenceType.setSoTerms(consequenceTypeEntryList); consequenceType.setStrand(null); /* * Add consequenceType final bean to list */ consequenceTypeList.add(consequenceType); return consequenceTypeList; } /** * method to set Population Frequency Parameters * @return populationFrequencyList */ public List<PopulationFrequency> setPopulationFrequencyParams(){ List<PopulationFrequency> populationFrequencyList = new ArrayList<>(); PopulationFrequency populationFrequency = new PopulationFrequency(); populationFrequency.setAltAllele(null); populationFrequency.setAltAlleleFreq(null); populationFrequency.setAltHomGenotypeFreq(null); populationFrequency.setHetGenotypeFreq(null); populationFrequency.setPop(null); populationFrequency.setRefAllele(null); populationFrequency.setRefAlleleFreq(null); populationFrequency.setRefHomGenotypeFreq(null); populationFrequency.setStudy(null); populationFrequency.setSuperPop(null); populationFrequencyList.add(populationFrequency); return populationFrequencyList; } /** * method to set Varaint Annotation Parameters * @return variantAnnotation */ public VariantAnnotation setVaraintAnnotationParams(){ VariantAnnotation variantAnnotation = new VariantAnnotation(); /* * set AdditionalAttributes map type parameter */ Map<CharSequence, CharSequence> additionalAttributesMap = new HashMap(); //additionalAttributesMap.put(null, null); variantAnnotation.setAdditionalAttributes(additionalAttributesMap); /* * set AlternateAllele parameter */ variantAnnotation.setAlternateAllele(null); /* * set CaddScore list type parameter */ List<CaddScore> caddScoreList = new ArrayList<>(); CaddScore caddScore = new CaddScore(); /*caddScore.setCScore(null); caddScore.setRawScore(null); caddScore.setTranscriptId(null);*/ caddScoreList.add(caddScore); variantAnnotation.setCaddScore(caddScoreList); /* * set Chromosome parameter */ variantAnnotation.setChromosome(null); /* * set Clinical map type parameter */ Map<CharSequence, CharSequence> clinicalMap = new HashMap<>(); //clinicalMap.put(null, null); variantAnnotation.setClinical(clinicalMap); /* * set ConsequenceTypes list type parameter */ variantAnnotation.setConsequenceTypes(setConsequenceTypeParams()); /* * set ConservationScores list type parameter */ List<Score> conservationScoreList = new ArrayList<>(); Score score = new Score(); /*score.setDescription(null); score.setScore(null); score.setSource(null); */ conservationScoreList.add(score); variantAnnotation.setConservationScores(conservationScoreList); variantAnnotation.setEnd(0); /* * set GeneDrugInteraction map of list type parameter */ Map<CharSequence, List<CharSequence>> geneDrugInteractionMap = new HashMap<>(); List<CharSequence> geneDrugInteractionList = new ArrayList<>(); //geneDrugInteractionList.add("AAA"); //geneDrugInteractionMap.put("000", geneDrugInteractionList); variantAnnotation.setGeneDrugInteraction(geneDrugInteractionMap); /* * set Hgvs list type parameter */ List<CharSequence> hgvsList = new ArrayList<>(); //hgvsList.add(null); variantAnnotation.setHgvs(hgvsList); variantAnnotation.setId(null); /* * set PopulationFrequencies list type parameter */ variantAnnotation.setPopulationFrequencies(setPopulationFrequencyParams()); variantAnnotation.setReferenceAllele(null); variantAnnotation.setStart(0); /* * set Xref list type parameter */ List<Xref> xrefsList = new ArrayList<>(); Xref xref = new Xref(); /*xref.setId(null); xref.setSrc(null);*/ xrefsList.add(xref); variantAnnotation.setXrefs(xrefsList); /* * return variantAnnotation bean */ return variantAnnotation; } /** * get sample data * @param keyString * @param valueString * @return */ public static Map<CharSequence, CharSequence> getSampleDataMap( String keyString, String valueString) { String keyArray[] = keyString.split(":"); String valueArray[] = valueString.split(":"); Map<CharSequence, CharSequence> sampleDataMap = new HashMap<CharSequence, CharSequence>(); for (int i = 0; i < keyArray.length; i++) { sampleDataMap.put(keyArray[i], valueArray[i]); } return sampleDataMap; } /** * method to get alternate allele * @return alternateAlleleString */ public static String getAlternateAllele(String alternateAllele) { //System.out.print("insdie method " + alternateAllele); StringBuffer secondaryAllelString = new StringBuffer(); String secondaryAllelArrayTemp[] = alternateAllele.trim().split(","); if (secondaryAllelArrayTemp.length > 1) { for (int i = 0; i < secondaryAllelArrayTemp.length; i++) { if (i == 0) { secondaryAllelString.append(secondaryAllelArrayTemp[i] .toString().trim()); break; } } } //System.out.println(secondaryAllelString.toString()); return secondaryAllelString.toString().trim(); } /** * method to get secondary allele * @param secondaryAllele * @return secondaryAllelArrayList */ public static List<CharSequence> getSecondaryAlternateAllele( String secondaryAllele) { CharSequence secondaryAllelArray[] = null; StringBuffer secondaryAlleleString = new StringBuffer(); CharSequence secondaryAlleleArrayTemp[] = secondaryAllele.trim().split(","); if (secondaryAlleleArrayTemp.length >= 2) { for (int i = 1; i < secondaryAlleleArrayTemp.length; i++) { secondaryAlleleString.append(secondaryAlleleArrayTemp[i] .toString().trim()); secondaryAlleleString.append(","); } } secondaryAllelArray = secondaryAlleleString.substring(0, secondaryAlleleString.length() - 1).split(","); return Arrays.asList(secondaryAllelArray); } /** * method to set Variant Stats Parameters * @param variantHardyWeinbergStats * @param variantContext * @return variantStats */ private VariantStats setVariantStatsParams( VariantHardyWeinbergStats variantHardyWeinbergStats, VariantContext variantContext) { VariantStats variantStats = new VariantStats(); variantStats.setAltAllele("aa"); variantStats.setAltAlleleCount(1); variantStats.setAltAlleleFreq(2.1f); variantStats.setCasesPercentDominant(3.1f); variantStats.setCasesPercentRecessive(5.1f); variantStats.setControlsPercentDominant(1.0f); variantStats.setControlsPercentRecessive(3.1f); variantStats.setMaf(4f); variantStats.setMafAllele("ss"); variantStats.setMendelianErrors(4); variantStats.setMgf(3f); variantStats.setMgfGenotype("AA"); variantStats.setMissingAlleles(3); variantStats.setMissingGenotypes(3); variantStats.setNumSamples(4); variantStats.setPassedFilters(true); variantStats.setQuality((float) variantContext.getPhredScaledQual()); variantStats.setRefAllele("SS"); variantStats.setRefAlleleCount(4); variantStats.setRefAlleleFreq(2f); variantStats.setHw(variantHardyWeinbergStats); variantStats.setVariantType(getEnumFromString( org.opencb.biodata.models.variant.avro.VariantType.class, variantContext.getType() .toString())); return variantStats; } /** * method to set VariantHardyWeinberg Stats Parameters * @return variantHardyWeinbergStats */ private VariantHardyWeinbergStats setVariantHardyWeinbergStatsParams() { VariantHardyWeinbergStats variantHardyWeinbergStats = new VariantHardyWeinbergStats(); variantHardyWeinbergStats.setChi2(1f); variantHardyWeinbergStats.setEAa00(2f); variantHardyWeinbergStats.setEAa10(3f); variantHardyWeinbergStats.setEAA11(4f); variantHardyWeinbergStats.setN(1); variantHardyWeinbergStats.setNAa00(2); variantHardyWeinbergStats.setNAa10(3); variantHardyWeinbergStats.setNAA11(4); variantHardyWeinbergStats.setP(1f); variantHardyWeinbergStats.setQ(2f); return variantHardyWeinbergStats; } /** * method which will write data into Avro format * @param vcfBean * @param outputAvroFilePath * @throws FileNotFoundException */ public void writeHtsjdkDataIntoAvro(List<Variant> vcfBean, String outputAvroFilePath) throws FileNotFoundException { if (outputAvroFilePath.isEmpty()) { throw new FileNotFoundException( "Output file path is empty or null..."); } try { FileOutputStream outputStream = new FileOutputStream( outputAvroFilePath); DatumWriter<Variant> vcfDatumWriter = new SpecificDatumWriter<Variant>( Variant.class); DataFileWriter<Variant> vcfdataFileWriter = new DataFileWriter<Variant>( vcfDatumWriter); Variant variant = new Variant(); vcfdataFileWriter.setCodec(CodecFactory.snappyCodec()); vcfdataFileWriter.create(variant.getSchema(), outputStream); for (Variant variantAvro : vcfBean) { vcfdataFileWriter.append(variantAvro); } vcfdataFileWriter.flush(); vcfdataFileWriter.close(); outputStream.close(); } catch (Exception e) { System.out.println("Error :: " + e); } } /** * Method to convert avro data to variantContext * @return * @throws IOException */ public void convertToVariantContext(String avroFilePath, String contextFilePath) throws IOException{ /* * Read avro file and set value to the bean */ DatumReader<Variant> variantDatumReader = new SpecificDatumReader<Variant>(Variant.class); DataFileReader<Variant> variantDataFileReader = new DataFileReader<Variant>(new File(avroFilePath), variantDatumReader); Variant readAvro = null; File file = new File(contextFilePath); FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); while (variantDataFileReader.hasNext()) { AvroToVariantContextBean avroToVariantContextBean = new AvroToVariantContextBean(); readAvro = variantDataFileReader.next(readAvro); /* * Set chromosome */ avroToVariantContextBean.setChrom(readAvro.getChromosome().toString()); /* * Set position */ int pos= readAvro.getStart(); int position = 0; if ((readAvro.getLength()) == 1){ position = pos; avroToVariantContextBean.setPos(position); }else { position = pos-1; avroToVariantContextBean.setPos(position); } /* * Set reference */ avroToVariantContextBean.setRef(readAvro.getReference().toString()); //get parameters from variant source entry List<CharSequence> secondaryAltList = new ArrayList<CharSequence>(); String secondaryAlt = ""; String format = ""; String filter = ""; String quality = ""; String sample = ""; String info = ""; for(Map.Entry<CharSequence, VariantSourceEntry> srcEntry: readAvro.getSourceEntries().entrySet()){ //get secondary alternate secondaryAltList = srcEntry.getValue().getSecondaryAlternates(); for(CharSequence secAlt : secondaryAltList){ if(secAlt.toString().equals("null")){ secondaryAlt = ""; }else{ secondaryAlt = secAlt.toString(); } } //get format format = srcEntry.getValue().getFormat().toString(); //get filter for(Entry<CharSequence, VariantStats> qual : srcEntry.getValue().getCohortStats().entrySet()){ if(qual.getValue().getPassedFilters().toString().equals("true")){ filter = "Pass"; }else{ filter = "Fail"; } } //get quality for(Entry<CharSequence, VariantStats> qual : srcEntry.getValue().getCohortStats().entrySet()){ quality = qual.getValue().getQuality().toString(); } //get sample for(Entry<CharSequence, Map<CharSequence, CharSequence>> smpl : srcEntry.getValue().getSamplesData().entrySet()){ sample = smpl.getValue().toString(); } //get attributes Map<CharSequence, CharSequence> attributeMap = srcEntry.getValue().getAttributes(); for(Map.Entry<CharSequence, CharSequence> attribute : attributeMap.entrySet()){ info += attribute.getKey()+"="+attribute.getValue()+";"; info=info.substring(0, info.length()-1); } } /* * Set alternate */ String alternate = readAvro.getAlternate().toString()+","+ secondaryAlt; alternate=alternate.substring(0, alternate.length()-1); avroToVariantContextBean.setAlt(alternate); /* * set format */ avroToVariantContextBean.setFormat(format); /* * set filter */ avroToVariantContextBean.setFilter(filter); /* * set quality */ avroToVariantContextBean.setQual(quality); /* * set sample */ avroToVariantContextBean.setSample1(sample); /* * set id */ List<CharSequence> idList = readAvro.getIds(); String ids = ""; for(CharSequence idStr : idList){ ids=ids+idStr+","; } ids=ids.substring(0, ids.length()-1); avroToVariantContextBean.setId(ids); /* * set info */ avroToVariantContextBean.setInfo(info); /*System.out.println(avroToVariantContextBean.getChrom() +" "+ avroToVariantContextBean.getPos() +" "+ avroToVariantContextBean.getId() +" "+ avroToVariantContextBean.getRef() +" "+ avroToVariantContextBean.getAlt() +" "+ avroToVariantContextBean.getQual() +" "+ avroToVariantContextBean.getFilter() +" "+ avroToVariantContextBean.getInfo() +" "+ avroToVariantContextBean.getFormat() +" "+ avroToVariantContextBean.getSample1() );*/ bw.write(avroToVariantContextBean.getChrom() +"\t"+ avroToVariantContextBean.getPos() +"\t"+ avroToVariantContextBean.getId() +"\t"+ avroToVariantContextBean.getRef() +"\t"+ avroToVariantContextBean.getAlt() +"\t"+ avroToVariantContextBean.getQual() +"\t"+ avroToVariantContextBean.getFilter() +"\t"+ avroToVariantContextBean.getInfo() +"\t"+ avroToVariantContextBean.getFormat() +"\t"+ avroToVariantContextBean.getSample1()); bw.write("\n"); } bw.close(); variantDataFileReader.close(); } /** * @param variantType * @param string * @return */ public static <VariantType extends Enum<VariantType>> VariantType getEnumFromString( Class<VariantType> variantType, String string) { if (variantType != null && string != null) { try { return Enum.valueOf(variantType, string.trim().toUpperCase()); } catch (IllegalArgumentException e) { } } return null; } }
BioModel: update Variant converter method
biodata-models/src/main/java/org/opencb/biodata/models/variant/avro/VariantContextToVariantConverter.java
BioModel: update Variant converter method
<ide><path>iodata-models/src/main/java/org/opencb/biodata/models/variant/avro/VariantContextToVariantConverter.java <ide> <ide> try { <ide> while (itr.hasNext()) { <del> Variant variant = new Variant(); <ide> VariantContext variantContext = itr.next(); <del> variant = convert(variantContext,variant); <add> Variant variant = convert(variantContext); <ide> variantList.add(variant); <ide> } <ide> /* <ide> } <ide> } <ide> <del> public Variant convert(VariantContext variantContext, Variant variant){ <add> public Variant convert(VariantContext variantContext){ <add> Variant variant = new Variant(); <add> <ide> /* <ide> * set reference parameter <ide> */
Java
apache-2.0
43244ced7df55c5736f38119d60ec2ae9b3c8d92
0
socialsensor/socialsensor-query-builder
package eu.socialsensor.sfc.builder.ranking; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import eu.socialsensor.framework.client.search.solr.SolrDyscoHandler; import eu.socialsensor.framework.client.search.solr.SolrItemHandler; import eu.socialsensor.framework.common.domain.Item; import eu.socialsensor.framework.common.domain.Query; import eu.socialsensor.framework.common.domain.dysco.Dysco; import eu.socialsensor.sfc.builder.solrQueryBuilder.Calculator; public class TrendsRanker { private static Long DAY_IN_MILLISECONDS = 86400000L; private SolrItemHandler solrItemHandler; private Dysco dysco; private List<Dysco> dyscos; public TrendsRanker(String solrCollection){ try { solrItemHandler = SolrItemHandler.getInstance(solrCollection); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Double getScore(Dysco dysco){ Double score = 0.0; List<Query> solrQueries = dysco.getPrimalSolrQueries(); List<Float> queriesScores = new ArrayList<Float>(); for(Query sQuery : solrQueries){ float queryLength = sQuery.getName().length(); //System.out.println("Query Length : "+queryLength); String query = "(title : ("+sQuery.getName()+")) OR (description : ("+sQuery.getName()+"))"; //System.out.println("Query : "+query); Map<Item,Float> itemsByRelevance = solrItemHandler.findItemsWithScore(query); //System.out.println(); float avgScore = Calculator.computeAverageFloat(itemsByRelevance.values()); //System.out.println("Average score for query : "+query + " ->> "+avgScore); avgScore *= (queryLength/10); //System.out.println("Average score for query : "+query + " ->> "+avgScore); //System.out.println(); queriesScores.add(avgScore); } long dateTimeOfDysco = dysco.getCreationDate().getTime(); long currentDateTime = System.currentTimeMillis(); double timeDiff = (double) Math.abs(dateTimeOfDysco - currentDateTime)/DAY_IN_MILLISECONDS; double timeEval = Math.sqrt(20/(20 + (Math.exp(timeDiff)))); //System.out.println("Time diff : "+timeDiff); //System.out.println("Time eval : "+timeEval); score = Calculator.computeAverageFloat(queriesScores) * timeEval; //System.out.println("Total Average score for dysco : "+score); return score; } public List<Dysco> rankDyscos(List<Dysco> dyscos){ List<Dysco> rankedDyscos = new LinkedList<Dysco>(); Map<Double,List<Dysco>> dyscosByValues = new TreeMap<Double,List<Dysco>>(Collections.reverseOrder()); for(Dysco dysco : dyscos){ Double score = getScore(dysco); if(dyscosByValues.get(score) == null){ List<Dysco> alreadyIn = new ArrayList<Dysco>(); alreadyIn.add(dysco); dyscosByValues.put(score, alreadyIn); } else{ List<Dysco> alreadyIn = dyscosByValues.get(score); alreadyIn.add(dysco); dyscosByValues.put(score, alreadyIn); } } for(Map.Entry<Double, List<Dysco>> entry : dyscosByValues.entrySet()){ for(Dysco dysco : entry.getValue()){ rankedDyscos.add(dysco); } } return rankedDyscos; } /** * @param args */ public static void main(String[] args) { } }
src/main/java/eu/socialsensor/sfc/builder/ranking/TrendsRanker.java
package eu.socialsensor.sfc.builder.ranking; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import eu.socialsensor.framework.client.search.solr.SolrDyscoHandler; import eu.socialsensor.framework.client.search.solr.SolrItemHandler; import eu.socialsensor.framework.common.domain.Item; import eu.socialsensor.framework.common.domain.Query; import eu.socialsensor.framework.common.domain.dysco.Dysco; import eu.socialsensor.sfc.builder.solrQueryBuilder.Calculator; public class TrendsRanker { private static Long DAY_IN_MILLISECONDS = 86400000L; private SolrItemHandler solrItemHandler; private Dysco dysco; private List<Dysco> dyscos; public TrendsRanker(String solrCollection){ try { solrItemHandler = SolrItemHandler.getInstance(solrCollection); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public Double getScore(Dysco dysco){ Double score = 0.0; List<Query> solrQueries = dysco.getPrimalSolrQueries(); List<Float> queriesScores = new ArrayList<Float>(); for(Query sQuery : solrQueries){ float queryLength = sQuery.getName().length(); //System.out.println("Query Length : "+queryLength); String query = "(title : ("+sQuery.getName()+")) OR (description : ("+sQuery.getName()+"))"; //System.out.println("Query : "+query); Map<Item,Float> itemsByRelevance = solrItemHandler.findItemsWithScore(query); //System.out.println(); float avgScore = Calculator.computeAverageFloat(itemsByRelevance.values()); //System.out.println("Average score for query : "+query + " ->> "+avgScore); avgScore *= (queryLength/10); //System.out.println("Average score for query : "+query + " ->> "+avgScore); //System.out.println(); queriesScores.add(avgScore); } long dateTimeOfDysco = dysco.getCreationDate().getTime(); long currentDateTime = System.currentTimeMillis(); double timeDiff = (double) Math.abs(dateTimeOfDysco - currentDateTime)/DAY_IN_MILLISECONDS; double timeEval = Math.sqrt(20/(20 + (Math.exp(timeDiff)))); //System.out.println("Time diff : "+timeDiff); //System.out.println("Time eval : "+timeEval); score = Calculator.computeAverageFloat(queriesScores) * timeEval; //System.out.println("Total Average score for dysco : "+score); return score; } public List<Dysco> rankDyscos(List<Dysco> dyscos){ List<Dysco> rankedDyscos = new LinkedList<Dysco>(); Map<Double,List<Dysco>> dyscosByValues = new TreeMap<Double,List<Dysco>>(Collections.reverseOrder()); for(Dysco dysco : dyscos){ Double score = getScore(dysco); if(dyscosByValues.get(score) == null){ List<Dysco> alreadyIn = new ArrayList<Dysco>(); alreadyIn.add(dysco); dyscosByValues.put(score, alreadyIn); } else{ List<Dysco> alreadyIn = dyscosByValues.get(score); alreadyIn.add(dysco); dyscosByValues.put(score, alreadyIn); } } for(Map.Entry<Double, List<Dysco>> entry : dyscosByValues.entrySet()){ for(Dysco dysco : entry.getValue()){ rankedDyscos.add(dysco); } } return rankedDyscos; } /** * @param args */ public static void main(String[] args) { SolrDyscoHandler solrDyscoHandler = SolrDyscoHandler.getInstance("http://social1.atc.gr:8080/solr/dyscos"); Dysco testDysco = solrDyscoHandler.findDyscoLight("4adac785-2f1e-4941-b518-9f2bfa93b35a"); TrendsRanker ranker = new TrendsRanker("http://160.40.50.230:8080/solr/NewsFeed"); ranker.getScore(testDysco); } }
removed prints from ranker
src/main/java/eu/socialsensor/sfc/builder/ranking/TrendsRanker.java
removed prints from ranker
<ide><path>rc/main/java/eu/socialsensor/sfc/builder/ranking/TrendsRanker.java <ide> * @param args <ide> */ <ide> public static void main(String[] args) { <del> SolrDyscoHandler solrDyscoHandler = SolrDyscoHandler.getInstance("http://social1.atc.gr:8080/solr/dyscos"); <del> <del> Dysco testDysco = solrDyscoHandler.findDyscoLight("4adac785-2f1e-4941-b518-9f2bfa93b35a"); <ide> <del> TrendsRanker ranker = new TrendsRanker("http://160.40.50.230:8080/solr/NewsFeed"); <del> ranker.getScore(testDysco); <ide> } <ide> <ide> }
JavaScript
mit
ca7b3fac6b9b23e455a63d90880f079ed5b23c9b
0
kalleth/static,kalleth/static,tadast/static,robinwhittleton/static,alphagov/static,alphagov/static,tadast/static,robinwhittleton/static,robinwhittleton/static,kalleth/static,alphagov/static,tadast/static,kalleth/static,robinwhittleton/static,tadast/static
/*globals $, GOVUK, suchi */ /*jslint white: true, browser: true */ $(function() { "use strict"; function browserWarning() { var container = $('<div id="global-browser-prompt"></div>'), text = $('<p><a href="/help/browsers">Upgrade your web browser</a> (the software you use to access the internet), it’s out of date</p>'), closeLink = $('<a href="#" class="dismiss" title="Dismiss this message">Close</a>'); return container.append(text.append(closeLink)); } // we don't show the message when the cookie warning is also there if (GOVUK.cookie('seen_cookie_message')) { if (suchi.isOld(navigator.userAgent)) { if(GOVUK.cookie('govuk_not_first_visit') !== null && GOVUK.cookie('govuk_browser_upgrade_dismissed') === null){ var $prompt = browserWarning(); $('#global-cookie-message').after($prompt); $prompt.show(); window._gaq && _gaq.push(['_trackEvent', 'browser-check', 'prompt-shown', '', 1, true]); $prompt.on("click", ".dismiss", function(e) { $prompt.hide(); // the warning is dismissable for 4 weeks, for users who are not in a // position to upgrade right now or unable to (no control of browser) GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 28 }); }); } } // We're not showing the message on first visit GOVUK.cookie('govuk_not_first_visit', 'yes', { days: 28 }); } });
app/assets/javascripts/browser-check.js
/*globals $, GOVUK, suchi */ /*jslint white: true, browser: true */ $(function() { "use strict"; function browserWarning() { var container = $('<div id="global-browser-prompt"></div>'), text = $('<p><a href="/help/browsers">Upgrade your web browser</a> (the software you use to access the internet), it’s out of date</p>'), closeLink = $('<a href="#" class="dismiss" title="Dismiss this message">Close</a>'); return container.append(text.append(closeLink)); } // we don't show the message when the cookie warning is also there if (GOVUK.cookie('seen_cookie_message')) { if (suchi.isOld(navigator.userAgent)) { if(GOVUK.cookie('govuk_not_first_visit') !== null && GOVUK.cookie('govuk_browser_upgrade_dismissed') === null){ var $prompt = browserWarning(); $('#global-cookie-message').after($prompt); $prompt.show(); $prompt.on("click", ".dismiss", function(e) { $prompt.hide(); // the warning is dismissable for 4 weeks, for users who are not in a // position to upgrade right now or unable to (no control of browser) GOVUK.cookie('govuk_browser_upgrade_dismissed', 'yes', { days: 28 }); }); } } // We're not showing the message on first visit GOVUK.cookie('govuk_not_first_visit', 'yes', { days: 28 }); } });
Track when we show the browser upgrade prompt At the moment it's getting quite a lot of negative feedback, and knowing who actually sees it will help use decide how to respond to that. We've been inferring this from traffic to the /help/browsers page, but that only captures users who are clicking on the banner. This will record exactlty who sees it.
app/assets/javascripts/browser-check.js
Track when we show the browser upgrade prompt
<ide><path>pp/assets/javascripts/browser-check.js <ide> var $prompt = browserWarning(); <ide> $('#global-cookie-message').after($prompt); <ide> $prompt.show(); <add> window._gaq && _gaq.push(['_trackEvent', 'browser-check', 'prompt-shown', '', 1, true]); <ide> $prompt.on("click", ".dismiss", function(e) { <ide> $prompt.hide(); <ide> // the warning is dismissable for 4 weeks, for users who are not in a
Java
mit
e910d277bbe9a6a572d1b49f1f0e9b9aae1723f0
0
Clarifai/clarifai-api-java
package com.clarifai.samples.clirecognizer; import java.io.File; import java.io.IOException; import java.util.List; import com.clarifai.api.ClarifaiClient; import com.clarifai.api.RecognitionRequest; import com.clarifai.api.RecognitionResult; import com.clarifai.api.RecognitionResult.StatusCode; import com.clarifai.api.Tag; import com.clarifai.api.VideoSegment; /** * A command-line tool that allows you to send images to the Clarifai API for recognition. */ public class Main { public static void main(String[] args) throws IOException { if (args.length == 0) { System.err.println("Please pass 1 or more filenames or URLs as arguments."); return; } // Construct a client. This constructor reads the app ID and secret from environment variables. ClarifaiClient client = new ClarifaiClient(); // The client can accept publicly-accessible URLs, local files, or image/video bytes. For // this example, we will send URLs or files depending on the command-line arguments: RecognitionRequest request; if (args[0].toLowerCase().startsWith("http:") || args[0].toLowerCase().startsWith("https:")) { // Pass the URLs to the recognition API. request = new RecognitionRequest(args); } else { // Pass the files to the recognition API. File[] files = new File[args.length]; for (int i = 0; i < args.length; i++) { files[i] = new File(args[i]); } request = new RecognitionRequest(files); } // Send the request to the server for recognition. In a real application, we might want to // customize the RecognitionRequest first or catch and handle the ClarifaiException that this // call might throw. See the documentation for each of these classes for details. List<RecognitionResult> results = client.recognize(request); // We now have a result. For this sample, we're just going to print out the tags. for (int i = 0; i < results.size(); i++) { RecognitionResult result = results.get(i); // Each result contains a status code indicating whether the recognition succeeded or failed. System.out.println("\nResult for " + args[i] + ": " + result.getStatusCode()); if (result.getStatusCode() == StatusCode.OK) { List<VideoSegment> segments = result.getVideoSegments(); if (segments != null) { // If the input was a video, we get back a list of VideoSegments. for (VideoSegment segment : segments) { System.out.println(String.format("\n At time %.3f:", segment.getTimestampSeconds())); printTags(segment.getTags()); } } else { printTags(result.getTags()); } } else { System.out.println(" Failed: " + result.getStatusMessage()); } } } private static void printTags(List<Tag> tags) { for (Tag tag : tags) { // Each tag contains a name and probability assigned to it by the recognition engine. System.out.println(String.format(" %s (%.4f)", tag.getName(), tag.getProbability())); } } }
samples/command-line/src/main/java/com/clarifai/samples/clirecognizer/Main.java
package com.clarifai.samples.clirecognizer; import java.io.File; import java.io.IOException; import java.util.List; import com.clarifai.api.ClarifaiClient; import com.clarifai.api.RecognitionRequest; import com.clarifai.api.RecognitionResult; import com.clarifai.api.RecognitionResult.StatusCode; import com.clarifai.api.Tag; /** * A command-line tool that allows you to send images to the Clarifai API for recognition. */ public class Main { public static void main(String[] args) throws IOException { if (args.length == 0) { System.err.println("Please pass 1 or more filenames or URLs as arguments."); return; } // Construct a client. This constructor reads the app ID and secret from environment variables. ClarifaiClient client = new ClarifaiClient(); // Send the file bytes or URLs up to the Clarifai API. List<RecognitionResult> results; if (args[0].toLowerCase().startsWith("http:") || args[0].toLowerCase().startsWith("https:")) { // Pass the URLs to the recognition API. results = client.recognize(new RecognitionRequest(args)); } else { // Pass the files to the recognition API. File[] files = new File[args.length]; for (int i = 0; i < args.length; i++) { files[i] = new File(args[i]); } results = client.recognize(new RecognitionRequest(files)); } // Print out the results: for (int i = 0; i < results.size(); i++) { RecognitionResult result = results.get(i); // Each result contains a status code indicating whether the recognition succeeded or failed. System.out.println("\nResult for " + args[i] + ": " + result.getStatusCode()); if (result.getStatusCode() == StatusCode.OK) { for (Tag tag : result.getTags()) { // Each tag contains a name and probability assigned to it by the recognition engine. System.out.println(String.format(" %s (%.4f)", tag.getName(), tag.getProbability())); } } else { System.out.println(" Status message: " + result.getStatusMessage()); } } } }
Show video example in the sample
samples/command-line/src/main/java/com/clarifai/samples/clirecognizer/Main.java
Show video example in the sample
<ide><path>amples/command-line/src/main/java/com/clarifai/samples/clirecognizer/Main.java <ide> import com.clarifai.api.RecognitionResult; <ide> import com.clarifai.api.RecognitionResult.StatusCode; <ide> import com.clarifai.api.Tag; <add>import com.clarifai.api.VideoSegment; <ide> <ide> /** <ide> * A command-line tool that allows you to send images to the Clarifai API for recognition. <ide> // Construct a client. This constructor reads the app ID and secret from environment variables. <ide> ClarifaiClient client = new ClarifaiClient(); <ide> <del> // Send the file bytes or URLs up to the Clarifai API. <del> List<RecognitionResult> results; <add> // The client can accept publicly-accessible URLs, local files, or image/video bytes. For <add> // this example, we will send URLs or files depending on the command-line arguments: <add> RecognitionRequest request; <ide> if (args[0].toLowerCase().startsWith("http:") || args[0].toLowerCase().startsWith("https:")) { <ide> // Pass the URLs to the recognition API. <del> results = client.recognize(new RecognitionRequest(args)); <add> request = new RecognitionRequest(args); <ide> } else { <ide> // Pass the files to the recognition API. <ide> File[] files = new File[args.length]; <ide> for (int i = 0; i < args.length; i++) { <ide> files[i] = new File(args[i]); <ide> } <del> results = client.recognize(new RecognitionRequest(files)); <add> request = new RecognitionRequest(files); <ide> } <ide> <del> // Print out the results: <add> // Send the request to the server for recognition. In a real application, we might want to <add> // customize the RecognitionRequest first or catch and handle the ClarifaiException that this <add> // call might throw. See the documentation for each of these classes for details. <add> List<RecognitionResult> results = client.recognize(request); <add> <add> // We now have a result. For this sample, we're just going to print out the tags. <ide> for (int i = 0; i < results.size(); i++) { <ide> RecognitionResult result = results.get(i); <ide> <ide> // Each result contains a status code indicating whether the recognition succeeded or failed. <ide> System.out.println("\nResult for " + args[i] + ": " + result.getStatusCode()); <ide> if (result.getStatusCode() == StatusCode.OK) { <del> for (Tag tag : result.getTags()) { <del> // Each tag contains a name and probability assigned to it by the recognition engine. <del> System.out.println(String.format(" %s (%.4f)", tag.getName(), tag.getProbability())); <add> List<VideoSegment> segments = result.getVideoSegments(); <add> if (segments != null) { <add> // If the input was a video, we get back a list of VideoSegments. <add> for (VideoSegment segment : segments) { <add> System.out.println(String.format("\n At time %.3f:", segment.getTimestampSeconds())); <add> printTags(segment.getTags()); <add> } <add> } else { <add> printTags(result.getTags()); <ide> } <ide> } else { <del> System.out.println(" Status message: " + result.getStatusMessage()); <add> System.out.println(" Failed: " + result.getStatusMessage()); <ide> } <ide> } <ide> } <add> <add> private static void printTags(List<Tag> tags) { <add> for (Tag tag : tags) { <add> // Each tag contains a name and probability assigned to it by the recognition engine. <add> System.out.println(String.format(" %s (%.4f)", tag.getName(), tag.getProbability())); <add> } <add> } <ide> }
Java
apache-2.0
8aaf1239d6d7c4021cd7a8d7b6c0ffa15fdcff6a
0
aika-algorithm/aika,aika-algorithm/aika
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package network.aika.neuron; import network.aika.*; import network.aika.lattice.OrNode; import network.aika.neuron.activation.Activation; import network.aika.neuron.activation.Range; import network.aika.neuron.activation.SearchNode; import network.aika.lattice.InputNode; import network.aika.neuron.relation.Relation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*; import java.util.stream.Collectors; /** * The {@code INeuron} class represents a internal neuron implementation in Aikas neural network and is connected to other neurons through * input synapses and output synapses. The activation value of a neuron is calculated by computing the weighted sum * (input act. value * synapse weight) of the input synapses, adding the bias to it and sending the resulting value * through a transfer function (the upper part of tanh). * <p> * <p>The neuron does not store its activations by itself. The activation objects are stored within the * logic nodes. To access the activations of this neuron simply use the member variable {@code node} or use * the method {@code getFinalActivations(Document doc)} to ge the final activations of this neuron. * * @author Lukas Molzberger */ public class INeuron extends AbstractNode<Neuron, Activation> implements Comparable<INeuron> { public static boolean ALLOW_WEAK_NEGATIVE_WEIGHTS = false; private static final Logger log = LoggerFactory.getLogger(INeuron.class); public static double WEIGHT_TOLERANCE = 0.001; public static double TOLERANCE = 0.000001; public String label; public Type type; public enum Type { EXCITATORY, INHIBITORY } public LogicType logicType; public enum LogicType { CONJUNCTIVE, DISJUNCTIVE } public String outputText; public volatile double bias; public volatile double biasDelta; public volatile double biasSum; public volatile double biasSumDelta; public volatile double posDirSum; public volatile double negDirSum; public volatile double negRecSum; public volatile double posRecSum; public volatile double posPassiveSum; public volatile double requiredSum; public volatile int numDisjunctiveSynapses = 0; public Writable statistic; public ActivationFunction activationFunction = ActivationFunction.RECTIFIED_SCALED_LOGISTIC_SIGMOID; public int numberOfInputSynapses = 0; // synapseId -> relation public Map<Integer, Relation> outputRelations; // A synapse is stored only in one direction, depending on the synapse weight. public TreeMap<Synapse, Synapse> inputSynapses = new TreeMap<>(Synapse.INPUT_SYNAPSE_COMP); public TreeMap<Synapse, Synapse> outputSynapses = new TreeMap<>(Synapse.OUTPUT_SYNAPSE_COMP); public TreeMap<Synapse, Synapse> passiveInputSynapses = null; public Provider<InputNode> outputNode; public Provider<OrNode> node; public ReadWriteLock lock = new ReadWriteLock(); public PassiveInputFunction passiveInputFunction = null; public ThreadState[] threads; /** * The {@code ThreadState} is a thread local data structure containing the activations of a single document for * a specific logic node. */ public static class ThreadState { public long lastUsed; private TreeMap<ActKey, Activation> activations; private TreeMap<ActKey, Activation> activationsEnd; public int minLength = Integer.MAX_VALUE; public int maxLength = 0; public ThreadState() { activations = new TreeMap<>(BEGIN_COMP); activationsEnd = new TreeMap<>(END_COMP); } public void addActivation(Activation act) { ActKey ak = new ActKey(act.range, act.id); activations.put(ak, act); TreeMap<ActKey, Activation> actEnd = activationsEnd; if (actEnd != null) actEnd.put(ak, act); } public Collection<Activation> getActivations() { return activations.values(); } public boolean isEmpty() { return activations.isEmpty(); } public int size() { return activations.size(); } public void clearActivations() { activations.clear(); if (activationsEnd != null) activationsEnd.clear(); } public Collection<Activation> getActivationsByRangeBegin(Range fromKey, boolean fromInclusive, Range toKey, boolean toInclusive) { return activations.subMap( new INeuron.ActKey(fromKey, Integer.MIN_VALUE), fromInclusive, new INeuron.ActKey(toKey, Integer.MAX_VALUE), toInclusive ).values(); } public Collection<Activation> getActivationsByRangeEnd(Range fromKey, boolean fromInclusive, Range toKey, boolean toInclusive) { return activationsEnd.subMap( new INeuron.ActKey(fromKey, Integer.MIN_VALUE), fromInclusive, new INeuron.ActKey(toKey, Integer.MAX_VALUE), toInclusive ).values(); } public Activation getActivationByRange(Range r) { Map.Entry<ActKey, Activation> me = activations.higherEntry(new ActKey(r, Integer.MIN_VALUE)); if(me != null && me.getValue().range.equals(r)) { return me.getValue(); } return null; } public Collection<Activation> getActivations(boolean onlyFinal) { return onlyFinal ? activations .values() .stream() .filter(act -> act.isFinalActivation()) .collect(Collectors.toList()) : getActivations(); } } public static final Comparator<ActKey> BEGIN_COMP = (ak1, ak2) -> { int r = Range.BEGIN_COMP.compare(ak1.r, ak2.r); if(r != 0) return r; return Integer.compare(ak1.actId, ak2.actId); }; public static final Comparator<ActKey> END_COMP = (ak1, ak2) -> { int r = Range.END_COMP.compare(ak1.r, ak2.r); if(r != 0) return r; return Integer.compare(ak1.actId, ak2.actId); }; public static class ActKey { Range r; int actId; public ActKey(Range r, int actId) { this.r = r; this.actId = actId; } } public ThreadState getThreadState(int threadId, boolean create) { ThreadState th = threads[threadId]; if (th == null) { if (!create) return null; th = new ThreadState(); threads[threadId] = th; } th.lastUsed = provider.model.docIdCounter.get(); return th; } private INeuron() { } public INeuron(Model m) { this(m, null); } public INeuron(Model m, String label) { this(m, label, null); } public INeuron(Model m, String label, String outputText) { this.label = label; this.outputText = outputText; if(m.getNeuronStatisticFactory() != null) { statistic = m.getNeuronStatisticFactory().createObject(); } threads = new ThreadState[m.numberOfThreads]; provider = new Neuron(m, this); OrNode node = new OrNode(m); node.neuron = provider; this.node = node.provider; setModified(); } /** * Propagate an input activation into the network. * * @param doc The current document * @param input */ public Activation addInput(Document doc, Activation.Builder input) { assert input.range.begin <= input.range.end; Activation act = getThreadState(doc.threadId, true).getActivationByRange(input.range); if(act == null) { act = new Activation(doc.activationIdCounter++, doc, node.get(doc)); act.range = input.range; } register(act); Activation.State s = new Activation.State(input.value, input.value, 1.0, 0.0, 0.0, input.fired, 0.0); act.rounds.set(0, s); act.avgState = s; act.inputValue = input.value; act.upperBound = input.value; act.lowerBound = input.value; act.inputDecision = SearchNode.Decision.SELECTED; act.finalDecision = act.inputDecision; act.setDecision(act.inputDecision, doc.visitedCounter++); act.setTargetValue(input.targetValue); doc.inputNeuronActivations.add(act); doc.finallyActivatedNeurons.add(act.getINeuron()); propagate(act); doc.propagate(); return act; } // TODO public void remove() { clearActivations(); for (Synapse s : inputSynapses.values()) { INeuron in = s.input.get(); in.provider.lock.acquireWriteLock(); in.provider.inMemoryOutputSynapses.remove(s); in.provider.lock.releaseWriteLock(); } provider.lock.acquireReadLock(); for (Synapse s : provider.inMemoryOutputSynapses.values()) { INeuron out = s.output.get(); out.lock.acquireWriteLock(); out.inputSynapses.remove(s); out.lock.releaseWriteLock(); } provider.lock.releaseReadLock(); } public void propagate(Activation act) { Document doc = act.doc; outputNode.get(doc).addActivation(act); } public Collection<Activation> getActivations(Document doc, boolean onlyFinal) { ThreadState th = getThreadState(doc.threadId, false); if (th == null) return Collections.EMPTY_LIST; return th.getActivations(onlyFinal); } public Activation getActivation(Document doc, Range r, boolean onlyFinal) { ThreadState th = getThreadState(doc.threadId, false); if (th == null) return null; for(Activation act : th.getActivationsByRangeBegin(r, true, r, false)) { if (!onlyFinal || act.isFinalActivation()) { return act; } } return null; } public void clearActivations() { for (int i = 0; i < provider.model.numberOfThreads; i++) { clearActivations(i); } } public void clearActivations(Document doc) { clearActivations(doc.threadId); } public void clearActivations(int threadId) { ThreadState th = getThreadState(threadId, false); if (th == null) return; th.clearActivations(); } public int compareTo(INeuron n) { if (provider.id < n.provider.id) return -1; else if (provider.id > n.provider.id) return 1; else return 0; } @Override public void write(DataOutput out) throws IOException { out.writeBoolean(true); out.writeBoolean(label != null); if(label != null) { out.writeUTF(label); } out.writeBoolean(type != null); if(type != null) { out.writeUTF(type.name()); } out.writeBoolean(logicType != null); if(logicType != null) { out.writeUTF(logicType.name()); } out.writeBoolean(outputText != null); if(outputText != null) { out.writeUTF(outputText); } out.writeBoolean(statistic != null); if(statistic != null) { statistic.write(out); } out.writeDouble(bias); out.writeDouble(biasSum); out.writeDouble(posDirSum); out.writeDouble(negDirSum); out.writeDouble(negRecSum); out.writeDouble(posRecSum); out.writeDouble(posPassiveSum); out.writeDouble(requiredSum); out.writeInt(numDisjunctiveSynapses); out.writeUTF(activationFunction.name()); out.writeInt(outputNode.id); out.writeBoolean(node != null); if (node != null) { out.writeInt(node.id); } out.writeInt(numberOfInputSynapses); for (Synapse s : inputSynapses.values()) { if (s.input != null) { out.writeBoolean(true); s.write(out); } } out.writeBoolean(false); for (Synapse s : outputSynapses.values()) { if (s.output != null) { out.writeBoolean(true); s.write(out); } } out.writeBoolean(false); if(outputRelations != null) { out.writeInt(outputRelations.size()); for (Map.Entry<Integer, Relation> me : outputRelations.entrySet()) { out.writeInt(me.getKey()); me.getValue().write(out); } } else { out.writeInt(0); } } @Override public void readFields(DataInput in, Model m) throws IOException { if(in.readBoolean()) { label = in.readUTF(); } if(in.readBoolean()) { type = Type.valueOf(in.readUTF()); } if(in.readBoolean()) { logicType = LogicType.valueOf(in.readUTF()); } if(in.readBoolean()) { outputText = in.readUTF(); } if(in.readBoolean()) { statistic = m.getNeuronStatisticFactory().createObject(); statistic.readFields(in, m); } bias = in.readDouble(); biasSum = in.readDouble(); posDirSum = in.readDouble(); negDirSum = in.readDouble(); negRecSum = in.readDouble(); posRecSum = in.readDouble(); posPassiveSum = in.readDouble(); requiredSum = in.readDouble(); numDisjunctiveSynapses = in.readInt(); activationFunction = ActivationFunction.valueOf(in.readUTF()); outputNode = m.lookupNodeProvider(in.readInt()); if (in.readBoolean()) { Integer nId = in.readInt(); node = m.lookupNodeProvider(nId); } numberOfInputSynapses = in.readInt(); while (in.readBoolean()) { Synapse syn = Synapse.read(in, m); inputSynapses.put(syn, syn); if(syn.input.get().isPassiveInputNeuron()) { registerPassiveInputSynapse(syn); } } while (in.readBoolean()) { Synapse syn = Synapse.read(in, m); outputSynapses.put(syn, syn); if(isPassiveInputNeuron()) { syn.output.get().registerPassiveInputSynapse(syn); } } int l = in.readInt(); if(l > 0) { outputRelations = new TreeMap<>(); for(int i = 0; i < l; i++) { int synId = in.readInt(); Relation r = Relation.read(in, m); outputRelations.put(synId, r); } } passiveInputFunction = m.passiveActivationFunctions.get(provider.id); } @Override public void suspend() { for (Synapse s : inputSynapses.values()) { s.input.removeInMemoryOutputSynapse(s); } for (Synapse s : outputSynapses.values()) { s.output.removeInMemoryInputSynapse(s); } provider.lock.acquireReadLock(); for (Synapse s : provider.inMemoryInputSynapses.values()) { if(!s.isConjunction) { s.input.removeInMemoryOutputSynapse(s); } } for (Synapse s : provider.inMemoryOutputSynapses.values()) { if(s.isConjunction) { s.output.removeInMemoryInputSynapse(s); } } provider.lock.releaseReadLock(); } @Override public void reactivate() { provider.lock.acquireReadLock(); for (Synapse s : provider.inMemoryInputSynapses.values()) { if(!s.isConjunction) { s.input.addInMemoryOutputSynapse(s); } } for (Synapse s : provider.inMemoryOutputSynapses.values()) { if(s.isConjunction) { s.output.addInMemoryInputSynapse(s); } } provider.lock.releaseReadLock(); for (Synapse s : inputSynapses.values()) { s.input.addInMemoryOutputSynapse(s); if (!s.input.isSuspended()) { s.output.addInMemoryInputSynapse(s); } } for (Synapse s : outputSynapses.values()) { s.output.addInMemoryInputSynapse(s); if (!s.output.isSuspended()) { s.input.addInMemoryOutputSynapse(s); } } } public void setBias(double b) { double newBiasDelta = b - bias; biasSumDelta += newBiasDelta - biasDelta; biasDelta = newBiasDelta; } public void changeBias(double bd) { biasDelta += bd; biasSumDelta += bd; } public double getNewBiasSum() { return biasSum + biasSumDelta; } public void register(Activation act) { Document doc = act.doc; INeuron.ThreadState th = act.node.neuron.get().getThreadState(doc.threadId, true); if (th.isEmpty()) { doc.activatedNeurons.add(act.node.neuron.get()); } th.minLength = Math.min(th.minLength, act.range.length()); th.maxLength = Math.max(th.maxLength, act.range.length()); th.addActivation(act); doc.addActivation(act); } public static boolean update(int threadId, Document doc, Neuron pn, Double bias, Collection<Synapse> modifiedSynapses) { INeuron n = pn.get(); if(bias != null) { n.setBias(bias); } // s.link requires an updated n.biasSumDelta value. modifiedSynapses.forEach(s -> s.link()); return Converter.convert(threadId, doc, n, modifiedSynapses); } public static INeuron readNeuron(DataInput in, Neuron p) throws IOException { INeuron n = new INeuron(); n.provider = p; n.threads = new ThreadState[p.model.numberOfThreads]; n.readFields(in, p.model); return n; } public boolean isPassiveInputNeuron() { return passiveInputFunction != null; } public void registerPassiveInputSynapse(Synapse s) { if(passiveInputSynapses == null) { passiveInputSynapses = new TreeMap<>(Synapse.INPUT_SYNAPSE_COMP); } passiveInputSynapses.put(s, s); } public String toString() { return label; } public String toStringWithSynapses() { SortedSet<Synapse> is = new TreeSet<>((s1, s2) -> { int r = Double.compare(s2.weight, s1.weight); if (r != 0) return r; return Integer.compare(s1.input.id, s2.input.id); }); is.addAll(inputSynapses.values()); StringBuilder sb = new StringBuilder(); sb.append(toString()); sb.append("<"); sb.append("B:"); sb.append(Utils.round(biasSum)); for (Synapse s : is) { sb.append(", "); sb.append(Utils.round(s.weight)); sb.append(":"); sb.append(s.input.toString()); } sb.append(">"); return sb.toString(); } }
src/main/java/network/aika/neuron/INeuron.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package network.aika.neuron; import network.aika.*; import network.aika.lattice.OrNode; import network.aika.neuron.activation.Activation; import network.aika.neuron.activation.Range; import network.aika.neuron.activation.SearchNode; import network.aika.lattice.InputNode; import network.aika.neuron.relation.Relation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.*; import java.util.stream.Collectors; /** * The {@code INeuron} class represents a internal neuron implementation in Aikas neural network and is connected to other neurons through * input synapses and output synapses. The activation value of a neuron is calculated by computing the weighted sum * (input act. value * synapse weight) of the input synapses, adding the bias to it and sending the resulting value * through a transfer function (the upper part of tanh). * <p> * <p>The neuron does not store its activations by itself. The activation objects are stored within the * logic nodes. To access the activations of this neuron simply use the member variable {@code node} or use * the method {@code getFinalActivations(Document doc)} to ge the final activations of this neuron. * * @author Lukas Molzberger */ public class INeuron extends AbstractNode<Neuron, Activation> implements Comparable<INeuron> { public static boolean ALLOW_WEAK_NEGATIVE_WEIGHTS = false; private static final Logger log = LoggerFactory.getLogger(INeuron.class); public static double WEIGHT_TOLERANCE = 0.001; public static double TOLERANCE = 0.000001; public String label; public Type type; public enum Type { EXCITATORY, INHIBITORY } public LogicType logicType; public enum LogicType { CONJUNCTIVE, DISJUNCTIVE } public String outputText; public volatile double bias; public volatile double biasDelta; public volatile double biasSum; public volatile double biasSumDelta; public volatile double posDirSum; public volatile double negDirSum; public volatile double negRecSum; public volatile double posRecSum; public volatile double posPassiveSum; public volatile double requiredSum; public volatile int numDisjunctiveSynapses = 0; public Writable statistic; public ActivationFunction activationFunction = ActivationFunction.RECTIFIED_SCALED_LOGISTIC_SIGMOID; public int numberOfInputSynapses = 0; // synapseId -> relation public Map<Integer, Relation> outputRelations; // A synapse is stored only in one direction, depending on the synapse weight. public TreeMap<Synapse, Synapse> inputSynapses = new TreeMap<>(Synapse.INPUT_SYNAPSE_COMP); public TreeMap<Synapse, Synapse> outputSynapses = new TreeMap<>(Synapse.OUTPUT_SYNAPSE_COMP); public TreeMap<Synapse, Synapse> passiveInputSynapses = null; public Provider<InputNode> outputNode; public Provider<OrNode> node; public ReadWriteLock lock = new ReadWriteLock(); public PassiveInputFunction passiveInputFunction = null; public ThreadState[] threads; /** * The {@code ThreadState} is a thread local data structure containing the activations of a single document for * a specific logic node. */ public static class ThreadState { public long lastUsed; private TreeMap<ActKey, Activation> activations; private TreeMap<ActKey, Activation> activationsEnd; public int minLength = Integer.MAX_VALUE; public int maxLength = 0; public ThreadState() { activations = new TreeMap<>(BEGIN_COMP); activationsEnd = new TreeMap<>(END_COMP); } public void addActivation(Activation act) { ActKey ak = new ActKey(act.range, act.id); activations.put(ak, act); TreeMap<ActKey, Activation> actEnd = activationsEnd; if (actEnd != null) actEnd.put(ak, act); } public Collection<Activation> getActivations() { return activations.values(); } public boolean isEmpty() { return activations.isEmpty(); } public int size() { return activations.size(); } public void clearActivations() { activations.clear(); if (activationsEnd != null) activationsEnd.clear(); } public Collection<Activation> getActivationsByRangeBegin(Range fromKey, boolean fromInclusive, Range toKey, boolean toInclusive) { return activations.subMap( new INeuron.ActKey(fromKey, Integer.MIN_VALUE), fromInclusive, new INeuron.ActKey(toKey, Integer.MAX_VALUE), toInclusive ).values(); } public Collection<Activation> getActivationsByRangeEnd(Range fromKey, boolean fromInclusive, Range toKey, boolean toInclusive) { return activationsEnd.subMap( new INeuron.ActKey(fromKey, Integer.MIN_VALUE), fromInclusive, new INeuron.ActKey(toKey, Integer.MAX_VALUE), toInclusive ).values(); } public Activation getActivationByRange(Range r) { Map.Entry<ActKey, Activation> me = activations.higherEntry(new ActKey(r, Integer.MIN_VALUE)); if(me != null && me.getValue().range.equals(r)) { return me.getValue(); } return null; } public Collection<Activation> getActivations(boolean onlyFinal) { return onlyFinal ? activations .values() .stream() .filter(act -> act.isFinalActivation()) .collect(Collectors.toList()) : getActivations(); } } public static final Comparator<ActKey> BEGIN_COMP = (ak1, ak2) -> { int r = Range.BEGIN_COMP.compare(ak1.r, ak2.r); if(r != 0) return r; return Integer.compare(ak1.actId, ak2.actId); }; public static final Comparator<ActKey> END_COMP = (ak1, ak2) -> { int r = Range.END_COMP.compare(ak1.r, ak2.r); if(r != 0) return r; return Integer.compare(ak1.actId, ak2.actId); }; public static class ActKey { Range r; int actId; public ActKey(Range r, int actId) { this.r = r; this.actId = actId; } } public ThreadState getThreadState(int threadId, boolean create) { ThreadState th = threads[threadId]; if (th == null) { if (!create) return null; th = new ThreadState(); threads[threadId] = th; } th.lastUsed = provider.model.docIdCounter.get(); return th; } private INeuron() { } public INeuron(Model m) { this(m, null); } public INeuron(Model m, String label) { this(m, label, null); } public INeuron(Model m, String label, String outputText) { this.label = label; this.outputText = outputText; if(m.getNeuronStatisticFactory() != null) { statistic = m.getNeuronStatisticFactory().createObject(); } threads = new ThreadState[m.numberOfThreads]; provider = new Neuron(m, this); OrNode node = new OrNode(m); node.neuron = provider; this.node = node.provider; setModified(); } /** * Propagate an input activation into the network. * * @param doc The current document * @param input */ public Activation addInput(Document doc, Activation.Builder input) { assert input.range.begin <= input.range.end; Activation act = getThreadState(doc.threadId, true).getActivationByRange(input.range); if(act == null) { act = new Activation(doc.activationIdCounter++, doc, node.get(doc)); act.range = input.range; } register(act); Activation.State s = new Activation.State(input.value, input.value, 1.0, 0.0, 0.0, input.fired, 0.0); act.rounds.set(0, s); act.avgState = s; act.inputValue = input.value; act.upperBound = input.value; act.lowerBound = input.value; act.inputDecision = SearchNode.Decision.SELECTED; act.finalDecision = act.inputDecision; act.setDecision(act.inputDecision, doc.visitedCounter++); act.setTargetValue(input.targetValue); doc.inputNeuronActivations.add(act); doc.finallyActivatedNeurons.add(act.getINeuron()); propagate(act); doc.propagate(); return act; } // TODO public void remove() { clearActivations(); for (Synapse s : inputSynapses.values()) { INeuron in = s.input.get(); in.provider.lock.acquireWriteLock(); in.provider.inMemoryOutputSynapses.remove(s); in.provider.lock.releaseWriteLock(); } provider.lock.acquireReadLock(); for (Synapse s : provider.inMemoryOutputSynapses.values()) { INeuron out = s.output.get(); out.lock.acquireWriteLock(); out.inputSynapses.remove(s); out.lock.releaseWriteLock(); } provider.lock.releaseReadLock(); } public void propagate(Activation act) { Document doc = act.doc; outputNode.get(doc).addActivation(act); } public Collection<Activation> getActivations(Document doc, boolean onlyFinal) { ThreadState th = getThreadState(doc.threadId, false); if (th == null) return Collections.EMPTY_LIST; return th.getActivations(onlyFinal); } public Activation getActivation(Document doc, Range r, boolean onlyFinal) { ThreadState th = getThreadState(doc.threadId, false); if (th == null) return null; for(Activation act : th.getActivationsByRangeBegin(r, true, r, false)) { if (!onlyFinal || act.isFinalActivation()) { return act; } } return null; } public void clearActivations() { for (int i = 0; i < provider.model.numberOfThreads; i++) { clearActivations(i); } } public void clearActivations(Document doc) { clearActivations(doc.threadId); } public void clearActivations(int threadId) { ThreadState th = getThreadState(threadId, false); if (th == null) return; th.clearActivations(); } public int compareTo(INeuron n) { if (provider.id < n.provider.id) return -1; else if (provider.id > n.provider.id) return 1; else return 0; } @Override public void write(DataOutput out) throws IOException { out.writeBoolean(true); out.writeBoolean(label != null); if(label != null) { out.writeUTF(label); } out.writeBoolean(type != null); if(type != null) { out.writeUTF(type.name()); } out.writeBoolean(logicType != null); if(logicType != null) { out.writeUTF(logicType.name()); } out.writeBoolean(outputText != null); if(outputText != null) { out.writeUTF(outputText); } out.writeBoolean(statistic != null); if(statistic != null) { statistic.write(out); } out.writeDouble(bias); out.writeDouble(biasSum); out.writeDouble(posDirSum); out.writeDouble(negDirSum); out.writeDouble(negRecSum); out.writeDouble(posRecSum); out.writeDouble(posPassiveSum); out.writeDouble(requiredSum); out.writeInt(numDisjunctiveSynapses); out.writeUTF(activationFunction.name()); out.writeInt(outputNode.id); out.writeBoolean(node != null); if (node != null) { out.writeInt(node.id); } out.writeInt(numberOfInputSynapses); for (Synapse s : inputSynapses.values()) { if (s.input != null) { out.writeBoolean(true); s.write(out); } } out.writeBoolean(false); for (Synapse s : outputSynapses.values()) { if (s.output != null) { out.writeBoolean(true); s.write(out); } } out.writeBoolean(false); if(outputRelations != null) { out.writeInt(outputRelations.size()); for (Map.Entry<Integer, Relation> me : outputRelations.entrySet()) { out.writeInt(me.getKey()); me.getValue().write(out); } } else { out.writeInt(0); } } @Override public void readFields(DataInput in, Model m) throws IOException { if(in.readBoolean()) { label = in.readUTF(); } if(in.readBoolean()) { type = Type.valueOf(in.readUTF()); } if(in.readBoolean()) { logicType = LogicType.valueOf(in.readUTF()); } if(in.readBoolean()) { outputText = in.readUTF(); } if(in.readBoolean()) { statistic = m.getNeuronStatisticFactory().createObject(); statistic.readFields(in, m); } bias = in.readDouble(); biasSum = in.readDouble(); posDirSum = in.readDouble(); negDirSum = in.readDouble(); negRecSum = in.readDouble(); posRecSum = in.readDouble(); posPassiveSum = in.readDouble(); requiredSum = in.readDouble(); numDisjunctiveSynapses = in.readInt(); activationFunction = ActivationFunction.valueOf(in.readUTF()); outputNode = m.lookupNodeProvider(in.readInt()); if (in.readBoolean()) { Integer nId = in.readInt(); node = m.lookupNodeProvider(nId); } numberOfInputSynapses = in.readInt(); while (in.readBoolean()) { Synapse syn = Synapse.read(in, m); inputSynapses.put(syn, syn); } while (in.readBoolean()) { Synapse syn = Synapse.read(in, m); outputSynapses.put(syn, syn); } int l = in.readInt(); if(l > 0) { outputRelations = new TreeMap<>(); for(int i = 0; i < l; i++) { int synId = in.readInt(); Relation r = Relation.read(in, m); outputRelations.put(synId, r); } } passiveInputFunction = m.passiveActivationFunctions.get(provider.id); } @Override public void suspend() { for (Synapse s : inputSynapses.values()) { s.input.removeInMemoryOutputSynapse(s); } for (Synapse s : outputSynapses.values()) { s.output.removeInMemoryInputSynapse(s); } provider.lock.acquireReadLock(); for (Synapse s : provider.inMemoryInputSynapses.values()) { if(!s.isConjunction) { s.input.removeInMemoryOutputSynapse(s); } } for (Synapse s : provider.inMemoryOutputSynapses.values()) { if(s.isConjunction) { s.output.removeInMemoryInputSynapse(s); } } provider.lock.releaseReadLock(); } @Override public void reactivate() { provider.lock.acquireReadLock(); for (Synapse s : provider.inMemoryInputSynapses.values()) { if(!s.isConjunction) { s.input.addInMemoryOutputSynapse(s); } } for (Synapse s : provider.inMemoryOutputSynapses.values()) { if(s.isConjunction) { s.output.addInMemoryInputSynapse(s); } } provider.lock.releaseReadLock(); for (Synapse s : inputSynapses.values()) { s.input.addInMemoryOutputSynapse(s); if (!s.input.isSuspended()) { s.output.addInMemoryInputSynapse(s); } } for (Synapse s : outputSynapses.values()) { s.output.addInMemoryInputSynapse(s); if (!s.output.isSuspended()) { s.input.addInMemoryOutputSynapse(s); } } } public void setBias(double b) { double newBiasDelta = b - bias; biasSumDelta += newBiasDelta - biasDelta; biasDelta = newBiasDelta; } public void changeBias(double bd) { biasDelta += bd; biasSumDelta += bd; } public double getNewBiasSum() { return biasSum + biasSumDelta; } public void register(Activation act) { Document doc = act.doc; INeuron.ThreadState th = act.node.neuron.get().getThreadState(doc.threadId, true); if (th.isEmpty()) { doc.activatedNeurons.add(act.node.neuron.get()); } th.minLength = Math.min(th.minLength, act.range.length()); th.maxLength = Math.max(th.maxLength, act.range.length()); th.addActivation(act); doc.addActivation(act); } public static boolean update(int threadId, Document doc, Neuron pn, Double bias, Collection<Synapse> modifiedSynapses) { INeuron n = pn.get(); if(bias != null) { n.setBias(bias); } // s.link requires an updated n.biasSumDelta value. modifiedSynapses.forEach(s -> s.link()); return Converter.convert(threadId, doc, n, modifiedSynapses); } public static INeuron readNeuron(DataInput in, Neuron p) throws IOException { INeuron n = new INeuron(); n.provider = p; n.threads = new ThreadState[p.model.numberOfThreads]; n.readFields(in, p.model); return n; } public boolean isPassiveInputNeuron() { return passiveInputFunction != null; } public void registerPassiveInputSynapse(Synapse s) { if(passiveInputSynapses == null) { passiveInputSynapses = new TreeMap<>(Synapse.INPUT_SYNAPSE_COMP); } passiveInputSynapses.put(s, s); } public String toString() { return label; } public String toStringWithSynapses() { SortedSet<Synapse> is = new TreeSet<>((s1, s2) -> { int r = Double.compare(s2.weight, s1.weight); if (r != 0) return r; return Integer.compare(s1.input.id, s2.input.id); }); is.addAll(inputSynapses.values()); StringBuilder sb = new StringBuilder(); sb.append(toString()); sb.append("<"); sb.append("B:"); sb.append(Utils.round(biasSum)); for (Synapse s : is) { sb.append(", "); sb.append(Utils.round(s.weight)); sb.append(":"); sb.append(s.input.toString()); } sb.append(">"); return sb.toString(); } }
fixed loading passive input neurons
src/main/java/network/aika/neuron/INeuron.java
fixed loading passive input neurons
<ide><path>rc/main/java/network/aika/neuron/INeuron.java <ide> while (in.readBoolean()) { <ide> Synapse syn = Synapse.read(in, m); <ide> inputSynapses.put(syn, syn); <add> <add> if(syn.input.get().isPassiveInputNeuron()) { <add> registerPassiveInputSynapse(syn); <add> } <ide> } <ide> <ide> while (in.readBoolean()) { <ide> Synapse syn = Synapse.read(in, m); <ide> outputSynapses.put(syn, syn); <add> <add> if(isPassiveInputNeuron()) { <add> syn.output.get().registerPassiveInputSynapse(syn); <add> } <ide> } <ide> <ide> int l = in.readInt();
JavaScript
mit
d237904cbbf550d288214ebe11aff848ccc11587
0
jspsych/jsPsych-Redux-GUI,jspsych/jsPsych-Redux-GUI,jspsych/jsPsych-Redux-GUI
/* This file is the reducers for timelineNode class from jsPsych (timeline, trial) A timeline state = { id: string, type: string, name: string, // if its parent is mainTimeline, null parent: string, childrenById: array, collapsed: boolean, enabled: boolean, // jsPsych timeline properties parameters: object, } A trial state = { id: string, type: string, name: string, // if its parent is mainTimeline, null parent: string, enabled: boolean, // specific parameters decided by which plugin user chooses parameters: object, } */ import * as actionTypes from '../constants/ActionTypes'; import * as utils from './timelineNodeUtils'; const DEFAULT_TIMELINE_NAME = 'Untitled Timeline'; const DEFAULT_TRIAL_NAME = 'Untitled Trial'; const DEFAULT_PLUGIN_TYPE = 'text'; var timeline = 0; var trial = 0; export const initState = { // id of which is being previewed/editted previewId: null, // the main timeline. array of ids mainTimeline: [], } export default function(state=initState, action) { switch(action.type) { case actionTypes.ADD_TIMELINE: return addTimeline(state, action); case actionTypes.DELETE_TIMELINE: return deleteTimeline(state, action); case actionTypes.ADD_TRIAL: return addTrial(state, action); case actionTypes.DELETE_TRIAL: return deleteTrial(state, action); case actionTypes.MOVE_NODE: return moveNode(state, action); case actionTypes.ON_PREVIEW: return onPreview(state, action); case actionTypes.ON_TOGGLE: return onToggle(state, action); case actionTypes.SET_COLLAPSED: return setCollapsed(state, action); case actionTypes.HOVER_NODE: return hoverNode(state, action); case actionTypes.CHANGE_PLUGIN_TYPE: return changePlugin(state, action); case actionTypes.TOGGLE_PARAM_VAL: return changeToggleValue(state, action); case actionTypes.CHANGE_PARAM_TEXT: return changeParamText(state, action); default: return state; } } /************************** Helper functions ********************************/ var __TEST__ = 0; export function enterTest() { __TEST__ = 1; } function getNodeById(state, id) { if (id === null) return null; return state[id]; } export function getLevel(state, node) { if (node.parent === null) return 0; else return 1 + getLevel(state, getNodeById(state, node.parent)); } export function getIndex(state, node) { if (node.parent === null) { return state.mainTimeline.indexOf(node.id); } else { return state[node.parent].childrenById.indexOf(node.id); } } const getDefaultTimelineName = () => { if (__TEST__) return DEFAULT_TIMELINE_NAME; return DEFAULT_TIMELINE_NAME + " " + (timeline++); }; const getDefaultTrialName = () => { if (__TEST__) return DEFAULT_TRIAL_NAME; return DEFAULT_TRIAL_NAME + " " + (trial++); }; /* Decides if source node is ancestor of target node */ export function isAncestor(state, sourceId, targetId) { let target = getNodeById(state, targetId); while (target && target.parent !== null) { if (target.parent === sourceId) return true; target = state[target.parent]; } return false; } /* Decides if source node can be moved under target node Two case it can't: 1. target node is a trial 2. source node is ancestor of target node If targetId is null, always true */ function canMoveUnder(state, sourceId, targetId) { if (!targetId) return true; if (utils.isTrial(state[targetId]) || isAncestor(state, sourceId, targetId)) { return false; } return true; } export function createTimeline(id, parent=null, name=getDefaultTimelineName(), childrenById=[], collapsed=true, enabled=true, parameters={}) { return { id: id, type: utils.TIMELINE_TYPE, name: name, parent: parent, childrenById: childrenById, collapsed: collapsed, enabled: enabled, predictedLevel: null, parameters: parameters }; } // define deep copy for parameters later function copyTimeline(timeline) { return createTimeline(timeline.id, timeline.parent, timeline.name, timeline.childrenById.slice(), timeline.collapsed, timeline.enabled, timeline.parameters) } export function createTrial(id, parent=null, name=getDefaultTrialName(), enabled=true, parameters={text: '', choices: ''}, pluginType=DEFAULT_PLUGIN_TYPE) { return { id: id, type: utils.TRIAL_TYPE, name: name, parent: parent, enabled: enabled, predictedLevel: null, pluginType: pluginType }; } function copyTrial(trial) { return createTrial(trial.id, trial.parent, trial.name, trial.enabled, trial.parameters, trial.pluginType) } function copyNode(node) { if (utils.isTimeline(node)) { return copyTimeline(node); } else { return copyTrial(node); } } /* action = { id: id, parent: string, } */ function addTimeline(state, action) { let new_state = Object.assign({}, state); let id = action.id; let parent = getNodeById(new_state, action.parent); if (parent !== null) { // update parent: childrenById parent = copyTimeline(parent); new_state[parent.id] = parent; parent.childrenById.push(id); parent.collapsed = false; } else { // update parent: childrenById new_state.mainTimeline = state.mainTimeline.slice(); new_state.mainTimeline.push(id); } let timeline = createTimeline(id, action.parent) new_state[id] = timeline; return new_state; } /* action = { id: string, parent: string, } */ function addTrial(state, action) { let new_state = Object.assign({}, state); let id = action.id; let parent = getNodeById(new_state, action.parent); if (parent !== null) { // update parent: childrenById parent = copyTimeline(parent); new_state[parent.id] = parent; parent.childrenById.push(id); parent.collapsed = false; } else { // update parent: main timeline new_state.mainTimeline = state.mainTimeline.slice(); new_state.mainTimeline.push(id); } let trial = createTrial(id, action.parent) new_state[id] = trial; return new_state; } function deleteTimelineHelper(state, id) { let timeline = getNodeById(state, id); // delete its children timeline.childrenById.map((childId) => { if (utils.isTimeline(state[childId])) { state = deleteTimelineHelper(state, childId); } else { state = deleteTrialHelper(state, childId) } }); // delete itself let parent = timeline.parent; if (parent === null) { // that is, main timeline state.mainTimeline = state.mainTimeline.filter((item) => (item !== id)); } else { parent = getNodeById(state, parent) parent = copyTimeline(parent); state[parent.id] = parent; parent.childrenById = parent.childrenById.filter((item) => (item !== id)); } if (state.previewId === id) state.previewId = null; delete state[id]; return state; } /* action = { id: string } */ function deleteTimeline(state, action) { let new_state = Object.assign({}, state); return deleteTimelineHelper(new_state, action.id); } function deleteTrialHelper(state, id) { let trial = getNodeById(state, id); let parent = trial.parent; if (parent === null) { // that is, main timeline state.mainTimeline = state.mainTimeline.filter((item) => (item !== id)); } else { parent = getNodeById(state, parent); parent = copyTimeline(parent); state[parent.id] = parent; parent.childrenById = parent.childrenById.filter((item) => (item !== id)); } if (state.previewId === id) state.previewId = null; delete state[id]; return state; } /* action = { id: string } */ function deleteTrial(state, action) { let new_state = Object.assign({}, state); return deleteTrialHelper(new_state, action.id); } /* Move Node action = { sourceId: string, targetId: string, up: boolean, } */ export const DRAG_TYPE = { // source and target have the same parent DISPLACEMENT: 1, // source takes target as new parent TRANSPLANT: 2, // different level displacement JUMP: 3, } function moveNode(state, action) { if (action.sourceId === action.targetId) return state; // console.log(action); switch (action.dragType) { case DRAG_TYPE.TRANSPLANT: return nodeTransplant(state, action); case DRAG_TYPE.DISPLACEMENT: return nodeDisplacement(state, action); case DRAG_TYPE.JUMP: return nodeJump(state, action); default: return state; } } function hoverNode(state, action) { // console.log(action); switch (action.dragType) { case DRAG_TYPE.TRANSPLANT: return nodeHoverTransplant(state, action); case DRAG_TYPE.DISPLACEMENT: return nodeHoverDisplacement(state, action); case DRAG_TYPE.JUMP: return nodeHoverJump(state, action); default: return state; } } // source and target have the same parent function nodeDisplacement(state, action) { let source = state[action.sourceId]; let target = state[action.targetId]; let targetIndex = getIndex(state, target); let new_state = Object.assign({}, state); let arr; // source was in the main timeline if (source.parent === null) { new_state.mainTimeline = state.mainTimeline.slice(); arr = new_state.mainTimeline; } else { let parent = copyTimeline(new_state[source.parent]); new_state[parent.id] = parent; arr = parent.childrenById; } let from = arr.indexOf(source.id); if (!action.up) targetIndex++; arr.move(from, targetIndex); return new_state; } function nodeHoverDisplacement(state, action) { let new_state = Object.assign({}, state); let source = copyNode(state[action.sourceId]); new_state[source.id] = source; source.predictedLevel = getLevel(state, source); return new_state; } // source takes target as new parent function nodeTransplant(state, action) { if (canMoveUnder(state, action.sourceId, action.targetId)) { let new_state = Object.assign({}, state); let source = copyNode(new_state[action.sourceId]); let target = copyTimeline(new_state[action.targetId]); new_state[source.id] = source; new_state[target.id] = target; target.collapsed = false; if (source.parent === target.id) { target.childrenById.move(target.childrenById.indexOf(source.id), 0); return new_state; } // source was in the main timeline if (source.parent === null) { new_state.mainTimeline = state.mainTimeline.slice(); new_state.mainTimeline = new_state.mainTimeline.filter((id) => (id !== source.id)); } else { let oldParent = copyTimeline(new_state[source.parent]); new_state[oldParent.id] = oldParent; oldParent.childrenById = oldParent.childrenById.filter((id) => (id !== source.id)); } source.parent = target.id; if (target.childrenById.indexOf(source.id) === -1) { target.childrenById.unshift(source.id); } return new_state; } else { return state; } } function nodeHoverTransplant(state, action) { let new_state = Object.assign({}, state); let source = copyNode(state[action.sourceId]); let target = copyTimeline(state[action.targetId]); new_state[source.id] = source; new_state[target.id] = target; target.collapsed = false; source.predictedLevel = getLevel(state, target) + 1; return new_state; } // different level displacement // that is, two items have different parent function nodeJump(state, action) { let canJump = true; if (utils.isTimeline(state[action.sourceId])) { canJump = !isAncestor(state, action.sourceId, action.targetId); } if (canJump) { let new_state = Object.assign({}, state); let source = copyNode(new_state[action.sourceId]); let target = new_state[action.targetId]; new_state[source.id] = source; let targetParentId = target.parent; // source was in the main timeline // delete itself from old parent if (source.parent === null) { new_state.mainTimeline = state.mainTimeline.slice(); new_state.mainTimeline = new_state.mainTimeline.filter((id) => (id !== source.id)); } else { let oldParent = copyTimeline(new_state[source.parent]); new_state[oldParent.id] = oldParent; oldParent.childrenById = oldParent.childrenById.filter((id) => (id !== source.id)); } // add source to new parent source.parent = targetParentId; // target parent is main timeline let targetIndex, arr; if (targetParentId === null) { new_state.mainTimeline = state.mainTimeline.slice(); arr = new_state.mainTimeline; } else { let targetParent = copyTimeline(new_state[targetParentId]); new_state[targetParentId] = targetParent; arr = targetParent.childrenById; } targetIndex = arr.indexOf(target.id); if (!action.up) targetIndex++; if (arr.indexOf(source.id) === -1) { arr.splice(targetIndex, 0, source.id); } return new_state; } else { return state; } } function nodeHoverJump(state, action) { let new_state = Object.assign({}, state); let source = copyNode(state[action.sourceId]); let target = state[action.targetId]; new_state[source.id] = source; source.predictedLevel = getLevel(state, target); return new_state; } function onPreview(state, action) { let new_state = Object.assign({}, state, { previewId: action.id }); return new_state; } function onToggle(state, action) { let node = state[action.id]; let new_state = Object.assign({}, state); if (utils.isTimeline(node)) { node = copyTimeline(node); } else { node = copyTrial(node); } node.enabled = !node.enabled; new_state[node.id] = node; return new_state; } function setCollapsed(state, action) { let timeline = state[action.id]; let new_state = Object.assign({}, state); timeline = copyTimeline(timeline); timeline.collapsed = !timeline.collapsed; new_state[timeline.id] = timeline; return new_state; } const pluginType = (type) => { switch(type) { case 1: return 'text'; case 2: return 'single-stim'; default: return 'text'; } } const pluginParam = (pluginType) => { switch (pluginType) { case 1: return { text: '', choices: '' }; case 2: return { stimulus: '', is_html: false, choices: '', prompt: '', timing_stim: '', timing_response: '', response_ends_trial: false }; default: return { text: '', choices: '' }; } } function changePlugin(state, action) { let node = state[state.previewId]; let new_state = Object.assign({}, state); node = copyTrial(node); node.pluginType = pluginType(action.key); node.parameters = pluginParam(action.key); new_state[state.previewId] = node; return new_state; } function changeToggleValue(state, action) { let node = state[state.previewId]; let new_state = Object.assign({}, state); node = copyTrial(node); parameters: [node.parameters, action.newVal] new_state[state.previewId] = node; return new_state; } function changeParamText(state, action) { let node = state[state.previewId]; let new_state = Object.assign({}, state); node = copyTrial(node); new_state[state.previewId] = node; node.parameters = Object.assign({}, node.parameters); //console.log("node.parameters[action.paramId] " + node.parameters[action.paramId]); node.parameters[action.paramId] = action.newVal; console.log('INSIDE REDUCER:') console.log(new_state); return new_state; }
src/common/reducers/timelineNode.js
/* This file is the reducers for timelineNode class from jsPsych (timeline, trial) A timeline state = { id: string, type: string, name: string, // if its parent is mainTimeline, null parent: string, childrenById: array, collapsed: boolean, enabled: boolean, // jsPsych timeline properties parameters: object, } A trial state = { id: string, type: string, name: string, // if its parent is mainTimeline, null parent: string, enabled: boolean, // specific parameters decided by which plugin user chooses parameters: object, } */ import * as actionTypes from '../constants/ActionTypes'; import * as utils from './timelineNodeUtils'; const DEFAULT_TIMELINE_NAME = 'Untitled Timeline'; const DEFAULT_TRIAL_NAME = 'Untitled Trial'; const DEFAULT_PLUGIN_TYPE = 'text'; var timeline = 0; var trial = 0; export const initState = { // id of which is being previewed/editted previewId: null, // the main timeline. array of ids mainTimeline: [], } export default function(state=initState, action) { switch(action.type) { case actionTypes.ADD_TIMELINE: return addTimeline(state, action); case actionTypes.DELETE_TIMELINE: return deleteTimeline(state, action); case actionTypes.ADD_TRIAL: return addTrial(state, action); case actionTypes.DELETE_TRIAL: return deleteTrial(state, action); case actionTypes.MOVE_NODE: return moveNode(state, action); case actionTypes.ON_PREVIEW: return onPreview(state, action); case actionTypes.ON_TOGGLE: return onToggle(state, action); case actionTypes.SET_COLLAPSED: return setCollapsed(state, action); case actionTypes.HOVER_NODE: return hoverNode(state, action); case actionTypes.CHANGE_PLUGIN_TYPE: return changePlugin(state, action); case actionTypes.TOGGLE_PARAM_VAL: return changeToggleValue(state, action); case actionTypes.CHANGE_PARAM_TEXT: return changeParamText(state, action); default: return state; } } /************************** Helper functions ********************************/ var __TEST__ = 0; export function enterTest() { __TEST__ = 1; } function getNodeById(state, id) { if (id === null) return null; return state[id]; } export function getLevel(state, node) { if (node.parent === null) return 0; else return 1 + getLevel(state, getNodeById(state, node.parent)); } export function getIndex(state, node) { if (node.parent === null) { return state.mainTimeline.indexOf(node.id); } else { return state[node.parent].childrenById.indexOf(node.id); } } const getDefaultTimelineName = () => { if (__TEST__) return DEFAULT_TIMELINE_NAME; return DEFAULT_TIMELINE_NAME + " " + (timeline++); }; const getDefaultTrialName = () => { if (__TEST__) return DEFAULT_TRIAL_NAME; return DEFAULT_TRIAL_NAME + " " + (trial++); }; /* Decides if source node is ancestor of target node */ export function isAncestor(state, sourceId, targetId) { let target = getNodeById(state, targetId); while (target && target.parent !== null) { if (target.parent === sourceId) return true; target = state[target.parent]; } return false; } /* Decides if source node can be moved under target node Two case it can't: 1. target node is a trial 2. source node is ancestor of target node If targetId is null, always true */ function canMoveUnder(state, sourceId, targetId) { if (!targetId) return true; if (utils.isTrial(state[targetId]) || isAncestor(state, sourceId, targetId)) { return false; } return true; } export function createTimeline(id, parent=null, name=getDefaultTimelineName(), childrenById=[], collapsed=true, enabled=true, parameters={}) { return { id: id, type: utils.TIMELINE_TYPE, name: name, parent: parent, childrenById: childrenById, collapsed: collapsed, enabled: enabled, predictedLevel: null, parameters: parameters }; } // define deep copy for parameters later function copyTimeline(timeline) { return createTimeline(timeline.id, timeline.parent, timeline.name, timeline.childrenById.slice(), timeline.collapsed, timeline.enabled, timeline.parameters) } export function createTrial(id, parent=null, name=getDefaultTrialName(), enabled=true, parameters={text: '', choices: ''}, pluginType=DEFAULT_PLUGIN_TYPE) { return { id: id, type: utils.TRIAL_TYPE, name: name, parent: parent, enabled: enabled, predictedLevel: null, pluginType: pluginType }; } function copyTrial(trial) { return createTrial(trial.id, trial.parent, trial.name, trial.enabled, trial.parameters, trial.pluginType) } function copyNode(node) { if (utils.isTimeline(node)) { return copyTimeline(node); } else { return copyTrial(node); } } /* action = { id: id, parent: string, } */ function addTimeline(state, action) { let new_state = Object.assign({}, state); let id = action.id; let parent = getNodeById(new_state, action.parent); if (parent !== null) { // update parent: childrenById parent = copyTimeline(parent); new_state[parent.id] = parent; parent.childrenById.push(id); parent.collapsed = false; } else { // update parent: childrenById new_state.mainTimeline = state.mainTimeline.slice(); new_state.mainTimeline.push(id); } let timeline = createTimeline(id, action.parent) new_state[id] = timeline; return new_state; } /* action = { id: string, parent: string, } */ function addTrial(state, action) { let new_state = Object.assign({}, state); let id = action.id; let parent = getNodeById(new_state, action.parent); if (parent !== null) { // update parent: childrenById parent = copyTimeline(parent); new_state[parent.id] = parent; parent.childrenById.push(id); parent.collapsed = false; } else { // update parent: main timeline new_state.mainTimeline = state.mainTimeline.slice(); new_state.mainTimeline.push(id); } let trial = createTrial(id, action.parent) new_state[id] = trial; return new_state; } function deleteTimelineHelper(state, id) { let timeline = getNodeById(state, id); // delete its children timeline.childrenById.map((childId) => { if (utils.isTimeline(state[childId])) { state = deleteTimelineHelper(state, childId); } else { state = deleteTrialHelper(state, childId) } }); // delete itself let parent = timeline.parent; if (parent === null) { // that is, main timeline state.mainTimeline = state.mainTimeline.filter((item) => (item !== id)); } else { parent = getNodeById(state, parent) parent = copyTimeline(parent); state[parent.id] = parent; parent.childrenById = parent.childrenById.filter((item) => (item !== id)); } if (state.previewId === id) state.previewId = null; delete state[id]; return state; } /* action = { id: string } */ function deleteTimeline(state, action) { let new_state = Object.assign({}, state); return deleteTimelineHelper(new_state, action.id); } function deleteTrialHelper(state, id) { let trial = getNodeById(state, id); let parent = trial.parent; if (parent === null) { // that is, main timeline state.mainTimeline = state.mainTimeline.filter((item) => (item !== id)); } else { parent = getNodeById(state, parent); parent = copyTimeline(parent); state[parent.id] = parent; parent.childrenById = parent.childrenById.filter((item) => (item !== id)); } if (state.previewId === id) state.previewId = null; delete state[id]; return state; } /* action = { id: string } */ function deleteTrial(state, action) { let new_state = Object.assign({}, state); return deleteTrialHelper(new_state, action.id); } /* Move Node action = { sourceId: string, targetId: string, up: boolean, } */ export const DRAG_TYPE = { // source and target have the same parent DISPLACEMENT: 1, // source takes target as new parent TRANSPLANT: 2, // different level displacement JUMP: 3, } function moveNode(state, action) { if (action.sourceId === action.targetId) return state; // console.log(action); switch (action.dragType) { case DRAG_TYPE.TRANSPLANT: return nodeTransplant(state, action); case DRAG_TYPE.DISPLACEMENT: return nodeDisplacement(state, action); case DRAG_TYPE.JUMP: return nodeJump(state, action); default: return state; } } function hoverNode(state, action) { // console.log(action); switch (action.dragType) { case DRAG_TYPE.TRANSPLANT: return nodeHoverTransplant(state, action); case DRAG_TYPE.DISPLACEMENT: return nodeHoverDisplacement(state, action); case DRAG_TYPE.JUMP: return nodeHoverJump(state, action); default: return state; } } // source and target have the same parent function nodeDisplacement(state, action) { let source = state[action.sourceId]; let target = state[action.targetId]; let targetIndex = getIndex(state, target); let new_state = Object.assign({}, state); let arr; // source was in the main timeline if (source.parent === null) { new_state.mainTimeline = state.mainTimeline.slice(); arr = new_state.mainTimeline; } else { let parent = copyTimeline(new_state[source.parent]); new_state[parent.id] = parent; arr = parent.childrenById; } let from = arr.indexOf(source.id); if (!action.up) targetIndex++; arr.move(from, targetIndex); return new_state; } function nodeHoverDisplacement(state, action) { let new_state = Object.assign({}, state); let source = copyNode(state[action.sourceId]); new_state[source.id] = source; source.predictedLevel = getLevel(state, source); return new_state; } // source takes target as new parent function nodeTransplant(state, action) { if (canMoveUnder(state, action.sourceId, action.targetId)) { let new_state = Object.assign({}, state); let source = copyNode(new_state[action.sourceId]); let target = copyTimeline(new_state[action.targetId]); new_state[source.id] = source; new_state[target.id] = target; target.collapsed = false; if (source.parent === target.id) { target.childrenById.move(target.childrenById.indexOf(source.id), 0); return new_state; } // source was in the main timeline if (source.parent === null) { new_state.mainTimeline = state.mainTimeline.slice(); new_state.mainTimeline = new_state.mainTimeline.filter((id) => (id !== source.id)); } else { let oldParent = copyTimeline(new_state[source.parent]); new_state[oldParent.id] = oldParent; oldParent.childrenById = oldParent.childrenById.filter((id) => (id !== source.id)); } source.parent = target.id; if (target.childrenById.indexOf(source.id) === -1) { target.childrenById.unshift(source.id); } return new_state; } else { return state; } } function nodeHoverTransplant(state, action) { let new_state = Object.assign({}, state); let source = copyNode(state[action.sourceId]); let target = copyTimeline(state[action.targetId]); new_state[source.id] = source; new_state[target.id] = target; target.collapsed = false; source.predictedLevel = getLevel(state, target) + 1; return new_state; } // different level displacement // that is, two items have different parent function nodeJump(state, action) { let canJump = true; if (utils.isTimeline(state[action.sourceId])) { canJump = !isAncestor(state, action.sourceId, action.targetId); } if (canJump) { let new_state = Object.assign({}, state); let source = copyNode(new_state[action.sourceId]); let target = new_state[action.targetId]; new_state[source.id] = source; let targetParentId = target.parent; // source was in the main timeline // delete itself from old parent if (source.parent === null) { new_state.mainTimeline = state.mainTimeline.slice(); new_state.mainTimeline = new_state.mainTimeline.filter((id) => (id !== source.id)); } else { let oldParent = copyTimeline(new_state[source.parent]); new_state[oldParent.id] = oldParent; oldParent.childrenById = oldParent.childrenById.filter((id) => (id !== source.id)); } // add source to new parent source.parent = targetParentId; // target parent is main timeline let targetIndex, arr; if (targetParentId === null) { new_state.mainTimeline = state.mainTimeline.slice(); arr = new_state.mainTimeline; } else { let targetParent = copyTimeline(new_state[targetParentId]); new_state[targetParentId] = targetParent; arr = targetParent.childrenById; } targetIndex = arr.indexOf(target.id); if (!action.up) targetIndex++; if (arr.indexOf(source.id) === -1) { arr.splice(targetIndex, 0, source.id); } return new_state; } else { return state; } } function nodeHoverJump(state, action) { let new_state = Object.assign({}, state); let source = copyNode(state[action.sourceId]); let target = state[action.targetId]; new_state[source.id] = source; source.predictedLevel = getLevel(state, target); return new_state; } function onPreview(state, action) { let new_state = Object.assign({}, state, { previewId: action.id }); return new_state; } function onToggle(state, action) { let node = state[action.id]; let new_state = Object.assign({}, state); if (utils.isTimeline(node)) { node = copyTimeline(node); } else { node = copyTrial(node); } node.enabled = !node.enabled; new_state[node.id] = node; return new_state; } function setCollapsed(state, action) { let timeline = state[action.id]; let new_state = Object.assign({}, state); timeline = copyTimeline(timeline); timeline.collapsed = !timeline.collapsed; new_state[timeline.id] = timeline; return new_state; } const pluginType = (type) => { switch(type) { case 1: return ('text'); break; case 2: return ('single-stim'); break; default: return ('text'); } } const pluginParam = (pluginType) => { switch(pluginType) { case 1: return ({text: '', choices: ''}); break; case 2: return ({stimulus: '', is_html: false, choices: '', prompt: '', timing_stim: '', timing_response: '', response_ends_trial: false}); break; default: return ({text: '', choices: ''}); } } function changePlugin(state, action) { let node = state[state.previewId]; let new_state = Object.assign({}, state); node = copyTrial(node); node.pluginType = pluginType(action.key); node.parameters = pluginParam(action.key); new_state[state.previewId] = node; return new_state; } function changeToggleValue(state, action) { let node = state[state.previewId]; let new_state = Object.assign({}, state); node = copyTrial(node); parameters: [node.parameters, action.newVal] new_state[state.previewId] = node; return new_state; } function changeParamText(state, action) { let node = state[state.previewId]; let new_state = Object.assign({}, state); node = copyTrial(node); new_state[state.previewId] = node; node.parameters = Object.assign({}, node.parameters); //console.log("node.parameters[action.paramId] " + node.parameters[action.paramId]); node.parameters[action.paramId] = action.newVal; console.log('INSIDE REDUCER:') console.log(new_state); return new_state; }
Clean up
src/common/reducers/timelineNode.js
Clean up
<ide><path>rc/common/reducers/timelineNode.js <ide> <ide> const pluginType = (type) => { <ide> switch(type) { <del> case 1: return ('text'); <del> break; <del> case 2: return ('single-stim'); <del> break; <del> default: return ('text'); <add> case 1: <add> return 'text'; <add> case 2: <add> return 'single-stim'; <add> default: <add> return 'text'; <ide> } <ide> } <ide> <ide> const pluginParam = (pluginType) => { <del> switch(pluginType) { <del> case 1: return ({text: '', choices: ''}); <del> break; <del> case 2: return ({stimulus: '', is_html: false, <del> choices: '', prompt: '', timing_stim: '', <del> timing_response: '', response_ends_trial: false}); <del> break; <del> default: return ({text: '', choices: ''}); <add> switch (pluginType) { <add> case 1: <add> return { <add> text: '', <add> choices: '' <add> }; <add> case 2: <add> return { <add> stimulus: '', <add> is_html: false, <add> choices: '', <add> prompt: '', <add> timing_stim: '', <add> timing_response: '', <add> response_ends_trial: false <add> }; <add> default: <add> return { <add> text: '', <add> choices: '' <add> }; <ide> } <ide> } <ide>