answer
stringlengths
17
10.2M
package org.flymine.codegen; // Most of this code originated in the ArgoUML project, which carries // software and its documentation without fee, and without a written // and this paragraph appear in all copies. This software program and // California. The software program and documentation are supplied "AS // IS", without any accompanying services from The Regents. The Regents // does not warrant that the operation of the program will be // uninterrupted or error-free. The end-user understands that the program // was developed for research purposes and is advised not to rely // exclusively on the program for any reason. IN NO EVENT SHALL THE // UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, // SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, // ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF // THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE // PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF // CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, // UPDATES, ENHANCEMENTS, OR MODIFICATIONS. import ru.novosoft.uml.xmi.XMIReader; import ru.novosoft.uml.foundation.core.*; import ru.novosoft.uml.foundation.data_types.*; import ru.novosoft.uml.model_management.*; import ru.novosoft.uml.foundation.extension_mechanisms.*; import java.io.File; import java.util.StringTokenizer; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.LinkedHashSet; import java.util.ArrayList; import java.util.Collection; import org.xml.sax.InputSource; public class JavaModelOutput extends ModelOutput { private static final boolean OJB = true; public JavaModelOutput(MModel mmodel) { super(mmodel); } protected String generateOperation(MOperation op) { StringBuffer sb = new StringBuffer(); String nameStr = generateName(op.getName()); String clsName = generateName(op.getOwner().getName()); // modifiers sb.append(INDENT); sb.append(generateConcurrency(op)); sb.append(generateAbstractness(op)); sb.append(generateChangeability(op)); sb.append(generateScope(op)); sb.append(generateVisibility(op)); // return type MParameter rp = getReturnParameter(op); if (rp != null) { MClassifier returnType = rp.getType(); if (returnType == null && !nameStr.equals(clsName)) { sb.append("void "); } else if (returnType != null) { sb.append(generateClassifierRef(returnType)).append(' '); } } // method name sb.append(nameStr); // parameters List params = new ArrayList(op.getParameters()); params.remove(rp); sb.append('('); if (params != null) { for (int i = 0; i < params.size(); i++) { MParameter p = (MParameter) params.get(i); if (i > 0) { sb.append(", "); } sb.append(generateParameter(p)); } } sb.append(')'); return sb.toString(); } protected String generateAttribute (MAttribute attr) { StringBuffer sb = new StringBuffer(); MClassifier owner = attr.getOwner(); // modifiers sb.append(INDENT); sb.append(generateVisibility(attr)); sb.append(generateScope(attr)); sb.append(generateChangability(attr)); // type MClassifier type = attr.getType(); if (type != null) { sb.append(generateClassifierRef(type)).append(' '); } // field name sb.append(generateName(attr.getName())); // initial value MExpression init = attr.getInitialValue(); if (init != null) { String initStr = generateExpression(init).trim(); if (initStr.length() > 0) { sb.append(" = ").append(initStr); } } sb.append(";\n") .append(generateGetSet(generateNoncapitalName(attr.getName()), generateClassifierRef(type))) .append("\n"); return sb.toString(); } protected String generateParameter(MParameter param) { StringBuffer sb = new StringBuffer(); // type sb.append(generateClassifierRef(param.getType())).append(' '); // name sb.append(generateName(param.getName())); return sb.toString(); } protected String generateClassifier(MClassifier cls) { StringBuffer sb = new StringBuffer(); sb.append(generateClassifierStart(cls)) .append(generateClassifierBody(cls)) .append(generateClassifierEnd(cls)); return sb.toString(); } protected String generateAssociationEnd(MAssociationEnd ae) { if (!ae.isNavigable()) { return ""; } StringBuffer sb = new StringBuffer(); String type = ""; String impl = ""; String name = ""; String construct = ""; //sb.append(INDENT + generateVisibility(ae.getVisibility())); if (MScopeKind.CLASSIFIER.equals(ae.getTargetScope())) { sb.append("static "); } MMultiplicity m = ae.getMultiplicity(); if (MMultiplicity.M1_1.equals(m) || MMultiplicity.M0_1.equals(m)) { type = generateClassifierRef(ae.getType()); } else { // if(ae.getOrdering()==null || ae.getOrdering().getName().equals("unordered")) { // type="Set"; // impl="HashSet"; // } else { type = "List"; impl = "ArrayList"; name = "s"; construct = " = new " + impl + "()"; } String n = ae.getName(); MAssociation asc = ae.getAssociation(); String ascName = asc.getName(); if (n != null && n.length() > 0) { name = n + name; } else if (ascName != null && ascName.length() > 0) { name = ascName + name; } else { name = generateClassifierRef(ae.getType()) + name; } if (OJB && (MMultiplicity.M1_1.equals(m) || MMultiplicity.M0_1.equals(m))) { sb.append(INDENT + "protected int ") .append(generateNoncapitalName(name) + "Id;\n"); } sb.append(INDENT + "protected ") .append(type) .append(' ') .append(generateNoncapitalName(name)) .append(construct) .append(";\n") .append(generateGetSet(generateNoncapitalName(name), type)) .append("\n"); return sb.toString(); } protected void generateFileStart(File path) { } protected void generateFile(MClassifier cls, File path) { String filename = cls.getName() + ".java"; int lastIndex = -1; do { if (!path.isDirectory()) { if (!path.mkdir()) { LOG.debug(" could not make directory " + path); return; } } String packagePath = getPackagePath(cls); if (lastIndex == packagePath.length()) { break; } int index = packagePath.indexOf (".", lastIndex + 1); if (index == -1) { index = packagePath.length(); } path = new File(path, packagePath.substring (lastIndex + 1, index)); lastIndex = index; } while (true); path = new File(path, filename); initFile(path); String header = generateHeader(cls); String src = generate(cls); outputToFile(path, header + src); } protected void generateFileEnd(File path) { } private String generateHeader (MClassifier cls) { StringBuffer sb = new StringBuffer(); String packagePath = getPackagePath(cls); if (packagePath.length() > 0) { sb.append("package ").append(packagePath).append(";\n\n"); } sb.append("import java.util.*;\n\n"); return sb.toString(); } private StringBuffer generateClassifierStart (MClassifier cls) { StringBuffer sb = new StringBuffer (); String sClassifierKeyword = null; if (cls instanceof MClassImpl) { sClassifierKeyword = "class"; } else if (cls instanceof MInterface) { sClassifierKeyword = "interface"; } // Now add visibility sb.append(generateVisibility(cls.getVisibility())); // Add other modifiers if (cls.isAbstract() && !(cls instanceof MInterface)) { sb.append("abstract "); } if (cls.isLeaf()) { sb.append("final "); } // add classifier keyword and classifier name sb.append (sClassifierKeyword) .append(" ") .append (generateName(cls.getName())); // add base class/interface String baseClass = generateGeneralization(cls.getGeneralizations()); if (!baseClass.equals("")) { sb.append (" ") .append ("extends ") .append (baseClass); } // add implemented interfaces, if needed if (cls instanceof MClass) { String interfaces = generateSpecification((MClass) cls); if (!interfaces.equals ("")) { sb.append (" ") .append ("implements ") .append (interfaces); } } // add opening brace sb.append("\n{\n"); if (OJB && sClassifierKeyword.equals("class")) { if (baseClass.equals("")) { sb.append(INDENT + "protected int id;\n"); } if (!baseClass.equals("") || cls.getSpecializations().size() > 0) { sb.append(INDENT + "protected String ojbConcreteClass = \"" + generateQualified(cls) + "\";\n"); } } return sb.append("\n"); } private String generateGetSet(String name, String type) { StringBuffer sb = new StringBuffer(); // Get method sb.append(INDENT) .append("public "); if (type != null) { sb.append(type).append(' '); } sb.append("get").append(generateCapitalName(name)).append("() { ") .append("return this.").append(generateName(name)).append("; }\n"); // Set method sb.append(INDENT) .append("public void ") .append("set").append(generateCapitalName(name)).append("("); if (type != null) { sb.append(type).append(" "); } sb.append(generateName(name)).append(") { ") .append("this.").append(generateName(name)).append("=") .append(generateName(name)).append("; }\n"); return sb.toString(); } // private String generateHashCode(MClassifier cls) { // StringBuffer sb = new StringBuffer(); // Collection keyFields = getKeys(cls); // if (keyFields.size() > 0) { // sb.append(INDENT + "public int hashCode() { ") // .append("return "); // Iterator iter = keyFields.iterator(); // while (iter.hasNext()) { // String field = (String) iter.next(); // sb.append(field+".hashCode()"); // if (iter.hasNext()) { // sb.append(" ^ "); // sb.append("; }\n"); // return sb.toString(); // private String generateEquals(MClassifier cls) { // StringBuffer sb = new StringBuffer(); // Collection keyFields = getKeys(cls); // if (keyFields.size() > 0) { // sb.append(INDENT + "public boolean equals(Object o) { ") // .append("return o != null && o instanceof " + cls.getName()) // .append(" && o.hashCode() == hashCode(); }\n"); // return sb.toString(); private String generateEquals(MClassifier cls) { StringBuffer sb = new StringBuffer(); Collection keyFields = getKeys(cls); if (keyFields.size() > 0) { sb.append(INDENT + "public boolean equals(Object o) { ") .append("return (o instanceof " + cls.getName() + " && "); Iterator iter = keyFields.iterator(); while (iter.hasNext()) { String field = (String) iter.next(); sb.append("((" + cls.getName() + ")o)." + field + "==" + field); if (iter.hasNext()) { sb.append(" && "); } } sb.append("); }\n"); } return sb.toString(); } private String generateToString(MClassifier cls) { StringBuffer sb = new StringBuffer(); Collection keyFields = getKeys(cls); if (keyFields.size() > 0) { sb.append(INDENT + "public String toString() {") .append("return \"" + cls.getName() + " [\"") .append(OJB ? "+id" : "+get" + generateCapitalName(cls.getName()) + "Id()") .append("+\"] \"+"); Iterator iter = keyFields.iterator(); while (iter.hasNext()) { String field = (String) iter.next(); sb.append(field); if (iter.hasNext()) { sb.append("+\", \"+"); } } sb.append("; }\n"); } return sb.toString(); } private StringBuffer generateClassifierEnd(MClassifier cls) { StringBuffer sb = new StringBuffer(); sb.append(generateEquals(cls)) .append("\n") .append(generateToString(cls)) .append("}"); return sb; } private StringBuffer generateClassifierBody(MClassifier cls) { StringBuffer sb = new StringBuffer(); // (attribute) fields Collection strs = getAttributes(cls); if (!strs.isEmpty()) { Iterator strIter = strs.iterator(); while (strIter.hasNext()) { sb.append(generate((MStructuralFeature) strIter.next())); } } // (association) fields Collection ends = new ArrayList(cls.getAssociationEnds()); if (!ends.isEmpty()) { Iterator endIter = ends.iterator(); while (endIter.hasNext()) { MAssociationEnd ae = (MAssociationEnd) endIter.next(); sb.append(generateAssociationEnd(ae.getOppositeEnd())); } } // methods Collection behs = getOperations(cls); if (!behs.isEmpty()) { sb.append('\n'); Iterator behEnum = behs.iterator(); while (behEnum.hasNext()) { MBehavioralFeature bf = (MBehavioralFeature) behEnum.next(); sb.append(generate(bf)); if ((cls instanceof MClassImpl) && (bf instanceof MOperation) && (!((MOperation) bf).isAbstract())) { sb.append(" {\n") .append(generateMethodBody((MOperation) bf)) .append(INDENT) .append("}\n"); } else { sb.append(";\n"); } } } return sb; } private String generateMethodBody (MOperation op) { if (op != null) { Collection methods = op.getMethods(); Iterator i = methods.iterator(); MMethod m = null; while (i != null && i.hasNext()) { m = (MMethod) i.next(); if (m != null) { if (m.getBody() != null) { return m.getBody().getBody(); } else { return ""; } } } // pick out return type MParameter rp = getReturnParameter(op); if (rp != null) { MClassifier returnType = rp.getType(); return generateDefaultReturnStatement (returnType); } } return generateDefaultReturnStatement (null); } private String generateDefaultReturnStatement(MClassifier cls) { if (cls == null) { return ""; } String clsName = cls.getName(); if (clsName.equals("void")) { return ""; } if (clsName.equals("char")) { return INDENT + "return 'x';\n"; } if (clsName.equals("int")) { return INDENT + "return 0;\n"; } if (clsName.equals("boolean")) { return INDENT + "return false;\n"; } if (clsName.equals("byte")) { return INDENT + "return 0;\n"; } if (clsName.equals("long")) { return INDENT + "return 0;\n"; } if (clsName.equals("float")) { return INDENT + "return 0.0;\n"; } if (clsName.equals("double")) { return INDENT + "return 0.0;\n"; } return INDENT + "return null;\n"; } private String generateSpecification(MClass cls) { Collection realizations = getSpecifications(cls); if (realizations == null) { return ""; } StringBuffer sb = new StringBuffer(); Iterator clsEnum = realizations.iterator(); while (clsEnum.hasNext()) { MInterface i = (MInterface) clsEnum.next(); sb.append(generateClassifierRef(i)); if (clsEnum.hasNext()) { sb.append(", "); } } return sb.toString(); } private String generateVisibility(MVisibilityKind vis) { if (MVisibilityKind.PUBLIC.equals(vis)) { return "public "; } if (MVisibilityKind.PRIVATE.equals(vis)) { return "private "; } if (MVisibilityKind.PROTECTED.equals(vis)) { return "protected "; } return ""; } private String generateVisibility(MFeature f) { return generateVisibility(f.getVisibility()); } private String generateScope(MFeature f) { MScopeKind scope = f.getOwnerScope(); if (MScopeKind.CLASSIFIER.equals(scope)) { return "static "; } return ""; } private String generateAbstractness(MOperation op) { if (op.isAbstract()) { return "abstract "; } return ""; } private String generateChangeability(MOperation op) { if (op.isLeaf()) { return "final "; } return ""; } private String generateChangability(MStructuralFeature sf) { MChangeableKind ck = sf.getChangeability(); //if (ck == null) return ""; if (MChangeableKind.FROZEN.equals(ck)) { return "final "; } //if (MChangeableKind.ADDONLY.equals(ck)) return "final "; return ""; } private String generateConcurrency(MOperation op) { if (op.getConcurrency() != null && op.getConcurrency().getValue() == MCallConcurrencyKind._GUARDED) { return "synchronized "; } return ""; } private Collection getKeys(MClassifier cls) { Set keyFields = new LinkedHashSet(); Collection tvs = cls.getTaggedValues(); if (tvs != null && tvs.size() > 0) { Iterator iter = tvs.iterator(); while (iter.hasNext()) { MTaggedValue tv = (MTaggedValue) iter.next(); if (tv.getTag().equals("key")) { StringTokenizer st = new StringTokenizer(tv.getValue(), ", "); while (st.hasMoreElements()) { keyFields.add(st.nextElement()); } } } } Iterator parents = cls.getGeneralizations().iterator(); if (parents.hasNext()) { keyFields.addAll(getKeys((MClassifier) ((MGeneralization) parents.next()).getParent())); } return keyFields; } public static void main(String[] args) throws Exception { if (args.length != 3) { System.err.println("Usage: JavaModelOutput <project name> <input dir> <output dir>"); System.exit(1); } String projectName = args[0]; String inputDir = args[1]; String outputDir = args[2]; File xmiFile = new File(inputDir, projectName + "_.xmi"); InputSource source = new InputSource(xmiFile.toURL().toString()); File path = new File(outputDir); new JavaModelOutput(new XMIReader().parse(source)).output(path); } }
package org.jgroups.tests; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import junit.framework.Test; import junit.framework.TestSuite; import org.jgroups.Channel; import org.jgroups.JChannelFactory; import org.jgroups.Message; import org.jgroups.View; import org.jgroups.util.Util; /** * Tests concurrent startup with state transfer and concurrent state tranfer. * * @author bela * @version $Id: ConcurrentStartupTest.java,v 1.30 2007/11/02 13:34:32 vlada Exp $ */ public class ConcurrentStartupTest extends ChannelTestBase { private int mod = 1; public void setUp() throws Exception { super.setUp(); mod = 1; CHANNEL_CONFIG = System.getProperty("channel.conf.flush", "flush-udp.xml"); } public boolean useBlocking() { return true; } public void testConcurrentStartupLargeState() { concurrentStartupHelper(true, false); } public void testConcurrentStartupSmallState() { concurrentStartupHelper(false, true); } protected void concurrentStartupHelper(boolean largeState, boolean useDispatcher) { String[] names = null; // mux applications on top of same channel have to have unique name if(isMuxChannelUsed()){ names = createMuxApplicationNames(1); }else{ names = new String[] { "A", "B", "C", "D" }; } int count = names.length; ConcurrentStartupChannel[] channels = new ConcurrentStartupChannel[count]; try{ // Create a semaphore and take all its permits Semaphore semaphore = new Semaphore(count); semaphore.acquire(count); // Create activation threads that will block on the semaphore for(int i = 0;i < count;i++){ if(largeState){ if(isMuxChannelUsed()){ channels[i] = new ConcurrentStartupChannelWithLargeState(names[i], muxFactory[i % getMuxFactoryCount()], semaphore); }else{ channels[i] = new ConcurrentStartupChannelWithLargeState(semaphore, names[i], useDispatcher); } }else{ if(isMuxChannelUsed()){ channels[i] = new ConcurrentStartupChannel(names[i], muxFactory[i % getMuxFactoryCount()], semaphore); }else{ channels[i] = new ConcurrentStartupChannel(names[i], semaphore, useDispatcher); } } // Release one ticket at a time to allow the thread to start // working channels[i].start(); semaphore.release(1); //sleep at least a second and max second and a half sleepRandom(1000,1500); } // Make sure everyone is in sync if(isMuxChannelUsed()){ blockUntilViewsReceived(channels, getMuxFactoryCount(), 60000); }else{ blockUntilViewsReceived(channels, 60000); } // Sleep to ensure the threads get all the semaphore tickets Util.sleep(2000); // Reacquire the semaphore tickets; when we have them all // we know the threads are done boolean acquired = semaphore.tryAcquire(count, 20, TimeUnit.SECONDS); if(!acquired){ log.warn("Most likely a bug, analyse the stack below:"); log.warn(Util.dumpThreads()); } // Sleep to ensure async message arrive Util.sleep(3000); // do test verification List[] lists = new List[count]; for(int i = 0;i < count;i++){ lists[i] = channels[i].getList(); } Map[] mods = new Map[count]; for(int i = 0;i < count;i++){ mods[i] = channels[i].getModifications(); } printLists(lists); printModifications(mods); int len = lists.length; for(int i = 0;i < lists.length;i++){ List l = lists[i]; assertEquals("list #" + i + " should have " + len + " elements", len, l.size()); } }catch(Exception ex){ log.warn("Exception encountered during test", ex); fail(ex.getLocalizedMessage()); }finally{ for(ConcurrentStartupChannel channel:channels){ channel.cleanup(); Util.sleep(2000); // remove before 2.6 GA } } } public void testConcurrentLargeStateTransfer() { concurrentStateTranferHelper(true, false); } public void testConcurrentSmallStateTranfer() { concurrentStateTranferHelper(false, true); } protected void concurrentStateTranferHelper(boolean largeState, boolean useDispatcher) { String[] names = null; // mux applications on top of same channel have to have unique name if(isMuxChannelUsed()){ names = createMuxApplicationNames(1); }else{ names = new String[] { "A", "B", "C", "D" }; } int count = names.length; ConcurrentStateTransfer[] channels = new ConcurrentStateTransfer[count]; // Create a semaphore and take all its tickets Semaphore semaphore = new Semaphore(count); try{ semaphore.acquire(count); // Create activation threads that will block on the semaphore for(int i = 0;i < count;i++){ if(largeState){ if(isMuxChannelUsed()){ channels[i] = new ConcurrentLargeStateTransfer(names[i], muxFactory[i % getMuxFactoryCount()], semaphore); }else{ channels[i] = new ConcurrentLargeStateTransfer(names[i], semaphore, useDispatcher); } }else{ if(isMuxChannelUsed()){ channels[i] = new ConcurrentStateTransfer(names[i], muxFactory[i % getMuxFactoryCount()], semaphore); }else{ channels[i] = new ConcurrentStateTransfer(names[i], semaphore, useDispatcher); } } // Start threads and let them join the channel channels[i].start(); Util.sleep(2000); } // Make sure everyone is in sync if(isMuxChannelUsed()){ blockUntilViewsReceived(channels, getMuxFactoryCount(), 60000); }else{ blockUntilViewsReceived(channels, 60000); } Util.sleep(2000); // Unleash hell ! semaphore.release(count); // Sleep to ensure the threads get all the semaphore tickets Util.sleep(2000); // Reacquire the semaphore tickets; when we have them all // we know the threads are done boolean acquired = semaphore.tryAcquire(count, 20, TimeUnit.SECONDS); if(!acquired){ log.warn("Most likely a bug, analyse the stack below:"); log.warn(Util.dumpThreads()); } // Sleep to ensure async message arrive Util.sleep(6000); // do test verification List[] lists = new List[count]; for(int i = 0;i < count;i++){ lists[i] = channels[i].getList(); } Map[] mods = new Map[count]; for(int i = 0;i < count;i++){ mods[i] = channels[i].getModifications(); } printLists(lists); printModifications(mods); int len = lists.length; for(int i = 0;i < lists.length;i++){ List l = lists[i]; assertEquals("list #" + i + " should have " + len + " elements", len, l.size()); } }catch(Exception ex){ log.warn("Exception encountered during test", ex); fail(ex.getLocalizedMessage()); }finally{ for(ConcurrentStateTransfer channel:channels){ channel.cleanup(); Util.sleep(2000); // remove before 2.6 GA } } } protected int getMod() { synchronized(this){ int retval = mod; mod++; return retval; } } protected void printModifications(Map[] modifications) { for(int i = 0;i < modifications.length;i++){ Map modification = modifications[i]; log.info("modifications for #" + i + ": " + modification); } } protected void printLists(List[] lists) { for(int i = 0;i < lists.length;i++){ List l = lists[i]; log.info(i + ": " + l); } } protected class ConcurrentStateTransfer extends ConcurrentStartupChannel { public ConcurrentStateTransfer(String name,Semaphore semaphore,boolean useDispatcher) throws Exception{ super(name, semaphore, useDispatcher); channel.connect("test"); } public ConcurrentStateTransfer(String name,JChannelFactory factory,Semaphore semaphore) throws Exception{ super(name, factory, semaphore); channel.connect("test"); } public void useChannel() throws Exception { boolean success = channel.getState(null, 30000); log.info("channel.getState at " + getName() + getLocalAddress() + " returned " + success); channel.send(null, null, channel.getLocalAddress()); } } protected class ConcurrentLargeStateTransfer extends ConcurrentStateTransfer { private static final long TRANSFER_TIME = 5000; public ConcurrentLargeStateTransfer(String name,Semaphore semaphore,boolean useDispatcher) throws Exception{ super(name, semaphore, useDispatcher); } public ConcurrentLargeStateTransfer(String name,JChannelFactory factory,Semaphore semaphore) throws Exception{ super(name, factory, semaphore); } public void setState(byte[] state) { Util.sleep(TRANSFER_TIME); super.setState(state); } public byte[] getState() { Util.sleep(TRANSFER_TIME); return super.getState(); } public void getState(OutputStream ostream) { Util.sleep(TRANSFER_TIME); super.getState(ostream); } public void setState(InputStream istream) { Util.sleep(TRANSFER_TIME); super.setState(istream); } } protected class ConcurrentStartupChannelWithLargeState extends ConcurrentStartupChannel { private static final long TRANSFER_TIME = 5000; public ConcurrentStartupChannelWithLargeState(Semaphore semaphore, String name, boolean useDispatcher) throws Exception{ super(name, semaphore, useDispatcher); } public ConcurrentStartupChannelWithLargeState(String name, JChannelFactory f, Semaphore semaphore) throws Exception{ super(name, f, semaphore); } public void setState(byte[] state) { Util.sleep(TRANSFER_TIME); super.setState(state); } public byte[] getState() { Util.sleep(TRANSFER_TIME); return super.getState(); } public void getState(OutputStream ostream) { Util.sleep(TRANSFER_TIME); super.getState(ostream); } public void setState(InputStream istream) { Util.sleep(TRANSFER_TIME); super.setState(istream); } } protected class ConcurrentStartupChannel extends PushChannelApplicationWithSemaphore { final List l = new LinkedList(); Channel ch; int modCount = 1; final Map mods = new TreeMap(); public ConcurrentStartupChannel(String name,JChannelFactory f,Semaphore semaphore) throws Exception{ super(name, f, semaphore); } public ConcurrentStartupChannel(String name,Semaphore semaphore,boolean useDispatcher) throws Exception{ super(name, semaphore, useDispatcher); } public void useChannel() throws Exception { channel.connect("test", null, null, 25000); channel.send(null, null, channel.getLocalAddress()); } List getList() { return l; } Map getModifications() { return mods; } public void receive(Message msg) { if(msg.getBuffer() == null) return; Object obj = msg.getObject(); log.info("-- [#" + getName() + " (" + channel.getLocalAddress() + ")]: received " + obj); synchronized(this){ l.add(obj); Integer key = new Integer(getMod()); mods.put(key, obj); } } public void viewAccepted(View new_view) { super.viewAccepted(new_view); synchronized(this){ Integer key = new Integer(getMod()); mods.put(key, new_view.getVid()); } } public void setState(byte[] state) { super.setState(state); try{ List tmp = (List) Util.objectFromByteBuffer(state); synchronized(this){ l.clear(); l.addAll(tmp); log.info("-- [#" + getName() + " (" + channel.getLocalAddress() + ")]: state is " + l); Integer key = new Integer(getMod()); mods.put(key, tmp); } }catch(Exception e){ e.printStackTrace(); } } public byte[] getState() { super.getState(); List tmp = null; synchronized(this){ tmp = new LinkedList(l); try{ return Util.objectToByteBuffer(tmp); }catch(Exception e){ e.printStackTrace(); return null; } } } public void getState(OutputStream ostream) { super.getState(ostream); ObjectOutputStream oos = null; try{ oos = new ObjectOutputStream(ostream); List tmp = null; synchronized(this){ tmp = new LinkedList(l); } oos.writeObject(tmp); oos.flush(); }catch(IOException e){ e.printStackTrace(); }finally{ Util.close(oos); } } public void setState(InputStream istream) { super.setState(istream); ObjectInputStream ois = null; try{ ois = new ObjectInputStream(istream); List tmp = (List) ois.readObject(); synchronized(this){ l.clear(); l.addAll(tmp); log.info("-- [#" + getName() + " (" + channel.getLocalAddress() + ")]: state is " + l); Integer key = new Integer(getMod()); mods.put(key, tmp); } }catch(Exception e){ e.printStackTrace(); }finally{ Util.close(ois); } } } public static Test suite() { return new TestSuite(ConcurrentStartupTest.class); } public static void main(String[] args) { String[] testCaseName = { ConcurrentStartupTest.class.getName() }; junit.textui.TestRunner.main(testCaseName); } }
package com.badlogic.gdx.maps.tiled; import com.badlogic.gdx.assets.AssetLoaderParameters; import com.badlogic.gdx.assets.loaders.AsynchronousAssetLoader; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.maps.ImageResolver; import com.badlogic.gdx.maps.MapLayer; import com.badlogic.gdx.maps.MapObject; import com.badlogic.gdx.maps.MapProperties; import com.badlogic.gdx.maps.objects.EllipseMapObject; import com.badlogic.gdx.maps.objects.PolygonMapObject; import com.badlogic.gdx.maps.objects.PolylineMapObject; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.maps.objects.TextureMapObject; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer.Cell; import com.badlogic.gdx.math.Polygon; import com.badlogic.gdx.math.Polyline; import com.badlogic.gdx.utils.Base64Coder; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.StreamUtils; import com.badlogic.gdx.utils.XmlReader; import com.badlogic.gdx.utils.XmlReader.Element; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.StringTokenizer; import java.util.zip.GZIPInputStream; import java.util.zip.InflaterInputStream; public abstract class BaseTmxMapLoader<P extends AssetLoaderParameters<TiledMap>> extends AsynchronousAssetLoader<TiledMap, P> { public static class Parameters extends AssetLoaderParameters<TiledMap> { /** generate mipmaps? **/ public boolean generateMipMaps = false; /** The TextureFilter to use for minification **/ public TextureFilter textureMinFilter = TextureFilter.Nearest; /** The TextureFilter to use for magnification **/ public TextureFilter textureMagFilter = TextureFilter.Nearest; /** Whether to convert the objects' pixel position and size to the equivalent in tile space. **/ public boolean convertObjectToTileSpace = false; } protected static final int FLAG_FLIP_HORIZONTALLY = 0x80000000; protected static final int FLAG_FLIP_VERTICALLY = 0x40000000; protected static final int FLAG_FLIP_DIAGONALLY = 0x20000000; protected static final int MASK_CLEAR = 0xE0000000; protected XmlReader xml = new XmlReader(); protected Element root; protected boolean convertObjectToTileSpace; protected int mapTileWidth; protected int mapTileHeight; protected int mapWidthInPixels; protected int mapHeightInPixels; protected TiledMap map; public BaseTmxMapLoader (FileHandleResolver resolver) { super(resolver); } protected void loadTileLayer (TiledMap map, Element element) { if (element.getName().equals("layer")) { int width = element.getIntAttribute("width", 0); int height = element.getIntAttribute("height", 0); int tileWidth = element.getParent().getIntAttribute("tilewidth", 0); int tileHeight = element.getParent().getIntAttribute("tileheight", 0); TiledMapTileLayer layer = new TiledMapTileLayer(width, height, tileWidth, tileHeight); loadBasicLayerInfo(layer, element); int[] ids = getTileIds(element, width, height); TiledMapTileSets tilesets = map.getTileSets(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int id = ids[y * width + x]; boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0); boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0); boolean flipDiagonally = ((id & FLAG_FLIP_DIAGONALLY) != 0); TiledMapTile tile = tilesets.getTile(id & ~MASK_CLEAR); if (tile != null) { Cell cell = createTileLayerCell(flipHorizontally, flipVertically, flipDiagonally); cell.setTile(tile); layer.setCell(x, height - 1 - y, cell); } } } Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(layer.getProperties(), properties); } map.getLayers().add(layer); } } protected void loadObjectGroup (TiledMap map, Element element) { if (element.getName().equals("objectgroup")) { String name = element.getAttribute("name", null); MapLayer layer = new MapLayer(); layer.setName(name); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(layer.getProperties(), properties); } for (Element objectElement : element.getChildrenByName("object")) { loadObject(map, layer, objectElement); } map.getLayers().add(layer); } } protected void loadImageLayer (TiledMap map, Element element, FileHandle tmxFile, ImageResolver imageResolver) { if (element.getName().equals("imagelayer")) { int x = Integer.parseInt(element.getAttribute("x", "0")); int y = mapHeightInPixels - Integer.parseInt(element.getAttribute("y", "0")); TextureRegion texture = null; Element image = element.getChildByName("image"); if (image != null) { String source = image.getAttribute("source"); FileHandle handle = getRelativeFileHandle(tmxFile, source); texture = imageResolver.getImage(handle.path()); y -= texture.getRegionHeight(); } TiledMapImageLayer layer = new TiledMapImageLayer(texture, x, y); loadBasicLayerInfo(layer, element); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(layer.getProperties(), properties); } map.getLayers().add(layer); } } protected void loadBasicLayerInfo (MapLayer layer, Element element) { String name = element.getAttribute("name", null); float opacity = Float.parseFloat(element.getAttribute("opacity", "1.0")); boolean visible = element.getIntAttribute("visible", 1) == 1; layer.setName(name); layer.setOpacity(opacity); layer.setVisible(visible); } protected void loadObject (TiledMap map, MapLayer layer, Element element) { if (element.getName().equals("object")) { MapObject object = null; float scaleX = convertObjectToTileSpace ? 1.0f / mapTileWidth : 1.0f; float scaleY = convertObjectToTileSpace ? 1.0f / mapTileHeight : 1.0f; float x = element.getFloatAttribute("x", 0) * scaleX; float y = (mapHeightInPixels - element.getFloatAttribute("y", 0)) * scaleY; float width = element.getFloatAttribute("width", 0) * scaleX; float height = element.getFloatAttribute("height", 0) * scaleY; if (element.getChildCount() > 0) { Element child = null; if ((child = element.getChildByName("polygon")) != null) { String[] points = child.getAttribute("points").split(" "); float[] vertices = new float[points.length * 2]; for (int i = 0; i < points.length; i++) { String[] point = points[i].split(","); vertices[i * 2] = Float.parseFloat(point[0]) * scaleX; vertices[i * 2 + 1] = -Float.parseFloat(point[1]) * scaleY; } Polygon polygon = new Polygon(vertices); polygon.setPosition(x, y); object = new PolygonMapObject(polygon); } else if ((child = element.getChildByName("polyline")) != null) { String[] points = child.getAttribute("points").split(" "); float[] vertices = new float[points.length * 2]; for (int i = 0; i < points.length; i++) { String[] point = points[i].split(","); vertices[i * 2] = Float.parseFloat(point[0]) * scaleX; vertices[i * 2 + 1] = -Float.parseFloat(point[1]) * scaleY; } Polyline polyline = new Polyline(vertices); polyline.setPosition(x, y); object = new PolylineMapObject(polyline); } else if ((child = element.getChildByName("ellipse")) != null) { object = new EllipseMapObject(x, y - height, width, height); } } if (object == null) { String gid = null; if ((gid = element.getAttribute("gid", null)) != null) { int id = (int)Long.parseLong(gid); boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0); boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0); TiledMapTile tile = map.getTileSets().getTile(id & ~MASK_CLEAR); TextureRegion textureRegion = new TextureRegion(tile.getTextureRegion()); textureRegion.flip(flipHorizontally, flipVertically); TextureMapObject textureMapObject = new TextureMapObject(textureRegion); textureMapObject.getProperties().put("gid", id); textureMapObject.setX(x); textureMapObject.setY(y - height); textureMapObject.setScaleX(scaleX); textureMapObject.setScaleY(scaleY); textureMapObject.setRotation(element.getFloatAttribute("rotation", 0)); object = textureMapObject; } else { object = new RectangleMapObject(x, y - height, width, height); } } object.setName(element.getAttribute("name", null)); String rotation = element.getAttribute("rotation", null); if (rotation != null) { object.getProperties().put("rotation", Float.parseFloat(rotation)); } String type = element.getAttribute("type", null); if (type != null) { object.getProperties().put("type", type); } object.getProperties().put("x", x * scaleX); object.getProperties().put("y", (y - height) * scaleY); object.getProperties().put("width", width); object.getProperties().put("height", height); object.setVisible(element.getIntAttribute("visible", 1) == 1); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(object.getProperties(), properties); } layer.getObjects().add(object); } } protected void loadProperties (MapProperties properties, Element element) { if (element == null) return; if (element.getName().equals("properties")) { for (Element property : element.getChildrenByName("property")) { String name = property.getAttribute("name", null); String value = property.getAttribute("value", null); if (value == null) { value = property.getText(); } properties.put(name, value); } } } protected Cell createTileLayerCell (boolean flipHorizontally, boolean flipVertically, boolean flipDiagonally) { Cell cell = new Cell(); if (flipDiagonally) { if (flipHorizontally && flipVertically) { cell.setFlipHorizontally(true); cell.setRotation(Cell.ROTATE_270); } else if (flipHorizontally) { cell.setRotation(Cell.ROTATE_270); } else if (flipVertically) { cell.setRotation(Cell.ROTATE_90); } else { cell.setFlipVertically(true); cell.setRotation(Cell.ROTATE_270); } } else { cell.setFlipHorizontally(flipHorizontally); cell.setFlipVertically(flipVertically); } return cell; } static public int[] getTileIds (Element element, int width, int height) { Element data = element.getChildByName("data"); String encoding = data.getAttribute("encoding", null); if (encoding == null) { // no 'encoding' attribute means that the encoding is XML throw new GdxRuntimeException("Unsupported encoding (XML) for TMX Layer Data"); } int[] ids = new int[width * height]; if (encoding.equals("csv")) { String[] array = data.getText().split(","); for (int i = 0; i < array.length; i++) ids[i] = (int)Long.parseLong(array[i].trim()); } else { if (true) if (encoding.equals("base64")) { InputStream is = null; try { String compression = data.getAttribute("compression", null); byte[] bytes = Base64Coder.decode(data.getText()); if (compression == null) is = new ByteArrayInputStream(bytes); else if (compression.equals("gzip")) is = new GZIPInputStream(new ByteArrayInputStream(bytes), bytes.length); else if (compression.equals("zlib")) is = new InflaterInputStream(new ByteArrayInputStream(bytes)); else throw new GdxRuntimeException("Unrecognised compression (" + compression + ") for TMX Layer Data"); byte[] temp = new byte[4]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int read = is.read(temp); while (read < temp.length) { int curr = is.read(temp, read, temp.length - read); if (curr == -1) break; read += curr; } if (read != temp.length) throw new GdxRuntimeException("Error Reading TMX Layer Data: Premature end of tile data"); ids[y * width + x] = unsignedByteToInt(temp[0]) | unsignedByteToInt(temp[1]) << 8 | unsignedByteToInt(temp[2]) << 16 | unsignedByteToInt(temp[3]) << 24; } } } catch (IOException e) { throw new GdxRuntimeException("Error Reading TMX Layer Data - IOException: " + e.getMessage()); } finally { StreamUtils.closeQuietly(is); } } else { // any other value of 'encoding' is one we're not aware of, probably a feature of a future version of Tiled // or another editor throw new GdxRuntimeException("Unrecognised encoding (" + encoding + ") for TMX Layer Data"); } } return ids; } protected static int unsignedByteToInt (byte b) { return (int)b & 0xFF; } protected static FileHandle getRelativeFileHandle (FileHandle file, String path) { StringTokenizer tokenizer = new StringTokenizer(path, "\\/"); FileHandle result = file.parent(); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); if (token.equals("..")) result = result.parent(); else { result = result.child(token); } } return result; } }
/* * $Log: IteratingPipe.java,v $ * Revision 1.10 2008-05-21 09:40:09 europe\L190409 * added block feature * * Revision 1.9 2008/05/15 15:31:35 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * modified element of timeout * * Revision 1.8 2008/05/15 15:28:55 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added attribute ignoreExceptions * added Xslt facility for each message * * Revision 1.7 2008/02/26 09:18:50 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * * Revision 1.6 2008/02/21 12:49:05 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added option for pushing iteration * * Revision 1.5 2007/10/08 12:23:51 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * changed HashMap to Map where possible * * Revision 1.4 2007/08/03 08:47:16 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * * Revision 1.3 2007/07/17 10:54:25 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * removed unused code * * Revision 1.2 2007/07/17 10:49:42 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * uses now IDataIterator * * Revision 1.1 2007/07/10 08:01:46 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * first version, lightly based on ForEachChildElementPipe * */ package nl.nn.adapterframework.pipes; import java.io.IOException; import java.util.Map; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.core.IDataIterator; import nl.nn.adapterframework.core.ISender; import nl.nn.adapterframework.core.ISenderWithParameters; import nl.nn.adapterframework.core.PipeLineSession; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.core.TimeOutException; import nl.nn.adapterframework.parameters.ParameterResolutionContext; import nl.nn.adapterframework.util.ClassUtils; import nl.nn.adapterframework.util.DomBuilderException; import nl.nn.adapterframework.util.TransformerPool; import nl.nn.adapterframework.util.XmlUtils; import org.apache.commons.lang.StringUtils; * &lt;param name="value-of-current-item" xpathExpression="/*" /&gt; * </pre> * * @author Gerrit van Brakel * @since 4.7 * @version Id */ public abstract class IteratingPipe extends MessageSendingPipe { public static final String version="$RCSfile: IteratingPipe.java,v $ $Revision: 1.10 $ $Date: 2008-05-21 09:40:09 $"; private String stopConditionXPathExpression=null; private boolean removeXmlDeclarationInResults=false; private boolean collectResults=true; private String xpathExpression=null; private String outputType="text"; private String styleSheetName; private boolean omitXmlDeclaration=true; private boolean ignoreExceptions=false; private String blockPrefix="<block>"; private String blockSuffix="</block>"; private int blockSize=0; protected TransformerPool msgTransformerPool; private TransformerPool stopConditionTp=null; private TransformerPool encapsulateResultsTp=null; protected String makeEncapsulatingXslt(String rootElementname,String xpathExpression) { return "<xsl:stylesheet xmlns:xsl=\"http: "<xsl:output method=\"xml\" omit-xml-declaration=\"yes\"/>" + "<xsl:strip-space elements=\"*\"/>" + "<xsl:template match=\"/\">" + "<xsl:element name=\"" + rootElementname + "\">" + "<xsl:copy-of select=\"" + xpathExpression + "\"/>" + "</xsl:element>" + "</xsl:template>" + "</xsl:stylesheet>"; } public void configure() throws ConfigurationException { super.configure(); msgTransformerPool = TransformerPool.configureTransformer(getLogPrefix(null), getXpathExpression(), getStyleSheetName(), getOutputType(), !isOmitXmlDeclaration(), getParameterList(), false); try { if (StringUtils.isNotEmpty(getStopConditionXPathExpression())) { stopConditionTp=new TransformerPool(XmlUtils.createXPathEvaluatorSource(null,getStopConditionXPathExpression(),"xml",false)); } if (isRemoveXmlDeclarationInResults()) { encapsulateResultsTp=new TransformerPool( makeEncapsulatingXslt("result","*")); } } catch (TransformerConfigurationException e) { throw new ConfigurationException(e); } } protected IDataIterator getIterator(Object input, PipeLineSession session, String correlationID, Map threadContext) throws SenderException { return null; } protected void iterateInput(Object input, PipeLineSession session, String correlationID, Map threadContext, ItemCallback callback) throws SenderException { throw new SenderException("Could not obtain iterator and no iterateInput method provided by class ["+ClassUtils.nameOf(this)+"]"); } protected class ItemCallback { PipeLineSession session; String correlationID; ISender sender; ISenderWithParameters psender=null; private String results=""; int count=0; public ItemCallback(PipeLineSession session, String correlationID, ISender sender) { this.session=session; this.correlationID=correlationID; this.sender=sender; if (sender instanceof ISenderWithParameters && getParameterList()!=null) { psender = (ISenderWithParameters) sender; } } public boolean handleItem(String item) throws SenderException, TimeOutException { String itemResult=null; count++; if (log.isDebugEnabled()) { //log.debug(getLogPrefix(session)+"set current item to ["+item+"]"); log.debug(getLogPrefix(session)+"sending item no ["+count+"]"); } ParameterResolutionContext prc=null; if (psender !=null || msgTransformerPool!=null && getParameterList()!=null) { //TODO find out why ParameterResolutionContext cannot be constructed using dom-source prc = new ParameterResolutionContext(item, session, isNamespaceAware()); } if (msgTransformerPool!=null) { try { String transformedMsg=msgTransformerPool.transform(item,prc!=null?prc.getValueMap(getParameterList()):null); if (log.isDebugEnabled()) { log.debug(getLogPrefix(session)+" transformed item ["+item+"] into ["+transformedMsg+"]"); } item=transformedMsg; } catch (Exception e) { throw new SenderException(getLogPrefix(session)+"cannot transform item",e); } } try { if (psender!=null) { //result = psender.sendMessage(correlationID, item, new ParameterResolutionContext(src, session)); itemResult = psender.sendMessage(correlationID, item, prc); } else { itemResult = sender.sendMessage(correlationID, item); } } catch (SenderException e) { if (isIgnoreExceptions()) { log.info(getLogPrefix(session)+"ignoring SenderException after excution of sender for item ["+item+"]",e); itemResult="<exception>"+XmlUtils.encodeChars(e.getMessage())+"</exception>"; } else { throw e; } } catch (TimeOutException e) { if (isIgnoreExceptions()) { log.info(getLogPrefix(session)+"ignoring TimeOutException after excution of sender for item ["+item+"]",e); itemResult="<timeout>"+XmlUtils.encodeChars(e.getMessage())+"</timeout>"; } else { throw e; } } try { if (isCollectResults()) { if (isRemoveXmlDeclarationInResults()) { log.debug(getLogPrefix(session)+"post processing partial result ["+itemResult+"]"); itemResult = getEncapsulateResultsTp().transform(itemResult,null); } else { log.debug(getLogPrefix(session)+"partial result ["+itemResult+"]"); itemResult = "<result>\n"+itemResult+"\n</result>"; } results += itemResult+"\n"; } if (getStopConditionTp()!=null) { String stopConditionResult = getStopConditionTp().transform(itemResult,null); if (StringUtils.isNotEmpty(stopConditionResult) && !stopConditionResult.equalsIgnoreCase("false")) { log.debug(getLogPrefix(session)+"stopcondition result ["+stopConditionResult+"], stopping loop"); return false; } else { log.debug(getLogPrefix(session)+"stopcondition result ["+stopConditionResult+"], continueing loop"); } } return true; } catch (DomBuilderException e) { throw new SenderException(getLogPrefix(session)+"cannot parse input",e); } catch (TransformerException e) { throw new SenderException(getLogPrefix(session)+"cannot serialize item",e); } catch (IOException e) { throw new SenderException(getLogPrefix(session)+"cannot serialize item",e); } } public String getResults() { return results; } public int getCount() { return count; } } protected String sendMessage(Object input, PipeLineSession session, String correlationID, ISender sender, Map threadContext) throws SenderException, TimeOutException { // sendResult has a messageID for async senders, the result for sync senders boolean keepGoing = true; IDataIterator it=null; try { ItemCallback callback = new ItemCallback(session,correlationID,sender); it = getIterator(input,session, correlationID,threadContext); if (it==null) { iterateInput(input,session,correlationID, threadContext, callback); } else { while (keepGoing && it.hasNext()) { StringBuffer items = new StringBuffer(); if (getBlockSize()>0) { items.append(getBlockPrefix()); for (int i=0; i<getBlockSize() && it.hasNext(); i++) { String item = (String)it.next(); items.append(item); } items.append(getBlockSuffix()); keepGoing = callback.handleItem(items.toString()); } else { String item = (String)it.next(); keepGoing = callback.handleItem(item); } } } String results = ""; if (isCollectResults()) { results = "<results count=\""+callback.getCount()+"\">\n"+callback.getResults()+"</results>"; } else { results = "<results count=\""+callback.getCount()+"\"/>"; } return results; } finally { if (it!=null) { try { it.close(); } catch (Exception e) { log.warn("Exception closing iterator", e); } } } } public void setSender(Object sender) { if (sender instanceof ISender) { super.setSender((ISender)sender); } else { throw new IllegalArgumentException("sender ["+ClassUtils.nameOf(sender)+"] must implment interface ISender"); } } public void setStopConditionXPathExpression(String string) { stopConditionXPathExpression = string; } public String getStopConditionXPathExpression() { return stopConditionXPathExpression; } public void setRemoveXmlDeclarationInResults(boolean b) { removeXmlDeclarationInResults = b; } public boolean isRemoveXmlDeclarationInResults() { return removeXmlDeclarationInResults; } public void setCollectResults(boolean b) { collectResults = b; } public boolean isCollectResults() { return collectResults; } protected TransformerPool getEncapsulateResultsTp() { return encapsulateResultsTp; } protected TransformerPool getStopConditionTp() { return stopConditionTp; } public void setStyleSheetName(String stylesheetName){ this.styleSheetName=stylesheetName; } public String getStyleSheetName() { return styleSheetName; } public void setOmitXmlDeclaration(boolean b) { omitXmlDeclaration = b; } public boolean isOmitXmlDeclaration() { return omitXmlDeclaration; } public void setXpathExpression(String string) { xpathExpression = string; } public String getXpathExpression() { return xpathExpression; } public void setOutputType(String string) { outputType = string; } public String getOutputType() { return outputType; } public void setIgnoreExceptions(boolean b) { ignoreExceptions = b; } public boolean isIgnoreExceptions() { return ignoreExceptions; } public void setBlockPrefix(String string) { blockPrefix = string; } public String getBlockPrefix() { return blockPrefix; } public void setBlockSuffix(String string) { blockSuffix = string; } public String getBlockSuffix() { return blockSuffix; } public void setBlockSize(int i) { blockSize = i; } public int getBlockSize() { return blockSize; } }
package org.oscm.ui.beans; import static org.oscm.ui.common.Constants.REQ_PARAM_TENANT_ID; import static org.oscm.ui.common.Constants.SESSION_PARAM_SAML_LOGOUT_REQUEST; import java.io.IOException; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.oscm.billing.external.pricemodel.service.PriceModel; import org.oscm.internal.intf.MarketplaceService; import org.oscm.internal.types.exception.ObjectNotFoundException; import org.oscm.internal.types.exception.SaaSSystemException; import org.oscm.logging.Log4jLogger; import org.oscm.logging.LoggerFactory; import org.oscm.types.enumtypes.LogMessageIdentifier; import org.oscm.ui.common.*; /** * Managed bean to store session specific values which are not persisted in the * database. * */ @SessionScoped @ManagedBean(name = "sessionBean") public class SessionBean implements Serializable { private static final Log4jLogger logger = LoggerFactory .getLogger(SessionBean.class); public static final String USER_AGENT_HEADER = "user-agent"; private static final long serialVersionUID = -8453011510859899681L; private Boolean ie; private int navHeight = 580; private int navWidth = 240; private Long subscribeToServiceKey; private transient MarketplaceService marketplaceService = null; private Boolean selfRegistrationEnabled = null; /** * The key of the last edited user group. */ private String selectedUserGroupId; /** * The key of the last edited user. */ private String selectedUserIdToEdit; /** * The key of the last selected technical service - applies to technology * provider and supplier (operations on technical and marketable services). */ private long selectedTechnicalServiceKey; /** * The key of the last selected marketable service - applies to supplier * (operations on price model and marketable services). */ private Long selectedServiceKeyForSupplier; /** * The id of the last selected customer - applies to supplier (operations on * customer and price model). */ private String selectedCustomerId; /** * The id of the last selected subscription id - applies to customer * (operations on subscriptions). */ private String selectedSubscriptionId; /** * TODO add jdoc */ private long selectedSubscriptionKey; /** * The id of the last selected User id - */ private String selectedUserId; /** * The key for the selected service */ private Long serviceKeyForPayment; /** * The key of the last selected marketable service - applies to customer * (browsing in marketplace). */ private long selectedServiceKeyForCustomer; /** * The marketplace brand URL which is currently used as a String. */ private Map<String, String> brandUrlMidMapping = new HashMap<>(); /** * Caching marketplace trackingCodes */ private Map<String, String> trackingCodeMapping = new HashMap<>(); /** * The name of selected user group */ private String selectedGroupId; /** * The name of selected tab */ private String selectedTab; /** * The status of check box "Display my operations only" */ private boolean myOperationsOnly = true; /** * The status of check box "Display my processes only check box" */ private boolean myProcessesOnly = true; private PriceModel selectedExternalPriceModel; private String samlLogoutRequest; public boolean isMyOperationsOnly() { return myOperationsOnly; } public void setMyOperationsOnly(boolean myOperationsOnly) { this.myOperationsOnly = myOperationsOnly; } public boolean isMyProcessesOnly() { return myProcessesOnly; } public void setMyProcessesOnly(boolean myProcessesOnly) { this.myProcessesOnly = myProcessesOnly; } /** * Initial state - no service key set */ static int SERIVE_KEY_NOT_SET = 0; /** * A valid service key was given, but service could not be retrieved */ static int SERIVE_KEY_ERROR = -1; /** * @return true if the browser of the current user is an internet explorer */ public boolean isIe() { if (ie != null) { return ie.booleanValue(); } FacesContext context = FacesContext.getCurrentInstance(); if (context == null) { return false; } Object obj = context.getExternalContext().getRequest(); if (!(obj instanceof HttpServletRequest)) { return false; } HttpServletRequest request = (HttpServletRequest) obj; // The user-agent string contains information about which // browser is used to view the pages String useragent = request.getHeader(USER_AGENT_HEADER); if (useragent == null) { ie = Boolean.FALSE; return ie.booleanValue(); } if (useragent.toLowerCase().contains("msie")) { ie = Boolean.TRUE; return ie.booleanValue(); } // Check if browser is IE11 if (useragent.toLowerCase().contains("trident") && useragent.toLowerCase().contains("rv:11")) { ie = Boolean.TRUE; } else { ie = Boolean.FALSE; } return ie.booleanValue(); } /** * @return true if the browser of the current user is an internet explorer */ public boolean isAutoOpenMpLogonDialog() { final FacesContext context = getFacesContext(); if (context == null) { return false; } final Object obj = context.getExternalContext().getRequest(); return obj instanceof HttpServletRequest && Boolean.TRUE.toString() .equals(((ServletRequest) obj).getParameter( Constants.REQ_PARAM_AUTO_OPEN_MP_LOGIN_DIALOG)); } protected HttpServletRequest getRequest() { return (HttpServletRequest) FacesContext.getCurrentInstance() .getExternalContext().getRequest(); } public int getNavWidth() { return navWidth; } public void setNavWidth(int width) { this.navWidth = width; } public int getNavHeight() { return navHeight; } public void setNavHeight(int height) { this.navHeight = height; } public Map<Long, Long> getTableHeightMap() { return new TableHeightMap(navHeight, isIe()); } public void setSelectedTechnicalServiceKey( long selectedTechnicalServiceKey) { this.selectedTechnicalServiceKey = selectedTechnicalServiceKey; } public long getSelectedTechnicalServiceKey() { return selectedTechnicalServiceKey; } public void setSelectedServiceKeyForSupplier(Long selectedServiceKey) { this.selectedServiceKeyForSupplier = selectedServiceKey; } public Long getSelectedServiceKeyForSupplier() { return selectedServiceKeyForSupplier; } public void setSelectedCustomerId(String selectedCustomerId) { this.selectedCustomerId = selectedCustomerId; } public String getSelectedCustomerId() { return selectedCustomerId; } /** * Set the subscription id selected by the customer. * * @param selectedSubscriptionId * the subscription id */ public void setSelectedSubscriptionId(String selectedSubscriptionId) { this.selectedSubscriptionId = selectedSubscriptionId; } /** * Get the subscription id last selected by the customer. * * @return the subscription id */ public String getSelectedSubscriptionId() { return selectedSubscriptionId; } /** * @return the selectedUserId */ public String getSelectedUserId() { return selectedUserId; } /** * @param selectedUserId * the selectedUserId to set */ public void setSelectedUserId(String selectedUserId) { this.selectedUserId = selectedUserId; } public void setSubscribeToServiceKey(Long subscribeToServiceKey) { this.subscribeToServiceKey = subscribeToServiceKey; } public Long getSubscribeToServiceKey() { return subscribeToServiceKey; } public long determineSelectedServiceKeyForCustomer() { if (selectedServiceKeyForCustomer == SERIVE_KEY_NOT_SET) { HttpServletRequest httpRequest = getRequest(); String key = httpRequest .getParameter(Constants.REQ_PARAM_SELECTED_SERVICE_KEY); if (ADMStringUtils.isBlank(key)) { // Bug 9466: Read the service key from temporary cookie // be able to continue a subscription in case of a possible // session timeout String serviceKeyVal = JSFUtils.getCookieValue(httpRequest, Constants.REQ_PARAM_SERVICE_KEY); if (serviceKeyVal != null && serviceKeyVal.length() > 0) selectedServiceKeyForCustomer = Long .parseLong(serviceKeyVal); } } return selectedServiceKeyForCustomer; } public void setServiceKeyForPayment(Long serviceKeyForPayment) { this.serviceKeyForPayment = serviceKeyForPayment; } public Long getServiceKeyForPayment() { return serviceKeyForPayment; } public long getSelectedServiceKeyForCustomer() { return selectedServiceKeyForCustomer; } public void setSelectedServiceKeyForCustomer( long selectedServiceKeyForCustomer) { this.selectedServiceKeyForCustomer = selectedServiceKeyForCustomer; if (isValidServiceKey(selectedServiceKeyForCustomer)) { try { final HttpServletResponse httpResponse = JSFUtils.getResponse(); if (httpResponse != null) { // store the service key in a temporary cookie in order to // be able to continue a subscription in case of a possible // session timeout JSFUtils.setCookieValue(JSFUtils.getRequest(), httpResponse, Constants.REQ_PARAM_SERVICE_KEY, URLEncoder.encode( Long.valueOf(selectedServiceKeyForCustomer) .toString(), Constants.CHARACTER_ENCODING_UTF8), -1); } } catch (SaaSSystemException e) { // Faces context is not initialized, just return logger.logDebug(e.getMessage()); } catch (UnsupportedEncodingException e) { logger.logError(Log4jLogger.SYSTEM_LOG, e, LogMessageIdentifier.ERROR_UNSUPPORTED_ENCODING); } } } public String getMarketplaceBrandUrl() { String marketplaceBrandUrl = brandUrlMidMapping.get(getMarketplaceId()); if (marketplaceBrandUrl == null) { try { marketplaceBrandUrl = getMarketplaceService() .getBrandingUrl(getMarketplaceId()); if (marketplaceBrandUrl == null) { marketplaceBrandUrl = getWhiteLabelBrandingUrl(); } } catch (ObjectNotFoundException e) { marketplaceBrandUrl = getWhiteLabelBrandingUrl(); } setMarketplaceBrandUrl(marketplaceBrandUrl); } return marketplaceBrandUrl; } public void setMarketplaceBrandUrl(String marketplaceBrandUrl) { brandUrlMidMapping.put(getMarketplaceId(), marketplaceBrandUrl); } public String getMarketplaceTrackingCode() { return trackingCodeMapping.get(getMarketplaceId()); } public void setMarketplaceTrackingCode(String marketplaceTrackingCode) { trackingCodeMapping.put(getMarketplaceId(), marketplaceTrackingCode); } public String getMarketplaceId() { return BaseBean.getMarketplaceIdStatic(); } FacesContext getFacesContext() { return FacesContext.getCurrentInstance(); } public String getWhiteLabelBrandingUrl() { return getFacesContext().getExternalContext().getRequestContextPath() + "/marketplace/css/mp.css"; } /** * Checks if the error in the request header was also added to the faces * context. This method is used to avoid that the same error is rendered * twice. * * @return boolean */ public boolean isErrorMessageDuplicate() { FacesContext fc = FacesContext.getCurrentInstance(); String errorKey = (String) getRequest() .getAttribute(Constants.REQ_ATTR_ERROR_KEY); List<Object> params = new ArrayList<>(); for (int i = 0; i < 5; i++) { Object param = getRequest() .getAttribute(Constants.REQ_ATTR_ERROR_PARAM + i); if (param != null) { params.add(param); } } String errorMessage = JSFUtils.getText(errorKey, params.toArray()); return JSFUtils.existMessageInList(fc, errorMessage); } public boolean isHasWarnings() { return JSFUtils.hasWarnings(FacesContext.getCurrentInstance()); } protected MarketplaceService getMarketplaceService() { if (marketplaceService == null) { marketplaceService = ServiceAccess .getServiceAcccessFor(JSFUtils.getRequest().getSession()) .getService(MarketplaceService.class); } return marketplaceService; } public void redirectToIdpLogout() throws IOException { ExternalContext externalContext = getFacesContext().getExternalContext(); externalContext.redirect(getSamlLogoutRequest()); } public void setSelfRegistrationEnabled(Boolean selfRegistrationEnabled) { this.selfRegistrationEnabled = selfRegistrationEnabled; } public Boolean getSelfRegistrationEnabled() { return selfRegistrationEnabled; } public boolean getNameSequenceReversed() { return new UiDelegate().isNameSequenceReversed(); } static boolean isValidServiceKey(long key) { return ((key != SERIVE_KEY_ERROR) && (key != SERIVE_KEY_NOT_SET)); } /** * @return the selectedGroupId */ public String getSelectedGroupId() { return selectedGroupId; } /** * @param selectedGroupId * the selectedGroupId to set */ public void setSelectedGroupId(String selectedGroupId) { this.selectedGroupId = selectedGroupId; } /** * @return the selectedTab */ public String getSelectedTab() { return selectedTab; } /** * @param selectedTab * the selectedTab to set */ public void setSelectedTab(String selectedTab) { this.selectedTab = selectedTab; } /** * @return - selected subscription key */ public long getSelectedSubscriptionKey() { return selectedSubscriptionKey; } /** * @param selectedSubscriptionKey * - the selected subscription key */ public void setSelectedSubscriptionKey(long selectedSubscriptionKey) { this.selectedSubscriptionKey = selectedSubscriptionKey; } public String getSelectedUserGroupId() { return selectedUserGroupId; } public void setSelectedUserGroupId(String selectedUserGroupId) { this.selectedUserGroupId = selectedUserGroupId; } public String getSelectedUserIdToEdit() { return selectedUserIdToEdit; } public void setSelectedUserIdToEdit(String selectedUserIdToEdit) { this.selectedUserIdToEdit = selectedUserIdToEdit; } public PriceModel getSelectedExternalPriceModel() { return selectedExternalPriceModel; } public void setSelectedExternalPriceModel( PriceModel selectedExternalPriceModel) { this.selectedExternalPriceModel = selectedExternalPriceModel; } public void setSamlLogoutRequest(String samlLogoutRequest) { this.samlLogoutRequest = samlLogoutRequest; } public String getSamlLogoutRequest() { return (String) new UiDelegate().getSession().getAttribute(SESSION_PARAM_SAML_LOGOUT_REQUEST); } public String getTenantID() { return (String) new UiDelegate().getSession().getAttribute(REQ_PARAM_TENANT_ID); } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-07-28"); this.setApiVersion("17.5.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package org.bouncycastle.est; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.URISyntaxException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.digests.MD5Digest; import org.bouncycastle.crypto.io.DigestOutputStream; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; /** * Implements DigestAuth. */ public class DigestAuth implements ESTAuth { private final String realm; private final String username; private final String password; // TODO: this needs to be removed private static SecureRandom secureRandom = new SecureRandom(); public DigestAuth(String username, String password) { this.username = username; this.password = password; this.realm = null; } public DigestAuth(String realm, String username, String password) { this.realm = realm; this.username = username; this.password = password; } public ESTRequest applyAuth(final ESTRequest request) { ESTRequest r = request.newWithHijacker(new ESTHijacker() { public ESTResponse hijack(ESTRequest req, Source sock) throws IOException { ESTResponse res = new ESTResponse(req, sock); if (res.getStatusCode() == 401 && res.getHeader("WWW-Authenticate").startsWith("Digest")) { res = doDigestFunction(res); } return res; } }); return r; } protected ESTResponse doDigestFunction(ESTResponse res) throws IOException { res.close(); // Close off the last request. ESTRequest req = res.getOriginalRequest(); Map<String, String> parts = HttpUtil.splitCSL("Digest", res.getHeader("WWW-Authenticate")); String uri = null; try { uri = req.getUrl().toURI().getPath(); } catch (URISyntaxException e) { throw new IOException("unable to process URL in request: " + e.getMessage()); } String method = req.getMethod(); String realm = parts.get("realm"); String nonce = parts.get("nonce"); String opaque = parts.get("opaque"); String algorithm = parts.get("algorithm"); String qop = parts.get("qop"); List<String> qopMods = new ArrayList<String>(); // Preserve ordering. // Override the realm supplied by the server. if (this.realm != null) { realm = this.realm; } // If an algorithm is not specified, default to MD5. if (algorithm == null) { algorithm = "MD5"; } algorithm = Strings.toLowerCase(algorithm); if (qop != null) { qop = Strings.toLowerCase(qop); String[] s = qop.split(","); for (String j : s) { String jt = j.trim(); if (qopMods.contains(jt)) { continue; } qopMods.add(jt); } } else { qopMods.add("missing"); } Digest dig = null; if (algorithm.equals("md5") || algorithm.equals("md5-sess")) { dig = new MD5Digest(); } byte[] ha1 = null; byte[] ha2 = null; ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(bos); String crnonce = makeNonce(10); // TODO arbitrary? if (algorithm.equals("md5-sess")) { pw.print(username); pw.print(":"); pw.print(realm); pw.print(":"); pw.print(password); pw.flush(); String cs = Hex.toHexString(takeDigest(dig, bos.toByteArray())); bos.reset(); pw.print(cs); pw.print(":"); pw.print(nonce); pw.print(":"); pw.print(crnonce); pw.flush(); ha1 = takeDigest(dig, bos.toByteArray()); } else { pw.print(username); pw.print(":"); pw.print(realm); pw.print(":"); pw.print(password); pw.flush(); ha1 = takeDigest(dig, bos.toByteArray()); } String hashHa1 = Hex.toHexString(ha1); bos.reset(); if (qopMods.get(0).equals("auth-int")) { bos.reset(); pw.write(method); pw.write(':'); pw.write(uri); pw.write(':'); dig.reset(); // Digest body DigestOutputStream dos = new DigestOutputStream(dig); req.getWriter().ready(dos); dos.flush(); byte[] b = new byte[dig.getDigestSize()]; dig.doFinal(b, 0); pw.write(Hex.toHexString(b)); pw.flush(); ha2 = bos.toByteArray(); } else if (qopMods.get(0).equals("auth")) { bos.reset(); pw.write(method); pw.write(':'); pw.write(uri); pw.flush(); ha2 = bos.toByteArray(); } String hashHa2 = Hex.toHexString(takeDigest(dig, ha2)); bos.reset(); byte[] digestResult; if (qopMods.contains("missing")) { pw.write(hashHa1); pw.write(':'); pw.write(nonce); pw.write(':'); pw.write(hashHa2); pw.flush(); digestResult = bos.toByteArray(); } else { pw.write(hashHa1); pw.write(':'); pw.write(nonce); pw.write(':'); pw.write("00000001"); pw.write(':'); pw.write(crnonce); pw.write(':'); if (qopMods.get(0).equals("auth-int")) { pw.write("auth-int"); } else { pw.write("auth"); } pw.write(':'); pw.write(hashHa2); pw.flush(); digestResult = bos.toByteArray(); } String digest = Hex.toHexString(takeDigest(dig, digestResult)); Map<String, String> hdr = new HashMap<String, String>(); hdr.put("username", username); hdr.put("realm", realm); hdr.put("nonce", nonce); hdr.put("uri", uri); hdr.put("response", digest); if (qopMods.get(0).equals("auth-int")) { hdr.put("qop", "auth-int"); hdr.put("nc", "00000001"); hdr.put("cnonce", crnonce); } else if (qopMods.get(0).equals("auth")) { hdr.put("qop", "auth"); hdr.put("nc", "00000001"); hdr.put("cnonce", crnonce); } hdr.put("algorithm", algorithm); if (opaque == null || opaque.length() == 0) { hdr.put("opaque", makeNonce(20)); } ESTRequest answer = req.newWithHijacker(null); answer.setHeader("Authorization", HttpUtil.mergeCSL("Digest", hdr)); return req.getEstClient().doRequest(answer); } private byte[] takeDigest(Digest dig, byte[] b) { dig.reset(); dig.update(b, 0, b.length); byte[] o = new byte[dig.getDigestSize()]; dig.doFinal(o, 0); return o; } private static String makeNonce(int len) { byte[] b = new byte[len]; secureRandom.nextBytes(b); return Hex.toHexString(b); } //f0386ad8a5dfdc3d77914c5442c24233 }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:17-12-02"); this.setApiVersion("3.3.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package me.everything.inbloom; import junit.framework.TestCase; import java.io.InvalidObjectException; public class BloomFilterTest extends TestCase { public void testCreateFilterWithBadParameters() { try { BloomFilter bf = new BloomFilter( -1, 0.01 ); fail( "should have thrown an exception" ); } catch( RuntimeException e ) { assertEquals( "Invalid params for bloom filter", e.getMessage() ); } // Error value cannot be arbitrarily close to zero. Must be bounded. try { BloomFilter bf = new BloomFilter( 1, 0.000000001 ); fail( "should have thrown an exception: error value is not bounded by a precision or tolerance value." ); } catch( RuntimeException e ) { assertEquals( "Invalid params for bloom filter", e.getMessage() ); } // Creating an unusable bloom filter (zero bits, zero hashes) should fail. try { BloomFilter bf = new BloomFilter(199, 1.0); fail( "should have thrown an exception: created an unusable bloom filter with zero bits and zero hashes." ); } catch( RuntimeException e ) { assertEquals( "Invalid params for bloom filter", e.getMessage() ); } // Giving it an error value that is too big should fail. try { BloomFilter bf = new BloomFilter(199, 100.0); fail( "should have thrown an exception: error value is too big." ); } catch( RuntimeException e ) { assertEquals( "Invalid params for bloom filter", e.getMessage() ); } // Adding more data than expected should fail. try { byte []data = "add more entries than bytes available".getBytes(); BloomFilter bf0 = new BloomFilter(data, 1, 0.1); fail( "should have thrown an exception: too much data." ); } catch( RuntimeException e ) { assertEquals( "Expected 1 bytes, got 37", e.getMessage() ); } } public void testValuesFromPublicAPI() { BloomFilter bf = null; assertEquals(0.000000001, bf.errorPrecision); bf = new BloomFilter(1, 0.01); assertEquals(2, bf.bytes); assertEquals(1, bf.entries); assertEquals(0.01, bf.error); assertEquals(9, bf.bits); assertEquals(7, bf.hashes); bf = new BloomFilter(1, 0.1); assertEquals(1, bf.bytes); assertEquals(1, bf.entries); assertEquals(0.1, bf.error); assertEquals(4, bf.bits); assertEquals(4, bf.hashes); bf = new BloomFilter(8, 0.000001); assertEquals(29, bf.bytes); assertEquals(8, bf.entries); assertEquals(0.000001, bf.error); assertEquals(230, bf.bits); assertEquals(20, bf.hashes); } public void testFilter() throws InvalidObjectException { BloomFilter bf = new BloomFilter(20, 0.01); bf.add("foo"); bf.add("bar"); bf.add("foosdfsdfs"); bf.add("fossdfsdfo"); bf.add("foasdfasdfasdfasdfo"); bf.add("foasdfasdfasdasdfasdfasdfasdfasdfo"); assertTrue(bf.contains("foo")); assertTrue(bf.contains("bar")); assertFalse(bf.contains("baz")); assertFalse(bf.contains("faskdjfhsdkfjhsjdkfhskdjfh")); BloomFilter bf2 = new BloomFilter(bf.bf, bf.entries, bf.error); assertTrue(bf2.contains("foo")); assertTrue(bf2.contains("bar")); assertFalse(bf2.contains("baz")); assertFalse(bf2.contains("faskdjfhsdkfjhsjdkfhskdjfh")); String serialized = BinAscii.hexlify(BloomFilter.dump(bf)); System.out.printf("Serialized: %s\n", serialized); String hexPayload = "620d006400000014000000000020001000080000000000002000100008000400"; BloomFilter deserialized = BloomFilter.load(BinAscii.unhexlify(hexPayload)); String dump = BinAscii.hexlify(BloomFilter.dump(deserialized)); System.out.printf("Re-Serialized: %s\n", dump); assertEquals(dump.toLowerCase(), hexPayload); //BloomFilter deserialized = BloomFilter.load(BloomFilter.dump(bf)); assertEquals(deserialized.entries, 20); assertEquals(deserialized.error, 0.01); assertTrue(deserialized.contains("abc")); } }
package com.intellij.pom; /** * Represents an instance which can be shown in the IDE (e.g. a file, a specific location inside a file, etc). * <p/> * Many {@link com.intellij.psi.PsiElement}s implement this interface (see {@link com.intellij.psi.NavigatablePsiElement}). To create an * instance which opens a file in editor and put caret to a specific location use {@link com.intellij.openapi.fileEditor.OpenFileDescriptor}. */ public interface Navigatable { /** * Open editor and select/navigate to the object there if possible. * Just do nothing if navigation is not possible like in case of a package * * @param requestFocus {@code true} if focus requesting is necessary */ void navigate(boolean requestFocus); /** * Indicates whether this instance supports navigation of any kind. * Usually this method is called to ensure that navigation is possible. * Note that it is not called if navigation to source is supported, * i.e. {@link #canNavigateToSource()} returns {@code true}. * We assume that this method should return {@code true} in such case, * so implement this method respectively. * * @return {@code false} if navigation is not possible for any reason. */ boolean canNavigate(); /** * Indicates whether this instance supports navigation to source (that means some kind of editor). * Note that navigation can be supported even if this method returns {@code false}. * In such cases it is not recommended to do batch navigation for all navigatables * available via {@link com.intellij.openapi.actionSystem.CommonDataKeys#NAVIGATABLE_ARRAY}, * because it may lead to opening several modal dialogs. * Use {@link com.intellij.util.OpenSourceUtil#navigate} to process such arrays correctly. * * @return {@code false} if navigation to source is not possible for any reason. */ boolean canNavigateToSource(); }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:20-07-30"); this.setApiVersion("16.7.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package io.branch.referral; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; /** * <p>Class that provides a chooser dialog with customised share options to share a link. * Class provides customised and easy way of sharing a deep link with other applications. </p> */ class ShareLinkManager { /* The custom chooser dialog for selecting an application to share the link. */ AnimatedDialog shareDlg_; Branch.BranchLinkShareListener callback_; Branch.IChannelProperties channelPropertiesCallback_; /* List of apps available for sharing. */ private List<ResolveInfo> appList_; /* Intent for sharing with selected application.*/ private Intent shareLinkIntent_; /* Background color for the list view in enabled state. */ private final int BG_COLOR_ENABLED = Color.argb(60, 17, 4, 56); /* Background color for the list view in disabled state. */ private final int BG_COLOR_DISABLED = Color.argb(20, 17, 4, 56); /* Current activity context.*/ Context context_; /* Default height for the list item.*/ private static int viewItemMinHeight_ = 100; /* Indicates whether a sharing is in progress*/ private boolean isShareInProgress_ = false; /* Styleable resource for share sheet.*/ private int shareDialogThemeID_ = -1; private Branch.ShareLinkBuilder builder_; final int padding = 5; final int leftMargin = 100; /** * Creates an application selector and shares a link on user selecting the application. * * @param builder A {@link io.branch.referral.Branch.ShareLinkBuilder} instance to build share link. * @return Instance of the {@link Dialog} holding the share view. Null if sharing dialog is not created due to any error. */ public Dialog shareLink(Branch.ShareLinkBuilder builder) { builder_ = builder; context_ = builder.getActivity(); callback_ = builder.getCallback(); channelPropertiesCallback_ = builder.getChannelPropertiesCallback(); shareLinkIntent_ = new Intent(Intent.ACTION_SEND); shareLinkIntent_.setType("text/plain"); shareDialogThemeID_ = builder.getStyleResourceID(); try { createShareDialog(builder.getPreferredOptions()); } catch (Exception e) { e.printStackTrace(); if (callback_ != null) { callback_.onLinkShareResponse(null, null, new BranchError("Trouble sharing link", BranchError.ERR_BRANCH_NO_SHARE_OPTION)); } else { Log.i("BranchSDK", "Unable create share options. Couldn't find applications on device to share the link."); } } return shareDlg_; } /** * Dismiss the share dialog if showing. Should be called on activity stopping. * * @param animateClose A {@link Boolean} to specify whether to close the dialog with an animation. * A value of true will close the dialog with an animation. Setting this value * to false will close the Dialog immediately. */ public void cancelShareLinkDialog(boolean animateClose) { if (shareDlg_ != null && shareDlg_.isShowing()) { if (animateClose) { // Cancel the dialog with animation shareDlg_.cancel(); } else { // Dismiss the dialog immediately shareDlg_.dismiss(); } } } /** * Create a custom chooser dialog with available share options. * * @param preferredOptions List of {@link io.branch.referral.SharingHelper.SHARE_WITH} options. */ private void createShareDialog(List<SharingHelper.SHARE_WITH> preferredOptions) { final PackageManager packageManager = context_.getPackageManager(); final List<ResolveInfo> preferredApps = new ArrayList<>(); final List<ResolveInfo> matchingApps = packageManager.queryIntentActivities(shareLinkIntent_, PackageManager.MATCH_DEFAULT_ONLY); ArrayList<SharingHelper.SHARE_WITH> packagesFilterList = new ArrayList<>(preferredOptions); /* Get all apps available for sharing and the available preferred apps. */ for (ResolveInfo resolveInfo : matchingApps) { SharingHelper.SHARE_WITH foundMatching = null; String packageName = resolveInfo.activityInfo.packageName; for (SharingHelper.SHARE_WITH PackageFilter : packagesFilterList) { if (resolveInfo.activityInfo != null && packageName.toLowerCase().contains(PackageFilter.toString().toLowerCase())) { foundMatching = PackageFilter; break; } } if (foundMatching != null) { preferredApps.add(resolveInfo); preferredOptions.remove(foundMatching); } } /* Create all app list with copy link item. */ matchingApps.removeAll(preferredApps); matchingApps.addAll(0, preferredApps); matchingApps.add(new CopyLinkItem()); preferredApps.add(new CopyLinkItem()); if (preferredApps.size() > 1) { /* Add more and copy link option to preferred app.*/ if (matchingApps.size() > preferredApps.size()) { preferredApps.add(new MoreShareItem()); } appList_ = preferredApps; } else { appList_ = matchingApps; } /* Copy link option will be always there for sharing. */ final ChooserArrayAdapter adapter = new ChooserArrayAdapter(); final ListView shareOptionListView; if (shareDialogThemeID_ > 1 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { shareOptionListView = new ListView(context_, null, 0, shareDialogThemeID_); } else { shareOptionListView = new ListView(context_); } shareOptionListView.setHorizontalFadingEdgeEnabled(false); shareOptionListView.setBackgroundColor(Color.WHITE); if (builder_.getSharingTitleView() != null) { shareOptionListView.addHeaderView(builder_.getSharingTitleView()); } else if (!TextUtils.isEmpty(builder_.getSharingTitle())) { TextView textView = new TextView(context_); textView.setText(builder_.getSharingTitle()); textView.setBackgroundColor(BG_COLOR_DISABLED); textView.setTextColor(BG_COLOR_DISABLED); textView.setTextAppearance(context_, android.R.style.TextAppearance_Medium); textView.setTextColor(context_.getResources().getColor(android.R.color.darker_gray)); textView.setPadding(leftMargin, padding, padding, padding); shareOptionListView.addHeaderView(textView); } shareOptionListView.setAdapter(adapter); if (builder_.getDividerHeight() >= 0) { //User set height shareOptionListView.setDividerHeight(builder_.getDividerHeight()); } else if (builder_.getIsFullWidthStyle()) { shareOptionListView.setDividerHeight(0); // Default no divider for full width dialog } shareOptionListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) { if (view.getTag() instanceof MoreShareItem) { appList_ = matchingApps; adapter.notifyDataSetChanged(); } else { if (callback_ != null) { String selectedChannelName = ""; if (view.getTag() != null && context_ != null && ((ResolveInfo) view.getTag()).loadLabel(context_.getPackageManager()) != null) { selectedChannelName = ((ResolveInfo) view.getTag()).loadLabel(context_.getPackageManager()).toString(); } callback_.onChannelSelected(selectedChannelName); } adapter.selectedPos = pos; adapter.notifyDataSetChanged(); invokeSharingClient((ResolveInfo) view.getTag()); if (shareDlg_ != null) { shareDlg_.cancel(); } } } }); shareDlg_ = new AnimatedDialog(context_, builder_.getIsFullWidthStyle()); shareDlg_.setContentView(shareOptionListView); shareDlg_.show(); if (callback_ != null) { callback_.onShareLinkDialogLaunched(); } shareDlg_.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialogInterface) { if (callback_ != null) { callback_.onShareLinkDialogDismissed(); callback_ = null; } // Release context to prevent leaks if (!isShareInProgress_) { context_ = null; builder_ = null; } shareDlg_ = null; } }); } private void invokeSharingClient(final ResolveInfo selectedResolveInfo) { isShareInProgress_ = true; final String channelName = selectedResolveInfo.loadLabel(context_.getPackageManager()).toString(); BranchShortLinkBuilder shortLinkBuilder = builder_.getShortLinkBuilder(); shortLinkBuilder.setChannel(channelName); shortLinkBuilder.generateShortUrl(new Branch.BranchLinkCreateListener() { @Override public void onLinkCreate(String url, BranchError error) { if (error == null) { shareWithClient(selectedResolveInfo, url, channelName); } else { //If there is a default URL specified share it. String defaultUrl = builder_.getDefaultURL(); if (defaultUrl != null && defaultUrl.trim().length() > 0) { shareWithClient(selectedResolveInfo, defaultUrl, channelName); } else { if (callback_ != null) { callback_.onLinkShareResponse(url, channelName, error); } else { Log.i("BranchSDK", "Unable to share link " + error.getMessage()); } } } isShareInProgress_ = false; // Cancel the dialog and context is released on dialog cancel cancelShareLinkDialog(false); } }, true); } private void shareWithClient(ResolveInfo selectedResolveInfo, String url, String channelName) { if (callback_ != null) { callback_.onLinkShareResponse(url, channelName, null); } else { Log.i("BranchSDK", "Shared link with " + channelName); } if (selectedResolveInfo instanceof CopyLinkItem) { addLinkToClipBoard(url, builder_.getShareMsg()); } else { shareLinkIntent_.setPackage(selectedResolveInfo.activityInfo.packageName); String shareSub = builder_.getShareSub(); String shareMsg = builder_.getShareMsg(); if (channelPropertiesCallback_ != null) { String customShareSub = channelPropertiesCallback_.getSharingTitleForChannel(channelName); String customShareMsg = channelPropertiesCallback_.getSharingMessageForChannel(channelName); if (!TextUtils.isEmpty(customShareSub)) { shareSub = customShareSub; } if (!TextUtils.isEmpty(customShareMsg)) { shareMsg = customShareMsg; } } if (shareSub != null && shareSub.trim().length() > 0) { shareLinkIntent_.putExtra(Intent.EXTRA_SUBJECT, shareSub); } shareLinkIntent_.putExtra(Intent.EXTRA_TEXT, shareMsg + "\n" + url); context_.startActivity(shareLinkIntent_); } } /** * Adds a given link to the clip board. * * @param url A {@link String} to add to the clip board * @param label A {@link String} label for the adding link */ @SuppressWarnings("deprecation") @SuppressLint("NewApi") private void addLinkToClipBoard(String url, String label) { int sdk = android.os.Build.VERSION.SDK_INT; if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) { android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context_.getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(url); } else { android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context_.getSystemService(Context.CLIPBOARD_SERVICE); android.content.ClipData clip = android.content.ClipData.newPlainText(label, url); clipboard.setPrimaryClip(clip); } Toast.makeText(context_, builder_.getUrlCopiedMessage(), Toast.LENGTH_SHORT).show(); } /* * Adapter class for creating list of available share options */ private class ChooserArrayAdapter extends BaseAdapter { public int selectedPos = -1; @Override public int getCount() { return appList_.size(); } @Override public Object getItem(int position) { return appList_.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ShareItemView itemView; if (convertView == null) { itemView = new ShareItemView(context_); } else { itemView = (ShareItemView) convertView; } ResolveInfo resolveInfo = appList_.get(position); boolean setSelected = position == selectedPos; itemView.setLabel(resolveInfo.loadLabel(context_.getPackageManager()).toString(), resolveInfo.loadIcon(context_.getPackageManager()), setSelected); itemView.setTag(resolveInfo); itemView.setClickable(false); return itemView; } @Override public boolean isEnabled(int position) { return selectedPos < 0; } } /** * Class for sharing item view to be displayed in the list with Application icon and Name. */ private class ShareItemView extends TextView { Context context_; public ShareItemView(Context context) { super(context); context_ = context; this.setPadding(leftMargin, padding, padding, padding); this.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); this.setMinWidth(context_.getResources().getDisplayMetrics().widthPixels); } public void setLabel(String appName, Drawable appIcon, boolean isEnabled) { this.setText("\t" + appName); this.setTag(appName); if (appIcon == null) { this.setTextAppearance(context_, android.R.style.TextAppearance_Large); this.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); } else { this.setTextAppearance(context_, android.R.style.TextAppearance_Medium); this.setCompoundDrawablesWithIntrinsicBounds(appIcon, null, null, null); viewItemMinHeight_ = Math.max(viewItemMinHeight_, (appIcon.getIntrinsicHeight() + padding)); } this.setMinHeight(viewItemMinHeight_); this.setTextColor(context_.getResources().getColor(android.R.color.black)); if (isEnabled) { this.setBackgroundColor(BG_COLOR_ENABLED); } else { this.setBackgroundColor(BG_COLOR_DISABLED); } } } /** * Class for sharing item more */ private class MoreShareItem extends ResolveInfo { @SuppressWarnings("NullableProblems") @Override public CharSequence loadLabel(PackageManager pm) { return builder_.getMoreOptionText(); } @SuppressWarnings("NullableProblems") @Override public Drawable loadIcon(PackageManager pm) { return builder_.getMoreOptionIcon(); } } /** * Class for Sharing Item copy URl */ private class CopyLinkItem extends ResolveInfo { @SuppressWarnings("NullableProblems") @Override public CharSequence loadLabel(PackageManager pm) { return builder_.getCopyURlText(); } @SuppressWarnings("NullableProblems") @Override public Drawable loadIcon(PackageManager pm) { return builder_.getCopyUrlIcon(); } } }
package com.intellij.facet; import com.intellij.facet.autodetecting.FacetDetectorRegistry; import com.intellij.facet.ui.DefaultFacetSettingsEditor; import com.intellij.facet.ui.FacetEditor; import com.intellij.facet.ui.MultipleFacetSettingsEditor; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.extensions.PluginAware; import com.intellij.openapi.extensions.PluginDescriptor; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleType; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.NlsSafe; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; /** * Override this class to provide custom type of facets. The implementation should be registered in your {@code plugin.xml}: * <pre> * &lt;extensions defaultExtensionNs="com.intellij"&gt; * &nbsp;&nbsp;&lt;facetType implementation="qualified-class-name"/&gt; * &lt;/extensions&gt; * </pre> */ public abstract class FacetType<F extends Facet, C extends FacetConfiguration> implements PluginAware { public static final ExtensionPointName<FacetType> EP_NAME = ExtensionPointName.create("com.intellij.facetType"); private final @NotNull FacetTypeId<F> myId; private final @NotNull String myStringId; @Nls(capitalization = Nls.Capitalization.Title) private final @NotNull String myPresentableName; private final @Nullable FacetTypeId myUnderlyingFacetType; private PluginDescriptor myPluginDescriptor; public static <T extends FacetType> T findInstance(Class<T> aClass) { return EP_NAME.findExtension(aClass); } /** * @param id unique instance of {@link FacetTypeId} * @param stringId unique string id of the facet type * @param presentableName name of this facet type which will be shown in UI * @param underlyingFacetType if this parameter is not {@code null} then you will be able to add facets of this type only as * subfacets to a facet of the specified type. If this parameter is {@code null} it will be possible to add facet of this type * directly to a module */ public FacetType(final @NotNull FacetTypeId<F> id, final @NotNull @NonNls String stringId, final @NotNull @Nls(capitalization = Nls.Capitalization.Title) String presentableName, final @Nullable FacetTypeId underlyingFacetType) { myId = id; myStringId = stringId; myPresentableName = presentableName; myUnderlyingFacetType = underlyingFacetType; } /** * @param id unique instance of {@link FacetTypeId} * @param stringId unique string id of the facet type * @param presentableName name of this facet type which will be shown in UI */ public FacetType(final @NotNull FacetTypeId<F> id, final @NotNull @NonNls String stringId, final @NotNull @Nls(capitalization = Nls.Capitalization.Title) String presentableName) { this(id, stringId, presentableName, null); } @NotNull public final FacetTypeId<F> getId() { return myId; } @NotNull public final String getStringId() { return myStringId; } @NotNull @Nls(capitalization = Nls.Capitalization.Title) public String getPresentableName() { return myPresentableName; } /** * Default name which will be used then user creates a facet of this type. */ @NotNull public @NlsSafe String getDefaultFacetName() { return myPresentableName; } @Nullable public FacetTypeId<?> getUnderlyingFacetType() { return myUnderlyingFacetType; } @Override public void setPluginDescriptor(@NotNull PluginDescriptor pluginDescriptor) { myPluginDescriptor = pluginDescriptor; } public final PluginDescriptor getPluginDescriptor() { return myPluginDescriptor; } /** * @deprecated this method is not called by IDE core anymore. Use {@link com.intellij.framework.detection.FrameworkDetector} extension * to provide automatic detection for facets */ @SuppressWarnings("unused") @Deprecated public void registerDetectors(FacetDetectorRegistry<C> registry) { } /** * Create default configuration of facet. See {@link FacetConfiguration} for details. */ public abstract C createDefaultConfiguration(); /** * Create a new facet instance. * * @param module parent module for facet. Must be passed to {@link Facet} constructor * @param name name of facet. Must be passed to {@link Facet} constructor * @param configuration facet configuration. Must be passed to {@link Facet} constructor * @param underlyingFacet underlying facet. Must be passed to {@link Facet} constructor * @return a created facet */ public abstract F createFacet(@NotNull Module module, final @NlsSafe String name, @NotNull C configuration, @Nullable Facet underlyingFacet); /** * @return {@code true} if only one facet of this type is allowed within the containing module (if this type doesn't have the underlying * facet type) or within the underlying facet */ public boolean isOnlyOneFacetAllowed() { return true; } /** * @param moduleType type of module * @return {@code true} if facet of this type are allowed in module of type {@code moduleType} */ public abstract boolean isSuitableModuleType(ModuleType moduleType); @Nullable public Icon getIcon() { return null; } /** * Returns the topic in the help file which is shown when help for this facet type is requested. * * @return the help topic, or null if no help is available. */ @Nullable @NonNls public String getHelpTopic() { return null; } @Nullable public DefaultFacetSettingsEditor createDefaultConfigurationEditor(@NotNull Project project, @NotNull C configuration) { return null; } /** * Override to allow editing several facets at once. * * @param project project * @param editors editors of selected facets * @return editor */ @Nullable public MultipleFacetSettingsEditor createMultipleConfigurationsEditor(@NotNull Project project, FacetEditor @NotNull [] editors) { return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-10-11"); this.setApiVersion("17.11.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-06-30"); this.setApiVersion("14.1.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:21-11-06"); this.setApiVersion("17.12.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:22-10-13"); this.setApiVersion("18.16.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param language language */ public void setLanguage(String language){ this.requestConfiguration.put("language", language); } /** * language * * @return String */ public String getLanguage(){ if(this.requestConfiguration.containsKey("language")){ return(String) this.requestConfiguration.get("language"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:17-12-23"); this.setApiVersion("3.3.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:20-10-26"); this.setApiVersion("16.10.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package com.mapswithme.maps.widget; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.location.Location; import android.support.v4.view.GestureDetectorCompat; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.ImageSpan; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.webkit.WebView; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.PopupMenu; import android.widget.ScrollView; import android.widget.TextView; import android.widget.TextView.BufferType; import com.mapswithme.maps.Framework; import com.mapswithme.maps.MWMApplication; import com.mapswithme.maps.R; import com.mapswithme.maps.api.ParsedMmwRequest; import com.mapswithme.maps.bookmarks.BookmarkActivity; import com.mapswithme.maps.bookmarks.data.Bookmark; import com.mapswithme.maps.bookmarks.data.BookmarkManager; import com.mapswithme.maps.bookmarks.data.MapObject; import com.mapswithme.maps.bookmarks.data.MapObject.MapObjectType; import com.mapswithme.maps.bookmarks.data.MapObject.Poi; import com.mapswithme.maps.bookmarks.data.MapObject.SearchResult; import com.mapswithme.util.ShareAction; import com.mapswithme.util.UiUtils; import com.mapswithme.util.UiUtils.SimpleAnimationListener; import com.mapswithme.util.Utils; public class MapInfoView extends LinearLayout { private final ViewGroup mPreviewGroup; private final ViewGroup mPlacePageGroup; private final ScrollView mPlacePageContainer; private final View mView; // Preview private final TextView mTitle; private final TextView mSubtitle; private final CheckBox mIsBookmarked; // Views private final LayoutInflater mInflater; // Gestures private final GestureDetectorCompat mGestureDetector; private OnVisibilityChangedListener mVisibilityChangedListener; private boolean mIsPreviewVisible = true; private boolean mIsPlacePageVisible = true; private State mCurrentState = State.HIDDEN; // Data private MapObject mMapObject; private int mMaxPlacePageHeight = 0; private LinearLayout mGeoLayout = null; private View mDistanceView; private TextView mDistanceText; public MapInfoView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs); mInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); mView = mInflater.inflate(R.layout.info_box, this, true); mPreviewGroup = (ViewGroup) mView.findViewById(R.id.preview); mPlacePageGroup = (ViewGroup) mView.findViewById(R.id.place_page); showPlacePage(false); showPreview(false); // Preview mTitle = (TextView) mPreviewGroup.findViewById(R.id.info_title); mSubtitle = (TextView) mPreviewGroup.findViewById(R.id.info_subtitle); mIsBookmarked = (CheckBox) mPreviewGroup.findViewById(R.id.info_box_is_bookmarked); // We don't want to use OnCheckedChangedListener because it gets called // if someone calls setChecked() from code. We need only user interaction. mIsBookmarked.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { final BookmarkManager bm = BookmarkManager.getBookmarkManager(); if (mMapObject.getType() == MapObjectType.BOOKMARK) { final MapObject p = new Poi(mMapObject.getName(), mMapObject.getLat(), mMapObject.getLon(), null); bm.deleteBookmark((Bookmark) mMapObject); setMapObject(p); } else { final Bookmark newBookmark = bm.getBookmark(bm.addNewBookmark(mMapObject.getName(), mMapObject.getLat(), mMapObject.getLon())); setMapObject(newBookmark); } Framework.invalidate(); } }); // Place Page mPlacePageContainer = (ScrollView) mPlacePageGroup.findViewById(R.id.place_page_container); // Gestures OnGestureListener mGestureListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { final boolean isVertical = Math.abs(distanceY) > 2 * Math.abs(distanceX); final boolean isInRange = Math.abs(distanceY) > 1 && Math.abs(distanceY) < 100; if (isVertical && isInRange) { if (distanceY < 0) setState(State.PREVIEW_ONLY); else setState(State.FULL_PLACEPAGE); return true; } return false; } @Override public boolean onSingleTapConfirmed(MotionEvent e) { if (mCurrentState == State.FULL_PLACEPAGE) setState(State.PREVIEW_ONLY); else setState(State.FULL_PLACEPAGE); return true; } }; mGestureDetector = new GestureDetectorCompat(getContext(), mGestureListener); mView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* Friggin system does not work without this stub.*/ } }); } public MapInfoView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MapInfoView(Context context) { this(context, null, 0); } @Override public boolean onTouchEvent(MotionEvent event) { mGestureDetector.onTouchEvent(event); return super.onTouchEvent(event); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); calculateMaxPlacePageHeight(); } // Place Page (full information about an object on the map) private void showPlacePage(final boolean show) { calculateMaxPlacePageHeight(); if (mIsPlacePageVisible == show) return; // if state is already same as we need final long duration = 400; // Calculate translate offset final int previewHeight = mPreviewGroup.getHeight(); final int totalHeight = previewHeight + mMaxPlacePageHeight; final float offset = previewHeight / (float) totalHeight; if (show) // slide down { final TranslateAnimation slideDown = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, offset - 1, Animation.RELATIVE_TO_SELF, 0); slideDown.setDuration(duration); UiUtils.show(mPlacePageGroup); mView.startAnimation(slideDown); if (mVisibilityChangedListener != null) mVisibilityChangedListener.onPlacePageVisibilityChanged(show); } else // slide up { final TranslateAnimation slideUp = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, offset - 1); slideUp.setDuration(duration); slideUp.setFillEnabled(true); slideUp.setFillBefore(true); slideUp.setAnimationListener(new UiUtils.SimpleAnimationListener() { @Override public void onAnimationEnd(Animation animation) { UiUtils.hide(mPlacePageGroup); if (mVisibilityChangedListener != null) mVisibilityChangedListener.onPlacePageVisibilityChanged(show); } }); mView.startAnimation(slideUp); } mIsPlacePageVisible = show; } // Place Page Preview private void showPreview(final boolean show) { if (mIsPreviewVisible == show) return; final int duration = 200; if (show) { final TranslateAnimation slideDown = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0); slideDown.setDuration(duration); UiUtils.show(mPreviewGroup); slideDown.setAnimationListener(new SimpleAnimationListener() { @Override public void onAnimationEnd(Animation animation) { if (mVisibilityChangedListener != null) mVisibilityChangedListener.onPreviewVisibilityChanged(show); } }); mPreviewGroup.startAnimation(slideDown); } else { final TranslateAnimation slideUp = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1); slideUp.setDuration(duration); slideUp.setAnimationListener(new SimpleAnimationListener() { @Override public void onAnimationEnd(Animation animation) { UiUtils.hide(mPreviewGroup); if (mVisibilityChangedListener != null) mVisibilityChangedListener.onPreviewVisibilityChanged(show); } }); mPreviewGroup.startAnimation(slideUp); } mIsPreviewVisible = show; } private void setTextAndShow(final CharSequence title, final CharSequence subtitle) { mTitle.setText(title); mSubtitle.setText(subtitle); showPreview(true); } public State getState() { return mCurrentState; } public void setState(State state) { if (mCurrentState != state) { // Do some transitions if (mCurrentState == State.HIDDEN && state == State.PREVIEW_ONLY) showPreview(true); else if (mCurrentState == State.PREVIEW_ONLY && state == State.FULL_PLACEPAGE) showPlacePage(true); else if (mCurrentState == State.PREVIEW_ONLY && state == State.HIDDEN) showPreview(false); else if (mCurrentState == State.FULL_PLACEPAGE && state == State.PREVIEW_ONLY) showPlacePage(false); else if (mCurrentState == State.FULL_PLACEPAGE && state == State.HIDDEN) slideEverythingUp(); else throw new IllegalStateException(String.format("Invalid transition %s - > %s", mCurrentState, state)); mCurrentState = state; } } public boolean hasThatObject(MapObject mo) { if (mo == null && mMapObject == null) return true; else if (mMapObject != null) return mMapObject.equals(mo); return false; } public void setMapObject(MapObject mo) { if (!hasThatObject(mo)) { if (mo != null) { mo.setDefaultIfEmpty(getResources()); setTextAndShow(mo.getName(), mo.getPoiTypeName()); mMapObject = mo; boolean isChecked = false; switch (mo.getType()) { case POI: placePagePOI(mo); break; case BOOKMARK: isChecked = true; placePageBookmark((Bookmark) mo); break; case ADDITIONAL_LAYER: placePageAdditionalLayer((SearchResult) mo); break; case API_POINT: placePageAPI(mo); break; default: throw new IllegalArgumentException("Unknown MapObject type:" + mo.getType()); } mIsBookmarked.setChecked(isChecked); setUpAddressBox(); setUpGeoInformation(); setUpBottomButtons(); } else { mMapObject = mo; } } // Sometimes we have to force update view invalidate(); requestLayout(); } private void setUpBottomButtons() { mPlacePageGroup.findViewById(R.id.info_box_share).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ShareAction.getAnyShare().shareMapObject((Activity) getContext(), mMapObject); } }); final View editBtn = mPlacePageGroup.findViewById(R.id.info_box_edit); TextView mReturnToCallerBtn = (TextView) mPlacePageGroup.findViewById(R.id.info_box_back_to_caller); UiUtils.hide(editBtn); UiUtils.hide(mReturnToCallerBtn); if (mMapObject.getType() == MapObjectType.BOOKMARK) { // BOOKMARK final Bookmark bmk = (Bookmark) mMapObject; editBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { BookmarkActivity.startWithBookmark(getContext(), bmk.getCategoryId(), bmk.getBookmarkId()); } }); UiUtils.show(editBtn); } else if (mMapObject.getType() == MapObjectType.API_POINT) { // API final ParsedMmwRequest r = ParsedMmwRequest.getCurrentRequest(); // Text and icon final String txtPattern = String .format("%s {icon} %s", getResources().getString(R.string.more_info), r.getCallerName(getContext())); final int spanStart = txtPattern.indexOf("{icon}"); final int spanEnd = spanStart + "{icon}".length(); final Drawable icon = r.getIcon(getContext()); final int spanSize = (int) (25 * getResources().getDisplayMetrics().density); icon.setBounds(0, 0, spanSize, spanSize); final ImageSpan callerIconSpan = new ImageSpan(icon, ImageSpan.ALIGN_BOTTOM); final SpannableString ss = new SpannableString(txtPattern); ss.setSpan(callerIconSpan, spanStart, spanEnd, Spannable.SPAN_INCLUSIVE_EXCLUSIVE); UiUtils.show(mReturnToCallerBtn); mReturnToCallerBtn.setText(ss, BufferType.SPANNABLE); mReturnToCallerBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ParsedMmwRequest.getCurrentRequest().sendResponseAndFinish((Activity) getContext(), true); } }); } } private void setUpGeoInformation() { mGeoLayout = (LinearLayout) mPlacePageContainer.findViewById(R.id.info_box_geo_ref); mDistanceView = mGeoLayout.findViewById(R.id.info_box_geo_container_dist); mDistanceText = (TextView) mGeoLayout.findViewById(R.id.info_box_geo_distance); final Location lastKnown = MWMApplication.get().getLocationService().getLastKnown(); updateDistance(lastKnown); final TextView coord = (TextView) mGeoLayout.findViewById(R.id.info_box_geo_location); final double lat = mMapObject.getLat(); final double lon = mMapObject.getLon(); coord.setText(UiUtils.formatLatLon(lat, lon)); // Context menu for the coordinates copying. if (Utils.apiEqualOrGreaterThan(11)) { coord.setOnLongClickListener(new OnLongClickListener() { @Override public boolean onLongClick(View v) { final PopupMenu popup = new PopupMenu(getContext(), v); final Menu menu = popup.getMenu(); final String copyText = getResources().getString(android.R.string.copy); final String arrCoord[] = { UiUtils.formatLatLon(lat, lon), UiUtils.formatLatLonToDMS(lat, lon)}; menu.add(Menu.NONE, 0, 0, String.format("%s %s", copyText, arrCoord[0])); menu.add(Menu.NONE, 1, 1, String.format("%s %s", copyText, arrCoord[1])); menu.add(Menu.NONE, 2, 2, android.R.string.cancel); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { final int id = item.getItemId(); if (id >= 0 && id < 2) { final Context ctx = getContext(); Utils.copyTextToClipboard(ctx, arrCoord[id]); Utils.toastShortcut(ctx, ctx.getString(R.string.copied_to_clipboard, arrCoord[id])); } return true; } }); popup.show(); return true; } }); } } public void updateDistance(Location l) { if (mGeoLayout != null && mMapObject != null) { mDistanceView.setVisibility(l != null ? View.VISIBLE : View.GONE); if (l != null) { final CharSequence distanceText = Framework.getDistanceAndAzimutFromLatLon(mMapObject.getLat(), mMapObject.getLon(), l.getLatitude(), l.getLongitude(), 0.0).getDistance(); mDistanceText.setText(distanceText); } } } private void placePagePOI(MapObject poi) { mPlacePageContainer.removeAllViews(); final View poiView = mInflater.inflate(R.layout.info_box_poi, null); mPlacePageContainer.addView(poiView); } private void setUpAddressBox() { final TextView addressText = (TextView) mPlacePageGroup.findViewById(R.id.info_box_address); addressText.setText(Framework.getNameAndAddress4Point(mMapObject.getLat(), mMapObject.getLon())); } private void placePageBookmark(final Bookmark bmk) { mPlacePageContainer.removeAllViews(); final View bmkView = mInflater.inflate(R.layout.info_box_bookmark, null); // Description of BMK final WebView descriptionWv = (WebView) bmkView.findViewById(R.id.info_box_bookmark_descr); final String descriptionTxt = bmk.getBookmarkDescription(); if (TextUtils.isEmpty(descriptionTxt)) { UiUtils.hide(descriptionWv); } else { descriptionWv.loadData(descriptionTxt, "text/html; charset=UTF-8", null); descriptionWv.setBackgroundColor(Color.TRANSPARENT); UiUtils.show(descriptionWv); } mPlacePageContainer.addView(bmkView); } private void placePageAdditionalLayer(SearchResult sr) { mPlacePageContainer.removeAllViews(); final View addLayerView = mInflater.inflate(R.layout.info_box_additional_layer, null); mPlacePageContainer.addView(addLayerView); } private void placePageAPI(MapObject mo) { mPlacePageContainer.removeAllViews(); final View apiView = mInflater.inflate(R.layout.info_box_api, null); mPlacePageContainer.addView(apiView); } public void setOnVisibilityChangedListener(OnVisibilityChangedListener listener) { mVisibilityChangedListener = listener; } private void calculateMaxPlacePageHeight() { final View parent = (View) getParent(); if (parent != null) { mMaxPlacePageHeight = parent.getHeight() / 2; final ViewGroup.LayoutParams lp = mPlacePageGroup.getLayoutParams(); if (lp != null && lp.height != mMaxPlacePageHeight) { lp.height = mMaxPlacePageHeight; mPlacePageGroup.setLayoutParams(lp); requestLayout(); invalidate(); } } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); calculateMaxPlacePageHeight(); } public void onResume() { if (mMapObject == null) { return; } checkBookmarkWasDeleted(); checkApiWasCanceled(); } private void checkApiWasCanceled() { if ((mMapObject.getType() == MapObjectType.API_POINT) && !ParsedMmwRequest.hasRequest()) { setMapObject(null); showPlacePage(false); showPreview(false); } } private void checkBookmarkWasDeleted() { // We need to check, if content of body is still valid if (mMapObject.getType() == MapObjectType.BOOKMARK) { final Bookmark bmk = (Bookmark) mMapObject; final BookmarkManager bm = BookmarkManager.getBookmarkManager(); // Was bookmark deleted? boolean deleted = false; if (bm.getCategoriesCount() <= bmk.getCategoryId()) deleted = true; else if (bm.getCategoryById(bmk.getCategoryId()).getBookmarksCount() <= bmk.getBookmarkId()) deleted = true; else if (bm.getBookmark(bmk.getCategoryId(), bmk.getBookmarkId()).getLat() != bmk.getLat()) deleted = true; // We can do check above, because lat/lon cannot be changed from edit screen. if (deleted) { // Make Poi from bookmark final MapObject p = new Poi(mMapObject.getName(), mMapObject.getLat(), mMapObject.getLon(), null); setMapObject(p); // TODO how to handle the case, when bookmark was moved to another group? } else { // Update data for current bookmark final Bookmark updatedBmk = bm.getBookmark(bmk.getCategoryId(), bmk.getBookmarkId()); setMapObject(null); setMapObject(updatedBmk); } } } private void slideEverythingUp() { final TranslateAnimation slideUp = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, -1); slideUp.setDuration(400); slideUp.setAnimationListener(new SimpleAnimationListener() { @Override public void onAnimationEnd(Animation animation) { mIsPlacePageVisible = false; mIsPreviewVisible = false; UiUtils.hide(mPreviewGroup); UiUtils.hide(mPlacePageGroup); if (mVisibilityChangedListener != null) { mVisibilityChangedListener.onPreviewVisibilityChanged(false); mVisibilityChangedListener.onPlacePageVisibilityChanged(false); } } }); mView.startAnimation(slideUp); } public static enum State { HIDDEN, PREVIEW_ONLY, FULL_PLACEPAGE } public interface OnVisibilityChangedListener { public void onPreviewVisibilityChanged(boolean isVisible); public void onPlacePageVisibilityChanged(boolean isVisible); } }
package com.untamedears.mustercull; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.DyeColor; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.Ghast; import org.bukkit.entity.IronGolem; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.entity.Skeleton.SkeletonType; import org.bukkit.entity.Wither; import java.awt.Point; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * This class performs damage to mobs using the DAMAGE CullType. * @author ngozi */ public class HardCapLaborer extends Laborer { // Statistics private int _numberOfTimesExecuted = 0; private int _numberOfTimesExecutedWithPenaltyPurge = 0; private long _averageTimePerExecutionInMs = 0; private long _executionTimeForLastExecutionInMs = 0; /** * Constructor which takes a reference to the main plug-in class. * @param pluginInstance A reference to the main plug-in class. */ public HardCapLaborer(MusterCull pluginInstance) { super(pluginInstance); } /** * Repeating method for the class. * Kills N mobs where N is the number of mobs over the mob cap. * Recently dead mobs are counted toward the mob cap since filtering them out is costly. * Therefore, this should not run too quickly (set config). * * If a lot of mobs recently died when this runs then this will kill too many mobs. Possible far too many. * Luckily this can only happen when the cap is lowered or old chunks are loaded. */ private static final Object lockObj = new Object(); private static boolean currentlyRunning = false; public void run() { if (this.getPluginInstance().isPaused(GlobalCullType.HARDCAP)) { return; } synchronized(lockObj) { if(!currentlyRunning) { currentlyRunning = true; } else { return; } } int overHardMobLimit = getPluginInstance().overHardMobLimit(); if (overHardMobLimit > 0) { long purgeTimeStart = System.currentTimeMillis(); // Only console-warn if the number of mobs to cull is a fairly large-ish number. if (overHardMobLimit > 100) { this.getPluginInstance().getLogger().warning("Hard Cap Laborer - Exceptional Culling - Required to cull " + overHardMobLimit + " mobs."); } GlobalCullCullingStrategyType cullStrat = this.getPluginInstance().getGlobalCullingStrategy(); int toKill = overHardMobLimit; if (cullStrat == GlobalCullCullingStrategyType.RANDOM) { // this.getPluginInstance().getLogger().warning("Hard Cap Laborer - Random based culling."); List<LivingEntity> mobs = getPluginInstance().getAllLivingNonPlayerMobs(); for (LivingEntity mob : mobs) { if (! mob.isDead()) { toKill getPluginInstance().damageEntity(mob, 100); } if (toKill == 0) break; } } else if(cullStrat == GlobalCullCullingStrategyType.PRIORITY) { // this.getPluginInstance().getLogger().warning("Hard Cap Laborer - Priority based culling."); toKill = HandleCullingBasedOnChunkConcentration(getPluginInstance().getAllLivingNonPlayerMobs(), toKill); toKill = HandleGlobalCulling(getPluginInstance().getAllLivingNonPlayerMobs(), toKill); } else { this.getPluginInstance().getLogger().warning("Hard Cap Laborer - Cannot determine culling strategy, no work to do."); } _executionTimeForLastExecutionInMs = System.currentTimeMillis() - purgeTimeStart; _averageTimePerExecutionInMs = (long) (_averageTimePerExecutionInMs * (_numberOfTimesExecuted / (_numberOfTimesExecuted + 1.)) + _executionTimeForLastExecutionInMs / (_numberOfTimesExecuted + 1.)); _numberOfTimesExecuted++; } keepHostilesWithinSpawnLimit(); currentlyRunning = false; return; } public String GetStatisticDisplayString() { StringBuilder sb = new StringBuilder(); sb.append("Hard Cap Cull Statistics: \n"); sb.append("Hard Cap Cull Execution count: "); sb.append(_numberOfTimesExecuted); sb.append("\n"); sb.append("Number of culls with penalty purges: "); sb.append(_numberOfTimesExecutedWithPenaltyPurge); sb.append("\n"); sb.append("Average time per execution: "); sb.append(_averageTimePerExecutionInMs); sb.append(" milliseconds\n"); sb.append("Execution time for last execution: "); sb.append(_executionTimeForLastExecutionInMs); sb.append(" milliseconds\n"); return sb.toString(); } public int cullPriority(LivingEntity mob) { // Priority 1 - Named mob. if (null != mob.getCustomName() || mob.isCustomNameVisible()) { return 5; } // Priority 2/3/4 - Persistent mobs. else if (!mob.getRemoveWhenFarAway()) { // Priority 2 - High value persistent mobs (horses, villagers, player created iron golems). if (mob.getType() == EntityType.HORSE || mob.getType() == EntityType.VILLAGER) { return 6; } else if (mob.getType() == EntityType.IRON_GOLEM && mob instanceof IronGolem && ((IronGolem) mob).isPlayerCreated()) { return 6; } //Priority 3 - tame wolves, colored sheep, tame cats. else if (mob.getType() == EntityType.WOLF && ((org.bukkit.entity.Tameable)mob).isTamed()) { return 7; } else if (mob.getType() == EntityType.OCELOT && ((org.bukkit.entity.Tameable)mob).isTamed()) { return 7; } else if (mob.getType() == EntityType.SHEEP && ((org.bukkit.material.Colorable)mob).getColor() != DyeColor.WHITE) { return 7; } // Priority 4 - low value persistent mobs. else { return 8; } } else { // Non Priority - non persistent mobs. return 9; } } public void keepHostilesWithinSpawnLimit() { if (!this.getPluginInstance().getConfiguration().monsterCullToSpawnEnabled()) { return; } for (World world : Bukkit.getServer().getWorlds()) { // Find the spawn chunks around players in the world Set<Chunk> mobSpawnChunks = getMobSpawnChunks(world); int spawnChunkCount = mobSpawnChunks.size(); // Find hostiles in this world List<LivingEntity> hostiles = new ArrayList<LivingEntity>(); int i = 0; for (LivingEntity entity : world.getLivingEntities()) { i++; // Monster is hostiles except Ghast, Slime, Magma Cube (which are special case hostiles) if (entity instanceof Monster) { Monster mob = (Monster) entity; // Wither skeletons count as skeletons so are culled fast - exempt them if (mob instanceof Skeleton && ((Skeleton) mob).getSkeletonType().equals(SkeletonType.WITHER)) { // Do nothing } else if (entity instanceof Wither) { // Withers are rare constructs - exempt them } else { hostiles.add(mob); } } } int naturalLimit = world.getMonsterSpawnLimit() * spawnChunkCount / 256; // Cull in a cycle, most aggressive at full moon, to encourage turnover rather than stasis // Fluctuate aggression from 10% of the cap at full moon to 0 to the cap at new moon double days = world.getFullTime() / 24000.0; double phase = (days % 8); double cycleAmplitude = (1 + Math.cos(days * Math.PI * 0.25)) / 2.0; int maxAggression = getPluginInstance().getConfiguration().getMaximumMonsterCullAggression(); int minAggression = getPluginInstance().getConfiguration().getMinimumMonsterCullAggression(); int aggression = minAggression + ((int) (Math.round(cycleAmplitude * (maxAggression - minAggression)))); this.getPluginInstance().getLogger().info("Hostile cull - World " + world.getName() + " contains " + hostiles.size() + " of an allowed hostile spawn limit of " + naturalLimit + " minus an aggression factor of " + aggression + "."); int toKill = hostiles.size() - (naturalLimit - aggression); if (toKill >= 0 && hostiles.size() > 0) { int maxCullPerPass = this.getPluginInstance().getConfiguration().getMaximumMonsterCullPerPass(); if (toKill > maxCullPerPass) { toKill = maxCullPerPass; } this.getPluginInstance().getLogger().info("Hostile cull in world " + world.getName() + " - culling " + toKill + " mobs."); GlobalCullCullingStrategyType cullStrat = this.getPluginInstance().getGlobalCullingStrategy(); if (cullStrat == GlobalCullCullingStrategyType.RANDOM) { // this.getPluginInstance().getLogger().warning("Hard Cap Laborer - Random based culling."); for (LivingEntity mob : hostiles) { if (! mob.isDead()) { toKill getPluginInstance().damageEntity(mob, 100); } if (toKill == 0) break; } } else if(cullStrat == GlobalCullCullingStrategyType.PRIORITY) { // this.getPluginInstance().getLogger().warning("Hard Cap Laborer - Priority based culling."); toKill = HandleGlobalCulling(hostiles, toKill); } else { this.getPluginInstance().getLogger().warning("Hard Cap Hostile Cull - Cannot determine culling strategy, no work to do."); } } } } private Set<Chunk> getMobSpawnChunks(World world) { Set<Chunk> chunks = new HashSet<Chunk>(); for (Player player : world.getPlayers()) { int chunkX = player.getLocation().getBlockX() / 16; int chunkZ = player.getLocation().getBlockZ() / 16; int spawnRadius = Bukkit.getServer().getSpawnRadius(); int viewLimit = Bukkit.getServer().getViewDistance(); int dist = 8; if (spawnRadius < dist) dist = spawnRadius; if (viewLimit < dist) dist = viewLimit; for (int dx = -dist; dx <= dist; ++dx) { for (int dz = -dist; dz <= dist; ++dz) { if (world.isChunkLoaded(chunkX + dx, chunkZ + dz)) { chunks.add(world.getChunkAt(chunkX + dx, chunkZ + dz)); } } } } return chunks; } /** * Given an integer mob to kill count, it will attempt to find if there are any problem chunks and begin a culling * @param mobCountToCull Amount of mobs we would like to kill in total - not the amount of mobs we have to kill just from this chunk based culling. * @return How many mobs are left of the mobs we would like to kill. */ private int HandleCullingBasedOnChunkConcentration(List<LivingEntity> mobs, int mobCountToCull) { HashMap<Point, List<LivingEntity>> chunkEntities = new HashMap<Point, List<LivingEntity>>(); int totalCullScore = 0; for (LivingEntity mob : mobs) { if ( ! mob.isDead()) { Chunk mobChunk = mob.getLocation().getChunk(); Point d = new Point(mobChunk.getX(), mobChunk.getZ()); if (!chunkEntities.containsKey(d)) { chunkEntities.put(d, new ArrayList<LivingEntity>()); } if (mob instanceof LivingEntity) { chunkEntities.get(d).add(mob); totalCullScore += cullPriority(mob); } } } Point maxCenterPoint = null; int mobCullScoreInLargestSuperChunk = -1; int maxChunksInMatchSet = 0; // For each chunk check all the chunks surrounding it. 3x3 and get mob counts. // Find the most populous super chunk. for(Point point : chunkEntities.keySet()) { int cullScore = 0; int tempChunkCount = 0; for(int x = -3; x <= 3; x++) { for (int z = -3; z <= 3; z++) { if (chunkEntities.containsKey(new Point(point.x - x, point.y - z))) { for (Entity e : chunkEntities.get(new Point(point.x - x, point.y - z))) { if (e instanceof LivingEntity) { cullScore += cullPriority((LivingEntity) e); tempChunkCount++; } } } } } // If more mobs than our last super chunk, update it. if (cullScore > mobCullScoreInLargestSuperChunk) { maxCenterPoint = point; mobCullScoreInLargestSuperChunk = cullScore; maxChunksInMatchSet = tempChunkCount; } } // Number of loaded chunks with mobs excepting the bad super chunk. int numberOfChunksToAverageOver = (chunkEntities.keySet().size()-maxChunksInMatchSet); // If the max mobs for a super chunk doesn't meet the penalty purge percent, early out. // Or if the 'penalty chunks' -is- all the chunks loaded. if ((mobCullScoreInLargestSuperChunk / ((1.0) * totalCullScore) <= this.getPluginInstance().getHardCapCullingPriorityStrategyPenaltyMobPercent()) || numberOfChunksToAverageOver == 0) { return mobCountToCull; } // Log out the naughty chunk. this.getPluginInstance().getLogger().warning("Hard Cap Laborer - Found chunk that triggered a penalty purge based on mob count. Chunk " + maxCenterPoint.x + ", " + maxCenterPoint.y + "."); _numberOfTimesExecutedWithPenaltyPurge++; int averageScorePerChunk = (int) Math.ceil(totalCullScore / (1. * numberOfChunksToAverageOver)); int superChunkMobScoreToCull = mobCullScoreInLargestSuperChunk - averageScorePerChunk; superChunkMobScoreToCull = superChunkMobScoreToCull > mobCountToCull ? mobCountToCull : superChunkMobScoreToCull; if (superChunkMobScoreToCull <= 0) { // It met the limit but its not more than the average, so do nothing. // Only in special cases where loaded chunks are extremely few. return mobCountToCull; } // Consider purging every mob in the chunks surrounding it. 7x7 with the superchunk at the center. List<LivingEntity> mobsToConsiderPurging = new ArrayList<LivingEntity>(); for(int x = -3; x <= 3; x++) { for (int z = -3; z <= 3; z++) { if (chunkEntities.containsKey(new Point(maxCenterPoint.x - x, maxCenterPoint.y - z))) { mobsToConsiderPurging.addAll(chunkEntities.get(new Point(maxCenterPoint.x - x, maxCenterPoint.y - z))); } } } // We are only going to purge enough to bring this superchunk into a good status with our other chunks. // Our unculled mobs, then, after this call would be our original mobCountToCull - the superCullCount + whats left over. return mobCountToCull - superChunkMobScoreToCull + PerformCullingLogic(mobsToConsiderPurging, mobCountToCull, superChunkMobScoreToCull); } /** * For a given set of candidates, we will first bring the candidates into proportion based on entity type (up to max items to cull) and will then round-robin remove them (up to max items to cull) * @param cullCandidates The list of possible items that can be culled. * @param maxItemsToCull Maximum items to cull on this run. * @return The number of items remaining out of the orignal items-to-cull passed in. */ private int PerformCullingLogic(List<LivingEntity> cullCandidates, int maxItemsToCull, int scoreToCull) { if (scoreToCull == 0) return scoreToCull; // Step 1 - Categorize all items on our list into categories based on priority. Map<Integer, List<LivingEntity>> prioritisedMobs = new HashMap<Integer, List<LivingEntity>>(); for(LivingEntity mob : cullCandidates) { // TODO: add prioritised entities int priority = cullPriority(mob); if (!prioritisedMobs.containsKey(priority)) { prioritisedMobs.put(priority, new ArrayList<LivingEntity>()); } prioritisedMobs.get(priority).add(mob); } List<Integer> priorities = new ArrayList<Integer>(prioritisedMobs.keySet()); Collections.sort(priorities); Collections.reverse(priorities); // Step 2 - Cull based on purge priorities. for (Integer priority : priorities) { if (scoreToCull > 0) { int remaining = purgeToEquivalentNumbers(maxItemsToCull, getListSortedByCounts(prioritisedMobs.get(priority))); int culled = maxItemsToCull - remaining; scoreToCull -= culled * priority; maxItemsToCull = remaining; } } return maxItemsToCull; } /** * For a given categorized entity list all of the same priority, we will attempt to bring them into proportion with one another and then round-robin remove (up to max items to cull). * @param maxItemsToCull Maximum amount of items we can cull. * @param orderedPurgeList * @return Of the maxItemsToCull originally passed in, how many remain to be culled. */ private int purgeToEquivalentNumbers(int maxItemsToCull, List<Entry<EntityType, List<LivingEntity>>> orderedPurgeList) { // Early out if we have no work to do. if (orderedPurgeList.size() <= 0 || maxItemsToCull <= 0) { return maxItemsToCull; } // Determine the average mob count per category. int totalItems = 0; for(int i = 0; i < orderedPurgeList.size(); i++) { totalItems += orderedPurgeList.get(i).getValue().size(); } int average = totalItems / orderedPurgeList.size(); // Iterate over all of the mob lists to remove (largest list first) and start removing items until it is equal to the average. // For each category, while we still have items left to cull. for(int i = 0; i < orderedPurgeList.size() && maxItemsToCull > 0; i++) { List<LivingEntity> purgeList = orderedPurgeList.get(i).getValue(); // Even if the purgeList is already correctly-sized, we still want to always sort these lists. Important in round-robin culling next. Collections.shuffle(purgeList); // Start removing mobs from this category. while(purgeList.size() > average && purgeList.size() > 0 && maxItemsToCull > 0) { LivingEntity mob = purgeList.remove(0); if (!mob.isDead()) { // Cull it and remove it from our to-cull count. maxItemsToCull getPluginInstance().damageEntity(mob, 100); } } } // Now that we have made our categories approximately equivalent to each other, time to cull round-robin over these now-sorted lists. int ctr = 0; boolean removedAtLeastOneItemThisIteration = true; while(maxItemsToCull > 0) { // If the cycle has restarted. if (ctr == 0) { // Have we removed at least one item? If not, bye! if (!removedAtLeastOneItemThisIteration) { // Control structure. break; } // Restart! removedAtLeastOneItemThisIteration = false; } // Kill off one item of this type. if (orderedPurgeList.get(ctr).getValue().size() > 0) { LivingEntity mob = orderedPurgeList.get(ctr).getValue().remove(0); if (!mob.isDead()) { // Cull it and remove it from our to-cull count. maxItemsToCull getPluginInstance().damageEntity(mob, 100); // Note that we removed at least one mob this iteration. removedAtLeastOneItemThisIteration = true; } } // Move to next category and loop back if needed. ctr++; if (ctr >= orderedPurgeList.size() ) { ctr = 0; } } return maxItemsToCull; } /** * For a given unordered list of of mobs, we will attempt to categorize these and order this such that our largest mob categories come first. * @param mobList Unordered list of mobs. * @return Ordered list of categorized mobs (categorized by entity types) such that the largest entity categories will come first. */ private List<Entry<EntityType, List<LivingEntity>>> getListSortedByCounts(List<LivingEntity> mobList) { // Separate mobs by entity type. HashMap<EntityType, List<LivingEntity>> equivalentPurgeList = new HashMap<EntityType, List<LivingEntity>>(); for(LivingEntity mob : mobList) { EntityType type = mob.getType(); if(!equivalentPurgeList.containsKey(type)) { equivalentPurgeList.put(type, new ArrayList<LivingEntity>()); } equivalentPurgeList.get(type).add(mob); } // Sort these entity-types by the ones with the most first. List<Entry<EntityType, List<LivingEntity>>> orderedPurgeList = new LinkedList<Entry<EntityType, List<LivingEntity>>> (equivalentPurgeList.entrySet()); Collections.sort(orderedPurgeList, Collections.reverseOrder(new Comparator<Entry<EntityType, List<LivingEntity>>>() { public int compare(Entry<EntityType, List<LivingEntity>> o1, Entry<EntityType, List<LivingEntity>> o2) { return o1.getValue().size() - o2.getValue().size(); } } )); return orderedPurgeList; } /** * Will perform categorized and proportional global culling in priority order. * @param overHardMobLimit Max number of items to purge. * @return */ private int HandleGlobalCulling(List<LivingEntity> mobList, int overHardMobLimit) { return PerformCullingLogic(mobList, overHardMobLimit, mobList.size() * 10); } }
package com.heaven7.java.mvcs; import com.heaven7.java.mvcs.IController.StateFactory; import com.heaven7.java.mvcs.util.SparseArray; import java.util.ArrayList; import java.util.List; import static com.heaven7.java.mvcs.util.MathUtil.max2K; /** * the state group . manage a group of state. * * @param <P> the state parameter type. * @author heaven7 */ /*public*/ final class StateGroup<S extends AbstractState<P> ,P> implements Disposeable{ private int mCurrentStates; private P mParam; private final Callback<S,P> mCallback; private final IController<S, P> mController; /** the cached all states without current states. that means background states.*/ private int mCachedState; public StateGroup(IController<S, P> controller, Callback<S,P> callback) { this.mController = controller; this.mCallback = callback; } private P getStateParameter() { return mParam; } private StateFactory<S,P> getStateFactory() { return mCallback.getStateFactory(); } private SparseArray<S> getStateMap(){ return mCallback.getStateMap(); } private ParameterMerger<P> getMerger(){ return mCallback.getMerger(); } private IController<S, P> getController(){ return mController; } private boolean isStateCacheEnabled(){ return mController.isStateCacheEnabled(); } public int getCachedStateFlags(){ return mCachedState; } public int getStateFlags() { return mCurrentStates; } public boolean hasState(int state) { return (getStateFlags() & state) != 0; } public boolean clearState(P param) { final int current = mCurrentStates; if(current == 0){ return false; } this.mCurrentStates = 0; this.mParam = param; dispatchStateChange(current, 0); this.mParam = null; return true; } public boolean removeState(int states, P param) { if (states <= 0) return false; this.mCurrentStates &= ~states; this.mParam = param; dispatchStateChange(0, 0, states); this.mParam = null; return true; } public boolean addState(int states, P extra) { if (states <= 0) return false; //no change. final int shareFlags = mCurrentStates & states; if (shareFlags == states) { return false; } this.mParam = extra; this.mCurrentStates |= states; dispatchStateChange(shareFlags, states & ~shareFlags, 0); this.mParam = null; return true; } public boolean setStates(int newStates, P p) { if (newStates <= 0 ) return false; final int mCurr = this.mCurrentStates; if (mCurr == newStates) { return false; } this.mCurrentStates = newStates; this.mParam = p; dispatchStateChange(mCurr, newStates); mParam = null; return true; } /** * dispatch the state change if need. * * @param currentState the current state before this state change. * @param newState the target or new state */ private void dispatchStateChange(int currentState, int newState) { final int shareFlags = currentState & newState; final int enterFlags = newState & ~shareFlags; final int exitFlags = currentState & ~shareFlags; dispatchStateChange(shareFlags, enterFlags, exitFlags); } /** * dispatch state change. * * @param shareFlags the share flags to exit(). * @param enterFlags the enter flags to exit() * @param exitFlags the exit flags to exit(). */ protected void dispatchStateChange(int shareFlags, int enterFlags, int exitFlags) { // Call the exit method of the existing state if (exitFlags != 0) { exitState(exitFlags); } // Call the entry method of the new state if (enterFlags != 0) { enterState(enterFlags); } //call reenter state if (shareFlags != 0) { reenter(shareFlags); } } private void reenter(int sharFlags) { int maxKey; for (; sharFlags > 0; ) { maxKey = max2K(sharFlags); if (maxKey > 0) { reenter0(maxKey); sharFlags -= maxKey; } } } private void exitState(int exitFlags) { int maxKey; for (; exitFlags > 0; ) { maxKey = max2K(exitFlags); if (maxKey > 0) { exit0(maxKey); exitFlags -= maxKey; } } } private void enterState(int enterFlags) { final StateFactory<S,P> factory = getStateFactory(); final P sp = getStateParameter(); int maxKey; for (; enterFlags > 0; ) { maxKey = max2K(enterFlags); if (maxKey > 0) { enter0(maxKey, factory.createState(maxKey, sp)); enterFlags -= maxKey; } } } public S getStateByKey(int key) { return getStateMap().get(key); } public int getStateCount() { return getStateMap().size(); } private void reenter0(int singleState) { AbstractState<P> state = getStateMap().get(singleState); final P p = getMerger().merge(state.getStateParameter(), getStateParameter()); state.setStateParameter(p); state.onAttach(getController()); state.onReenter(); //TODO need handle mutex ? } private void enter0(int singleState, S state) { if(state == null){ throw new IllegalStateException("create state failed. Are you forget to create State " + "for state_flag = " + singleState + " ? "); } //cache state mCachedState &= ~singleState; getStateMap().put(singleState, state); final P p = getMerger().merge(state.getStateParameter(), getStateParameter()); state.setStateParameter(p); state.onAttach(getController()); state.onEnter(); //handle mutex states int[] mutexStates = getController().getMutexState(singleState); if(mutexStates != null){ final SparseArray<S> stateMap = getStateMap(); int oppositeState = 0; for(int s : mutexStates){ if(stateMap.get(s) != null){ oppositeState |= s; exit0(s); } } this.mCurrentStates &= ~oppositeState; //System.out.println("mutex state occurs. Main state : " + singleState + " , Mutex states : "+ Arrays.toString(mutexStates)); //System.out.println("mutex state occurs. after adjust current state : " + mCurrentStates); } } private void exit0(int singleState) { final SparseArray<S> stateMap = getStateMap(); AbstractState<P> state = stateMap.get(singleState); // no cache ? remove from cache if(!isStateCacheEnabled()){ stateMap.remove(singleState); mCachedState &= ~singleState; }else{ mCachedState |= singleState; } final P p = getMerger().merge(state.getStateParameter(), getStateParameter()); state.setStateParameter(p); state.onExit(); state.onDetach(); } public List<S> getStates() { if(mCurrentStates == 0){ return null; } final List<S> list = new ArrayList<S>(); int curFlags = this.mCurrentStates; int maxKey; for (; curFlags > 0; ) { maxKey = max2K(curFlags); if (maxKey > 0) { list.add(getStateByKey(maxKey)); curFlags -= maxKey; } } return list; } /** get max state. * @return the max state. */ public S getMaxState() { if(mCurrentStates == 0){ return null; } int maxKey = max2K(this.mCurrentStates); return getStateByKey(maxKey); } public void notifyStateUpdate(P param) { final List<S> states = getStates(); if(states != null ) { for (S s : states) { s.onUpdate(param); } } } /** destroy state cache without current states. */ public void destroyStateCache() { if(mCachedState > 0){ final SparseArray<S> map = getStateMap(); int curFlags = this.mCachedState; int maxKey; for (; curFlags > 0 ; ) { maxKey = max2K(curFlags); if (maxKey > 0) { map.remove(maxKey); // System.out.println("destroy state = " + maxKey); curFlags -= maxKey; } } }/*else{ System.out.println("no state cache..."); }*/ } public void dispose() { final SparseArray<S> map = getStateMap(); int curFlags = this.mCurrentStates; int maxKey; for (; curFlags > 0 ; ) { maxKey = max2K(curFlags); if (maxKey > 0) { final S s = map.get(maxKey); //destroy foreground state. s.onExit(); s.onDetach(); s.dispose(); map.remove(maxKey); // System.out.println("dispose : " + s.toString()); curFlags -= maxKey; } } this.mCurrentStates = 0; this.mCachedState = 0; this.mParam = null; } public interface Callback<S extends AbstractState<P>, P>{ ParameterMerger<P> getMerger(); StateFactory<S,P> getStateFactory(); SparseArray<S> getStateMap(); } }
package com.karateca.ddescriber.model; import com.intellij.find.FindResult; import com.karateca.ddescriber.BaseTestCase; import java.util.List; public class JasmineFinderTest extends BaseTestCase { public void testFindAll() throws Exception { findsAllTests("jasmine1/jasmineTestBefore.js"); findsAllTests("jasmine2/jasmineTestBefore.js"); } private void findsAllTests(String fileName) { List<FindResult> findResults = whenYouFindTestsForJsFile(fileName); // Then ensure there are 9 tests and suites. assertEquals(9, findResults.size()); } public void testWithCaretAtTheTop() { findsTestsWithCaretAtTheTop("jasmine1/jasmineTestCaretTop.js"); findsTestsWithCaretAtTheTop("jasmine2/jasmineTestCaretTop.js"); } private void findsTestsWithCaretAtTheTop(String fileName) { List<FindResult> findResults = whenYouFindTestsForJsFile(fileName); // Then ensure there are 6 tests and suites. assertEquals(7, findResults.size()); } public void testShouldFindTestsWithTrickyText() { findsTestsWithTrickyText("jasmine1/jasmineWithWeirdRegularExpressions.js"); findsTestsWithTrickyText("jasmine2/jasmineWithWeirdRegularExpressions.js"); } private void findsTestsWithTrickyText(String fileName) { List<FindResult> findResults = whenYouFindTestsForJsFile( fileName); // Then ensure all the tests were found. assertEquals(11, findResults.size()); } private List<FindResult> whenYouFindTestsForJsFile(String fileName) { prepareScenarioWithTestFile(fileName); jasmineFinder.findAll(); return jasmineFinder.getFindResults(); } }
package org.bouncycastle.jce.provider.test; import org.bouncycastle.asn1.ASN1EncodableVector; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.DEREnumerated; import org.bouncycastle.asn1.DERObjectIdentifier; import org.bouncycastle.asn1.DEROctetString; import org.bouncycastle.asn1.DERSequence; import org.bouncycastle.asn1.DERSet; import org.bouncycastle.asn1.DERTaggedObject; import org.bouncycastle.asn1.cms.CMSObjectIdentifiers; import org.bouncycastle.asn1.cms.ContentInfo; import org.bouncycastle.asn1.cms.SignedData; import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; import org.bouncycastle.asn1.x509.CRLReason; import org.bouncycastle.asn1.x509.GeneralName; import org.bouncycastle.asn1.x509.GeneralNames; import org.bouncycastle.asn1.x509.KeyPurposeId; import org.bouncycastle.asn1.x509.X509Extension; import org.bouncycastle.asn1.x509.X509Extensions; import org.bouncycastle.asn1.x9.X9ObjectIdentifiers; import org.bouncycastle.jce.X509KeyUsage; import org.bouncycastle.jce.X509Principal; import org.bouncycastle.jce.interfaces.ECPointEncoder; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.jce.spec.ECParameterSpec; import org.bouncycastle.jce.spec.ECPrivateKeySpec; import org.bouncycastle.jce.spec.ECPublicKeySpec; import org.bouncycastle.jce.spec.GOST3410ParameterSpec; import org.bouncycastle.math.ec.ECCurve; import org.bouncycastle.util.encoders.Base64; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTest; import org.bouncycastle.x509.X509V1CertificateGenerator; import org.bouncycastle.x509.X509V2CRLGenerator; import org.bouncycastle.x509.X509V3CertificateGenerator; import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure; import org.bouncycastle.x509.extension.X509ExtensionUtil; import javax.security.auth.x500.X500Principal; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Security; import java.security.Signature; import java.security.cert.CRL; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.CertificateParsingException; import java.security.cert.X509CRL; import java.security.cert.X509CRLEntry; import java.security.cert.X509Certificate; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.Collection; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Vector; public class CertTest extends SimpleTest { // server.crt byte[] cert1 = Base64.decode( "MIIDXjCCAsegAwIBAgIBBzANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx" + "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY" + "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB" + "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ" + "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU2MjFaFw0wMTA2" + "MDIwNzU2MjFaMIG4MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW" + "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM" + "dGQxFzAVBgNVBAsTDldlYnNlcnZlciBUZWFtMR0wGwYDVQQDExR3d3cyLmNvbm5l" + "Y3Q0LmNvbS5hdTEoMCYGCSqGSIb3DQEJARYZd2VibWFzdGVyQGNvbm5lY3Q0LmNv" + "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArvDxclKAhyv7Q/Wmr2re" + "Gw4XL9Cnh9e+6VgWy2AWNy/MVeXdlxzd7QAuc1eOWQkGQEiLPy5XQtTY+sBUJ3AO" + "Rvd2fEVJIcjf29ey7bYua9J/vz5MG2KYo9/WCHIwqD9mmG9g0xLcfwq/s8ZJBswE" + "7sb85VU+h94PTvsWOsWuKaECAwEAAaN3MHUwJAYDVR0RBB0wG4EZd2VibWFzdGVy" + "QGNvbm5lY3Q0LmNvbS5hdTA6BglghkgBhvhCAQ0ELRYrbW9kX3NzbCBnZW5lcmF0" + "ZWQgY3VzdG9tIHNlcnZlciBjZXJ0aWZpY2F0ZTARBglghkgBhvhCAQEEBAMCBkAw" + "DQYJKoZIhvcNAQEEBQADgYEAotccfKpwSsIxM1Hae8DR7M/Rw8dg/RqOWx45HNVL" + "iBS4/3N/TO195yeQKbfmzbAA2jbPVvIvGgTxPgO1MP4ZgvgRhasaa0qCJCkWvpM4" + "yQf33vOiYQbpv4rTwzU8AmRlBG45WdjyNIigGV+oRc61aKCTnLq7zB8N3z1TF/bF" + "5/8="); // ca.crt byte[] cert2 = Base64.decode( "MIIDbDCCAtWgAwIBAgIBADANBgkqhkiG9w0BAQQFADCBtzELMAkGA1UEBhMCQVUx" + "ETAPBgNVBAgTCFZpY3RvcmlhMRgwFgYDVQQHEw9Tb3V0aCBNZWxib3VybmUxGjAY" + "BgNVBAoTEUNvbm5lY3QgNCBQdHkgTHRkMR4wHAYDVQQLExVDZXJ0aWZpY2F0ZSBB" + "dXRob3JpdHkxFTATBgNVBAMTDENvbm5lY3QgNCBDQTEoMCYGCSqGSIb3DQEJARYZ" + "d2VibWFzdGVyQGNvbm5lY3Q0LmNvbS5hdTAeFw0wMDA2MDIwNzU1MzNaFw0wMTA2" + "MDIwNzU1MzNaMIG3MQswCQYDVQQGEwJBVTERMA8GA1UECBMIVmljdG9yaWExGDAW" + "BgNVBAcTD1NvdXRoIE1lbGJvdXJuZTEaMBgGA1UEChMRQ29ubmVjdCA0IFB0eSBM" + "dGQxHjAcBgNVBAsTFUNlcnRpZmljYXRlIEF1dGhvcml0eTEVMBMGA1UEAxMMQ29u" + "bmVjdCA0IENBMSgwJgYJKoZIhvcNAQkBFhl3ZWJtYXN0ZXJAY29ubmVjdDQuY29t" + "LmF1MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDgs5ptNG6Qv1ZpCDuUNGmv" + "rhjqMDPd3ri8JzZNRiiFlBA4e6/ReaO1U8ASewDeQMH6i9R6degFdQRLngbuJP0s" + "xcEE+SksEWNvygfzLwV9J/q+TQDyJYK52utb++lS0b48A1KPLwEsyL6kOAgelbur" + "ukwxowprKUIV7Knf1ajetQIDAQABo4GFMIGCMCQGA1UdEQQdMBuBGXdlYm1hc3Rl" + "ckBjb25uZWN0NC5jb20uYXUwDwYDVR0TBAgwBgEB/wIBADA2BglghkgBhvhCAQ0E" + "KRYnbW9kX3NzbCBnZW5lcmF0ZWQgY3VzdG9tIENBIGNlcnRpZmljYXRlMBEGCWCG" + "SAGG+EIBAQQEAwICBDANBgkqhkiG9w0BAQQFAAOBgQCsGvfdghH8pPhlwm1r3pQk" + "msnLAVIBb01EhbXm2861iXZfWqGQjrGAaA0ZpXNk9oo110yxoqEoSJSzniZa7Xtz" + "soTwNUpE0SLHvWf/SlKdFWlzXA+vOZbzEv4UmjeelekTm7lc01EEa5QRVzOxHFtQ" + "DhkaJ8VqOMajkQFma2r9iA=="); // testx509.pem byte[] cert3 = Base64.decode( "MIIBWzCCAQYCARgwDQYJKoZIhvcNAQEEBQAwODELMAkGA1UEBhMCQVUxDDAKBgNV" + "BAgTA1FMRDEbMBkGA1UEAxMSU1NMZWF5L3JzYSB0ZXN0IENBMB4XDTk1MDYxOTIz" + "MzMxMloXDTk1MDcxNzIzMzMxMlowOjELMAkGA1UEBhMCQVUxDDAKBgNVBAgTA1FM" + "RDEdMBsGA1UEAxMUU1NMZWF5L3JzYSB0ZXN0IGNlcnQwXDANBgkqhkiG9w0BAQEF" + "AANLADBIAkEAqtt6qS5GTxVxGZYWa0/4u+IwHf7p2LNZbcPBp9/OfIcYAXBQn8hO" + "/Re1uwLKXdCjIoaGs4DLdG88rkzfyK5dPQIDAQABMAwGCCqGSIb3DQIFBQADQQAE" + "Wc7EcF8po2/ZO6kNCwK/ICH6DobgLekA5lSLr5EvuioZniZp5lFzAw4+YzPQ7XKJ" + "zl9HYIMxATFyqSiD9jsx"); // v3-cert1.pem byte[] cert4 = Base64.decode( "MIICjTCCAfigAwIBAgIEMaYgRzALBgkqhkiG9w0BAQQwRTELMAkGA1UEBhMCVVMx" + "NjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFuZCBTcGFjZSBBZG1pbmlz" + "dHJhdGlvbjAmFxE5NjA1MjgxMzQ5MDUrMDgwMBcROTgwNTI4MTM0OTA1KzA4MDAw" + "ZzELMAkGA1UEBhMCVVMxNjA0BgNVBAoTLU5hdGlvbmFsIEFlcm9uYXV0aWNzIGFu" + "ZCBTcGFjZSBBZG1pbmlzdHJhdGlvbjEgMAkGA1UEBRMCMTYwEwYDVQQDEwxTdGV2" + "ZSBTY2hvY2gwWDALBgkqhkiG9w0BAQEDSQAwRgJBALrAwyYdgxmzNP/ts0Uyf6Bp" + "miJYktU/w4NG67ULaN4B5CnEz7k57s9o3YY3LecETgQ5iQHmkwlYDTL2fTgVfw0C" + "AQOjgaswgagwZAYDVR0ZAQH/BFowWDBWMFQxCzAJBgNVBAYTAlVTMTYwNAYDVQQK" + "Ey1OYXRpb25hbCBBZXJvbmF1dGljcyBhbmQgU3BhY2UgQWRtaW5pc3RyYXRpb24x" + "DTALBgNVBAMTBENSTDEwFwYDVR0BAQH/BA0wC4AJODMyOTcwODEwMBgGA1UdAgQR" + "MA8ECTgzMjk3MDgyM4ACBSAwDQYDVR0KBAYwBAMCBkAwCwYJKoZIhvcNAQEEA4GB" + "AH2y1VCEw/A4zaXzSYZJTTUi3uawbbFiS2yxHvgf28+8Js0OHXk1H1w2d6qOHH21" + "X82tZXd/0JtG0g1T9usFFBDvYK8O0ebgz/P5ELJnBL2+atObEuJy1ZZ0pBDWINR3" + "WkDNLCGiTkCKp0F5EWIrVDwh54NNevkCQRZita+z4IBO"); // v3-cert2.pem byte[] cert5 = Base64.decode( "MIICiTCCAfKgAwIBAgIEMeZfHzANBgkqhkiG9w0BAQQFADB9MQswCQYDVQQGEwJD" + "YTEPMA0GA1UEBxMGTmVwZWFuMR4wHAYDVQQLExVObyBMaWFiaWxpdHkgQWNjZXB0" + "ZWQxHzAdBgNVBAoTFkZvciBEZW1vIFB1cnBvc2VzIE9ubHkxHDAaBgNVBAMTE0Vu" + "dHJ1c3QgRGVtbyBXZWIgQ0EwHhcNOTYwNzEyMTQyMDE1WhcNOTYxMDEyMTQyMDE1" + "WjB0MSQwIgYJKoZIhvcNAQkBExVjb29rZUBpc3NsLmF0bC5ocC5jb20xCzAJBgNV" + "BAYTAlVTMScwJQYDVQQLEx5IZXdsZXR0IFBhY2thcmQgQ29tcGFueSAoSVNTTCkx" + "FjAUBgNVBAMTDVBhdWwgQS4gQ29va2UwXDANBgkqhkiG9w0BAQEFAANLADBIAkEA" + "6ceSq9a9AU6g+zBwaL/yVmW1/9EE8s5you1mgjHnj0wAILuoB3L6rm6jmFRy7QZT" + "G43IhVZdDua4e+5/n1ZslwIDAQABo2MwYTARBglghkgBhvhCAQEEBAMCB4AwTAYJ" + "YIZIAYb4QgENBD8WPVRoaXMgY2VydGlmaWNhdGUgaXMgb25seSBpbnRlbmRlZCBm" + "b3IgZGVtb25zdHJhdGlvbiBwdXJwb3Nlcy4wDQYJKoZIhvcNAQEEBQADgYEAi8qc" + "F3zfFqy1sV8NhjwLVwOKuSfhR/Z8mbIEUeSTlnH3QbYt3HWZQ+vXI8mvtZoBc2Fz" + "lexKeIkAZXCesqGbs6z6nCt16P6tmdfbZF3I3AWzLquPcOXjPf4HgstkyvVBn0Ap" + "jAFN418KF/Cx4qyHB4cjdvLrRjjQLnb2+ibo7QU="); // pem encoded pkcs7 byte[] cert6 = Base64.decode( "MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIJbzCCAj0w" + "ggGmAhEAzbp/VvDf5LxU/iKss3KqVTANBgkqhkiG9w0BAQIFADBfMQswCQYDVQQGEwJVUzEXMBUG" + "A1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGljIFByaW1hcnkgQ2Vy" + "dGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTYwMTI5MDAwMDAwWhcNMjgwODAxMjM1OTU5WjBfMQsw" + "CQYDVQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVi" + "bGljIFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwgZ8wDQYJKoZIhvcNAQEBBQADgY0A" + "MIGJAoGBAOUZv22jVmEtmUhx9mfeuY3rt56GgAqRDvo4Ja9GiILlc6igmyRdDR/MZW4MsNBWhBiH" + "mgabEKFz37RYOWtuwfYV1aioP6oSBo0xrH+wNNePNGeICc0UEeJORVZpH3gCgNrcR5EpuzbJY1zF" + "4Ncth3uhtzKwezC6Ki8xqu6jZ9rbAgMBAAEwDQYJKoZIhvcNAQECBQADgYEATD+4i8Zo3+5DMw5d" + "6abLB4RNejP/khv0Nq3YlSI2aBFsfELM85wuxAc/FLAPT/+Qknb54rxK6Y/NoIAK98Up8YIiXbix" + "3YEjo3slFUYweRb46gVLlH8dwhzI47f0EEA8E8NfH1PoSOSGtHuhNbB7Jbq4046rPzidADQAmPPR" + "cZQwggMuMIICl6ADAgECAhEA0nYujRQMPX2yqCVdr+4NdTANBgkqhkiG9w0BAQIFADBfMQswCQYD" + "VQQGEwJVUzEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xNzA1BgNVBAsTLkNsYXNzIDEgUHVibGlj" + "IFByaW1hcnkgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNOTgwNTEyMDAwMDAwWhcNMDgwNTEy" + "MjM1OTU5WjCBzDEXMBUGA1UEChMOVmVyaVNpZ24sIEluYy4xHzAdBgNVBAsTFlZlcmlTaWduIFRy" + "dXN0IE5ldHdvcmsxRjBEBgNVBAsTPXd3dy52ZXJpc2lnbi5jb20vcmVwb3NpdG9yeS9SUEEgSW5j" + "b3JwLiBCeSBSZWYuLExJQUIuTFREKGMpOTgxSDBGBgNVBAMTP1ZlcmlTaWduIENsYXNzIDEgQ0Eg" + "SW5kaXZpZHVhbCBTdWJzY3JpYmVyLVBlcnNvbmEgTm90IFZhbGlkYXRlZDCBnzANBgkqhkiG9w0B" + "AQEFAAOBjQAwgYkCgYEAu1pEigQWu1X9A3qKLZRPFXg2uA1Ksm+cVL+86HcqnbnwaLuV2TFBcHqB" + "S7lIE1YtxwjhhEKrwKKSq0RcqkLwgg4C6S/7wju7vsknCl22sDZCM7VuVIhPh0q/Gdr5FegPh7Yc" + "48zGmo5/aiSS4/zgZbqnsX7vyds3ashKyAkG5JkCAwEAAaN8MHowEQYJYIZIAYb4QgEBBAQDAgEG" + "MEcGA1UdIARAMD4wPAYLYIZIAYb4RQEHAQEwLTArBggrBgEFBQcCARYfd3d3LnZlcmlzaWduLmNv" + "bS9yZXBvc2l0b3J5L1JQQTAPBgNVHRMECDAGAQH/AgEAMAsGA1UdDwQEAwIBBjANBgkqhkiG9w0B" + "AQIFAAOBgQCIuDc73dqUNwCtqp/hgQFxHpJqbS/28Z3TymQ43BuYDAeGW4UVag+5SYWklfEXfWe0" + "fy0s3ZpCnsM+tI6q5QsG3vJWKvozx74Z11NMw73I4xe1pElCY+zCphcPXVgaSTyQXFWjZSAA/Rgg" + "5V+CprGoksVYasGNAzzrw80FopCubjCCA/gwggNhoAMCAQICEBbbn/1G1zppD6KsP01bwywwDQYJ" + "KoZIhvcNAQEEBQAwgcwxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2ln" + "biBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3JlcG9zaXRvcnkvUlBB" + "IEluY29ycC4gQnkgUmVmLixMSUFCLkxURChjKTk4MUgwRgYDVQQDEz9WZXJpU2lnbiBDbGFzcyAx" + "IENBIEluZGl2aWR1YWwgU3Vic2NyaWJlci1QZXJzb25hIE5vdCBWYWxpZGF0ZWQwHhcNMDAxMDAy" + "MDAwMDAwWhcNMDAxMjAxMjM1OTU5WjCCAQcxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYD" + "VQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMUYwRAYDVQQLEz13d3cudmVyaXNpZ24uY29tL3Jl" + "cG9zaXRvcnkvUlBBIEluY29ycC4gYnkgUmVmLixMSUFCLkxURChjKTk4MR4wHAYDVQQLExVQZXJz" + "b25hIE5vdCBWYWxpZGF0ZWQxJzAlBgNVBAsTHkRpZ2l0YWwgSUQgQ2xhc3MgMSAtIE1pY3Jvc29m" + "dDETMBEGA1UEAxQKRGF2aWQgUnlhbjElMCMGCSqGSIb3DQEJARYWZGF2aWRAbGl2ZW1lZGlhLmNv" + "bS5hdTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAqxBsdeNmSvFqhMNwhQgNzM8mdjX9eSXb" + "DawpHtQHjmh0AKJSa3IwUY0VIsyZHuXWktO/CgaMBVPt6OVf/n0R2sQigMP6Y+PhEiS0vCJBL9aK" + "0+pOo2qXrjVBmq+XuCyPTnc+BOSrU26tJsX0P9BYorwySiEGxGanBNATdVL4NdUCAwEAAaOBnDCB" + "mTAJBgNVHRMEAjAAMEQGA1UdIAQ9MDswOQYLYIZIAYb4RQEHAQgwKjAoBggrBgEFBQcCARYcaHR0" + "cHM6Ly93d3cudmVyaXNpZ24uY29tL3JwYTARBglghkgBhvhCAQEEBAMCB4AwMwYDVR0fBCwwKjAo" + "oCagJIYiaHR0cDovL2NybC52ZXJpc2lnbi5jb20vY2xhc3MxLmNybDANBgkqhkiG9w0BAQQFAAOB" + "gQBC8yIIdVGpFTf8/YiL14cMzcmL0nIRm4kGR3U59z7UtcXlfNXXJ8MyaeI/BnXwG/gD5OKYqW6R" + "yca9vZOxf1uoTBl82gInk865ED3Tej6msCqFzZffnSUQvOIeqLxxDlqYRQ6PmW2nAnZeyjcnbI5Y" + "syQSM2fmo7n6qJFP+GbFezGCAkUwggJBAgEBMIHhMIHMMRcwFQYDVQQKEw5WZXJpU2lnbiwgSW5j" + "LjEfMB0GA1UECxMWVmVyaVNpZ24gVHJ1c3QgTmV0d29yazFGMEQGA1UECxM9d3d3LnZlcmlzaWdu" + "LmNvbS9yZXBvc2l0b3J5L1JQQSBJbmNvcnAuIEJ5IFJlZi4sTElBQi5MVEQoYyk5ODFIMEYGA1UE" + "AxM/VmVyaVNpZ24gQ2xhc3MgMSBDQSBJbmRpdmlkdWFsIFN1YnNjcmliZXItUGVyc29uYSBOb3Qg" + "VmFsaWRhdGVkAhAW25/9Rtc6aQ+irD9NW8MsMAkGBSsOAwIaBQCggbowGAYJKoZIhvcNAQkDMQsG" + "CSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMDAxMDAyMTczNTE4WjAjBgkqhkiG9w0BCQQxFgQU" + "gZjSaBEY2oxGvlQUIMnxSXhivK8wWwYJKoZIhvcNAQkPMU4wTDAKBggqhkiG9w0DBzAOBggqhkiG" + "9w0DAgICAIAwDQYIKoZIhvcNAwICAUAwBwYFKw4DAgcwDQYIKoZIhvcNAwICASgwBwYFKw4DAh0w" + "DQYJKoZIhvcNAQEBBQAEgYAzk+PU91/ZFfoiuKOECjxEh9fDYE2jfDCheBIgh5gdcCo+sS1WQs8O" + "HreQ9Nop/JdJv1DQMBK6weNBBDoP0EEkRm1XCC144XhXZC82jBZohYmi2WvDbbC//YN58kRMYMyy" + "srrfn4Z9I+6kTriGXkrpGk9Q0LSGjmG2BIsqiF0dvwAAAAAAAA=="); // dsaWithSHA1 cert byte[] cert7 = Base64.decode( "MIIEXAYJKoZIhvcNAQcCoIIETTCCBEkCAQExCzAJBgUrDgMCGgUAMAsGCSqG" + "SIb3DQEHAaCCAsMwggK/MIIB4AIBADCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7" + "d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULjw3GobwaJX13kquPh" + "fVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABj" + "TUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/z" + "m8Q12PFp/PjOhh+nMA4xDDAKBgNVBAMTA0lEMzAeFw05NzEwMDEwMDAwMDBa" + "Fw0zODAxMDEwMDAwMDBaMA4xDDAKBgNVBAMTA0lEMzCB8DCBpwYFKw4DAhsw" + "gZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61TX5k+7NU4XPf1TULj" + "w3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BUj+pJOF9ROBM4u+FE" + "WA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqjijUHfXKTrHL1OEqV3" + "SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nA0QAAkEAkYkXLYMtGVGWj9OnzjPn" + "sB9sefSRPrVegZJCZbpW+Iv0/1RP1u04pHG9vtRpIQLjzUiWvLMU9EKQTThc" + "eNMmWDCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxg" + "Y61TX5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/Q" + "F4BUj+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jH" + "SqjijUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nAy8AMCwC" + "FBY3dBSdeprGcqpr6wr3xbG+6WW+AhRMm/facKJNxkT3iKgJbp7R8Xd3QTGC" + "AWEwggFdAgEBMBMwDjEMMAoGA1UEAxMDSUQzAgEAMAkGBSsOAwIaBQCgXTAY" + "BgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEPFw0wMjA1" + "MjQyMzEzMDdaMCMGCSqGSIb3DQEJBDEWBBS4WMsoJhf7CVbZYCFcjoTRzPkJ" + "xjCBpwYFKw4DAhswgZ0CQQEkJRHP+mN7d8miwTMN55CUSmo3TO8WGCxgY61T" + "X5k+7NU4XPf1TULjw3GobwaJX13kquPhfVXk+gVy46n4Iw3hAhUBSe/QF4BU" + "j+pJOF9ROBM4u+FEWA8CQQD4mSJbrABjTUWrlnAte8pS22Tq4/FPO7jHSqji" + "jUHfXKTrHL1OEqV3SVWcFy5j/cqBgX/zm8Q12PFp/PjOhh+nBC8wLQIVALID" + "dt+MHwawrDrwsO1Z6sXBaaJsAhRaKssrpevmLkbygKPV07XiAKBG02Zvb2Jh" + "cg=="); // testcrl.pem byte[] crl1 = Base64.decode( "MIICjTCCAfowDQYJKoZIhvcNAQECBQAwXzELMAkGA1UEBhMCVVMxIDAeBgNVBAoT" + "F1JTQSBEYXRhIFNlY3VyaXR5LCBJbmMuMS4wLAYDVQQLEyVTZWN1cmUgU2VydmVy" + "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5Fw05NTA1MDIwMjEyMjZaFw05NTA2MDEw" + "MDAxNDlaMIIBaDAWAgUCQQAABBcNOTUwMjAxMTcyNDI2WjAWAgUCQQAACRcNOTUw" + "MjEwMDIxNjM5WjAWAgUCQQAADxcNOTUwMjI0MDAxMjQ5WjAWAgUCQQAADBcNOTUw" + "MjI1MDA0NjQ0WjAWAgUCQQAAGxcNOTUwMzEzMTg0MDQ5WjAWAgUCQQAAFhcNOTUw" + "MzE1MTkxNjU0WjAWAgUCQQAAGhcNOTUwMzE1MTk0MDQxWjAWAgUCQQAAHxcNOTUw" + "MzI0MTk0NDMzWjAWAgUCcgAABRcNOTUwMzI5MjAwNzExWjAWAgUCcgAAERcNOTUw" + "MzMwMDIzNDI2WjAWAgUCQQAAIBcNOTUwNDA3MDExMzIxWjAWAgUCcgAAHhcNOTUw" + "NDA4MDAwMjU5WjAWAgUCcgAAQRcNOTUwNDI4MTcxNzI0WjAWAgUCcgAAOBcNOTUw" + "NDI4MTcyNzIxWjAWAgUCcgAATBcNOTUwNTAyMDIxMjI2WjANBgkqhkiG9w0BAQIF" + "AAN+AHqOEJXSDejYy0UwxxrH/9+N2z5xu/if0J6qQmK92W0hW158wpJg+ovV3+wQ" + "wvIEPRL2rocL0tKfAsVq1IawSJzSNgxG0lrcla3MrJBnZ4GaZDu4FutZh72MR3Gt" + "JaAL3iTJHJD55kK2D/VoyY1djlsPuNh6AEgdVwFAyp0v"); // ecdsa cert with extra octet string. byte[] oldEcdsa = Base64.decode( "MIICljCCAkCgAwIBAgIBATALBgcqhkjOPQQBBQAwgY8xCzAJBgNVBAYTAkFVMSgwJ" + "gYDVQQKEx9UaGUgTGVnaW9uIG9mIHRoZSBCb3VuY3kgQ2FzdGxlMRIwEAYDVQQHEw" + "lNZWxib3VybmUxETAPBgNVBAgTCFZpY3RvcmlhMS8wLQYJKoZIhvcNAQkBFiBmZWV" + "kYmFjay1jcnlwdG9AYm91bmN5Y2FzdGxlLm9yZzAeFw0wMTEyMDcwMTAwMDRaFw0w" + "MTEyMDcwMTAxNDRaMIGPMQswCQYDVQQGEwJBVTEoMCYGA1UEChMfVGhlIExlZ2lvb" + "iBvZiB0aGUgQm91bmN5IENhc3RsZTESMBAGA1UEBxMJTWVsYm91cm5lMREwDwYDVQ" + "QIEwhWaWN0b3JpYTEvMC0GCSqGSIb3DQEJARYgZmVlZGJhY2stY3J5cHRvQGJvdW5" + "jeWNhc3RsZS5vcmcwgeQwgb0GByqGSM49AgEwgbECAQEwKQYHKoZIzj0BAQIef + "////////////f///////gAAAAAAAf///////MEAEHn///////////////3///////" + "4AAAAAAAH///////AQeawFsO9zxiUHQ1lSSFHXKcanbL7J9HTd5YYXClCwKBB8CD/" + "qWPNyogWzMM7hkK+35BcPTWFc9Pyf7vTs8uaqvAh5///////////////9///+eXpq" + "fXZBx+9FSJoiQnQsDIgAEHwJbbcU7xholSP+w9nFHLebJUhqdLSU05lq/y9X+DHAw" + "CwYHKoZIzj0EAQUAA0MAMEACHnz6t4UNoVROp74ma4XNDjjGcjaqiIWPZLK8Bdw3G" + "QIeLZ4j3a6ividZl344UH+UPUE7xJxlYGuy7ejTsqRR"); byte[] uncompressedPtEC = Base64.decode( "MIIDKzCCAsGgAwIBAgICA+kwCwYHKoZIzj0EAQUAMGYxCzAJBgNVBAYTAkpQ" + "MRUwEwYDVQQKEwxuaXRlY2guYWMuanAxDjAMBgNVBAsTBWFpbGFiMQ8wDQYD" + "VQQDEwZ0ZXN0Y2ExHzAdBgkqhkiG9w0BCQEWEHRlc3RjYUBsb2NhbGhvc3Qw" + "HhcNMDExMDEzMTE1MzE3WhcNMjAxMjEyMTE1MzE3WjBmMQswCQYDVQQGEwJK" + "UDEVMBMGA1UEChMMbml0ZWNoLmFjLmpwMQ4wDAYDVQQLEwVhaWxhYjEPMA0G" + "A1UEAxMGdGVzdGNhMR8wHQYJKoZIhvcNAQkBFhB0ZXN0Y2FAbG9jYWxob3N0" + "MIIBczCCARsGByqGSM49AgEwggEOAgEBMDMGByqGSM49AQECKEdYWnajFmnZ" + "tzrukK2XWdle2v+GsD9l1ZiR6g7ozQDbhFH/bBiMDQcwVAQoJ5EQKrI54/CT" + "xOQ2pMsd/fsXD+EX8YREd8bKHWiLz8lIVdD5cBNeVwQoMKSc6HfI7vKZp8Q2" + "zWgIFOarx1GQoWJbMcSt188xsl30ncJuJT2OoARRBAqJ4fD+q6hbqgNSjTQ7" + "htle1KO3eiaZgcJ8rrnyN8P+5A8+5K+H9aQ/NbBR4Gs7yto5PXIUZEUgodHA" + "TZMSAcSq5ZYt4KbnSYaLY0TtH9CqAigEwZ+hglbT21B7ZTzYX2xj0x+qooJD" + "hVTLtIPaYJK2HrMPxTw6/zfrAgEPA1IABAnvfFcFDgD/JicwBGn6vR3N8MIn" + "mptZf/mnJ1y649uCF60zOgdwIyI7pVSxBFsJ7ohqXEHW0x7LrGVkdSEiipiH" + "LYslqh3xrqbAgPbl93GUo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB" + "/wQEAwIBxjAdBgNVHQ4EFgQUAEo62Xm9H6DcsE0zUDTza4BRG90wCwYHKoZI" + "zj0EAQUAA1cAMFQCKAQsCHHSNOqfJXLgt3bg5+k49hIBGVr/bfG0B9JU3rNt" + "Ycl9Y2zfRPUCKAK2ccOQXByAWfsasDu8zKHxkZv7LVDTFjAIffz3HaCQeVhD" + "z+fauEg="); byte[] keyUsage = Base64.decode( "MIIE7TCCBFagAwIBAgIEOAOR7jANBgkqhkiG9w0BAQQFADCByTELMAkGA1UE" + "BhMCVVMxFDASBgNVBAoTC0VudHJ1c3QubmV0MUgwRgYDVQQLFD93d3cuZW50" + "cnVzdC5uZXQvQ2xpZW50X0NBX0luZm8vQ1BTIGluY29ycC4gYnkgcmVmLiBs" + "aW1pdHMgbGlhYi4xJTAjBgNVBAsTHChjKSAxOTk5IEVudHJ1c3QubmV0IExp" + "bWl0ZWQxMzAxBgNVBAMTKkVudHJ1c3QubmV0IENsaWVudCBDZXJ0aWZpY2F0" + "aW9uIEF1dGhvcml0eTAeFw05OTEwMTIxOTI0MzBaFw0xOTEwMTIxOTU0MzBa" + "MIHJMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50cnVzdC5uZXQxSDBGBgNV" + "BAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0FfSW5mby9DUFMgaW5jb3Jw" + "LiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UECxMcKGMpIDE5OTkgRW50" + "cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50cnVzdC5uZXQgQ2xpZW50" + "IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIGdMA0GCSqGSIb3DQEBAQUAA4GL" + "ADCBhwKBgQDIOpleMRffrCdvkHvkGf9FozTC28GoT/Bo6oT9n3V5z8GKUZSv" + "x1cDR2SerYIbWtp/N3hHuzeYEpbOxhN979IMMFGpOZ5V+Pux5zDeg7K6PvHV" + "iTs7hbqqdCz+PzFur5GVbgbUB01LLFZHGARS2g4Qk79jkJvh34zmAqTmT173" + "iwIBA6OCAeAwggHcMBEGCWCGSAGG+EIBAQQEAwIABzCCASIGA1UdHwSCARkw" + "ggEVMIHkoIHhoIHepIHbMIHYMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRW50" + "cnVzdC5uZXQxSDBGBgNVBAsUP3d3dy5lbnRydXN0Lm5ldC9DbGllbnRfQ0Ff" + "SW5mby9DUFMgaW5jb3JwLiBieSByZWYuIGxpbWl0cyBsaWFiLjElMCMGA1UE" + "CxMcKGMpIDE5OTkgRW50cnVzdC5uZXQgTGltaXRlZDEzMDEGA1UEAxMqRW50" + "cnVzdC5uZXQgQ2xpZW50IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MQ0wCwYD" + "VQQDEwRDUkwxMCygKqAohiZodHRwOi8vd3d3LmVudHJ1c3QubmV0L0NSTC9D" + "bGllbnQxLmNybDArBgNVHRAEJDAigA8xOTk5MTAxMjE5MjQzMFqBDzIwMTkx" + "MDEyMTkyNDMwWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUxPucKXuXzUyW" + "/O5bs8qZdIuV6kwwHQYDVR0OBBYEFMT7nCl7l81MlvzuW7PKmXSLlepMMAwG" + "A1UdEwQFMAMBAf8wGQYJKoZIhvZ9B0EABAwwChsEVjQuMAMCBJAwDQYJKoZI" + "hvcNAQEEBQADgYEAP66K8ddmAwWePvrqHEa7pFuPeJoSSJn59DXeDDYHAmsQ" + "OokUgZwxpnyyQbJq5wcBoUv5nyU7lsqZwz6hURzzwy5E97BnRqqS5TvaHBkU" + "ODDV4qIxJS7x7EU47fgGWANzYrAQMY9Av2TgXD7FTx/aEkP/TOYGJqibGapE" + "PHayXOw="); byte[] nameCert = Base64.decode( "MIIEFjCCA3+gAwIBAgIEdS8BozANBgkqhkiG9w0BAQUFADBKMQswCQYDVQQGEwJE"+ "RTERMA8GA1UEChQIREFURVYgZUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRQ0Eg"+ "REFURVYgRDAzIDE6UE4wIhgPMjAwMTA1MTAxMDIyNDhaGA8yMDA0MDUwOTEwMjI0"+ "OFowgYQxCzAJBgNVBAYTAkRFMQ8wDQYDVQQIFAZCYXllcm4xEjAQBgNVBAcUCU7I"+ "dXJuYmVyZzERMA8GA1UEChQIREFURVYgZUcxHTAbBgNVBAUTFDAwMDAwMDAwMDA4"+ "OTU3NDM2MDAxMR4wHAYDVQQDFBVEaWV0bWFyIFNlbmdlbmxlaXRuZXIwgaEwDQYJ"+ "KoZIhvcNAQEBBQADgY8AMIGLAoGBAJLI/LJLKaHoMk8fBECW/od8u5erZi6jI8Ug"+ "C0a/LZyQUO/R20vWJs6GrClQtXB+AtfiBSnyZOSYzOdfDI8yEKPEv8qSuUPpOHps"+ "uNCFdLZF1vavVYGEEWs2+y+uuPmg8q1oPRyRmUZ+x9HrDvCXJraaDfTEd9olmB/Z"+ "AuC/PqpjAgUAwAAAAaOCAcYwggHCMAwGA1UdEwEB/wQCMAAwDwYDVR0PAQH/BAUD"+ "AwdAADAxBgNVHSAEKjAoMCYGBSskCAEBMB0wGwYIKwYBBQUHAgEWD3d3dy56cy5k"+ "YXRldi5kZTApBgNVHREEIjAggR5kaWV0bWFyLnNlbmdlbmxlaXRuZXJAZGF0ZXYu"+ "ZGUwgYQGA1UdIwR9MHuhc6RxMG8xCzAJBgNVBAYTAkRFMT0wOwYDVQQKFDRSZWd1"+ "bGllcnVuZ3NiZWjIb3JkZSBmyHVyIFRlbGVrb21tdW5pa2F0aW9uIHVuZCBQb3N0"+ "MSEwDAYHAoIGAQoHFBMBMTARBgNVBAMUCjVSLUNBIDE6UE6CBACm8LkwDgYHAoIG"+ "AQoMAAQDAQEAMEcGA1UdHwRAMD4wPKAUoBKGEHd3dy5jcmwuZGF0ZXYuZGWiJKQi"+ "MCAxCzAJBgNVBAYTAkRFMREwDwYDVQQKFAhEQVRFViBlRzAWBgUrJAgDBAQNMAsT"+ "A0VVUgIBBQIBATAdBgNVHQ4EFgQUfv6xFP0xk7027folhy+ziZvBJiwwLAYIKwYB"+ "BQUHAQEEIDAeMBwGCCsGAQUFBzABhhB3d3cuZGlyLmRhdGV2LmRlMA0GCSqGSIb3"+ "DQEBBQUAA4GBAEOVX6uQxbgtKzdgbTi6YLffMftFr2mmNwch7qzpM5gxcynzgVkg"+ "pnQcDNlm5AIbS6pO8jTCLfCd5TZ5biQksBErqmesIl3QD+VqtB+RNghxectZ3VEs"+ "nCUtcE7tJ8O14qwCb3TxS9dvIUFiVi4DjbxX46TdcTbTaK8/qr6AIf+l"); byte[] probSelfSignedCert = Base64.decode( "MIICxTCCAi6gAwIBAgIQAQAAAAAAAAAAAAAAAAAAATANBgkqhkiG9w0BAQUFADBF" + "MScwJQYDVQQKEx4gRElSRUNUSU9OIEdFTkVSQUxFIERFUyBJTVBPVFMxGjAYBgNV" + "BAMTESBBQyBNSU5FRkkgQiBURVNUMB4XDTA0MDUwNzEyMDAwMFoXDTE0MDUwNzEy" + "MDAwMFowRTEnMCUGA1UEChMeIERJUkVDVElPTiBHRU5FUkFMRSBERVMgSU1QT1RT" + "MRowGAYDVQQDExEgQUMgTUlORUZJIEIgVEVTVDCBnzANBgkqhkiG9w0BAQEFAAOB" + "jQAwgYkCgYEAveoCUOAukZdcFCs2qJk76vSqEX0ZFzHqQ6faBPZWjwkgUNwZ6m6m" + "qWvvyq1cuxhoDvpfC6NXILETawYc6MNwwxsOtVVIjuXlcF17NMejljJafbPximEt" + "DQ4LcQeSp4K7FyFlIAMLyt3BQ77emGzU5fjFTvHSUNb3jblx0sV28c0CAwEAAaOB" + "tTCBsjAfBgNVHSMEGDAWgBSEJ4bLbvEQY8cYMAFKPFD1/fFXlzAdBgNVHQ4EFgQU" + "hCeGy27xEGPHGDABSjxQ9f3xV5cwDgYDVR0PAQH/BAQDAgEGMBEGCWCGSAGG+EIB" + "AQQEAwIBBjA8BgNVHR8ENTAzMDGgL6AthitodHRwOi8vYWRvbmlzLnBrNy5jZXJ0" + "cGx1cy5uZXQvZGdpLXRlc3QuY3JsMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN" + "AQEFBQADgYEAmToHJWjd3+4zknfsP09H6uMbolHNGG0zTS2lrLKpzcmkQfjhQpT9" + "LUTBvfs1jdjo9fGmQLvOG+Sm51Rbjglb8bcikVI5gLbclOlvqLkm77otjl4U4Z2/" + "Y0vP14Aov3Sn3k+17EfReYUZI4liuB95ncobC4e8ZM++LjQcIM0s+Vs="); byte[] gost34102001base = Base64.decode( "MIIB1DCCAYECEEjpVKXP6Wn1yVz3VeeDQa8wCgYGKoUDAgIDBQAwbTEfMB0G" + "A1UEAwwWR29zdFIzNDEwLTIwMDEgZXhhbXBsZTESMBAGA1UECgwJQ3J5cHRv" + "UHJvMQswCQYDVQQGEwJSVTEpMCcGCSqGSIb3DQEJARYaR29zdFIzNDEwLTIw" + "MDFAZXhhbXBsZS5jb20wHhcNMDUwMjAzMTUxNjQ2WhcNMTUwMjAzMTUxNjQ2" + "WjBtMR8wHQYDVQQDDBZHb3N0UjM0MTAtMjAwMSBleGFtcGxlMRIwEAYDVQQK" + "DAlDcnlwdG9Qcm8xCzAJBgNVBAYTAlJVMSkwJwYJKoZIhvcNAQkBFhpHb3N0" + "UjM0MTAtMjAwMUBleGFtcGxlLmNvbTBjMBwGBiqFAwICEzASBgcqhQMCAiQA" + "BgcqhQMCAh4BA0MABECElWh1YAIaQHUIzROMMYks/eUFA3pDXPRtKw/nTzJ+" + "V4/rzBa5lYgD0Jp8ha4P5I3qprt+VsfLsN8PZrzK6hpgMAoGBiqFAwICAwUA" + "A0EAHw5dw/aw/OiNvHyOE65kvyo4Hp0sfz3csM6UUkp10VO247ofNJK3tsLb" + "HOLjUaqzefrlGb11WpHYrvWFg+FcLA=="); byte[] gost341094base = Base64.decode( "MIICDzCCAbwCEBcxKsIb0ghYvAQeUjfQdFAwCgYGKoUDAgIEBQAwaTEdMBsG" + "A1UEAwwUR29zdFIzNDEwLTk0IGV4YW1wbGUxEjAQBgNVBAoMCUNyeXB0b1By" + "bzELMAkGA1UEBhMCUlUxJzAlBgkqhkiG9w0BCQEWGEdvc3RSMzQxMC05NEBl" + "eGFtcGxlLmNvbTAeFw0wNTAyMDMxNTE2NTFaFw0xNTAyMDMxNTE2NTFaMGkx" + "HTAbBgNVBAMMFEdvc3RSMzQxMC05NCBleGFtcGxlMRIwEAYDVQQKDAlDcnlw" + "dG9Qcm8xCzAJBgNVBAYTAlJVMScwJQYJKoZIhvcNAQkBFhhHb3N0UjM0MTAt" + "OTRAZXhhbXBsZS5jb20wgaUwHAYGKoUDAgIUMBIGByqFAwICIAIGByqFAwIC" + "HgEDgYQABIGAu4Rm4XmeWzTYLIB/E6gZZnFX/oxUJSFHbzALJ3dGmMb7R1W+" + "t7Lzk2w5tUI3JoTiDRCKJA4fDEJNKzsRK6i/ZjkyXJSLwaj+G2MS9gklh8x1" + "G/TliYoJgmjTXHemD7aQEBON4z58nJHWrA0ILD54wbXCtrcaqCqLRYGTMjJ2" + "+nswCgYGKoUDAgIEBQADQQBxKNhOmjgz/i5CEgLOyKyz9pFGkDcaymsWYQWV" + "v7CZ0pTM8IzMzkUBW3GHsUjCFpanFZDfg2zuN+3kT+694n9B"); byte[] gost341094A = Base64.decode( "MIICSDCCAfWgAwIBAgIBATAKBgYqhQMCAgQFADCBgTEXMBUGA1UEAxMOZGVmYXVsdDM0MTAtOTQx" + "DTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1vbGExDDAKBgNVBAgT" + "A01FTDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAzMjkx" + "MzExNTdaFw0wNjAzMjkxMzExNTdaMIGBMRcwFQYDVQQDEw5kZWZhdWx0MzQxMC05NDENMAsGA1UE" + "ChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLW9sYTEMMAoGA1UECBMDTUVMMQsw" + "CQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MIGlMBwGBiqFAwICFDASBgcq" + "hQMCAiACBgcqhQMCAh4BA4GEAASBgIQACDLEuxSdRDGgdZxHmy30g/DUYkRxO9Mi/uSHX5NjvZ31" + "b7JMEMFqBtyhql1HC5xZfUwZ0aT3UnEFDfFjLP+Bf54gA+LPkQXw4SNNGOj+klnqgKlPvoqMGlwa" + "+hLPKbS561WpvB2XSTgbV+pqqXR3j6j30STmybelEV3RdS2Now8wDTALBgNVHQ8EBAMCB4AwCgYG" + "KoUDAgIEBQADQQBCFy7xWRXtNVXflKvDs0pBdBuPzjCMeZAXVxK8vUxsxxKu76d9CsvhgIFknFRi" + "wWTPiZenvNoJ4R1uzeX+vREm"); byte[] gost341094B = Base64.decode( "MIICSDCCAfWgAwIBAgIBATAKBgYqhQMCAgQFADCBgTEXMBUGA1UEAxMOcGFyYW0xLTM0MTAtOTQx" + "DTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1PbGExDDAKBgNVBAgT" + "A01lbDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAzMjkx" + "MzEzNTZaFw0wNjAzMjkxMzEzNTZaMIGBMRcwFQYDVQQDEw5wYXJhbTEtMzQxMC05NDENMAsGA1UE" + "ChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLU9sYTEMMAoGA1UECBMDTWVsMQsw" + "CQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MIGlMBwGBiqFAwICFDASBgcq" + "hQMCAiADBgcqhQMCAh4BA4GEAASBgEa+AAcZmijWs1M9x5Pn9efE8D9ztG1NMoIt0/hNZNqln3+j" + "lMZjyqPt+kTLIjtmvz9BRDmIDk6FZz+4LhG2OTL7yGpWfrMxMRr56nxomTN9aLWRqbyWmn3brz9Y" + "AUD3ifnwjjIuW7UM84JNlDTOdxx0XRUfLQIPMCXe9cO02Xskow8wDTALBgNVHQ8EBAMCB4AwCgYG" + "KoUDAgIEBQADQQBzFcnuYc/639OTW+L5Ecjw9KxGr+dwex7lsS9S1BUgKa3m1d5c+cqI0B2XUFi5" + "4iaHHJG0dCyjtQYLJr0OZjRw"); byte[] gost34102001A = Base64.decode( "MIICCzCCAbigAwIBAgIBATAKBgYqhQMCAgMFADCBhDEaMBgGA1UEAxMRZGVmYXVsdC0zNDEwLTIw" + "MDExDTALBgNVBAoTBERpZ3QxDzANBgNVBAsTBkNyeXB0bzEOMAwGA1UEBxMFWS1PbGExDDAKBgNV" + "BAgTA01lbDELMAkGA1UEBhMCcnUxGzAZBgkqhkiG9w0BCQEWDHRlc3RAdGVzdC5ydTAeFw0wNTAz" + "MjkxMzE4MzFaFw0wNjAzMjkxMzE4MzFaMIGEMRowGAYDVQQDExFkZWZhdWx0LTM0MTAtMjAwMTEN" + "MAsGA1UEChMERGlndDEPMA0GA1UECxMGQ3J5cHRvMQ4wDAYDVQQHEwVZLU9sYTEMMAoGA1UECBMD" + "TWVsMQswCQYDVQQGEwJydTEbMBkGCSqGSIb3DQEJARYMdGVzdEB0ZXN0LnJ1MGMwHAYGKoUDAgIT" + "MBIGByqFAwICIwEGByqFAwICHgEDQwAEQG/4c+ZWb10IpeHfmR+vKcbpmSOClJioYmCVgnojw0Xn" + "ned0KTg7TJreRUc+VX7vca4hLQaZ1o/TxVtfEApK/O6jDzANMAsGA1UdDwQEAwIHgDAKBgYqhQMC" + "AgMFAANBAN8y2b6HuIdkD3aWujpfQbS1VIA/7hro4vLgDhjgVmev/PLzFB8oTh3gKhExpDo82IEs" + "ZftGNsbbyp1NFg7zda0="); byte[] gostCA1 = Base64.decode( "MIIDNDCCAuGgAwIBAgIQZLcKDcWcQopF+jp4p9jylDAKBgYqhQMCAgQFADBm" + "MQswCQYDVQQGEwJSVTEPMA0GA1UEBxMGTW9zY293MRcwFQYDVQQKEw5PT08g" + "Q3J5cHRvLVBybzEUMBIGA1UECxMLRGV2ZWxvcG1lbnQxFzAVBgNVBAMTDkNQ" + "IENTUCBUZXN0IENBMB4XDTAyMDYwOTE1NTIyM1oXDTA5MDYwOTE1NTkyOVow" + "ZjELMAkGA1UEBhMCUlUxDzANBgNVBAcTBk1vc2NvdzEXMBUGA1UEChMOT09P" + "IENyeXB0by1Qcm8xFDASBgNVBAsTC0RldmVsb3BtZW50MRcwFQYDVQQDEw5D" + "UCBDU1AgVGVzdCBDQTCBpTAcBgYqhQMCAhQwEgYHKoUDAgIgAgYHKoUDAgIe" + "AQOBhAAEgYAYglywKuz1nMc9UiBYOaulKy53jXnrqxZKbCCBSVaJ+aCKbsQm" + "glhRFrw6Mwu8Cdeabo/ojmea7UDMZd0U2xhZFRti5EQ7OP6YpqD0alllo7za" + "4dZNXdX+/ag6fOORSLFdMpVx5ganU0wHMPk67j+audnCPUj/plbeyccgcdcd" + "WaOCASIwggEeMAsGA1UdDwQEAwIBxjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud" + "DgQWBBTe840gTo4zt2twHilw3PD9wJaX0TCBygYDVR0fBIHCMIG/MDygOqA4" + "hjYtaHR0cDovL2ZpZXdhbGwvQ2VydEVucm9sbC9DUCUyMENTUCUyMFRlc3Ql" + "MjBDQSgzKS5jcmwwRKBCoECGPmh0dHA6Ly93d3cuY3J5cHRvcHJvLnJ1L0Nl" + "cnRFbnJvbGwvQ1AlMjBDU1AlMjBUZXN0JTIwQ0EoMykuY3JsMDmgN6A1hjMt" + "ZmlsZTovL1xcZmlld2FsbFxDZXJ0RW5yb2xsXENQIENTUCBUZXN0IENBKDMp" + "LmNybC8wEgYJKwYBBAGCNxUBBAUCAwMAAzAKBgYqhQMCAgQFAANBAIJi7ni7" + "9rwMR5rRGTFftt2k70GbqyUEfkZYOzrgdOoKiB4IIsIstyBX0/ne6GsL9Xan" + "G2IN96RB7KrowEHeW+k="); byte[] gostCA2 = Base64.decode( "MIIC2DCCAoWgAwIBAgIQe9ZCugm42pRKNcHD8466zTAKBgYqhQMCAgMFADB+" + "MRowGAYJKoZIhvcNAQkBFgtzYmFAZGlndC5ydTELMAkGA1UEBhMCUlUxDDAK" + "BgNVBAgTA01FTDEUMBIGA1UEBxMLWW9zaGthci1PbGExDTALBgNVBAoTBERp" + "Z3QxDzANBgNVBAsTBkNyeXB0bzEPMA0GA1UEAxMGc2JhLUNBMB4XDTA0MDgw" + "MzEzMzE1OVoXDTE0MDgwMzEzNDAxMVowfjEaMBgGCSqGSIb3DQEJARYLc2Jh" + "QGRpZ3QucnUxCzAJBgNVBAYTAlJVMQwwCgYDVQQIEwNNRUwxFDASBgNVBAcT" + "C1lvc2hrYXItT2xhMQ0wCwYDVQQKEwREaWd0MQ8wDQYDVQQLEwZDcnlwdG8x" + "DzANBgNVBAMTBnNiYS1DQTBjMBwGBiqFAwICEzASBgcqhQMCAiMBBgcqhQMC" + "Ah4BA0MABEDMSy10CuOH+i8QKG2UWA4XmCt6+BFrNTZQtS6bOalyDY8Lz+G7" + "HybyipE3PqdTB4OIKAAPsEEeZOCZd2UXGQm5o4HaMIHXMBMGCSsGAQQBgjcU" + "AgQGHgQAQwBBMAsGA1UdDwQEAwIBhjAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud" + "DgQWBBRJJl3LcNMxkZI818STfoi3ng1xoDBxBgNVHR8EajBoMDGgL6Athito" + "dHRwOi8vc2JhLmRpZ3QubG9jYWwvQ2VydEVucm9sbC9zYmEtQ0EuY3JsMDOg" + "MaAvhi1maWxlOi8vXFxzYmEuZGlndC5sb2NhbFxDZXJ0RW5yb2xsXHNiYS1D" + "QS5jcmwwEAYJKwYBBAGCNxUBBAMCAQAwCgYGKoUDAgIDBQADQQA+BRJHbc/p" + "q8EYl6iJqXCuR+ozRmH7hPAP3c4KqYSC38TClCgBloLapx/3/WdatctFJW/L" + "mcTovpq088927shE"); byte[] inDirectCrl = Base64.decode( "MIIdXjCCHMcCAQEwDQYJKoZIhvcNAQEFBQAwdDELMAkGA1UEBhMCREUxHDAaBgNV" +"BAoUE0RldXRzY2hlIFRlbGVrb20gQUcxFzAVBgNVBAsUDlQtVGVsZVNlYyBUZXN0" +"MS4wDAYHAoIGAQoHFBMBMTAeBgNVBAMUF1QtVGVsZVNlYyBUZXN0IERJUiA4OlBO" +"Fw0wNjA4MDQwODQ1MTRaFw0wNjA4MDQxNDQ1MTRaMIIbfzB+AgQvrj/pFw0wMzA3" +"MjIwNTQxMjhaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD" +"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU" +"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP+oXDTAzMDcyMjA1NDEyOFowZzBlBgNV" +"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl" +"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6" +"UE4wfgIEL64/5xcNMDQwNDA1MTMxODE3WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw" +"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC" +"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/oFw0wNDA0" +"MDUxMzE4MTdaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD" +"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU" +"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP+UXDTAzMDExMzExMTgxMVowZzBlBgNV" +"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl" +"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6" +"UE4wfgIEL64/5hcNMDMwMTEzMTExODExWjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw" +"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC" +"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/jFw0wMzAx" +"MTMxMTI2NTZaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD" +"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU" +"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP+QXDTAzMDExMzExMjY1NlowZzBlBgNV" +"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl" +"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6" +"UE4wfgIEL64/4hcNMDQwNzEzMDc1ODM4WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw" +"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC" +"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/eFw0wMzAy" +"MTcwNjMzMjVaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD" +"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU" +"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP98XDTAzMDIxNzA2MzMyNVowZzBlBgNV" +"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl" +"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6" +"UE4wfgIEL64/0xcNMDMwMjE3MDYzMzI1WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw" +"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC" +"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/dFw0wMzAx" +"MTMxMTI4MTRaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD" +"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU" +"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP9cXDTAzMDExMzExMjcwN1owZzBlBgNV" +"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl" +"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6" +"UE4wfgIEL64/2BcNMDMwMTEzMTEyNzA3WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw" +"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC" +"BgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNDpQTjB+AgQvrj/VFw0wMzA0" +"MzAxMjI3NTNaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYD" +"VQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMU" +"EVNpZ0cgVGVzdCBDQSA0OlBOMH4CBC+uP9YXDTAzMDQzMDEyMjc1M1owZzBlBgNV" +"HR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl" +"bGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDQ6" +"UE4wfgIEL64/xhcNMDMwMjEyMTM0NTQwWjBnMGUGA1UdHQEB/wRbMFmkVzBVMQsw" +"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKC" +"BgEKBxQTATEwGAYDVQQDFBFUVEMgVGVzdCBDQSAxMTpQTjCBkAIEL64/xRcNMDMw" +"MjEyMTM0NTQwWjB5MHcGA1UdHQEB/wRtMGukaTBnMQswCQYDVQQGEwJERTEcMBoG" +"A1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEQMA4GA1UECxQHVGVsZVNlYzEoMAwG" +"BwKCBgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0EgNTpQTjB+AgQvrj/CFw0w" +"MzAyMTIxMzA5MTZaMGcwZQYDVR0dAQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRww" +"GgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNV" +"BAMUEVRUQyBUZXN0IENBIDExOlBOMIGQAgQvrj/BFw0wMzAyMTIxMzA4NDBaMHkw" +"dwYDVR0dAQH/BG0wa6RpMGcxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2No" +"ZSBUZWxla29tIEFHMRAwDgYDVQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAY" +"BgNVBAMUEVNpZ0cgVGVzdCBDQSA1OlBOMH4CBC+uP74XDTAzMDIxNzA2MzcyNVow" +"ZzBlBgNVHR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRz" +"Y2hlIFRlbGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRVFRDIFRlc3Qg" +"Q0EgMTE6UE4wgZACBC+uP70XDTAzMDIxNzA2MzcyNVoweTB3BgNVHR0BAf8EbTBr" +"pGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcx" +"EDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBU" +"ZXN0IENBIDU6UE4wgZACBC+uP7AXDTAzMDIxMjEzMDg1OVoweTB3BgNVHR0BAf8E" +"bTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20g" +"QUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2ln" +"RyBUZXN0IENBIDU6UE4wgZACBC+uP68XDTAzMDIxNzA2MzcyNVoweTB3BgNVHR0B" +"Af8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVr" +"b20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQR" +"U2lnRyBUZXN0IENBIDU6UE4wfgIEL64/kxcNMDMwNDEwMDUyNjI4WjBnMGUGA1Ud" +"HQEB/wRbMFmkVzBVMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVs" +"ZWtvbSBBRzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFUVEMgVGVzdCBDQSAxMTpQ" +"TjCBkAIEL64/khcNMDMwNDEwMDUyNjI4WjB5MHcGA1UdHQEB/wRtMGukaTBnMQsw" +"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEQMA4GA1UE" +"CxQHVGVsZVNlYzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFTaWdHIFRlc3QgQ0Eg" +"NTpQTjB+AgQvrj8/Fw0wMzAyMjYxMTA0NDRaMGcwZQYDVR0dAQH/BFswWaRXMFUx" +"CzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMSgwDAYH" +"AoIGAQoHFBMBMTAYBgNVBAMUEVRUQyBUZXN0IENBIDExOlBOMIGQAgQvrj8+Fw0w" +"MzAyMjYxMTA0NDRaMHkwdwYDVR0dAQH/BG0wa6RpMGcxCzAJBgNVBAYTAkRFMRww" +"GgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAwDgYDVQQLFAdUZWxlU2VjMSgw" +"DAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVzdCBDQSA1OlBOMH4CBC+uPs0X" +"DTAzMDUyMDA1MjczNlowZzBlBgNVHR0BAf8EWzBZpFcwVTELMAkGA1UEBhMCREUx" +"HDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxKDAMBgcCggYBCgcUEwExMBgG" +"A1UEAxQRVFRDIFRlc3QgQ0EgMTE6UE4wgZACBC+uPswXDTAzMDUyMDA1MjczNlow" +"eTB3BgNVHR0BAf8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRz" +"Y2hlIFRlbGVrb20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwEx" +"MBgGA1UEAxQRU2lnRyBUZXN0IENBIDY6UE4wfgIEL64+PBcNMDMwNjE3MTAzNDE2" +"WjBnMGUGA1UdHQEB/wRbMFmkVzBVMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1" +"dHNjaGUgVGVsZWtvbSBBRzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFUVEMgVGVz" +"dCBDQSAxMTpQTjCBkAIEL64+OxcNMDMwNjE3MTAzNDE2WjB5MHcGA1UdHQEB/wRt" +"MGukaTBnMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBB" +"RzEQMA4GA1UECxQHVGVsZVNlYzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFTaWdH" +"IFRlc3QgQ0EgNjpQTjCBkAIEL64+OhcNMDMwNjE3MTAzNDE2WjB5MHcGA1UdHQEB" +"/wRtMGukaTBnMQswCQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtv" +"bSBBRzEQMA4GA1UECxQHVGVsZVNlYzEoMAwGBwKCBgEKBxQTATEwGAYDVQQDFBFT" +"aWdHIFRlc3QgQ0EgNjpQTjB+AgQvrj45Fw0wMzA2MTcxMzAxMDBaMGcwZQYDVR0d" +"AQH/BFswWaRXMFUxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxl" +"a29tIEFHMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVRUQyBUZXN0IENBIDExOlBO" +"MIGQAgQvrj44Fw0wMzA2MTcxMzAxMDBaMHkwdwYDVR0dAQH/BG0wa6RpMGcxCzAJ" +"BgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAwDgYDVQQL" +"FAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVzdCBDQSA2" +"OlBOMIGQAgQvrj43Fw0wMzA2MTcxMzAxMDBaMHkwdwYDVR0dAQH/BG0wa6RpMGcx" +"CzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAwDgYD" +"VQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVzdCBD" +"QSA2OlBOMIGQAgQvrj42Fw0wMzA2MTcxMzAxMDBaMHkwdwYDVR0dAQH/BG0wa6Rp" +"MGcxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFHMRAw" +"DgYDVQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cgVGVz" +"dCBDQSA2OlBOMIGQAgQvrj4zFw0wMzA2MTcxMDM3NDlaMHkwdwYDVR0dAQH/BG0w" +"a6RpMGcxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFH" +"MRAwDgYDVQQLFAdUZWxlU2VjMSgwDAYHAoIGAQoHFBMBMTAYBgNVBAMUEVNpZ0cg" +"VGVzdCBDQSA2OlBOMH4CBC+uPjEXDTAzMDYxNzEwNDI1OFowZzBlBgNVHR0BAf8E" +"WzBZpFcwVTELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20g" +"QUcxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRVFRDIFRlc3QgQ0EgMTE6UE4wgZAC" +"BC+uPjAXDTAzMDYxNzEwNDI1OFoweTB3BgNVHR0BAf8EbTBrpGkwZzELMAkGA1UE" +"BhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAOBgNVBAsUB1Rl" +"bGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDY6UE4w" +"gZACBC+uPakXDTAzMTAyMjExMzIyNFoweTB3BgNVHR0BAf8EbTBrpGkwZzELMAkG" +"A1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAOBgNVBAsU" +"B1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENBIDY6" +"UE4wgZACBC+uPLIXDTA1MDMxMTA2NDQyNFoweTB3BgNVHR0BAf8EbTBrpGkwZzEL" +"MAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAOBgNV" +"BAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0IENB" +"IDY6UE4wgZACBC+uPKsXDTA0MDQwMjA3NTQ1M1oweTB3BgNVHR0BAf8EbTBrpGkw" +"ZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcxEDAO" +"BgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBUZXN0" +"IENBIDY6UE4wgZACBC+uOugXDTA1MDEyNzEyMDMyNFoweTB3BgNVHR0BAf8EbTBr" +"pGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20gQUcx" +"EDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2lnRyBU" +"ZXN0IENBIDY6UE4wgZACBC+uOr4XDTA1MDIxNjA3NTcxNloweTB3BgNVHR0BAf8E" +"bTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVrb20g" +"QUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQRU2ln" +"RyBUZXN0IENBIDY6UE4wgZACBC+uOqcXDTA1MDMxMDA1NTkzNVoweTB3BgNVHR0B" +"Af8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRlbGVr" +"b20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UEAxQR" +"U2lnRyBUZXN0IENBIDY6UE4wgZACBC+uOjwXDTA1MDUxMTEwNDk0NloweTB3BgNV" +"HR0BAf8EbTBrpGkwZzELMAkGA1UEBhMCREUxHDAaBgNVBAoUE0RldXRzY2hlIFRl" +"bGVrb20gQUcxEDAOBgNVBAsUB1RlbGVTZWMxKDAMBgcCggYBCgcUEwExMBgGA1UE" +"AxQRU2lnRyBUZXN0IENBIDY6UE4wgaoCBC+sbdUXDTA1MTExMTEwMDMyMVowgZIw" +"gY8GA1UdHQEB/wSBhDCBgaR/MH0xCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0" +"c2NoZSBUZWxla29tIEFHMR8wHQYDVQQLFBZQcm9kdWt0emVudHJ1bSBUZWxlU2Vj" +"MS8wDAYHAoIGAQoHFBMBMTAfBgNVBAMUGFRlbGVTZWMgUEtTIFNpZ0cgQ0EgMTpQ" +"TjCBlQIEL64uaBcNMDYwMTIzMTAyNTU1WjB+MHwGA1UdHQEB/wRyMHCkbjBsMQsw" +"CQYDVQQGEwJERTEcMBoGA1UEChQTRGV1dHNjaGUgVGVsZWtvbSBBRzEWMBQGA1UE" +"CxQNWmVudHJhbGUgQm9ubjEnMAwGBwKCBgEKBxQTATEwFwYDVQQDFBBUVEMgVGVz" +"dCBDQSA5OlBOMIGVAgQvribHFw0wNjA4MDEwOTQ4NDRaMH4wfAYDVR0dAQH/BHIw" +"cKRuMGwxCzAJBgNVBAYTAkRFMRwwGgYDVQQKFBNEZXV0c2NoZSBUZWxla29tIEFH" +"MRYwFAYDVQQLFA1aZW50cmFsZSBCb25uMScwDAYHAoIGAQoHFBMBMTAXBgNVBAMU" +"EFRUQyBUZXN0IENBIDk6UE6ggZswgZgwCwYDVR0UBAQCAhEMMB8GA1UdIwQYMBaA" +"FANbyNumDI9545HwlCF26NuOJC45MA8GA1UdHAEB/wQFMAOEAf8wVwYDVR0SBFAw" +"ToZMbGRhcDovL3Brc2xkYXAudHR0Yy5kZS9vdT1ULVRlbGVTZWMgVGVzdCBESVIg" +"ODpQTixvPURldXRzY2hlIFRlbGVrb20gQUcsYz1kZTANBgkqhkiG9w0BAQUFAAOB" +"gQBewL5gLFHpeOWO07Vk3Gg7pRDuAlvaovBH4coCyCWpk5jEhUfFSYEDuaQB7do4" +"IlJmeTHvkI0PIZWJ7bwQ2PVdipPWDx0NVwS/Cz5jUKiS3BbAmZQZOueiKLFpQq3A" +"b8aOHA7WHU4078/1lM+bgeu33Ln1CGykEbmSjA/oKPi/JA=="); byte[] directCRL = Base64.decode( "MIIGXTCCBckCAQEwCgYGKyQDAwECBQAwdDELMAkGA1UEBhMCREUxHDAaBgNVBAoU" +"E0RldXRzY2hlIFRlbGVrb20gQUcxFzAVBgNVBAsUDlQtVGVsZVNlYyBUZXN0MS4w" +"DAYHAoIGAQoHFBMBMTAeBgNVBAMUF1QtVGVsZVNlYyBUZXN0IERJUiA4OlBOFw0w" +"NjA4MDQwODQ1MTRaFw0wNjA4MDQxNDQ1MTRaMIIElTAVAgQvrj/pFw0wMzA3MjIw" +"NTQxMjhaMBUCBC+uP+oXDTAzMDcyMjA1NDEyOFowFQIEL64/5xcNMDQwNDA1MTMx" +"ODE3WjAVAgQvrj/oFw0wNDA0MDUxMzE4MTdaMBUCBC+uP+UXDTAzMDExMzExMTgx" +"MVowFQIEL64/5hcNMDMwMTEzMTExODExWjAVAgQvrj/jFw0wMzAxMTMxMTI2NTZa" +"MBUCBC+uP+QXDTAzMDExMzExMjY1NlowFQIEL64/4hcNMDQwNzEzMDc1ODM4WjAV" +"AgQvrj/eFw0wMzAyMTcwNjMzMjVaMBUCBC+uP98XDTAzMDIxNzA2MzMyNVowFQIE" +"L64/0xcNMDMwMjE3MDYzMzI1WjAVAgQvrj/dFw0wMzAxMTMxMTI4MTRaMBUCBC+u" +"P9cXDTAzMDExMzExMjcwN1owFQIEL64/2BcNMDMwMTEzMTEyNzA3WjAVAgQvrj/V" +"Fw0wMzA0MzAxMjI3NTNaMBUCBC+uP9YXDTAzMDQzMDEyMjc1M1owFQIEL64/xhcN" +"MDMwMjEyMTM0NTQwWjAVAgQvrj/FFw0wMzAyMTIxMzQ1NDBaMBUCBC+uP8IXDTAz" +"MDIxMjEzMDkxNlowFQIEL64/wRcNMDMwMjEyMTMwODQwWjAVAgQvrj++Fw0wMzAy" +"MTcwNjM3MjVaMBUCBC+uP70XDTAzMDIxNzA2MzcyNVowFQIEL64/sBcNMDMwMjEy" +"MTMwODU5WjAVAgQvrj+vFw0wMzAyMTcwNjM3MjVaMBUCBC+uP5MXDTAzMDQxMDA1" +"MjYyOFowFQIEL64/khcNMDMwNDEwMDUyNjI4WjAVAgQvrj8/Fw0wMzAyMjYxMTA0" +"NDRaMBUCBC+uPz4XDTAzMDIyNjExMDQ0NFowFQIEL64+zRcNMDMwNTIwMDUyNzM2" +"WjAVAgQvrj7MFw0wMzA1MjAwNTI3MzZaMBUCBC+uPjwXDTAzMDYxNzEwMzQxNlow" +"FQIEL64+OxcNMDMwNjE3MTAzNDE2WjAVAgQvrj46Fw0wMzA2MTcxMDM0MTZaMBUC" +"BC+uPjkXDTAzMDYxNzEzMDEwMFowFQIEL64+OBcNMDMwNjE3MTMwMTAwWjAVAgQv" +"rj43Fw0wMzA2MTcxMzAxMDBaMBUCBC+uPjYXDTAzMDYxNzEzMDEwMFowFQIEL64+" +"MxcNMDMwNjE3MTAzNzQ5WjAVAgQvrj4xFw0wMzA2MTcxMDQyNThaMBUCBC+uPjAX" +"DTAzMDYxNzEwNDI1OFowFQIEL649qRcNMDMxMDIyMTEzMjI0WjAVAgQvrjyyFw0w" +"NTAzMTEwNjQ0MjRaMBUCBC+uPKsXDTA0MDQwMjA3NTQ1M1owFQIEL6466BcNMDUw" +"MTI3MTIwMzI0WjAVAgQvrjq+Fw0wNTAyMTYwNzU3MTZaMBUCBC+uOqcXDTA1MDMx" +"MDA1NTkzNVowFQIEL646PBcNMDUwNTExMTA0OTQ2WjAVAgQvrG3VFw0wNTExMTEx" +"MDAzMjFaMBUCBC+uLmgXDTA2MDEyMzEwMjU1NVowFQIEL64mxxcNMDYwODAxMDk0" +"ODQ0WqCBijCBhzALBgNVHRQEBAICEQwwHwYDVR0jBBgwFoAUA1vI26YMj3njkfCU" +"IXbo244kLjkwVwYDVR0SBFAwToZMbGRhcDovL3Brc2xkYXAudHR0Yy5kZS9vdT1U" +"LVRlbGVTZWMgVGVzdCBESVIgODpQTixvPURldXRzY2hlIFRlbGVrb20gQUcsYz1k" +"ZTAKBgYrJAMDAQIFAAOBgQArj4eMlbAwuA2aS5O4UUUHQMKKdK/dtZi60+LJMiMY" +"ojrMIf4+ZCkgm1Ca0Cd5T15MJxVHhh167Ehn/Hd48pdnAP6Dfz/6LeqkIHGWMHR+" +"z6TXpwWB+P4BdUec1ztz04LypsznrHcLRa91ixg9TZCb1MrOG+InNhleRs1ImXk8" +"MQ=="); private final byte[] pkcs7CrlProblem = Base64.decode( "MIIwSAYJKoZIhvcNAQcCoIIwOTCCMDUCAQExCzAJBgUrDgMCGgUAMAsGCSqG" + "SIb3DQEHAaCCEsAwggP4MIIC4KADAgECAgF1MA0GCSqGSIb3DQEBBQUAMEUx" + "CzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMR4wHAYDVQQD" + "ExVHZW9UcnVzdCBDQSBmb3IgQWRvYmUwHhcNMDQxMjAyMjEyNTM5WhcNMDYx" + "MjMwMjEyNTM5WjBMMQswCQYDVQQGEwJVUzEVMBMGA1UEChMMR2VvVHJ1c3Qg" + "SW5jMSYwJAYDVQQDEx1HZW9UcnVzdCBBZG9iZSBPQ1NQIFJlc3BvbmRlcjCB" + "nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA4gnNYhtw7U6QeVXZODnGhHMj" + "+OgZ0DB393rEk6a2q9kq129IA2e03yKBTfJfQR9aWKc2Qj90dsSqPjvTDHFG" + "Qsagm2FQuhnA3fb1UWhPzeEIdm6bxDsnQ8nWqKqxnWZzELZbdp3I9bBLizIq" + "obZovzt60LNMghn/unvvuhpeVSsCAwEAAaOCAW4wggFqMA4GA1UdDwEB/wQE" + "AwIE8DCB5QYDVR0gAQH/BIHaMIHXMIHUBgkqhkiG9y8BAgEwgcYwgZAGCCsG" + "AQUFBwICMIGDGoGAVGhpcyBjZXJ0aWZpY2F0ZSBoYXMgYmVlbiBpc3N1ZWQg" + "aW4gYWNjb3JkYW5jZSB3aXRoIHRoZSBBY3JvYmF0IENyZWRlbnRpYWxzIENQ" + "UyBsb2NhdGVkIGF0IGh0dHA6Ly93d3cuZ2VvdHJ1c3QuY29tL3Jlc291cmNl" + "cy9jcHMwMQYIKwYBBQUHAgEWJWh0dHA6Ly93d3cuZ2VvdHJ1c3QuY29tL3Jl" + "c291cmNlcy9jcHMwEwYDVR0lBAwwCgYIKwYBBQUHAwkwOgYDVR0fBDMwMTAv" + "oC2gK4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9hZG9iZWNhMS5j" + "cmwwHwYDVR0jBBgwFoAUq4BZw2WDbR19E70Zw+wajw1HaqMwDQYJKoZIhvcN" + "AQEFBQADggEBAENJf1BD7PX5ivuaawt90q1OGzXpIQL/ClzEeFVmOIxqPc1E" + "TFRq92YuxG5b6+R+k+tGkmCwPLcY8ipg6ZcbJ/AirQhohzjlFuT6YAXsTfEj" + "CqEZfWM2sS7crK2EYxCMmKE3xDfPclYtrAoz7qZvxfQj0TuxHSstHZv39wu2" + "ZiG1BWiEcyDQyTgqTOXBoZmfJtshuAcXmTpgkrYSrS37zNlPTGh+pMYQ0yWD" + "c8OQRJR4OY5ZXfdna01mjtJTOmj6/6XPoLPYTq2gQrc2BCeNJ4bEhLb7sFVB" + "PbwPrpzTE/HRbQHDrzj0YimDxeOUV/UXctgvYwHNtEkcBLsOm/uytMYwggSh" + "MIIDiaADAgECAgQ+HL0oMA0GCSqGSIb3DQEBBQUAMGkxCzAJBgNVBAYTAlVT" + "MSMwIQYDVQQKExpBZG9iZSBTeXN0ZW1zIEluY29ycG9yYXRlZDEdMBsGA1UE" + "CxMUQWRvYmUgVHJ1c3QgU2VydmljZXMxFjAUBgNVBAMTDUFkb2JlIFJvb3Qg" + "Q0EwHhcNMDMwMTA4MjMzNzIzWhcNMjMwMTA5MDAwNzIzWjBpMQswCQYDVQQG" + "EwJVUzEjMCEGA1UEChMaQWRvYmUgU3lzdGVtcyBJbmNvcnBvcmF0ZWQxHTAb" + "BgNVBAsTFEFkb2JlIFRydXN0IFNlcnZpY2VzMRYwFAYDVQQDEw1BZG9iZSBS" + "b290IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzE9UhPen" + "ouczU38/nBKIayyZR2d+Dx65rRSI+cMQ2B3w8NWfaQovWTWwzGypTJwVoJ/O" + "IL+gz1Ti4CBmRT85hjh+nMSOByLGJPYBErA131XqaZCw24U3HuJOB7JCoWoT" + "aaBm6oCREVkqmwh5WiBELcm9cziLPC/gQxtdswvwrzUaKf7vppLdgUydPVmO" + "rTE8QH6bkTYG/OJcjdGNJtVcRc+vZT+xqtJilvSoOOq6YEL09BxKNRXO+E4i" + "Vg+VGMX4lp+f+7C3eCXpgGu91grwxnSUnfMPUNuad85LcIMjjaDKeCBEXDxU" + "ZPHqojAZn+pMBk0GeEtekt8i0slns3rSAQIDAQABo4IBTzCCAUswEQYJYIZI" + "AYb4QgEBBAQDAgAHMIGOBgNVHR8EgYYwgYMwgYCgfqB8pHoweDELMAkGA1UE" + "BhMCVVMxIzAhBgNVBAoTGkFkb2JlIFN5c3RlbXMgSW5jb3Jwb3JhdGVkMR0w" + "GwYDVQQLExRBZG9iZSBUcnVzdCBTZXJ2aWNlczEWMBQGA1UEAxMNQWRvYmUg" + "Um9vdCBDQTENMAsGA1UEAxMEQ1JMMTArBgNVHRAEJDAigA8yMDAzMDEwODIz" + "MzcyM1qBDzIwMjMwMTA5MDAwNzIzWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgw" + "FoAUgrc4SpOqmxDvgLvZVOLxD/uAnN4wHQYDVR0OBBYEFIK3OEqTqpsQ74C7" + "2VTi8Q/7gJzeMAwGA1UdEwQFMAMBAf8wHQYJKoZIhvZ9B0EABBAwDhsIVjYu" + "MDo0LjADAgSQMA0GCSqGSIb3DQEBBQUAA4IBAQAy2p9DdcH6b8lv26sdNjc+" + "vGEZNrcCPB0jWZhsnu5NhedUyCAfp9S74r8Ad30ka3AvXME6dkm10+AjhCpx" + "aiLzwScpmBX2NZDkBEzDjbyfYRzn/SSM0URDjBa6m02l1DUvvBHOvfdRN42f" + "kOQU8Rg/vulZEjX5M5LznuDVa5pxm5lLyHHD4bFhCcTl+pHwQjo3fTT5cujN" + "qmIcIenV9IIQ43sFti1oVgt+fpIsb01yggztVnSynbmrLSsdEF/bJ3Vwj/0d" + "1+ICoHnlHOX/r2RAUS2em0fbQqV8H8KmSLDXvpJpTaT2KVfFeBEY3IdRyhOy" + "Yp1PKzK9MaXB+lKrBYjIMIIEyzCCA7OgAwIBAgIEPhy9tTANBgkqhkiG9w0B" + "AQUFADBpMQswCQYDVQQGEwJVUzEjMCEGA1UEChMaQWRvYmUgU3lzdGVtcyBJ" + "bmNvcnBvcmF0ZWQxHTAbBgNVBAsTFEFkb2JlIFRydXN0IFNlcnZpY2VzMRYw" + "FAYDVQQDEw1BZG9iZSBSb290IENBMB4XDTA0MDExNzAwMDMzOVoXDTE1MDEx" + "NTA4MDAwMFowRTELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IElu" + "Yy4xHjAcBgNVBAMTFUdlb1RydXN0IENBIGZvciBBZG9iZTCCASIwDQYJKoZI" + "hvcNAQEBBQADggEPADCCAQoCggEBAKfld+BkeFrnOYW8r9L1WygTDlTdSfrO" + "YvWS/Z6Ye5/l+HrBbOHqQCXBcSeCpz7kB2WdKMh1FOE4e9JlmICsHerBLdWk" + "emU+/PDb69zh8E0cLoDfxukF6oVPXj6WSThdSG7H9aXFzRr6S3XGCuvgl+Qw" + "DTLiLYW+ONF6DXwt3TQQtKReJjOJZk46ZZ0BvMStKyBaeB6DKZsmiIo89qso" + "13VDZINH2w1KvXg0ygDizoNtbvgAPFymwnsINS1klfQlcvn0x0RJm9bYQXK3" + "5GNZAgL3M7Lqrld0jMfIUaWvuHCLyivytRuzq1dJ7E8rmidjDEk/G+27pf13" + "fNZ7vR7M+IkCAwEAAaOCAZ0wggGZMBIGA1UdEwEB/wQIMAYBAf8CAQEwUAYD" + "VR0gBEkwRzBFBgkqhkiG9y8BAgEwODA2BggrBgEFBQcCARYqaHR0cHM6Ly93" + "d3cuYWRvYmUuY29tL21pc2MvcGtpL2Nkc19jcC5odG1sMBQGA1UdJQQNMAsG" + "CSqGSIb3LwEBBTCBsgYDVR0fBIGqMIGnMCKgIKAehhxodHRwOi8vY3JsLmFk" + "b2JlLmNvbS9jZHMuY3JsMIGAoH6gfKR6MHgxCzAJBgNVBAYTAlVTMSMwIQYD" + "VQQKExpBZG9iZSBTeXN0ZW1zIEluY29ycG9yYXRlZDEdMBsGA1UECxMUQWRv" + "YmUgVHJ1c3QgU2VydmljZXMxFjAUBgNVBAMTDUFkb2JlIFJvb3QgQ0ExDTAL" + "BgNVBAMTBENSTDEwCwYDVR0PBAQDAgEGMB8GA1UdIwQYMBaAFIK3OEqTqpsQ" + "74C72VTi8Q/7gJzeMB0GA1UdDgQWBBSrgFnDZYNtHX0TvRnD7BqPDUdqozAZ" + "BgkqhkiG9n0HQQAEDDAKGwRWNi4wAwIEkDANBgkqhkiG9w0BAQUFAAOCAQEA" + "PzlZLqIAjrFeEWEs0uC29YyJhkXOE9mf3YSaFGsITF+Gl1j0pajTjyH4R35Q" + "r3floW2q3HfNzTeZ90Jnr1DhVERD6zEMgJpCtJqVuk0sixuXJHghS/KicKf4" + "YXJJPx9epuIRF1siBRnznnF90svmOJMXApc0jGnYn3nQfk4kaShSnDaYaeYR" + "DJKcsiWhl6S5zfwS7Gg8hDeyckhMQKKWnlG1CQrwlSFisKCduoodwRtWgft8" + "kx13iyKK3sbalm6vnVc+5nufS4vI+TwMXoV63NqYaSroafBWk0nL53zGXPEy" + "+A69QhzEViJKn2Wgqt5gt++jMMNImbRObIqgfgF1VjCCBUwwggQ0oAMCAQIC" + "AgGDMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1H" + "ZW9UcnVzdCBJbmMuMR4wHAYDVQQDExVHZW9UcnVzdCBDQSBmb3IgQWRvYmUw" + "HhcNMDYwMzI0MTU0MjI5WhcNMDkwNDA2MTQ0MjI5WjBzMQswCQYDVQQGEwJV" + "UzELMAkGA1UECBMCTUExETAPBgNVBAoTCEdlb1RydXN0MR0wGwYDVQQDExRN" + "YXJrZXRpbmcgRGVwYXJ0bWVudDElMCMGCSqGSIb3DQEJARYWbWFya2V0aW5n" + "QGdlb3RydXN0LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB" + "ANmvajTO4XJvAU2nVcLmXeCnAQX7RZt+7+ML3InmqQ3LCGo1weop09zV069/" + "1x/Nmieol7laEzeXxd2ghjGzwfXafqQEqHn6+vBCvqdNPoSi63fSWhnuDVWp" + "KVDOYgxOonrXl+Cc43lu4zRSq+Pi5phhrjDWcH74a3/rdljUt4c4GFezFXfa" + "w2oTzWkxj2cTSn0Szhpr17+p66UNt8uknlhmu4q44Speqql2HwmCEnpLYJrK" + "W3fOq5D4qdsvsLR2EABLhrBezamLI3iGV8cRHOUTsbTMhWhv/lKfHAyf4XjA" + "z9orzvPN5jthhIfICOFq/nStTgakyL4Ln+nFAB/SMPkCAwEAAaOCAhYwggIS" + "MA4GA1UdDwEB/wQEAwIF4DCB5QYDVR0gAQH/BIHaMIHXMIHUBgkqhkiG9y8B" + "AgEwgcYwgZAGCCsGAQUFBwICMIGDGoGAVGhpcyBjZXJ0aWZpY2F0ZSBoYXMg" + "YmVlbiBpc3N1ZWQgaW4gYWNjb3JkYW5jZSB3aXRoIHRoZSBBY3JvYmF0IENy" + "ZWRlbnRpYWxzIENQUyBsb2NhdGVkIGF0IGh0dHA6Ly93d3cuZ2VvdHJ1c3Qu" + "Y29tL3Jlc291cmNlcy9jcHMwMQYIKwYBBQUHAgEWJWh0dHA6Ly93d3cuZ2Vv" + "dHJ1c3QuY29tL3Jlc291cmNlcy9jcHMwOgYDVR0fBDMwMTAvoC2gK4YpaHR0" + "cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9hZG9iZWNhMS5jcmwwHwYDVR0j" + "BBgwFoAUq4BZw2WDbR19E70Zw+wajw1HaqMwRAYIKwYBBQUHAQEEODA2MDQG" + "CCsGAQUFBzABhihodHRwOi8vYWRvYmUtb2NzcC5nZW90cnVzdC5jb20vcmVz" + "cG9uZGVyMBQGA1UdJQQNMAsGCSqGSIb3LwEBBTA8BgoqhkiG9y8BAQkBBC4w" + "LAIBAYYnaHR0cDovL2Fkb2JlLXRpbWVzdGFtcC5nZW90cnVzdC5jb20vdHNh" + "MBMGCiqGSIb3LwEBCQIEBTADAgEBMAwGA1UdEwQFMAMCAQAwDQYJKoZIhvcN" + "AQEFBQADggEBAAOhy6QxOo+i3h877fvDvTa0plGD2bIqK7wMdNqbMDoSWied" + "FIcgcBOIm2wLxOjZBAVj/3lDq59q2rnVeNnfXM0/N0MHI9TumHRjU7WNk9e4" + "+JfJ4M+c3anrWOG3NE5cICDVgles+UHjXetHWql/LlP04+K2ZOLb6LE2xGnI" + "YyLW9REzCYNAVF+/WkYdmyceHtaBZdbyVAJq0NAJPsfgY1pWcBo31Mr1fpX9" + "WrXNTYDCqMyxMImJTmN3iI68tkXlNrhweQoArKFqBysiBkXzG/sGKYY6tWKU" + "pzjLc3vIp/LrXC5zilROes8BSvwu1w9qQrJNcGwo7O4uijoNtyYil1Exgh1Q" + "MIIdTAIBATBLMEUxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJ" + "bmMuMR4wHAYDVQQDExVHZW9UcnVzdCBDQSBmb3IgQWRvYmUCAgGDMAkGBSsO" + "AwIaBQCgggxMMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwIwYJKoZIhvcN" + "AQkEMRYEFP4R6qIdpQJzWyzrqO8X1ZfJOgChMIIMCQYJKoZIhvcvAQEIMYIL" + "+jCCC/agggZ5MIIGdTCCA6gwggKQMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV" + "BAYTAlVTMRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMR4wHAYDVQQDExVHZW9U" + "cnVzdCBDQSBmb3IgQWRvYmUXDTA2MDQwNDE3NDAxMFoXDTA2MDQwNTE3NDAx" + "MFowggIYMBMCAgC5Fw0wNTEwMTEyMDM2MzJaMBICAVsXDTA0MTEwNDE1MDk0" + "MVowEwICALgXDTA1MTIxMjIyMzgzOFowEgIBWhcNMDQxMTA0MTUwOTMzWjAT" + "AgIA5hcNMDUwODI3MDQwOTM4WjATAgIAtxcNMDYwMTE2MTc1NTEzWjATAgIA" + "hhcNMDUxMjEyMjIzODU1WjATAgIAtRcNMDUwNzA2MTgzODQwWjATAgIA4BcN" + "MDYwMzIwMDc0ODM0WjATAgIAgRcNMDUwODAyMjIzMTE1WjATAgIA3xcNMDUx" + "MjEyMjIzNjUwWjASAgFKFw0wNDExMDQxNTA5MTZaMBICAUQXDTA0MTEwNDE1" + "MDg1M1owEgIBQxcNMDQxMDAzMDEwMDQwWjASAgFsFw0wNDEyMDYxOTQ0MzFa" + "MBMCAgEoFw0wNjAzMDkxMjA3MTJaMBMCAgEkFw0wNjAxMTYxNzU1MzRaMBIC" + "AWcXDTA1MDMxODE3NTYxNFowEwICAVEXDTA2MDEzMTExMjcxMVowEgIBZBcN" + "MDQxMTExMjI0ODQxWjATAgIA8RcNMDUwOTE2MTg0ODAxWjATAgIBThcNMDYw" + "MjIxMjAxMDM2WjATAgIAwRcNMDUxMjEyMjIzODE2WjASAgFiFw0wNTAxMTAx" + "NjE5MzRaMBICAWAXDTA1MDExMDE5MDAwNFowEwICAL4XDTA1MDUxNzE0NTYx" + "MFowDQYJKoZIhvcNAQEFBQADggEBAEKhRMS3wVho1U3EvEQJZC8+JlUngmZQ" + "A78KQbHPWNZWFlNvPuf/b0s7Lu16GfNHXh1QAW6Y5Hi1YtYZ3YOPyMd4Xugt" + "gCdumbB6xtKsDyN5RvTht6ByXj+CYlYqsL7RX0izJZ6mJn4fjMkqzPKNOjb8" + "kSn5T6rn93BjlATtCE8tPVOM8dnqGccRE0OV59+nDBXc90UMt5LdEbwaUOap" + "snVB0oLcNm8d/HnlVH6RY5LnDjrT4vwfe/FApZtTecEWsllVUXDjSpwfcfD/" + "476/lpGySB2otALqzImlA9R8Ok3hJ8dnF6hhQ5Oe6OJMnGYgdhkKbxsKkdib" + "tTVl3qmH5QAwggLFMIIBrQIBATANBgkqhkiG9w0BAQUFADBpMQswCQYDVQQG" + "EwJVUzEjMCEGA1UEChMaQWRvYmUgU3lzdGVtcyBJbmNvcnBvcmF0ZWQxHTAb" + "BgNVBAsTFEFkb2JlIFRydXN0IFNlcnZpY2VzMRYwFAYDVQQDEw1BZG9iZSBS" + "b290IENBFw0wNjAxMjcxODMzMzFaFw0wNzAxMjcwMDAwMDBaMIHeMCMCBD4c" + "vUAXDTAzMDEyMTIzNDY1NlowDDAKBgNVHRUEAwoBBDAjAgQ+HL1BFw0wMzAx" + "MjEyMzQ3MjJaMAwwCgYDVR0VBAMKAQQwIwIEPhy9YhcNMDMwMTIxMjM0NzQy" + "WjAMMAoGA1UdFQQDCgEEMCMCBD4cvWEXDTA0MDExNzAxMDg0OFowDDAKBgNV" + "HRUEAwoBBDAjAgQ+HL2qFw0wNDAxMTcwMTA5MDVaMAwwCgYDVR0VBAMKAQQw" + "IwIEPhy9qBcNMDQwMTE3MDEzOTI5WjAMMAoGA1UdFQQDCgEEoC8wLTAKBgNV" + "HRQEAwIBDzAfBgNVHSMEGDAWgBSCtzhKk6qbEO+Au9lU4vEP+4Cc3jANBgkq" + "hkiG9w0BAQUFAAOCAQEAwtXF9042wG39icUlsotn5tpE3oCusLb/hBpEONhx" + "OdfEQOq0w5hf/vqaxkcf71etA+KpbEUeSVaHMHRPhx/CmPrO9odE139dJdbt" + "9iqbrC9iZokFK3h/es5kg73xujLKd7C/u5ngJ4mwBtvhMLjFjF2vJhPKHL4C" + "IgMwdaUAhrcNzy16v+mw/VGJy3Fvc6oCESW1K9tvFW58qZSNXrMlsuidgunM" + "hPKG+z0SXVyCqL7pnqKiaGddcgujYGOSY4S938oVcfZeZQEODtSYGlzldojX" + "C1U1hCK5+tHAH0Ox/WqRBIol5VCZQwJftf44oG8oviYq52aaqSejXwmfT6zb" + "76GCBXUwggVxMIIFbQoBAKCCBWYwggViBgkrBgEFBQcwAQEEggVTMIIFTzCB" + "taIWBBS+8EpykfXdl4h3z7m/NZfdkAQQERgPMjAwNjA0MDQyMDIwMTVaMGUw" + "YzA7MAkGBSsOAwIaBQAEFEb4BuZYkbjBjOjT6VeA/00fBvQaBBT3fTSQniOp" + "BbHBSkz4xridlX0bsAICAYOAABgPMjAwNjA0MDQyMDIwMTVaoBEYDzIwMDYw" + "NDA1MDgyMDE1WqEjMCEwHwYJKwYBBQUHMAECBBIEEFqooq/R2WltD7TposkT" + "BhMwDQYJKoZIhvcNAQEFBQADgYEAMig6lty4b0JDsT/oanfQG5x6jVKPACpp" + "1UA9SJ0apJJa7LeIdDFmu5C2S/CYiKZm4A4P9cAu0YzgLHxE4r6Op+HfVlAG" + "6bzUe1P/hi1KCJ8r8wxOZAktQFPSzs85RAZwkHMfB0lP2e/h666Oye+Zf8VH" + "RaE+/xZ7aswE89HXoumgggQAMIID/DCCA/gwggLgoAMCAQICAXUwDQYJKoZI" + "hvcNAQEFBQAwRTELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IElu" + "Yy4xHjAcBgNVBAMTFUdlb1RydXN0IENBIGZvciBBZG9iZTAeFw0wNDEyMDIy" + "MTI1MzlaFw0wNjEyMzAyMTI1MzlaMEwxCzAJBgNVBAYTAlVTMRUwEwYDVQQK" + "EwxHZW9UcnVzdCBJbmMxJjAkBgNVBAMTHUdlb1RydXN0IEFkb2JlIE9DU1Ag" + "UmVzcG9uZGVyMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDiCc1iG3Dt" + "TpB5Vdk4OcaEcyP46BnQMHf3esSTprar2SrXb0gDZ7TfIoFN8l9BH1pYpzZC" + "P3R2xKo+O9MMcUZCxqCbYVC6GcDd9vVRaE/N4Qh2bpvEOydDydaoqrGdZnMQ" + "tlt2ncj1sEuLMiqhtmi/O3rQs0yCGf+6e++6Gl5VKwIDAQABo4IBbjCCAWow" + "DgYDVR0PAQH/BAQDAgTwMIHlBgNVHSABAf8EgdowgdcwgdQGCSqGSIb3LwEC" + "ATCBxjCBkAYIKwYBBQUHAgIwgYMagYBUaGlzIGNlcnRpZmljYXRlIGhhcyBi" + "ZWVuIGlzc3VlZCBpbiBhY2NvcmRhbmNlIHdpdGggdGhlIEFjcm9iYXQgQ3Jl" + "ZGVudGlhbHMgQ1BTIGxvY2F0ZWQgYXQgaHR0cDovL3d3dy5nZW90cnVzdC5j" + "b20vcmVzb3VyY2VzL2NwczAxBggrBgEFBQcCARYlaHR0cDovL3d3dy5nZW90" + "cnVzdC5jb20vcmVzb3VyY2VzL2NwczATBgNVHSUEDDAKBggrBgEFBQcDCTA6" + "BgNVHR8EMzAxMC+gLaArhilodHRwOi8vY3JsLmdlb3RydXN0LmNvbS9jcmxz" + "L2Fkb2JlY2ExLmNybDAfBgNVHSMEGDAWgBSrgFnDZYNtHX0TvRnD7BqPDUdq" + "ozANBgkqhkiG9w0BAQUFAAOCAQEAQ0l/UEPs9fmK+5prC33SrU4bNekhAv8K" + "XMR4VWY4jGo9zURMVGr3Zi7Eblvr5H6T60aSYLA8txjyKmDplxsn8CKtCGiH" + "OOUW5PpgBexN8SMKoRl9YzaxLtysrYRjEIyYoTfEN89yVi2sCjPupm/F9CPR" + "O7EdKy0dm/f3C7ZmIbUFaIRzINDJOCpM5cGhmZ8m2yG4BxeZOmCSthKtLfvM" + "2U9MaH6kxhDTJYNzw5BElHg5jlld92drTWaO0lM6aPr/pc+gs9hOraBCtzYE" + "J40nhsSEtvuwVUE9vA+unNMT8dFtAcOvOPRiKYPF45RX9Rdy2C9jAc20SRwE" + "uw6b+7K0xjANBgkqhkiG9w0BAQEFAASCAQC7a4yICFGCEMPlJbydK5qLG3rV" + "sip7Ojjz9TB4nLhC2DgsIHds8jjdq2zguInluH2nLaBCVS+qxDVlTjgbI2cB" + "TaWS8nglC7nNjzkKAsa8vThA8FZUVXTW0pb74jNJJU2AA27bb4g+4WgunCrj" + "fpYp+QjDyMmdrJVqRmt5eQN+dpVxMS9oq+NrhOSEhyIb4/rejgNg9wnVK1ms" + "l5PxQ4x7kpm7+Ua41//owkJVWykRo4T1jo4eHEz1DolPykAaKie2VKH/sMqR" + "Spjh4E5biKJLOV9fKivZWKAXByXfwUbbMsJvz4v/2yVHFy9xP+tqB5ZbRoDK" + "k8PzUyCprozn+/22oYIPijCCD4YGCyqGSIb3DQEJEAIOMYIPdTCCD3EGCSqG" + "SIb3DQEHAqCCD2Iwgg9eAgEDMQswCQYFKw4DAhoFADCB+gYLKoZIhvcNAQkQ" + "AQSggeoEgecwgeQCAQEGAikCMCEwCQYFKw4DAhoFAAQUoT97qeCv3FXYaEcS" + "gY8patCaCA8CAiMHGA8yMDA2MDQwNDIwMjA1N1owAwIBPAEB/wIIO0yRre3L" + "8/6ggZCkgY0wgYoxCzAJBgNVBAYTAlVTMRYwFAYDVQQIEw1NYXNzYWNodXNl" + "dHRzMRAwDgYDVQQHEwdOZWVkaGFtMRUwEwYDVQQKEwxHZW9UcnVzdCBJbmMx" + "EzARBgNVBAsTClByb2R1Y3Rpb24xJTAjBgNVBAMTHGFkb2JlLXRpbWVzdGFt" + "cC5nZW90cnVzdC5jb22gggzJMIIDUTCCAjmgAwIBAgICAI8wDQYJKoZIhvcN" + "AQEFBQAwRTELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4x" + "HjAcBgNVBAMTFUdlb1RydXN0IENBIGZvciBBZG9iZTAeFw0wNTAxMTAwMTI5" + "MTBaFw0xNTAxMTUwODAwMDBaMIGKMQswCQYDVQQGEwJVUzEWMBQGA1UECBMN" + "TWFzc2FjaHVzZXR0czEQMA4GA1UEBxMHTmVlZGhhbTEVMBMGA1UEChMMR2Vv" + "VHJ1c3QgSW5jMRMwEQYDVQQLEwpQcm9kdWN0aW9uMSUwIwYDVQQDExxhZG9i" + "ZS10aW1lc3RhbXAuZ2VvdHJ1c3QuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GN" + "ADCBiQKBgQDRbxJotLFPWQuuEDhKtOMaBUJepGxIvWxeahMbq1DVmqnk88+j" + "w/5lfPICPzQZ1oHrcTLSAFM7Mrz3pyyQKQKMqUyiemzuG/77ESUNfBNSUfAF" + "PdtHuDMU8Is8ABVnFk63L+wdlvvDIlKkE08+VTKCRdjmuBVltMpQ6QcLFQzm" + "AQIDAQABo4GIMIGFMDoGA1UdHwQzMDEwL6AtoCuGKWh0dHA6Ly9jcmwuZ2Vv" + "dHJ1c3QuY29tL2NybHMvYWRvYmVjYTEuY3JsMB8GA1UdIwQYMBaAFKuAWcNl" + "g20dfRO9GcPsGo8NR2qjMA4GA1UdDwEB/wQEAwIGwDAWBgNVHSUBAf8EDDAK" + "BggrBgEFBQcDCDANBgkqhkiG9w0BAQUFAAOCAQEAmnyXjdtX+F79Nf0KggTd" + "6YC2MQD9s09IeXTd8TP3rBmizfM+7f3icggeCGakNfPRmIUMLoa0VM5Kt37T" + "2X0TqzBWusfbKx7HnX4v1t/G8NJJlT4SShSHv+8bjjU4lUoCmW2oEcC5vXwP" + "R5JfjCyois16npgcO05ZBT+LLDXyeBijE6qWmwLDfEpLyILzVRmyU4IE7jvm" + "rgb3GXwDUvd3yQXGRRHbPCh3nj9hBGbuzyt7GnlqnEie3wzIyMG2ET/wvTX5" + "4BFXKNe7lDLvZj/MXvd3V7gMTSVW0kAszKao56LfrVTgp1VX3UBQYwmQqaoA" + "UwFezih+jEvjW6cYJo/ErDCCBKEwggOJoAMCAQICBD4cvSgwDQYJKoZIhvcN" + "AQEFBQAwaTELMAkGA1UEBhMCVVMxIzAhBgNVBAoTGkFkb2JlIFN5c3RlbXMg" + "SW5jb3Jwb3JhdGVkMR0wGwYDVQQLExRBZG9iZSBUcnVzdCBTZXJ2aWNlczEW" + "MBQGA1UEAxMNQWRvYmUgUm9vdCBDQTAeFw0wMzAxMDgyMzM3MjNaFw0yMzAx" + "MDkwMDA3MjNaMGkxCzAJBgNVBAYTAlVTMSMwIQYDVQQKExpBZG9iZSBTeXN0" + "ZW1zIEluY29ycG9yYXRlZDEdMBsGA1UECxMUQWRvYmUgVHJ1c3QgU2Vydmlj" + "ZXMxFjAUBgNVBAMTDUFkb2JlIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUA" + "A4IBDwAwggEKAoIBAQDMT1SE96ei5zNTfz+cEohrLJlHZ34PHrmtFIj5wxDY" + "HfDw1Z9pCi9ZNbDMbKlMnBWgn84gv6DPVOLgIGZFPzmGOH6cxI4HIsYk9gES" + "sDXfVeppkLDbhTce4k4HskKhahNpoGbqgJERWSqbCHlaIEQtyb1zOIs8L+BD" + "G12zC/CvNRop/u+mkt2BTJ09WY6tMTxAfpuRNgb84lyN0Y0m1VxFz69lP7Gq" + "0mKW9Kg46rpgQvT0HEo1Fc74TiJWD5UYxfiWn5/7sLd4JemAa73WCvDGdJSd" + "8w9Q25p3zktwgyONoMp4IERcPFRk8eqiMBmf6kwGTQZ4S16S3yLSyWezetIB" + "AgMBAAGjggFPMIIBSzARBglghkgBhvhCAQEEBAMCAAcwgY4GA1UdHwSBhjCB" + "gzCBgKB+oHykejB4MQswCQYDVQQGEwJVUzEjMCEGA1UEChMaQWRvYmUgU3lz" + "dGVtcyBJbmNvcnBvcmF0ZWQxHTAbBgNVBAsTFEFkb2JlIFRydXN0IFNlcnZp" + "Y2VzMRYwFAYDVQQDEw1BZG9iZSBSb290IENBMQ0wCwYDVQQDEwRDUkwxMCsG" + "A1UdEAQkMCKADzIwMDMwMTA4MjMzNzIzWoEPMjAyMzAxMDkwMDA3MjNaMAsG" + "A1UdDwQEAwIBBjAfBgNVHSMEGDAWgBSCtzhKk6qbEO+Au9lU4vEP+4Cc3jAd" + "BgNVHQ4EFgQUgrc4SpOqmxDvgLvZVOLxD/uAnN4wDAYDVR0TBAUwAwEB/zAd" + "BgkqhkiG9n0HQQAEEDAOGwhWNi4wOjQuMAMCBJAwDQYJKoZIhvcNAQEFBQAD" + "ggEBADLan0N1wfpvyW/bqx02Nz68YRk2twI8HSNZmGye7k2F51TIIB+n1Lvi" + "vwB3fSRrcC9cwTp2SbXT4COEKnFqIvPBJymYFfY1kOQETMONvJ9hHOf9JIzR" + "REOMFrqbTaXUNS+8Ec6991E3jZ+Q5BTxGD++6VkSNfkzkvOe4NVrmnGbmUvI" + "ccPhsWEJxOX6kfBCOjd9NPly6M2qYhwh6dX0ghDjewW2LWhWC35+kixvTXKC" + "DO1WdLKduastKx0QX9sndXCP/R3X4gKgeeUc5f+vZEBRLZ6bR9tCpXwfwqZI" + "sNe+kmlNpPYpV8V4ERjch1HKE7JinU8rMr0xpcH6UqsFiMgwggTLMIIDs6AD" + "AgECAgQ+HL21MA0GCSqGSIb3DQEBBQUAMGkxCzAJBgNVBAYTAlVTMSMwIQYD" + "VQQKExpBZG9iZSBTeXN0ZW1zIEluY29ycG9yYXRlZDEdMBsGA1UECxMUQWRv" + "YmUgVHJ1c3QgU2VydmljZXMxFjAUBgNVBAMTDUFkb2JlIFJvb3QgQ0EwHhcN" + "MDQwMTE3MDAwMzM5WhcNMTUwMTE1MDgwMDAwWjBFMQswCQYDVQQGEwJVUzEW" + "MBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgQ0Eg" + "Zm9yIEFkb2JlMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp+V3" + "4GR4Wuc5hbyv0vVbKBMOVN1J+s5i9ZL9nph7n+X4esFs4epAJcFxJ4KnPuQH" + "ZZ0oyHUU4Th70mWYgKwd6sEt1aR6ZT788Nvr3OHwTRwugN/G6QXqhU9ePpZJ" + "OF1Ibsf1pcXNGvpLdcYK6+CX5DANMuIthb440XoNfC3dNBC0pF4mM4lmTjpl" + "nQG8xK0rIFp4HoMpmyaIijz2qyjXdUNkg0fbDUq9eDTKAOLOg21u+AA8XKbC" + "ewg1LWSV9CVy+fTHREmb1thBcrfkY1kCAvczsuquV3SMx8hRpa+4cIvKK/K1" + "G7OrV0nsTyuaJ2MMST8b7bul/Xd81nu9Hsz4iQIDAQABo4IBnTCCAZkwEgYD" + "VR0TAQH/BAgwBgEB/wIBATBQBgNVHSAESTBHMEUGCSqGSIb3LwECATA4MDYG" + "CCsGAQUFBwIBFipodHRwczovL3d3dy5hZG9iZS5jb20vbWlzYy9wa2kvY2Rz" + "X2NwLmh0bWwwFAYDVR0lBA0wCwYJKoZIhvcvAQEFMIGyBgNVHR8Egaowgacw" + "IqAgoB6GHGh0dHA6Ly9jcmwuYWRvYmUuY29tL2Nkcy5jcmwwgYCgfqB8pHow" + "eDELMAkGA1UEBhMCVVMxIzAhBgNVBAoTGkFkb2JlIFN5c3RlbXMgSW5jb3Jw" + "b3JhdGVkMR0wGwYDVQQLExRBZG9iZSBUcnVzdCBTZXJ2aWNlczEWMBQGA1UE" + "AxMNQWRvYmUgUm9vdCBDQTENMAsGA1UEAxMEQ1JMMTALBgNVHQ8EBAMCAQYw" + "HwYDVR0jBBgwFoAUgrc4SpOqmxDvgLvZVOLxD/uAnN4wHQYDVR0OBBYEFKuA" + "WcNlg20dfRO9GcPsGo8NR2qjMBkGCSqGSIb2fQdBAAQMMAobBFY2LjADAgSQ" + "MA0GCSqGSIb3DQEBBQUAA4IBAQA/OVkuogCOsV4RYSzS4Lb1jImGRc4T2Z/d" + "hJoUawhMX4aXWPSlqNOPIfhHflCvd+Whbarcd83NN5n3QmevUOFUREPrMQyA" + "mkK0mpW6TSyLG5ckeCFL8qJwp/hhckk/H16m4hEXWyIFGfOecX3Sy+Y4kxcC" + "lzSMadifedB+TiRpKFKcNphp5hEMkpyyJaGXpLnN/BLsaDyEN7JySExAopae" + "UbUJCvCVIWKwoJ26ih3BG1aB+3yTHXeLIorextqWbq+dVz7me59Li8j5PAxe" + "hXrc2phpKuhp8FaTScvnfMZc8TL4Dr1CHMRWIkqfZaCq3mC376Mww0iZtE5s" + "iqB+AXVWMYIBgDCCAXwCAQEwSzBFMQswCQYDVQQGEwJVUzEWMBQGA1UEChMN" + "R2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgQ0EgZm9yIEFkb2Jl" + "AgIAjzAJBgUrDgMCGgUAoIGMMBoGCSqGSIb3DQEJAzENBgsqhkiG9w0BCRAB" + "BDAcBgkqhkiG9w0BCQUxDxcNMDYwNDA0MjAyMDU3WjAjBgkqhkiG9w0BCQQx" + "FgQUp7AnXBqoNcarvO7fMJut1og2U5AwKwYLKoZIhvcNAQkQAgwxHDAaMBgw" + "FgQU1dH4eZTNhgxdiSABrat6zsPdth0wDQYJKoZIhvcNAQEBBQAEgYCinr/F" + "rMiQz/MRm9ZD5YGcC0Qo2dRTPd0Aop8mZ4g1xAhKFLnp7lLsjCbkSDpVLDBh" + "cnCk7CV+3FT5hlvt8OqZlR0CnkSnCswLFhrppiWle6cpxlwGqyAteC8uKtQu" + "wjE5GtBKLcCOAzQYyyuNZZeB6oCZ+3mPhZ62FxrvvEGJCgAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="); private final byte[] emptyDNCert = Base64.decode( "MIICfTCCAeagAwIBAgIBajANBgkqhkiG9w0BAQQFADB8MQswCQYDVQQGEwJVUzEMMAoGA1UEChMD" + "Q0RXMQkwBwYDVQQLEwAxCTAHBgNVBAcTADEJMAcGA1UECBMAMRowGAYDVQQDExFUZW1wbGFyIFRl" + "c3QgMTAyNDEiMCAGCSqGSIb3DQEJARYTdGVtcGxhcnRlc3RAY2R3LmNvbTAeFw0wNjA1MjIwNTAw" + "MDBaFw0xMDA1MjIwNTAwMDBaMHwxCzAJBgNVBAYTAlVTMQwwCgYDVQQKEwNDRFcxCTAHBgNVBAsT" + "ADEJMAcGA1UEBxMAMQkwBwYDVQQIEwAxGjAYBgNVBAMTEVRlbXBsYXIgVGVzdCAxMDI0MSIwIAYJ" + "KoZIhvcNAQkBFhN0ZW1wbGFydGVzdEBjZHcuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB" + "gQDH3aJpJBfM+A3d84j5YcU6zEQaQ76u5xO9NSBmHjZykKS2kCcUqPpvVOPDA5WgV22dtKPh+lYV" + "iUp7wyCVwAKibq8HIbihHceFqMKzjwC639rMoDJ7bi/yzQWz1Zg+075a4FGPlUKn7Yfu89wKkjdW" + "wDpRPXc/agqBnrx5pJTXzQIDAQABow8wDTALBgNVHQ8EBAMCALEwDQYJKoZIhvcNAQEEBQADgYEA" + "RRsRsjse3i2/KClFVd6YLZ+7K1BE0WxFyY2bbytkwQJSxvv3vLSuweFUbhNxutb68wl/yW4GLy4b" + "1QdyswNxrNDXTuu5ILKhRDDuWeocz83aG2KGtr3JlFyr3biWGEyn5WUOE6tbONoQDJ0oPYgI6CAc" + "EHdUp0lioOCt6UOw7Cs="); private PublicKey dudPublicKey = new PublicKey() { public String getAlgorithm() { return null; } public String getFormat() { return null; } public byte[] getEncoded() { return null; } }; public String getName() { return "CertTest"; } public void checkCertificate( int id, byte[] bytes) { ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(bytes); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); Certificate cert = fact.generateCertificate(bIn); PublicKey k = cert.getPublicKey(); // System.out.println(cert); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } public void checkNameCertificate( int id, byte[] bytes) { ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(bytes); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); X509Certificate cert = (X509Certificate)fact.generateCertificate(bIn); PublicKey k = cert.getPublicKey(); if (!cert.getIssuerDN().toString().equals("C=DE,O=DATEV eG,0.2.262.1.10.7.20=1+CN=CA DATEV D03 1:PN")) { fail(id + " failed - name test."); } // System.out.println(cert); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } public void checkKeyUsage( int id, byte[] bytes) { ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(bytes); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); X509Certificate cert = (X509Certificate)fact.generateCertificate(bIn); PublicKey k = cert.getPublicKey(); if (cert.getKeyUsage()[7]) { fail("error generating cert - key usage wrong."); } // System.out.println(cert); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } public void checkSelfSignedCertificate( int id, byte[] bytes) { ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(bytes); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); Certificate cert = fact.generateCertificate(bIn); PublicKey k = cert.getPublicKey(); cert.verify(k); // System.out.println(cert); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } /** * we generate a self signed certificate for the sake of testing - RSA */ public void checkCreation1() throws Exception { // a sample key pair. RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // set up the keys PrivateKey privKey; PublicKey pubKey; KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); privKey = fact.generatePrivate(privKeySpec); pubKey = fact.generatePublic(pubKeySpec); // distinguished name table. Hashtable attrs = new Hashtable(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); Vector ord = new Vector(); Vector values = new Vector(); ord.addElement(X509Principal.C); ord.addElement(X509Principal.O); ord.addElement(X509Principal.L); ord.addElement(X509Principal.ST); ord.addElement(X509Principal.E); values.addElement("AU"); values.addElement("The Legion of the Bouncy Castle"); values.addElement("Melbourne"); values.addElement("Victoria"); values.addElement("feedback-crypto@bouncycastle.org"); // extensions // create the certificate - version 3 - without extensions X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); X509Certificate cert = certGen.generate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); Set dummySet = cert.getNonCriticalExtensionOIDs(); if (dummySet != null) { fail("non-critical oid set should be null"); } dummySet = cert.getCriticalExtensionOIDs(); if (dummySet != null) { fail("critical oid set should be null"); } // create the certificate - version 3 - with extensions certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("MD5WithRSAEncryption"); certGen.addExtension("2.5.29.15", true, new X509KeyUsage(X509KeyUsage.encipherOnly)); certGen.addExtension("2.5.29.37", true, new DERSequence(KeyPurposeId.anyExtendedKeyUsage)); certGen.addExtension("2.5.29.17", true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); cert = certGen.generate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); ByteArrayInputStream sbIn = new ByteArrayInputStream(cert.getEncoded()); ASN1InputStream sdIn = new ASN1InputStream(sbIn); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)certFact.generateCertificate(bIn); if (!cert.getKeyUsage()[7]) { fail("error generating cert - key usage wrong."); } List l = cert.getExtendedKeyUsage(); if (!l.get(0).equals(KeyPurposeId.anyExtendedKeyUsage.getId())) { fail("failed extended key usage test"); } Collection c = cert.getSubjectAlternativeNames(); Iterator it = c.iterator(); while (it.hasNext()) { List gn = (List)it.next(); if (!gn.get(1).equals("test@test.test")) { fail("failed subject alternative names test"); } } // System.out.println(cert); // create the certificate - version 1 X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator(); certGen1.setSerialNumber(BigInteger.valueOf(1)); certGen1.setIssuerDN(new X509Principal(ord, attrs)); certGen1.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen1.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen1.setSubjectDN(new X509Principal(ord, values)); certGen1.setPublicKey(pubKey); certGen1.setSignatureAlgorithm("MD5WithRSAEncryption"); cert = certGen1.generate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); bIn = new ByteArrayInputStream(cert.getEncoded()); certFact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)certFact.generateCertificate(bIn); // System.out.println(cert); if (!cert.getIssuerDN().equals(cert.getSubjectDN())) { fail("name comparison fails"); } } /** * we generate a self signed certificate for the sake of testing - DSA */ public void checkCreation2() { // set up the keys PrivateKey privKey; PublicKey pubKey; try { KeyPairGenerator g = KeyPairGenerator.getInstance("DSA", "SUN"); g.initialize(512, new SecureRandom()); KeyPair p = g.generateKeyPair(); privKey = p.getPrivate(); pubKey = p.getPublic(); } catch (Exception e) { fail("error setting up keys - " + e.toString()); return; } // distinguished name table. Hashtable attrs = new Hashtable(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); // extensions // create the certificate - version 3 X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("SHA1withDSA"); try { X509Certificate cert = certGen.generate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)fact.generateCertificate(bIn); // System.out.println(cert); } catch (Exception e) { fail("error setting generating cert - " + e.toString()); } // create the certificate - version 1 X509V1CertificateGenerator certGen1 = new X509V1CertificateGenerator(); certGen1.setSerialNumber(BigInteger.valueOf(1)); certGen1.setIssuerDN(new X509Principal(attrs)); certGen1.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen1.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen1.setSubjectDN(new X509Principal(attrs)); certGen1.setPublicKey(pubKey); certGen1.setSignatureAlgorithm("SHA1withDSA"); try { X509Certificate cert = certGen1.generate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)fact.generateCertificate(bIn); //System.out.println(cert); } catch (Exception e) { fail("error setting generating cert - " + e.toString()); } // exception test try { certGen.setPublicKey(dudPublicKey); fail("key without encoding not detected in v1"); } catch (IllegalArgumentException e) { // expected } } /** * we generate a self signed certificate for the sake of testing - ECDSA */ public void checkCreation3() { ECCurve curve = new ECCurve.Fp( new BigInteger("883423532389192164791648750360308885314476597252960362792450860609699839"), new BigInteger("7fffffffffffffffffffffff7fffffffffff8000000000007ffffffffffc", 16), new BigInteger("6b016c3bdcf18941d0d654921475ca71a9db2fb27d1d37796185c2942c0a", 16)); ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("020ffa963cdca8816ccc33b8642bedf905c3d358573d3f27fbbd3b3cb9aaaf")), new BigInteger("883423532389192164791648750360308884807550341691627752275345424702807307")); ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec( new BigInteger("876300101507107567501066130761671078357010671067781776716671676178726717"), spec); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("025b6dc53bc61a2548ffb0f671472de6c9521a9d2d2534e65abfcbd5fe0c70")), spec); // set up the keys PrivateKey privKey; PublicKey pubKey; try { KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC"); privKey = fact.generatePrivate(privKeySpec); pubKey = fact.generatePublic(pubKeySpec); } catch (Exception e) { fail("error setting up keys - " + e.toString()); return; } // distinguished name table. Hashtable attrs = new Hashtable(); Vector order = new Vector(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); order.addElement(X509Principal.C); order.addElement(X509Principal.O); order.addElement(X509Principal.L); order.addElement(X509Principal.ST); order.addElement(X509Principal.E); // toString test X509Principal p = new X509Principal(order, attrs); String s = p.toString(); if (!s.equals("C=AU,O=The Legion of the Bouncy Castle,L=Melbourne,ST=Victoria,E=feedback-crypto@bouncycastle.org")) { fail("ordered X509Principal test failed - s = " + s + "."); } p = new X509Principal(attrs); s = p.toString(); // we need two of these as the hash code for strings changed... if (!s.equals("O=The Legion of the Bouncy Castle,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU") && !s.equals("ST=Victoria,L=Melbourne,C=AU,E=feedback-crypto@bouncycastle.org,O=The Legion of the Bouncy Castle")) { fail("unordered X509Principal test failed."); } // create the certificate - version 3 X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(order, attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(order, attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("SHA1withECDSA"); try { X509Certificate cert = certGen.generate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)fact.generateCertificate(bIn); // try with point compression turned off ((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED"); certGen.setPublicKey(pubKey); cert = certGen.generate(privKey, "BC"); cert.checkValidity(new Date()); cert.verify(pubKey); bIn = new ByteArrayInputStream(cert.getEncoded()); fact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)fact.generateCertificate(bIn); // System.out.println(cert); } catch (Exception e) { fail("error setting generating cert - " + e.toString()); } X509Principal pr = new X509Principal("O=\"The Bouncy Castle, The Legion of\",E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU"); if (!pr.toString().equals("O=The Bouncy Castle\\, The Legion of,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU")) { fail("string based X509Principal test failed."); } pr = new X509Principal("O=The Bouncy Castle\\, The Legion of,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU"); if (!pr.toString().equals("O=The Bouncy Castle\\, The Legion of,E=feedback-crypto@bouncycastle.org,ST=Victoria,L=Melbourne,C=AU")) { fail("string based X509Principal test failed."); } } /** * we generate a self signed certificate for the sake of testing - SHA224withECDSA */ private void createECCert(String algorithm, DERObjectIdentifier algOid) throws Exception { ECCurve.Fp curve = new ECCurve.Fp( new BigInteger("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151"), // q (or p) new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", 16), new BigInteger("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", 16)); ECParameterSpec spec = new ECParameterSpec( curve, curve.decodePoint(Hex.decode("02C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66")), new BigInteger("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", 16)); ECPrivateKeySpec privKeySpec = new ECPrivateKeySpec( new BigInteger("5769183828869504557786041598510887460263120754767955773309066354712783118202294874205844512909370791582896372147797293913785865682804434049019366394746072023"), spec); ECPublicKeySpec pubKeySpec = new ECPublicKeySpec( curve.decodePoint(Hex.decode("026BFDD2C9278B63C92D6624F151C9D7A822CC75BD983B17D25D74C26740380022D3D8FAF304781E416175EADF4ED6E2B47142D2454A7AC7801DD803CF44A4D1F0AC")), spec); // set up the keys PrivateKey privKey; PublicKey pubKey; KeyFactory fact = KeyFactory.getInstance("ECDSA", "BC"); privKey = fact.generatePrivate(privKeySpec); pubKey = fact.generatePublic(pubKeySpec); // distinguished name table. Hashtable attrs = new Hashtable(); Vector order = new Vector(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); order.addElement(X509Principal.C); order.addElement(X509Principal.O); order.addElement(X509Principal.L); order.addElement(X509Principal.ST); order.addElement(X509Principal.E); // create the certificate - version 3 X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(order, attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(order, attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm(algorithm); X509Certificate cert = certGen.generate(privKey, "BC"); cert.checkValidity(new Date()); cert.verify(pubKey); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)certFact.generateCertificate(bIn); // try with point compression turned off ((ECPointEncoder)pubKey).setPointFormat("UNCOMPRESSED"); certGen.setPublicKey(pubKey); cert = certGen.generate(privKey, "BC"); cert.checkValidity(new Date()); cert.verify(pubKey); bIn = new ByteArrayInputStream(cert.getEncoded()); certFact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)certFact.generateCertificate(bIn); if (!cert.getSigAlgOID().equals(algOid.toString())) { fail("ECDSA oid incorrect."); } if (cert.getSigAlgParams() != null) { fail("sig parameters present"); } Signature sig = Signature.getInstance(algorithm, "BC"); sig.initVerify(pubKey); sig.update(cert.getTBSCertificate()); if (!sig.verify(cert.getSignature())) { fail("EC certificate signature not mapped correctly."); } // System.out.println(cert); } private void checkCRL( int id, byte[] bytes) { ByteArrayInputStream bIn; String dump = ""; try { bIn = new ByteArrayInputStream(bytes); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); CRL cert = fact.generateCRL(bIn); // System.out.println(cert); } catch (Exception e) { fail(dump + System.getProperty("line.separator") + getName() + ": "+ id + " failed - exception " + e.toString(), e); } } public void checkCRLCreation1() throws Exception { KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); X509V2CRLGenerator crlGen = new X509V2CRLGenerator(); Date now = new Date(); KeyPair pair = kpGen.generateKeyPair(); crlGen.setIssuerDN(new X500Principal("CN=Test CA")); crlGen.setThisUpdate(now); crlGen.setNextUpdate(new Date(now.getTime() + 100000)); crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); crlGen.addCRLEntry(BigInteger.ONE, now, CRLReason.privilegeWithdrawn); crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic())); X509CRL crl = crlGen.generate(pair.getPrivate(), "BC"); if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA"))) { fail("failed CRL issuer test"); } byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); if (authExt == null) { fail("failed to find CRL extension"); } AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt); X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE); if (entry == null) { fail("failed to find CRL entry"); } if (!entry.getSerialNumber().equals(BigInteger.ONE)) { fail("CRL cert serial number does not match"); } if (!entry.hasExtensions()) { fail("CRL entry extension not found"); } byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId()); if (ext != null) { DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext); if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) { fail("CRL entry reasonCode wrong"); } } else { fail("CRL entry reasonCode not found"); } } public void checkCRLCreation2() throws Exception { KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); X509V2CRLGenerator crlGen = new X509V2CRLGenerator(); Date now = new Date(); KeyPair pair = kpGen.generateKeyPair(); crlGen.setIssuerDN(new X500Principal("CN=Test CA")); crlGen.setThisUpdate(now); crlGen.setNextUpdate(new Date(now.getTime() + 100000)); crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); Vector extOids = new Vector(); Vector extValues = new Vector(); CRLReason crlReason = new CRLReason(CRLReason.privilegeWithdrawn); try { extOids.addElement(X509Extensions.ReasonCode); extValues.addElement(new X509Extension(false, new DEROctetString(crlReason.getEncoded()))); } catch (IOException e) { throw new IllegalArgumentException("error encoding reason: " + e); } X509Extensions entryExtensions = new X509Extensions(extOids, extValues); crlGen.addCRLEntry(BigInteger.ONE, now, entryExtensions); crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic())); X509CRL crl = crlGen.generate(pair.getPrivate(), "BC"); if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA"))) { fail("failed CRL issuer test"); } byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); if (authExt == null) { fail("failed to find CRL extension"); } AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt); X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE); if (entry == null) { fail("failed to find CRL entry"); } if (!entry.getSerialNumber().equals(BigInteger.ONE)) { fail("CRL cert serial number does not match"); } if (!entry.hasExtensions()) { fail("CRL entry extension not found"); } byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId()); if (ext != null) { DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext); if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) { fail("CRL entry reasonCode wrong"); } } else { fail("CRL entry reasonCode not found"); } } public void checkCRLCreation3() throws Exception { KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC"); X509V2CRLGenerator crlGen = new X509V2CRLGenerator(); Date now = new Date(); KeyPair pair = kpGen.generateKeyPair(); crlGen.setIssuerDN(new X500Principal("CN=Test CA")); crlGen.setThisUpdate(now); crlGen.setNextUpdate(new Date(now.getTime() + 100000)); crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); Vector extOids = new Vector(); Vector extValues = new Vector(); CRLReason crlReason = new CRLReason(CRLReason.privilegeWithdrawn); try { extOids.addElement(X509Extensions.ReasonCode); extValues.addElement(new X509Extension(false, new DEROctetString(crlReason.getEncoded()))); } catch (IOException e) { throw new IllegalArgumentException("error encoding reason: " + e); } X509Extensions entryExtensions = new X509Extensions(extOids, extValues); crlGen.addCRLEntry(BigInteger.ONE, now, entryExtensions); crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic())); X509CRL crl = crlGen.generate(pair.getPrivate(), "BC"); if (!crl.getIssuerX500Principal().equals(new X500Principal("CN=Test CA"))) { fail("failed CRL issuer test"); } byte[] authExt = crl.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); if (authExt == null) { fail("failed to find CRL extension"); } AuthorityKeyIdentifier authId = new AuthorityKeyIdentifierStructure(authExt); X509CRLEntry entry = crl.getRevokedCertificate(BigInteger.ONE); if (entry == null) { fail("failed to find CRL entry"); } if (!entry.getSerialNumber().equals(BigInteger.ONE)) { fail("CRL cert serial number does not match"); } if (!entry.hasExtensions()) { fail("CRL entry extension not found"); } byte[] ext = entry.getExtensionValue(X509Extensions.ReasonCode.getId()); if (ext != null) { DEREnumerated reasonCode = (DEREnumerated)X509ExtensionUtil.fromExtensionValue(ext); if (reasonCode.getValue().intValue() != CRLReason.privilegeWithdrawn) { fail("CRL entry reasonCode wrong"); } } else { fail("CRL entry reasonCode not found"); } // check loading of existing CRL crlGen = new X509V2CRLGenerator(); now = new Date(); crlGen.setIssuerDN(new X500Principal("CN=Test CA")); crlGen.setThisUpdate(now); crlGen.setNextUpdate(new Date(now.getTime() + 100000)); crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); crlGen.addCRL(crl); crlGen.addCRLEntry(BigInteger.valueOf(2), now, entryExtensions); crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(pair.getPublic())); X509CRL newCrl = crlGen.generate(pair.getPrivate(), "BC"); int count = 0; boolean oneFound = false; boolean twoFound = false; Iterator it = newCrl.getRevokedCertificates().iterator(); while (it.hasNext()) { X509CRLEntry crlEnt = (X509CRLEntry)it.next(); if (crlEnt.getSerialNumber().intValue() == 1) { oneFound = true; } else if (crlEnt.getSerialNumber().intValue() == 2) { twoFound = true; } count++; } if (count != 2) { fail("wrong number of CRLs found"); } if (!oneFound || !twoFound) { fail("wrong CRLs found in copied list"); } // check factory read back CertificateFactory cFact = CertificateFactory.getInstance("X.509", "BC"); X509CRL readCrl = (X509CRL)cFact.generateCRL(new ByteArrayInputStream(newCrl.getEncoded())); if (readCrl == null) { fail("crl not returned!"); } Collection col = cFact.generateCRLs(new ByteArrayInputStream(newCrl.getEncoded())); if (col.size() != 1) { fail("wrong number of CRLs found in collection"); } } /** * we generate a self signed certificate for the sake of testing - GOST3410 */ public void checkCreation4() throws Exception { // set up the keys PrivateKey privKey; PublicKey pubKey; KeyPairGenerator g = KeyPairGenerator.getInstance("GOST3410", "BC"); GOST3410ParameterSpec gost3410P = new GOST3410ParameterSpec("GostR3410-94-CryptoPro-A"); g.initialize(gost3410P, new SecureRandom()); KeyPair p = g.generateKeyPair(); privKey = p.getPrivate(); pubKey = p.getPublic(); // distinguished name table. Hashtable attrs = new Hashtable(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); // extensions // create the certificate - version 3 X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("GOST3411withGOST3410"); X509Certificate cert = certGen.generate(privKey, "BC"); cert.checkValidity(new Date()); // check verifies in general cert.verify(pubKey); // check verifies with contained key cert.verify(cert.getPublicKey()); ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded()); CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); cert = (X509Certificate)fact.generateCertificate(bIn); //System.out.println(cert); //check getEncoded() byte[] bytesch = cert.getEncoded(); } public void checkCreation5() throws Exception { // a sample key pair. RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // set up the keys SecureRandom rand = new SecureRandom(); PrivateKey privKey; PublicKey pubKey; KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); privKey = fact.generatePrivate(privKeySpec); pubKey = fact.generatePublic(pubKeySpec); // distinguished name table. Hashtable attrs = new Hashtable(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); Vector ord = new Vector(); Vector values = new Vector(); ord.addElement(X509Principal.C); ord.addElement(X509Principal.O); ord.addElement(X509Principal.L); ord.addElement(X509Principal.ST); ord.addElement(X509Principal.E); values.addElement("AU"); values.addElement("The Legion of the Bouncy Castle"); values.addElement("Melbourne"); values.addElement("Victoria"); values.addElement("feedback-crypto@bouncycastle.org"); // create base certificate - version 3 X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("MD5WithRSAEncryption"); certGen.addExtension("2.5.29.15", true, new X509KeyUsage(X509KeyUsage.encipherOnly)); certGen.addExtension("2.5.29.37", true, new DERSequence(KeyPurposeId.anyExtendedKeyUsage)); certGen.addExtension("2.5.29.17", true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); X509Certificate baseCert = certGen.generate(privKey, "BC"); // copy certificate certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("MD5WithRSAEncryption"); certGen.copyAndAddExtension(new DERObjectIdentifier("2.5.29.15"), true, baseCert); certGen.copyAndAddExtension("2.5.29.37", false, baseCert); X509Certificate cert = certGen.generate(privKey, "BC"); cert.checkValidity(new Date()); cert.verify(pubKey); if (!areEqual(baseCert.getExtensionValue("2.5.29.15"), cert.getExtensionValue("2.5.29.15"))) { fail("2.5.29.15 differs"); } if (!areEqual(baseCert.getExtensionValue("2.5.29.37"), cert.getExtensionValue("2.5.29.37"))) { fail("2.5.29.37 differs"); } // exception test try { certGen.copyAndAddExtension("2.5.99.99", true, baseCert); fail("exception not thrown on dud extension copy"); } catch (CertificateParsingException e) { // expected } try { certGen.setPublicKey(dudPublicKey); certGen.generate(privKey, "BC"); fail("key without encoding not detected in v3"); } catch (IllegalArgumentException e) { // expected } } private void testForgedSignature() throws Exception { String cert = "MIIBsDCCAVoCAQYwDQYJKoZIhvcNAQEFBQAwYzELMAkGA1UEBhMCQVUxEzARBgNV" + "BAgTClF1ZWVuc2xhbmQxGjAYBgNVBAoTEUNyeXB0U29mdCBQdHkgTHRkMSMwIQYD" + "VQQDExpTZXJ2ZXIgdGVzdCBjZXJ0ICg1MTIgYml0KTAeFw0wNjA5MTEyMzU4NTVa" + "Fw0wNjEwMTEyMzU4NTVaMGMxCzAJBgNVBAYTAkFVMRMwEQYDVQQIEwpRdWVlbnNs" + "YW5kMRowGAYDVQQKExFDcnlwdFNvZnQgUHR5IEx0ZDEjMCEGA1UEAxMaU2VydmVy" + "IHRlc3QgY2VydCAoNTEyIGJpdCkwXDANBgkqhkiG9w0BAQEFAANLADBIAkEAn7PD" + "hCeV/xIxUg8V70YRxK2A5jZbD92A12GN4PxyRQk0/lVmRUNMaJdq/qigpd9feP/u" + "12S4PwTLb/8q/v657QIDAQABMA0GCSqGSIb3DQEBBQUAA0EAbynCRIlUQgaqyNgU" + "DF6P14yRKUtX8akOP2TwStaSiVf/akYqfLFm3UGka5XbPj4rifrZ0/sOoZEEBvHQ" + "e20sRA=="; CertificateFactory certFact = CertificateFactory.getInstance("X.509", "BC"); X509Certificate x509 = (X509Certificate)certFact.generateCertificate(new ByteArrayInputStream(Base64.decode(cert))); try { x509.verify(x509.getPublicKey()); fail("forged RSA signature passed"); } catch (Exception e) { // expected } } private void pemTest() throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); Certificate cert = readPEMCert(cf, PEMData.CERTIFICATE_1); if (cert == null) { fail("PEM cert not read"); } cert = readPEMCert(cf, " if (cert == null) { fail("PEM cert with extraneous header not read"); } CRL crl = cf.generateCRL(new ByteArrayInputStream(PEMData.CRL_1.getBytes("US-ASCII"))); if (crl == null) { fail("PEM crl not read"); } Collection col = cf.generateCertificates(new ByteArrayInputStream(PEMData.CERTIFICATE_2.getBytes("US-ASCII"))); if (col.size() != 1 || !col.contains(cert)) { fail("PEM cert collection not right"); } col = cf.generateCRLs(new ByteArrayInputStream(PEMData.CRL_2.getBytes("US-ASCII"))); if (col.size() != 1 || !col.contains(crl)) { fail("PEM crl collection not right"); } } private static Certificate readPEMCert(CertificateFactory cf, String pemData) throws CertificateException, UnsupportedEncodingException { return cf.generateCertificate(new ByteArrayInputStream(pemData.getBytes("US-ASCII"))); } private void pkcs7Test() throws Exception { ASN1EncodableVector certs = new ASN1EncodableVector(); certs.add(new ASN1InputStream(CertPathTest.rootCertBin).readObject()); certs.add(new DERTaggedObject(false, 2, new ASN1InputStream(AttrCertTest.attrCert).readObject())); ASN1EncodableVector crls = new ASN1EncodableVector(); crls.add(new ASN1InputStream(CertPathTest.rootCrlBin).readObject()); SignedData sigData = new SignedData(new DERSet(), new ContentInfo(CMSObjectIdentifiers.data, null), new DERSet(certs), new DERSet(crls), new DERSet()); ContentInfo info = new ContentInfo(CMSObjectIdentifiers.signedData, sigData); CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); X509Certificate cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(info.getEncoded())); if (cert == null || !areEqual(cert.getEncoded(), certs.get(0).getDERObject().getEncoded())) { fail("PKCS7 cert not read"); } X509CRL crl = (X509CRL)cf.generateCRL(new ByteArrayInputStream(info.getEncoded())); if (crl == null || !areEqual(crl.getEncoded(), crls.get(0).getDERObject().getEncoded())) { fail("PKCS7 crl not read"); } Collection col = cf.generateCertificates(new ByteArrayInputStream(info.getEncoded())); if (col.size() != 1 || !col.contains(cert)) { fail("PKCS7 cert collection not right"); } col = cf.generateCRLs(new ByteArrayInputStream(info.getEncoded())); if (col.size() != 1 || !col.contains(crl)) { fail("PKCS7 crl collection not right"); } // data with no certificates or CRLs sigData = new SignedData(new DERSet(), new ContentInfo(CMSObjectIdentifiers.data, null), new DERSet(), new DERSet(), new DERSet()); info = new ContentInfo(CMSObjectIdentifiers.signedData, sigData); cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(info.getEncoded())); if (cert != null) { fail("PKCS7 cert present"); } crl = (X509CRL)cf.generateCRL(new ByteArrayInputStream(info.getEncoded())); if (crl != null) { fail("PKCS7 crl present"); } // data with absent certificates and CRLS sigData = new SignedData(new DERSet(), new ContentInfo(CMSObjectIdentifiers.data, null), null, null, new DERSet()); info = new ContentInfo(CMSObjectIdentifiers.signedData, sigData); cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(info.getEncoded())); if (cert != null) { fail("PKCS7 cert present"); } crl = (X509CRL)cf.generateCRL(new ByteArrayInputStream(info.getEncoded())); if (crl != null) { fail("PKCS7 crl present"); } // sample message InputStream in = new ByteArrayInputStream(pkcs7CrlProblem); Collection certCol = cf.generateCertificates(in); Collection crlCol = cf.generateCRLs(in); if (crlCol.size() != 0) { fail("wrong number of CRLs: " + crlCol.size()); } if (certCol.size() != 4) { fail("wrong number of Certs: " + certCol.size()); } } private void createPSSCert(String algorithm) throws Exception { RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16)); RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( new BigInteger("a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137",16), new BigInteger("010001",16), new BigInteger("33a5042a90b27d4f5451ca9bbbd0b44771a101af884340aef9885f2a4bbe92e894a724ac3c568c8f97853ad07c0266c8c6a3ca0929f1e8f11231884429fc4d9ae55fee896a10ce707c3ed7e734e44727a39574501a532683109c2abacaba283c31b4bd2f53c3ee37e352cee34f9e503bd80c0622ad79c6dcee883547c6a3b325",16), new BigInteger("e7e8942720a877517273a356053ea2a1bc0c94aa72d55c6e86296b2dfc967948c0a72cbccca7eacb35706e09a1df55a1535bd9b3cc34160b3b6dcd3eda8e6443",16), new BigInteger("b69dca1cf7d4d7ec81e75b90fcca874abcde123fd2700180aa90479b6e48de8d67ed24f9f19d85ba275874f542cd20dc723e6963364a1f9425452b269a6799fd",16), new BigInteger("28fa13938655be1f8a159cbaca5a72ea190c30089e19cd274a556f36c4f6e19f554b34c077790427bbdd8dd3ede2448328f385d81b30e8e43b2fffa027861979",16), new BigInteger("1a8b38f398fa712049898d7fb79ee0a77668791299cdfa09efc0e507acb21ed74301ef5bfd48be455eaeb6e1678255827580a8e4e8e14151d1510a82a3f2e729",16), new BigInteger("27156aba4126d24a81f3a528cbfb27f56886f840a9f6e86e17a44b94fe9319584b8e22fdde1e5a2e3bd8aa5ba8d8584194eb2190acf832b847f13a3d24a79f4d",16)); KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); PrivateKey privKey = fact.generatePrivate(privKeySpec); PublicKey pubKey = fact.generatePublic(pubKeySpec); // distinguished name table. Hashtable attrs = new Hashtable(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.ST, "Victoria"); attrs.put(X509Principal.E, "feedback-crypto@bouncycastle.org"); Vector ord = new Vector(); Vector values = new Vector(); ord.addElement(X509Principal.C); ord.addElement(X509Principal.O); ord.addElement(X509Principal.L); ord.addElement(X509Principal.ST); ord.addElement(X509Principal.E); values.addElement("AU"); values.addElement("The Legion of the Bouncy Castle"); values.addElement("Melbourne"); values.addElement("Victoria"); values.addElement("feedback-crypto@bouncycastle.org"); // create base certificate - version 3 X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(new X509Principal(attrs)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal(attrs)); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm(algorithm); certGen.addExtension("2.5.29.15", true, new X509KeyUsage(X509KeyUsage.encipherOnly)); certGen.addExtension("2.5.29.37", true, new DERSequence(KeyPurposeId.anyExtendedKeyUsage)); certGen.addExtension("2.5.29.17", true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); X509Certificate baseCert = certGen.generate(privKey, "BC"); baseCert.verify(pubKey); } public void performTest() throws Exception { checkCertificate(1, cert1); checkCertificate(2, cert2); checkCertificate(3, cert3); checkCertificate(4, cert4); checkCertificate(5, cert5); checkCertificate(6, oldEcdsa); checkCertificate(7, cert7); checkKeyUsage(8, keyUsage); checkSelfSignedCertificate(9, uncompressedPtEC); checkNameCertificate(10, nameCert); checkSelfSignedCertificate(11, probSelfSignedCert); checkSelfSignedCertificate(12, gostCA1); checkSelfSignedCertificate(13, gostCA2); checkSelfSignedCertificate(14, gost341094base); checkSelfSignedCertificate(15, gost34102001base); checkSelfSignedCertificate(16, gost341094A); checkSelfSignedCertificate(17, gost341094B); checkSelfSignedCertificate(17, gost34102001A); checkCRL(1, crl1); checkCreation1(); checkCreation2(); checkCreation3(); checkCreation4(); checkCreation5(); createECCert("SHA1withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA1); createECCert("SHA224withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA224); createECCert("SHA256withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA256); createECCert("SHA384withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA384); createECCert("SHA512withECDSA", X9ObjectIdentifiers.ecdsa_with_SHA512); createPSSCert("SHA1withRSAandMGF1"); createPSSCert("SHA224withRSAandMGF1"); createPSSCert("SHA256withRSAandMGF1"); createPSSCert("SHA384withRSAandMGF1"); checkCRLCreation1(); checkCRLCreation2(); checkCRLCreation3(); pemTest(); pkcs7Test(); testForgedSignature(); checkCertificate(18, emptyDNCert); } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); runTest(new CertTest()); } }
package hex.glm; import hex.ModelMetricsBinomialGLM; import hex.glm.GLMModel.GLMParameters; import hex.glm.GLMModel.GLMParameters.Family; import hex.glm.GLMModel.GLMParameters.Solver; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import water.TestUtil; import water.*; import water.exceptions.H2OModelBuilderIllegalArgumentException; import water.fvec.*; import java.util.HashMap; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class GLMBasicTestBinomial extends TestUtil { static Frame _prostateTrain; // prostate_cat_replaced static Frame _prostateTrainUpsampled; // prostate_cat_replaced static Frame _prostateTest; // prostate_cat_replaced static Frame _abcd; // tiny corner case dataset @Test public void testOffset() { GLMModel model = null; double [] offset_train = new double[] { -0.39771185,+1.20479170,-0.16374109,-0.97885903,-1.42996530,+0.83474893,+0.83474893,-0.74488827,+0.83474893,+0.86851236, +1.41589611,+1.41589611,-1.42996530,-0.39771185,-2.01111248,-0.39771185,-0.16374109,+0.62364452,-0.39771185,+0.60262749, -0.06143251,-1.42996530,-0.06143251,-0.06143251,+0.14967191,-0.06143251,-0.39771185,+0.14967191,+1.20479170,-0.39771185, -0.16374109,-0.06143251,-0.06143251,-1.42996530,-0.39771185,-0.39771185,-0.64257969,+1.65774729,-0.97885903,-0.39771185, -0.39771185,-0.39771185,-1.42996530,+1.41589611,-0.06143251,-0.06143251,-0.39771185,-0.06143251,-0.06143251,-0.39771185, -0.06143251,+0.14967191,-0.39771185,-1.42996530,-0.39771185,-0.64257969,-0.39771185,-0.06143251,-0.06143251,-0.06143251, -1.42996530,-2.01111248,-0.06143251,-0.39771185,-0.39771185,-1.42996530,-0.39771185,-1.42996530,-0.06143251,+1.41589611, +0.14967191,-1.42996530,-1.42996530,-0.06143251,-1.42996530,-1.42996530,-0.06143251,-1.42996530,-0.06143251,-0.39771185, -0.06143251,-1.42996530,-0.06143251,-0.39771185,-1.42996530,-0.06143251,-0.06143251,-0.06143251,-1.42996530,-0.39771185, -1.42996530,-0.43147527,-0.39771185,-0.39771185,-0.39771185,-1.42996530,-1.42996530,-0.43147527,-0.39771185,-0.39771185, -0.39771185,-0.39771185,-1.42996530,-1.42996530,-1.42996530,-0.39771185,+0.14967191,+1.41589611,-1.42996530,+1.41589611, -1.42996530,+1.41589611,-0.06143251,+0.14967191,-0.39771185,-0.97885903,-1.42996530,-0.39771185,-0.39771185,-0.39771185, -0.39771185,-1.42996530,-0.39771185,-0.97885903,-0.06143251,-0.06143251,+0.86851236,-0.39771185,-0.39771185,-0.06143251, -0.39771185,-0.39771185,-0.06143251,+0.14967191,-1.42996530,-1.42996530,-0.39771185,+1.20479170,-1.42996530,-0.39771185, -0.06143251,-1.42996530,-0.97885903,+0.14967191,+0.14967191,-1.42996530,-1.42996530,-0.39771185,-0.06143251,-0.43147527, -0.06143251,-0.39771185,-1.42996530,-0.06143251,-0.39771185,-0.39771185,-1.42996530,-0.39771185,-0.39771185,-0.06143251, -0.39771185,-0.39771185,+0.14967191,-0.06143251,+1.41589611,-0.06143251,-0.39771185,-0.39771185,-0.06143251,-1.42996530, -0.06143251,-1.42996530,-0.39771185,-0.64257969,-0.06143251,+1.20479170,-0.43147527,-0.97885903,-0.39771185,-0.39771185, -0.39771185,+0.14967191,-2.01111248,-1.42996530,-0.06143251,+0.83474893,-1.42996530,-1.42996530,-2.01111248,-1.42996530, -0.06143251,+0.86851236,+0.05524374,-0.39771185,-0.39771185,-0.39771185,+1.41589611,-1.42996530,-0.39771185,-1.42996530, -0.39771185,-0.39771185,-0.06143251,+0.14967191,-1.42996530,-0.39771185,-1.42996530,-1.42996530,-0.39771185,-0.39771185, -0.06143251,-1.42996530,-0.97885903,-1.42996530,-0.39771185,-0.06143251,-0.39771185,-0.06143251,-1.42996530,-1.42996530, -0.06143251,-1.42996530,-0.39771185,+0.14967191,-0.06143251,-1.42996530,-1.42996530,+0.14967191,-0.39771185,-0.39771185, -1.42996530,-0.06143251,-0.06143251,-1.42996530,-0.06143251,-1.42996530,+0.14967191,+1.20479170,-1.42996530,-0.06143251, -0.39771185,-0.39771185,-0.06143251,+0.14967191,-0.06143251,-1.42996530,-1.42996530,-1.42996530,-0.39771185,-0.39771185, -0.39771185,+0.86851236,-0.06143251,-0.97885903,-0.06143251,-0.64257969,+0.14967191,+0.86851236,-0.39771185,-0.39771185, -0.39771185,-0.64257969,-1.42996530,-0.06143251,-0.39771185,-0.39771185,-1.42996530,-1.42996530,-0.06143251,+0.14967191, -0.06143251,+0.86851236,-0.97885903,-1.42996530,-1.42996530,-1.42996530,-1.42996530,+0.86851236,+0.14967191,-1.42996530, -0.97885903,-1.42996530,-1.42996530,-0.06143251,+0.14967191,-1.42996530,-0.64257969,-2.01111248,-0.97885903,-0.39771185 }; double [] offset_test = new double [] { +1.20479170,-1.42996530,-1.42996530,-1.42996530,-0.39771185,-0.39771185,-0.39771185,-0.39771185,-0.06143251,-0.06143251, -0.06143251,-0.39771185,-0.39771185,-0.39771185,-0.06143251,-1.42996530,-0.39771185,+0.86851236,-0.06143251,+1.20479170, -1.42996530,+1.20479170,-0.06143251,-0.06143251,+1.20479170,+0.14967191,-0.39771185,-0.39771185,-0.39771185,+0.14967191, -0.39771185,-1.42996530,-0.97885903,-0.39771185,-2.01111248,-1.42996530,-0.39771185,-0.06143251,-0.39771185,+0.14967191, +0.14967191,-0.06143251,+0.14967191,-1.42996530,-0.06143251,+1.20479170,-0.06143251,-0.06143251,-0.39771185,+1.41589611, -0.39771185,-1.42996530,+0.14967191,-1.42996530,+0.14967191,-1.42996530,-0.06143251,-1.42996530,-0.43147527,+0.86851236, -0.39771185,-0.39771185,-0.06143251,-0.06143251,-0.39771185,-0.06143251,-1.42996530,-0.39771185,-0.06143251,-0.39771185, +0.14967191,+1.41589611,-0.39771185,-0.39771185,+1.41589611,+0.14967191,-0.64257969,-1.42996530,+0.14967191,-0.06143251, -1.42996530,-1.42996530,-0.39771185,-1.42996530,-1.42996530,-0.39771185,-0.39771185,+0.14967191,-0.39771185,-0.39771185 }; double [] pred_test = new double[] { +0.904121393,+0.208967788,+0.430064980,+0.063563661,+0.420390154,+0.300577441,+0.295405224,+0.629308103,+0.324441281,+0.563699642, +0.639184514,+0.082179963,+0.462563464,+0.344521206,+0.351577428,+0.339043527,+0.435998848,+0.977492380,+0.581711493,+0.974570868, +0.143071580,+0.619404446,+0.362033860,+0.570068411,+0.978069860,+0.562268311,+0.158184617,+0.608996256,+0.162259728,+0.578987913, +0.289325534,+0.286251414,+0.749507189,+0.469565216,+0.069466938,+0.112383575,+0.481307819,+0.398935638,+0.589102941,+0.337382932, +0.409333118,+0.366674225,+0.640036454,+0.263683222,+0.779866040,+0.635071654,+0.377463657,+0.518320766,+0.322693268,+0.833778660, +0.459703088,+0.115189180,+0.694175044,+0.132131043,+0.402412653,+0.270949939,+0.353738040,+0.256239963,+0.467322078,+0.956569336, +0.172230761,+0.265478787,+0.559113124,+0.248798085,+0.140841191,+0.607922656,+0.113752627,+0.289291072,+0.241123681,+0.290387448, +0.782068785,+0.927494110,+0.176397617,+0.263745527,+0.992043885,+0.653252457,+0.385483627,+0.222333476,+0.537344319,+0.202589973, +0.334941144,+0.172066050,+0.292733797,+0.001169431,+0.114393635,+0.153848294,+0.632500120,+0.387718306,+0.269126887,+0.564594040 }; Vec offsetVecTrain = _prostateTrain.anyVec().makeZero(); try( Vec.Writer vw = offsetVecTrain.open() ) { for (int i = 0; i < offset_train.length; ++i) vw.set(i, offset_train[i]); } Vec offsetVecTest = _prostateTest.anyVec().makeZero(); try( Vec.Writer vw = offsetVecTest.open() ) { for (int i = 0; i < offset_test.length; ++i) vw.set(i, offset_test[i]); } Key fKeyTrain = Key.make("prostate_with_offset_train"); Key fKeyTest = Key.make("prostate_with_offset_test"); Frame fTrain = new Frame(fKeyTrain, new String[]{"offset"}, new Vec[]{offsetVecTrain}); fTrain.add(_prostateTrain.names(), _prostateTrain.vecs()); DKV.put(fKeyTrain,fTrain); Frame fTest = new Frame(fKeyTest, new String[]{"offset"}, new Vec[]{offsetVecTest}); fTest.add(_prostateTest.names(),_prostateTest.vecs()); DKV.put(fKeyTest,fTest); // Call: glm(formula = CAPSULE ~ . - RACE - DPROS - DCAPS, family = binomial, // data = train, offset = offset_train) // Coefficients: // (Intercept) AGE PSA VOL GLEASON // -4.839677 -0.007815 0.023796 -0.007325 0.794385 // Degrees of Freedom: 289 Total (i.e. Null); 285 Residual // Null Deviance: 355.7 // Residual Deviance: 305.1 AIC: 315.1 String [] cfs1 = new String [] { "Intercept", "AGE" , "PSA", "VOL", "GLEASON"}; double [] vals = new double [] {-4.839677, -0.007815, 0.023796, -0.007325, 0.794385}; GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID","RACE","DPROS","DCAPS"}; params._train = fKeyTrain; params._valid = fKeyTest; params._offset_column = "offset"; params._lambda = new double[]{0}; params._alpha = new double[]{0}; params._standardize = false; params._objective_epsilon = 0; params._gradient_epsilon = 1e-6; params._max_iterations = 100; // not expected to reach max iterations here try { for (Solver s : new Solver[]{Solver.IRLSM}) { //{Solver.AUTO, Solver.IRLSM, Solver.L_BFGS, Solver.COORDINATE_DESCENT_NAIVE, Solver.COORDINATE_DESCENT}){ Frame scoreTrain = null, scoreTest = null; try { params._solver = s; System.out.println("SOLVER = " + s); model = new GLM(params).trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); System.out.println("coefs = " + coefs); boolean CD = (s == Solver.COORDINATE_DESCENT || s == Solver.COORDINATE_DESCENT_NAIVE); System.out.println(" solver " + s); System.out.println("validation = " + model._output._training_metrics); for (int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]), CD?5e-2:1e-4); assertEquals(355.7, GLMTest.nullDeviance(model), 1e-1); assertEquals(305.1, GLMTest.residualDeviance(model), 1e-1); assertEquals(289, GLMTest.nullDOF(model), 0); assertEquals(285, GLMTest.resDOF(model), 0); assertEquals(315.1, GLMTest.aic(model), 1e-1); assertEquals(76.8525, GLMTest.residualDevianceTest(model),CD?1e-3:1e-4); // test scoring try { scoreTrain = model.score(_prostateTrain); assertTrue("shoul've thrown IAE", false); } catch (IllegalArgumentException iae) { assertTrue(iae.getMessage().contains("Test/Validation dataset is missing offset vector")); } hex.ModelMetricsBinomialGLM mmTrain = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTrain); hex.AUC2 adata = mmTrain._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mmTrain._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._training_metrics)._resDev, mmTrain._resDev, 1e-8); scoreTrain = model.score(fTrain); mmTrain = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTrain); adata = mmTrain._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mmTrain._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._training_metrics)._resDev, mmTrain._resDev, 1e-8); scoreTest = model.score(fTest); ModelMetricsBinomialGLM mmTest = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTest); adata = mmTest._auc; assertEquals(model._output._validation_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._validation_metrics._MSE, mmTest._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._validation_metrics)._resDev, mmTest._resDev, 1e-8); // test the actual predictions Vec.Reader preds = scoreTest.vec("p1").new Reader(); for(int i = 0; i < pred_test.length; ++i) assertEquals(pred_test[i],preds.at(i),CD?1e-3:1e-6); } finally { if (model != null) model.delete(); if (scoreTrain != null) scoreTrain.delete(); if (scoreTest != null) scoreTest.delete(); } } } finally { if (fTrain != null) { fTrain.remove("offset").remove(); DKV.remove(fTrain._key); } if(fTest != null){ fTest.remove("offset").remove(); DKV.remove(fTest._key); } } } // test various problematic inputs to make sure fron-tend (ignoring/moving cols) works. @Test public void testCornerCases() { // new GLM2("GLM testing constant offset on a toy dataset.", Key.make(), modelKey, new GLM2.Source(fr, fr.vec("D"), false, false, fr.vec("E")), Family.gaussian).setRegularization(new double[]{0}, new double[]{0}).doInit().fork().get(); // just test it does not blow up and the model is sane // model = DKV.get(modelKey).get(); // assertEquals(model.coefficients().get("E"), 1, 0); // should be exactly 1 GLMParameters parms = new GLMParameters(Family.gaussian); parms._response_column = "D"; parms._offset_column = "E"; parms._train = _abcd._key; parms._intercept = false; parms._standardize = false; GLMModel m = null; try { m = new GLM(parms).trainModel().get(); System.out.println(m.coefficients()); } finally { if(m != null) m.delete(); } } @Test public void testNoInterceptWithOffset() { GLMModel model = null; double [] offset_train = new double[] { -0.39771185,+1.20479170,-0.16374109,-0.97885903,-1.42996530,+0.83474893,+0.83474893,-0.74488827,+0.83474893,+0.86851236, +1.41589611,+1.41589611,-1.42996530,-0.39771185,-2.01111248,-0.39771185,-0.16374109,+0.62364452,-0.39771185,+0.60262749, -0.06143251,-1.42996530,-0.06143251,-0.06143251,+0.14967191,-0.06143251,-0.39771185,+0.14967191,+1.20479170,-0.39771185, -0.16374109,-0.06143251,-0.06143251,-1.42996530,-0.39771185,-0.39771185,-0.64257969,+1.65774729,-0.97885903,-0.39771185, -0.39771185,-0.39771185,-1.42996530,+1.41589611,-0.06143251,-0.06143251,-0.39771185,-0.06143251,-0.06143251,-0.39771185, -0.06143251,+0.14967191,-0.39771185,-1.42996530,-0.39771185,-0.64257969,-0.39771185,-0.06143251,-0.06143251,-0.06143251, -1.42996530,-2.01111248,-0.06143251,-0.39771185,-0.39771185,-1.42996530,-0.39771185,-1.42996530,-0.06143251,+1.41589611, +0.14967191,-1.42996530,-1.42996530,-0.06143251,-1.42996530,-1.42996530,-0.06143251,-1.42996530,-0.06143251,-0.39771185, -0.06143251,-1.42996530,-0.06143251,-0.39771185,-1.42996530,-0.06143251,-0.06143251,-0.06143251,-1.42996530,-0.39771185, -1.42996530,-0.43147527,-0.39771185,-0.39771185,-0.39771185,-1.42996530,-1.42996530,-0.43147527,-0.39771185,-0.39771185, -0.39771185,-0.39771185,-1.42996530,-1.42996530,-1.42996530,-0.39771185,+0.14967191,+1.41589611,-1.42996530,+1.41589611, -1.42996530,+1.41589611,-0.06143251,+0.14967191,-0.39771185,-0.97885903,-1.42996530,-0.39771185,-0.39771185,-0.39771185, -0.39771185,-1.42996530,-0.39771185,-0.97885903,-0.06143251,-0.06143251,+0.86851236,-0.39771185,-0.39771185,-0.06143251, -0.39771185,-0.39771185,-0.06143251,+0.14967191,-1.42996530,-1.42996530,-0.39771185,+1.20479170,-1.42996530,-0.39771185, -0.06143251,-1.42996530,-0.97885903,+0.14967191,+0.14967191,-1.42996530,-1.42996530,-0.39771185,-0.06143251,-0.43147527, -0.06143251,-0.39771185,-1.42996530,-0.06143251,-0.39771185,-0.39771185,-1.42996530,-0.39771185,-0.39771185,-0.06143251, -0.39771185,-0.39771185,+0.14967191,-0.06143251,+1.41589611,-0.06143251,-0.39771185,-0.39771185,-0.06143251,-1.42996530, -0.06143251,-1.42996530,-0.39771185,-0.64257969,-0.06143251,+1.20479170,-0.43147527,-0.97885903,-0.39771185,-0.39771185, -0.39771185,+0.14967191,-2.01111248,-1.42996530,-0.06143251,+0.83474893,-1.42996530,-1.42996530,-2.01111248,-1.42996530, -0.06143251,+0.86851236,+0.05524374,-0.39771185,-0.39771185,-0.39771185,+1.41589611,-1.42996530,-0.39771185,-1.42996530, -0.39771185,-0.39771185,-0.06143251,+0.14967191,-1.42996530,-0.39771185,-1.42996530,-1.42996530,-0.39771185,-0.39771185, -0.06143251,-1.42996530,-0.97885903,-1.42996530,-0.39771185,-0.06143251,-0.39771185,-0.06143251,-1.42996530,-1.42996530, -0.06143251,-1.42996530,-0.39771185,+0.14967191,-0.06143251,-1.42996530,-1.42996530,+0.14967191,-0.39771185,-0.39771185, -1.42996530,-0.06143251,-0.06143251,-1.42996530,-0.06143251,-1.42996530,+0.14967191,+1.20479170,-1.42996530,-0.06143251, -0.39771185,-0.39771185,-0.06143251,+0.14967191,-0.06143251,-1.42996530,-1.42996530,-1.42996530,-0.39771185,-0.39771185, -0.39771185,+0.86851236,-0.06143251,-0.97885903,-0.06143251,-0.64257969,+0.14967191,+0.86851236,-0.39771185,-0.39771185, -0.39771185,-0.64257969,-1.42996530,-0.06143251,-0.39771185,-0.39771185,-1.42996530,-1.42996530,-0.06143251,+0.14967191, -0.06143251,+0.86851236,-0.97885903,-1.42996530,-1.42996530,-1.42996530,-1.42996530,+0.86851236,+0.14967191,-1.42996530, -0.97885903,-1.42996530,-1.42996530,-0.06143251,+0.14967191,-1.42996530,-0.64257969,-2.01111248,-0.97885903,-0.39771185 }; double [] offset_test = new double [] { +1.65774729,-0.97700971,-0.97700971,-0.97700971,+0.05524374,+0.05524374,+0.05524374,+0.05524374,+0.39152308,+0.39152308, +0.39152308,+0.05524374,+0.05524374,+0.05524374,+0.39152308,-0.97700971,+0.05524374,+1.32146795,+0.39152308,+1.65774729, -0.97700971,+1.65774729,+0.39152308,+0.39152308,+1.65774729,+0.60262749,+0.05524374,+0.05524374,+0.05524374,+0.60262749, +0.05524374,-0.97700971,-0.97885903,+0.05524374,-2.01111248,-0.97700971,+0.05524374,+0.39152308,+0.05524374,+0.60262749, +0.60262749,+0.39152308,+0.60262749,-0.97700971,+0.39152308,+1.65774729,+0.39152308,+0.39152308,+0.05524374,+1.86885170, +0.05524374,-0.97700971,+0.60262749,-0.97700971,+0.60262749,-0.97700971,+0.39152308,-0.97700971,-0.43147527,+1.32146795, +0.05524374,+0.05524374,+0.39152308,+0.39152308,+0.05524374,+0.39152308,-0.97700971,+0.05524374,+0.39152308,+0.05524374, +0.60262749,+1.86885170,+0.05524374,+0.05524374,+1.86885170,+0.60262749,-0.64257969,-0.97700971,+0.60262749,+0.39152308, -0.97700971,-0.97700971,+0.05524374,-0.97700971,-0.97700971,+0.05524374,+0.05524374,+0.60262749,+0.05524374,+0.05524374 }; double [] pred_test = new double[] { +0.88475366,+0.23100271,+0.40966315,+0.08957188,+0.47333302,+0.44622513,+0.56450046,+0.74271010,+0.45129280,+0.72359111, +0.67918401,+0.19882802,+0.42330391,+0.62734862,+0.38055506,+0.47286476,+0.40180469,+0.97907526,+0.61428344,+0.97109299, +0.30489181,+0.81303545,+0.36130639,+0.65434899,+0.98863675,+0.58301866,+0.37950467,+0.53679205,+0.30636941,+0.70320372, +0.45303278,+0.35011042,+0.78165074,+0.44915160,+0.09008065,+0.16789833,+0.45748862,+0.59328118,+0.75002334,+0.35170410, +0.57550279,+0.42038237,+0.76349569,+0.28883753,+0.84824847,+0.72396381,+0.56782477,+0.54078190,+0.51169047,+0.80828547, +0.52001699,+0.26202346,+0.81014557,+0.29986016,+0.62011569,+0.33034872,+0.62284802,+0.28303618,+0.38470707,+0.96444405, +0.36155179,+0.46368503,+0.65192144,+0.43597041,+0.30906461,+0.69259415,+0.21819579,+0.49998652,+0.57162728,+0.44255738, +0.80820564,+0.90616782,+0.49377901,+0.34235025,+0.99621673,+0.65768252,+0.43909050,+0.23205826,+0.71124897,+0.42908417, +0.47880901,+0.29185818,+0.42648317,+0.01247279,+0.18372518,+0.27281535,+0.63807876,+0.44563524,+0.32821696,+0.43636099 }; Vec offsetVecTrain = _prostateTrain.anyVec().makeZero(); try( Vec.Writer vw = offsetVecTrain.open() ) { for (int i = 0; i < offset_train.length; ++i) vw.set(i, offset_train[i]); } Vec offsetVecTest = _prostateTest.anyVec().makeZero(); try( Vec.Writer vw = offsetVecTest.open() ) { for (int i = 0; i < offset_test.length; ++i) vw.set(i, offset_test[i]); } Key fKeyTrain = Key.make("prostate_with_offset_train"); Key fKeyTest = Key.make("prostate_with_offset_test"); Frame fTrain = new Frame(fKeyTrain, new String[]{"offset"}, new Vec[]{offsetVecTrain}); fTrain.add(_prostateTrain.names(), _prostateTrain.vecs()); DKV.put(fKeyTrain,fTrain); Frame fTest = new Frame(fKeyTest, new String[]{"offset"}, new Vec[]{offsetVecTest}); fTest.add(_prostateTest.names(),_prostateTest.vecs()); DKV.put(fKeyTest,fTest); // Call: glm(formula = CAPSULE ~ . - ID - RACE - DCAPS - DPROS - 1, family = binomial, // data = train, offset = offset_train) // Coefficients: // AGE PSA VOL GLEASON // -0.054102 0.027517 -0.008937 0.516363 // Degrees of Freedom: 290 Total (i.e. Null); 286 Residual // Null Deviance: 355.7 // Residual Deviance: 313 AIC: 321 String [] cfs1 = new String [] { "Intercept", "AGE" , "PSA", "VOL", "GLEASON"}; double [] vals = new double [] { 0, -0.054102, 0.027517, -0.008937, 0.516363}; GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID","RACE","DPROS","DCAPS"}; params._train = fKeyTrain; params._valid = fKeyTest; params._offset_column = "offset"; params._lambda = new double[]{0}; params._alpha = new double[]{0}; params._standardize = false; params._objective_epsilon = 0; params._gradient_epsilon = 1e-6; params._max_iterations = 100; // not expected to reach max iterations here params._intercept = false; params._beta_epsilon = 1e-6; try { for (Solver s : new Solver[]{Solver.AUTO, Solver.IRLSM, Solver.L_BFGS /* , Solver.COORDINATE_DESCENT_NAIVE, Solver.COORDINATE_DESCENT*/}) { Frame scoreTrain = null, scoreTest = null; try { params._solver = s; System.out.println("SOLVER = " + s); model = new GLM(params).trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); System.out.println("coefs = " + coefs); for (int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]), 1e-4); assertEquals(355.7, GLMTest.nullDeviance(model), 1e-1); assertEquals(313.0, GLMTest.residualDeviance(model), 1e-1); assertEquals(290, GLMTest.nullDOF(model), 0); assertEquals(286, GLMTest.resDOF(model), 0); assertEquals(321, GLMTest.aic(model), 1e-1); boolean CD = (s == Solver.COORDINATE_DESCENT || s == Solver.COORDINATE_DESCENT_NAIVE); assertEquals(88.72363, GLMTest.residualDevianceTest(model),CD?1e-2:1e-4); // test scoring try { scoreTrain = model.score(_prostateTrain); assertTrue("shoul've thrown IAE", false); } catch (IllegalArgumentException iae) { assertTrue(iae.getMessage().contains("Test/Validation dataset is missing offset vector")); } hex.ModelMetricsBinomialGLM mmTrain = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTrain); hex.AUC2 adata = mmTrain._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mmTrain._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._training_metrics)._resDev, mmTrain._resDev, 1e-8); scoreTrain = model.score(fTrain); mmTrain = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTrain); adata = mmTrain._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mmTrain._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._training_metrics)._resDev, mmTrain._resDev, 1e-8); scoreTest = model.score(fTest); ModelMetricsBinomialGLM mmTest = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTest); adata = mmTest._auc; assertEquals(model._output._validation_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._validation_metrics._MSE, mmTest._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._validation_metrics)._resDev, mmTest._resDev, 1e-8); // test the actual predictions Vec.Reader preds = scoreTest.vec("p1").new Reader(); for(int i = 0; i < pred_test.length; ++i) assertEquals(pred_test[i],preds.at(i), CD?1e-4:1e-6);// s == Solver.COORDINATE_DESCENT_NAIVE } finally { if (model != null) model.delete(); if (scoreTrain != null) scoreTrain.delete(); if (scoreTest != null) scoreTest.delete(); } } } finally { if (fTrain != null) { fTrain.remove("offset").remove(); DKV.remove(fTrain._key); } if(fTest != null) { fTest.remove("offset").remove(); DKV.remove(fTest._key); } } } @Test public void testNoIntercept() { GLMModel model = null; // Call: glm(formula = CAPSULE ~ . - 1 - RACE - DCAPS, family = binomial, // data = train) // Coefficients: // AGE DPROSa DPROSb DPROSc DPROSd PSA VOL GLEASON // -0.00743 -6.46499 -5.60120 -5.18213 -5.70027 0.02753 -0.01235 0.86122 // Degrees of Freedom: 290 Total (i.e. Null); 282 Residual // Null Deviance: 402 // Residual Deviance: 302.9 AIC: 318.9 String [] cfs1 = new String [] {"AGE", "DPROS.a", "DPROS.b", "DPROS.c", "DPROS.d", "PSA", "VOL", "GLEASON"}; double [] vals = new double [] {-0.00743, -6.46499, -5.60120, -5.18213, -5.70027, 0.02753, -0.01235, 0.86122}; GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID","RACE","DCAPS"}; params._train = _prostateTrain._key; params._valid = _prostateTest._key; params._lambda = new double[]{0}; params._alpha = new double[]{0}; params._standardize = false; params._intercept = false; params._objective_epsilon = 0; params._gradient_epsilon = 1e-6; params._max_iterations = 100; // not expected to reach max iterations here for(Solver s:new Solver[]{Solver.AUTO,Solver.IRLSM,Solver.L_BFGS /*, Solver.COORDINATE_DESCENT_NAIVE, Solver.COORDINATE_DESCENT*/}) { Frame scoreTrain = null, scoreTest = null; try { params._solver = s; System.out.println("SOLVER = " + s); model = new GLM( params).trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); System.out.println("coefs = " + coefs.toString()); System.out.println("metrics = " + model._output._training_metrics); boolean CD = (s == Solver.COORDINATE_DESCENT || s == Solver.COORDINATE_DESCENT_NAIVE); for (int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]), CD? 1e-1:1e-4); assertEquals(402, GLMTest.nullDeviance(model), 1e-1); assertEquals(302.9, GLMTest.residualDeviance(model), 1e-1); assertEquals(290, GLMTest.nullDOF(model), 0); assertEquals(282, GLMTest.resDOF(model), 0); assertEquals(318.9, GLMTest.aic(model), 1e-1); System.out.println("VAL METRICS: " + model._output._validation_metrics); // compare validation res dev matches R // sum(binomial()$dev.resids(y=test$CAPSULE,mu=p,wt=1)) // [1]80.92923 assertTrue(80.92923 >= GLMTest.residualDevianceTest(model) - 1e-2); // compare validation null dev against R // sum(binomial()$dev.resids(y=test$CAPSULE,mu=.5,wt=1)) // [1] 124.7665 assertEquals(124.7665, GLMTest.nullDevianceTest(model),1e-4); model.delete(); // test scoring scoreTrain = model.score(_prostateTrain); hex.ModelMetricsBinomial mm = hex.ModelMetricsBinomial.getFromDKV(model, _prostateTrain); hex.AUC2 adata = mm._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mm._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM) mm)._resDev, 1e-8); scoreTest = model.score(_prostateTest); mm = hex.ModelMetricsBinomial.getFromDKV(model, _prostateTest); adata = mm._auc; assertEquals(model._output._validation_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._validation_metrics._MSE, mm._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._validation_metrics)._resDev, ((ModelMetricsBinomialGLM) mm)._resDev, 1e-8); } finally { if (model != null) model.delete(); if (scoreTrain != null) scoreTrain.delete(); if(scoreTest != null) scoreTest.delete(); } } } @Test public void testWeights() { System.out.println("got " + _prostateTrain.anyVec().nChunks() + " chunks"); GLMModel model = null, modelUpsampled = null; // random observation weights, integers in 0 - 9 range double [] weights = new double[] { 0, 6, 5, 4, 4, 8, 2, 4, 9, 5, 2, 0, 0, 4, 0, 0, 6, 3, 6, 5, 5, 5, 6, 0, 9, 9, 8, 6, 6, 5, 6, 1, 0, 6, 8, 6, 9, 2, 8, 0, 3, 0, 2, 3, 0, 2, 5, 0, 0, 3, 7, 4, 8, 4, 1, 9, 3, 7, 1, 3, 8, 6, 9, 5, 5, 1, 9, 5, 2, 1, 0, 6, 4, 0, 5, 3, 1, 2, 4, 0, 7, 9, 6, 8, 0, 2, 3, 7, 5, 8, 3, 4, 7, 8, 1, 2, 5, 7, 3, 7, 1, 1, 5, 7, 4, 9, 2, 6, 3, 5, 4, 9, 8, 1, 8, 5, 3, 0, 4, 5, 1, 2, 2, 7, 8, 3, 4, 9, 0, 1, 3, 9, 8, 7, 0, 8, 2, 7, 1, 9, 0, 7, 7, 5, 2, 9, 7, 6, 4, 3, 4, 6, 9, 1, 5, 0, 7, 9, 4, 1, 6, 8, 8, 5, 4, 2, 5, 9, 8, 1, 9, 2, 9, 2, 3, 0, 6, 7, 3, 2, 3, 0, 9, 5, 1, 8, 0, 2, 8, 6, 9, 5, 1, 2, 3, 1, 3, 5, 0, 7, 4, 0, 5, 5, 7, 9, 3, 0, 0, 0, 1, 5, 3, 2, 8, 9, 9, 1, 6, 2, 2, 0, 5, 5, 6, 2, 8, 8, 9, 8, 5, 0, 1, 5, 3, 0, 2, 5, 4, 0, 6, 5, 4, 5, 9, 7, 5, 6, 2, 2, 6, 2, 5, 1, 5, 9, 0, 3, 0, 2, 7, 0, 4, 7, 7, 9, 3, 7, 9, 7, 9, 6, 2, 6, 2, 2, 9, 0, 9, 8, 1, 2, 6, 3, 4, 1, 2, 2, 3, 0 }; //double [] weights = new double[290]; //Arrays.fill(weights, 1); Vec offsetVecTrain = _prostateTrain.anyVec().makeZero(); try( Vec.Writer vw = offsetVecTrain.open() ) { for (int i = 0; i < weights.length; ++i) vw.set(i, weights[i]); } // Vec offsetVecTest = _prostateTest.anyVec().makeZero(); // vw = offsetVecTest.open(); // for(int i = 0; i < weights.length; ++i) // vw.set(i,weights[i]); // vw.close(); Key fKeyTrain = Key.make("prostate_with_weights_train"); // Key fKeyTest = Key.make("prostate_with_offset_test"); Frame fTrain = new Frame(fKeyTrain, new String[]{"weights"}, new Vec[]{offsetVecTrain}); fTrain.add(_prostateTrain.names(), _prostateTrain.vecs()); DKV.put(fKeyTrain,fTrain); // Frame fTest = new Frame(fKeyTest, new String[]{"offset"}, new Vec[]{offsetVecTest}); // fTest.add(_prostateTest.names(),_prostateTest.vecs()); // DKV.put(fKeyTest,fTest); // Call: glm(formula = CAPSULE ~ . - ID, family = binomial, data = train, // weights = w) // Coefficients: // (Intercept) AGE RACER2 RACER3 DPROSb DPROSc // -6.019527 -0.027350 -0.424333 -0.869188 1.359856 1.745655 // DPROSd DCAPSb PSA VOL GLEASON // 1.517155 0.664479 0.034541 -0.005819 0.947644 // Degrees of Freedom: 251 Total (i.e. Null); 241 Residual // Null Deviance: 1673 // Residual Deviance: 1195 AIC: 1217 String [] cfs1 = new String [] { "Intercept", "AGE", "RACE.R2", "RACE.R3", "DPROS.b", "DPROS.c", "DPROS.d", "DCAPS.b", "PSA", "VOL", "GLEASON"}; double [] vals = new double [] { -6.019527, -0.027350, -0.424333, -0.869188, 1.359856, 1.745655, 1.517155, 0.664479, 0.034541, -0.005819, 0.947644}; GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID"}; params._train = fKeyTrain; // params._valid = fKeyTest; params._weights_column = "weights"; params._lambda = new double[]{0}; params._alpha = new double[]{0}; //params._standardize = false; params._objective_epsilon = 0; params._gradient_epsilon = 1e-6; params._beta_epsilon = 1e-6; params._max_iterations = 1000; // not expected to reach max iterations here try { for (Solver s : new Solver[]{Solver.AUTO, Solver.IRLSM, Solver.L_BFGS /*, Solver.COORDINATE_DESCENT_NAIVE, Solver.COORDINATE_DESCENT*/}) { Frame scoreTrain = null, scoreTest = null; try { params._solver = s; params._train = fKeyTrain; params._weights_column = "weights"; params._gradient_epsilon = 1e-8; params._objective_epsilon = 0; System.out.println("SOLVER = " + s); model = new GLM(params).trainModel().get(); params._train = _prostateTrainUpsampled._key; params._weights_column = null; modelUpsampled = new GLM(params).trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); HashMap<String, Double> coefsUpsampled = modelUpsampled.coefficients(); System.out.println("coefs = " + coefs); System.out.println("coefs upsampled = " + coefsUpsampled); System.out.println(model._output._training_metrics); System.out.println(modelUpsampled._output._training_metrics); boolean CD = (s == Solver.COORDINATE_DESCENT || s == Solver.COORDINATE_DESCENT_NAIVE); for (int i = 0; i < cfs1.length; ++i) { System.out.println("cfs = " + cfs1[i]); assertEquals(coefsUpsampled.get(cfs1[i]), coefs.get(cfs1[i]), s == Solver.IRLSM?1e-8:1e-4); assertEquals(vals[i], coefs.get(cfs1[i]), CD?1e-3:1e-4);//dec } assertEquals(GLMTest.auc(modelUpsampled),GLMTest.auc(model),1e-4); assertEquals(GLMTest.logloss(modelUpsampled),GLMTest.logloss(model),1e-4); assertEquals(GLMTest.mse(modelUpsampled),GLMTest.mse(model),1e-4); assertEquals(1673, GLMTest.nullDeviance(model),1); assertEquals(1195, GLMTest.residualDeviance(model),1); assertEquals(251, GLMTest.nullDOF(model), 0); assertEquals(241, GLMTest.resDOF(model), 0); assertEquals(1217, GLMTest.aic(model), 1); // mse computed in R on upsampled data assertEquals(0.1604573,model._output._training_metrics._MSE,1e-5); // auc computed in R on explicitly upsampled data assertEquals(0.8348088,GLMTest.auc(model),1e-4); // assertEquals(76.8525, GLMTest.residualDevianceTest(model),1e-4); // test scoring // try { // NO LONGER check that we get IAE if computing metrics on data with no weights (but trained with weights) scoreTrain = model.score(_prostateTrain); scoreTrain.delete(); // assertTrue("shoul've thrown IAE", false); //TN-1 now autofills with weights 1 // assertTrue(iae.getMessage().contains("Test/Validation dataset is missing weights vector")); Frame f = new Frame(_prostateTrain); f.remove("CAPSULE"); // test we can generate predictions with no weights (no metrics) scoreTrain = model.score(f); scoreTrain.delete(); hex.ModelMetricsBinomialGLM mmTrain = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTrain); hex.AUC2 adata = mmTrain._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mmTrain._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._training_metrics)._resDev, mmTrain._resDev, 1e-8); scoreTrain = model.score(fTrain); mmTrain = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTrain); adata = mmTrain._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mmTrain._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._training_metrics)._resDev, mmTrain._resDev, 1e-8); // test we got auc // scoreTest = model.score(fTest); // ModelMetricsBinomialGLM mmTest = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTest); // adata = mmTest._auc; // assertEquals(model._output._validation_metrics.auc()._auc, adata._auc, 1e-8); // assertEquals(model._output._validation_metrics._MSE, mmTest._MSE, 1e-8); // assertEquals(((ModelMetricsBinomialGLM) model._output._validation_metrics)._resDev, mmTest._resDev, 1e-8); // // test the actual predictions // Vec preds = scoreTest.vec("p1"); // for(int i = 0; i < pred_test.length; ++i) // assertEquals(pred_test[i],preds.at(i),1e-6); } finally { if (model != null) model.delete(); if (modelUpsampled != null) modelUpsampled.delete(); if (scoreTrain != null) scoreTrain.delete(); if (scoreTest != null) scoreTest.delete(); } } } finally { if (fTrain != null) { fTrain.remove("weights").remove(); DKV.remove(fTrain._key); } // if(fTest != null)fTest.delete(); } } @Test public void testNonNegative() { GLMModel model = null; // glmnet result // (Intercept) AGE RACER1 RACER2 RACER3 DPROSb // -7.85142421 0.00000000 0.76094020 0.87641840 0.00000000 0.93030614 // DPROSc DPROSd DCAPSb PSA VOL GLEASON // 1.31814009 0.82918839 0.63285077 0.02949062 0.00000000 0.83011321 String [] cfs1 = new String [] {"Intercept", "AGE", "DPROS.b", "DPROS.c", "DPROS.d", "DCAPS.b", "PSA", "VOL", "GLEASON"}; double [] vals = new double [] {-7.85142421, 0.0, 0.93030614, 1.31814009, 0.82918839, 0.63285077, 0.02949062, 0.0, 0.83011321}; GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID",}; params._train = _prostateTrain._key; params._lambda = new double[]{0}; params._alpha = new double[]{0}; params._standardize = false; params._non_negative = true; params._intercept = true; params._objective_epsilon = 1e-10; params._gradient_epsilon = 1e-6; params._max_iterations = 10000; // not expected to reach max iterations here for(Solver s:new Solver[]{Solver.AUTO,Solver.IRLSM,Solver.L_BFGS}) { Frame scoreTrain = null, scoreTest = null; try { params._solver = s; System.out.println("SOLVER = " + s); model = new GLM(params).trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); System.out.println("coefs = " + coefs.toString()); System.out.println("metrics = " + model._output._training_metrics); // for (int i = 0; i < cfs1.length; ++i) // assertEquals(vals[i], coefs.get(cfs1[i]), Math.abs(5e-1 * vals[i])); assertEquals(390.3468, GLMTest.nullDeviance(model), 1e-4); assertEquals(300.7231, GLMTest.residualDeviance(model), 3); System.out.println("VAL METRICS: " + model._output._validation_metrics); model.delete(); // test scoring scoreTrain = model.score(_prostateTrain); hex.ModelMetricsBinomial mm = hex.ModelMetricsBinomial.getFromDKV(model, _prostateTrain); hex.AUC2 adata = mm._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mm._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM) mm)._resDev, 1e-8); } finally { if (model != null) model.delete(); if (scoreTrain != null) scoreTrain.delete(); if(scoreTest != null) scoreTest.delete(); } } } @Test public void testNonNegativeNoIntercept() { Scope.enter(); GLMModel model = null; // glmnet result // (Intercept) AGE RACER1 RACER2 RACER3 DPROSb // 0.000000000 0.000000000 0.240953925 0.000000000 0.000000000 0.000000000 // DPROSc DPROSd DCAPSb PSA VOL GLEASON // 0.000000000 0.000000000 0.680406869 0.007137494 0.000000000 0.000000000 String [] cfs1 = new String [] {"Intercept", "AGE", "DPROS.b", "DPROS.c", "DPROS.d", "DCAPS.b", "PSA", "VOL", "GLEASON", "RACE.R1"}; double [] vals = new double [] { 0.0, 0.0, 0.0, 0, 0.0, 0.680406869, 0.007137494, 0.0, 0.0, 0.240953925}; GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID",}; params._train = _prostateTrain._key; params._lambda = new double[]{0}; params._alpha = new double[]{0}; params._standardize = false; params._non_negative = true; params._intercept = false; params._objective_epsilon = 1e-6; params._gradient_epsilon = 1e-5; params._max_iterations = 150; // not expected to reach max iterations here for(Solver s:new Solver[]{Solver.AUTO,Solver.IRLSM,Solver.L_BFGS}) { Frame scoreTrain = null, scoreTest = null; try { params._solver = s; params._max_iterations = 500; System.out.println("SOLVER = " + s); model = new GLM(params).trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); System.out.println("coefs = " + coefs.toString()); System.out.println("metrics = " + model._output._training_metrics); double relTol = s == Solver.IRLSM?1e-1:1; for (int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]), relTol * (vals[i] + 1e-1)); assertEquals(402.0254, GLMTest.nullDeviance(model), 1e-1); assertEquals(394.3998, GLMTest.residualDeviance(model), s == Solver.L_BFGS?50:1); System.out.println("VAL METRICS: " + model._output._validation_metrics); model.delete(); // test scoring scoreTrain = model.score(_prostateTrain); hex.ModelMetricsBinomial mm = hex.ModelMetricsBinomial.getFromDKV(model, _prostateTrain); hex.AUC2 adata = mm._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mm._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._training_metrics)._resDev, ((ModelMetricsBinomialGLM) mm)._resDev, 1e-8); } finally { if (model != null) model.delete(); if (scoreTrain != null) scoreTrain.delete(); if(scoreTest != null) scoreTest.delete(); } } Scope.exit(); } @Test public void testNoInterceptWithOffsetAndWeights() { Scope.enter(); GLMModel model = null; double [] offset_train = new double[] { -0.39771185,+1.20479170,-0.16374109,-0.97885903,-1.42996530,+0.83474893,+0.83474893,-0.74488827,+0.83474893,+0.86851236, +1.41589611,+1.41589611,-1.42996530,-0.39771185,-2.01111248,-0.39771185,-0.16374109,+0.62364452,-0.39771185,+0.60262749, -0.06143251,-1.42996530,-0.06143251,-0.06143251,+0.14967191,-0.06143251,-0.39771185,+0.14967191,+1.20479170,-0.39771185, -0.16374109,-0.06143251,-0.06143251,-1.42996530,-0.39771185,-0.39771185,-0.64257969,+1.65774729,-0.97885903,-0.39771185, -0.39771185,-0.39771185,-1.42996530,+1.41589611,-0.06143251,-0.06143251,-0.39771185,-0.06143251,-0.06143251,-0.39771185, -0.06143251,+0.14967191,-0.39771185,-1.42996530,-0.39771185,-0.64257969,-0.39771185,-0.06143251,-0.06143251,-0.06143251, -1.42996530,-2.01111248,-0.06143251,-0.39771185,-0.39771185,-1.42996530,-0.39771185,-1.42996530,-0.06143251,+1.41589611, +0.14967191,-1.42996530,-1.42996530,-0.06143251,-1.42996530,-1.42996530,-0.06143251,-1.42996530,-0.06143251,-0.39771185, -0.06143251,-1.42996530,-0.06143251,-0.39771185,-1.42996530,-0.06143251,-0.06143251,-0.06143251,-1.42996530,-0.39771185, -1.42996530,-0.43147527,-0.39771185,-0.39771185,-0.39771185,-1.42996530,-1.42996530,-0.43147527,-0.39771185,-0.39771185, -0.39771185,-0.39771185,-1.42996530,-1.42996530,-1.42996530,-0.39771185,+0.14967191,+1.41589611,-1.42996530,+1.41589611, -1.42996530,+1.41589611,-0.06143251,+0.14967191,-0.39771185,-0.97885903,-1.42996530,-0.39771185,-0.39771185,-0.39771185, -0.39771185,-1.42996530,-0.39771185,-0.97885903,-0.06143251,-0.06143251,+0.86851236,-0.39771185,-0.39771185,-0.06143251, -0.39771185,-0.39771185,-0.06143251,+0.14967191,-1.42996530,-1.42996530,-0.39771185,+1.20479170,-1.42996530,-0.39771185, -0.06143251,-1.42996530,-0.97885903,+0.14967191,+0.14967191,-1.42996530,-1.42996530,-0.39771185,-0.06143251,-0.43147527, -0.06143251,-0.39771185,-1.42996530,-0.06143251,-0.39771185,-0.39771185,-1.42996530,-0.39771185,-0.39771185,-0.06143251, -0.39771185,-0.39771185,+0.14967191,-0.06143251,+1.41589611,-0.06143251,-0.39771185,-0.39771185,-0.06143251,-1.42996530, -0.06143251,-1.42996530,-0.39771185,-0.64257969,-0.06143251,+1.20479170,-0.43147527,-0.97885903,-0.39771185,-0.39771185, -0.39771185,+0.14967191,-2.01111248,-1.42996530,-0.06143251,+0.83474893,-1.42996530,-1.42996530,-2.01111248,-1.42996530, -0.06143251,+0.86851236,+0.05524374,-0.39771185,-0.39771185,-0.39771185,+1.41589611,-1.42996530,-0.39771185,-1.42996530, -0.39771185,-0.39771185,-0.06143251,+0.14967191,-1.42996530,-0.39771185,-1.42996530,-1.42996530,-0.39771185,-0.39771185, -0.06143251,-1.42996530,-0.97885903,-1.42996530,-0.39771185,-0.06143251,-0.39771185,-0.06143251,-1.42996530,-1.42996530, -0.06143251,-1.42996530,-0.39771185,+0.14967191,-0.06143251,-1.42996530,-1.42996530,+0.14967191,-0.39771185,-0.39771185, -1.42996530,-0.06143251,-0.06143251,-1.42996530,-0.06143251,-1.42996530,+0.14967191,+1.20479170,-1.42996530,-0.06143251, -0.39771185,-0.39771185,-0.06143251,+0.14967191,-0.06143251,-1.42996530,-1.42996530,-1.42996530,-0.39771185,-0.39771185, -0.39771185,+0.86851236,-0.06143251,-0.97885903,-0.06143251,-0.64257969,+0.14967191,+0.86851236,-0.39771185,-0.39771185, -0.39771185,-0.64257969,-1.42996530,-0.06143251,-0.39771185,-0.39771185,-1.42996530,-1.42996530,-0.06143251,+0.14967191, -0.06143251,+0.86851236,-0.97885903,-1.42996530,-1.42996530,-1.42996530,-1.42996530,+0.86851236,+0.14967191,-1.42996530, -0.97885903,-1.42996530,-1.42996530,-0.06143251,+0.14967191,-1.42996530,-0.64257969,-2.01111248,-0.97885903,-0.39771185 }; double [] offset_test = new double [] { +1.65774729,-0.97700971,-0.97700971,-0.97700971,+0.05524374,+0.05524374,+0.05524374,+0.05524374,+0.39152308,+0.39152308, +0.39152308,+0.05524374,+0.05524374,+0.05524374,+0.39152308,-0.97700971,+0.05524374,+1.32146795,+0.39152308,+1.65774729, -0.97700971,+1.65774729,+0.39152308,+0.39152308,+1.65774729,+0.60262749,+0.05524374,+0.05524374,+0.05524374,+0.60262749, +0.05524374,-0.97700971,-0.97885903,+0.05524374,-2.01111248,-0.97700971,+0.05524374,+0.39152308,+0.05524374,+0.60262749, +0.60262749,+0.39152308,+0.60262749,-0.97700971,+0.39152308,+1.65774729,+0.39152308,+0.39152308,+0.05524374,+1.86885170, +0.05524374,-0.97700971,+0.60262749,-0.97700971,+0.60262749,-0.97700971,+0.39152308,-0.97700971,-0.43147527,+1.32146795, +0.05524374,+0.05524374,+0.39152308,+0.39152308,+0.05524374,+0.39152308,-0.97700971,+0.05524374,+0.39152308,+0.05524374, +0.60262749,+1.86885170,+0.05524374,+0.05524374,+1.86885170,+0.60262749,-0.64257969,-0.97700971,+0.60262749,+0.39152308, -0.97700971,-0.97700971,+0.05524374,-0.97700971,-0.97700971,+0.05524374,+0.05524374,+0.60262749,+0.05524374,+0.05524374 }; // random observation weights, integers in 0 - 9 range double [] weights_train = new double[] { 0, 6, 5, 4, 4, 8, 2, 4, 9, 5, 2, 0, 0, 4, 0, 0, 6, 3, 6, 5, 5, 5, 6, 0, 9, 9, 8, 6, 6, 5, 6, 1, 0, 6, 8, 6, 9, 2, 8, 0, 3, 0, 2, 3, 0, 2, 5, 0, 0, 3, 7, 4, 8, 4, 1, 9, 3, 7, 1, 3, 8, 6, 9, 5, 5, 1, 9, 5, 2, 1, 0, 6, 4, 0, 5, 3, 1, 2, 4, 0, 7, 9, 6, 8, 0, 2, 3, 7, 5, 8, 3, 4, 7, 8, 1, 2, 5, 7, 3, 7, 1, 1, 5, 7, 4, 9, 2, 6, 3, 5, 4, 9, 8, 1, 8, 5, 3, 0, 4, 5, 1, 2, 2, 7, 8, 3, 4, 9, 0, 1, 3, 9, 8, 7, 0, 8, 2, 7, 1, 9, 0, 7, 7, 5, 2, 9, 7, 6, 4, 3, 4, 6, 9, 1, 5, 0, 7, 9, 4, 1, 6, 8, 8, 5, 4, 2, 5, 9, 8, 1, 9, 2, 9, 2, 3, 0, 6, 7, 3, 2, 3, 0, 9, 5, 1, 8, 0, 2, 8, 6, 9, 5, 1, 2, 3, 1, 3, 5, 0, 7, 4, 0, 5, 5, 7, 9, 3, 0, 0, 0, 1, 5, 3, 2, 8, 9, 9, 1, 6, 2, 2, 0, 5, 5, 6, 2, 8, 8, 9, 8, 5, 0, 1, 5, 3, 0, 2, 5, 4, 0, 6, 5, 4, 5, 9, 7, 5, 6, 2, 2, 6, 2, 5, 1, 5, 9, 0, 3, 0, 2, 7, 0, 4, 7, 7, 9, 3, 7, 9, 7, 9, 6, 2, 6, 2, 2, 9, 0, 9, 8, 1, 2, 6, 3, 4, 1, 2, 2, 3, 0 }; Vec offsetVecTrain = _prostateTrain.anyVec().makeZero(); try( Vec.Writer vw = offsetVecTrain.open() ) { for (int i = 0; i < offset_train.length; ++i) vw.set(i, offset_train[i]); } Vec weightsVecTrain = _prostateTrain.anyVec().makeZero(); try( Vec.Writer vw = weightsVecTrain.open() ) { for (int i = 0; i < weights_train.length; ++i) vw.set(i, weights_train[i]); } Vec offsetVecTest = _prostateTest.anyVec().makeZero(); try( Vec.Writer vw = offsetVecTest.open() ) { for (int i = 0; i < offset_test.length; ++i) vw.set(i, offset_test[i]); } Frame fTrain = new Frame(Key.make("prostate_with_offset_train"), new String[]{"offset","weights"}, new Vec[]{offsetVecTrain, weightsVecTrain}); fTrain.add(_prostateTrain.names(), _prostateTrain.vecs()); DKV.put(fTrain); Frame fTest = new Frame(Key.make("prostate_with_offset_test"), new String[]{"offset"}, new Vec[]{offsetVecTest}); fTest.add(_prostateTest.names(),_prostateTest.vecs()); DKV.put(fTest); // Call: glm(formula = CAPSULE ~ . - ID - RACE - DCAPS - DPROS - 1, family = binomial, // data = train, weights = w, offset = offset_train) // Coefficients: // AGE PSA VOL GLEASON // -0.070637 0.034939 -0.006326 0.645700 // Degrees of Freedom: 252 Total (i.e. Null); 248 Residual // Null Deviance: 1494 // Residual Deviance: 1235 AIC: 1243 String [] cfs1 = new String [] { "Intercept", "AGE" , "PSA", "VOL", "GLEASON"}; double [] vals = new double [] { 0, -0.070637, 0.034939, -0.006326, 0.645700}; GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._ignored_columns = new String[]{"ID","RACE","DPROS","DCAPS"}; params._train = fTrain._key; params._offset_column = "offset"; params._weights_column = "weights"; params._lambda = new double[]{0}; params._alpha = new double[]{0}; params._standardize = false; params._objective_epsilon = 0; params._gradient_epsilon = 1e-6; params._max_iterations = 100; // not expected to reach max iterations here params._intercept = false; params._beta_epsilon = 1e-6; try { for (Solver s : new Solver[]{Solver.AUTO, Solver.IRLSM, Solver.L_BFGS}) { Frame scoreTrain = null, scoreTest = null; try { params._solver = s; params._valid = fTest._key; System.out.println("SOLVER = " + s); try { model = new GLM(params,Key.<GLMModel>make("prostate_model")).trainModel().get(); } catch(Exception iae) { assertTrue(iae.getMessage().contains("Test dataset is missing weights vector")); } params._valid = null; model = new GLM(params,Key.<GLMModel>make("prostate_model")).trainModel().get(); HashMap<String, Double> coefs = model.coefficients(); System.out.println("coefs = " + coefs); for (int i = 0; i < cfs1.length; ++i) assertEquals(vals[i], coefs.get(cfs1[i]), 1e-4); assertEquals(1494, GLMTest.nullDeviance(model), 1); assertEquals(1235, GLMTest.residualDeviance(model), 1); assertEquals( 252, GLMTest.nullDOF(model), 0); assertEquals( 248, GLMTest.resDOF(model), 0); assertEquals(1243, GLMTest.aic(model), 1); // assertEquals(88.72363, GLMTest.residualDevianceTest(model),1e-4); // test scoring try { scoreTrain = model.score(_prostateTrain); assertTrue("shoul've thrown IAE", false); } catch (IllegalArgumentException iae) { assertTrue(iae.getMessage().contains("Test/Validation dataset is missing")); } hex.ModelMetricsBinomialGLM mmTrain = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTrain); hex.AUC2 adata = mmTrain._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mmTrain._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._training_metrics)._resDev, mmTrain._resDev, 1e-8); scoreTrain = model.score(fTrain); mmTrain = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTrain); adata = mmTrain._auc; assertEquals(model._output._training_metrics.auc_obj()._auc, adata._auc, 1e-8); assertEquals(model._output._training_metrics._MSE, mmTrain._MSE, 1e-8); assertEquals(((ModelMetricsBinomialGLM) model._output._training_metrics)._resDev, mmTrain._resDev, 1e-8); // scoreTest = model.score(fTest); // ModelMetricsBinomialGLM mmTest = (ModelMetricsBinomialGLM)hex.ModelMetricsBinomial.getFromDKV(model, fTest); // adata = mmTest._auc; // assertEquals(model._output._validation_metrics.auc()._auc, adata._auc, 1e-8); // assertEquals(model._output._validation_metrics._MSE, mmTest._MSE, 1e-8); // assertEquals(((ModelMetricsBinomialGLM) model._output._validation_metrics)._resDev, mmTest._resDev, 1e-8); // // test the actual predictions // Vec preds = scoreTest.vec("p1"); // for(int i = 0; i < pred_test.length; ++i) // assertEquals(pred_test[i],preds.at(i),1e-6); } finally { if (model != null) model.delete(); if (scoreTrain != null) scoreTrain.delete(); if (scoreTest != null) scoreTest.delete(); } } } finally { DKV.remove(fTrain._key); DKV.remove(fTest._key); Scope.exit(); } } @Test public void testPValues(){ // 1) NON-STANDARDIZED // summary(m) // Call: // glm(formula = CAPSULE ~ ., family = binomial, data = D) // Deviance Residuals: // Min 1Q Median 3Q Max // -2.0601 -0.8079 -0.4491 0.8933 2.2877 // Coefficients: // Estimate Std. Error z value Pr(>|z|) // (Intercept) -7.133333 2.383945 -2.992 0.00277 ** // ID 0.001710 0.001376 1.242 0.21420 // AGE -0.003268 0.022370 -0.146 0.88384 // RACER2 0.068308 1.542397 0.044 0.96468 // RACER3 -0.741133 1.582719 -0.468 0.63959 // DPROSb 0.888329 0.395088 2.248 0.02455 * // DPROSc 1.305940 0.416197 3.138 0.00170 ** // DPROSd 0.784403 0.542651 1.446 0.14832 // DCAPSb 0.612371 0.517959 1.182 0.23710 // PSA 0.030255 0.011149 2.714 0.00665 ** // VOL -0.009793 0.008753 -1.119 0.26320 // (Dispersion parameter for binomial family taken to be 1) // Null deviance: 390.35 on 289 degrees of freedom // Residual deviance: 297.65 on 278 degrees of freedom // AIC: 321.65 // Number of Fisher Scoring iterations: 5 // sm$coefficients // Estimate Std. Error z value Pr(>|z|) // (Intercept) -7.133333499 2.383945093 -2.99223901 2.769394e-03 // ID 0.001709562 0.001376361 1.24208800 2.142041e-01 // AGE -0.003268379 0.022369891 -0.14610616 8.838376e-01 // RACER2 0.068307757 1.542397413 0.04428674 9.646758e-01 // RACER3 -0.741133313 1.582718967 -0.46826589 6.395945e-01 // DPROSb 0.888329484 0.395088333 2.24843259 2.454862e-02 // DPROSc 1.305940109 0.416197382 3.13779030 1.702266e-03 // DPROSd 0.784403119 0.542651183 1.44550154 1.483171e-01 // DCAPSb 0.612371497 0.517959064 1.18227779 2.370955e-01 // PSA 0.030255231 0.011148747 2.71377864 6.652060e-03 // VOL -0.009793481 0.008753002 -1.11887108 2.631951e-01 // GLEASON 0.851867113 0.182282351 4.67333842 2.963429e-06 GLMParameters params = new GLMParameters(Family.binomial); params._response_column = "CAPSULE"; params._standardize = false; params._train = _prostateTrain._key; params._compute_p_values = true; params._lambda = new double[]{0}; GLM job0 = null; try { job0 = new GLM(params); params._solver = Solver.L_BFGS; GLMModel model = job0.trainModel().get(); assertFalse("should've thrown, p-values only supported with IRLSM",true); } catch(H2OModelBuilderIllegalArgumentException t) { } try { job0 = new GLM(params); params._solver = Solver.COORDINATE_DESCENT_NAIVE; GLMModel model = job0.trainModel().get(); assertFalse("should've thrown, p-values only supported with IRLSM",true); } catch(H2OModelBuilderIllegalArgumentException t) { } try { job0 = new GLM(params); params._solver = Solver.COORDINATE_DESCENT; GLMModel model = job0.trainModel().get(); assertFalse("should've thrown, p-values only supported with IRLSM",true); } catch(H2OModelBuilderIllegalArgumentException t) { } params._solver = Solver.IRLSM; try { job0 = new GLM(params); params._lambda = new double[]{1}; GLMModel model = job0.trainModel().get(); assertFalse("should've thrown, p-values only supported with no regularization",true); } catch(H2OModelBuilderIllegalArgumentException t) { } params._lambda = new double[]{0}; try { params._lambda_search = true; GLMModel model = job0.trainModel().get(); assertFalse("should've thrown, p-values only supported with no regularization (i.e. no lambda search)",true); } catch(H2OModelBuilderIllegalArgumentException t) { } params._lambda_search = false; GLM job = new GLM(params); GLMModel model = null; try { model = job.trainModel().get(); String[] names_expected = new String[]{"Intercept", "ID", "AGE", "RACE.R2", "RACE.R3", "DPROS.b", "DPROS.c", "DPROS.d", "DCAPS.b", "PSA", "VOL", "GLEASON"}; double[] stder_expected = new double[]{2.383945093, 0.001376361, 0.022369891, 1.542397413, 1.582718967, 0.395088333, 0.416197382, 0.542651183, 0.517959064, 0.011148747, 0.008753002, 0.182282351}; double[] zvals_expected = new double[]{-2.99223901, 1.24208800, -0.14610616, 0.04428674, -0.46826589, 2.24843259, 3.13779030, 1.44550154, 1.18227779, 2.71377864, -1.11887108, 4.67333842}; double[] pvals_expected = new double[]{2.769394e-03, 2.142041e-01, 8.838376e-01, 9.646758e-01, 6.395945e-01, 2.454862e-02, 1.702266e-03, 1.483171e-01, 2.370955e-01, 6.652060e-03, 2.631951e-01, 2.963429e-06}; String[] names_actual = model._output.coefficientNames(); HashMap<String, Integer> coefMap = new HashMap<>(); for (int i = 0; i < names_expected.length; ++i) coefMap.put(names_expected[i], i); double[] stder_actual = model._output.stdErr(); double[] zvals_actual = model._output.zValues(); double[] pvals_actual = model._output.pValues(); for (int i = 0; i < stder_expected.length; ++i) { int id = coefMap.get(names_actual[i]); assertEquals(stder_expected[id], stder_actual[i], stder_expected[id] * 1e-4); assertEquals(zvals_expected[id], zvals_actual[i], Math.abs(zvals_expected[id]) * 1e-4); assertEquals(pvals_expected[id], pvals_actual[i], pvals_expected[id] * 1e-3); } } finally { if(model != null) model.delete(); } // 2) STANDARDIZED // Call: // glm(formula = CAPSULE ~ ., family = binomial, data = Dstd) // Deviance Residuals: // Min 1Q Median 3Q Max // -2.0601 -0.8079 -0.4491 0.8933 2.2877 // Coefficients: // Estimate Std. Error z value Pr(>|z|) // (Intercept) -1.28045 1.56879 -0.816 0.41438 // ID 0.19054 0.15341 1.242 0.21420 // AGE -0.02118 0.14498 -0.146 0.88384 // RACER2 0.06831 1.54240 0.044 0.96468 // RACER3 -0.74113 1.58272 -0.468 0.63959 // DPROSb 0.88833 0.39509 2.248 0.02455 * // DPROSc 1.30594 0.41620 3.138 0.00170 ** // DPROSd 0.78440 0.54265 1.446 0.14832 // DCAPSb 0.61237 0.51796 1.182 0.23710 // PSA 0.60917 0.22447 2.714 0.00665 ** // VOL -0.18130 0.16204 -1.119 0.26320 // (Dispersion parameter for binomial family taken to be 1) // Null deviance: 390.35 on 289 degrees of freedom // Residual deviance: 297.65 on 278 degrees of freedom // AIC: 321.65 // Number of Fisher Scoring iterations: 5 // Estimate Std. Error z value Pr(>|z|) // (Intercept) -1.28045434 1.5687858 -0.81620723 4.143816e-01 // ID 0.19054396 0.1534062 1.24208800 2.142041e-01 // AGE -0.02118315 0.1449847 -0.14610616 8.838376e-01 // RACER2 0.06830776 1.5423974 0.04428674 9.646758e-01 // RACER3 -0.74113331 1.5827190 -0.46826589 6.395945e-01 // DPROSb 0.88832948 0.3950883 2.24843259 2.454862e-02 // DPROSc 1.30594011 0.4161974 3.13779030 1.702266e-03 // DPROSd 0.78440312 0.5426512 1.44550154 1.483171e-01 // DCAPSb 0.61237150 0.5179591 1.18227779 2.370955e-01 // PSA 0.60917093 0.2244733 2.71377864 6.652060e-03 // VOL -0.18129997 0.1620383 -1.11887108 2.631951e-01 // GLEASON 0.91750972 0.1963285 4.67333842 2.963429e-06 params._standardize = true; job = new GLM(params); try { model = job.trainModel().get(); String[] names_expected = new String[]{"Intercept", "ID", "AGE", "RACE.R2", "RACE.R3", "DPROS.b", "DPROS.c", "DPROS.d", "DCAPS.b", "PSA", "VOL", "GLEASON"}; // do not compare std_err here, depends on the coefficients // double[] stder_expected = new double[]{1.5687858, 0.1534062, 0.1449847, 1.5423974, 1.5827190, 0.3950883, 0.4161974, 0.5426512, 0.5179591, 0.2244733, 0.1620383, 0.1963285}; double[] zvals_expected = new double[]{-0.81620723, 1.24208800, -0.14610616 , 0.04428674, -0.46826589 , 2.24843259, 3.13779030 , 1.44550154 , 1.18227779 , 2.71377864 ,-1.11887108 , 4.67333842}; double[] pvals_expected = new double[]{4.143816e-01 ,2.142041e-01 ,8.838376e-01, 9.646758e-01, 6.395945e-01, 2.454862e-02, 1.702266e-03, 1.483171e-01, 2.370955e-01, 6.652060e-03 ,2.631951e-01, 2.963429e-06}; String[] names_actual = model._output.coefficientNames(); HashMap<String, Integer> coefMap = new HashMap<>(); for (int i = 0; i < names_expected.length; ++i) coefMap.put(names_expected[i], i); double[] stder_actual = model._output.stdErr(); double[] zvals_actual = model._output.zValues(); double[] pvals_actual = model._output.pValues(); for (int i = 0; i < zvals_expected.length; ++i) { int id = coefMap.get(names_actual[i]); // assertEquals(stder_expected[id], stder_actual[i], stder_expected[id] * 1e-5); assertEquals(zvals_expected[id], zvals_actual[i], Math.abs(zvals_expected[id]) * 1e-4); assertEquals(pvals_expected[id], pvals_actual[i], pvals_expected[id] * 1e-3); } } finally { if(model != null) model.delete(); } } @BeforeClass public static void setup() { stall_till_cloudsize(1); _prostateTrain = parse_test_file("smalldata/glm_test/prostate_cat_train.csv"); _prostateTest = parse_test_file("smalldata/glm_test/prostate_cat_test.csv"); _prostateTrainUpsampled = parse_test_file("smalldata/glm_test/prostate_cat_train_upsampled.csv"); _abcd = parse_test_file("smalldata/glm_test/abcd.csv"); } @AfterClass public static void cleanUp() { if(_abcd != null) _abcd.delete(); if(_prostateTrainUpsampled != null) _prostateTrainUpsampled.delete(); if(_prostateTest != null) _prostateTest.delete(); if(_prostateTrain != null) _prostateTrain.delete(); } }
package org.cleartk.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.uima.UIMAException; import org.apache.uima.collection.CollectionReader; import org.apache.uima.jcas.JCas; import org.apache.uima.resource.ResourceInitializationException; import org.apache.uima.util.FileUtils; import org.junit.Assert; import org.junit.Test; import org.uutuc.factory.CollectionReaderFactory; import org.uutuc.util.JCasIterable; public class FilesCollectionReaderTests { /** * The directory containing all the files to be loaded. */ private final String inputDir = "test/data/html"; /** * The paths for the files in the input directory. */ private final String[] paths = new String[]{ "/1.html", "/2/2.1.html", "/2/2.2.html", "/3.html", "/4/1/4.1.1.html", }; private final String[] pathsSuffix1 = new String[]{ "/1.html", "/2/2.1.html", "/4/1/4.1.1.html", }; private final String[] pathsSuffix2 = new String[]{ "/1.html", "/2/2.1.html", "/2/2.2.html", "/4/1/4.1.1.html", }; /** * Test that the text loaded into the CAS by the CollectionReader matches * the text in the files on disk. * * @throws IOException * @throws UIMAException */ @Test public void testText() throws Exception { // create the PlainTextCollectionReader with the HTML input directory String languageCode = "en-us"; CollectionReader reader = CollectionReaderFactory.createCollectionReader( FilesCollectionReader.class, null, FilesCollectionReader.PARAM_FILE_OR_DIRECTORY, this.inputDir, FilesCollectionReader.PARAM_LANGUAGE, languageCode); Assert.assertEquals(0, reader.getProgress()[0].getCompleted()); // check that each document in the CAS matches the document on disk for (JCas jCas: new JCasIterable(reader)) { Assert.assertEquals(languageCode, jCas.getDocumentLanguage()); String jCasText = jCas.getDocumentText(); String docText = this.getFileText(jCas); Assert.assertEquals(jCasText, docText); } reader.close(); Assert.assertEquals(this.paths.length, reader.getProgress()[0].getCompleted()); } /** * Test that that the CollectionReader can load the text into different * CAS views when requested. * * @throws IOException * @throws UIMAException */ @Test public void testViewText() throws Exception { // check texts when different views are used for (String viewName: new String[]{"TestView", "OtherTestView"}) { // create the PlainTextCollectionReader with the current view name CollectionReader reader = CollectionReaderFactory.createCollectionReader( FilesCollectionReader.class, null, FilesCollectionReader.PARAM_FILE_OR_DIRECTORY, this.inputDir, FilesCollectionReader.PARAM_VIEW_NAME, viewName); // check that each document in the JCas views matches the document on disk for (JCas jCas: new JCasIterable(reader)) { JCas view = jCas.getView(viewName); String jCasText = view.getDocumentText(); String docText = this.getFileText(view); Assert.assertEquals(jCasText, docText); } reader.close(); } } /** * Test that all files in the directory (and subdirectories) are * loaded into the CAS. * * @throws IOException * @throws UIMAException */ @Test public void testFilePaths() throws IOException, UIMAException { // create the PlainTextCollectionReader with the HTML input directory CollectionReader reader = CollectionReaderFactory.createCollectionReader( FilesCollectionReader.class, null, FilesCollectionReader.PARAM_FILE_OR_DIRECTORY, this.inputDir); // check that each path in the CAS matches a path on disk Set<String> pathsSet = new HashSet<String>(); pathsSet.addAll(Arrays.asList(this.paths)); for (JCas jCas: new JCasIterable(reader)) { String docPath = ViewURIUtil.getURI(jCas).replace('\\', '/'); Assert.assertTrue(pathsSet.contains(docPath)); pathsSet.remove(docPath); } reader.close(); // check that all documents were seen Assert.assertTrue(pathsSet.isEmpty()); } @Test public void testSuffixes() throws IOException, UIMAException { // create the PlainTextCollectionReader with the HTML input directory CollectionReader reader = CollectionReaderFactory.createCollectionReader( FilesCollectionReader.class, null, FilesCollectionReader.PARAM_FILE_OR_DIRECTORY, this.inputDir, FilesCollectionReader.PARAM_SUFFIXES, new String[] {"1.html"}); // check that each path in the CAS matches a path on disk Set<String> pathsSet = new HashSet<String>(); pathsSet.addAll(Arrays.asList(this.pathsSuffix1)); for (JCas jCas: new JCasIterable(reader)) { String docPath = ViewURIUtil.getURI(jCas).replace('\\', '/'); Assert.assertTrue(pathsSet.contains(docPath)); pathsSet.remove(docPath); } reader.close(); // check that all documents were seen Assert.assertTrue(pathsSet.isEmpty()); } @Test public void testSuffixes2() throws IOException, UIMAException { // create the PlainTextCollectionReader with the HTML input directory CollectionReader reader = CollectionReaderFactory.createCollectionReader( FilesCollectionReader.class, null, FilesCollectionReader.PARAM_FILE_OR_DIRECTORY, this.inputDir, FilesCollectionReader.PARAM_SUFFIXES, new String[] {"1.html", "2.html"}); // check that each path in the CAS matches a path on disk Set<String> pathsSet = new HashSet<String>(); pathsSet.addAll(Arrays.asList(this.pathsSuffix2)); for (JCas jCas: new JCasIterable(reader)) { String docPath = ViewURIUtil.getURI(jCas).replace('\\', '/'); Assert.assertTrue(pathsSet.contains(docPath)); pathsSet.remove(docPath); } reader.close(); // check that all documents were seen Assert.assertTrue(pathsSet.isEmpty()); } private final String[] fileNames = new String[]{ "11319941.tree", "11597317.txt", "watcha.txt", "huckfinn.txt"}; @Test public void testFileNames() throws IOException, UIMAException { // create the PlainTextCollectionReader with the HTML input directory CollectionReader reader = CollectionReaderFactory.createCollectionReader( FilesCollectionReader.class, null, FilesCollectionReader.PARAM_FILE_OR_DIRECTORY, "test/data/docs", FilesCollectionReader.PARAM_FILE_NAMES_FILES, new String[] {"test/data/util/PlainTextFileNames.txt"}); // check that each path in the CAS matches a path on disk Set<String> fileNamesSet = new HashSet<String>(); fileNamesSet.addAll(Arrays.asList(this.fileNames)); int i=0; for (JCas jCas: new JCasIterable(reader)) { String fileName = ViewURIUtil.getURI(jCas).replace('\\', '/'); fileName = fileName.substring(fileName.lastIndexOf("/")+1); Assert.assertTrue(fileNamesSet.contains(fileName)); fileNamesSet.remove(fileName); i++; } Assert.assertEquals(4, reader.getProgress()[0].getTotal()); reader.close(); Assert.assertEquals(4, i); // check that all documents were seen Assert.assertTrue(fileNamesSet.isEmpty()); } /** * Check that the reader works with just a single file. * * @throws IOException * @throws UIMAException */ @Test public void testSingleFile() throws IOException, UIMAException { String path = "test/data/html/1.html"; CollectionReader reader = CollectionReaderFactory.createCollectionReader( FilesCollectionReader.class, null, FilesCollectionReader.PARAM_FILE_OR_DIRECTORY, path); List<String> paths = new ArrayList<String>(); for (JCas jCas: new JCasIterable(reader)) { paths.add(ViewURIUtil.getURI(jCas).replace('\\', '/')); } reader.close(); Assert.assertEquals(1, paths.size()); Assert.assertEquals(path, paths.get(0)); } /** * Check that the reader gives an error with an invalid file. * * @throws IOException * @throws UIMAException */ @Test public void testBadFileException() throws IOException, UIMAException { try { CollectionReaderFactory.createCollectionReader( FilesCollectionReader.class, null, FilesCollectionReader.PARAM_FILE_OR_DIRECTORY, "data/hmtl"); Assert.fail("expected error for invalid path"); } catch (ResourceInitializationException e){} } /** * Get the text of the file referred to by this ClearTK Document. * * @param jCas The JCas for this document. * @return The text of the file. * @throws IOException */ private String getFileText(JCas jCas) throws Exception { File docFile = new File(this.inputDir, ViewURIUtil.getURI(jCas)); return FileUtils.file2String(docFile); } @Test public void testDescriptor() throws UIMAException, IOException { try { CollectionReaderFactory.createCollectionReader("org.cleartk.util.FilesCollectionReader"); Assert.fail("expected exception with no file or directory specified"); } catch (ResourceInitializationException e) {} CollectionReader reader = CollectionReaderFactory.createCollectionReader( "org.cleartk.util.FilesCollectionReader", FilesCollectionReader.PARAM_FILE_OR_DIRECTORY, this.inputDir); Object fileOrDirectory = reader.getConfigParameterValue( FilesCollectionReader.PARAM_FILE_OR_DIRECTORY); Assert.assertEquals(this.inputDir, fileOrDirectory); Object viewName = reader.getConfigParameterValue( FilesCollectionReader.PARAM_VIEW_NAME); Assert.assertEquals(null, viewName); Object encoding = reader.getConfigParameterValue( FilesCollectionReader.PARAM_ENCODING); Assert.assertEquals(null, encoding); Object language = reader.getConfigParameterValue( FilesCollectionReader.PARAM_LANGUAGE); Assert.assertEquals(null, language); } @Test public void testXOR() { assertTrue(true ^ false ^ false); assertFalse(true ^ true ^ false); assertTrue(false ^ false ^ true); assertFalse(true ^ false ^ true); assertFalse(false ^ false ^ false); } }
package edu.teco.dnd.eclipse.deployView; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.regex.Pattern; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.xmi.impl.XMIResourceImpl; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorSite; import org.eclipse.ui.PartInitException; import org.eclipse.ui.part.EditorPart; import org.eclipse.ui.part.FileEditorInput; import edu.teco.dnd.blocks.FunctionBlock; import edu.teco.dnd.blocks.InvalidFunctionBlockException; import edu.teco.dnd.deploy.Constraint; import edu.teco.dnd.deploy.Distribution; import edu.teco.dnd.deploy.Distribution.BlockTarget; import edu.teco.dnd.deploy.Deploy; import edu.teco.dnd.deploy.DeployListener; import edu.teco.dnd.deploy.DistributionGenerator; import edu.teco.dnd.deploy.MinimalModuleCountEvaluator; import edu.teco.dnd.deploy.UserConstraints; import edu.teco.dnd.eclipse.Activator; import edu.teco.dnd.eclipse.EclipseUtil; import edu.teco.dnd.eclipse.ModuleManager; import edu.teco.dnd.eclipse.ModuleManagerListener; import edu.teco.dnd.graphiti.model.FunctionBlockModel; import edu.teco.dnd.module.Module; import edu.teco.dnd.util.Dependencies; import edu.teco.dnd.util.FutureListener; import edu.teco.dnd.util.FutureNotifier; import edu.teco.dnd.util.StringUtil; /** * This class gives the user access to all functionality needed to deploy an * application. The user can load an existing data flow graph, rename its * function blocks and constrain them to specific modules and / or places. The * user can also create a distribution and deploy the function blocks on the * modules. * */ public class DeployView extends EditorPart implements ModuleManagerListener { /** * The logger for this class. */ private static final Logger LOGGER = LogManager.getLogger(DeployView.class); private Display display; private Activator activator; private ModuleManager manager; private ArrayList<UUID> idList = new ArrayList<UUID>(); private Collection<FunctionBlockModel> functionBlockModels; private Map<TableItem, FunctionBlockModel> mapItemToBlockModel; private Map<FunctionBlock, BlockTarget> mapBlockToTarget; private Resource resource; private DeployViewGraphics graphicsManager; private boolean newConstraints; private Button serverButton; private Button updateModulesButton; // Button to update moduleCombo private Button updateBlocksButton; private Button createButton; // Button to create deployment private Button deployButton; // Button to deploy deployment private Button constraintsButton; private Label appName; private Text blockModelName; // Name of BlockModel private Combo moduleCombo; private Text places; private Table deployment; // Table to show blockModels and current // deployment private int selectedIndex; // Index of selected field of moduleCombo // = index in idList + 1 private UUID selectedID; private TableItem selectedItem; private FunctionBlockModel selectedBlockModel; private Map<FunctionBlockModel, UUID> moduleConstraints = new HashMap<FunctionBlockModel, UUID>(); private Map<FunctionBlockModel, String> placeConstraints = new HashMap<FunctionBlockModel, String>(); private URL[] classPath = new URL[0]; @Override public void setFocus() { } @Override public void init(IEditorSite site, IEditorInput input) throws PartInitException { LOGGER.entry(site, input); setSite(site); setInput(input); activator = Activator.getDefault(); display = Display.getCurrent(); manager = activator.getModuleManager(); if (display == null) { display = Display.getDefault(); LOGGER.trace( "Display.getCurrent() returned null, using Display.getDefault(): {}", display); } manager.addModuleManagerListener(this); LOGGER.exit(); mapBlockToTarget = new HashMap<FunctionBlock, BlockTarget>(); } @Override public void createPartControl(Composite parent) { functionBlockModels = new ArrayList<FunctionBlockModel>(); mapItemToBlockModel = new HashMap<TableItem, FunctionBlockModel>(); graphicsManager = new DeployViewGraphics(parent, activator); graphicsManager.initializeParent(); appName = graphicsManager.createAppNameLabel(); serverButton = graphicsManager.createServerButton(); graphicsManager.createBlockModelSpecsLabel(); deployment = graphicsManager.createDeploymentTable(); updateModulesButton = graphicsManager.createUpdateModulesButton(); graphicsManager.createBlockModelLabel(); blockModelName = graphicsManager.createBlockModelName(); updateBlocksButton = graphicsManager.createUpdateBlocksButton(); graphicsManager.createModuleLabel(); moduleCombo = graphicsManager.createModuleCombo(); createButton = graphicsManager.createCreateButton(); graphicsManager.createPlaceLabel(); places = graphicsManager.createPlacesText(); deployButton = graphicsManager.createDeployButton(); constraintsButton = graphicsManager.createConstraintsButton(); createSelectionListeners(); loadBlockModels(getEditorInput()); } /** * Invoked whenever the UpdateModules Button is pressed. */ private void updateModules() { if (Activator.getDefault().isRunning()) { warn("Not implemented yet. \n Later: Will update information on moduleCombo"); } else { warn("Server not running"); } } /** * Invoked whenever the UpdateBlocks Button is pressed. */ private void updateBlocks() { Collection<FunctionBlockModel> newBlockModels = new ArrayList<FunctionBlockModel>(); Map<UUID, FunctionBlockModel> newIDs = new HashMap<UUID, FunctionBlockModel>(); Map<UUID, FunctionBlockModel> oldIDs = new HashMap<UUID, FunctionBlockModel>(); if (getEditorInput() instanceof FileEditorInput) { try { newBlockModels = loadInput((FileEditorInput) getEditorInput()); } catch (IOException e) { LOGGER.catching(e); } } else { LOGGER.error("Input is not a FileEditorInput {}", getEditorInput()); } for (FunctionBlockModel model : newBlockModels) { newIDs.put(model.getID(), model); } for (FunctionBlockModel model : functionBlockModels) { oldIDs.put(model.getID(), model); } resetDeployment(); if (selectedBlockModel != null) { if (!newIDs.keySet().contains(selectedBlockModel.getID())) { resetSelectedBlock(); } else { selectedBlockModel = newIDs.get(selectedBlockModel.getID()); if (selectedBlockModel.getPosition() != null) { places.setText(selectedBlockModel.getPosition()); } if (selectedBlockModel.getBlockName() != null) { blockModelName.setText(selectedBlockModel.getBlockName()); } } } for (FunctionBlockModel oldModel : functionBlockModels) { if (newIDs.containsKey(oldModel.getID())) { FunctionBlockModel newModel = newIDs.get(oldModel.getID()); replaceBlock(oldModel, newModel); } else { removeBlock(oldModel); } } for (FunctionBlockModel newModel : newBlockModels) { if (!oldIDs.containsKey(newModel.getID())) { addBlock(newModel); } } functionBlockModels = newBlockModels; } /** * Adds representation of a functionBlockModel that has just been added to * the functionBlockModels list. * * @param model * FunctionBlockModel to add. */ private void addBlock(FunctionBlockModel model) { TableItem item = new TableItem(deployment, SWT.NONE); String name = model.getBlockName(); if (name != null) { item.setText(0, name); } String position = model.getPosition(); if (position != null && !position.isEmpty()) { item.setText(2, position); placeConstraints.put(model, position); } mapItemToBlockModel.put(item, model); } /** * Replaces a FunctionBlockModel another FunctionBlockModel. This method * does NOT add the newBlock to the functionBlockModels list but takes care * of everything else - representation and constraints. * * @param oldBlock * old Block * @param newBlock * new Block. */ private void replaceBlock(FunctionBlockModel oldBlock, FunctionBlockModel newBlock) { TableItem item = getItem(oldBlock); UUID module = moduleConstraints.get(oldBlock); moduleConstraints.remove(oldBlock); placeConstraints.remove(oldBlock); mapItemToBlockModel.put(item, newBlock); if (newBlock.getBlockName() != null) { item.setText(0, newBlock.getBlockName()); } if (module != null) { moduleConstraints.put(newBlock, module); } String newPosition = newBlock.getPosition(); if (newPosition != null) { item.setText(2, newPosition); if (!newPosition.isEmpty()) { placeConstraints.put(newBlock, newPosition); } } else { item.setText(2, ""); } } private void removeBlock(FunctionBlockModel model) { TableItem item = getItem(model); moduleConstraints.remove(model); placeConstraints.remove(model); mapItemToBlockModel.remove(item); item.dispose(); } /** * Invoked whenever the Create Button is pressed. */ private void create() { Collection<Module> moduleCollection = getModuleCollection(); if (functionBlockModels.isEmpty()) { warn("No blockModels to distribute"); return; } if (moduleCollection.isEmpty()) { warn("No modules to deploy on"); return; } final ClassLoader classLoader = new URLClassLoader(classPath, DeployView.class.getClassLoader()); Map<FunctionBlock, FunctionBlockModel> blocksToModels = new HashMap<FunctionBlock, FunctionBlockModel>(); for (FunctionBlockModel model : functionBlockModels) { try { blocksToModels.put(model.createBlock(classLoader), model); } catch (InvalidFunctionBlockException e) { e.printStackTrace(); } } Collection<Constraint> constraints = new ArrayList<Constraint>(); constraints .add(new UserConstraints(moduleConstraints, placeConstraints)); DistributionGenerator generator = new DistributionGenerator( new MinimalModuleCountEvaluator(), constraints); Distribution dist = generator.getDistribution(blocksToModels.keySet(), moduleCollection); if (dist == null) { warn("No valid deployment exists"); } else { mapBlockToTarget = dist.getMapping(); for (FunctionBlock block : mapBlockToTarget.keySet()) { FunctionBlockModel blockModel = blocksToModels.get(block); TableItem item = getItem(blockModel); final String name = mapBlockToTarget.get(block).getModule() .getName(); item.setText(3, name == null ? "" : name); final String location = mapBlockToTarget.get(block).getModule() .getLocation(); item.setText(4, location == null ? "" : location); deployButton.setEnabled(true); newConstraints = false; } } } /** * Invoked whenever the Deploy Button is pressed. */ private void deploy() { if (mapBlockToTarget.isEmpty()) { warn(DeployViewTexts.NO_DEPLOYMENT_YET); return; } if (newConstraints) { int cancel = warn(DeployViewTexts.NEWCONSTRAINTS); if (cancel == -4) { return; } } final Dependencies dependencies = new Dependencies( StringUtil.joinArray(classPath, ":"), Arrays.asList( Pattern.compile("java\\..*"), Pattern.compile("edu\\.teco\\.dnd\\..*"), Pattern.compile("com\\.google\\.gson\\..*"), Pattern.compile("org\\.apache\\.bcel\\..*"), Pattern.compile("io\\.netty\\..*"), Pattern.compile("org\\.apache\\.logging\\.log4j") ) ); final Deploy deploy = new Deploy(Activator.getDefault().getConnectionManager(), mapBlockToTarget, appName.getText(), dependencies); // TODO: I don't know if this will be needed by DeployView. It can be used to wait until the deployment finishes or to run code at that point deploy.getDeployFutureNotifier().addListener(new FutureListener<FutureNotifier<? super Void>>() { @Override public void operationComplete(FutureNotifier<? super Void> future) { if (LOGGER.isInfoEnabled()) { LOGGER.info("deploy: {}", future.isSuccess()); } } }); deploy.addListener(new DeployListener() { // TODO: actually show the progress. Probably using Eclipse Jobs @Override public void moduleJoined(UUID appId, UUID moduleUUID) { LOGGER.debug("Module {} joined Application {}", moduleUUID, appId); } @Override public void moduleLoadedClasses(UUID appId, UUID moduleUUID) { LOGGER.debug("Module {} loaded all classes for Application {}", moduleUUID, appId); } @Override public void moduleLoadedBlocks(UUID appId, UUID moduleUUID) { LOGGER.debug( "Module {} loaded all FunctionBlocks for Application {}", moduleUUID, appId); } @Override public void moduleStarted(final UUID appId, final UUID moduleUUID) { LOGGER.debug("Module {} started the Application {}", moduleUUID, appId); } @Override public void deployFailed(UUID appId, Throwable cause) { LOGGER.debug("deploying Application {} failed: {}", appId, cause); } }); deploy.deploy(); resetDeployment(); } /** * Invoked whenever a Function BlockModel from the deploymentTable is * selected. */ protected void blockModelSelected() { moduleCombo.setEnabled(true); places.setEnabled(true); constraintsButton.setEnabled(true); blockModelName.setEnabled(true); TableItem[] items = deployment.getSelection(); if (items.length == 1) { selectedItem = items[0]; selectedBlockModel = mapItemToBlockModel.get(items[0]); blockModelName.setText(selectedBlockModel.getBlockName()); if (placeConstraints.containsKey(selectedBlockModel)) { places.setText(placeConstraints.get(selectedBlockModel)); } else { places.setText(""); } selectedIndex = idList.indexOf(moduleConstraints .get(selectedBlockModel)) + 1; moduleCombo.select(selectedIndex); } } /** * Invoked whenever a Module from moduleCombo is selected. */ private void moduleSelected() { selectedIndex = moduleCombo.getSelectionIndex(); } private void saveConstraints() { String text = places.getText(); if (selectedIndex > 0) { selectedID = idList.get(selectedIndex - 1); } else { selectedID = null; } if (!text.isEmpty() && selectedID != null) { int cancel = warn(DeployViewTexts.WARN_CONSTRAINTS); if (cancel == -4) { return; } } if (text.isEmpty()) { placeConstraints.remove(selectedBlockModel); } else { placeConstraints.put(selectedBlockModel, text); } selectedBlockModel.setPosition(text); selectedItem.setText(2, text); if (selectedID != null) { moduleConstraints.put(selectedBlockModel, selectedID); String module = moduleCombo.getItem(selectedIndex); selectedItem.setText(1, module); } else { selectedItem.setText(1, ""); moduleConstraints.remove(selectedBlockModel); } selectedBlockModel.setBlockName(this.blockModelName.getText()); selectedItem.setText(0, blockModelName.getText()); try { resource.save(null); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } newConstraints = true; } /** * Adds a Module ID. * * @param id * the ID to add */ private synchronized void addID(final UUID id) { LOGGER.entry(id); if (!idList.contains(id)) { LOGGER.trace("id {} is new, adding", id); moduleCombo.add(id.toString()); idList.add(id); } else { LOGGER.debug("trying to add existing id {}", id); } LOGGER.exit(); } /** * Removes a Module ID including all dependent information on this module. * * @param id * the ID to remove */ private synchronized void removeID(final UUID id) { LOGGER.entry(id); int idIndex = idList.indexOf(id); if (idIndex >= 0) { moduleCombo.remove(idIndex + 1); idList.remove(idIndex); resetDeployment(); for (FunctionBlockModel model : moduleConstraints.keySet()) { if (moduleConstraints.get(model).equals(id)) { moduleConstraints.remove(model); getItem(model).setText(1, ""); } } LOGGER.trace("found combo entry for id {}", id); } else { LOGGER.debug("trying to remove nonexistant id {}", id); } LOGGER.exit(); } /** * Loads the FunctinoBlockModels of a data flow graph and displays them in * the deployment table. * * @param input * the input of the editor */ private void loadBlockModels(IEditorInput input) { // set to empty Collection to prevent NPE in case loading fails functionBlockModels = new ArrayList<FunctionBlockModel>(); if (input instanceof FileEditorInput) { final IProject project = EclipseUtil.getWorkspaceProject(((FileEditorInput) input).getPath()); if (project != null) { classPath = getClassPath(project); } else { classPath = new URL[0]; } try { functionBlockModels = loadInput((FileEditorInput) input); } catch (IOException e) { LOGGER.catching(e); } } else { LOGGER.error("Input is not a FileEditorInput {}", input); } mapItemToBlockModel.clear(); for (FunctionBlockModel blockModel : functionBlockModels) { addBlock(blockModel); } } private URL[] getClassPath(final IProject project) { final Set<IPath> paths = EclipseUtil.getAbsoluteBinPaths(project); final ArrayList<URL> classPath = new ArrayList<URL>(paths.size()); for (final IPath path : paths) { try { classPath.add(path.toFile().toURI().toURL()); } catch (final MalformedURLException e) { if (LOGGER.isDebugEnabled()) { LOGGER.catching(Level.DEBUG, e); LOGGER.debug("Not adding path {} to class path", path); } } } return classPath.toArray(new URL[0]); } /** * Loads the given data flow graph. The file given in the editor input must * be a valid graph. Its function block models are loaded into a list and * returned. * * @param input * the input of the editor * @return a collection of FunctionBlockModels that were defined in the * model * @throws IOException * if reading fails */ private Collection<FunctionBlockModel> loadInput(final FileEditorInput input) throws IOException { LOGGER.entry(input); Collection<FunctionBlockModel> blockModelList = new ArrayList<FunctionBlockModel>(); appName.setText(input.getFile().getName().replaceAll("\\.diagram", "")); URI uri = URI.createURI(input.getURI().toASCIIString()); resource = new XMIResourceImpl(uri); resource.load(null); for (EObject object : resource.getContents()) { if (object instanceof FunctionBlockModel) { LOGGER.trace("found FunctionBlockModel {}", object); blockModelList.add(((FunctionBlockModel) object)); } } return blockModelList; } /** * Opens a warning window with the given message. * * @param message * Warning message */ private int warn(String message) { Display display = Display.getCurrent(); Shell shell = new Shell(display); MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); dialog.setText("Warning"); dialog.setMessage(message); return dialog.open(); } /** * Returns a Collection of currently running modules that are already * resolved. Does not contain modules that haven't been resolved from their * UUID yet. * * @return collection of currently running modules to deploy on. */ private Collection<Module> getModuleCollection() { Collection<Module> collection = new ArrayList<Module>(); Map<UUID, Module> map = manager.getMap(); for (UUID id : map.keySet()) { Module m = map.get(id); if (m != null) { collection.add(m); } } return collection; } /** * Returns table item representing a given function blockModel. * * @param blockModel * The blockModel to find in the table * @return item holding the blockModel */ private TableItem getItem(FunctionBlockModel blockModel) { UUID id = blockModel.getID(); for (TableItem i : mapItemToBlockModel.keySet()) { if (mapItemToBlockModel.get(i).getID() == id) { return i; } } return null; } /** * Invoked whenever a possibly created deployment gets invalid. */ private void resetDeployment() { mapBlockToTarget = new HashMap<FunctionBlock, BlockTarget>(); deployButton.setEnabled(false); for (TableItem item : deployment.getItems()) { item.setText(3, ""); item.setText(4, ""); } } /** * Invoked whenever the selected Block gets dirty. */ private void resetSelectedBlock() { places.setText(""); selectedItem = null; selectedBlockModel = null; blockModelName.setText("<select block on the left>"); blockModelName.setEnabled(false); moduleCombo.setEnabled(false); places.setEnabled(false); constraintsButton.setEnabled(false); } @Override public void doSave(IProgressMonitor monitor) { // TODO Auto-generated method stub } @Override public void doSaveAs() { // TODO Auto-generated method stub } @Override public boolean isDirty() { // TODO Auto-generated method stub return false; } @Override public boolean isSaveAsAllowed() { // TODO Auto-generated method stub return false; } @Override public void dispose() { manager.removeModuleManagerListener(this); } @Override public void moduleOnline(final UUID id) { LOGGER.entry(id); display.asyncExec(new Runnable() { @Override public void run() { addID(id); } }); LOGGER.exit(); } @Override public void moduleOffline(final UUID id) { LOGGER.entry(id); display.asyncExec(new Runnable() { @Override public void run() { removeID(id); } }); LOGGER.exit(); } @Override public void moduleResolved(final UUID id, final Module module) { display.asyncExec(new Runnable() { @Override public void run() { if (!idList.contains(id)) { LOGGER.entry(id); LOGGER.trace("id {} is new, adding", id); idList.add(id); LOGGER.exit(); } int comboIndex = idList.indexOf(id) + 1; String text = ""; if (module.getName() != null) { text = module.getName(); } text = text.concat(" : "); text = text.concat(id.toString()); moduleCombo.setItem(comboIndex, text); if (moduleConstraints.containsValue(id)) { for (FunctionBlockModel blockModel : moduleConstraints .keySet()) { getItem(blockModel).setText(1, text); } } } }); } @Override public void serverOnline(final Map<UUID, Module> modules) { display.asyncExec(new Runnable() { @Override public void run() { if (serverButton != null) { serverButton.setText("Stop Server"); } updateModulesButton.setEnabled(true); createButton.setEnabled(true); moduleCombo.setToolTipText(""); synchronized (DeployView.this) { while (!idList.isEmpty()) { removeID(idList.get(0)); // hoffentlich? } for (UUID moduleID : modules.keySet()) { addID(moduleID); } } } }); } @Override public void serverOffline() { display.asyncExec(new Runnable() { @Override public void run() { if (serverButton != null) { serverButton.setText("Start Server"); } updateModulesButton.setEnabled(false); createButton.setEnabled(false); resetDeployment(); moduleCombo .setToolTipText(DeployViewTexts.SELECTMODULEOFFLINE_TOOLTIP); synchronized (DeployView.this) { while (!idList.isEmpty()) { removeID(idList.get(0)); // hoffentlich? } } } }); } private void createSelectionListeners() { serverButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { new Thread() { @Override public void run() { if (DeployView.this.activator.isRunning()) { DeployView.this.activator.shutdownServer(); } else { DeployView.this.activator.startServer(); } } }.run(); } }); deployment.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.blockModelSelected(); } }); updateModulesButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.updateModules(); } }); updateBlocksButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.updateBlocks(); } }); moduleCombo.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.moduleSelected(); } }); createButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.create(); } }); deployButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.deploy(); } }); constraintsButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { DeployView.this.saveConstraints(); } }); } }
package com.androidsx.rateme; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Parcel; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.androidsx.libraryrateme.R; /** * Dialog to ask the user for feedback after a low rating. */ public class FeedbackDialog extends DialogFragment { private static final String TAG = FeedbackDialog.class.getSimpleName(); private static final String EXTRA_EMAIL = "email"; private static final String EXTRA_DIALOG_TITLE_COLOR = "dialog-title-color"; private static final String EXTRA_DIALOG_COLOR = "dialog-color"; private static final String EXTRA_TEXT_COLOR = "text-color"; private static final String EXTRA_HEADER_TEXT_COLOR = "header-text-color"; private static final String EXTRA_LOGO = "icon"; private static final String EXTRA_RATE_BUTTON_TEXT_COLOR = "button-text-color"; private static final String EXTRA_RATE_BUTTON_BG_COLOR = "button-bg-color"; private static final String EXTRA_TITLE_DIVIDER = "color-title-divider"; private static final String EXTRA_RATING_BAR = "get-rating"; private static final String EXTRA_ON_ACTION_LISTENER = "on-action-listener"; // Views private View confirmDialogTitleView; private View confirmDialogView; private Button cancel; private Button yes; private OnRatingListener onActionListener; public static FeedbackDialog newInstance(String email, int titleBackgroundColor, int dialogColor, int headerTextColor, int textColor, int logoResId, int rateButtonTextColor, int rateButtonBackgroundColor, int lineDividerColor, float getRatingBar, OnRatingListener onRatingListener) { FeedbackDialog feedbackDialog = new FeedbackDialog(); Bundle args = new Bundle(); args.putString(EXTRA_EMAIL, email); args.putInt(EXTRA_DIALOG_TITLE_COLOR, titleBackgroundColor); args.putInt(EXTRA_DIALOG_COLOR, dialogColor); args.putInt(EXTRA_HEADER_TEXT_COLOR, headerTextColor); args.putInt(EXTRA_TEXT_COLOR, textColor); args.putInt(EXTRA_LOGO, logoResId); args.putInt(EXTRA_RATE_BUTTON_TEXT_COLOR, rateButtonTextColor); args.putInt(EXTRA_RATE_BUTTON_BG_COLOR, rateButtonBackgroundColor); args.putInt(EXTRA_TITLE_DIVIDER, lineDividerColor); args.putFloat(EXTRA_RATING_BAR, getRatingBar); args.putParcelable(EXTRA_ON_ACTION_LISTENER, onRatingListener); feedbackDialog.setArguments(args); return feedbackDialog; } public FeedbackDialog() { super(); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); initializeUiFieldsDialogGoToMail(); Log.d(TAG, "All components were initialized successfully"); cancel.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dismiss(); onActionListener.onRating(OnRatingListener.RatingAction.LOW_RATING_REFUSED_TO_GIVE_FEEDBACK, getArguments().getFloat(EXTRA_RATING_BAR)); Log.d(TAG, "Canceled the feedback dialog"); } }); yes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goToMail(); onActionListener.onRating(OnRatingListener.RatingAction.LOW_RATING_GAVE_FEEDBACK, getArguments().getFloat(EXTRA_RATING_BAR)); Log.d(TAG, "Agreed to provide feedback"); dismiss(); } }); return builder.setCustomTitle(confirmDialogTitleView).setView(confirmDialogView).create(); } private void initializeUiFieldsDialogGoToMail() { confirmDialogTitleView = View.inflate(getActivity(), R.layout.feedback_dialog_title, null); confirmDialogView = View.inflate(getActivity(), R.layout.feedback_dialog_message, null); confirmDialogTitleView.setBackgroundColor(getArguments().getInt(EXTRA_DIALOG_TITLE_COLOR)); confirmDialogView.setBackgroundColor(getArguments().getInt(EXTRA_DIALOG_COLOR)); if (getArguments().getInt(EXTRA_LOGO) == 0) { confirmDialogView.findViewById(R.id.app_icon_dialog_mail).setVisibility(View.GONE); } else { ((ImageView) confirmDialogView.findViewById(R.id.app_icon_dialog_mail)).setImageResource(getArguments().getInt(EXTRA_LOGO)); confirmDialogView.findViewById(R.id.app_icon_dialog_mail).setVisibility(View.VISIBLE); } ((TextView) confirmDialogTitleView.findViewById(R.id.confirmDialogTitle)).setTextColor(getArguments().getInt(EXTRA_HEADER_TEXT_COLOR)); ((TextView) confirmDialogView.findViewById(R.id.mail_dialog_message)).setTextColor(getArguments().getInt(EXTRA_TEXT_COLOR)); cancel = (Button) confirmDialogView.findViewById(R.id.buttonCancel); yes = (Button) confirmDialogView.findViewById(R.id.buttonYes); cancel.setTextColor(getArguments().getInt(EXTRA_RATE_BUTTON_TEXT_COLOR)); yes.setTextColor(getArguments().getInt(EXTRA_RATE_BUTTON_TEXT_COLOR)); cancel.setBackgroundColor(getArguments().getInt(EXTRA_RATE_BUTTON_BG_COLOR)); yes.setBackgroundColor(getArguments().getInt(EXTRA_RATE_BUTTON_BG_COLOR)); onActionListener = getArguments().getParcelable(EXTRA_ON_ACTION_LISTENER); } private void goToMail() { final String subject = getResources().getString(R.string.rateme_subject_email, getResources().getString(R.string.app_name)); final String gmailPackageName = "com.google.android.gm"; try { if (isPackageInstalled(gmailPackageName)) { Intent sendMailWithGmail = new Intent(Intent.ACTION_SEND); sendMailWithGmail.setType("plain/text"); sendMailWithGmail.putExtra(Intent.EXTRA_EMAIL, new String[]{getArguments().getString(EXTRA_EMAIL)}); sendMailWithGmail.putExtra(Intent.EXTRA_SUBJECT, subject); sendMailWithGmail.setClassName("com.google.android.gm", "com.google.android.gm.ComposeActivityGmail"); startActivity(Intent.createChooser(sendMailWithGmail, "")); } else { sendGenericMail(subject); } } catch (android.content.ActivityNotFoundException ex) { sendGenericMail(subject); } } @Override public void onStart() { super.onStart(); final int titleDividerId = getResources().getIdentifier("titleDivider", "id", "android"); final View titleDivider = getDialog().findViewById(titleDividerId); if (titleDivider != null) { titleDivider.setBackgroundColor(getArguments().getInt(EXTRA_TITLE_DIVIDER)); } } private boolean isPackageInstalled(String packageName) { PackageManager pm = getActivity().getPackageManager(); try { pm.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES); return true; } catch (PackageManager.NameNotFoundException e) { return false; } } private void sendGenericMail(String subject) { Log.w(TAG, "Cannot send the email with GMail. Will use the generic chooser"); Intent sendGeneric = new Intent(Intent.ACTION_SEND); sendGeneric.setType("plain/text"); sendGeneric.putExtra(Intent.EXTRA_EMAIL, new String[] { getArguments().getString(EXTRA_EMAIL) }); sendGeneric.putExtra(Intent.EXTRA_SUBJECT, subject); startActivity(Intent.createChooser(sendGeneric, "")); } }
package com.egzosn.pay.demo.entity; import com.egzosn.pay.ali.api.AliPayConfigStorage; import com.egzosn.pay.ali.api.AliPayService; import com.egzosn.pay.ali.bean.AliTransactionType; import com.egzosn.pay.common.api.PayService; import com.egzosn.pay.common.bean.BasePayType; import com.egzosn.pay.common.bean.MsgType; import com.egzosn.pay.common.bean.TransactionType; import com.egzosn.pay.common.http.HttpConfigStorage; import com.egzosn.pay.fuiou.api.FuiouPayConfigStorage; import com.egzosn.pay.fuiou.api.FuiouPayService; import com.egzosn.pay.fuiou.bean.FuiouTransactionType; import com.egzosn.pay.payoneer.api.PayoneerConfigStorage; import com.egzosn.pay.payoneer.api.PayoneerPayService; import com.egzosn.pay.payoneer.bean.PayoneerTransactionType; import com.egzosn.pay.union.api.UnionPayConfigStorage; import com.egzosn.pay.union.api.UnionPayService; import com.egzosn.pay.union.bean.UnionTransactionType; import com.egzosn.pay.wx.api.WxPayConfigStorage; import com.egzosn.pay.wx.api.WxPayService; import com.egzosn.pay.wx.bean.WxTransactionType; import com.egzosn.pay.wx.youdian.api.WxYouDianPayConfigStorage; import com.egzosn.pay.wx.youdian.api.WxYouDianPayService; import com.egzosn.pay.wx.youdian.bean.YoudianTransactionType; /** * * * @author egan * email egzosn@gmail.com * date 2016/11/20 0:30 */ public enum PayType implements BasePayType { aliPay{ /** * @see com.egzosn.pay.ali.api.AliPayService 17, * @param apyAccount * @return */ @Override public PayService getPayService(ApyAccount apyAccount) { AliPayConfigStorage configStorage = new AliPayConfigStorage(); configStorage.setAttach(apyAccount.getPayId()); configStorage.setPid(apyAccount.getPartner()); configStorage.setAppId(apyAccount.getAppid()); configStorage.setKeyPublic(apyAccount.getPublicKey()); configStorage.setKeyPrivate(apyAccount.getPrivateKey()); configStorage.setNotifyUrl(apyAccount.getNotifyUrl()); configStorage.setReturnUrl(apyAccount.getReturnUrl()); configStorage.setSignType(apyAccount.getSignType()); configStorage.setSeller(apyAccount.getSeller()); configStorage.setPayType(apyAccount.getPayType().toString()); configStorage.setMsgType(apyAccount.getMsgType()); configStorage.setInputCharset(apyAccount.getInputCharset()); configStorage.setTest(apyAccount.isTest()); return new AliPayService(configStorage); } @Override public TransactionType getTransactionType(String transactionType) { // com.egzosn.pay.ali.before.bean.AliTransactionType 17, // AliTransactionType 17, return AliTransactionType.valueOf(transactionType); } },wxPay { @Override public PayService getPayService(ApyAccount apyAccount) { WxPayConfigStorage wxPayConfigStorage = new WxPayConfigStorage(); wxPayConfigStorage.setMchId(apyAccount.getPartner()); wxPayConfigStorage.setAppid(apyAccount.getAppid()); wxPayConfigStorage.setKeyPublic(apyAccount.getPublicKey()); wxPayConfigStorage.setSecretKey(apyAccount.getPrivateKey()); wxPayConfigStorage.setNotifyUrl(apyAccount.getNotifyUrl()); wxPayConfigStorage.setReturnUrl(apyAccount.getReturnUrl()); wxPayConfigStorage.setSignType(apyAccount.getSignType()); wxPayConfigStorage.setPayType(apyAccount.getPayType().toString()); wxPayConfigStorage.setMsgType(apyAccount.getMsgType()); wxPayConfigStorage.setInputCharset(apyAccount.getInputCharset()); wxPayConfigStorage.setTest(apyAccount.isTest()); //https /* HttpConfigStorage httpConfigStorage = new HttpConfigStorage(); httpConfigStorage.setKeystore(""); httpConfigStorage.setStorePassword(""); // httpConfigStorage.setPath(false); return new WxPayService(wxPayConfigStorage, httpConfigStorage);*/ return new WxPayService(wxPayConfigStorage); } /** * * @param transactionType * @see WxTransactionType * @return */ @Override public TransactionType getTransactionType(String transactionType) { return WxTransactionType.valueOf(transactionType); } },youdianPay { @Override public PayService getPayService(ApyAccount apyAccount) { WxYouDianPayConfigStorage wxPayConfigStorage = new WxYouDianPayConfigStorage(); wxPayConfigStorage.setKeyPrivate(apyAccount.getPrivateKey()); wxPayConfigStorage.setKeyPublic(apyAccount.getPublicKey()); // wxPayConfigStorage.setNotifyUrl(apyAccount.getNotifyUrl()); // wxPayConfigStorage.setReturnUrl(apyAccount.getReturnUrl()); wxPayConfigStorage.setSignType(apyAccount.getSignType()); wxPayConfigStorage.setPayType(apyAccount.getPayType().toString()); wxPayConfigStorage.setMsgType(apyAccount.getMsgType()); wxPayConfigStorage.setSeller(apyAccount.getSeller()); wxPayConfigStorage.setInputCharset(apyAccount.getInputCharset()); wxPayConfigStorage.setTest(apyAccount.isTest()); return new WxYouDianPayService(wxPayConfigStorage); } /** * * @param transactionType * @see YoudianTransactionType * @return */ @Override public TransactionType getTransactionType(String transactionType) { return YoudianTransactionType.valueOf(transactionType); } },fuiou{ @Override public PayService getPayService(ApyAccount apyAccount) { FuiouPayConfigStorage fuiouPayConfigStorage = new FuiouPayConfigStorage(); fuiouPayConfigStorage.setKeyPublic(apyAccount.getPublicKey()); fuiouPayConfigStorage.setKeyPrivate(apyAccount.getPrivateKey()); fuiouPayConfigStorage.setNotifyUrl(apyAccount.getNotifyUrl()); fuiouPayConfigStorage.setReturnUrl(apyAccount.getReturnUrl()); fuiouPayConfigStorage.setSignType(apyAccount.getSignType()); fuiouPayConfigStorage.setPayType(apyAccount.getPayType().toString()); fuiouPayConfigStorage.setMsgType(apyAccount.getMsgType()); fuiouPayConfigStorage.setInputCharset(apyAccount.getInputCharset()); fuiouPayConfigStorage.setTest(apyAccount.isTest()); return new FuiouPayService(fuiouPayConfigStorage); } @Override public TransactionType getTransactionType(String transactionType) { return FuiouTransactionType.valueOf(transactionType); } },unionPay{ @Override public PayService getPayService(ApyAccount apyAccount) { UnionPayConfigStorage unionPayConfigStorage = new UnionPayConfigStorage(); unionPayConfigStorage.setMerId(apyAccount.getPartner()); unionPayConfigStorage.setCertSign(true); unionPayConfigStorage.setKeyPublic(apyAccount.getPublicKey()); unionPayConfigStorage.setKeyPrivate(apyAccount.getPrivateKey()); unionPayConfigStorage.setNotifyUrl(apyAccount.getNotifyUrl()); unionPayConfigStorage.setReturnUrl(apyAccount.getReturnUrl()); unionPayConfigStorage.setSignType(apyAccount.getSignType()); unionPayConfigStorage.setPayType(apyAccount.getPayType().toString()); unionPayConfigStorage.setMsgType(apyAccount.getMsgType()); unionPayConfigStorage.setInputCharset(apyAccount.getInputCharset()); unionPayConfigStorage.setTest(apyAccount.isTest()); return new UnionPayService(unionPayConfigStorage); } @Override public TransactionType getTransactionType(String transactionType) { return UnionTransactionType.valueOf(transactionType); } },payoneer{ @Override public PayService getPayService(ApyAccount apyAccount) { PayoneerConfigStorage configStorage = new PayoneerConfigStorage(); configStorage.setProgramId("id"); configStorage.setMsgType(MsgType.json); configStorage.setInputCharset("utf-8"); configStorage.setTest(true); //Basic Auth HttpConfigStorage httpConfigStorage = new HttpConfigStorage(); httpConfigStorage.setAuthUsername("PayoneerPay "); httpConfigStorage.setAuthPassword("PayoneerPay API password"); return new PayoneerPayService(configStorage, httpConfigStorage); } @Override public TransactionType getTransactionType(String transactionType) { return PayoneerTransactionType.valueOf(transactionType); } }; public abstract PayService getPayService(ApyAccount apyAccount); }
package org.pentaho.ui.xul.swt.tags; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.swt.widgets.ToolItem; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.XulDomContainer; import org.pentaho.ui.xul.containers.XulToolbaritem; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.swt.AbstractSwtXulContainer; public class SwtToolbaritem extends AbstractSwtXulContainer implements XulToolbaritem { private XulComponent parent; private XulDomContainer container; private Composite panel; private ToolItem item; private ToolBar toolbar; private final int MARGIN_VALUE = 3; private static final Log logger = LogFactory.getLog( SwtToolbaritem.class ); public SwtToolbaritem( Element self, XulComponent parent, XulDomContainer domContainer, String tagName ) { super( "treeitem" ); toolbar = (ToolBar) parent.getManagedObject(); this.parent = parent; this.container = domContainer; item = new ToolItem( (ToolBar) parent.getManagedObject(), SWT.SEPARATOR ); setManagedObject( parent.getManagedObject() ); } /** * Get item method required because managedObject is parent object. */ public ToolItem getItem() { return item; } @Override public void layout() { if ( getChildNodes().size() > 0 ) { XulComponent c = getChildNodes().get( 0 ); Control control = (Control) c.getManagedObject(); control.pack(); item.setWidth( control.getSize().x ); item.setControl( control ); } ( (ToolBar) parent.getManagedObject() ).pack(); } public void setFlex( int flex ) { super.setFlex( flex ); if ( getFlex() > 0 ) { // only support one flexible spacer per toolbar for now. toolbar.addControlListener( new ControlAdapter() { @Override public void controlResized( ControlEvent arg0 ) { int totalWidth = toolbar.getBounds().width; int childTotalWidth = 0; for ( ToolItem i : toolbar.getItems() ) { if ( i != item ) { childTotalWidth += i.getBounds().width + MARGIN_VALUE; } } item.setWidth( Math.max( 0, totalWidth - childTotalWidth ) ); } } ); } } }
package com.uoit.freeroomfinder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class DateTimeUtility { private static final String ARMY_TIME = "kk:mm"; private static final String NORMAL_TIME = "hh:mm aa"; private static final String DATE = "yyyy-MM-dd"; private SimpleDateFormat stf; private SimpleDateFormat sdf; private Locale locale; private boolean notUseArmyClock; public DateTimeUtility(boolean notUseArmyClock, Locale locale) { if(notUseArmyClock) { stf = new SimpleDateFormat(NORMAL_TIME, locale); } else { stf = new SimpleDateFormat(ARMY_TIME, locale); } sdf = new SimpleDateFormat(DATE, locale); this.locale = locale; this.notUseArmyClock = notUseArmyClock; } public void setArmyClock(boolean notUseArmyClock) { if(this.notUseArmyClock != notUseArmyClock) { this.notUseArmyClock = notUseArmyClock; if(notUseArmyClock) { stf = new SimpleDateFormat(NORMAL_TIME, locale); } else { stf = new SimpleDateFormat(ARMY_TIME, locale); } } } public String formatDate(Date date) { return sdf.format(date); } public String formatDate(long date) { return sdf.format(date); } public Date parseDate(String date) throws ParseException { return sdf.parse(date); } public Date parseTime(String time) throws ParseException { return stf.parse(time); } public String formatTime(Date date) { return stf.format(date); } }
package com.intellij.diff.merge; import com.intellij.diff.DiffContext; import com.intellij.diff.DiffDialogHints; import com.intellij.diff.DiffManager; import com.intellij.diff.FrameDiffTool; import com.intellij.diff.actions.ProxyUndoRedoAction; import com.intellij.diff.comparison.ComparisonManager; import com.intellij.diff.comparison.ComparisonMergeUtil; import com.intellij.diff.comparison.ComparisonPolicy; import com.intellij.diff.comparison.DiffTooBigException; import com.intellij.diff.contents.DiffContent; import com.intellij.diff.contents.DocumentContent; import com.intellij.diff.fragments.MergeLineFragment; import com.intellij.diff.requests.ContentDiffRequest; import com.intellij.diff.requests.SimpleDiffRequest; import com.intellij.diff.tools.simple.ThreesideTextDiffViewerEx; import com.intellij.diff.tools.util.DiffNotifications; import com.intellij.diff.tools.util.KeyboardModifierListener; import com.intellij.diff.tools.util.base.HighlightPolicy; import com.intellij.diff.tools.util.base.IgnorePolicy; import com.intellij.diff.tools.util.base.TextDiffViewerUtil; import com.intellij.diff.tools.util.text.LineOffsets; import com.intellij.diff.tools.util.text.LineOffsetsUtil; import com.intellij.diff.tools.util.text.MergeInnerDifferences; import com.intellij.diff.tools.util.text.TextDiffProviderBase; import com.intellij.diff.util.*; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionUtil; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.diff.DiffBundle; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.editor.event.DocumentEvent; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.markup.MarkupEditorFilter; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; import com.intellij.openapi.progress.util.BackgroundTaskUtil; import com.intellij.openapi.progress.util.ProgressWindow; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.LineTokenizer; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.ex.LineStatusMarkerPopupRenderer; import com.intellij.openapi.vcs.ex.LineStatusTrackerBase; import com.intellij.openapi.vcs.ex.Range; import com.intellij.openapi.vcs.ex.SimpleLineStatusTracker; import com.intellij.ui.awt.RelativePoint; import com.intellij.util.Alarm; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.JBUI; import gnu.trove.TIntArrayList; import org.jetbrains.annotations.*; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.util.List; import java.util.*; import static com.intellij.diff.util.DiffUtil.getLineCount; import static com.intellij.util.containers.ContainerUtil.ar; public class TextMergeViewer implements MergeTool.MergeViewer { @NotNull private final MergeContext myMergeContext; @NotNull private final TextMergeRequest myMergeRequest; @NotNull private final MyThreesideViewer myViewer; public TextMergeViewer(@NotNull MergeContext context, @NotNull TextMergeRequest request) { myMergeContext = context; myMergeRequest = request; DiffContext diffContext = new MergeUtil.ProxyDiffContext(myMergeContext); ContentDiffRequest diffRequest = new SimpleDiffRequest(myMergeRequest.getTitle(), getDiffContents(myMergeRequest), getDiffContentTitles(myMergeRequest)); diffRequest.putUserData(DiffUserDataKeys.FORCE_READ_ONLY_CONTENTS, new boolean[]{true, false, true}); myViewer = new MyThreesideViewer(diffContext, diffRequest); } @NotNull private static List<DiffContent> getDiffContents(@NotNull TextMergeRequest mergeRequest) { List<DocumentContent> contents = mergeRequest.getContents(); final DocumentContent left = ThreeSide.LEFT.select(contents); final DocumentContent right = ThreeSide.RIGHT.select(contents); final DocumentContent output = mergeRequest.getOutputContent(); return ContainerUtil.list(left, output, right); } @NotNull private static List<String> getDiffContentTitles(@NotNull TextMergeRequest mergeRequest) { List<String> titles = MergeUtil.notNullizeContentTitles(mergeRequest.getContentTitles()); titles.set(ThreeSide.BASE.getIndex(), DiffBundle.message("merge.version.title.merged.result")); return titles; } // Impl @NotNull @Override public JComponent getComponent() { return myViewer.getComponent(); } @Nullable @Override public JComponent getPreferredFocusedComponent() { return myViewer.getPreferredFocusedComponent(); } @NotNull @Override public MergeTool.ToolbarComponents init() { MergeTool.ToolbarComponents components = new MergeTool.ToolbarComponents(); FrameDiffTool.ToolbarComponents init = myViewer.init(); components.statusPanel = init.statusPanel; components.toolbarActions = init.toolbarActions; components.closeHandler = () -> { if (myViewer.myContentModified) return MergeUtil.showExitWithoutApplyingChangesDialog(this, myMergeRequest, myMergeContext); else return true; }; return components; } @Nullable @Override public Action getResolveAction(@NotNull MergeResult result) { return myViewer.getResolveAction(result); } @Override public void dispose() { Disposer.dispose(myViewer); } // Getters @NotNull public MyThreesideViewer getViewer() { return myViewer; } // Viewer public class MyThreesideViewer extends ThreesideTextDiffViewerEx { @NotNull private final MergeModelBase myModel; @NotNull private final ModifierProvider myModifierProvider; @NotNull private final MyInnerDiffWorker myInnerDiffWorker; @NotNull private final SimpleLineStatusTracker myLineStatusTracker; @NotNull private final TextDiffProviderBase myTextDiffProvider; // all changes - both applied and unapplied ones @NotNull private final List<TextMergeChange> myAllMergeChanges = new ArrayList<>(); @NotNull private IgnorePolicy myCurrentIgnorePolicy; private boolean myInitialRediffStarted; private boolean myInitialRediffFinished; private boolean myContentModified; public MyThreesideViewer(@NotNull DiffContext context, @NotNull ContentDiffRequest request) { super(context, request); myModel = new MyMergeModel(getProject(), getEditor().getDocument()); myModifierProvider = new ModifierProvider(); myInnerDiffWorker = new MyInnerDiffWorker(); myLineStatusTracker = new SimpleLineStatusTracker(getProject(), getEditor().getDocument(), MyLineStatusMarkerRenderer::new); myTextDiffProvider = new TextDiffProviderBase( getTextSettings(), () -> { restartMergeResolveIfNeeded(); myInnerDiffWorker.onSettingsChanged(); }, this, ar(IgnorePolicy.DEFAULT, IgnorePolicy.TRIM_WHITESPACES, IgnorePolicy.IGNORE_WHITESPACES), ar(HighlightPolicy.BY_LINE, HighlightPolicy.BY_WORD)); myCurrentIgnorePolicy = myTextDiffProvider.getIgnorePolicy(); DiffUtil.registerAction(new ApplySelectedChangesAction(Side.LEFT, true), myPanel); DiffUtil.registerAction(new ApplySelectedChangesAction(Side.RIGHT, true), myPanel); DiffUtil.registerAction(new IgnoreSelectedChangesSideAction(Side.LEFT, true), myPanel); DiffUtil.registerAction(new IgnoreSelectedChangesSideAction(Side.RIGHT, true), myPanel); DiffUtil.registerAction(new ResolveSelectedConflictsAction(true), myPanel); DiffUtil.registerAction(new NavigateToChangeMarkerAction(false), myPanel); DiffUtil.registerAction(new NavigateToChangeMarkerAction(true), myPanel); ProxyUndoRedoAction.register(getProject(), getEditor(), myContentPanel); } @Override protected void onInit() { super.onInit(); myModifierProvider.init(); } @Override protected void onDispose() { Disposer.dispose(myModel); myLineStatusTracker.release(); super.onDispose(); } @NotNull @Override protected List<AnAction> createToolbarActions() { List<AnAction> group = new ArrayList<>(); DefaultActionGroup diffGroup = new DefaultActionGroup("Compare Contents", true); diffGroup.getTemplatePresentation().setIcon(AllIcons.Actions.Diff); diffGroup.add(Separator.create("Compare Contents")); diffGroup.add(new TextShowPartialDiffAction(PartialDiffMode.LEFT_MIDDLE)); diffGroup.add(new TextShowPartialDiffAction(PartialDiffMode.RIGHT_MIDDLE)); diffGroup.add(new TextShowPartialDiffAction(PartialDiffMode.LEFT_RIGHT)); diffGroup.add(new ShowDiffWithBaseAction(ThreeSide.LEFT)); diffGroup.add(new ShowDiffWithBaseAction(ThreeSide.BASE)); diffGroup.add(new ShowDiffWithBaseAction(ThreeSide.RIGHT)); group.add(diffGroup); group.add(new Separator("Apply non-conflicting changes:")); group.add(new ApplyNonConflictsAction(ThreeSide.LEFT, "Left")); group.add(new ApplyNonConflictsAction(ThreeSide.BASE, "All")); group.add(new ApplyNonConflictsAction(ThreeSide.RIGHT, "Right")); group.add(new MagicResolvedConflictsAction()); group.add(Separator.getInstance()); group.addAll(myTextDiffProvider.getToolbarActions()); group.add(new MyToggleAutoScrollAction()); group.add(myEditorSettingsAction); return group; } @NotNull @Override protected List<AnAction> createEditorPopupActions() { List<AnAction> group = new ArrayList<>(); group.add(new ApplySelectedChangesAction(Side.LEFT, false)); group.add(new ApplySelectedChangesAction(Side.RIGHT, false)); group.add(new ResolveSelectedChangesAction(Side.LEFT)); group.add(new ResolveSelectedChangesAction(Side.RIGHT)); group.add(new IgnoreSelectedChangesSideAction(Side.LEFT, false)); group.add(new IgnoreSelectedChangesSideAction(Side.RIGHT, false)); group.add(new ResolveSelectedConflictsAction(false)); group.add(new IgnoreSelectedChangesAction()); group.add(Separator.getInstance()); group.addAll(TextDiffViewerUtil.createEditorPopupActions()); return group; } @Nullable @Override protected List<AnAction> createPopupActions() { List<AnAction> group = new ArrayList<>(myTextDiffProvider.getPopupActions()); group.add(Separator.getInstance()); group.add(new MyToggleAutoScrollAction()); return group; } @Nullable public Action getResolveAction(@NotNull final MergeResult result) { String caption = MergeUtil.getResolveActionTitle(result, myMergeRequest, myMergeContext); return new AbstractAction(caption) { @Override public void actionPerformed(ActionEvent e) { if ((result == MergeResult.LEFT || result == MergeResult.RIGHT) && myContentModified && Messages.showYesNoDialog(myPanel.getRootPane(), DiffBundle.message("merge.dialog.resolve.side.with.discard.message", result == MergeResult.LEFT ? 0 : 1), DiffBundle.message("merge.dialog.resolve.side.with.discard.title"), Messages.getQuestionIcon()) != Messages.YES) { return; } if (result == MergeResult.RESOLVED) { if ((getChangesCount() > 0 || getConflictsCount() > 0) && Messages.showYesNoDialog(myPanel.getRootPane(), DiffBundle.message("merge.dialog.apply.partially.resolved.changes.confirmation.message", getChangesCount(), getConflictsCount()), DiffBundle.message("apply.partially.resolved.merge.dialog.title"), Messages.getQuestionIcon()) != Messages.YES) { return; } } if (result == MergeResult.CANCEL && myContentModified && !MergeUtil.showExitWithoutApplyingChangesDialog(TextMergeViewer.this, myMergeRequest, myMergeContext)) { return; } destroyChangedBlocks(); myMergeContext.finishMerge(result); } }; } // Diff private void restartMergeResolveIfNeeded() { if (myTextDiffProvider.getIgnorePolicy().equals(myCurrentIgnorePolicy)) return; if (!myInitialRediffFinished) { ApplicationManager.getApplication().invokeLater(() -> restartMergeResolveIfNeeded()); return; } if (myContentModified) { if (Messages.showYesNoDialog(myProject, "This operation will reset all applied changes. Are you sure you want to continue?", "Restart Visual Merge", Messages.getQuestionIcon()) != Messages.YES) { getTextSettings().setIgnorePolicy(myCurrentIgnorePolicy); return; } } myInitialRediffFinished = false; doRediff(); } private boolean setInitialOutputContent() { final Document baseDocument = ThreeSide.BASE.select(myMergeRequest.getContents()).getDocument(); final Document outputDocument = myMergeRequest.getOutputContent().getDocument(); return DiffUtil.executeWriteCommand(outputDocument, getProject(), "Init merge content", () -> { outputDocument.setText(baseDocument.getCharsSequence()); DiffUtil.putNonundoableOperation(getProject(), outputDocument); if (getTextSettings().isEnableLstGutterMarkersInMerge()) { myLineStatusTracker.setBaseRevision(baseDocument.getCharsSequence()); getEditor().getGutterComponentEx().setForceShowRightFreePaintersArea(true); } }); } @Override @CalledInAwt public void rediff(boolean trySync) { if (myInitialRediffStarted) return; myInitialRediffStarted = true; assert myAllMergeChanges.isEmpty(); doRediff(); } @NotNull @Override protected Runnable performRediff(@NotNull ProgressIndicator indicator) { throw new UnsupportedOperationException(); } @CalledInAwt private void doRediff() { myStatusPanel.setBusy(true); myInnerDiffWorker.disable(); // This is made to reduce unwanted modifications before rediff is finished. // It could happen between this init() EDT chunk and invokeLater(). getEditor().setViewer(true); // we need invokeLater() here because viewer is partially-initialized (ex: there are no toolbar or status panel) // user can see this state while we're showing progress indicator, so we want let init() to finish. ApplicationManager.getApplication().invokeLater(() -> { ProgressManager.getInstance().run(new Task.Modal(getProject(), "Computing Differences...", true) { private Runnable myCallback; @Override public void run(@NotNull ProgressIndicator indicator) { myCallback = doPerformRediff(indicator); } @Override public void onCancel() { myMergeContext.finishMerge(MergeResult.CANCEL); } @Override public void onThrowable(@NotNull Throwable error) { LOG.error(error); myMergeContext.finishMerge(MergeResult.CANCEL); } @Override public void onSuccess() { if (isDisposed()) return; myCallback.run(); } }); }); } @NotNull protected Runnable doPerformRediff(@NotNull ProgressIndicator indicator) { try { indicator.checkCanceled(); IgnorePolicy ignorePolicy = myTextDiffProvider.getIgnorePolicy(); List<DocumentContent> contents = myMergeRequest.getContents(); List<CharSequence> sequences = ReadAction.compute(() -> { indicator.checkCanceled(); return ContainerUtil.map(contents, content -> content.getDocument().getImmutableCharSequence()); }); List<LineOffsets> lineOffsets = ContainerUtil.map(sequences, LineOffsetsUtil::create); ComparisonManager manager = ComparisonManager.getInstance(); List<MergeLineFragment> lineFragments = manager.mergeLines(sequences.get(0), sequences.get(1), sequences.get(2), ignorePolicy.getComparisonPolicy(), indicator); List<MergeConflictType> conflictTypes = ContainerUtil.map(lineFragments, fragment -> { return DiffUtil.getLineMergeType(fragment, sequences, lineOffsets, ignorePolicy.getComparisonPolicy()); }); return () -> apply(lineFragments, conflictTypes, ignorePolicy); } catch (DiffTooBigException e) { return applyNotification(DiffNotifications.createDiffTooBig()); } catch (ProcessCanceledException e) { throw e; } catch (Throwable e) { LOG.error(e); return () -> { clearDiffPresentation(); myPanel.setErrorContent(); }; } } @CalledInAwt private void apply(@NotNull List<MergeLineFragment> fragments, @NotNull List<MergeConflictType> conflictTypes, @NotNull IgnorePolicy ignorePolicy) { clearDiffPresentation(); resetChangeCounters(); boolean success = setInitialOutputContent(); if (!success) { fragments = Collections.emptyList(); conflictTypes = Collections.emptyList(); myPanel.addNotification(DiffNotifications.createNotification("Can't resolve conflicts in a read-only file")); } myModel.setChanges(ContainerUtil.map(fragments, f -> new LineRange(f.getStartLine(ThreeSide.BASE), f.getEndLine(ThreeSide.BASE)))); for (int index = 0; index < fragments.size(); index++) { MergeLineFragment fragment = fragments.get(index); MergeConflictType conflictType = conflictTypes.get(index); TextMergeChange change = new TextMergeChange(index, fragment, conflictType, TextMergeViewer.this); myAllMergeChanges.add(change); onChangeAdded(change); } myInitialScrollHelper.onRediff(); myContentPanel.repaintDividers(); myStatusPanel.update(); getEditor().setViewer(false); myInnerDiffWorker.onEverythingChanged(); myInitialRediffFinished = true; myContentModified = false; myCurrentIgnorePolicy = ignorePolicy; if (myViewer.getTextSettings().isAutoApplyNonConflictedChanges()) { if (hasNonConflictedChanges(ThreeSide.BASE)) { applyNonConflictedChanges(ThreeSide.BASE); } } } @Override @CalledInAwt protected void destroyChangedBlocks() { super.destroyChangedBlocks(); myInnerDiffWorker.stop(); for (TextMergeChange change : myAllMergeChanges) { change.destroy(); } myAllMergeChanges.clear(); myModel.setChanges(Collections.emptyList()); } // By-word diff private class MyInnerDiffWorker { @NotNull private final Set<TextMergeChange> myScheduled = ContainerUtil.newHashSet(); @NotNull private final Alarm myAlarm = new Alarm(MyThreesideViewer.this); @Nullable private ProgressIndicator myProgress; private boolean myEnabled = false; @CalledInAwt public void scheduleRediff(@NotNull TextMergeChange change) { scheduleRediff(Collections.singletonList(change)); } @CalledInAwt public void scheduleRediff(@NotNull Collection<TextMergeChange> changes) { if (!myEnabled) return; putChanges(changes); schedule(); } @CalledInAwt public void onSettingsChanged() { boolean enabled = myTextDiffProvider.getHighlightPolicy() == HighlightPolicy.BY_WORD; if (myEnabled == enabled) return; myEnabled = enabled; rebuildEverything(); } @CalledInAwt public void onEverythingChanged() { myEnabled = myTextDiffProvider.getHighlightPolicy() == HighlightPolicy.BY_WORD; rebuildEverything(); } @CalledInAwt public void disable() { myEnabled = false; stop(); } private void rebuildEverything() { if (myProgress != null) myProgress.cancel(); myProgress = null; if (myEnabled) { putChanges(myAllMergeChanges); launchRediff(true); } else { myStatusPanel.setBusy(false); myScheduled.clear(); for (TextMergeChange change : myAllMergeChanges) { change.setInnerFragments(null); } } } @CalledInAwt public void stop() { if (myProgress != null) myProgress.cancel(); myProgress = null; myScheduled.clear(); myAlarm.cancelAllRequests(); } @CalledInAwt private void putChanges(@NotNull Collection<TextMergeChange> changes) { for (TextMergeChange change : changes) { if (change.isResolved()) continue; myScheduled.add(change); } } @CalledInAwt private void schedule() { if (myProgress != null) return; if (myScheduled.isEmpty()) return; myAlarm.cancelAllRequests(); myAlarm.addRequest(() -> launchRediff(false), ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS); } @CalledInAwt private void launchRediff(boolean trySync) { myStatusPanel.setBusy(true); final List<TextMergeChange> scheduled = ContainerUtil.newArrayList(myScheduled); myScheduled.clear(); List<Document> documents = ThreeSide.map((side) -> getEditor(side).getDocument()); final List<InnerChunkData> data = ContainerUtil.map(scheduled, change -> new InnerChunkData(change, documents)); int waitMillis = trySync ? ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS : 0; ProgressIndicator progress = BackgroundTaskUtil.executeAndTryWait(indicator -> { return performRediff(scheduled, data, indicator); }, null, waitMillis, false); if (progress.isRunning()) { myProgress = progress; } } @NotNull @CalledInBackground private Runnable performRediff(@NotNull final List<TextMergeChange> scheduled, @NotNull final List<InnerChunkData> data, @NotNull final ProgressIndicator indicator) { ComparisonPolicy comparisonPolicy = myTextDiffProvider.getIgnorePolicy().getComparisonPolicy(); final List<MergeInnerDifferences> result = new ArrayList<>(data.size()); for (InnerChunkData chunkData : data) { result.add(DiffUtil.compareThreesideInner(chunkData.text, comparisonPolicy, indicator)); } return () -> { if (!myEnabled || indicator.isCanceled()) return; myProgress = null; for (int i = 0; i < scheduled.size(); i++) { TextMergeChange change = scheduled.get(i); if (myScheduled.contains(change)) continue; change.setInnerFragments(result.get(i)); } myStatusPanel.setBusy(false); if (!myScheduled.isEmpty()) { launchRediff(false); } }; } } // Impl @Override @CalledInAwt protected void onBeforeDocumentChange(@NotNull DocumentEvent e) { super.onBeforeDocumentChange(e); if (myInitialRediffFinished) myContentModified = true; } public void repaintDividers() { myContentPanel.repaintDividers(); } private void onChangeResolved(@NotNull TextMergeChange change) { if (change.isResolved()) { onChangeRemoved(change); } else { onChangeAdded(change); } if (getChangesCount() == 0 && getConflictsCount() == 0) { LOG.assertTrue(ContainerUtil.and(getAllChanges(), TextMergeChange::isResolved)); ApplicationManager.getApplication().invokeLater(() -> { if (isDisposed()) return; JComponent component = getEditor().getComponent(); RelativePoint point = new RelativePoint(component, new Point(component.getWidth() / 2, JBUI.scale(5))); String message = DiffBundle.message("merge.all.changes.processed.message.text"); DiffUtil.showSuccessPopup(message, point, this, () -> { if (isDisposed()) return; destroyChangedBlocks(); myMergeContext.finishMerge(MergeResult.RESOLVED); }); }); } } // Getters @NotNull public MergeModelBase getModel() { return myModel; } @NotNull @Override public List<TextMergeChange> getAllChanges() { return myAllMergeChanges; } @NotNull @Override public List<TextMergeChange> getChanges() { return ContainerUtil.filter(myAllMergeChanges, mergeChange -> !mergeChange.isResolved()); } @NotNull @Override protected DiffDividerDrawUtil.DividerPaintable getDividerPaintable(@NotNull Side side) { return new MyDividerPaintable(side); } @NotNull public ModifierProvider getModifierProvider() { return myModifierProvider; } @NotNull public EditorEx getEditor() { return getEditor(ThreeSide.BASE); } // Modification operations /* * affected changes should be sorted */ public boolean executeMergeCommand(@Nullable String commandName, boolean underBulkUpdate, @Nullable List<TextMergeChange> affected, @NotNull Runnable task) { myContentModified = true; TIntArrayList affectedIndexes = null; if (affected != null) { affectedIndexes = new TIntArrayList(affected.size()); for (TextMergeChange change : affected) { affectedIndexes.add(change.getIndex()); } } return myModel.executeMergeCommand(commandName, null, UndoConfirmationPolicy.DEFAULT, underBulkUpdate, affectedIndexes, task); } public boolean executeMergeCommand(@Nullable String commandName, @Nullable List<TextMergeChange> affected, @NotNull Runnable task) { return executeMergeCommand(commandName, false, affected, task); } @CalledInAwt public void markChangeResolved(@NotNull TextMergeChange change) { if (change.isResolved()) return; change.setResolved(Side.LEFT, true); change.setResolved(Side.RIGHT, true); onChangeResolved(change); myModel.invalidateHighlighters(change.getIndex()); } @CalledInAwt public void markChangeResolved(@NotNull TextMergeChange change, @NotNull Side side) { if (change.isResolved(side)) return; change.setResolved(side, true); if (change.isResolved()) onChangeResolved(change); myModel.invalidateHighlighters(change.getIndex()); } public void ignoreChange(@NotNull TextMergeChange change, @NotNull Side side, boolean resolveChange) { if (!change.isConflict() || resolveChange) { markChangeResolved(change); } else { markChangeResolved(change, side); } } @CalledWithWriteLock public void replaceChange(@NotNull TextMergeChange change, @NotNull Side side, boolean resolveChange) { if (change.isResolved(side)) return; if (!change.isChange(side)) { markChangeResolved(change); return; } ThreeSide sourceSide = side.select(ThreeSide.LEFT, ThreeSide.RIGHT); ThreeSide oppositeSide = side.select(ThreeSide.RIGHT, ThreeSide.LEFT); Document sourceDocument = getContent(sourceSide).getDocument(); int sourceStartLine = change.getStartLine(sourceSide); int sourceEndLine = change.getEndLine(sourceSide); List<String> newContent = DiffUtil.getLines(sourceDocument, sourceStartLine, sourceEndLine); if (change.isConflict()) { boolean append = change.isOnesideAppliedConflict(); if (append) { myModel.appendChange(change.getIndex(), newContent); } else { myModel.replaceChange(change.getIndex(), newContent); } if (resolveChange || change.getStartLine(oppositeSide) == change.getEndLine(oppositeSide)) { markChangeResolved(change); } else { change.markOnesideAppliedConflict(); markChangeResolved(change, side); } } else { myModel.replaceChange(change.getIndex(), newContent); markChangeResolved(change); } } private class MyMergeModel extends MergeModelBase<TextMergeChange.State> { MyMergeModel(@Nullable Project project, @NotNull Document document) { super(project, document); } @Override protected void reinstallHighlighters(int index) { TextMergeChange change = myAllMergeChanges.get(index); change.reinstallHighlighters(); myInnerDiffWorker.scheduleRediff(change); } @NotNull @Override protected TextMergeChange.State storeChangeState(int index) { TextMergeChange change = myAllMergeChanges.get(index); return change.storeState(); } @Override protected void restoreChangeState(@NotNull TextMergeChange.State state) { super.restoreChangeState(state); TextMergeChange change = myAllMergeChanges.get(state.myIndex); boolean wasResolved = change.isResolved(); change.restoreState(state); if (wasResolved != change.isResolved()) onChangeResolved(change); } @Nullable @Override protected TextMergeChange.State processDocumentChange(int index, int oldLine1, int oldLine2, int shift) { TextMergeChange.State state = super.processDocumentChange(index, oldLine1, oldLine2, shift); TextMergeChange mergeChange = myAllMergeChanges.get(index); if (mergeChange.getStartLine() == mergeChange.getEndLine() && mergeChange.getDiffType() == TextDiffType.DELETED && !mergeChange.isResolved()) { myViewer.markChangeResolved(mergeChange); } return state; } } // Actions private boolean hasNonConflictedChanges(@NotNull ThreeSide side) { return ContainerUtil.exists(getAllChanges(), change -> !change.isConflict() && canResolveChangeAutomatically(change, side)); } private void applyNonConflictedChanges(@NotNull ThreeSide side) { executeMergeCommand("Apply Non Conflicted Changes", true, null, () -> { List<TextMergeChange> allChanges = ContainerUtil.newArrayList(getAllChanges()); for (TextMergeChange change : allChanges) { if (!change.isConflict()) { resolveChangeAutomatically(change, side); } } }); TextMergeChange firstUnresolved = ContainerUtil.find(getAllChanges(), c -> !c.isResolved()); if (firstUnresolved != null) doScrollToChange(firstUnresolved, true); } private boolean hasResolvableConflictedChanges() { return ContainerUtil.exists(getAllChanges(), change -> canResolveChangeAutomatically(change, ThreeSide.BASE)); } private void applyResolvableConflictedChanges() { executeMergeCommand("Resolve Simple Conflicted Changes", true, null, () -> { List<TextMergeChange> allChanges = ContainerUtil.newArrayList(getAllChanges()); for (TextMergeChange change : allChanges) { resolveChangeAutomatically(change, ThreeSide.BASE); } }); TextMergeChange firstUnresolved = ContainerUtil.find(getAllChanges(), c -> !c.isResolved()); if (firstUnresolved != null) doScrollToChange(firstUnresolved, true); } public boolean canResolveChangeAutomatically(@NotNull TextMergeChange change, @NotNull ThreeSide side) { if (change.isConflict()) { return side == ThreeSide.BASE && change.getType().canBeResolved() && !change.isResolved(Side.LEFT) && !change.isResolved(Side.RIGHT) && !isChangeRangeModified(change); } else { return !change.isResolved() && change.isChange(side) && !isChangeRangeModified(change); } } private boolean isChangeRangeModified(@NotNull TextMergeChange change) { MergeLineFragment changeFragment = change.getFragment(); int baseStartLine = changeFragment.getStartLine(ThreeSide.BASE); int baseEndLine = changeFragment.getEndLine(ThreeSide.BASE); DocumentContent baseDiffContent = ThreeSide.BASE.select(myMergeRequest.getContents()); Document baseDocument = baseDiffContent.getDocument(); int resultStartLine = change.getStartLine(); int resultEndLine = change.getEndLine(); Document resultDocument = getEditor().getDocument(); CharSequence baseContent = DiffUtil.getLinesContent(baseDocument, baseStartLine, baseEndLine); CharSequence resultContent = DiffUtil.getLinesContent(resultDocument, resultStartLine, resultEndLine); return !StringUtil.equals(baseContent, resultContent); } public void resolveChangeAutomatically(@NotNull TextMergeChange change, @NotNull ThreeSide side) { if (!canResolveChangeAutomatically(change, side)) return; if (change.isConflict()) { List<CharSequence> texts = ThreeSide.map(it -> { return DiffUtil.getLinesContent(getEditor(it).getDocument(), change.getStartLine(it), change.getEndLine(it)); }); CharSequence newContent = ComparisonMergeUtil.tryResolveConflict(texts.get(0), texts.get(1), texts.get(2)); if (newContent == null) { LOG.warn(String.format("Can't resolve conflicting change:\n'%s'\n'%s'\n'%s'\n", texts.get(0), texts.get(1), texts.get(2))); return; } String[] newContentLines = LineTokenizer.tokenize(newContent, false); myModel.replaceChange(change.getIndex(), Arrays.asList(newContentLines)); markChangeResolved(change); } else { Side masterSide = side.select(Side.LEFT, change.isChange(Side.LEFT) ? Side.LEFT : Side.RIGHT, Side.RIGHT); replaceChange(change, masterSide, false); } } private abstract class ApplySelectedChangesActionBase extends AnAction implements DumbAware { private final boolean myShortcut; ApplySelectedChangesActionBase(boolean shortcut) { myShortcut = shortcut; } @Override public void update(@NotNull AnActionEvent e) { if (myShortcut) { // consume shortcut even if there are nothing to do - avoid calling some other action e.getPresentation().setEnabledAndVisible(true); return; } Presentation presentation = e.getPresentation(); Editor editor = e.getData(CommonDataKeys.EDITOR); ThreeSide side = getEditorSide(editor); if (side == null) { presentation.setEnabledAndVisible(false); return; } if (!isVisible(side)) { presentation.setEnabledAndVisible(false); return; } presentation.setText(getText(side)); presentation.setVisible(true); presentation.setEnabled(isSomeChangeSelected(side)); } @Override public void actionPerformed(@NotNull final AnActionEvent e) { Editor editor = e.getData(CommonDataKeys.EDITOR); final ThreeSide side = getEditorSide(editor); if (editor == null || side == null) return; final List<TextMergeChange> selectedChanges = getSelectedChanges(side); if (selectedChanges.isEmpty()) return; String title = e.getPresentation().getText() + " in merge"; executeMergeCommand(title, selectedChanges.size() > 1, selectedChanges, () -> { apply(side, selectedChanges); }); } private boolean isSomeChangeSelected(@NotNull ThreeSide side) { EditorEx editor = getEditor(side); return DiffUtil.isSomeRangeSelected(editor, lines -> { return ContainerUtil.exists(getAllChanges(), change -> isChangeSelected(change, lines, side)); }); } @NotNull @CalledInAwt private List<TextMergeChange> getSelectedChanges(@NotNull ThreeSide side) { EditorEx editor = getEditor(side); BitSet lines = DiffUtil.getSelectedLines(editor); return ContainerUtil.filter(getChanges(), change -> isChangeSelected(change, lines, side)); } private boolean isChangeSelected(@NotNull TextMergeChange change, @NotNull BitSet lines, @NotNull ThreeSide side) { if (!isEnabled(change)) return false; int line1 = change.getStartLine(side); int line2 = change.getEndLine(side); return DiffUtil.isSelectedByLine(lines, line1, line2); } protected abstract String getText(@NotNull ThreeSide side); protected abstract boolean isVisible(@NotNull ThreeSide side); protected abstract boolean isEnabled(@NotNull TextMergeChange change); @CalledWithWriteLock protected abstract void apply(@NotNull ThreeSide side, @NotNull List<TextMergeChange> changes); } private class IgnoreSelectedChangesSideAction extends ApplySelectedChangesActionBase { @NotNull private final Side mySide; IgnoreSelectedChangesSideAction(@NotNull Side side, boolean shortcut) { super(shortcut); mySide = side; ActionUtil.copyFrom(this, mySide.select("Diff.IgnoreLeftSide", "Diff.IgnoreRightSide")); } @Override protected String getText(@NotNull ThreeSide side) { return "Ignore"; } @Override protected boolean isVisible(@NotNull ThreeSide side) { return side == mySide.select(ThreeSide.LEFT, ThreeSide.RIGHT); } @Override protected boolean isEnabled(@NotNull TextMergeChange change) { return !change.isResolved(mySide); } @Override protected void apply(@NotNull ThreeSide side, @NotNull List<TextMergeChange> changes) { for (TextMergeChange change : changes) { ignoreChange(change, mySide, false); } } } private class IgnoreSelectedChangesAction extends ApplySelectedChangesActionBase { IgnoreSelectedChangesAction() { super(false); getTemplatePresentation().setIcon(AllIcons.Diff.Remove); } @Override protected String getText(@NotNull ThreeSide side) { return "Ignore"; } @Override protected boolean isVisible(@NotNull ThreeSide side) { return side == ThreeSide.BASE; } @Override protected boolean isEnabled(@NotNull TextMergeChange change) { return !change.isResolved(); } @Override protected void apply(@NotNull ThreeSide side, @NotNull List<TextMergeChange> changes) { for (TextMergeChange change : changes) { markChangeResolved(change); } } } private class ApplySelectedChangesAction extends ApplySelectedChangesActionBase { @NotNull private final Side mySide; ApplySelectedChangesAction(@NotNull Side side, boolean shortcut) { super(shortcut); mySide = side; ActionUtil.copyFrom(this, mySide.select("Diff.ApplyLeftSide", "Diff.ApplyRightSide")); } @Override protected String getText(@NotNull ThreeSide side) { return side != ThreeSide.BASE ? "Accept" : getTemplatePresentation().getText(); } @Override protected boolean isVisible(@NotNull ThreeSide side) { if (side == ThreeSide.BASE) return true; return side == mySide.select(ThreeSide.LEFT, ThreeSide.RIGHT); } @Override protected boolean isEnabled(@NotNull TextMergeChange change) { return !change.isResolved(mySide); } @Override protected void apply(@NotNull ThreeSide side, @NotNull List<TextMergeChange> changes) { for (int i = changes.size() - 1; i >= 0; i replaceChange(changes.get(i), mySide, false); } } } private class ResolveSelectedChangesAction extends ApplySelectedChangesActionBase { @NotNull private final Side mySide; ResolveSelectedChangesAction(@NotNull Side side) { super(false); mySide = side; } @Override protected String getText(@NotNull ThreeSide side) { return mySide.select("Resolve using Left", "Resolve using Right"); } @Override protected boolean isVisible(@NotNull ThreeSide side) { if (side == ThreeSide.BASE) return true; return side == mySide.select(ThreeSide.LEFT, ThreeSide.RIGHT); } @Override protected boolean isEnabled(@NotNull TextMergeChange change) { return !change.isResolved(mySide); } @Override protected void apply(@NotNull ThreeSide side, @NotNull List<TextMergeChange> changes) { for (int i = changes.size() - 1; i >= 0; i replaceChange(changes.get(i), mySide, true); } } } private class ResolveSelectedConflictsAction extends ApplySelectedChangesActionBase { ResolveSelectedConflictsAction(boolean shortcut) { super(shortcut); ActionUtil.copyFrom(this, "Diff.ResolveConflict"); } @Override protected String getText(@NotNull ThreeSide side) { return "Resolve Automatically"; } @Override protected boolean isVisible(@NotNull ThreeSide side) { return side == ThreeSide.BASE; } @Override protected boolean isEnabled(@NotNull TextMergeChange change) { return canResolveChangeAutomatically(change, ThreeSide.BASE); } @Override protected void apply(@NotNull ThreeSide side, @NotNull List<TextMergeChange> changes) { for (int i = changes.size() - 1; i >= 0; i TextMergeChange change = changes.get(i); resolveChangeAutomatically(change, ThreeSide.BASE); } } } public class ApplyNonConflictsAction extends DumbAwareAction { @NotNull private final ThreeSide mySide; public ApplyNonConflictsAction(@NotNull ThreeSide side, @NotNull String text) { String id = side.select("Diff.ApplyNonConflicts.Left", "Diff.ApplyNonConflicts", "Diff.ApplyNonConflicts.Right"); ActionUtil.copyFrom(this, id); mySide = side; getTemplatePresentation().setText(text); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabled(hasNonConflictedChanges(mySide)); } @Override public void actionPerformed(@NotNull AnActionEvent e) { applyNonConflictedChanges(mySide); } @Override public boolean displayTextInToolbar() { return true; } @Override public boolean useSmallerFontForTextInToolbar() { return true; } } public class MagicResolvedConflictsAction extends DumbAwareAction { public MagicResolvedConflictsAction() { ActionUtil.copyFrom(this, "Diff.MagicResolveConflicts"); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabled(hasResolvableConflictedChanges()); } @Override public void actionPerformed(@NotNull AnActionEvent e) { applyResolvableConflictedChanges(); } } private class ShowDiffWithBaseAction extends DumbAwareAction { @NotNull private final ThreeSide mySide; ShowDiffWithBaseAction(@NotNull ThreeSide side) { mySide = side; String actionId = mySide.select("Diff.CompareWithBase.Left", "Diff.CompareWithBase.Result", "Diff.CompareWithBase.Right"); ActionUtil.copyFrom(this, actionId); } @Override public void actionPerformed(@NotNull AnActionEvent e) { DiffContent baseContent = ThreeSide.BASE.select(myMergeRequest.getContents()); String baseTitle = ThreeSide.BASE.select(myMergeRequest.getContentTitles()); DiffContent otherContent = mySide.select(myRequest.getContents()); String otherTitle = mySide.select(myRequest.getContentTitles()); SimpleDiffRequest request = new SimpleDiffRequest(myRequest.getTitle(), baseContent, otherContent, baseTitle, otherTitle); ThreeSide currentSide = getCurrentSide(); LogicalPosition currentPosition = DiffUtil.getCaretPosition(getCurrentEditor()); LogicalPosition resultPosition = transferPosition(currentSide, mySide, currentPosition); request.putUserData(DiffUserDataKeys.SCROLL_TO_LINE, Pair.create(Side.RIGHT, resultPosition.line)); DiffManager.getInstance().showDiff(myProject, request, new DiffDialogHints(null, myPanel)); } } // Helpers private class MyDividerPaintable implements DiffDividerDrawUtil.DividerPaintable { @NotNull private final Side mySide; MyDividerPaintable(@NotNull Side side) { mySide = side; } @Override public void process(@NotNull Handler handler) { ThreeSide left = mySide.select(ThreeSide.LEFT, ThreeSide.BASE); ThreeSide right = mySide.select(ThreeSide.BASE, ThreeSide.RIGHT); for (TextMergeChange mergeChange : myAllMergeChanges) { if (!mergeChange.isChange(mySide)) continue; boolean isResolved = mergeChange.isResolved(mySide); if (!handler.processResolvable(mergeChange.getStartLine(left), mergeChange.getEndLine(left), mergeChange.getStartLine(right), mergeChange.getEndLine(right), getEditor(), mergeChange.getDiffType(), isResolved)) { return; } } } } public class ModifierProvider extends KeyboardModifierListener { public void init() { init(myPanel, TextMergeViewer.this); } @Override public void onModifiersChanged() { for (TextMergeChange change : myAllMergeChanges) { change.updateGutterActions(false); } } } private class MyLineStatusMarkerRenderer extends LineStatusMarkerPopupRenderer { MyLineStatusMarkerRenderer(@NotNull LineStatusTrackerBase<?> tracker) { super(tracker); } @Nullable @Override protected MarkupEditorFilter getEditorFilter() { return editor -> editor == getEditor(); } @Override protected int getFramingBorderSize() { return JBUI.scale(2); } @Override public void scrollAndShow(@NotNull Editor editor, @NotNull Range range) { if (!myTracker.isValid()) return; final Document document = myTracker.getDocument(); int line = Math.min(range.getType() == Range.DELETED ? range.getLine2() : range.getLine2() - 1, getLineCount(document) - 1); int[] startLines = new int[]{ transferPosition(ThreeSide.BASE, ThreeSide.LEFT, new LogicalPosition(line, 0)).line, line, transferPosition(ThreeSide.BASE, ThreeSide.RIGHT, new LogicalPosition(line, 0)).line }; for (ThreeSide side : ThreeSide.values()) { DiffUtil.moveCaret(getEditor(side), side.select(startLines)); } getEditor().getScrollingModel().scrollToCaret(ScrollType.CENTER); showAfterScroll(editor, range); } @NotNull @Override protected List<AnAction> createToolbarActions(@NotNull Editor editor, @NotNull Range range, @Nullable Point mousePosition) { List<AnAction> actions = new ArrayList<>(); actions.add(new ShowPrevChangeMarkerAction(editor, range)); actions.add(new ShowNextChangeMarkerAction(editor, range)); actions.add(new MyRollbackLineStatusRangeAction(editor, range)); actions.add(new ShowLineStatusRangeDiffAction(editor, range)); actions.add(new CopyLineStatusRangeAction(editor, range)); actions.add(new ToggleByWordDiffAction(editor, range, mousePosition)); return actions; } private class MyRollbackLineStatusRangeAction extends RangeMarkerAction { private MyRollbackLineStatusRangeAction(@NotNull Editor editor, @NotNull Range range) { super(editor, range, IdeActions.SELECTED_CHANGES_ROLLBACK); } @Override protected boolean isEnabled(@NotNull Editor editor, @NotNull Range range) { return true; } @Override protected void actionPerformed(@NotNull Editor editor, @NotNull Range range) { DiffUtil.moveCaretToLineRangeIfNeeded(editor, range.getLine1(), range.getLine2()); myTracker.rollbackChanges(range); } } } private class NavigateToChangeMarkerAction extends DumbAwareAction { private final boolean myGoToNext; protected NavigateToChangeMarkerAction(boolean goToNext) { myGoToNext = goToNext; // TODO: reuse ShowChangeMarkerAction ActionUtil.copyFrom(this, myGoToNext ? "VcsShowNextChangeMarker" : "VcsShowPrevChangeMarker"); } @Override public void update(@NotNull AnActionEvent e) { e.getPresentation().setEnabled(getTextSettings().isEnableLstGutterMarkersInMerge()); } @Override public void actionPerformed(@NotNull AnActionEvent e) { if (!myLineStatusTracker.isValid()) return; int line = getEditor().getCaretModel().getLogicalPosition().line; Range targetRange = myGoToNext ? myLineStatusTracker.getNextRange(line) : myLineStatusTracker.getPrevRange(line); if (targetRange != null) new MyLineStatusMarkerRenderer(myLineStatusTracker).scrollAndShow(getEditor(), targetRange); } } } private static class InnerChunkData { @NotNull public final List<CharSequence> text; InnerChunkData(@NotNull TextMergeChange change, @NotNull List<Document> documents) { text = getChunks(change, documents); } @NotNull private static List<CharSequence> getChunks(@NotNull TextMergeChange change, @NotNull List<Document> documents) { return ThreeSide.map(side -> { if (!change.isChange(side) || change.isResolved(side)) return null; int startLine = change.getStartLine(side); int endLine = change.getEndLine(side); if (startLine == endLine) return null; return DiffUtil.getLinesContent(side.select(documents), startLine, endLine); }); } } }
package ru.matevosyan.start; public class StartUI { /** * Input instance variable input. */ private Input input; /** * Input instance variable tracker. */ private Tracker tracker; /** * Constructor for StartUI. * @param input for assign ot enter data to the program. * @param tracker for take the Tracker state. */ public StartUI(Input input, Tracker tracker) { this.input = input; this.tracker = tracker; } /** * Method for initialization program menu and interaction with user. */ public void init() { /** * variables for user check. */ final String exit = "y"; MenuTracker menu = new MenuTracker(this.input, this.tracker); menu.fillAction(); do { menu.show(); String key = input.ask("Select number of Tasks "); menu.select(key); } while (!exit.equals(this.input.ask("Esit? (y) "))); } /** * The static main method which is starting our program. * @param args is the array argument that pass to main method */ public static void main(String[] args) { /** * Instance variable StartUI and call the method init. */ Input input = new ConsoleInput(); new StartUI(input, new Tracker()).init(); } }
package org.usfirst.frc.team847.robot; import edu.wpi.first.wpilibj.*; //import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; //import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot implements RobotMap{ GamePad turnControl; GamePad controller2; DriveTrain scrubTrain; BallShooter shooter2; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ public void robotInit() { controller2 = new GamePad(OBJ_MANIP_GAMEPAD);// give controller2 in GamePad the variable 2 turnControl = new GamePad(DRIVE_GAMEPAD);// give controller1 in GamePad the variable 1 scrubTrain = new DriveTrain(); shooter2 = new BallShooter(controller2); } /** * This autonomous (along with the chooser code above) shows how to select between different autonomous modes * using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW * Dashboard, remove all of the chooser code and uncomment the getString line to get the auto name from the text box * below the Gyro * * You can add additional auto modes by adding additional comparisons to the switch structure below with additional strings. * If using the SendableChooser make sure to add them to the chooser code above as well. */ public void autonomousInit() { } /** * This function is called periodically during autonomous */ public void autonomousPeriodic() { } /*** * This function is called periodically during operator control */ public void teleopPeriodic() { double feedsd = turnControl.quadraticLY(); double feeddir = turnControl.rightStickX(); scrubTrain.turnWheel(feeddir); scrubTrain.driveWheels(feedsd); shooter2.shootingMethod(); } /** * This function is called periodically during test mode */ public void testPeriodic() { scrubTrain.testMotor(); } }
package owltools; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import org.semanticweb.HermiT.Reasoner; import org.semanticweb.elk.owlapi.ElkReasonerFactory; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.apibinding.OWLManager; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom; import org.semanticweb.owlapi.model.OWLObjectIntersectionOf; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyID; import org.semanticweb.owlapi.model.OWLOntologyManager; import org.semanticweb.owlapi.model.OWLRestriction; import org.semanticweb.owlapi.model.OWLSubClassOfAxiom; import org.semanticweb.owlapi.model.SetOntologyID; import org.semanticweb.owlapi.profiles.OWL2ELProfile; import org.semanticweb.owlapi.profiles.OWLProfileReport; import org.semanticweb.owlapi.profiles.OWLProfileViolation; import org.semanticweb.owlapi.reasoner.InferenceType; import org.semanticweb.owlapi.reasoner.Node; import org.semanticweb.owlapi.reasoner.NodeSet; import org.semanticweb.owlapi.reasoner.OWLReasoner; import org.semanticweb.owlapi.reasoner.OWLReasonerFactory; import owltools.graph.OWLGraphWrapper; import owltools.graph.OWLQuantifiedProperty.Quantifier; import owltools.reasoner.PlaceholderJcelFactory; import com.clarkparsia.pellet.owlapiv3.PelletReasonerFactory; /** * This class build inferred axioms of an ontology. * @author Shahid Manzoor * */ public class InferenceBuilder{ protected final static Logger logger = Logger .getLogger(InferenceBuilder.class); public static final String REASONER_PELLET = "pellet"; public static final String REASONER_HERMIT = "hermit"; public static final String REASONER_JCEL = "jcel"; public static final String REASONER_ELK = "elk"; private final FactoryDetails reasonerFactoryDetails; private volatile OWLReasoner reasoner = null; private OWLGraphWrapper graph; List<OWLAxiom> redundantAxioms = new ArrayList<OWLAxiom>(); List<OWLEquivalentClassesAxiom> equivalentNamedClassPairs = new ArrayList<OWLEquivalentClassesAxiom>(); public InferenceBuilder(OWLGraphWrapper graph){ this(graph, new PelletReasonerFactory(), false); } public InferenceBuilder(OWLGraphWrapper graph, String reasonerName){ this(graph, reasonerName, false); } public InferenceBuilder(OWLGraphWrapper graph, String reasonerName, boolean enforceEL){ this(graph, getFactory(reasonerName), enforceEL); } public InferenceBuilder(OWLGraphWrapper graph, OWLReasonerFactory factory, boolean enforceEL){ this(graph, new FactoryDetails(factory), enforceEL); } private InferenceBuilder(OWLGraphWrapper graph, FactoryDetails reasonerFactoryDetails, boolean enforceEL){ this.graph = graph; this.reasonerFactoryDetails = reasonerFactoryDetails; if (enforceEL) { this.graph = enforceEL(graph); } } private static FactoryDetails getFactory(String reasonerName) { if (REASONER_PELLET.equals(reasonerName)) { return new FactoryDetails(new PelletReasonerFactory()); } else if (REASONER_HERMIT.equals(reasonerName)) { return new FactoryDetails(new Reasoner.ReasonerFactory()); } else if (REASONER_JCEL.equals(reasonerName)) { return new FactoryDetails(new PlaceholderJcelFactory()); } else if (REASONER_ELK.equals(reasonerName)) { return new FactoryDetails(new ElkReasonerFactory(), InferenceType.values()); } throw new IllegalArgumentException("Unknown reasoner: "+reasonerName); } private static class FactoryDetails { final OWLReasonerFactory factory; final InferenceType[] precomputeInferences; FactoryDetails(OWLReasonerFactory factory, InferenceType[] precomputeInferences) { super(); this.factory = factory; this.precomputeInferences = precomputeInferences; } FactoryDetails(OWLReasonerFactory factory) { this(factory, null); } } public static OWLGraphWrapper enforceEL(OWLGraphWrapper graph) { String origIRI = graph.getSourceOntology().getOntologyID().getOntologyIRI().toString(); if (origIRI.endsWith(".owl")) { origIRI = origIRI.replace(".owl", "-el.owl"); } else { origIRI = origIRI + "-el"; } return enforceEL(graph, IRI.create(origIRI)); } /** * Create an ontology with EL as description logic profile. This is achieved by * removing the non-compatible axioms. * * WARNING: Due to the data type restrictions of EL, all deprecation annotations * are removed in this process. * * @param graph * @return ontology limited to EL */ public static OWLGraphWrapper enforceEL(OWLGraphWrapper graph, IRI elOntologyIRI) { OWL2ELProfile profile = new OWL2ELProfile(); OWLOntology sourceOntology = graph.getSourceOntology(); OWLProfileReport report = profile.checkOntology(sourceOntology); if (!report.isInProfile()) { logger.info("Using el-vira to restrict "+graph.getOntologyId()+" to EL"); OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); try { OWLOntology infOnt = manager.createOntology(elOntologyIRI); // Remove violations List<OWLProfileViolation> violations = report.getViolations(); Set<OWLAxiom> ignoreSet = new HashSet<OWLAxiom>(); for (OWLProfileViolation violation : violations) { OWLAxiom axiom = violation.getAxiom(); if (axiom!=null) { ignoreSet.add(axiom); } } int count = 0; for(OWLAxiom axiom : sourceOntology.getAxioms()) { if (!ignoreSet.contains(axiom)) { manager.addAxiom(infOnt, axiom); } else { count += 1; } } logger.info("enforce EL process removed "+count+" axioms"); return new OWLGraphWrapper(infOnt); } catch (OWLOntologyCreationException e) { logger.error("Could not create new Ontology for EL restriction", e); throw new RuntimeException(e); } } else { logger.info("enforce EL not required for "+graph.getOntologyId()); return graph; } } public OWLGraphWrapper getOWLGraphWrapper(){ return this.graph; } public void setOWLGraphWrapper(OWLGraphWrapper g){ this.reasoner = null; this.graph = g; } public synchronized void setReasoner(OWLReasoner reasoner){ this.reasoner = reasoner; } private synchronized OWLReasoner getReasoner(OWLOntology ontology){ if(reasoner == null){ OWLReasonerFactory factory = reasonerFactoryDetails.factory; String reasonerFactoryName = factory.getReasonerName(); if (reasonerFactoryName == null) { reasonerFactoryName = factory.getClass().getSimpleName(); } logger.info("Creating reasoner using: "+reasonerFactoryName); reasoner = factory.createReasoner(ontology); String reasonerName = reasoner.getReasonerName(); if (reasonerName == null) { reasonerName = reasoner.getClass().getSimpleName(); } logger.info("Created reasoner: "+reasonerName); if (reasonerFactoryDetails.precomputeInferences != null) { reasoner.precomputeInferences(reasonerFactoryDetails.precomputeInferences); // necessary for ELK logger.info("pre-computed inferences; types: "+reasonerFactoryDetails.precomputeInferences.length); } } return reasoner; } public List<OWLAxiom> getRedundantAxioms() { return redundantAxioms; } public List<OWLEquivalentClassesAxiom> getEquivalentNamedClassPairs() { return equivalentNamedClassPairs; } public List<OWLAxiom> buildInferences() { return buildInferences(true); } /** * if alwaysAssertSuperClasses then ensure * that superclasses are always asserted for every equivalence * axiom, except in the case where a more specific superclass is already * in the set of inferences. * * this is because applications - particularly obof-centered ones - * ignore equivalence axioms by default * * side effects: sets redundantAxioms (@see #getRedundantAxioms()) * * @param alwaysAssertSuperClasses * @return inferred axioms */ public List<OWLAxiom> buildInferences(boolean alwaysAssertSuperClasses) { List<OWLAxiom> axiomsToAdd = new ArrayList<OWLAxiom>(); List<OWLAxiom> equivAxiomsToAdd = new ArrayList<OWLAxiom>(); OWLDataFactory dataFactory = graph.getDataFactory(); OWLOntology ontology = graph.getSourceOntology(); reasoner = getReasoner(ontology); Set<OWLClass> nrClasses = new HashSet<OWLClass>(); logger.info("Finding asserted equivalencies..."); for (OWLClass cls : ontology.getClassesInSignature()) { for (OWLClassExpression ec : cls.getEquivalentClasses(ontology)) { //System.out.println(cls+"=EC="+ec); if (alwaysAssertSuperClasses) { if (ec instanceof OWLObjectIntersectionOf) { for (OWLClassExpression x : ((OWLObjectIntersectionOf)ec).getOperands()) { // Translate equivalence axioms into weaker subClassOf axioms. if (x instanceof OWLRestriction) { // we only include restrictions - note that if the operand is // an OWLClass it will be inferred as a superclass (see below) OWLSubClassOfAxiom sca = dataFactory.getOWLSubClassOfAxiom(cls, x); if (!ontology.containsAxiom(sca)) equivAxiomsToAdd.add(sca); } } } } } } logger.info("Finding inferred superclasses..."); for (OWLClass cls : ontology.getClassesInSignature()) { if (nrClasses.contains(cls)) continue; // do not report these // REPORT INFERRED EQUIVALENCE BETWEEN NAMED CLASSES for (OWLClass ec : reasoner.getEquivalentClasses(cls)) { if (nrClasses.contains(ec)) continue; // do not report these if (cls.equals(ec)) continue; if (logger.isDebugEnabled()) { logger.debug("Inferred Equiv: " + cls + " == " + ec); } if (ec instanceof OWLClass && !ec.equals(cls)) { OWLEquivalentClassesAxiom eca = graph.getDataFactory().getOWLEquivalentClassesAxiom(cls, ec); if (logger.isDebugEnabled()) { logger.info("Equivalent Named Class Pair: "+eca); } equivalentNamedClassPairs.add(eca); } if (cls.toString().compareTo(ec.toString()) > 0) // equivalence // symmetric: // report // each pair // once equivAxiomsToAdd.add(dataFactory.getOWLEquivalentClassesAxiom(cls, ec)); } // REPORT INFERRED SUBCLASSES NOT ALREADY ASSERTED NodeSet<OWLClass> scs = reasoner.getSuperClasses(cls, true); for (Node<OWLClass> scSet : scs) { for (OWLClass sc : scSet) { if (sc.isOWLThing()) { continue; // do not report subclasses of owl:Thing } if (nrClasses.contains(sc)) continue; // we do not want to report inferred subclass links // if they are already asserted in the ontology boolean isAsserted = false; for (OWLClassExpression asc : cls.getSuperClasses(ontology)) { if (asc.equals(sc)) { // we don't want to report this isAsserted = true; } } if (!alwaysAssertSuperClasses) { // when generating obo, we do NOT want equivalence axioms treated as // assertions for (OWLClassExpression ec : cls .getEquivalentClasses(ontology)) { if (ec instanceof OWLObjectIntersectionOf) { OWLObjectIntersectionOf io = (OWLObjectIntersectionOf) ec; for (OWLClassExpression op : io.getOperands()) { if (op.equals(sc)) { isAsserted = true; } } } } } // include any inferred axiom that is NOT already asserted in the ontology if (!isAsserted) { axiomsToAdd.add(dataFactory.getOWLSubClassOfAxiom(cls, sc)); } } } } // CHECK FOR REDUNDANCY logger.info("Checking for redundant assertions caused by inferences"); redundantAxioms = new ArrayList<OWLAxiom>(); for (OWLClass cls : ontology.getClassesInSignature()) { Set<OWLClassExpression> supers = cls.getSuperClasses(ontology); for (OWLAxiom ax : axiomsToAdd) { if (ax instanceof OWLSubClassOfAxiom) { OWLSubClassOfAxiom sax = (OWLSubClassOfAxiom)ax; if (sax.getSubClass().equals(cls)) { supers.add(sax.getSuperClass()); } } } for (OWLClassExpression sup : supers) { if (sup instanceof OWLClass) { if (sup.isOWLThing()) { redundantAxioms.add(dataFactory.getOWLSubClassOfAxiom(cls, sup)); continue; } for (Node<OWLClass> supNode : reasoner.getSuperClasses(sup,false)) { for (OWLClass sup2 : supNode.getEntities()) { if (supers.contains(sup2)) { redundantAxioms.add(dataFactory.getOWLSubClassOfAxiom(cls, sup2) ); } } } } } } axiomsToAdd.addAll(equivAxiomsToAdd); return axiomsToAdd; } public List<String> performConsistencyChecks(){ List<String> errors = new ArrayList<String>(); if(graph == null){ errors.add("The ontology is not set."); return errors; } OWLOntology ont = graph.getSourceOntology(); reasoner = getReasoner(ont); long t1 = System.currentTimeMillis(); logger.info("Consistency check started............"); boolean consistent = reasoner.isConsistent(); logger.info("Is the ontology consistent ....................." + consistent + ", " + (System.currentTimeMillis()-t1)/100); if(!consistent){ errors.add("The ontology '" + graph.getOntologyId() + " ' is not consistent"); } // We can easily get a list of unsatisfiable classes. (A class is unsatisfiable if it // can't possibly have any instances). Note that the getunsatisfiableClasses method // is really just a convenience method for obtaining the classes that are equivalent // to owl:Nothing. OWLClass nothing = graph.getDataFactory().getOWLNothing(); Node<OWLClass> unsatisfiableClasses = reasoner.getUnsatisfiableClasses(); if (unsatisfiableClasses.getSize() > 0) { for(OWLClass cls : unsatisfiableClasses.getEntities()) { logger.info("unsat: "+cls.getIRI()); if (cls.equals(nothing)) { // nothing to see here, move along continue; } errors.add ("unsatisfiable: " + graph.getIdentifier(cls) + " : " + graph.getLabel(cls)); } } return errors; } public Set<Set<OWLAxiom>> getExplaination(String c1, String c2, Quantifier quantifier){ /*OWLAxiom ax = null; OWLDataFactory dataFactory = graph.getDataFactory(); OWLClass cls1 = dataFactory.getOWLClass(IRI.create(c1)); OWLClass cls2 = dataFactory.getOWLClass(IRI.create(c2)); if(quantifier == Quantifier.EQUIVALENT){ ax = dataFactory.getOWLEquivalentClassesAxiom(cls1, cls2); }else{ ax = dataFactory.getOWLSubClassOfAxiom(cls1, cls2); } //graph.getManager().applyChange(new AddAxiom(graph.getSourceOntology(), ax)); DefaultExplanationGenerator gen = new DefaultExplanationGenerator(graph.getManager(), factory, infOntology, reasoner,null); return gen.getExplanations(ax);*/ return null; } }
package com.intellij.ui.popup; import com.intellij.codeInsight.hint.HintUtil; import com.intellij.icons.AllIcons; import com.intellij.ide.*; import com.intellij.ide.actions.WindowAction; import com.intellij.ide.ui.PopupLocationTracker; import com.intellij.ide.ui.ScreenAreaConsumer; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.TransactionGuard; import com.intellij.openapi.application.TransactionGuardImpl; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectUtil; import com.intellij.openapi.ui.popup.*; import com.intellij.openapi.util.*; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.IdeFrame; import com.intellij.openapi.wm.ToolWindowId; import com.intellij.openapi.wm.WindowManager; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.ex.WindowManagerEx; import com.intellij.openapi.wm.impl.IdeGlassPaneImpl; import com.intellij.ui.*; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.components.JBLabel; import com.intellij.ui.mac.touchbar.TouchBarsManager; import com.intellij.ui.scale.JBUIScale; import com.intellij.ui.speedSearch.SpeedSearch; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.WeakList; import com.intellij.util.ui.*; import com.intellij.util.ui.accessibility.AccessibleContextUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.List; import java.util.*; import java.util.function.Supplier; import static java.awt.event.MouseEvent.*; import static java.awt.event.WindowEvent.WINDOW_ACTIVATED; import static java.awt.event.WindowEvent.WINDOW_GAINED_FOCUS; public class AbstractPopup implements JBPopup, ScreenAreaConsumer { public static final String SHOW_HINTS = "ShowHints"; // Popup size stored with DimensionService is null first time // In this case you can put Dimension in content client properties to adjust size // Zero or negative values (with/height or both) would be ignored (actual values would be obtained from preferred size) public static final String FIRST_TIME_SIZE = "FirstTimeSize"; private static final Logger LOG = Logger.getInstance(AbstractPopup.class); private PopupComponent myPopup; private MyContentPanel myContent; private JComponent myPreferredFocusedComponent; private boolean myRequestFocus; private boolean myFocusable; private boolean myForcedHeavyweight; private boolean myLocateWithinScreen; private boolean myResizable; private WindowResizeListener myResizeListener; private WindowMoveListener myMoveListener; private JPanel myHeaderPanel; private CaptionPanel myCaption; private JComponent myComponent; private String myDimensionServiceKey; private Computable<Boolean> myCallBack; private Project myProject; private boolean myCancelOnClickOutside; private Set<JBPopupListener> myListeners; private boolean myUseDimServiceForXYLocation; private MouseChecker myCancelOnMouseOutCallback; private Canceller myMouseOutCanceller; private boolean myCancelOnWindow; private boolean myCancelOnWindowDeactivation = true; private Dimension myForcedSize; private Point myForcedLocation; private boolean myCancelKeyEnabled; private boolean myLocateByContent; private Dimension myMinSize; private List<Object> myUserData; private boolean myShadowed; private float myAlpha; private float myLastAlpha; private MaskProvider myMaskProvider; private Window myWindow; private boolean myInStack; private MyWindowListener myWindowListener; private boolean myModalContext; private Component[] myFocusOwners; private PopupBorder myPopupBorder; private Dimension myRestoreWindowSize; protected Component myOwner; private Component myRequestorComponent; private boolean myHeaderAlwaysFocusable; private boolean myMovable; private JComponent myHeaderComponent; InputEvent myDisposeEvent; private Runnable myFinalRunnable; private Runnable myOkHandler; @Nullable private BooleanFunction<? super KeyEvent> myKeyEventHandler; protected boolean myOk; private final List<Runnable> myResizeListeners = new ArrayList<>(); private static final WeakList<JBPopup> all = new WeakList<>(); private boolean mySpeedSearchAlwaysShown; protected final SpeedSearch mySpeedSearch = new SpeedSearch() { boolean searchFieldShown; @Override public void update() { mySpeedSearchPatternField.getTextEditor().setBackground(UIUtil.getTextFieldBackground()); onSpeedSearchPatternChanged(); mySpeedSearchPatternField.setText(getFilter()); if (!mySpeedSearchAlwaysShown) { if (isHoldingFilter() && !searchFieldShown) { setHeaderComponent(mySpeedSearchPatternField); searchFieldShown = true; } else if (!isHoldingFilter() && searchFieldShown) { setHeaderComponent(null); searchFieldShown = false; } } } @Override public void noHits() { mySpeedSearchPatternField.getTextEditor().setBackground(LightColors.RED); } }; protected SearchTextField mySpeedSearchPatternField; private boolean myNativePopup; private boolean myMayBeParent; private JLabel myAdComponent; private boolean myDisposed; private boolean myNormalWindowLevel; private UiActivity myActivityKey; private Disposable myProjectDisposable; private volatile State myState = State.NEW; void setNormalWindowLevel(boolean normalWindowLevel) { myNormalWindowLevel = normalWindowLevel; } private enum State {NEW, INIT, SHOWING, SHOWN, CANCEL, DISPOSE} private void debugState(@NotNull String message, State @NotNull ... states) { if (LOG.isDebugEnabled()) { LOG.debug(hashCode() + " - " + message); if (!ApplicationManager.getApplication().isDispatchThread()) { LOG.debug("unexpected thread"); } for (State state : states) { if (state == myState) { return; } } LOG.debug(new IllegalStateException("myState=" + myState)); } } protected AbstractPopup() { } @NotNull protected AbstractPopup init(Project project, @NotNull JComponent component, @Nullable JComponent preferredFocusedComponent, boolean requestFocus, boolean focusable, boolean movable, String dimensionServiceKey, boolean resizable, @Nullable String caption, @Nullable Computable<Boolean> callback, boolean cancelOnClickOutside, @Nullable Set<JBPopupListener> listeners, boolean useDimServiceForXYLocation, ActiveComponent commandButton, @Nullable IconButton cancelButton, @Nullable MouseChecker cancelOnMouseOutCallback, boolean cancelOnWindow, @Nullable ActiveIcon titleIcon, boolean cancelKeyEnabled, boolean locateByContent, boolean placeWithinScreenBounds, @Nullable Dimension minSize, float alpha, @Nullable MaskProvider maskProvider, boolean inStack, boolean modalContext, Component @Nullable [] focusOwners, @Nullable String adText, int adTextAlignment, boolean headerAlwaysFocusable, @NotNull List<? extends Pair<ActionListener, KeyStroke>> keyboardActions, Component settingsButtons, @Nullable final Processor<? super JBPopup> pinCallback, boolean mayBeParent, boolean showShadow, boolean showBorder, Color borderColor, boolean cancelOnWindowDeactivation, @Nullable BooleanFunction<? super KeyEvent> keyEventHandler) { assert !requestFocus || focusable : "Incorrect argument combination: requestFocus=true focusable=false"; all.add(this); myActivityKey = new UiActivity.Focus("Popup:" + this); myProject = project; myComponent = component; myPopupBorder = showBorder ? borderColor != null ? PopupBorder.Factory.createColored(borderColor) : PopupBorder.Factory.create(true, showShadow) : PopupBorder.Factory.createEmpty(); myShadowed = showShadow; myContent = createContentPanel(resizable, myPopupBorder, false); myMayBeParent = mayBeParent; myCancelOnWindowDeactivation = cancelOnWindowDeactivation; myContent.add(component, BorderLayout.CENTER); if (adText != null) { setAdText(adText, adTextAlignment); } myCancelKeyEnabled = cancelKeyEnabled; myLocateByContent = locateByContent; myLocateWithinScreen = placeWithinScreenBounds; myAlpha = alpha; myMaskProvider = maskProvider; myInStack = inStack; myModalContext = modalContext; myFocusOwners = focusOwners; myHeaderAlwaysFocusable = headerAlwaysFocusable; myMovable = movable; ActiveIcon actualIcon = titleIcon == null ? new ActiveIcon(EmptyIcon.ICON_0) : titleIcon; myHeaderPanel = new JPanel(new BorderLayout()); if (caption != null) { if (!caption.isEmpty()) { myCaption = new TitlePanel(actualIcon.getRegular(), actualIcon.getInactive()); ((TitlePanel)myCaption).setText(caption); } else { myCaption = new CaptionPanel(); } if (pinCallback != null) { Icon icon = ToolWindowManagerEx.getInstanceEx(myProject != null ? myProject : ProjectUtil.guessCurrentProject((JComponent)myOwner)) .getLocationIcon(ToolWindowId.FIND, AllIcons.General.Pin_tab); myCaption.setButtonComponent(new InplaceButton( new IconButton(IdeBundle.message("show.in.find.window.button.name"), icon), e -> pinCallback.process(this) ), JBUI.Borders.empty(4)); } else if (cancelButton != null) { myCaption.setButtonComponent(new InplaceButton(cancelButton, e -> cancel()), JBUI.Borders.empty(4)); } else if (commandButton != null) { myCaption.setButtonComponent(commandButton, null); } } else { myCaption = new CaptionPanel(); myCaption.setBorder(null); myCaption.setPreferredSize(JBUI.emptySize()); } setWindowActive(myHeaderAlwaysFocusable); myHeaderPanel.add(myCaption, BorderLayout.NORTH); myContent.add(myHeaderPanel, BorderLayout.NORTH); myForcedHeavyweight = true; myResizable = resizable; myPreferredFocusedComponent = preferredFocusedComponent; myRequestFocus = requestFocus; myFocusable = focusable; myDimensionServiceKey = dimensionServiceKey; myCallBack = callback; myCancelOnClickOutside = cancelOnClickOutside; myCancelOnMouseOutCallback = cancelOnMouseOutCallback; myListeners = listeners == null ? new HashSet<>() : listeners; myUseDimServiceForXYLocation = useDimServiceForXYLocation; myCancelOnWindow = cancelOnWindow; myMinSize = minSize; for (Pair<ActionListener, KeyStroke> pair : keyboardActions) { myContent.registerKeyboardAction(pair.getFirst(), pair.getSecond(), JComponent.WHEN_IN_FOCUSED_WINDOW); } if (settingsButtons != null) { myCaption.addSettingsComponent(settingsButtons); } myKeyEventHandler = keyEventHandler; debugState("popup initialized", State.NEW); myState = State.INIT; return this; } private void setWindowActive(boolean active) { boolean value = myHeaderAlwaysFocusable || active; if (myCaption != null) { myCaption.setActive(value); } myPopupBorder.setActive(value); myContent.repaint(); } @NotNull protected MyContentPanel createContentPanel(final boolean resizable, PopupBorder border, boolean isToDrawMacCorner) { return new MyContentPanel(border); } public void setShowHints(boolean show) { final Window ancestor = getContentWindow(myComponent); if (ancestor instanceof RootPaneContainer) { final JRootPane rootPane = ((RootPaneContainer)ancestor).getRootPane(); if (rootPane != null) { rootPane.putClientProperty(SHOW_HINTS, show); } } } public String getDimensionServiceKey() { return myDimensionServiceKey; } public void setDimensionServiceKey(@Nullable final String dimensionServiceKey) { myDimensionServiceKey = dimensionServiceKey; } public void setAdText(@NotNull final String s) { setAdText(s, SwingConstants.LEFT); } @NotNull public PopupBorder getPopupBorder() { return myPopupBorder; } @Override public void setAdText(@NotNull final String s, int alignment) { if (myAdComponent == null) { myAdComponent = HintUtil.createAdComponent(s, JBUI.CurrentTheme.Advertiser.border(), alignment); JPanel wrapper = new JPanel(new BorderLayout()); wrapper.setOpaque(false); wrapper.add(myAdComponent, BorderLayout.CENTER); myContent.add(wrapper, BorderLayout.SOUTH); pack(false, true); } else { myAdComponent.setText(s); myAdComponent.setHorizontalAlignment(alignment); } } public static Point getCenterOf(final Component aContainer, final JComponent content) { return getCenterOf(aContainer, content.getPreferredSize()); } private static Point getCenterOf(@NotNull Component aContainer, @NotNull Dimension contentSize) { final JComponent component = getTargetComponent(aContainer); Rectangle visibleBounds = component != null ? component.getVisibleRect() : new Rectangle(aContainer.getSize()); Point containerScreenPoint = visibleBounds.getLocation(); SwingUtilities.convertPointToScreen(containerScreenPoint, aContainer); visibleBounds.setLocation(containerScreenPoint); return UIUtil.getCenterPoint(visibleBounds, contentSize); } @Override public void showCenteredInCurrentWindow(@NotNull Project project) { if (UiInterceptors.tryIntercept(this)) return; Window window = null; Component focusedComponent = getWndManager().getFocusedComponent(project); if (focusedComponent != null) { Component parent = UIUtil.findUltimateParent(focusedComponent); if (parent instanceof Window) { window = (Window)parent; } } if (window == null) { window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); } if (window != null && window.isShowing()) { showInCenterOf(window); } } @Override public void showInCenterOf(@NotNull Component aComponent) { HelpTooltip.setMasterPopup(aComponent, this); Point popupPoint = getCenterOf(aComponent, getPreferredContentSize()); show(aComponent, popupPoint.x, popupPoint.y, false); } @Override public void showUnderneathOf(@NotNull Component aComponent) { show(new RelativePoint(aComponent, new Point(JBUIScale.scale(2), aComponent.getHeight()))); } @Override public void show(@NotNull RelativePoint aPoint) { if (UiInterceptors.tryIntercept(this)) return; HelpTooltip.setMasterPopup(aPoint.getOriginalComponent(), this); Point screenPoint = aPoint.getScreenPoint(); show(aPoint.getComponent(), screenPoint.x, screenPoint.y, false); } @Override public void showInScreenCoordinates(@NotNull Component owner, @NotNull Point point) { show(owner, point.x, point.y, false); } @NotNull @Override public Point getBestPositionFor(@NotNull DataContext dataContext) { final Editor editor = CommonDataKeys.EDITOR.getData(dataContext); if (editor != null && editor.getComponent().isShowing()) { return getBestPositionFor(editor).getScreenPoint(); } return relativePointByQuickSearch(dataContext).getScreenPoint(); } @Override public void showInBestPositionFor(@NotNull DataContext dataContext) { final Editor editor = CommonDataKeys.EDITOR_EVEN_IF_INACTIVE.getData(dataContext); if (editor != null && editor.getComponent().isShowing()) { showInBestPositionFor(editor); } else { show(relativePointByQuickSearch(dataContext)); } } @Override public void showInFocusCenter() { final Component focused = getWndManager().getFocusedComponent(myProject); if (focused != null) { showInCenterOf(focused); } else { final WindowManager manager = WindowManager.getInstance(); final JFrame frame = myProject != null ? manager.getFrame(myProject) : manager.findVisibleFrame(); showInCenterOf(frame.getRootPane()); } } @NotNull private RelativePoint relativePointByQuickSearch(@NotNull DataContext dataContext) { Rectangle dominantArea = PlatformDataKeys.DOMINANT_HINT_AREA_RECTANGLE.getData(dataContext); if (dominantArea != null) { final Component focusedComponent = getWndManager().getFocusedComponent(myProject); if (focusedComponent != null) { Window window = SwingUtilities.windowForComponent(focusedComponent); JLayeredPane layeredPane; if (window instanceof JFrame) { layeredPane = ((JFrame)window).getLayeredPane(); } else if (window instanceof JDialog) { layeredPane = ((JDialog)window).getLayeredPane(); } else if (window instanceof JWindow) { layeredPane = ((JWindow)window).getLayeredPane(); } else { throw new IllegalStateException("cannot find parent window: project=" + myProject + "; window=" + window); } return relativePointWithDominantRectangle(layeredPane, dominantArea); } } RelativePoint location; Component contextComponent = dataContext.getData(PlatformDataKeys.CONTEXT_COMPONENT); if (contextComponent == myComponent) { location = new RelativePoint(myComponent, new Point()); } else { location = JBPopupFactory.getInstance().guessBestPopupLocation(dataContext); } if (myLocateWithinScreen) { Point screenPoint = location.getScreenPoint(); Rectangle rectangle = new Rectangle(screenPoint, getSizeForPositioning()); Rectangle screen = ScreenUtil.getScreenRectangle(screenPoint); ScreenUtil.moveToFit(rectangle, screen, null); location = new RelativePoint(rectangle.getLocation()).getPointOn(location.getComponent()); } return location; } private Dimension getSizeForPositioning() { Dimension size = getSize(); if (size == null) { size = getStoredSize(); } if (size == null) { size = myContent.getPreferredSize(); } return size; } @Override public void showInBestPositionFor(@NotNull Editor editor) { // Intercept before the following assert; otherwise assertion may fail if (UiInterceptors.tryIntercept(this)) return; assert editor.getComponent().isShowing() : "Editor must be showing on the screen"; // Set the accessible parent so that screen readers don't announce // a window context change -- the tooltip is "logically" hosted // inside the component (e.g. editor) it appears on top of. AccessibleContextUtil.setParent((Component)myComponent, editor.getContentComponent()); show(getBestPositionFor(editor)); } @NotNull private RelativePoint getBestPositionFor(@NotNull Editor editor) { DataContext context = ((EditorEx)editor).getDataContext(); Rectangle dominantArea = PlatformDataKeys.DOMINANT_HINT_AREA_RECTANGLE.getData(context); if (dominantArea != null && !myRequestFocus) { final JLayeredPane layeredPane = editor.getContentComponent().getRootPane().getLayeredPane(); return relativePointWithDominantRectangle(layeredPane, dominantArea); } else { return guessBestPopupLocation(editor); } } @NotNull private RelativePoint guessBestPopupLocation(@NotNull Editor editor) { RelativePoint preferredLocation = JBPopupFactory.getInstance().guessBestPopupLocation(editor); Dimension targetSize = getSizeForPositioning(); Point preferredPoint = preferredLocation.getScreenPoint(); Point result = getLocationAboveEditorLineIfPopupIsClippedAtTheBottom(preferredPoint, targetSize, editor); if (myLocateWithinScreen) { Rectangle rectangle = new Rectangle(result, targetSize); Rectangle screen = ScreenUtil.getScreenRectangle(preferredPoint); ScreenUtil.moveToFit(rectangle, screen, null); result = rectangle.getLocation(); } return toRelativePoint(result, preferredLocation.getComponent()); } @NotNull private static RelativePoint toRelativePoint(@NotNull Point screenPoint, @Nullable Component component) { if (component == null) { return RelativePoint.fromScreen(screenPoint); } SwingUtilities.convertPointFromScreen(screenPoint, component); return new RelativePoint(component, screenPoint); } @NotNull private static Point getLocationAboveEditorLineIfPopupIsClippedAtTheBottom(@NotNull Point originalLocation, @NotNull Dimension popupSize, @NotNull Editor editor) { Rectangle preferredBounds = new Rectangle(originalLocation, popupSize); Rectangle adjustedBounds = new Rectangle(preferredBounds); ScreenUtil.moveRectangleToFitTheScreen(adjustedBounds); if (preferredBounds.y - adjustedBounds.y <= 0) { return originalLocation; } int adjustedY = preferredBounds.y - editor.getLineHeight() - popupSize.height; if (adjustedY < 0) { return originalLocation; } return new Point(preferredBounds.x, adjustedY); } protected void addPopupListener(JBPopupListener listener) { myListeners.add(listener); } private RelativePoint relativePointWithDominantRectangle(final JLayeredPane layeredPane, final Rectangle bounds) { Dimension size = getSizeForPositioning(); List<Supplier<Point>> optionsToTry = Arrays.asList(() -> new Point(bounds.x + bounds.width, bounds.y), () -> new Point(bounds.x - size.width, bounds.y)); for (Supplier<Point> option : optionsToTry) { Point location = option.get(); SwingUtilities.convertPointToScreen(location, layeredPane); Point adjustedLocation = fitToScreenAdjustingVertically(location, size); if (adjustedLocation != null) return new RelativePoint(adjustedLocation).getPointOn(layeredPane); } setDimensionServiceKey(null); // going to cut width Point rightTopCorner = new Point(bounds.x + bounds.width, bounds.y); final Point rightTopCornerScreen = (Point)rightTopCorner.clone(); SwingUtilities.convertPointToScreen(rightTopCornerScreen, layeredPane); Rectangle screen = ScreenUtil.getScreenRectangle(rightTopCornerScreen.x, rightTopCornerScreen.y); final int spaceOnTheLeft = bounds.x; final int spaceOnTheRight = screen.x + screen.width - rightTopCornerScreen.x; if (spaceOnTheLeft > spaceOnTheRight) { myComponent.setPreferredSize(new Dimension(spaceOnTheLeft, Math.max(size.height, JBUIScale.scale(200)))); return new RelativePoint(layeredPane, new Point(0, bounds.y)); } else { myComponent.setPreferredSize(new Dimension(spaceOnTheRight, Math.max(size.height, JBUIScale.scale(200)))); return new RelativePoint(layeredPane, rightTopCorner); } } // positions are relative to screen @Nullable private static Point fitToScreenAdjustingVertically(@NotNull Point position, @NotNull Dimension size) { Rectangle screenRectangle = ScreenUtil.getScreenRectangle(position); Rectangle rectangle = new Rectangle(position, size); if (rectangle.height > screenRectangle.height || rectangle.x < screenRectangle.x || rectangle.x + rectangle.width > screenRectangle.x + screenRectangle.width) { return null; } ScreenUtil.moveToFit(rectangle, screenRectangle, null); return rectangle.getLocation(); } @NotNull private Dimension getPreferredContentSize() { if (myForcedSize != null) { return myForcedSize; } Dimension size = getStoredSize(); if (size != null) return size; return myComponent.getPreferredSize(); } @Override public final void closeOk(@Nullable InputEvent e) { setOk(true); myFinalRunnable = FunctionUtil.composeRunnables(myOkHandler, myFinalRunnable); cancel(e); } @Override public final void cancel() { InputEvent inputEvent = null; AWTEvent event = IdeEventQueue.getInstance().getTrueCurrentEvent(); if (event instanceof InputEvent && myPopup != null) { InputEvent ie = (InputEvent)event; Window window = myPopup.getWindow(); if (window != null && UIUtil.isDescendingFrom(ie.getComponent(), window)) { inputEvent = ie; } } cancel(inputEvent); } @Override public void setRequestFocus(boolean requestFocus) { myRequestFocus = requestFocus; } @Override public void cancel(InputEvent e) { if (myState == State.CANCEL || myState == State.DISPOSE) { return; } debugState("cancel popup", State.SHOWN); myState = State.CANCEL; if (isDisposed()) return; if (myPopup != null) { if (!canClose()) { debugState("cannot cancel popup", State.CANCEL); myState = State.SHOWN; return; } storeDimensionSize(); if (myUseDimServiceForXYLocation) { final JRootPane root = myComponent.getRootPane(); if (root != null) { Point location = getLocationOnScreen(root.getParent()); if (location != null) { storeLocation(fixLocateByContent(location, true)); } } } if (e instanceof MouseEvent) { IdeEventQueue.getInstance().blockNextEvents((MouseEvent)e); } myPopup.hide(false); if (ApplicationManager.getApplication() != null) { StackingPopupDispatcher.getInstance().onPopupHidden(this); } disposePopup(); } if (myListeners != null) { for (JBPopupListener each : myListeners) { each.onClosed(new LightweightWindowEvent(this, myOk)); } } Disposer.dispose(this, false); if (myProjectDisposable != null) { Disposer.dispose(myProjectDisposable); } } private void disposePopup() { all.remove(this); if (myPopup != null) { resetWindow(); myPopup.hide(true); } myPopup = null; } @Override public boolean canClose() { return myCallBack == null || myCallBack.compute().booleanValue(); } @Override public boolean isVisible() { if (myPopup == null) return false; Window window = myPopup.getWindow(); if (window != null && window.isShowing()) return true; if (LOG.isDebugEnabled()) LOG.debug("window hidden, popup's state: " + myState); return false; } @Override public void show(@NotNull final Component owner) { show(owner, -1, -1, true); } public void show(@NotNull Component owner, int aScreenX, int aScreenY, final boolean considerForcedXY) { if (UiInterceptors.tryIntercept(this)) return; if (ApplicationManager.getApplication() != null && ApplicationManager.getApplication().isHeadlessEnvironment()) return; if (isDisposed()) { throw new IllegalStateException("Popup was already disposed. Recreate a new instance to show again"); } ApplicationManager.getApplication().assertIsDispatchThread(); assert myState == State.INIT : "Popup was already shown. Recreate a new instance to show again."; debugState("show popup", State.INIT); myState = State.SHOWING; installProjectDisposer(); addActivity(); final boolean shouldShow = beforeShow(); if (!shouldShow) { removeActivity(); debugState("rejected to show popup", State.SHOWING); myState = State.INIT; return; } prepareToShow(); installWindowHook(this); Dimension sizeToSet = getStoredSize(); if (myForcedSize != null) { sizeToSet = myForcedSize; } Rectangle screen = ScreenUtil.getScreenRectangle(aScreenX, aScreenY); if (myLocateWithinScreen) { Dimension preferredSize = myContent.getPreferredSize(); Object o = myContent.getClientProperty(FIRST_TIME_SIZE); if (sizeToSet == null && o instanceof Dimension) { int w = ((Dimension)o).width; int h = ((Dimension)o).height; if (w > 0) preferredSize.width = w; if (h > 0) preferredSize.height = h; sizeToSet = preferredSize; } Dimension size = sizeToSet != null ? sizeToSet : preferredSize; if (size.width > screen.width) { size.width = screen.width; sizeToSet = size; } if (size.height > screen.height) { size.height = screen.height; sizeToSet = size; } } if (sizeToSet != null) { JBInsets.addTo(sizeToSet, myContent.getInsets()); sizeToSet.width = Math.max(sizeToSet.width, myContent.getMinimumSize().width); sizeToSet.height = Math.max(sizeToSet.height, myContent.getMinimumSize().height); myContent.setSize(sizeToSet); myContent.setPreferredSize(sizeToSet); } Point xy = new Point(aScreenX, aScreenY); boolean adjustXY = true; if (myUseDimServiceForXYLocation) { Point storedLocation = getStoredLocation(); if (storedLocation != null) { xy = storedLocation; adjustXY = false; } } if (adjustXY) { final Insets insets = myContent.getInsets(); if (insets != null) { xy.x -= insets.left; xy.y -= insets.top; } } if (considerForcedXY && myForcedLocation != null) { xy = myForcedLocation; } fixLocateByContent(xy, false); Rectangle targetBounds = new Rectangle(xy, myContent.getPreferredSize()); if (targetBounds.width > screen.width || targetBounds.height > screen.height) { StringBuilder sb = new StringBuilder("popup preferred size is bigger than screen: "); sb.append(targetBounds.width).append("x").append(targetBounds.height); IJSwingUtilities.appendComponentClassNames(sb, myContent); LOG.warn(sb.toString()); } Rectangle original = new Rectangle(targetBounds); if (myLocateWithinScreen) { ScreenUtil.moveToFit(targetBounds, screen, null); } if (myMouseOutCanceller != null) { myMouseOutCanceller.myEverEntered = targetBounds.equals(original); } myOwner = getFrameOrDialog(owner); // use correct popup owner for non-modal dialogs too if (myOwner == null) { myOwner = owner; } myRequestorComponent = owner; boolean forcedDialog = myMayBeParent || SystemInfo.isMac && !(myOwner instanceof IdeFrame) && myOwner != null && myOwner.isShowing(); PopupComponent.Factory factory = getFactory(myForcedHeavyweight || myResizable, forcedDialog); myNativePopup = factory.isNativePopup(); Component popupOwner = myOwner; if (popupOwner instanceof RootPaneContainer && !(popupOwner instanceof IdeFrame && !Registry.is("popup.fix.ide.frame.owner"))) { // JDK uses cached heavyweight popup for a window ancestor RootPaneContainer root = (RootPaneContainer)popupOwner; popupOwner = root.getRootPane(); LOG.debug("popup owner fixed for JDK cache"); } if (LOG.isDebugEnabled()) { LOG.debug("expected preferred size: " + myContent.getPreferredSize()); } myPopup = factory.getPopup(popupOwner, myContent, targetBounds.x, targetBounds.y, this); if (LOG.isDebugEnabled()) { LOG.debug(" actual preferred size: " + myContent.getPreferredSize()); } if (targetBounds.width != myContent.getWidth() || targetBounds.height != myContent.getHeight()) { // JDK uses cached heavyweight popup that is not initialized properly LOG.debug("the expected size is not equal to the actual size"); Window popup = myPopup.getWindow(); if (popup != null) { popup.setSize(targetBounds.width, targetBounds.height); if (myContent.getParent().getComponentCount() != 1) { LOG.debug("unexpected count of components in heavy-weight popup"); } } else { LOG.debug("cannot fix size for non-heavy-weight popup"); } } if (myResizable) { final JRootPane root = myContent.getRootPane(); final IdeGlassPaneImpl glass = new IdeGlassPaneImpl(root); root.setGlassPane(glass); int i = Registry.intValue("ide.popup.resizable.border.sensitivity", 4); WindowResizeListener resizeListener = new WindowResizeListener( myComponent, myMovable ? JBUI.insets(i) : JBUI.insets(0, 0, i, i), null) { private Cursor myCursor; @Override protected void setCursor(Component content, Cursor cursor) { if (myCursor != cursor || myCursor != Cursor.getDefaultCursor()) { glass.setCursor(cursor, this); myCursor = cursor; if (content instanceof JComponent) { IdeGlassPaneImpl.savePreProcessedCursor((JComponent)content, content.getCursor()); } super.setCursor(content, cursor); } } @Override protected void notifyResized() { myResizeListeners.forEach(Runnable::run); } }; glass.addMousePreprocessor(resizeListener, this); glass.addMouseMotionPreprocessor(resizeListener, this); myResizeListener = resizeListener; } if (myCaption != null && myMovable) { final WindowMoveListener moveListener = new WindowMoveListener(myCaption) { @Override public void mousePressed(final MouseEvent e) { if (e.isConsumed()) return; if (UIUtil.isCloseClick(e) && myCaption.isWithinPanel(e)) { cancel(); } else { super.mousePressed(e); } } }; myCaption.addMouseListener(moveListener); myCaption.addMouseMotionListener(moveListener); final MyContentPanel saved = myContent; Disposer.register(this, () -> { ListenerUtil.removeMouseListener(saved, moveListener); ListenerUtil.removeMouseMotionListener(saved, moveListener); }); myMoveListener = moveListener; } for (JBPopupListener listener : myListeners) { listener.beforeShown(new LightweightWindowEvent(this)); } myPopup.setRequestFocus(myRequestFocus); final Window window = getContentWindow(myContent); if (window instanceof IdeFrame) { LOG.warn("Lightweight popup is shown using AbstractPopup class. But this class is not supposed to work with lightweight popups."); } window.setFocusableWindowState(myRequestFocus); window.setFocusable(myRequestFocus); // Swing popup default always on top state is set in true window.setAlwaysOnTop(false); if (myFocusable) { FocusTraversalPolicy focusTraversalPolicy = new FocusTraversalPolicy() { @Override public Component getComponentAfter(Container aContainer, Component aComponent) { return getComponent(); } private Component getComponent() { return myPreferredFocusedComponent == null ? myComponent : myPreferredFocusedComponent; } @Override public Component getComponentBefore(Container aContainer, Component aComponent) { return getComponent(); } @Override public Component getFirstComponent(Container aContainer) { return getComponent(); } @Override public Component getLastComponent(Container aContainer) { return getComponent(); } @Override public Component getDefaultComponent(Container aContainer) { return getComponent(); } }; window.setFocusTraversalPolicy(focusTraversalPolicy); Disposer.register(this, () -> window.setFocusTraversalPolicy(null)); } window.setAutoRequestFocus(myRequestFocus); final String data = getUserData(String.class); final boolean popupIsSimpleWindow = "TRUE".equals(getContent().getClientProperty("BookmarkPopup")); myContent.getRootPane().putClientProperty("SIMPLE_WINDOW", "SIMPLE_WINDOW".equals(data) || popupIsSimpleWindow); myWindow = window; if (myNormalWindowLevel) { myWindow.setType(Window.Type.NORMAL); } setMinimumSize(myMinSize); final Disposable tb = TouchBarsManager.showPopupBar(this, myContent); if (tb != null) Disposer.register(this, tb); myPopup.show(); Rectangle bounds = window.getBounds(); PopupLocationTracker.register(this); if (bounds.width > screen.width || bounds.height > screen.height) { ScreenUtil.fitToScreen(bounds); window.setBounds(bounds); } WindowAction.setEnabledFor(myPopup.getWindow(), myResizable); myWindowListener = new MyWindowListener(); window.addWindowListener(myWindowListener); if (myWindow != null) { // dialog wrapper-based popups do this internally through peer, // for other popups like jdialog-based we should exclude them manually, but // we still have to be able to use IdeFrame as parent if (!myMayBeParent && !(myWindow instanceof Frame)) { WindowManager.getInstance().doNotSuggestAsParent(myWindow); } } final Runnable afterShow = () -> { if (isDisposed()) { LOG.debug("popup is disposed after showing"); removeActivity(); return; } if ((myPreferredFocusedComponent instanceof AbstractButton || myPreferredFocusedComponent instanceof JTextField) && myFocusable) { IJSwingUtilities.moveMousePointerOn(myPreferredFocusedComponent); } removeActivity(); afterShow(); }; if (myRequestFocus) { if (myPreferredFocusedComponent != null) { myPreferredFocusedComponent.requestFocus(); } else { _requestFocus(); } window.setAutoRequestFocus(myRequestFocus); SwingUtilities.invokeLater(afterShow); } else { //noinspection SSBasedInspection SwingUtilities.invokeLater(() -> { if (isDisposed()) { removeActivity(); return; } afterShow.run(); }); } debugState("popup shown", State.SHOWING); myState = State.SHOWN; afterShowSync(); } public void focusPreferredComponent() { _requestFocus(); } private void installProjectDisposer() { final Component c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (c != null) { final DataContext context = DataManager.getInstance().getDataContext(c); final Project project = CommonDataKeys.PROJECT.getData(context); if (project != null) { myProjectDisposable = () -> { if (!isDisposed()) { Disposer.dispose(this); } }; Disposer.register(project, myProjectDisposable); } } } //Sometimes just after popup was shown the WINDOW_ACTIVATED cancels it private static void installWindowHook(final AbstractPopup popup) { if (popup.myCancelOnWindow) { popup.myCancelOnWindow = false; new Alarm(popup).addRequest(() -> popup.myCancelOnWindow = true, 100); } } private void addActivity() { UiActivityMonitor.getInstance().addActivity(myActivityKey); } private void removeActivity() { UiActivityMonitor.getInstance().removeActivity(myActivityKey); } protected void prepareToShow() { final MouseAdapter mouseAdapter = new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Rectangle bounds = getBoundsOnScreen(myContent); if (bounds != null) { bounds.x -= 2; bounds.y -= 2; bounds.width += 4; bounds.height += 4; } if (bounds == null || !bounds.contains(e.getLocationOnScreen())) { cancel(); } } }; myContent.addMouseListener(mouseAdapter); Disposer.register(this, () -> myContent.removeMouseListener(mouseAdapter)); myContent.addKeyListener(mySpeedSearch); if (myCancelOnMouseOutCallback != null || myCancelOnWindow) { myMouseOutCanceller = new Canceller(); Toolkit.getDefaultToolkit().addAWTEventListener(myMouseOutCanceller, MOUSE_EVENT_MASK | WINDOW_ACTIVATED | WINDOW_GAINED_FOCUS | MOUSE_MOTION_EVENT_MASK); } ChildFocusWatcher focusWatcher = new ChildFocusWatcher(myContent) { @Override protected void onFocusGained(final FocusEvent event) { setWindowActive(true); } @Override protected void onFocusLost(final FocusEvent event) { setWindowActive(false); } }; Disposer.register(this, focusWatcher); mySpeedSearchPatternField = new SearchTextField(false) { @Override protected void onFieldCleared() { mySpeedSearch.reset(); } }; mySpeedSearchPatternField.getTextEditor().setFocusable(mySpeedSearchAlwaysShown); if (mySpeedSearchAlwaysShown) { setHeaderComponent(mySpeedSearchPatternField); mySpeedSearchPatternField.setBorder(JBUI.Borders.customLine(JBUI.CurrentTheme.BigPopup.searchFieldBorderColor(), 1, 0, 1, 0)); mySpeedSearchPatternField.getTextEditor().setBorder(JBUI.Borders.empty()); } if (SystemInfo.isMac) { RelativeFont.TINY.install(mySpeedSearchPatternField); } } private Window updateMaskAndAlpha(Window window) { if (window == null) return null; if (!window.isDisplayable() || !window.isShowing()) return window; final WindowManagerEx wndManager = getWndManager(); if (wndManager == null) return window; if (!wndManager.isAlphaModeEnabled(window)) return window; if (myAlpha != myLastAlpha) { wndManager.setAlphaModeRatio(window, myAlpha); myLastAlpha = myAlpha; } if (myMaskProvider != null) { final Dimension size = window.getSize(); Shape mask = myMaskProvider.getMask(size); wndManager.setWindowMask(window, mask); } WindowManagerEx.WindowShadowMode mode = myShadowed ? WindowManagerEx.WindowShadowMode.NORMAL : WindowManagerEx.WindowShadowMode.DISABLED; WindowManagerEx.getInstanceEx().setWindowShadow(window, mode); return window; } private static WindowManagerEx getWndManager() { return ApplicationManager.getApplication() != null ? WindowManagerEx.getInstanceEx() : null; } @Override public boolean isDisposed() { return myContent == null; } protected boolean beforeShow() { if (ApplicationManager.getApplication() == null) return true; StackingPopupDispatcher.getInstance().onPopupShown(this, myInStack); return true; } protected void afterShow() { } protected void afterShowSync() { } protected final boolean requestFocus() { if (!myFocusable) return false; getFocusManager().doWhenFocusSettlesDown(() -> _requestFocus()); return true; } private void _requestFocus() { if (!myFocusable) return; JComponent toFocus = ObjectUtils.chooseNotNull(myPreferredFocusedComponent, mySpeedSearchAlwaysShown ? mySpeedSearchPatternField : null); if (toFocus != null) { IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> { if (!myDisposed) { IdeFocusManager.getGlobalInstance().requestFocus(toFocus, true); } }); } } private IdeFocusManager getFocusManager() { if (myProject != null) { return IdeFocusManager.getInstance(myProject); } if (myOwner != null) { return IdeFocusManager.findInstanceByComponent(myOwner); } return IdeFocusManager.findInstance(); } private static JComponent getTargetComponent(Component aComponent) { if (aComponent instanceof JComponent) { return (JComponent)aComponent; } if (aComponent instanceof RootPaneContainer) { return ((RootPaneContainer)aComponent).getRootPane(); } LOG.error("Cannot find target for:" + aComponent); return null; } private PopupComponent.Factory getFactory(boolean forceHeavyweight, boolean forceDialog) { if (Registry.is("allow.dialog.based.popups")) { boolean noFocus = !myFocusable || !myRequestFocus; boolean cannotBeDialog = noFocus; // && SystemInfo.isXWindow if (!cannotBeDialog && (isPersistent() || forceDialog)) { return new PopupComponent.Factory.Dialog(); } } if (forceHeavyweight) { return new PopupComponent.Factory.AwtHeavyweight(); } return new PopupComponent.Factory.AwtDefault(); } @NotNull @Override public JComponent getContent() { return myContent; } public void setLocation(RelativePoint p) { if (isBusy()) return; setLocation(p, myPopup); } private static void setLocation(final RelativePoint p, final PopupComponent popup) { if (popup == null) return; final Window wnd = popup.getWindow(); assert wnd != null; wnd.setLocation(p.getScreenPoint()); } @Override public void pack(boolean width, boolean height) { if (!isVisible() || !width && !height || isBusy()) return; Dimension size = getSize(); Dimension prefSize = myContent.computePreferredSize(); Point location = !myLocateWithinScreen ? null : getLocationOnScreen(); Rectangle screen = location == null ? null : ScreenUtil.getScreenRectangle(location); if (width) { size.width = prefSize.width; if (screen != null) { int delta = screen.width + screen.x - location.x; if (size.width > delta) { size.width = delta; if (!SystemInfo.isMac || Registry.is("mac.scroll.horizontal.gap")) { // we shrank horizontally - need to increase height to fit the horizontal scrollbar JScrollPane scrollPane = ScrollUtil.findScrollPane(myContent); if (scrollPane != null && scrollPane.getHorizontalScrollBarPolicy() != ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) { JScrollBar scrollBar = scrollPane.getHorizontalScrollBar(); if (scrollBar != null) { prefSize.height += scrollBar.getPreferredSize().height; } } } } } } if (height) { size.height = prefSize.height; if (screen != null) { int delta = screen.height + screen.y - location.y; if (size.height > delta) { size.height = delta; } } } size.height += getAdComponentHeight(); final Window window = getContentWindow(myContent); if (window != null) { window.setSize(size); } } public JComponent getComponent() { return myComponent; } public Project getProject() { return myProject; } @Override public void dispose() { if (myState == State.SHOWN) { LOG.debug("shown popup must be cancelled"); cancel(); } if (myState == State.DISPOSE) { return; } debugState("dispose popup", State.INIT, State.CANCEL); myState = State.DISPOSE; if (myDisposed) { return; } myDisposed = true; if (LOG.isDebugEnabled()) { LOG.debug("start disposing " + myContent); } Disposer.dispose(this, false); ApplicationManager.getApplication().assertIsDispatchThread(); if (myPopup != null) { cancel(myDisposeEvent); } if (myContent != null) { Container parent = myContent.getParent(); if (parent != null) parent.remove(myContent); myContent.removeAll(); myContent.removeKeyListener(mySpeedSearch); } myContent = null; myPreferredFocusedComponent = null; myComponent = null; myCallBack = null; myListeners = null; if (myMouseOutCanceller != null) { final Toolkit toolkit = Toolkit.getDefaultToolkit(); // it may happen, but have no idea how if (toolkit != null) { toolkit.removeAWTEventListener(myMouseOutCanceller); } } myMouseOutCanceller = null; if (myFinalRunnable != null) { final ActionCallback typeAheadDone = new ActionCallback(); IdeFocusManager.getInstance(myProject).typeAheadUntil(typeAheadDone, "Abstract Popup Disposal"); ModalityState modalityState = ModalityState.current(); Runnable finalRunnable = myFinalRunnable; getFocusManager().doWhenFocusSettlesDown(() -> { if (ModalityState.current().equals(modalityState)) { typeAheadDone.setDone(); ((TransactionGuardImpl)TransactionGuard.getInstance()).performUserActivity(finalRunnable); } else { typeAheadDone.setRejected(); LOG.debug("Final runnable of popup is skipped"); } // Otherwise the UI has changed unexpectedly and the action is likely not applicable. // And we don't want finalRunnable to perform potentially destructive actions // in the context of a suddenly appeared modal dialog. }); myFinalRunnable = null; } if (LOG.isDebugEnabled()) { LOG.debug("stop disposing content"); } } private void resetWindow() { if (myWindow != null && getWndManager() != null) { getWndManager().resetWindow(myWindow); if (myWindowListener != null) { myWindow.removeWindowListener(myWindowListener); } if (myWindow instanceof RootPaneContainer) { RootPaneContainer container = (RootPaneContainer)myWindow; JRootPane root = container.getRootPane(); root.putClientProperty(KEY, null); if (root.getGlassPane() instanceof IdeGlassPaneImpl) { // replace installed glass pane with the default one: JRootPane.createGlassPane() JPanel glass = new JPanel(); glass.setName(root.getName() + ".glassPane"); glass.setVisible(false); glass.setOpaque(false); root.setGlassPane(glass); } } myWindow = null; myWindowListener = null; } } public void storeDimensionSize() { if (myDimensionServiceKey != null) { Dimension size = myContent.getSize(); JBInsets.removeFrom(size, myContent.getInsets()); getWindowStateService(myProject).putSize(myDimensionServiceKey, size); } } private void storeLocation(final Point xy) { if (myDimensionServiceKey != null) { getWindowStateService(myProject).putLocation(myDimensionServiceKey, xy); } } public static class MyContentPanel extends JPanel implements DataProvider { @Nullable private DataProvider myDataProvider; /** * @deprecated use {@link MyContentPanel#MyContentPanel(PopupBorder)} */ @Deprecated public MyContentPanel(final boolean resizable, final PopupBorder border, boolean drawMacCorner) { this(border); } public MyContentPanel(PopupBorder border) { super(new BorderLayout()); putClientProperty(UIUtil.TEXT_COPY_ROOT, Boolean.TRUE); setBorder(border); } public Dimension computePreferredSize() { if (isPreferredSizeSet()) { Dimension setSize = getPreferredSize(); setPreferredSize(null); Dimension result = getPreferredSize(); setPreferredSize(setSize); return result; } return getPreferredSize(); } @Nullable @Override public Object getData(@NotNull @NonNls String dataId) { return myDataProvider != null ? myDataProvider.getData(dataId) : null; } public void setDataProvider(@Nullable DataProvider dataProvider) { myDataProvider = dataProvider; } } boolean isCancelOnClickOutside() { return myCancelOnClickOutside; } boolean isCancelOnWindowDeactivation() { return myCancelOnWindowDeactivation; } private class Canceller implements AWTEventListener { private boolean myEverEntered; @Override public void eventDispatched(final AWTEvent event) { switch (event.getID()) { case WINDOW_ACTIVATED: case WINDOW_GAINED_FOCUS: if (myCancelOnWindow && myPopup != null && isCancelNeeded((WindowEvent)event, myPopup.getWindow())) { cancel(); } break; case MOUSE_ENTERED: if (withinPopup(event)) { myEverEntered = true; } break; case MOUSE_MOVED: case MOUSE_PRESSED: if (myCancelOnMouseOutCallback != null && myEverEntered && !withinPopup(event)) { if (myCancelOnMouseOutCallback.check((MouseEvent)event)) { cancel(); } } break; } } private boolean withinPopup(final AWTEvent event) { final MouseEvent mouse = (MouseEvent)event; Rectangle bounds = getBoundsOnScreen(myContent); return bounds != null && bounds.contains(mouse.getLocationOnScreen()); } } @Override public void setLocation(@NotNull Point screenPoint) { if (myPopup == null) { myForcedLocation = screenPoint; } else if (!isBusy()) { final Insets insets = myContent.getInsets(); if (insets != null && (insets.top != 0 || insets.left != 0)) { screenPoint = new Point(screenPoint.x - insets.left, screenPoint.y - insets.top); } moveTo(myContent, screenPoint, myLocateByContent ? myHeaderPanel.getPreferredSize() : null); } } public static Window moveTo(JComponent content, Point screenPoint, final Dimension headerCorrectionSize) { final Window wnd = getContentWindow(content); if (wnd != null) { wnd.setCursor(Cursor.getDefaultCursor()); if (headerCorrectionSize != null) { screenPoint.y -= headerCorrectionSize.height; } wnd.setLocation(screenPoint); } return wnd; } private static Window getContentWindow(Component content) { Window window = SwingUtilities.getWindowAncestor(content); if (window == null) { if (LOG.isDebugEnabled()) { LOG.debug("no window ancestor for " + content); } } return window; } @NotNull @Override public Point getLocationOnScreen() { Window window = getContentWindow(myContent); Point screenPoint = window == null ? new Point() : window.getLocation(); fixLocateByContent(screenPoint, false); Insets insets = myContent.getInsets(); if (insets != null) { screenPoint.x += insets.left; screenPoint.y += insets.top; } return screenPoint; } @Override public void setSize(@NotNull final Dimension size) { setSize(size, true); } private void setSize(@NotNull Dimension size, boolean adjustByContent) { if (isBusy()) return; Dimension toSet = new Dimension(size); if (adjustByContent) toSet.height += getAdComponentHeight(); if (myPopup == null) { myForcedSize = toSet; } else { updateMaskAndAlpha(setSize(myContent, toSet)); } } private int getAdComponentHeight() { return myAdComponent != null ? myAdComponent.getPreferredSize().height + JBUIScale.scale(1) : 0; } @Override public Dimension getSize() { if (myPopup != null) { final Window popupWindow = getContentWindow(myContent); if (popupWindow != null) { Dimension size = popupWindow.getSize(); size.height -= getAdComponentHeight(); return size; } } return myForcedSize; } @Override public void moveToFitScreen() { if (myPopup == null || isBusy()) return; final Window popupWindow = getContentWindow(myContent); if (popupWindow == null) return; Rectangle bounds = popupWindow.getBounds(); ScreenUtil.moveRectangleToFitTheScreen(bounds); // calling #setLocation or #setSize makes the window move for a bit because of tricky computations // our aim here is to just move the window as-is to make it fit the screen // no tricks are included here popupWindow.setBounds(bounds); updateMaskAndAlpha(popupWindow); } public static Window setSize(JComponent content, final Dimension size) { final Window popupWindow = getContentWindow(content); if (popupWindow == null) return null; JBInsets.addTo(size, content.getInsets()); content.setPreferredSize(size); popupWindow.pack(); return popupWindow; } @Override public void setCaption(@NotNull String title) { if (myCaption instanceof TitlePanel) { ((TitlePanel)myCaption).setText(title); } } public void setSpeedSearchAlwaysShown(boolean value) { assert myState == State.INIT; mySpeedSearchAlwaysShown = value; } private class MyWindowListener extends WindowAdapter { @Override public void windowOpened(WindowEvent e) { updateMaskAndAlpha(myWindow); } @Override public void windowClosing(final WindowEvent e) { resetWindow(); cancel(); } } @Override public boolean isPersistent() { return !myCancelOnClickOutside && !myCancelOnWindow; } @Override public boolean isNativePopup() { return myNativePopup; } @Override public void setUiVisible(final boolean visible) { if (myPopup != null) { if (visible) { myPopup.show(); final Window window = getPopupWindow(); if (window != null && myRestoreWindowSize != null) { window.setSize(myRestoreWindowSize); myRestoreWindowSize = null; } } else { final Window window = getPopupWindow(); if (window != null) { myRestoreWindowSize = window.getSize(); window.setVisible(false); } } } } public Window getPopupWindow() { return myPopup != null ? myPopup.getWindow() : null; } public void setUserData(List<Object> userData) { myUserData = userData; } @Override public <T> T getUserData(@NotNull final Class<T> userDataClass) { if (myUserData != null) { for (Object o : myUserData) { if (userDataClass.isInstance(o)) { @SuppressWarnings("unchecked") T t = (T)o; return t; } } } return null; } @Override public boolean isModalContext() { return myModalContext; } @Override public boolean isFocused() { if (myComponent != null && isFocused(new Component[]{SwingUtilities.getWindowAncestor(myComponent)})) { return true; } return isFocused(myFocusOwners); } public static boolean isFocused(Component @Nullable [] components) { if (components == null) return false; Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (owner == null) return false; Window wnd = ComponentUtil.getWindow(owner); for (Component each : components) { if (each != null && SwingUtilities.isDescendingFrom(owner, each)) { Window eachWindow = ComponentUtil.getWindow(each); if (eachWindow == wnd) { return true; } } } return false; } @Override public boolean isCancelKeyEnabled() { return myCancelKeyEnabled; } @NotNull public CaptionPanel getTitle() { return myCaption; } protected void setHeaderComponent(JComponent c) { boolean doRevalidate = false; if (myHeaderComponent != null) { myHeaderPanel.remove(myHeaderComponent); myHeaderComponent = null; doRevalidate = true; } if (c != null) { myHeaderPanel.add(c, BorderLayout.CENTER); myHeaderComponent = c; if (isVisible()) { final Dimension size = myContent.getSize(); if (size.height < c.getPreferredSize().height * 2) { size.height += c.getPreferredSize().height; setSize(size); } } doRevalidate = true; } if (doRevalidate) myContent.revalidate(); } public void setWarning(@NotNull String text) { JBLabel label = new JBLabel(text, UIUtil.getBalloonWarningIcon(), SwingConstants.CENTER); label.setOpaque(true); Color color = HintUtil.getInformationColor(); label.setBackground(color); label.setBorder(BorderFactory.createLineBorder(color, 3)); myHeaderPanel.add(label, BorderLayout.SOUTH); } @Override public void addListener(@NotNull final JBPopupListener listener) { myListeners.add(listener); } @Override public void removeListener(@NotNull final JBPopupListener listener) { myListeners.remove(listener); } protected void onSpeedSearchPatternChanged() { } @Override public Component getOwner() { return myRequestorComponent; } @Override public void setMinimumSize(Dimension size) { //todo: consider changing only the caption panel minimum size Dimension sizeFromHeader = myHeaderPanel.getPreferredSize(); if (sizeFromHeader == null) { sizeFromHeader = myHeaderPanel.getMinimumSize(); } if (sizeFromHeader == null) { int minimumSize = myWindow.getGraphics().getFontMetrics(myHeaderPanel.getFont()).getHeight(); sizeFromHeader = new Dimension(minimumSize, minimumSize); } if (size == null) { myMinSize = sizeFromHeader; } else { final int width = Math.max(size.width, sizeFromHeader.width); final int height = Math.max(size.height, sizeFromHeader.height); myMinSize = new Dimension(width, height); } if (myWindow != null) { Rectangle screenRectangle = ScreenUtil.getScreenRectangle(myWindow.getLocation()); int width = Math.min(screenRectangle.width, myMinSize.width); int height = Math.min(screenRectangle.height, myMinSize.height); myWindow.setMinimumSize(new Dimension(width, height)); } } public void setOkHandler(Runnable okHandler) { myOkHandler = okHandler; } @Override public void setFinalRunnable(Runnable finalRunnable) { myFinalRunnable = finalRunnable; } public void setOk(boolean ok) { myOk = ok; } @Override public void setDataProvider(@NotNull DataProvider dataProvider) { if (myContent != null) { myContent.setDataProvider(dataProvider); } } @Override public boolean dispatchKeyEvent(@NotNull KeyEvent e) { BooleanFunction<? super KeyEvent> handler = myKeyEventHandler; if (handler != null && handler.fun(e)) { return true; } if (isCloseRequest(e) && myCancelKeyEnabled && !mySpeedSearch.isHoldingFilter()) { cancel(e); return true; } return false; } @NotNull public Dimension getHeaderPreferredSize() { return myHeaderPanel.getPreferredSize(); } @NotNull public Dimension getFooterPreferredSize() { return myAdComponent == null ? new Dimension(0,0) : myAdComponent.getPreferredSize(); } public static boolean isCloseRequest(KeyEvent e) { return e != null && e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_ESCAPE && e.getModifiers() == 0; } private Point fixLocateByContent(Point location, boolean save) { Dimension size = !myLocateByContent ? null : myHeaderPanel.getPreferredSize(); if (size != null) location.y -= save ? -size.height : size.height; return location; } protected boolean isBusy() { return myResizeListener != null && myResizeListener.isBusy() || myMoveListener != null && myMoveListener.isBusy(); } /** * Returns the first frame (or dialog) ancestor of the component. * Note that this method returns the component itself if it is a frame (or dialog). * * @param component the component used to find corresponding frame (or dialog) * @return the first frame (or dialog) ancestor of the component; or {@code null} * if the component is not a frame (or dialog) and is not contained inside a frame (or dialog) * * @see UIUtil#getWindow */ private static Component getFrameOrDialog(Component component) { while (component != null) { if (component instanceof Window) return component; component = component.getParent(); } return null; } @Nullable private static Point getLocationOnScreen(@Nullable Component component) { return component == null || !component.isShowing() ? null : component.getLocationOnScreen(); } @Nullable private static Rectangle getBoundsOnScreen(@Nullable Component component) { Point point = getLocationOnScreen(component); return point == null ? null : new Rectangle(point, component.getSize()); } @NotNull public static List<JBPopup> getChildPopups(@NotNull final Component component) { return ContainerUtil.filter(all.toStrongList(), popup -> { Component owner = popup.getOwner(); while (owner != null) { if (owner.equals(component)) { return true; } owner = owner.getParent(); } return false; }); } @Override public boolean canShow() { return myState == State.INIT; } @NotNull @Override public Rectangle getConsumedScreenBounds() { return myWindow.getBounds(); } @Override public Window getUnderlyingWindow() { return myWindow.getOwner(); } /** * Passed listener will be notified if popup is resized by user (using mouse) */ public void addResizeListener(@NotNull Runnable runnable, @NotNull Disposable parentDisposable) { myResizeListeners.add(runnable); Disposer.register(parentDisposable, () -> myResizeListeners.remove(runnable)); } /** * @param event a {@code WindowEvent} for the activated or focused window * @param popup a window that corresponds to the current popup * @return {@code false} if a focus moved to a popup window or its child window in the whole hierarchy */ private static boolean isCancelNeeded(@NotNull WindowEvent event, @Nullable Window popup) { Window window = event.getWindow(); // the activated or focused window while (window != null) { if (popup == window) return false; // do not close a popup, which child is activated or focused window = window.getOwner(); // consider a window owner as activated or focused } return true; } @Nullable private Point getStoredLocation() { if (myDimensionServiceKey == null) return null; return getWindowStateService(myProject).getLocation(myDimensionServiceKey); } @Nullable private Dimension getStoredSize() { if (myDimensionServiceKey == null) return null; return getWindowStateService(myProject).getSize(myDimensionServiceKey); } @NotNull private static WindowStateService getWindowStateService(@Nullable Project project) { return project == null ? WindowStateService.getInstance() : WindowStateService.getInstance(project); } }
package to.etc.domui.server; import java.io.*; import java.lang.reflect.*; import java.util.*; import javax.annotation.*; import javax.servlet.http.*; import org.slf4j.*; import to.etc.domui.ajax.*; import to.etc.domui.component.controlfactory.*; import to.etc.domui.component.delayed.*; import to.etc.domui.component.layout.*; import to.etc.domui.component.layout.title.*; import to.etc.domui.component.lookup.*; import to.etc.domui.dom.*; import to.etc.domui.dom.errors.*; import to.etc.domui.dom.header.*; import to.etc.domui.dom.html.*; import to.etc.domui.injector.*; import to.etc.domui.login.*; import to.etc.domui.parts.*; import to.etc.domui.server.parts.*; import to.etc.domui.state.*; import to.etc.domui.themes.*; import to.etc.domui.trouble.*; import to.etc.domui.util.*; import to.etc.domui.util.js.*; import to.etc.domui.util.resources.*; import to.etc.util.*; import to.etc.webapp.nls.*; import to.etc.webapp.query.*; public abstract class DomApplication { static public final Logger LOG = LoggerFactory.getLogger(DomApplication.class); @Nonnull private final PartRequestHandler m_partHandler = new PartRequestHandler(this); @Nonnull private Set<IAppSessionListener> m_appSessionListeners = new HashSet<IAppSessionListener>(); @Nullable private File m_webFilePath; @Nullable private String m_urlExtension; @Nonnull private ControlBuilder m_controlBuilder = new ControlBuilder(this); private boolean m_developmentMode; /** When T the UI will try to generate test ID's and helper thingies to easily show those IDs */ private boolean m_uiTestMode; /** When > 0, this defines that pages are automatically reloaded when changed */ private int m_autoRefreshPollInterval; /** When > 0, this defines the #of milliseconds for doing page keepalive. */ private int m_keepAliveInterval; /** The default poll interval time for pages containing Async objects (see {@link DelayedActivitiesManager}). */ private int m_defaultPollInterval = 2500; static private DomApplication m_application; static private int m_nextPageTag = (int) (System.nanoTime() & 0x7fffffff); private final boolean m_logOutput = DeveloperOptions.getBool("domui.log", false); @Nonnull private List<IRequestInterceptor> m_interceptorList = new ArrayList<IRequestInterceptor>(); /** * Contains the header contributors in the order that they were added. */ @Nonnull private List<HeaderContributorEntry> m_orderedContributorList = Collections.EMPTY_LIST; @Nonnull private List<INewPageInstantiated> m_newPageInstListeners = Collections.EMPTY_LIST; /** Timeout for a window session, in minutes. */ private int m_windowSessionTimeout = 15; /** The default expiry time for resources, in seconds. */ private int m_defaultExpiryTime = 7 * 24 * 60 * 60; private ILoginAuthenticator m_loginAuthenticator; private ILoginDialogFactory m_loginDialogFactory; @Nonnull private List<ILoginListener> m_loginListenerList = Collections.EMPTY_LIST; @Nonnull private IPageInjector m_injector = new DefaultPageInjector(); /** * Must return the "root" class of the application; the class rendered when the application's * root URL is entered without a class name. * @return */ abstract public Class< ? extends UrlPage> getRootPage(); /** * Render factories for different browser versions. */ @Nonnull private List<IHtmlRenderFactory> m_renderFactoryList = new ArrayList<IHtmlRenderFactory>(); final private String m_scriptVersion; @Nonnull private List<IResourceFactory> m_resourceFactoryList = Collections.EMPTY_LIST; @Nonnull private List<FilterRef> m_requestHandlerList = Collections.emptyList(); static final private class FilterRef { final private int m_score; @Nonnull final private IFilterRequestHandler m_handler; public FilterRef(@Nonnull IFilterRequestHandler handler, int score) { m_handler = handler; m_score = score; } public int getPriority() { return m_score; } @Nonnull public IFilterRequestHandler getHandler() { return m_handler; } } private static final Comparator<FilterRef> C_HANDLER_DESCPRIO = new Comparator<FilterRef>() { @Override public int compare(FilterRef a, FilterRef b) { return b.getPriority() - a.getPriority(); } }; @Nonnull private List<IAsyncListener< ? >> m_asyncListenerList = Collections.emptyList(); /* CODING: Initialization and session management. */ /** * The only constructor. */ public DomApplication() { m_scriptVersion = DeveloperOptions.getString("domui.scriptversion", "jquery-1.4.4"); registerControlFactories(); registerPartFactories(); initHeaderContributors(); addRenderFactory(new MsCrapwareRenderFactory()); // Add html renderers for IE <= 8 addExceptionListener(QNotFoundException.class, new IExceptionListener() { @Override public boolean handleException(final @Nonnull IRequestContext ctx, final @Nonnull Page page, final @Nullable NodeBase source, final @Nonnull Throwable x) throws Exception { if(!(x instanceof QNotFoundException)) throw new IllegalStateException("??"); // data has removed in meanwhile: redirect to error page. String rurl = DomUtil.createPageURL(ExpiredDataPage.class, new PageParameters(ExpiredDataPage.PARAM_ERRMSG, x.getLocalizedMessage())); UIGoto.redirect(rurl); return true; } }); addExceptionListener(DataAccessViolationException.class, new IExceptionListener() { @Override public boolean handleException(final @Nonnull IRequestContext ctx, final @Nonnull Page page, final @Nullable NodeBase source, final @Nonnull Throwable x) throws Exception { if(!(x instanceof DataAccessViolationException)) throw new IllegalStateException("??"); // data has removed in meanwhile: redirect to error page. String rurl = DomUtil.createPageURL(DataAccessViolationPage.class, new PageParameters(DataAccessViolationPage.PARAM_ERRMSG, x.getLocalizedMessage())); UIGoto.redirect(rurl); return true; } }); setCurrentTheme("blue/domui/blue"); setThemeFactory(SimpleThemeFactory.INSTANCE); registerResourceFactory(new ClassRefResourceFactory()); registerResourceFactory(new VersionedJsResourceFactory()); registerResourceFactory(new SimpleResourceFactory()); registerResourceFactory(new ThemeResourceFactory()); //-- Register default request handlers. addRequestHandler(new ApplicationRequestHandler(this), 100); // .ui and related addRequestHandler(new ResourceRequestHandler(this, m_partHandler), 0); // $xxxx resources are a last resort addRequestHandler(new AjaxRequestHandler(this), 20); // .xaja ajax calls. addRequestHandler(getPartRequestHandler(), 80); } protected void registerControlFactories() { registerControlFactory(ControlFactory.STRING_CF); registerControlFactory(ControlFactory.TEXTAREA_CF); registerControlFactory(ControlFactory.BOOLEAN_AND_ENUM_CF); registerControlFactory(ControlFactory.DATE_CF); registerControlFactory(ControlFactory.RELATION_COMBOBOX_CF); registerControlFactory(ControlFactory.RELATION_LOOKUP_CF); registerControlFactory(new ControlFactoryMoney()); } protected void registerPartFactories() { registerUrlPart(new ThemePartFactory(), 100); // convert *.theme.* as a JSTemplate. registerUrlPart(new SvgPartFactory(), 100); // Converts .svg.png to png. } static private synchronized void setCurrentApplication(DomApplication da) { m_application = da; } /** * Returns the single DomApplication instance in use for the webapp. * @return */ @Nonnull static synchronized public DomApplication get() { DomApplication da = m_application; if(da == null) throw new IllegalStateException("The 'current application' is unset!?"); return da; } public synchronized void addSessionListener(final IAppSessionListener l) { m_appSessionListeners = new HashSet<IAppSessionListener>(m_appSessionListeners); m_appSessionListeners.add(l); } public synchronized void removeSessionListener(final IAppSessionListener l) { m_appSessionListeners = new HashSet<IAppSessionListener>(m_appSessionListeners); m_appSessionListeners.remove(l); } private synchronized Set<IAppSessionListener> getAppSessionListeners() { return m_appSessionListeners; } /** * Returns the defined extension for DomUI pages. This returns the extension without * the dot, i.e. "ui" for [classname].ui pages. * @return */ @Nonnull public String getUrlExtension() { if(null != m_urlExtension) return m_urlExtension; throw new IllegalStateException("Application is not initialized"); } /** * Internal: return the sorted-by-descending-priority list of request handlers. * @return */ @Nonnull private synchronized List<FilterRef> getRequestHandlerList() { return m_requestHandlerList; } /** * Add a toplevel request handler to the chain. * @param fh */ public synchronized void addRequestHandler(@Nonnull IFilterRequestHandler fh, int priority) { m_requestHandlerList = new ArrayList<FilterRef>(m_requestHandlerList); m_requestHandlerList.add(new FilterRef(fh, priority)); Collections.sort(m_requestHandlerList, C_HANDLER_DESCPRIO); // Leave the list ordered by descending priority. } /** * Find a request handler by locating the highest-scoring request handler in the chain. * @param ctx * @return */ @Nullable public IFilterRequestHandler findRequestHandler(@Nonnull final IRequestContext ctx) throws Exception { for(FilterRef h : getRequestHandlerList()) { if(h.getHandler().accepts(ctx)) return h.getHandler(); } return null; } /** * Add a part that reacts on some part of the input URL instead of [classname].part. * * @param factory * @param priority The priority of handling. Keep it low for little-used factories. */ public void registerUrlPart(@Nonnull IUrlPart factory, int priority) { addRequestHandler(new UrlPartRequestHandler(getPartRequestHandler(), factory), priority); // Add a request handler for this part factory. } /** * Add a part that reacts on some part of the input URL instead of [classname].part, with a priority of 10. * * @param factory */ public void registerUrlPart(@Nonnull IUrlPart factory) { registerUrlPart(factory, 10); } @Nonnull public PartRequestHandler getPartRequestHandler() { return m_partHandler; } /** * Can be overridden to create your own instance of a session. * @return */ protected AppSession createSession() { AppSession aps = new AppSession(this); return aps; } /** * Called when the session is bound to the HTTPSession. This calls all session listeners. * @param sess */ void registerSession(final AppSession aps) { for(IAppSessionListener l : getAppSessionListeners()) { try { l.sessionCreated(this, aps); } catch(Exception x) { x.printStackTrace(); } } } void unregisterSession(final AppSession aps) { } final void internalDestroy() { LOG.info("Destroying application " + this); try { destroy(); } catch(Throwable x) { AppFilter.LOG.error("Exception when destroying Application", x); } } /** * Override to destroy resources when the application terminates. */ protected void destroy() {} /** * Override to initialize the application, called as soon as the webabb starts by the * filter's initialization code. * * @param pp * @throws Exception */ protected void initialize(@Nonnull final ConfigParameters pp) throws Exception {} final synchronized public void internalInitialize(@Nonnull final ConfigParameters pp, boolean development) throws Exception { setCurrentApplication(this); // m_myClassLoader = appClassLoader; m_webFilePath = pp.getWebFileRoot(); //-- Get the page extension to use. String ext = pp.getString("extension"); if(ext == null || ext.trim().length() == 0) m_urlExtension = "ui"; else { ext = ext.trim(); if(ext.startsWith(".")) ext = ext.substring(1); if(ext.indexOf('.') != -1) throw new IllegalArgumentException("The 'extension' parameter contains too many dots..."); m_urlExtension = ext; } m_developmentMode = development; if(m_developmentMode && DeveloperOptions.getBool("domui.traceallocations", true)) NodeBase.internalSetLogAllocations(true); String haso = DeveloperOptions.getString("domui.testui", null); if(m_developmentMode && haso == null) m_uiTestMode = true; if("true".equals(haso)) m_uiTestMode = true; haso = System.getProperty("domui.testui"); if("true".equals(haso)) m_uiTestMode = true; initialize(pp); /* * If we're running in development mode then we auto-reload changed pages when the developer changes * them. It can be reset by using a developer.properties option. */ int refreshinterval = 0; if(development) { if(DeveloperOptions.getBool("domui.autorefresh", true)) { //-- Auto-refresh pages is on.... Get the poll interval for it, refreshinterval = DeveloperOptions.getInt("domui.refreshinterval", 2500); // Initialize "auto refresh" interval to 2 seconds } setAutoRefreshPollInterval(refreshinterval); } } static public synchronized final int internalNextPageTag() { int id = ++m_nextPageTag; if(id <= 0) { id = m_nextPageTag = 1; } return id; } final Class< ? > loadApplicationClass(final String name) throws ClassNotFoundException { /* * jal 20081030 Code below is very wrong. When the application is not reloaded due to a * change the classloader passed at init time does not change. But a new classloader will * have been allocated!! */ // return m_myClassLoader.loadClass(name); return getClass().getClassLoader().loadClass(name); } public Class< ? extends UrlPage> loadPageClass(final String name) { //-- This should be a classname now Class< ? > clz = null; try { clz = loadApplicationClass(name); } catch(ClassNotFoundException x) { throw new ThingyNotFoundException("404 class " + name + " not found"); } catch(Exception x) { throw new IllegalStateException("Error in class " + name, x); } //-- Check type && validity, if(!NodeContainer.class.isAssignableFrom(clz)) throw new IllegalStateException("Class " + clz + " is not a valid page class (does not extend " + UrlPage.class.getName() + ")"); return (Class< ? extends UrlPage>) clz; } public String getScriptVersion() { return m_scriptVersion; } /* CODING: HTML per-browser rendering code. */ /** * Creates the appropriate full renderer for the specified browser version. * @param bv * @param o * @return */ public HtmlFullRenderer findRendererFor(BrowserVersion bv, final IBrowserOutput o) { boolean tm = inUiTestMode(); for(IHtmlRenderFactory f : getRenderFactoryList()) { HtmlFullRenderer tr = f.createFullRenderer(bv, o, tm); if(tr != null) return tr; } return new StandardHtmlFullRenderer(new StandardHtmlTagRenderer(bv, o, tm), o); // HtmlTagRenderer base = new HtmlTagRenderer(bv, o); // return new HtmlFullRenderer(base, o); } public HtmlTagRenderer findTagRendererFor(BrowserVersion bv, final IBrowserOutput o) { boolean tm = inUiTestMode(); for(IHtmlRenderFactory f : getRenderFactoryList()) { HtmlTagRenderer tr = f.createTagRenderer(bv, o, tm); if(tr != null) return tr; } return new StandardHtmlTagRenderer(bv, o, tm); } private synchronized List<IHtmlRenderFactory> getRenderFactoryList() { return m_renderFactoryList; } public synchronized void addRenderFactory(IHtmlRenderFactory f) { if(m_renderFactoryList.contains(f)) throw new IllegalStateException("Don't be silly, this one is already added"); m_renderFactoryList = new ArrayList<IHtmlRenderFactory>(m_renderFactoryList); m_renderFactoryList.add(0, f); } /* CODING: Webapp configuration */ // /** // * Returns the name of the current theme, like "blue". This returns the // * name only, not the URL to the theme or something. // */ // @Nonnull // public synchronized String getCurrentTheme() { // return m_currentTheme; // /** // * Sets a new default theme. The theme name is the name of a directory, like "blue", below the // * "themes" map in the webapp or the root resources. // * @param defaultTheme // */ // public synchronized void setDefaultTheme(@Nonnull final String defaultTheme) { // if(null == defaultTheme) // m_currentTheme = defaultTheme; // /** // * Get the name of the current icon set. This must resolve to a directory "icons/[name]" in // * either the class resources or the webapp. // * @return // */ // @Nonnull // public synchronized String getCurrentIconSet() { // return m_currentIconSet; // /** // * Set the name of the current icon set. This must resolve to a directory "icons/[name]" in // * either the class resources or the webapp. // * // * @param currentIconSet // */ // public synchronized void setCurrentIconSet(@Nonnull String currentIconSet) { // if(null == currentIconSet) // m_currentIconSet = currentIconSet; // @Nonnull // public synchronized String getCurrentColorSet() { // return m_currentColorSet; // public synchronized void setCurrentColorSet(@Nonnull String currentColorSet) { // if(null == currentColorSet) // m_currentColorSet = currentColorSet; /** * Returns T when running in development mode; this is defined as a mode where web.xml contains * reloadable classes. * @return */ public synchronized boolean inDevelopmentMode() { return m_developmentMode; } public synchronized boolean inUiTestMode() { return m_uiTestMode; } /** * When &gt; 0, we're running in development mode AND the user has not DISABLED automatic page reload * using the "domui.autorefresh=false" line in developer.properties. When T, the server will force * a regular poll callback for all pages, and will refresh them automatically if that fails (indicating * they changed). * The effect of this being true are: * <ul> * <li>Every page will immediately enable polling.</li> * <li>The "session expired" and "page lost" types of workstation errors are disabled, causing the workstation to refresh without any message.</li> * </ul> * * @return */ public int getAutoRefreshPollInterval() { return m_autoRefreshPollInterval; } public void setAutoRefreshPollInterval(int autoRefreshPollInterval) { m_autoRefreshPollInterval = autoRefreshPollInterval; } /** * When {@link #isAutoRefreshPage()} is enabled (T), this defines the poll interval that a client uses * to check for server-side changes. It defaults to 2.5 seconds (in domui.js), and can be set to a faster update value * to have the update check faster for development. If the interval is not set this contains 0, else it contains the * refresh time in milliseconds. * @return */ public synchronized int getAutoRefreshInterval() { return m_autoRefreshPollInterval; } /** * The default poll interval time for pages containing Async objects (see {@link DelayedActivitiesManager}), defaulting * to 2500 (2.5 seconds). */ synchronized public int getDefaultPollInterval() { return m_defaultPollInterval; } synchronized public void setDefaultPollInterval(int defaultPollInterval) { m_defaultPollInterval = defaultPollInterval; } public synchronized int calculatePollInterval(boolean pollCallbackRequired) { int pollinterval = Integer.MAX_VALUE; if(m_keepAliveInterval > 0) pollinterval = m_keepAliveInterval; if(m_autoRefreshPollInterval > 0) { if(m_autoRefreshPollInterval < pollinterval) pollinterval = m_autoRefreshPollInterval; } if(pollCallbackRequired) { if(m_defaultPollInterval < pollinterval) pollinterval = m_defaultPollInterval; } if(pollinterval == Integer.MAX_VALUE) return 0; return pollinterval; } /** * The #of minutes that a WindowSession remains valid; defaults to 15 minutes. * * @return */ public int getWindowSessionTimeout() { return m_windowSessionTimeout; } /** * Sets the windowSession timeout, in minutes. * @param windowSessionTimeout */ public void setWindowSessionTimeout(final int windowSessionTimeout) { m_windowSessionTimeout = windowSessionTimeout; } /** * Returns the default browser cache resource expiry time in seconds. When * running in production mode all "static" resources are sent to the browser * with an "Expiry" header. This causes the browser to cache the resources * until the expiry time has been reached. This is important for performance. * @return */ public synchronized int getDefaultExpiryTime() { return m_defaultExpiryTime; } /** * Set the static resource browser cache expiry time, in seconds. * @param defaultExpiryTime */ public synchronized void setDefaultExpiryTime(final int defaultExpiryTime) { m_defaultExpiryTime = defaultExpiryTime; } /** * This returns the locale to use for the request passed. It defaults to the locale * in the request itself, as returned by {@link HttpServletRequest#getLocale()}. You * can override this method to define the locale by yourself. * @param request * @return */ @Nonnull public Locale getRequestLocale(HttpServletRequest request) { return request.getLocale(); } /* CODING: Global header contributors. */ protected void initHeaderContributors() { addHeaderContributor(HeaderContributor.loadJavascript("$js/jquery.js"), -1000); addHeaderContributor(HeaderContributor.loadJavascript("$js/jquery-ui.js"), -1000); // addHeaderContributor(HeaderContributor.loadJavascript("$js/ui.core.js"), -990); // addHeaderContributor(HeaderContributor.loadJavascript("$js/ui.draggable.js"), -980); addHeaderContributor(HeaderContributor.loadJavascript("$js/jquery.blockUI.js"), -970); addHeaderContributor(HeaderContributor.loadJavascript("$js/domui.js"), -900); addHeaderContributor(HeaderContributor.loadJavascript("$js/weekagenda.js"), -790); addHeaderContributor(HeaderContributor.loadJavascript("$js/jquery.wysiwyg.js"), -780); addHeaderContributor(HeaderContributor.loadJavascript("$js/wysiwyg.rmFormat.js"), -779); addHeaderContributor(HeaderContributor.loadStylesheet("$js/jquery.wysiwyg.css"), -780); /* * FIXME LF lf Look&Feel btadic STYLE DEBUGER * STYLE DEBUGER * FOR DEVELOPMENT ONLY * REMOVE IT AFTER LOOK AND FEEL PROJECTS */ addHeaderContributor(HeaderContributor.loadJavascript("$js/styleDebuger.js"), 10); /* * FIXME: Delayed construction of components causes problems with components * that are delayed and that contribute. Example: tab pabel containing a * DateInput. The TabPanel gets built when header contributions have already * been handled... For now we add all JS files here 8-( */ addHeaderContributor(HeaderContributor.loadJavascript("$js/calendar.js"), -780); addHeaderContributor(HeaderContributor.loadJavascript("$js/calendar-setup.js"), -770); //-- Localized calendar resources are added per-page. /* * FIXME Same as above, this is for loading the CKEditor. */ addHeaderContributor(HeaderContributor.loadJavascript("$ckeditor/ckeditor.js"), -760); } /** * Call from within the onHeaderContributor call on a node to register any header * contributors needed by a node. The order value determines the order for contributors * which is mostly important for Javascript ones; higher order items are written later than * lower order items. All DomUI required Javascript code has orders < 0; user code should * start at 0 and go up. * * @param hc * @param order */ final public synchronized void addHeaderContributor(final HeaderContributor hc, int order) { for(HeaderContributorEntry hce : m_orderedContributorList) { if(hce.getContributor().equals(hc)) throw new IllegalArgumentException("The header contributor " + hc + " has already been added."); } m_orderedContributorList = new ArrayList<HeaderContributorEntry>(m_orderedContributorList); // Dup the original list, m_orderedContributorList.add(new HeaderContributorEntry(hc, order)); // And add the new'un } public synchronized List<HeaderContributorEntry> getHeaderContributorList() { return m_orderedContributorList; } /** * When a page has no error handling components (no component has registered an error listener) then * errors will not be visible. If such a page encounters an error it will call this method; the default * implementation will add an ErrorPanel as the first component in the Body; this panel will then * accept and render the errors. * * @param page */ public void addDefaultErrorComponent(final NodeContainer page) { ErrorPanel panel = new ErrorPanel(); page.add(0, panel); } /** * FIXME This code requires an absolute title which is not needed for the * DomUI framework. It's also only needed for the "BasicPage" and has no * meaning for any other part of the framework. It should move to some * BasicPage factory. * * This returns default page title component. * {@link AppPageTitleBar} is default one used by framework. * To set some custom page title component override this method in your application specific class. * * @param title * @return */ @Deprecated public BasePageTitleBar getDefaultPageTitleBar(String title) { return new AppPageTitleBar(title, true); } /* CODING: Control factories. */ /** * Return the component that knows everything you ever wanted to know about controls - but were afraid to ask... */ final public ControlBuilder getControlBuilder() { return m_controlBuilder; } /** * Add a new control factory to the registry. * @param cf The new factory */ final public void registerControlFactory(final ControlFactory cf) { getControlBuilder().registerControlFactory(cf); } /** * Register a new LookupControl factory. * @param f */ public void register(final ILookupControlFactory f) { getControlBuilder().register(f); } // /** // * Get the immutable list of current control factories. // * @return // */ // private synchronized List<ControlFactory> getControlFactoryList() { // return m_controlFactoryList; /* CODING: Generic data factories. */ /** * FIXME Needs a proper, injected implementation instead of a quicky. */ public <T> T createInstance(final Class<T> clz, final Object... args) { try { return clz.newInstance(); } catch(IllegalAccessException x) { throw new WrappedException(x); } catch(InstantiationException x) { throw new WrappedException(x); } } /* CODING: WebApp resource management. */ /** * Return a file from the webapp's root directory. Example: passing WEB-INF/web.xml * would return the file for the web.xml. * * @param path * @return */ @Nonnull public File getAppFile(final String path) { return new File(m_webFilePath, path); } /** * Primitive to return either a File-based resource from the web content files * or a classpath resource (below /resources/) for the same path. The result will * implement {@link IModifyableResource}. This will not use any kind of resource * factory. * * @param name * @return */ @Nonnull public IResourceRef getAppFileOrResource(String name) { //-- 1. Is a file-based resource available? File f = getAppFile(name); if(f.exists()) return new WebappResourceRef(f); return createClasspathReference("/resources/" + name); } public synchronized void registerResourceFactory(@Nonnull IResourceFactory f) { m_resourceFactoryList = new ArrayList<IResourceFactory>(m_resourceFactoryList); m_resourceFactoryList.add(f); } @Nonnull public synchronized List<IResourceFactory> getResourceFactories() { return m_resourceFactoryList; } /** * Get the best factory to resolve the specified resource name. * @param name * @return */ @Nullable public IResourceFactory findResourceFactory(String name) { IResourceFactory best = null; int bestscore = -1; for(IResourceFactory rf : getResourceFactories()) { int score = rf.accept(name); if(score > bestscore) { bestscore = score; best = rf; } } return best; } /** * Returns the root of the webapp's installation directory on the local file system. * @return */ @Nonnull public final File getWebAppFileRoot() { if(null != m_webFilePath) return m_webFilePath; throw new IllegalStateException("Application is not initialized"); } // /** Cache for application resources containing all resources we have checked existence for */ // private final Map<String, IResourceRef> m_resourceSet = new HashMap<String, IResourceRef>(); private final Map<String, Boolean> m_knownResourceSet = new HashMap<String, Boolean>(); /** * Create a resource ref to a class based resource. If we are running in DEBUG mode this will * generate something which knows the source of the resource, so it can handle changes to that * source while developing. * * @param name * @return */ @Nonnull public IResourceRef createClasspathReference(String name) { if(!name.startsWith("/")) name = "/" + name; if(inDevelopmentMode()) { //-- If running in debug mode get this classpath resource's original source file IModifyableResource ts = ClasspathInventory.getInstance().findResourceSource(name); return new ReloadingClassResourceRef(ts, name); } return new ProductionClassResourceRef(name); } /** * Get an application resource. This usually means either a web file with the specified name or a * class resource with this name below /resources/. But {@link IResourceFactory} instances registered * with DomApplication can provide other means to locate resources. * * @param name * @param rdl The dependency list. Pass {@link ResourceDependencyList#NULL} if you do not need the * dependencies. * @return * @throws Exception */ @Nonnull public IResourceRef getResource(@Nonnull String name, @Nonnull IResourceDependencyList rdl) throws Exception { IResourceRef ref = internalFindResource(name, rdl); /* * The code below was needed because the original code caused a 404 exception on web resources which were * checked every time. All other resource types like class resources were not checked for existence. */ if(ref instanceof WebappResourceRef) { if(!ref.exists()) throw new ThingyNotFoundException(name); } return ref; } /** * Quickly determines if a given resource exists. Enter with the full resource path, like $js/xxx, THEME/xxx and the like; it * mirrors the logic of {@link #getApplicationResourceByName(String)}. * @param name * @return * @throws Exception */ public boolean hasApplicationResource(final String name) throws Exception { synchronized(this) { Boolean k = m_knownResourceSet.get(name); if(k != null) return k.booleanValue(); } //-- Determine existence out-of-lock (single init is unimportant) // IResourceRef ref = internalFindCachedResource(name); IResourceRef ref = internalFindResource(name, ResourceDependencyList.NULL); Boolean k = Boolean.valueOf(ref.exists()); // System.out.println("hasAppResource: locate " + ref + ", exists=" + k); if(!inDevelopmentMode() || ref instanceof IModifyableResource) { synchronized(this) { m_knownResourceSet.put(name, k); } } return k.booleanValue(); } // /** // * Cached version to locate an application resource. // * @param name // * @return // * @throws Exception // */ // private IResourceRef internalFindCachedResource(@Nonnull String name) throws Exception { // IResourceRef ref; // synchronized(this) { // ref = m_resourceSet.get(name); // if(ref != null) // return ref; // //-- Determine existence out-of-lock (single init is unimportant). Only cache if // ref = internalFindResource(name); // if(!inDevelopmentMode() || ref instanceof IModifyableResource) { // synchronized(this) { // m_resourceSet.put(name, ref); // return ref; /** * UNCACHED version to locate a resource, using the registered resource factories. * * @param name * @param rdl * @return */ @Nonnull private IResourceRef internalFindResource(@Nonnull String name, @Nonnull IResourceDependencyList rdl) throws Exception { IResourceFactory rf = findResourceFactory(name); if(rf != null) return rf.getResource(this, name, rdl); //-- No factory. Return class/file reference. File src = new File(m_webFilePath, name); IResourceRef r = new WebappResourceRef(src); rdl.add(r); return r; } /** * This returns the name of an <i>existing</i> resource for the given name/suffix and locale. It uses the * default DomUI/webapp.core resource resolution pattern. * * @see BundleRef#loadBundleList(Locale) * * @param basename The base name: the part before the locale info * @param suffix The suffix: the part after the locale info. This usually includes a ., like .js * @param loc The locale to get the resource for. * @return * @throws Exception */ public String findLocalizedResourceName(final String basename, final String suffix, final Locale loc) throws Exception { StringBuilder sb = new StringBuilder(128); String s; s = tryKey(sb, basename, suffix, loc.getLanguage(), loc.getCountry(), loc.getVariant(), NlsContext.getDialect()); if(s != null) return s; s = tryKey(sb, basename, suffix, loc.getLanguage(), loc.getCountry(), loc.getVariant(), null); if(s != null) return s; s = tryKey(sb, basename, suffix, loc.getLanguage(), loc.getCountry(), null, NlsContext.getDialect()); if(s != null) return s; s = tryKey(sb, basename, suffix, loc.getLanguage(), loc.getCountry(), null, null); if(s != null) return s; s = tryKey(sb, basename, suffix, loc.getLanguage(), null, null, NlsContext.getDialect()); if(s != null) return s; s = tryKey(sb, basename, suffix, loc.getLanguage(), null, null, null); if(s != null) return s; s = tryKey(sb, basename, suffix, null, null, null, NlsContext.getDialect()); if(s != null) return s; s = tryKey(sb, basename, suffix, null, null, null, null); if(s != null) return s; return null; } private String tryKey(final StringBuilder sb, final String basename, final String suffix, final String lang, final String country, final String variant, final String dialect) throws Exception { sb.setLength(0); sb.append(basename); if(dialect != null && dialect.length() > 0) { sb.append('_'); sb.append(dialect); } if(lang != null && lang.length() > 0) { sb.append('_'); sb.append(lang); } if(country != null && country.length() > 0) { sb.append('_'); sb.append(country); } if(variant != null && variant.length() > 0) { sb.append('_'); sb.append(variant); } if(suffix != null && suffix.length() > 0) sb.append(suffix); String res = sb.toString(); if(hasApplicationResource(res)) return res; return null; } /* CODING: Code table cache. */ private final Map<String, ListRef< ? >> m_listCacheMap = new HashMap<String, ListRef< ? >>(); static private final class ListRef<T> { private List<T> m_list; private final ICachedListMaker<T> m_maker; public ListRef(final ICachedListMaker<T> maker) { m_maker = maker; } public synchronized List<T> initialize() throws Exception { if(m_list == null) m_list = m_maker.createList(DomApplication.get()); return m_list; } } /** * * @param <T> * @param key * @param maker * @return */ public <T> List<T> getCachedList(final IListMaker<T> maker) throws Exception { if(!(maker instanceof ICachedListMaker< ? >)) { //-- Just make on the fly. return maker.createList(this); } ICachedListMaker<T> cm = (ICachedListMaker<T>) maker; ListRef<T> ref; String key = cm.getCacheKey(); synchronized(m_listCacheMap) { ref = (ListRef<T>) m_listCacheMap.get(key); if(ref == null) { ref = new ListRef<T>(cm); m_listCacheMap.put(key, ref); } } return new ArrayList<T>(ref.initialize()); } /** * Discard all cached stuff in the list cache. */ public void clearListCaches() { synchronized(m_listCacheMap) { m_listCacheMap.clear(); } // FIXME URGENT Clear all other server's caches too by sending an event. } public void clearListCache(final ICachedListMaker< ? > maker) { synchronized(m_listCacheMap) { m_listCacheMap.remove(maker.getCacheKey()); } // FIXME URGENT Clear all other server's caches too by sending an event. } public boolean logOutput() { return m_logOutput; } public synchronized void addInterceptor(final IRequestInterceptor r) { List<IRequestInterceptor> l = new ArrayList<IRequestInterceptor>(m_interceptorList); l.add(r); m_interceptorList = l; } public synchronized List<IRequestInterceptor> getInterceptorList() { return m_interceptorList; } /* CODING: Exception translator handling. */ /** * An entry in the exception table. */ static public class ExceptionEntry { private final Class< ? extends Exception> m_exceptionClass; private final IExceptionListener m_listener; public ExceptionEntry(final Class< ? extends Exception> exceptionClass, final IExceptionListener listener) { m_exceptionClass = exceptionClass; m_listener = listener; } public Class< ? extends Exception> getExceptionClass() { return m_exceptionClass; } public IExceptionListener getListener() { return m_listener; } } /** The ORDERED list of [exception.class, handler] pairs. Exception SUPERCLASSES are ordered AFTER their subclasses. */ private List<ExceptionEntry> m_exceptionListeners = new ArrayList<ExceptionEntry>(); /** * Return the current, immutable, threadsafe copy of the list-of-listeners. * @return */ private synchronized List<ExceptionEntry> getExceptionListeners() { return m_exceptionListeners; } /** * Adds an exception handler for a given exception type. The handler is inserted ordered, * exceptions that are a superclass of other exceptions in the list are sorted AFTER their * subclass (this prevents the handler for the superclass from being called all the time). * Any given exception type may occur in this list only once or an exception occurs. * * @param l */ public synchronized void addExceptionListener(final Class< ? extends Exception> xclass, final IExceptionListener l) { m_exceptionListeners = new ArrayList<ExceptionEntry>(m_exceptionListeners); //-- Do a sortish insert. for(int i = 0; i < m_exceptionListeners.size(); i++) { ExceptionEntry ee = m_exceptionListeners.get(i); if(ee.getExceptionClass() == xclass) { //-- Same class-> replace the handler with the new one. m_exceptionListeners.set(i, new ExceptionEntry(xclass, l)); return; } else if(ee.getExceptionClass().isAssignableFrom(xclass)) { //-- Class [ee] is a SUPERCLASS of [xclass]; you can do [ee] = [xclass]. We need to add this handler BEFORE this superclass! m_exceptionListeners.add(i, new ExceptionEntry(xclass, l)); return; } } m_exceptionListeners.add(new ExceptionEntry(xclass, l)); } /** * This locates the handler for the specfied exception type, if it has been registered. It * currently uses a loop to locate the appropriate handler. * @param x * @return null if the handler was not registered. */ public IExceptionListener findExceptionListenerFor(final Exception x) { Class< ? extends Exception> xclass = x.getClass(); for(ExceptionEntry ee : getExceptionListeners()) { if(ee.getExceptionClass().isAssignableFrom(xclass)) return ee.getListener(); } return null; } public synchronized void addNewPageInstantiatedListener(final INewPageInstantiated l) { m_newPageInstListeners = new ArrayList<INewPageInstantiated>(m_newPageInstListeners); m_newPageInstListeners.add(l); } public synchronized void removeNewPageInstantiatedListener(final INewPageInstantiated l) { m_newPageInstListeners = new ArrayList<INewPageInstantiated>(m_newPageInstListeners); m_newPageInstListeners.remove(l); } public synchronized List<INewPageInstantiated> getNewPageInstantiatedListeners() { return m_newPageInstListeners; } public synchronized ILoginAuthenticator getLoginAuthenticator() { return m_loginAuthenticator; } public synchronized void setLoginAuthenticator(final ILoginAuthenticator loginAuthenticator) { m_loginAuthenticator = loginAuthenticator; } public synchronized ILoginDialogFactory getLoginDialogFactory() { return m_loginDialogFactory; } public synchronized void setLoginDialogFactory(final ILoginDialogFactory loginDialogFactory) { m_loginDialogFactory = loginDialogFactory; } public synchronized void addLoginListener(final ILoginListener l) { if(m_loginListenerList.contains(l)) return; m_loginListenerList = new ArrayList<ILoginListener>(m_loginListenerList); m_loginListenerList.add(l); } public synchronized List<ILoginListener> getLoginListenerList() { return m_loginListenerList; } /** * Add a new listener for asynchronous job events. * @param l */ public synchronized <T> void addAsyncListener(@Nonnull IAsyncListener<T> l) { m_asyncListenerList = new ArrayList<IAsyncListener< ? >>(m_asyncListenerList); m_asyncListenerList.add(l); } public synchronized <T> void removeAsyncListener(@Nonnull IAsyncListener<T> l) { m_asyncListenerList = new ArrayList<IAsyncListener< ? >>(m_asyncListenerList); m_asyncListenerList.remove(l); } @Nonnull public synchronized List<IAsyncListener< ? >> getAsyncListenerList() { return m_asyncListenerList; } /** * Responsible for redirecting to the appropriate login page. This default implementation checks * to see if there is an authenticator registered and uses it's result to redirect. If no * authenticator is registered this returns null, asking the caller to do normal exception * handling. * * @param ci * @param page * @param nlix */ public String handleNotLoggedInException(RequestContextImpl ci, Page page, NotLoggedInException x) { ILoginDialogFactory ldf = ci.getApplication().getLoginDialogFactory(); if(ldf == null) return null; // Nothing can be done- I don't know how to log in. //-- Redirect to the LOGIN page, passing the current page to return back to. String target = ldf.getLoginRURL(x.getURL()); // Create a RURL to move to. if(target == null) throw new IllegalStateException("The Login Dialog Handler=" + ldf + " returned an invalid URL for the login dialog."); //-- Make this an absolute URL by appending the webapp path return ci.getRelativePath(target); } /** * Get the page injector. * @return */ public synchronized IPageInjector getInjector() { return m_injector; } public synchronized void setInjector(IPageInjector injector) { m_injector = injector; } /* CODING: Rights registry. */ private final Map<String, BundleRef> m_rightsBundleMap = new HashMap<String, BundleRef>(); /** * Registers a set of possible rights and their names/translation bundle. * @param bundle * @param rights */ public void registerRight(final BundleRef bundle, final String... rights) { synchronized(m_rightsBundleMap) { for(String r : rights) { if(!m_rightsBundleMap.containsKey(r)) m_rightsBundleMap.put(r, bundle); } } } /** * Takes a class (or interface) and scans all static public final String fields therein. For * each field it's literal string value is used as a rights name and associated with the bundle. * If a right already exists it is skipped, meaning the first ever definition of a right wins. * * @param bundle * @param constantsclass */ public void registerRights(final BundleRef bundle, final Class< ? > constantsclass) { //-- Find all class fields. Field[] far = constantsclass.getDeclaredFields(); synchronized(m_rightsBundleMap) { for(Field f : far) { int mod = f.getModifiers(); if(Modifier.isFinal(mod) && Modifier.isPublic(mod) && Modifier.isStatic(mod)) { if(f.getType() == String.class) { try { String s = (String) f.get(null); if(s != null) { if(!m_rightsBundleMap.containsKey(s)) { m_rightsBundleMap.put(s, bundle); // System.out.println("app: registering right="+s); } } } catch(Exception x) { // Ignore all exceptions due to accessing the field using Introspection } } } } } } /** * Return a list of all currently registered right names. * @return */ public List<String> getRegisteredRights() { synchronized(m_rightsBundleMap) { return new ArrayList<String>(m_rightsBundleMap.keySet()); } } /** * Translates a right name to a description from the registered bundle, if registered. * @param right * @return */ public String findRightsDescription(final String right) { BundleRef br; synchronized(m_rightsBundleMap) { br = m_rightsBundleMap.get(right); } return br == null ? null : br.findMessage(NlsContext.getLocale(), right); } /** * Translates a right name to a description from the registered bundle, if registered. Returns the right name if no bundle or description is * found. * @param right * @return */ public String getRightsDescription(final String right) { String v = findRightsDescription(right); return v == null ? right : v; } // public AjaxRequestHandler getAjaxHandler() { // return m_ajaxHandler; /* CODING: Programmable theme code. */ /** The theme manager where theme calls are delegated to. */ final private ThemeManager m_themeManager = new ThemeManager(this); /** * This method can be overridden to add extra stuff to the theme map, after * it has been loaded from properties or whatnot. * @param themeMap */ @OverridingMethodsMustInvokeSuper public void augmentThemeMap(@Nonnull IScriptScope ss) throws Exception { ss.put("util", new ThemeCssUtils(ss)); ss.eval(Object.class, "function url(x) { return util.url(x);};", "internal"); } /** * Sets the current theme string. This string is used as a "parameter" for the theme factory * which will use it to decide on the "real" theme to use. * @param currentTheme The theme name, valid for the current theme engine. Cannot be null nor the empty string. */ public void setCurrentTheme(@Nonnull String currentTheme) { m_themeManager.setCurrentTheme(currentTheme); } /** * Gets the current theme string. This will become part of all themed resource URLs * and is interpreted by the theme factory to resolve resources. * @return */ @Nonnull public String getCurrentTheme() { return m_themeManager.getCurrentTheme(); } /** * Return the current theme itself. * @return */ @Nonnull public ITheme getTheme() { return m_themeManager.getTheme(getCurrentTheme(), null); } /** * Get the property map (the collection of all *.js files associated with the theme). * @return */ @Nonnull public IScriptScope getThemeMap() { return getTheme().getPropertyScope(); } /** * Get the current theme factory. * @return */ @Nonnull public IThemeFactory getThemeFactory() { return m_themeManager.getThemeFactory(); } /** * Set the factory for handling the theme. * @param themer */ public void setThemeFactory(@Nonnull IThemeFactory themer) { m_themeManager.setThemeFactory(themer); } /** * Get the theme store representing the specified theme name. This is the name as obtained * from the resource name which is the part between $THEME/ and the actual filename. * * @param rdl * @return * @throws Exception */ public ITheme getTheme(@Nonnull String themeName, @Nonnull IResourceDependencyList rdl) throws Exception { return m_themeManager.getTheme(themeName, rdl); } /** * EXPENSIVE CALL - ONLY USE TO CREATE CACHED RESOURCES * * This loads a theme resource as an utf-8 encoded template, then does expansion using the * current theme's variable map. This map is either a "style.properties" file * inside the theme's folder, or can be configured dynamically using a IThemeMapFactory. * * The result is returned as a string. * * * @param rdl * @param rurl * @return * @throws Exception */ public String getThemeReplacedString(IResourceDependencyList rdl, String rurl) throws Exception { return m_themeManager.getThemeReplacedString(rdl, rurl); } /** * EXPENSIVE CALL - ONLY USE TO CREATE CACHED RESOURCES * * This loads a theme resource as an utf-8 encoded template, then does expansion using the * current theme's variable map. This map is either a "style.properties" file * inside the theme's folder, or can be configured dynamically using a IThemeMapFactory. * * The result is returned as a string. * * @param rdl * @param key * @return */ public String getThemeReplacedString(IResourceDependencyList rdl, String rurl, BrowserVersion bv) throws Exception { return m_themeManager.getThemeReplacedString(rdl, rurl, bv); } /** * Return the current theme map (a readonly map), cached from the last * time. It will refresh automatically when the resource dependencies * for the theme are updated. * * @param rdl * @return * @throws Exception */ public IScriptScope getThemeMap(String themeName, IResourceDependencyList rdlin) throws Exception { return m_themeManager.getThemeMap(themeName, rdlin); } /** * This checks to see if the RURL passed is a theme-relative URL. These URLs start * with THEME/. If not the RURL is returned as-is; otherwise the URL is translated * to a path containing the current theme string: * <pre> * $THEME/[currentThemeString]/[name] * </pre> * where [name] is the rest of the path string after THEME/ has been removed from it. * @param path * @return */ @Nullable public String getThemedResourceRURL(@Nullable String path) { return m_themeManager.getThemedResourceRURL(path); } /* CODING: DomUI state listener handling. */ public synchronized int getKeepAliveInterval() { return m_keepAliveInterval; } /** * Set the keep-alive interval for DomUI screens, in milliseconds. * @param keepAliveInterval */ public synchronized void setKeepAliveInterval(int keepAliveInterval) { if(DeveloperOptions.getBool("domui.autorefresh", true) || DeveloperOptions.getBool("domui.keepalive", false)) // If "autorefresh" has been disabled do not use keepalive either. m_keepAliveInterval = keepAliveInterval; } private List<IDomUIStateListener> m_uiStateListeners = Collections.EMPTY_LIST; /** * Register a listener for internal DomUI events. * @param sl */ public synchronized void addUIStateListener(IDomUIStateListener sl) { m_uiStateListeners = new ArrayList<IDomUIStateListener>(m_uiStateListeners); // Dup list; m_uiStateListeners.add(sl); } /** * Remove a registered UI state listener. * @param sl */ public synchronized void removeUIStateListener(IDomUIStateListener sl) { m_uiStateListeners = new ArrayList<IDomUIStateListener>(m_uiStateListeners); // Dup list; m_uiStateListeners.remove(sl); } private synchronized List<IDomUIStateListener> getUIStateListeners() { return m_uiStateListeners; } public final void internalCallWindowSessionCreated(WindowSession ws) { for(IDomUIStateListener sl : getUIStateListeners()) { try { sl.windowSessionCreated(ws); } catch(Exception x) { x.printStackTrace(); } } } public final void internalCallWindowSessionDestroyed(WindowSession ws) { for(IDomUIStateListener sl : getUIStateListeners()) { try { sl.windowSessionDestroyed(ws); } catch(Exception x) { x.printStackTrace(); } } } public final void internalCallConversationCreated(ConversationContext ws) { for(IDomUIStateListener sl : getUIStateListeners()) { try { sl.conversationCreated(ws); } catch(Exception x) { x.printStackTrace(); } } } public final void internalCallConversationDestroyed(ConversationContext ws) { for(IDomUIStateListener sl : getUIStateListeners()) { try { sl.conversationDestroyed(ws); } catch(Exception x) { x.printStackTrace(); } } } public final void internalCallPageFullRender(RequestContextImpl ctx, Page ws) { for(IDomUIStateListener sl : getUIStateListeners()) { try { sl.onBeforeFullRender(ctx, ws); } catch(Exception x) { x.printStackTrace(); } } } public final void internalCallPageAction(RequestContextImpl ctx, Page ws) { for(IDomUIStateListener sl : getUIStateListeners()) { try { sl.onBeforePageAction(ctx, ws); } catch(Exception x) { x.printStackTrace(); } } } public final void internalCallPageComplete(IRequestContext ctx, Page ws) { for(IDomUIStateListener sl : getUIStateListeners()) { try { sl.onAfterPage(ctx, ws); } catch(Exception x) { x.printStackTrace(); } } } synchronized public void setUiTestMode(boolean value){ m_uiTestMode = value; } }
package info.justaway.util; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.Log; import org.opencv.android.Utils; import org.opencv.core.Core; import org.opencv.core.CvType; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfRect; import org.opencv.core.Point; import org.opencv.core.Rect; import org.opencv.core.Scalar; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import org.opencv.imgproc.Moments; import org.opencv.objdetect.CascadeClassifier; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import info.justaway.R; import info.justaway.settings.BasicSettings; public class FaceCrop { private static final String TAG = FaceCrop.class.getSimpleName(); private boolean mIsFirst = true; private boolean mIsSuccess; private int mMaxHeight; private float mWidth; private float mHeight; private Rect mRect; private List<Rect> mRects = new ArrayList<>(); private int mColor = Color.MAGENTA; private boolean mIsFace = false; private static CascadeClassifier sFaceDetector = null; private static Map<String, FaceCrop> sFaceInfoMap = new LinkedHashMap<String, FaceCrop>(100, 0.75f, true) { private static final int MAX_ENTRIES = 100; @Override protected boolean removeEldestEntry(Map.Entry<String, FaceCrop> eldest) { return size() > MAX_ENTRIES; } }; public static void initFaceDetector(Context context) { if (sFaceDetector == null) { sFaceDetector = setupFaceDetector(context); } } private static File setupCascadeFile(Context context) { File cascadeDir = context.getFilesDir(); File cascadeFile = null; InputStream is = null; FileOutputStream os = null; try { cascadeFile = new File(cascadeDir, "lbpcascade_animeface.xml"); if (!cascadeFile.exists()) { is = context.getResources().openRawResource(R.raw.lbpcascade_animeface); os = new FileOutputStream(cascadeFile); byte[] buffer = new byte[4096]; int readLen = 0; while ((readLen = is.read(buffer)) != -1) { os.write(buffer, 0, readLen); } } } catch (IOException e) { return null; } finally { if (is != null) { try { is.close(); } catch (IOException e) { // NOP } } if (os != null) { try { os.close(); } catch (IOException e) { // NOP } } } return cascadeFile; } private static CascadeClassifier setupFaceDetector(Context context) { File cascadeFile = setupCascadeFile(context); if (cascadeFile == null) { return null; } CascadeClassifier detector = new CascadeClassifier(cascadeFile.getAbsolutePath()); detector.load(cascadeFile.getAbsolutePath()); if (detector.empty()) { return null; } return detector; } public FaceCrop(int maxHeight, float w, float h) { this.mMaxHeight = maxHeight; this.mWidth = w; this.mHeight = h; } private static Bitmap drawFaceRegion(Rect rect, Bitmap image, int color) { try { Bitmap result = image.copy(Bitmap.Config.ARGB_8888, true); Paint paint = new Paint(); paint.setColor(color); paint.setStrokeWidth(4); paint.setStyle(Paint.Style.STROKE); Canvas canvas = new Canvas(result); if (rect != null) { canvas.drawRect(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, paint); } return result; } catch (Exception e) { e.printStackTrace(); return image; } } private static Bitmap drawFaceRegions(List<Rect> rects, Bitmap image, int color) { try { Bitmap result = image.copy(Bitmap.Config.ARGB_8888, true); Paint paint = new Paint(); paint.setColor(color); paint.setStrokeWidth(4); paint.setStyle(Paint.Style.STROKE); Canvas canvas = new Canvas(result); for (Rect rect : rects) { canvas.drawRect(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, paint); } return result; } catch (Exception e) { e.printStackTrace(); return image; } } public Bitmap drawRegion(Bitmap bitmap) { if (mIsSuccess) { if (BasicSettings.isDebug()) { // bitmap = drawFaceRegion(mRect, bitmap, Color.GREEN); bitmap = drawFaceRegions(mRects, bitmap, mColor); return bitmap; } } return null; } public Rect getFaceRect(Bitmap bitmap) { mColor = mIsFirst ? Color.MAGENTA : mIsFace ? Color.GREEN : Color.CYAN; if (mIsFirst) { mIsFirst = false; if (sFaceDetector != null) { MatOfRect faces = new MatOfRect(); Mat imageMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Utils.bitmapToMat(bitmap, imageMat); Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_RGB2GRAY); Imgproc.equalizeHist(imageMat, imageMat); sFaceDetector.detectMultiScale(imageMat, faces, 1.1, 3, 0, new Size(300 / 5, 300 / 5), new Size()); Rect[] facesArray = faces.toArray(); if (facesArray.length > 0) { Rect r = getLargestFace(facesArray); Log.d(TAG, String.format("image: (%s, %s)", mWidth, mHeight)); Log.d(TAG, String.format("face area: (%d, %d, %d, %d)", r.x, r.y, r.width, r.height)); mRect = r; mRects.clear(); Collections.addAll(mRects, facesArray); mIsFace = true; mIsSuccess = true; } else { return getCounterRect(bitmap); // return getFeatureArea(bitmap); } } } return mRect; } private Rect getGravityCenter(Bitmap bitmap) { MatOfRect faces = new MatOfRect(); Mat imageMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Mat mask = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Mat hadairo = Mat.zeros((int) mHeight, (int) mWidth, CvType.CV_8U); Utils.bitmapToMat(bitmap, imageMat); Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_RGB2HSV); Imgproc.medianBlur(imageMat, imageMat, 3); Bitmap dst = Bitmap.createBitmap(imageMat.width(), imageMat.height(), Bitmap.Config.ARGB_8888); Core.inRange(imageMat, new Scalar(0, 20, 88), new Scalar(25, 80, 255), mask); // Utils.matToBitmap(mask, dst); Utils.bitmapToMat(bitmap, imageMat); Imgproc.cvtColor(hadairo, hadairo, Imgproc.COLOR_RGB2GRAY); // Utils.matToBitmap(hadairo, dst); Moments mu = Imgproc.moments(hadairo, false); Rect r = new Rect(); r.x = (int) (mu.m10 / mu.m00); r.y = (int) (mu.m01 / mu.m00); r.x -= 50; r.width = 100; r.y -= 50; r.height = 100; mRect = r; mRects.clear(); mRects.add(r); mIsSuccess = true; mColor = Color.BLUE; return mRect; } private Rect getFeatureArea(Bitmap bitmap) { MatOfRect faces = new MatOfRect(); Mat srcMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Utils.bitmapToMat(bitmap, srcMat); Mat imageMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Imgproc.cvtColor(srcMat, imageMat, Imgproc.COLOR_RGB2HSV); Imgproc.medianBlur(imageMat, imageMat, 3); Bitmap dst = Bitmap.createBitmap(imageMat.width(), imageMat.height(), Bitmap.Config.ARGB_8888); Mat tmp = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Mat bw = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Core.inRange(imageMat, new Scalar(0, 20, 88), new Scalar(25, 80, 255), bw); Utils.matToBitmap(bw, dst); Imgproc.threshold(bw, bw, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU); Utils.matToBitmap(bw, dst); // ( and ) Mat kernel = Mat.ones(3, 3, CvType.CV_8U); Imgproc.morphologyEx(bw, bw, Imgproc.MORPH_OPEN, kernel, new Point(-1, -1), 2); // bw.convertTo(tmp, CvType.CV_8U); Imgproc.cvtColor(bw, tmp, Imgproc.COLOR_GRAY2RGB, 4); Utils.matToBitmap(tmp, dst); Mat sureBg = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Imgproc.dilate(bw, sureBg, kernel, new Point(-1, -1), 3); // sureBg.convertTo(tmp, CvType.CV_8U); Imgproc.cvtColor(sureBg, tmp, Imgproc.COLOR_GRAY2RGB, 4); Utils.matToBitmap(tmp, dst); Mat sureFg = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Imgproc.distanceTransform(bw, sureFg, Imgproc.DIST_L2, 3); // 3.5 or 0 CV_8C1 -> CV_32FC1 sureFg.convertTo(tmp, CvType.CV_8U); Imgproc.equalizeHist(tmp, tmp); Utils.matToBitmap(tmp, dst); Core.normalize(sureFg, sureFg, 0.0f, 255.0f, Core.NORM_MINMAX); sureFg.convertTo(tmp, CvType.CV_8U); Imgproc.equalizeHist(tmp, tmp); Utils.matToBitmap(tmp, dst); Imgproc.threshold(sureFg, sureFg, 40, 255, Imgproc.THRESH_BINARY); Imgproc.dilate(sureFg, sureFg, kernel, new Point(-1, -1), 3); // CV_32FC1 -> CV_32FC1 sureFg.convertTo(tmp, CvType.CV_8U); Imgproc.equalizeHist(tmp, tmp); Utils.matToBitmap(tmp, dst); Mat sureFgUC1 = sureFg.clone(); sureFg.convertTo(sureFgUC1, CvType.CV_8UC1); Mat unknown = sureFg.clone(); Core.subtract(sureBg, sureFgUC1, unknown); unknown.convertTo(tmp, CvType.CV_8U); Imgproc.equalizeHist(tmp, tmp); Utils.matToBitmap(tmp, dst); Mat markers = Mat.zeros(sureFg.size(), CvType.CV_32SC1); sureFg.convertTo(sureFg, CvType.CV_8U); int nLabels = Imgproc.connectedComponents(sureFg, markers, 8, CvType.CV_32SC1); if (nLabels < 2) { return mRect; } Core.add(markers, new Scalar(1), markers); for (int i=0; i<markers.rows(); i++) { for (int j=0; j<markers.cols(); j++) { double[] data = unknown.get(i, j); if (data[0] == 255) { int[] val = new int[] { 255 }; markers.put(i, j, val); } } } Imgproc.cvtColor(srcMat, srcMat, Imgproc.COLOR_RGBA2RGB); Imgproc.watershed(srcMat, markers); markers.convertTo(tmp, CvType.CV_8U); Imgproc.equalizeHist(tmp, tmp); Utils.matToBitmap(tmp, dst); mRect = null; mRects.clear(); return mRect; } private Rect getCounterRect(Bitmap bitmap) { if (bitmap == null) { return mRect; } MatOfRect faces = new MatOfRect(); Mat imageMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Utils.bitmapToMat(bitmap, imageMat); Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_RGB2HSV); Imgproc.medianBlur(imageMat, imageMat, 5); // Bitmap dst = Bitmap.createBitmap(imageMat.width(), imageMat.height(), Bitmap.Config.ARGB_8888); Mat bw = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Core.inRange(imageMat, new Scalar(0, 20, 88), new Scalar(25, 80, 255), bw); // Imgproc.threshold(bw, bw, 0, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU); // ( and ) Mat kernel = Mat.ones(3, 3, CvType.CV_8U); Imgproc.morphologyEx(bw, bw, Imgproc.MORPH_OPEN, kernel, new Point(-1, -1), 2); Imgproc.distanceTransform(bw, bw, Imgproc.DIST_L2, 3); // 3.5 or 0 CV_8C1 -> CV_32FC1 Core.normalize(bw, bw, 0.0f, 255.0f, Core.NORM_MINMAX); Imgproc.threshold(bw, bw, 30, 255, Imgproc.THRESH_BINARY); Imgproc.dilate(bw, bw, kernel, new Point(-1, -1), 3); // CV_32FC1 -> CV_32FC1 bw.convertTo(bw, CvType.CV_8U); // CV_32FC1 -> CV_8UC1 List<MatOfPoint> contours = new ArrayList<MatOfPoint>(); Mat hierarchy = Mat.zeros(new Size(5,5), CvType.CV_8UC1); Imgproc.findContours(bw, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_TC89_L1); mRect = null; mRects.clear(); double maxArea = 0; for (MatOfPoint contour : contours) { Rect r = Imgproc.boundingRect(contour); mRects.add(r); double area = Imgproc.contourArea(contour); if (maxArea < area) { maxArea = area; mRect = r; } } if (contours.size() > 0) { mColor = Color.BLUE; mIsSuccess = true; } return mRect; } public Bitmap cropFace(Bitmap bitmap, float aspect) { if (!mIsSuccess) { return bitmap; } float w = bitmap.getWidth(); float h = bitmap.getHeight(); float bitmapAspect = h / w; if (BasicSettings.isDebug()) { // bitmap = drawFaceRegion(mRect, bitmap, mColor); bitmap = drawFaceRegions(mRects, bitmap, mColor); } Rect r = new Rect(mRect.x, mRect.y, mRect.width, mRect.height); if (bitmapAspect > aspect) { r = addVPadding(r, bitmap, (int) (w * aspect)); Bitmap resized = Bitmap.createBitmap(bitmap, 0, r.y, (int)w, r.height); return resized; } else { r = addHPadding(r, bitmap, (int) (h / aspect)); Bitmap resized = Bitmap.createBitmap(bitmap, r.x, 0, r.width, (int)h); return resized; } } public Bitmap invoke(Bitmap bitmap) { mColor = mIsFirst ? Color.MAGENTA : Color.GREEN; if (mIsFirst) { mIsFirst = false; if (sFaceDetector != null) { MatOfRect faces = new MatOfRect(); Mat imageMat = new Mat((int) mHeight, (int) mWidth, CvType.CV_8U, new Scalar(4)); Utils.bitmapToMat(bitmap, imageMat); Imgproc.cvtColor(imageMat, imageMat, Imgproc.COLOR_RGB2GRAY); Imgproc.equalizeHist(imageMat, imageMat); sFaceDetector.detectMultiScale(imageMat, faces, 1.1f, 3, 0, new Size(300 / 5, 300 / 5), new Size()); Rect[] facesArray = faces.toArray(); if (facesArray.length > 0) { Rect r = getLargestFace(facesArray); Log.d(TAG, String.format("image: (%s, %s)", mWidth, mHeight)); Log.d(TAG, String.format("face area: (%d, %d, %d, %d)", r.x, r.y, r.width, r.height)); mRect = r; mRects.clear(); Collections.addAll(mRects, facesArray); mIsSuccess = true; } } } if (mIsSuccess) { if (BasicSettings.isDebug()) { bitmap = drawFaceRegion(mRect, bitmap, mColor); } Rect r = new Rect(mRect.x, mRect.y, mRect.width, mRect.height); r = addVPadding(r, bitmap, mMaxHeight); Bitmap resized = Bitmap.createBitmap(bitmap, 0, r.y, (int) mWidth, r.height); return resized; } else { return null; } } static private Rect addVPadding(Rect r, Bitmap bitmap, int maxHeight) { int padding = r.height < maxHeight ? maxHeight - r.height : (int)(r.height * 0.2f); r.y -= padding / 2; r.height += padding; if (r.y < 0) { r.y = 0; } int bottomExcess =r.y + r.height - bitmap.getHeight(); if (bottomExcess > 0) { r.y -= bottomExcess; if (r.y < 0) { r.y = 0; } r.height = bitmap.getHeight() - r.y; } return r; } static private Rect addHPadding(Rect r, Bitmap bitmap, int maxWidth) { int padding = r.width < maxWidth ? maxWidth - r.width : (int)(r.width * 0.2f); r.x -= padding / 2; r.width += padding; if (r.x < 0) { r.x = 0; } int rightExcess =r.x + r.width - bitmap.getWidth(); if (rightExcess > 0) { r.x -= rightExcess; if (r.x < 0) { r.x = 0; } r.width = bitmap.getWidth() - r.x; } return r; } private Rect getLargestFace(Rect[] facesArray) { Rect ret = null; int maxSize = -1; for (Rect r : facesArray) { int size = r.width * r.height; if (size > maxSize) { ret = r; maxSize = size; } } return ret; } public static FaceCrop get(String imageUri, int maxHeight, float w, float h) { FaceCrop faceCrop = sFaceInfoMap.get(imageUri); if (faceCrop == null) { faceCrop = new FaceCrop(maxHeight, w, h); sFaceInfoMap.put(imageUri, faceCrop); } return faceCrop; } public boolean isSuccess() { return mIsSuccess; } }
package org.pm4j.core.pm.pageable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; /** * Implements a {@link PageableCollection} based on an {@link List} of items to * handle. * * @author olaf boede * * @param <T_ITEM> * The type of items handled by this set. */ public class PageableListImpl<T_ITEM> implements PageableCollection<T_ITEM> { private Collection<T_ITEM> originalObjects; private List<T_ITEM> objectsInOriginalSortOrder; private List<T_ITEM> objects; private int pageSize = 10; private int currentPageIdx; private boolean multiSelect; private Set<T_ITEM> selectedItems = new LinkedHashSet<T_ITEM>(); private Comparator<?> currentSortComparator; private Filter<T_ITEM> currentFilter; /** * @param objects * The set of objects to iterate over. * @param pageSize * The page size to use. */ public PageableListImpl(Collection<T_ITEM> objects) { this.originalObjects = objects; this.currentPageIdx = 1; onUpdateCollection(); } /** * Creates an empty collection. * @param pageSize The page size. * @param multiSelect The multi selection behavior definition. */ public PageableListImpl(int pageSize, boolean multiSelect) { this(new ArrayList<T_ITEM>()); this.pageSize = pageSize; this.multiSelect = multiSelect; } @Override public List<T_ITEM> getItemsOnPage() { if (objects.isEmpty()) { return Collections.emptyList(); } int first = PageableCollectionUtil.getIdxOfFirstItemOnPage(this) - 1; int last = PageableCollectionUtil.getIdxOfLastItemOnPage(this); if (first < 0) throw new RuntimeException(); return objects.subList(first, last); } @Override public int getNumOfItems() { return objects.size(); } @Override public int getPageSize() { return pageSize; } @Override public void setPageSize(int newSize) { pageSize = newSize; } @Override public int getCurrentPageIdx() { return currentPageIdx; } @Override public void setCurrentPageIdx(int pageIdx) { this.currentPageIdx = pageIdx; } @Override public void sortItems(Comparator<?> sortComparator) { currentSortComparator = sortComparator; _applyFilterAndSortOrder(); } @Override public void sortBackingItems(Comparator<?> sortComparator) { sortItems(sortComparator); } @SuppressWarnings("unchecked") @Override public void setItemFilter(Filter<?> filter) { currentFilter = (Filter<T_ITEM>)filter; _applyFilterAndSortOrder(); } @Override public void setBackingItemFilter(Filter<?> filter) { setItemFilter(filter); } @Override public Filter<?> getBackingItemFilter() { return currentFilter; } @Override public boolean isSelected(T_ITEM item) { return selectedItems.contains(item); } @Override public void select(T_ITEM item) { if (!multiSelect) { selectedItems.clear(); } if (item != null) { selectedItems.add(item); } } @Override public void deSelect(T_ITEM item) { selectedItems.remove(item); } @Override public boolean isMultiSelect() { return multiSelect; } @Override public void setMultiSelect(boolean isMultiSelect) { this.multiSelect = isMultiSelect; } @Override public Collection<T_ITEM> getSelectedItems() { return selectedItems; } @Override public void onUpdateCollection() { _assignObjectsFromOri(); _applyFilterAndSortOrder(); } @SuppressWarnings("unchecked") private void _assignObjectsFromOri() { this.objectsInOriginalSortOrder = (originalObjects == null || originalObjects.isEmpty()) ? java.util.Collections.EMPTY_LIST : new ArrayList<T_ITEM>(originalObjects); this.objects = objectsInOriginalSortOrder; } private void _applyFilterAndSortOrder() { List<T_ITEM> filteredList = _filter(objectsInOriginalSortOrder); _sortAndAssignToObjects(filteredList); } @SuppressWarnings("unchecked") private void _sortAndAssignToObjects(List<T_ITEM> srcList) { if (currentSortComparator == null) { objects = srcList; } else { // prevent unintended sort operation on the source list. if (objects == srcList) { objects = new ArrayList<T_ITEM>(srcList); } Collections.sort(objects, (Comparator<T_ITEM>)currentSortComparator); } } private List<T_ITEM> _filter(List<T_ITEM> unfilteredList) { if (currentFilter == null) { return unfilteredList; } // remember selected item and clear selection if not multiSelect T_ITEM selectedItem = null; if(!multiSelect) { if(!selectedItems.isEmpty()) { selectedItem = selectedItems.iterator().next(); selectedItems.clear(); } } List<T_ITEM> filteredList = new ArrayList<T_ITEM>(); int listSize = unfilteredList.size(); for (int i=0; i<listSize; ++i) { T_ITEM item = unfilteredList.get(i); if (currentFilter.doesItemMatch(item)) { filteredList.add(item); // re-select item if not multiSelect and item is within filtered items if(!multiSelect) { if(item == selectedItem) { select(selectedItem); } } } } return filteredList; } }
package com.Ryan.Calculator; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.text.InputFilter; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; public class MainActivity extends Activity { public Complex currentValue=Complex.ZERO; /** Called when the activity is first created. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) { getActionBar().hide(); if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.ICE_CREAM_SANDWICH) findViewById(R.id.mainLayout).setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); } setZero(); InputFilter filter=new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (source!=null && source.toString().contains("!")) { SpannableString ch=new SpannableString(source.toString().replace('!', 'i')); if (source instanceof Spanned) // We need to copy spans if source is spanned TextUtils.copySpansFrom((Spanned)source, 0, source.length(), Spanned.class, ch, 0); return ch; } return null; } }; EditText ev=(EditText)findViewById(R.id.mainTextField); ArrayList<InputFilter> filters=new ArrayList<>(Arrays.asList(ev.getFilters())); filters.add(filter); ev.setFilters(filters.toArray(new InputFilter[]{})); } public double parseCoefficient(String num) // Parses a number of any form into a double coefficient { // Error handling if ("".equals(num) || num.length()<1) return 0; if (num.charAt(num.length()-1)=='\u03C0') { if (num.length()==1) return Math.PI; else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation return -Math.PI; // Return negative pi return parseCoefficient(num.substring(0, num.length()-1))*Math.PI; } if (num.charAt(num.length()-1)=='e') { if (num.length()==1) return Math.E; else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation return -Math.E; // Return negative e return parseCoefficient(num.substring(0, num.length()-1))*Math.E; } try { return Double.parseDouble(num); } catch (NumberFormatException ex) { setText("ERROR: Invalid number"); View v=findViewById(R.id.mainCalculateButton); v.setOnClickListener(null); // Cancel existing computation v.setVisibility(View.GONE); // Remove the button return Double.NaN; } } public Complex parseComplex(String num) { // Special string checks if (num==null || "".equals(num) || num.length()<1 || num.indexOf("Error", 0)==0 || num.indexOf("ERROR", 0)==0) return Complex.ZERO; if ("Not prime".equals(num) || "Not prime or composite".equals(num) || "Not Gaussian prime".equals(num)) return Complex.ZERO; if ("Prime".equals(num) || "Gaussian prime".equals(num)) return Complex.ONE; // Handle parentheticals if (num.charAt(0)=='(') { char ending=num.charAt(num.length()-1); if (ending=='\u03C0') return Complex.multiply(Complex.PI, parseComplex(num.substring(1, num.length() - 2))); else if (ending=='e') return Complex.multiply(Complex.E, parseComplex(num.substring(1, num.length()-2))); } // Start parsing the number if (num.contains("\u03C0") || num.contains("e")) { // If our number has a character Complex.parseString won't handle, use parseCoefficient-based processing String real; String imaginary; if (num.contains("+")) { // A plus sign is an easy indicator of a two-part number: -a+bi or a+bi int n=num.indexOf('+'); real=num.substring(0, n); imaginary=num.substring(n+1); } else if (num.contains("-")) { // A minus sign appears in one of four remaining formats: a-bi, -a-bi, -a, and -bi if (num.contains("i")) { // a-bi, -a-bi, or -bi int n=num.lastIndexOf('-'); if (n==0) { real=""; imaginary=num.substring(0, num.length()-1); } else { real=num.substring(0, n); imaginary=num.substring(n); // Include the minus sign } } else { imaginary=""; real=num; } } else { // If there is no sign, it can only be a or bi. Differentiate on i. real=""; imaginary=""; if (num.charAt(num.length()-1)=='i') imaginary=num.substring(0, num.length()-1); else real=num; } return new Complex(parseCoefficient(real), parseCoefficient(imaginary)); } // If didn't need to perform the relatively expensive parseCoefficient processing... try { // Try to use parseString return Complex.parseString(num); } catch (NumberFormatException e) { // We couldn't manage to handle the string setText("ERROR: Invalid number"); View v=findViewById(R.id.mainCalculateButton); v.setOnClickListener(null); // Cancel existing computation v.setVisibility(View.GONE); // Remove the button return Complex.ERROR; } } public String inIntTermsOfPi(double num) { if (num==0) return "0"; double tmp=num/Math.PI; int n=(int)tmp; if (n==tmp) { if (n==-1) // If it is a negative, but otherwise 1 return "-\u03C0"; // Return negative pi return (n==1 ? "" : Integer.toString(n))+"\u03C0"; } else return Double.toString(num); } public String inIntTermsOfPi(Complex num) { if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i" return "0"; if (Double.isNaN(num.real()) || Double.isNaN(num.imaginary())) // Trap NaNs return "ERROR: Non-numeric result."; // This avoids repeating the message. if (num.isReal()) return inIntTermsOfPi(num.real()); if (num.isImaginary()) { if (num.imaginary()==1) return "i"; else if (num.imaginary()==-1) return "-i"; return inIntTermsOfPi(num.imaginary()) + 'i'; } String out=inIntTermsOfPi(num.real()); if (num.imaginary()>0) out+="+"; if (num.imaginary()==1) out+='i'; else if (num.imaginary()==-1) out+="-i"; else out+=inIntTermsOfPi(num.imaginary())+'i'; return out; } public String inIntTermsOfE(double num) { if (num==0) return "0"; double tmp=num/Math.E; int n=(int)tmp; if (n==tmp) { if (n==-1) // If it is a negative, but otherwise 1 return "-e"; // Return negative e return (n==1 ? "" : Integer.toString((int)tmp))+"e"; } else return Double.toString(num); } public String inIntTermsOfE(Complex num) { if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i" return "0"; if (Double.isNaN(num.real()) || Double.isNaN(num.imaginary())) // Trap NaNs return "ERROR: Non-numeric result."; // This avoids repeating the message. if (num.isReal()) return inIntTermsOfE(num.real()); if (num.isImaginary()) { if (num.imaginary()==1) return "i"; else if (num.imaginary()==-1) return "-i"; return inIntTermsOfE(num.imaginary()) + 'i'; } String out=inIntTermsOfE(num.real()); if (num.imaginary()>0) out+="+"; if (num.imaginary()==1) out+='i'; else if (num.imaginary()==-1) out+="-i"; else out+=inIntTermsOfE(num.imaginary())+'i'; return out; } public String inIntTermsOfAny(double num) { if (Double.isNaN(num)) // "Last-resort" check return "ERROR: Non-numeric result."; // Trap NaN and return a generic error for it. // Because of that check, we can guarantee that NaN's will not be floating around for more than one expression. String out=inIntTermsOfPi(num); if (!out.equals(Double.toString(num))) return out; else return inIntTermsOfE(num); } public String inIntTermsOfAny(Complex num) { if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i" return "0"; if (Double.isNaN(num.real()) || Double.isNaN(num.imaginary())) // Trap NaNs return "ERROR: Non-numeric result."; // This avoids repeating the message. if (num.isReal()) return inIntTermsOfAny(num.real()); if (num.isImaginary()) { if (num.imaginary()==1) return "i"; else if (num.imaginary()==-1) return "-i"; return inIntTermsOfAny(num.imaginary()) + 'i'; } String out=inIntTermsOfAny(num.real()); if (num.imaginary()>0) out+="+"; if (num.imaginary()==1) out+='i'; else if (num.imaginary()==-1) out+="-i"; else out+=inIntTermsOfAny(num.imaginary())+'i'; return out; } public void zero(View v) { setZero(); } public void setZero(EditText ev) { setText("0", ev); } public void setZero() { setZero((EditText) findViewById(R.id.mainTextField)); } public void setText(String n, EditText ev) { ev.setText(n); ev.setSelection(0, n.length()); // Ensure the cursor is at the end } public void setText(String n) { setText(n, (EditText) findViewById(R.id.mainTextField)); } public void terms(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(parseComplex(ev.getText().toString().trim())), ev); } public void decimal(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); String str=ev.getText().toString().trim(); if (str==null || str.indexOf("Error", 0)==0 || str.indexOf("ERROR", 0)==0) setText(Complex.toString(Complex.ZERO)); else setText(Complex.toString(parseComplex(str)), ev); } public Complex getValue(final EditText ev) // Parses the content of ev into a double. { return parseComplex(ev.getText().toString().trim()); } public void doCalculate(final EditText ev, OnClickListener ocl) // Common code for buttons that use the mainCalculateButton. { doCalculate(ev, ocl, Complex.ZERO); } public void doCalculate(final EditText ev, OnClickListener ocl, Complex n) // Common code for buttons that use the mainCalculateButton, setting the default value to n rather than zero. { setText(inIntTermsOfAny(n), ev); final Button b=(Button)findViewById(R.id.mainCalculateButton); b.setVisibility(View.VISIBLE); b.setOnClickListener(ocl); } public void add(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num = ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(currentValue.addTo(parseComplex(num))), ev); v.setVisibility(View.GONE); } }); } public void subtract(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(currentValue.subtractTo(parseComplex(num))), ev); v.setVisibility(View.GONE); } }); } public void subtract2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(parseComplex(num).subtractTo(currentValue)), ev); v.setVisibility(View.GONE); } }); } public void multiply(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(currentValue.multiplyTo(parseComplex(num))), ev); v.setVisibility(View.GONE); } }); } public void divide(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; Complex n=parseComplex(num); if (n.equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(currentValue.divideTo(n)), ev); v.setVisibility(View.GONE); } }, Complex.ONE); } public void divide2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; Complex n=parseComplex(num); if (n.equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(n.divideTo(currentValue)), ev); v.setVisibility(View.GONE); } }, Complex.ONE); } public void remainder(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); if (!Complex.round(currentValue).equals(currentValue)) { setText("Error: Parameter is not an integer: "+ev.getText(), ev); return; } doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; v.setVisibility(View.GONE); Complex tmp=parseComplex(num); if (!Complex.round(tmp).equals(tmp)) setText("Error: Parameter is not an integer: "+num, ev); else if (Complex.round(tmp).equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(Complex.round(currentValue).moduloTo(Complex.round(tmp))), ev); } }, Complex.ONE); } public void remainder2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); if (!Complex.round(currentValue).equals(currentValue)) { setText("Error: Parameter is not an integer: "+ev.getText(), ev); return; } doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; v.setVisibility(View.GONE); Complex tmp=parseComplex(num); if (!Complex.round(tmp).equals(tmp)) setText("Error: Parameter is not an integer: "+num, ev); else if (Complex.round(currentValue).equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(Complex.round(tmp).moduloTo(Complex.round(currentValue))), ev); } }, Complex.ONE); } public void e(View v) { setText("e"); } public void pi(View v) { setText("\u03C0"); } public void i(View v) { setText("i"); } public void negate(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.negate(parseComplex(ev.getText().toString()))), ev); } public void sin(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.sin(parseComplex(ev.getText().toString()))), ev); } public void cos(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.cos(parseComplex(ev.getText().toString()))), ev); } public void tan(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.tan(parseComplex(ev.getText().toString()))), ev); } public void arcsin(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.asin(parseComplex(ev.getText().toString()))), ev); } public void arccos(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.acos(parseComplex(ev.getText().toString()))), ev); } public void arctan(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.atan(parseComplex(ev.getText().toString()))), ev); } public void exp(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfE(Complex.exp(parseComplex(ev.getText().toString()))), ev); } public void degrees(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText((Complex.toDegrees(parseComplex(ev.getText().toString()))).toString(), ev); } public void radians(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.toRadians(parseComplex(ev.getText().toString()))), ev); } public void radians2(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex tmp=parseComplex(ev.getText().toString()); tmp=Complex.divide(tmp, new Complex(180)); setText('('+Complex.toString(tmp)+')'+'\u03C0', ev); } public void ln(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfE(Complex.ln(parseComplex(ev.getText().toString()))), ev); } public void log(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.log10(parseComplex(ev.getText().toString()))), ev); } public void logb(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num = ev.getText().toString(); if ("".equals(num)) return; setText(inIntTermsOfAny(Complex.log(currentValue, parseComplex(num))), ev); v.setVisibility(View.GONE); } }, new Complex(10)); } public void logb2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev,new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString(); if ("".equals(num)) return; setText(inIntTermsOfAny(Complex.log(parseComplex(num), currentValue)), ev); v.setVisibility(View.GONE); } }, new Complex(10)); } public void round(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(Complex.toString(Complex.round(parseComplex(ev.getText().toString())))); } public void sqrt(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex n=parseComplex(ev.getText().toString()); setText(inIntTermsOfAny(Complex.sqrt(n)), ev); } public void cbrt(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.cbrt(parseComplex(ev.getText().toString()))), ev); } public void ceil(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(Complex.toString(Complex.ceil(parseComplex(ev.getText().toString()))), ev); } public void floor(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(Complex.toString(Complex.floor(parseComplex(ev.getText().toString()))), ev); } public void pow(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num = ev.getText().toString(); if (!"".equals(num)) setText(inIntTermsOfAny(Complex.pow(currentValue, parseComplex(num))), ev); v.setVisibility(View.GONE); } }, currentValue); } public void pow2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString(); if (!"".equals(num)) setText(inIntTermsOfAny(Complex.pow(parseComplex(num), currentValue)), ev); v.setVisibility(View.GONE); } }, currentValue); } public void abs (View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.abs(parseComplex(ev.getText().toString()))), ev); } public void sinh(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.sinh(parseComplex(ev.getText().toString()))), ev); } public void expm(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.expm1(parseComplex(ev.getText().toString()))), ev); } public void cosh(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.cosh(parseComplex(ev.getText().toString()))), ev); } public void tanh(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.tanh(parseComplex(ev.getText().toString()))), ev); } public void lnp(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.ln1p(parseComplex(ev.getText().toString()))), ev); } public void square(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex num=parseComplex(ev.getText().toString()); setText(inIntTermsOfAny(num.square()), ev); } public void cube(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex num=parseComplex(ev.getText().toString()); setText(inIntTermsOfAny(Complex.multiply(num.square(), num)), ev); } public void isPrime(View v) // Standard primality, not Gaussian { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex m=parseComplex(ev.getText().toString()); if (!m.isReal()) { if (!m.isImaginary()) // M is zero setText("Not prime"); else setText("Error: Cannot compute standard is prime for complex numbers"); return; } double num=m.real(); int n=(int)Math.floor(num); if (n!=num || n<1 || isDivisible(n,2)) { setText("Not prime"); return; } if (n==1) { setText("Not prime or composite"); return; } for (int i=3; i<=Math.sqrt(n); i+=2) { if (isDivisible(n, i)) { setText("Not prime"); return; } } setText("Prime"); } public void isGaussianPrime(View v) // Computes whether a prime number is a Gaussian prime { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex m=parseComplex(ev.getText().toString()); boolean prime=false; if (Math.floor(m.real())==m.real() && Math.floor(m.imaginary())==m.imaginary()) { if (m.isReal()) { int n=(int)Math.abs(m.real()); if (isDivisible(n-3, 4)) { prime=true; for (int i = 3; i <= Math.sqrt(n); i += 2) { if (isDivisible(n, i)) { prime = false; break; } } } } else if (m.isImaginary()) { int n=(int)Math.abs(m.imaginary()); if (isDivisible(n-3, 4)) { prime=true; for (int i=3; i<=Math.sqrt(n); i+=2) { if (isDivisible(n, i)) { prime=false; break; } } } } else { double norm=(m.real()*m.real())+(m.imaginary()*m.imaginary()); int n=(int) Math.floor(norm); if (n==norm) { if (n!=1 && !isDivisible(n, 2)) { prime=true; for (int i=3; i<=Math.sqrt(n); i+=2) { if (isDivisible(n, i)) { prime=false; break; } } } } } } setText(prime ? "Gaussian prime" : "Not Gaussian prime"); } public boolean isDivisible(int num, int den) { return num%den==0; } public double fastPow(double val, int power) { if (val==2) return fastPow(power).doubleValue(); switch (power) { case 0: return 1; case 1: return val; case 2: return val*val; default: if (power<0) return 1/fastPow(val, -1*power); if (power%2==0) return fastPow(fastPow(val, 2), power>>1); return val*fastPow(val, power-1); } } public BigInteger fastPow(int pow) // 2 as base { return BigInteger.ZERO.flipBit(pow); } public void raise2(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex num=parseComplex(ev.getText().toString()); if (num.isReal() && Math.round(num.real())==num.real()) // Integer power. Use the fastpow() and a BigInteger. setText(fastPow((int)Math.round(num.real())).toString(), ev); else setText(Complex.toString(Complex.pow(2, num)), ev); } }
package lib.morkim.mfw.ui; import android.content.Context; import android.os.Bundle; import android.preference.PreferenceFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.util.UUID; import lib.morkim.mfw.app.MorkimApp; public abstract class MorkimFragment<C extends Controller, P extends Presenter> extends PreferenceFragment implements Viewable<MorkimApp, C, P> { private C controller; private P presenter; private UUID id; protected int layoutId() { return 0; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); id = (savedInstanceState == null) ? UUID.randomUUID() : UUID.fromString(savedInstanceState.getString(VIEWABLE_ID)); presenter = (P) getMorkimContext().acquirePresenter(this); controller = (C) getMorkimContext().acquireController(this); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(VIEWABLE_ID, id.toString()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(layoutId(), container, false); } @Override public void onStart() { super.onStart(); controller.registerForUpdates(this); } @Override public void onStop() { super.onStop(); controller.unregisterFromUpdates(this); } @Override public MorkimApp getMorkimContext() { return (MorkimApp) getActivity().getApplication(); } @Override public Context getContext() { return getActivity(); } @Override public Screen getScreen() { return (Screen) getActivity(); } @Override public C getController() { return controller; } @Override public P getPresenter() { return presenter; } @Override public void showShortMessage(String message) { Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show(); } @Override public void keepScreenOn(boolean keepOn) { ((Screen) getActivity()).keepScreenOn(keepOn); } @Override public void finish() { } @Override public UUID getInstanceId() { return id; } }
package org.bobstuff.bobball; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; /* * simple load and save using shared preferences * you have to use setContext before using load or save in an activity * you should use setContext in onCreate() */ public class Preferences extends Application { private static SharedPreferences sharedPreferences; private static Context appContext; public static void setContext (Context context) { appContext = context; sharedPreferences = context.getSharedPreferences("sharedPreferences", Context.MODE_PRIVATE); } public static Context getContext () { return appContext; } public static String loadValue (String filename, String defaultValue) { return sharedPreferences.getString (filename, defaultValue); } public static void saveValue (String filename, String value) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(filename, value); editor.commit(); } }
package boundary.User; import boundary.Representation; import com.wordnik.swagger.annotations.Api; import com.wordnik.swagger.annotations.ApiOperation; import com.wordnik.swagger.annotations.ApiResponse; import com.wordnik.swagger.annotations.ApiResponses; import control.PasswordManagement; import entity.User; import entity.UserRole; import provider.Secured; import javax.ejb.EJB; import javax.ejb.Stateless; import javax.json.Json; import javax.json.JsonObject; import javax.ws.rs.*; import javax.ws.rs.core.*; import java.util.List; @Path("/users") @Stateless @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Api(value = "/users", description = "Users management") public class UserRepresentation extends Representation { @EJB UserResource userResource; @GET @Secured({UserRole.ADMIN}) @Path("/{email}") @ApiOperation(value = "Get a user by its email address", notes = "Access : Admin only") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 500, message = "Internal server error") }) public Response get(@PathParam("email") String email) { User user = userResource.findByEmail(email); if (user != null) return Response.ok(user, MediaType.APPLICATION_JSON).build(); else return Response.status(Response.Status.NOT_FOUND).build(); } @GET @Secured({UserRole.ADMIN}) @ApiOperation(value = "Get all the users", notes = "Access: Admin only") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 500, message = "Internal server error") }) public Response getAll(){ GenericEntity<List<User>> list = new GenericEntity<List<User>>(userResource.findAll()){}; return Response.ok(list, MediaType.APPLICATION_JSON).build(); } @GET @Secured({UserRole.CUSTOMER}) @ApiOperation(value = "Get a user by a JWT", notes = "Access : Logged user only") @ApiResponses(value = { @ApiResponse(code = 200, message = "OK"), @ApiResponse(code = 401, message = "Unauthorized"), @ApiResponse(code = 500, message = "Internal server error") }) @Path("/signedin") public Response getClientInfo(@Context SecurityContext securityContext){ User user = userResource.findByEmail(securityContext.getUserPrincipal().getName()); JsonObject json = Json.createObjectBuilder() .add("user", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("email", user.getEmail()) .add("name", user.getName()))) .build(); return Response.ok(json, MediaType.APPLICATION_JSON).build(); } @POST @Path("/signup") @ApiOperation(value = "Create a customer account", notes = "Email address is unique") @ApiResponses(value = { @ApiResponse(code = 204, message = "No content"), @ApiResponse(code = 404, message = "Not Found"), @ApiResponse(code = 409, message = "Conflict : email address is already used"), @ApiResponse(code = 500, message = "Internal server error") }) public Response signup(User user) { if ((user.getName() == null || user.getEmail() == null || user.getPassword() == null)) return Response.status(Response.Status.NOT_FOUND).build(); if (userResource.findByEmail(user.getEmail()) != null) flash(409, "This email address is already used"); try { userResource.insert(new User(user.getName(), user.getEmail(), PasswordManagement.digestPassword(user.getPassword()))); return Response.ok().build(); } catch (Exception e) { return Response.serverError().build(); } } }
package com.sharefile.api; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import com.sharefile.api.authentication.SFOAuth2Token; import com.sharefile.api.constants.SFKeywords; import com.sharefile.api.entities.SFItemsEntity; import com.sharefile.api.exceptions.SFInvalidStateException; import com.sharefile.api.exceptions.SFV3ErrorException; import com.sharefile.api.https.SFApiFileDownloadRunnable; import com.sharefile.api.https.SFApiFileUploadRunnable; import com.sharefile.api.https.SFApiRunnable; import com.sharefile.api.https.SFCookieManager; import com.sharefile.api.interfaces.ISFReAuthHandler; import com.sharefile.api.interfaces.SFApiDownloadProgressListener; import com.sharefile.api.interfaces.SFApiResponseListener; import com.sharefile.api.interfaces.SFApiUploadProgressListener; import com.sharefile.api.interfaces.SFAuthTokenChangeListener; import com.sharefile.api.models.SFDownloadSpecification; import com.sharefile.api.models.SFODataObject; import com.sharefile.api.models.SFSession; import com.sharefile.api.models.SFUploadSpecification; import com.sharefile.java.log.SLog; public class SFApiClient { private static final String TAG = SFKeywords.TAG + "-SFApiClient"; public static final String MSG_INVALID_STATE_OAUTH_NULL = "Invalid state: Oauth token not initialized for SFApiClient"; private final AtomicReference<SFOAuth2Token> mOAuthToken = new AtomicReference<SFOAuth2Token>(null); private SFSession mSession = null; private final SFCookieManager mCookieManager = new SFCookieManager(); private final String mClientID; private final String mClientSecret; private final SFAuthTokenChangeListener mAuthTokenChangeListener; private final String mSfUserId; private final AtomicBoolean mClientInitializedSuccessFully = new AtomicBoolean(false); public static final SFItemsEntity items = new SFItemsEntity(); public boolean isClientInitialised() { return mClientInitializedSuccessFully.get(); } public SFOAuth2Token getAuthToken() { return mOAuthToken.get(); } private void copyOAuthToken(SFOAuth2Token oauthToken) throws SFInvalidStateException { validateStateBeforeInit(oauthToken); mOAuthToken.set(oauthToken); mClientInitializedSuccessFully.set(true); } public SFApiClient(SFOAuth2Token oauthToken,String sfUserId,String clientID,String clientSecret, SFAuthTokenChangeListener listener) throws SFInvalidStateException { mClientInitializedSuccessFully.set(false); mAuthTokenChangeListener = listener; mClientID = clientID; mClientSecret = clientSecret; mSfUserId = sfUserId; copyOAuthToken(oauthToken); } /** * This function can be called only on clients which were previously initialized. * This will internally call the token change listener allowing the creator of this object * to store the new token to Persistant storage. */ @SFSDKDefaultAccessScope void reinitClientState(SFOAuth2Token oauthtoken) throws SFInvalidStateException { mClientInitializedSuccessFully.set(false); copyOAuthToken(oauthtoken); if(mAuthTokenChangeListener!=null) { try { mAuthTokenChangeListener.sfApiStoreNewToken(oauthtoken); } catch(Exception e) { SLog.d(TAG, "Exception in initclient", e); } } } /** * This will start a seperate thread to perform the operation and return immediately. Callers should use callback listeners to gather results */ public synchronized <T extends SFODataObject> Thread executeQuery(SFApiQuery<T> query , SFApiResponseListener<T> listener, ISFReAuthHandler reauthHandler) throws SFInvalidStateException { SFApiListenerReauthHandler<T> sfReauthHandler = new SFApiListenerReauthHandler<T>(listener, reauthHandler, this,query); return executeQueryInternal(query, sfReauthHandler, true); } /** * We use this to install our own intermediate API listener. This allows us to handle the token renewal on auth Errors for * ShareFile providers. This function has default access scope so that the SFApiListenerWrapper can call this to avoid * the infinite recursion while attempting to handle auth errors. */ @SFSDKDefaultAccessScope <T extends SFODataObject> Thread executeQueryInternal(SFApiQuery<T> query , SFApiListenerReauthHandler<T> listener, boolean useTokenRenewer) throws SFInvalidStateException { validateClientState(); SFApiResponseListener<T> targetLisner = listener; if(useTokenRenewer) { SFApiListenerTokenRenewer<T> listenereWrapper = new SFApiListenerTokenRenewer<T>(this,listener,query,mOAuthToken.get(),mClientID,mClientSecret); targetLisner = listenereWrapper; } SFApiRunnable<T> sfApiRunnable = new SFApiRunnable<T>(query, targetLisner, mOAuthToken.get(),mCookieManager); return sfApiRunnable.startNewThread(); } /** * This will block until operation is done and return the expected SFODataObject or throw a V3Exception. Never call this on UI thread. */ public <T extends SFODataObject> SFODataObject executeQuery(SFApiQuery<T> query) throws SFV3ErrorException, SFInvalidStateException { validateClientState(); SFApiRunnable<T> sfApiRunnable = new SFApiRunnable<T>(query, null, mOAuthToken.get(),mCookieManager); return sfApiRunnable.executeQuery(); } /** * Make this a more stronger check than a simple null check on OAuth. */ private void validateStateBeforeInit(SFOAuth2Token token) throws SFInvalidStateException { if(token == null) { throw new SFInvalidStateException(MSG_INVALID_STATE_OAUTH_NULL); } if(!token.isValid()) { throw new SFInvalidStateException(MSG_INVALID_STATE_OAUTH_NULL); } } private void validateClientState() throws SFInvalidStateException { if(!mClientInitializedSuccessFully.get()) { throw new SFInvalidStateException(MSG_INVALID_STATE_OAUTH_NULL); } } public SFSession getSession() { return mSession; } public Thread downloadFile(SFDownloadSpecification downloadSpecification,int resumeFromByteIndex, OutputStream outpuStream, SFApiDownloadProgressListener progressListener) throws SFInvalidStateException { validateClientState(); SFApiFileDownloadRunnable sfDownloadFile = new SFApiFileDownloadRunnable(downloadSpecification, resumeFromByteIndex, outpuStream , this,progressListener,mCookieManager); return sfDownloadFile.startNewThread(); } public Thread uploadFile(SFUploadSpecification uploadSpecification,int resumeFromByteIndex, long tolalBytes, String destinationName, InputStream inputStream, SFApiUploadProgressListener progressListener) throws SFInvalidStateException { validateClientState(); SFApiFileUploadRunnable sfUploadFile = new SFApiFileUploadRunnable(uploadSpecification, resumeFromByteIndex, tolalBytes,destinationName, inputStream, this,progressListener,mCookieManager); return sfUploadFile.startNewThread(); } /** * Resets the token and nulls the internal callbacks. Call this when you no longer want to use this object. */ public void reset() { mClientInitializedSuccessFully.set(false); } public String getUserId() { return mSfUserId; } }
package org.paxml.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.UnsupportedEncodingException; import java.security.KeyStore; import java.security.KeyStore.PasswordProtection; import java.security.KeyStoreException; import java.security.MessageDigest; import java.util.concurrent.Callable; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.paxml.core.PaxmlRuntimeException; import com.thoughtworks.xstream.core.util.Base64Encoder; public class CryptoUtils { public static final String DEFAULT_KEY_STORE_NAME = ""; public static final String DEFAULT_KEY_NAME = ""; public static final String KEY_STORE_TYPE = "JCEKS"; public static final String KEY_STORE_EXT = KEY_STORE_TYPE.toLowerCase(); public static final int KEY_LENGTH_BITS = 128; public static final int KEY_LENGTH_BYTES = KEY_LENGTH_BITS / 8; public static final String KEY_STORE_FOLDER = "keys"; public static final String KEY_TYPE = "AES"; public static final String HASH_TYPE = "SHA-1"; public static final String KEY_VALUE_ENCODING = "UTF-8"; private static final String DEFAULT_KEY_PASSWORD = "key_pass"; private static final RWTaskExecutor keyStoreExecutor = new RWTaskExecutor(); private static SecretKey getSecretKey(String keyValue) { byte[] b; try { MessageDigest sha = MessageDigest.getInstance(HASH_TYPE); b = sha.digest(keyValue.getBytes(KEY_VALUE_ENCODING)); } catch (Exception e) { throw new PaxmlRuntimeException(e); } byte[] kb = new byte[KEY_LENGTH_BYTES]; // take the left 16 bytes part of the sha-1 System.arraycopy(b, 0, kb, 0, kb.length); return new SecretKeySpec(kb, KEY_TYPE); } public static String base64Encode(byte[] data) { return new Base64Encoder().encode(data); } public static byte[] base64Decode(String data) { return new Base64Encoder().decode(data); } public static String hexEncode(byte[] data) { return new String(Hex.encodeHex(data)); } public static byte[] hexDecode(String data) { try { return Hex.decodeHex(data.toCharArray()); } catch (DecoderException e) { throw new PaxmlRuntimeException(e); } } public static byte[] encrypt(String data, String password) { SecretKey SecKey = getSecretKey(password); try { KeyGenerator KeyGen = KeyGenerator.getInstance(KEY_TYPE); KeyGen.init(KEY_LENGTH_BITS); Cipher cipher = Cipher.getInstance(KEY_TYPE); byte[] clear = data.getBytes(KEY_VALUE_ENCODING); cipher.init(Cipher.ENCRYPT_MODE, SecKey); return cipher.doFinal(clear); } catch (Exception e) { throw new PaxmlRuntimeException(e); } } public static String decrypt(byte[] data, String password) { SecretKey SecKey = getSecretKey(password); try { KeyGenerator KeyGen = KeyGenerator.getInstance(KEY_TYPE); KeyGen.init(KEY_LENGTH_BITS); Cipher cipher = Cipher.getInstance(KEY_TYPE); cipher.init(Cipher.DECRYPT_MODE, SecKey); byte[] clear = cipher.doFinal(data); return new String(clear, KEY_VALUE_ENCODING); } catch (Exception e) { throw new PaxmlRuntimeException(e); } } private static File getKeyStoreFile(String keyStoreName) { if (StringUtils.isBlank(keyStoreName)) { keyStoreName = DEFAULT_KEY_STORE_NAME; } String fileName = KEY_STORE_FOLDER + File.separatorChar + keyStoreName + "." + KEY_STORE_EXT; File file = PaxmlUtils.getFileUnderPaxmlHome(fileName, false); if (file == null) { file = PaxmlUtils.getFileUnderUserHome(fileName); } return file; } public static void changeKeyStorePassword(String keyStoreName, final String oldPassword, final String newPassword) { final File file = getKeyStoreFile(keyStoreName); final String key = file.getAbsolutePath(); keyStoreExecutor.executeWrite(key, new Callable<Void>() { @Override public Void call() throws Exception { KeyStore keyStore = getKeyStore(file, oldPassword); saveKeyStore(file, newPassword, keyStore); return null; } }); } public static String getKey(String keyStoreName, final String keyStorePassword, final String keyName, final String keyPassword) { final File file = getKeyStoreFile(keyStoreName); final String key = file.getAbsolutePath(); return keyStoreExecutor.executeRead(key, new Callable<String>() { @Override public String call() throws Exception { KeyStore keyStore = getKeyStore(file, keyStorePassword); return getKey(keyStore, keyName, keyPassword); } }); } private static String getKey(KeyStore keyStore, String keyName, String keyPassword) { if (StringUtils.isBlank(keyName)) { keyName = DEFAULT_KEY_NAME; } if (keyPassword == null) { keyPassword = DEFAULT_KEY_PASSWORD; } PasswordProtection _keyPassword = new PasswordProtection(keyPassword.toCharArray()); KeyStore.Entry entry; try { if (!keyStore.containsAlias(keyName)) { return null; } entry = keyStore.getEntry(keyName, _keyPassword); } catch (Exception e) { throw new PaxmlRuntimeException(e); } SecretKey key = ((KeyStore.SecretKeyEntry) entry).getSecretKey(); try { return new String(key.getEncoded(), KEY_VALUE_ENCODING); } catch (UnsupportedEncodingException e) { throw new PaxmlRuntimeException(e); } } public static boolean deleteKeyStore(String keyStoreName) { final File file = getKeyStoreFile(keyStoreName); return keyStoreExecutor.executeWrite(file.getAbsolutePath(), new Callable<Boolean>() { @Override public Boolean call() throws Exception { return file.delete(); } }); } public static void deleteKey(String keyStoreName, final String keyStorePassword, final String keyName) { final File file = getKeyStoreFile(keyStoreName); keyStoreExecutor.executeWrite(file.getAbsolutePath(), new Callable<Void>() { @Override public Void call() throws Exception { deleteKey(getKeyStore(file, keyStorePassword), keyName); return null; } }); } private static void deleteKey(KeyStore keyStore, String keyName) { try { if (keyStore.containsAlias(keyName)) { keyStore.deleteEntry(keyName); } } catch (KeyStoreException e) { throw new PaxmlRuntimeException(e); } } public static void setKey(String keyStoreName, final String keyStorePassword, final String keyName, final String keyPassword, final String keyValue) { final File file = getKeyStoreFile(keyStoreName); final String key = file.getAbsolutePath(); keyStoreExecutor.executeWrite(key, new Callable<Void>() { @Override public Void call() throws Exception { KeyStore keyStore = getKeyStore(file, keyStorePassword); setKey(keyStore, keyName, keyPassword, keyValue); saveKeyStore(file, keyStorePassword, keyStore); return null; } }); } private static void setKey(KeyStore keyStore, String keyName, String keyPassword, String keyValue) { if (StringUtils.isBlank(keyName)) { keyName = DEFAULT_KEY_NAME; } if (keyPassword == null) { keyPassword = DEFAULT_KEY_PASSWORD; } try { SecretKey secretKey = new SecretKeySpec(keyValue.getBytes(KEY_VALUE_ENCODING), KEY_TYPE); KeyStore.SecretKeyEntry keyStoreEntry = new KeyStore.SecretKeyEntry(secretKey); PasswordProtection _keyPassword = new PasswordProtection(keyPassword.toCharArray()); keyStore.setEntry(keyName, keyStoreEntry, _keyPassword); } catch (Exception e) { throw new PaxmlRuntimeException(e); } } private static void saveKeyStore(final File file, final String password, final KeyStore ks) { file.delete(); FileOutputStream fos = null; try { fos = new FileOutputStream(file); ks.store(fos, password.toCharArray()); } catch (Exception e) { throw new PaxmlRuntimeException("Cannot write to key store file: " + file.getAbsolutePath(), e); } finally { IOUtils.closeQuietly(fos); } } private static KeyStore getKeyStore(final File file, final String password) { final String key = file.getAbsolutePath(); KeyStore keyStore; final char[] pwd = password.toCharArray(); if (!file.exists()) { FileOutputStream fos = null; try { file.getParentFile().mkdirs(); fos = new FileOutputStream(file); // keystore file not created yet => create it keyStore = KeyStore.getInstance(KEY_STORE_TYPE); keyStore.load(null, null); keyStore.store(fos, pwd); } catch (Exception e) { throw new PaxmlRuntimeException("Cannot create new key store file: " + key, e); } finally { IOUtils.closeQuietly(fos); } } FileInputStream fis = null; try { fis = new FileInputStream(file); keyStore = KeyStore.getInstance(KEY_STORE_TYPE); // keystore file already exists => load it keyStore.load(fis, pwd); } catch (Exception e) { throw new PaxmlRuntimeException("Cannot read from key store file: " + key, e); } finally { IOUtils.closeQuietly(fis); } return keyStore; } }
// -*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: // @homepage@ package example; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; public final class MainPanel extends JPanel { private MainPanel() { super(new BorderLayout()); JCheckBox check = new JCheckBox("JMenu: hover(show popup automatically) on cursor", true); JMenuBar bar = makeMenuBar(); addListenerToJMenu(bar, new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (check.isSelected()) { ((AbstractButton) e.getComponent()).doClick(); } } @Override public void mouseEntered(MouseEvent e) { if (check.isSelected()) { ((AbstractButton) e.getComponent()).doClick(); } } }); EventQueue.invokeLater(() -> getRootPane().setJMenuBar(bar)); add(check, BorderLayout.SOUTH); setPreferredSize(new Dimension(320, 240)); } private static JMenuBar makeMenuBar() { JMenuBar bar = new JMenuBar(); JMenu menu = bar.add(new JMenu("File")); menu.add("Open"); menu.add("Save"); menu.add("Exit"); menu = bar.add(new JMenu("Edit")); menu.add("Undo"); menu.add("Redo"); menu.addSeparator(); menu.add("Cut"); menu.add("Copy"); menu.add("Paste"); menu.add("Delete"); menu = bar.add(new JMenu("Test")); menu.add("JMenuItem1"); menu.add("JMenuItem2"); JMenu sub = new JMenu("JMenu"); sub.add("JMenuItem4"); sub.add("JMenuItem5"); menu.add(sub); menu.add("JMenuItem3"); return bar; } private static void addListenerToJMenu(JToolBar toolBar, MouseListener l) { // for (Component menu: toolBar.getComponents()) { for (MenuElement menu: toolBar.getSubElements()) { if (menu instanceof JMenu) { ((JMenu) menu).addMouseListener(l); } } } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGui(); } }); } public static void createAndShowGui() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); Toolkit.getDefaultToolkit().beep(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
// of patent rights can be found in the PATENTS file in the same directory. package org.rocksdb; /** * The config for plain table sst format. * * BlockBasedTable is a RocksDB's default SST file format. */ public class BlockBasedTableConfig extends TableFormatConfig { public BlockBasedTableConfig() { noBlockCache_ = false; blockCacheSize_ = 8 * 1024 * 1024; blockCacheNumShardBits_ = 0; blockSize_ = 4 * 1024; blockSizeDeviation_ = 10; blockRestartInterval_ = 16; wholeKeyFiltering_ = true; filter_ = null; cacheIndexAndFilterBlocks_ = false; pinL0FilterAndIndexBlocksInCache_ = false; hashIndexAllowCollision_ = true; blockCacheCompressedSize_ = 0; blockCacheCompressedNumShardBits_ = 0; checksumType_ = ChecksumType.kCRC32c; indexType_ = IndexType.kBinarySearch; formatVersion_ = 0; } /** * Disable block cache. If this is set to true, * then no block cache should be used, and the block_cache should * point to a {@code nullptr} object. * Default: false * * @param noBlockCache if use block cache * @return the reference to the current config. */ public BlockBasedTableConfig setNoBlockCache(final boolean noBlockCache) { noBlockCache_ = noBlockCache; return this; } /** * @return if block cache is disabled */ public boolean noBlockCache() { return noBlockCache_; } /** * Set the amount of cache in bytes that will be used by RocksDB. * If cacheSize is non-positive, then cache will not be used. * DEFAULT: 8M * * @param blockCacheSize block cache size in bytes * @return the reference to the current config. */ public BlockBasedTableConfig setBlockCacheSize(final long blockCacheSize) { blockCacheSize_ = blockCacheSize; return this; } /** * @return block cache size in bytes */ public long blockCacheSize() { return blockCacheSize_; } /** * Controls the number of shards for the block cache. * This is applied only if cacheSize is set to non-negative. * * @param blockCacheNumShardBits the number of shard bits. The resulting * number of shards would be 2 ^ numShardBits. Any negative * number means use default settings." * @return the reference to the current option. */ public BlockBasedTableConfig setCacheNumShardBits( final int blockCacheNumShardBits) { blockCacheNumShardBits_ = blockCacheNumShardBits; return this; } /** * Returns the number of shard bits used in the block cache. * The resulting number of shards would be 2 ^ (returned value). * Any negative number means use default settings. * * @return the number of shard bits used in the block cache. */ public int cacheNumShardBits() { return blockCacheNumShardBits_; } /** * Approximate size of user data packed per block. Note that the * block size specified here corresponds to uncompressed data. The * actual size of the unit read from disk may be smaller if * compression is enabled. This parameter can be changed dynamically. * Default: 4K * * @param blockSize block size in bytes * @return the reference to the current config. */ public BlockBasedTableConfig setBlockSize(final long blockSize) { blockSize_ = blockSize; return this; } /** * @return block size in bytes */ public long blockSize() { return blockSize_; } /** * This is used to close a block before it reaches the configured * 'block_size'. If the percentage of free space in the current block is less * than this specified number and adding a new record to the block will * exceed the configured block size, then this block will be closed and the * new record will be written to the next block. * Default is 10. * * @param blockSizeDeviation the deviation to block size allowed * @return the reference to the current config. */ public BlockBasedTableConfig setBlockSizeDeviation( final int blockSizeDeviation) { blockSizeDeviation_ = blockSizeDeviation; return this; } /** * @return the hash table ratio. */ public int blockSizeDeviation() { return blockSizeDeviation_; } /** * Set block restart interval * * @param restartInterval block restart interval. * @return the reference to the current config. */ public BlockBasedTableConfig setBlockRestartInterval( final int restartInterval) { blockRestartInterval_ = restartInterval; return this; } /** * @return block restart interval */ public int blockRestartInterval() { return blockRestartInterval_; } /** * If true, place whole keys in the filter (not just prefixes). * This must generally be true for gets to be efficient. * Default: true * * @param wholeKeyFiltering if enable whole key filtering * @return the reference to the current config. */ public BlockBasedTableConfig setWholeKeyFiltering( final boolean wholeKeyFiltering) { wholeKeyFiltering_ = wholeKeyFiltering; return this; } /** * @return if whole key filtering is enabled */ public boolean wholeKeyFiltering() { return wholeKeyFiltering_; } /** * Use the specified filter policy to reduce disk reads. * * {@link org.rocksdb.Filter} should not be disposed before options instances * using this filter is disposed. If {@link Filter#dispose()} function is not * called, then filter object will be GC'd automatically. * * {@link org.rocksdb.Filter} instance can be re-used in multiple options * instances. * * @param filter {@link org.rocksdb.Filter} Filter Policy java instance. * @return the reference to the current config. */ public BlockBasedTableConfig setFilter( final Filter filter) { filter_ = filter; return this; } /** * Indicating if we'd put index/filter blocks to the block cache. If not specified, each "table reader" object will pre-load index/filter block during table initialization. * * @return if index and filter blocks should be put in block cache. */ public boolean cacheIndexAndFilterBlocks() { return cacheIndexAndFilterBlocks_; } /** * Indicating if we'd put index/filter blocks to the block cache. If not specified, each "table reader" object will pre-load index/filter block during table initialization. * * @param cacheIndexAndFilterBlocks and filter blocks should be put in block cache. * @return the reference to the current config. */ public BlockBasedTableConfig setCacheIndexAndFilterBlocks( final boolean cacheIndexAndFilterBlocks) { cacheIndexAndFilterBlocks_ = cacheIndexAndFilterBlocks; return this; } /** * Indicating if we'd like to pin L0 index/filter blocks to the block cache. If not specified, defaults to false. * * @return if L0 index and filter blocks should be pinned to the block cache. */ public boolean pinL0FilterAndIndexBlocksInCache() { return pinL0FilterAndIndexBlocksInCache_; } /** * Indicating if we'd like to pin L0 index/filter blocks to the block cache. If not specified, defaults to false. * * @param pinL0FilterAndIndexBlocksInCache pin blocks in block cache * @return the reference to the current config. */ public BlockBasedTableConfig setPinL0FilterAndIndexBlocksInCache( final boolean pinL0FilterAndIndexBlocksInCache) { pinL0FilterAndIndexBlocksInCache_ = pinL0FilterAndIndexBlocksInCache; return this; } /** * Influence the behavior when kHashSearch is used. if false, stores a precise prefix to block range mapping if true, does not store prefix and allows prefix hash collision (less memory consumption) * * @return if hash collisions should be allowed. */ public boolean hashIndexAllowCollision() { return hashIndexAllowCollision_; } /** * Influence the behavior when kHashSearch is used. if false, stores a precise prefix to block range mapping if true, does not store prefix and allows prefix hash collision (less memory consumption) * * @param hashIndexAllowCollision points out if hash collisions should be allowed. * @return the reference to the current config. */ public BlockBasedTableConfig setHashIndexAllowCollision( final boolean hashIndexAllowCollision) { hashIndexAllowCollision_ = hashIndexAllowCollision; return this; } /** * Size of compressed block cache. If 0, then block_cache_compressed is set * to null. * * @return size of compressed block cache. */ public long blockCacheCompressedSize() { return blockCacheCompressedSize_; } /** * Size of compressed block cache. If 0, then block_cache_compressed is set * to null. * * @param blockCacheCompressedSize of compressed block cache. * @return the reference to the current config. */ public BlockBasedTableConfig setBlockCacheCompressedSize( final long blockCacheCompressedSize) { blockCacheCompressedSize_ = blockCacheCompressedSize; return this; } /** * Controls the number of shards for the block compressed cache. * This is applied only if blockCompressedCacheSize is set to non-negative. * * @return numShardBits the number of shard bits. The resulting * number of shards would be 2 ^ numShardBits. Any negative * number means use default settings. */ public int blockCacheCompressedNumShardBits() { return blockCacheCompressedNumShardBits_; } /** * Controls the number of shards for the block compressed cache. * This is applied only if blockCompressedCacheSize is set to non-negative. * * @param blockCacheCompressedNumShardBits the number of shard bits. The resulting * number of shards would be 2 ^ numShardBits. Any negative * number means use default settings." * @return the reference to the current option. */ public BlockBasedTableConfig setBlockCacheCompressedNumShardBits( final int blockCacheCompressedNumShardBits) { blockCacheCompressedNumShardBits_ = blockCacheCompressedNumShardBits; return this; } /** * Sets the checksum type to be used with this table. * * @param checksumType {@link org.rocksdb.ChecksumType} value. * @return the reference to the current option. */ public BlockBasedTableConfig setChecksumType( final ChecksumType checksumType) { checksumType_ = checksumType; return this; } /** * * @return the currently set checksum type */ public ChecksumType checksumType() { return checksumType_; } /** * Sets the index type to used with this table. * * @param indexType {@link org.rocksdb.IndexType} value * @return the reference to the current option. */ public BlockBasedTableConfig setIndexType( final IndexType indexType) { indexType_ = indexType; return this; } /** * * @return the currently set index type */ public IndexType indexType() { return indexType_; } /** * <p>We currently have three versions:</p> * * <ul> * <li><strong>0</strong> - This version is currently written * out by all RocksDB's versions by default. Can be read by really old * RocksDB's. Doesn't support changing checksum (default is CRC32).</li> * <li><strong>1</strong> - Can be read by RocksDB's versions since 3.0. * Supports non-default checksum, like xxHash. It is written by RocksDB when * BlockBasedTableOptions::checksum is something other than kCRC32c. (version * 0 is silently upconverted)</li> * <li><strong>2</strong> - Can be read by RocksDB's versions since 3.10. * Changes the way we encode compressed blocks with LZ4, BZip2 and Zlib * compression. If you don't plan to run RocksDB before version 3.10, * you should probably use this.</li> * </ul> * <p> This option only affects newly written tables. When reading existing * tables, the information about version is read from the footer.</p> * * @param formatVersion integer representing the version to be used. * @return the reference to the current option. */ public BlockBasedTableConfig setFormatVersion( final int formatVersion) { assert(formatVersion >= 0 && formatVersion <= 2); formatVersion_ = formatVersion; return this; } /** * * @return the currently configured format version. * See also: {@link #setFormatVersion(int)}. */ public int formatVersion() { return formatVersion_; } @Override protected long newTableFactoryHandle() { long filterHandle = 0; if (filter_ != null) { filterHandle = filter_.nativeHandle_; } return newTableFactoryHandle(noBlockCache_, blockCacheSize_, blockCacheNumShardBits_, blockSize_, blockSizeDeviation_, blockRestartInterval_, wholeKeyFiltering_, filterHandle, cacheIndexAndFilterBlocks_, pinL0FilterAndIndexBlocksInCache_, hashIndexAllowCollision_, blockCacheCompressedSize_, blockCacheCompressedNumShardBits_, checksumType_.getValue(), indexType_.getValue(), formatVersion_); } private native long newTableFactoryHandle( boolean noBlockCache, long blockCacheSize, int blockCacheNumShardBits, long blockSize, int blockSizeDeviation, int blockRestartInterval, boolean wholeKeyFiltering, long filterPolicyHandle, boolean cacheIndexAndFilterBlocks, boolean pinL0FilterAndIndexBlocksInCache, boolean hashIndexAllowCollision, long blockCacheCompressedSize, int blockCacheCompressedNumShardBits, byte checkSumType, byte indexType, int formatVersion); private boolean cacheIndexAndFilterBlocks_; private boolean pinL0FilterAndIndexBlocksInCache_; private IndexType indexType_; private boolean hashIndexAllowCollision_; private ChecksumType checksumType_; private boolean noBlockCache_; private long blockSize_; private long blockCacheSize_; private int blockCacheNumShardBits_; private long blockCacheCompressedSize_; private int blockCacheCompressedNumShardBits_; private int blockSizeDeviation_; private int blockRestartInterval_; private Filter filter_; private boolean wholeKeyFiltering_; private int formatVersion_; }
package com.fatecpg.data; import br.com.fatecpg.helpers.ConnectionFactory; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; public class Alternativa { private Integer _id; private String _texto; private boolean _correta; private int _questaoId; public Alternativa(String texto, boolean correta, int questionId) { this._texto = texto; this._correta = correta; this._questaoId = questionId; } public Alternativa(Integer id, String texto, boolean correta, int questionId) { this._id = id; this._texto = texto; this._correta = correta; this._questaoId = questionId; } // public int getId() { return _id; } public String getTexto() { return _texto; } public void setTexto(String texto) { this._texto = texto; } public boolean isCorreta() { return _correta; } public void setCorreta(boolean correta) { this._correta = correta; } public int getQuestaoId() { return _questaoId; } public void setQuestaoId(int _questaoId) { this._questaoId = _questaoId; } // // Insere o registro no banco de dados de acordo com os atributos do objeto public boolean store() throws SQLException { try (Connection connection = ConnectionFactory.getConnection()) { try { Statement statement = connection.createStatement(); String SQL = String.format("INSERT INTO ALTERNATIVA(TEXTO, CORRECT, QUESTAO_ID) VALUES('%s', %b, %d)", this._texto, this._correta, this._questaoId); statement.execute(SQL, Statement.RETURN_GENERATED_KEYS); ResultSet rs = statement.getGeneratedKeys(); if (rs.next()) { this._id = rs.getInt(1); } rs.close(); if (this._id != null) { return true; } } catch (SQLException ex) { throw ex; } connection.close(); } return false; } // Busca uma alternativa pelo ID public static Alternativa find(Integer id) throws SQLException { try (Connection connection = ConnectionFactory.getConnection()) { PreparedStatement pstatement = connection.prepareStatement(String.format("SELECT * FROM ALTERNATIVA WHERE ID = ?")); pstatement.setInt(1, id); try (ResultSet result = pstatement.executeQuery()) { if (result.next()) { return new Alternativa( result.getInt("ID"), result.getString("TEXTO"), result.getBoolean("CORRECT"), result.getInt("QUESTAO_ID") ); } } catch (Exception ex) { System.out.println("Erro ao consultar a Alternativa: " + ex.getMessage()); } connection.close(); } catch (Exception ex) { System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage()); } return null; } // Retorna todas as alternativas public static ArrayList<Alternativa> all() throws SQLException { ArrayList<Alternativa> alternativas = new ArrayList<>(); try (Connection connection = ConnectionFactory.getConnection()) { Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("SELECT * FROM ALTERNATIVA"); while (result.next()) { alternativas.add(new Alternativa( result.getInt("ID"), result.getString("TEXTO"), result.getBoolean("CORRECT"), result.getInt("QUESTAO_ID") )); } } catch (Exception ex) { System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage()); } return alternativas; } public static ArrayList<Alternativa> all(int questaoId) throws SQLException { ArrayList<Alternativa> alternativas = new ArrayList<>(); try (Connection connection = ConnectionFactory.getConnection()) { Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("SELECT * FROM ALTERNATIVA WHERE QUESTAO_ID = " + questaoId); while (result.next()) { alternativas.add(new Alternativa( result.getInt("ID"), result.getString("TEXTO"), result.getBoolean("CORRECT"), result.getInt("QUESTAO_ID") )); } } catch (Exception ex) { System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage()); } return alternativas; } public boolean update() throws SQLException { try { int linhasAlteradas = 0; try (Connection connection = ConnectionFactory.getConnection()) { String SQL = String.format( "UPDATE ALTERNATIVA SET TEXTO = '%s', CORRECT = %b, QUESTAO_ID = %d WHERE ID = %d", this._texto, this._correta, this._questaoId, this._id ); try (Statement statement = connection.createStatement()) { linhasAlteradas = statement.executeUpdate(SQL); } catch (Exception ex) { System.out.println("Erro ao atualizar Alternativa: " + ex.getMessage()); } } return linhasAlteradas > 0; } catch (SQLException ex) { System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage()); } return false; } // Remove registro do banco de dados public boolean delete() throws SQLException { try (Connection connection = ConnectionFactory.getConnection()) { try (PreparedStatement pstatement = connection.prepareStatement("DELETE FROM ALTERNATIVA WHERE ID = ?")) { pstatement.setInt(1, this._id); pstatement.execute(); } catch (Exception ex) { System.out.println("Erro ao excluir a Alternativa: " + ex.getMessage()); } connection.close(); if (Alternativa.find(this._id) == null) { return true; } } catch (Exception ex) { System.out.println("Erro ao obter conexão com o banco de dados: " + ex.getMessage()); } return false; } public Questao getQuestao() { try { return Questao.find(this._questaoId); } catch (SQLException ex) { System.out.println("Não foi possível carregar a Questão: " + ex.getMessage()); } return null; } }
package uk.org.opentrv.ETV.filter; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import uk.org.opentrv.ETV.ETVPerHouseholdComputation.ETVPerHouseholdComputationSystemStatus; import uk.org.opentrv.ETV.ETVPerHouseholdComputation.SavingEnabledAndDataStatus; import uk.org.opentrv.ETV.parse.OTLogActivityParse.ValveLogParseResult; /**Algorithms for data segmentation into control/normal/ignore periods. * These algorithms are important to the robustness of the efficacy analysis. */ public final class StatusSegmentation { private StatusSegmentation() { /* Prevent instance instantiation. */ } /**Examine the activity and status of the energy-saving devices in a household to decide how to analyse each day. * This can use days where any device in the household * is calling for heat AND reporting its energy saving status (enabled or disabled). * <p> * Within those days, any that are marked as having energy saving features disabled * for the majority of devices can be regarded as control days; * where the majority have energy saving features enabled are normal days. * * @param devices collection of devices (eg valves) in household; never null * @return the overall household status by day; never null */ public static ETVPerHouseholdComputationSystemStatus segmentActivity(final Collection<ValveLogParseResult> devices) { if(null == devices) { throw new IllegalArgumentException(); } // // Deal with empty input quickly (result has no usable days). // if(devices.isEmpty()) // return(new ETVPerHouseholdComputationSystemStatus(){ // @Override public SortedMap<Integer, SavingEnabledAndDataStatus> getOptionalEnabledAndUsableFlagsByLocalDay() // { return(Collections.<Integer, SavingEnabledAndDataStatus>emptySortedMap()); } final SortedMap<Integer, SavingEnabledAndDataStatus> result = new TreeMap<>(); // Potentially usable days: where any device in the household // is calling for heat AND reporting its energy saving status (enabled or disabled) final Set<Integer> potentiallyUsableDays = new HashSet<>(); for(final ValveLogParseResult vlpr : devices) { final Set<Integer> s = new HashSet<>(vlpr.getDaysInWhichCallingForHeat()); s.retainAll(vlpr.getDaysInWhichEnergySavingStatsReported()); potentiallyUsableDays.addAll(s); } // From potentially usable days note those with majority of devices with // reporting energy-saving status and with energy-saving features enabled/disabled. // Other days, without a clear majority, are explicitly marked as unusable. final int quorum = (devices.size() / 2) + 1; for(final Integer day : potentiallyUsableDays) { int reportingSavingsEnabled = 0; int reportingSavingsDisabled = 0; for(final ValveLogParseResult vlpr : devices) { if(!vlpr.getDaysInWhichEnergySavingStatsReported().contains(day)) { continue; } if(vlpr.getDaysInWhichEnergySavingActive().contains(day)) { ++reportingSavingsEnabled; } else { ++reportingSavingsDisabled; } } if((reportingSavingsEnabled >= quorum) && (reportingSavingsEnabled > reportingSavingsDisabled)) { result.put(day, SavingEnabledAndDataStatus.Enabled); } else if((reportingSavingsDisabled >= quorum) && (reportingSavingsDisabled > reportingSavingsEnabled)) { result.put(day, SavingEnabledAndDataStatus.Disabled); } else { result.put(day, SavingEnabledAndDataStatus.DontUse); } } return(new ETVPerHouseholdComputationSystemStatus(){ @Override public SortedMap<Integer, SavingEnabledAndDataStatus> getOptionalEnabledAndUsableFlagsByLocalDay() { return(Collections.unmodifiableSortedMap(result)); } }); } }
package com.artemis.link; import com.artemis.ComponentType; import com.artemis.World; import com.artemis.annotations.LinkPolicy; import com.artemis.utils.IntBag; import com.artemis.utils.reflect.Field; class UniLinkSite extends LinkSite { UniFieldMutator fieldMutator; private final IntBag sourceToTarget = new IntBag(); protected UniLinkSite(World world, ComponentType type, Field field) { super(world, type, field, LinkPolicy.Policy.CHECK_SOURCE_AND_TARGETS); } @Override protected void check(int id) { // -1 == not linked int target = fieldMutator.read(mapper.get(id), field); if (target != -1 && !activeEntityIds.get(target)) { target = -1; fieldMutator.write(target, mapper.get(id), field); } int oldTarget = sourceToTarget.get(id); if (target != oldTarget) { sourceToTarget.set(id, target); if (oldTarget == -1) { if (listener != null) listener.onLinkEstablished(id, target); } else { if (listener != null) { if (target != -1) { listener.onTargetChanged(id, target, oldTarget); } else { listener.onTargetDead(id, oldTarget); } } } } } @Override protected void insert(int id) { int target = fieldMutator.read(mapper.get(id), field); sourceToTarget.set(id, target); if (target != -1 && listener != null) listener.onLinkEstablished(id, target); } @Override protected void removed(int id) { int target = sourceToTarget.size() > id ? sourceToTarget.get(id) : -1; if (target != -1) { sourceToTarget.set(id, 0); listener.onLinkKilled(id, target); } } }
package StevenDimDoors.mod_pocketDim.dungeon.pack; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import net.minecraft.util.WeightedRandom; import StevenDimDoors.mod_pocketDim.core.NewDimData; import StevenDimDoors.mod_pocketDim.dungeon.DungeonData; import StevenDimDoors.mod_pocketDim.helpers.DungeonHelper; import StevenDimDoors.mod_pocketDim.util.WeightedContainer; public class DungeonPack { //There is no precaution against having a dungeon type removed from a config file after dungeons of that type //have been generated. That would likely cause one or two problems. It's hard to guard against when I don't know //what the save format will be like completely. How should this class behave if it finds a "disowned" type? //The ID numbers would be a problem since it couldn't have a valid number, since it wasn't initialized by the pack instance. //FIXME: Do not release this code as an update without dealing with disowned types! private static final int MAX_HISTORY_LENGTH = 30; private final String name; private final HashMap<String, DungeonType> nameToTypeMapping; private final ArrayList<ArrayList<DungeonData>> groupedDungeons; private final ArrayList<DungeonData> allDungeons; private final DungeonPackConfig config; private final int maxRuleLength; private final ArrayList<DungeonChainRule> rules; public DungeonPack(DungeonPackConfig config) { config.validate(); this.config = config.clone(); //Store a clone of the config so that the caller can't change it externally later this.name = config.getName(); int index; int maxLength = 0; int typeCount = config.getTypeNames().size(); this.allDungeons = new ArrayList<DungeonData>(); this.nameToTypeMapping = new HashMap<String, DungeonType>(typeCount); this.groupedDungeons = new ArrayList<ArrayList<DungeonData>>(typeCount); this.groupedDungeons.add(allDungeons); //Make sure the list of all dungeons is placed at index 0 this.nameToTypeMapping.put(DungeonType.WILDCARD_TYPE.Name, DungeonType.WILDCARD_TYPE); index = 1; for (String typeName : config.getTypeNames()) { String standardName = typeName.toUpperCase(); this.nameToTypeMapping.put(standardName, new DungeonType(this, standardName, index)); this.groupedDungeons.add(new ArrayList<DungeonData>()); index++; } //Construct optimized rules from definitions ArrayList<DungeonChainRuleDefinition> definitions = config.getRules(); this.rules = new ArrayList<DungeonChainRule>(definitions.size()); for (DungeonChainRuleDefinition definition : definitions) { DungeonChainRule rule = new DungeonChainRule(definition, nameToTypeMapping); this.rules.add(rule); if (maxLength < rule.length()) { maxLength = rule.length(); } } this.maxRuleLength = maxLength; //Remove unnecessary references to save a little memory - we won't need them here this.config.setRules(null); this.config.setTypeNames(null); } public String getName() { return name; } public DungeonPackConfig getConfig() { return config.clone(); } public boolean isEmpty() { return allDungeons.isEmpty(); } public DungeonType getType(String typeName) { DungeonType result = nameToTypeMapping.get(typeName.toUpperCase()); if (result.Owner == this) //Filter out the wildcard dungeon type { return result; } else { return null; } } public boolean isKnownType(String typeName) { return (this.getType(typeName) != null); } public void addDungeon(DungeonData dungeon) { //Make sure this dungeon really belongs in this pack DungeonType type = dungeon.dungeonType(); if (type.Owner == this) { allDungeons.add(dungeon); groupedDungeons.get(type.ID).add(dungeon); } else { throw new IllegalArgumentException("The dungeon type of generator must belong to this instance of DungeonPack."); } } public DungeonData getNextDungeon(NewDimData dimension, Random random) { if (allDungeons.isEmpty()) { return null; } //Retrieve a list of the previous dungeons in this chain. //If we're not going to check for duplicates in chains, restrict the length of the history to the length //of the longest rule we have. Getting any more data would be useless. This optimization could be significant //for dungeon packs that can extend arbitrarily deep. We should probably set a reasonable limit anyway. int maxSearchLength = config.allowDuplicatesInChain() ? maxRuleLength : MAX_HISTORY_LENGTH; ArrayList<DungeonData> history = DungeonHelper.getDungeonChainHistory(dimension.parent(), this, maxSearchLength); return getNextDungeon(history, random); } private DungeonData getNextDungeon(ArrayList<DungeonData> history, Random random) { //Extract the dungeon types that have been used from history and convert them into an array of IDs int index; int[] typeHistory = new int[history.size()]; HashSet<DungeonData> excludedDungeons = null; for (index = 0; index < typeHistory.length; index++) { typeHistory[index] = history.get(index).dungeonType().ID; } for (DungeonChainRule rule : rules) { if (rule.evaluate(typeHistory)) { //Pick a random dungeon type to be generated next based on the rule's products ArrayList<WeightedContainer<DungeonType>> products = rule.products(); DungeonType nextType; do { nextType = getRandomDungeonType(random, products, groupedDungeons); if (nextType != null) { //Initialize the set of excluded dungeons if needed if (excludedDungeons == null && !config.allowDuplicatesInChain()) { excludedDungeons = new HashSet<DungeonData>(history); } //List which dungeons are allowed ArrayList<DungeonData> candidates; ArrayList<DungeonData> group = groupedDungeons.get(nextType.ID); if (excludedDungeons != null && !excludedDungeons.isEmpty()) { candidates = new ArrayList<DungeonData>(group.size()); for (DungeonData dungeon : group) { if (!excludedDungeons.contains(dungeon)) { candidates.add(dungeon); } } } else { candidates = group; } if (!candidates.isEmpty()) { return getRandomDungeon(random, candidates); } //If we've reached this point, then a dungeon was not selected. Discard the type and try again. for (index = 0; index < products.size(); index++) { if (products.get(index).getData().equals(nextType)) { products.remove(index); break; } } } } while (nextType != null); } } //None of the rules were applicable. Simply return a random dungeon. return getRandomDungeon(random); } public DungeonData getRandomDungeon(Random random) { if (!allDungeons.isEmpty()) { return getRandomDungeon(random, allDungeons); } else { return null; } } private static DungeonType getRandomDungeonType(Random random, Collection<WeightedContainer<DungeonType>> types, ArrayList<ArrayList<DungeonData>> groupedDungeons) { //TODO: Make this faster? This algorithm runs in quadratic time in the worst case because of the random-selection //process and the removal search. Might be okay for normal use, though. ~SenseiKiwi //Pick a random dungeon type based on weights. Repeat this process until a non-empty group is found or all groups are checked. while (!types.isEmpty()) { //Pick a random dungeon type @SuppressWarnings("unchecked") WeightedContainer<DungeonType> resultContainer = (WeightedContainer<DungeonType>) WeightedRandom.getRandomItem(random, types); //Check if there are any dungeons of that type DungeonType selectedType = resultContainer.getData(); if (!groupedDungeons.get(selectedType.ID).isEmpty()) { //Choose this type return selectedType; } else { //We can't use this type because there are no dungeons of this type //Remove it from the list of types and try again types.remove(resultContainer); } } //We have run out of types to try return null; } private static DungeonData getRandomDungeon(Random random, Collection<DungeonData> dungeons) { //Use Minecraft's WeightedRandom to select our dungeon. =D ArrayList<WeightedContainer<DungeonData>> weights = new ArrayList<WeightedContainer<DungeonData>>(dungeons.size()); for (DungeonData dungeon : dungeons) { weights.add(new WeightedContainer<DungeonData>(dungeon, dungeon.weight())); } @SuppressWarnings("unchecked") WeightedContainer<DungeonData> resultContainer = (WeightedContainer<DungeonData>) WeightedRandom.getRandomItem(random, weights); return (resultContainer != null) ? resultContainer.getData() : null; } }
package com.hd.snscoins.webentities; import java.util.List; public class WeProduct { Long product_id; Long sub_category_id; String product_title; List<WeYear> product_mint; String product_image; public String getProduct_image() { return product_image; } public void setProduct_image(String product_image) { this.product_image = product_image; } public List<WeYear> getProduct_mint() { return product_mint; } public void setProduct_mint(List<WeYear> product_mint) { this.product_mint = product_mint; } public Long getProduct_id() { return product_id; } public void setProduct_id(Long product_id) { this.product_id = product_id; } public Long getSub_category_id() { return sub_category_id; } public void setSub_category_id(Long sub_category_id) { this.sub_category_id = sub_category_id; } public String getProduct_title() { return product_title; } public void setProduct_title(String product_title) { this.product_title = product_title; } public class WeYear { String year; List<WeMint> mint_title; public String getYear() { return year; } public void setYear(String year) { this.year = year; } public List<WeMint> getMint_title() { return mint_title; } public void setMint_title(List<WeMint> mint_title) { this.mint_title = mint_title; } } public class WeMint { String title; Integer is_rare; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Integer getIs_rare() { return is_rare; } public void setIs_rare(Integer is_rare) { this.is_rare = is_rare; } } }
package io.spine.code.proto; import com.google.common.collect.ImmutableList; import com.google.protobuf.DescriptorProtos; import com.google.protobuf.DescriptorProtos.DescriptorProto; import com.google.protobuf.DescriptorProtos.FileDescriptorProto; import com.google.protobuf.DescriptorProtos.MessageOptions; import com.google.protobuf.Descriptors.Descriptor; import com.google.protobuf.Descriptors.FileDescriptor; import com.google.protobuf.Message; import io.spine.code.java.ClassName; import io.spine.code.java.SimpleClassName; import io.spine.code.java.VBuilderClassName; import io.spine.logging.Logging; import io.spine.option.IsOption; import io.spine.type.TypeName; import io.spine.type.TypeUrl; import java.util.ArrayDeque; import java.util.Deque; import java.util.Optional; import java.util.function.Predicate; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Lists.newLinkedList; import static io.spine.code.proto.FileDescriptors.sameFiles; import static io.spine.option.OptionsProto.enrichmentFor; /** * A message type as declared in a proto file. */ public class MessageType extends Type<Descriptor, DescriptorProto> implements Logging { /** * Standard suffix for a Validating Builder class name. */ public static final String VBUILDER_SUFFIX = "VBuilder"; /** * Creates a new instance by the given message descriptor. */ public MessageType(Descriptor descriptor) { super(descriptor, true); } public static MessageType of(Class<? extends Message> aClass) { TypeName typeName = TypeName.of(aClass); Descriptor descriptor = typeName.messageDescriptor(); return new MessageType(descriptor); } /** * Collects all message types, including nested, declared in the passed file. */ static TypeSet allFrom(FileDescriptor file) { checkNotNull(file); TypeSet.Builder result = TypeSet.newBuilder(); for (Descriptor messageType : file.getMessageTypes()) { addType(messageType, result); } return result.build(); } private static void addType(Descriptor type, TypeSet.Builder set) { if (type.getOptions() .getMapEntry()) { return; } MessageType messageType = new MessageType(type); set.add(messageType); for (Descriptor nestedType : type.getNestedTypes()) { addType(nestedType, set); } } @Override public final DescriptorProto toProto() { return descriptor().toProto(); } @Override public final TypeUrl url() { return TypeUrl.from(descriptor()); } @Override public final ClassName javaClassName() { return ClassName.from(descriptor()); } @Override @SuppressWarnings("unchecked") // It is safe since we work with a message descriptors public Class<? extends Message> javaClass() { return (Class<? extends Message>) super.javaClass(); } /** * Obtains source file with the declaration of this message type. */ public SourceFile sourceFile() { return SourceFile.from(descriptor().getFile()); } /** * Tells if this message is under the "google" package. */ public boolean isGoogle() { FileDescriptor file = descriptor().getFile(); boolean result = FileDescriptors.isGoogle(file); return result; } /** * Tells if this message type is not from "google" package, and is not an extension * defined in "options.proto". */ public boolean isCustom() { if (isGoogle()) { return false; } FileDescriptor optionsProto = IsOption.getDescriptor() .getFile(); FileDescriptor file = descriptor().getFile(); return !sameFiles(optionsProto, file); } /** * Tells if this message is top-level in its file. */ public boolean isTopLevel() { Descriptor descriptor = descriptor(); Descriptor parent = descriptor.getContainingType(); return parent == null; } /** * Tells if this message is nested inside another message declaration. */ public boolean isNested() { return !isTopLevel(); } /** * Tells if this message is a rejection. */ public boolean isRejection() { boolean result = isTopLevel() && declaringFileName().isRejections(); return result; } /** * Tells if this message is a command. */ public boolean isCommand() { boolean result = isTopLevel() && declaringFileName().isCommands(); return result; } /** * Tells if this message is an event. * * <p>Returns {@code false} if this type is a {@linkplain #isRejection() rejection}. */ public boolean isEvent() { boolean result = isTopLevel() && declaringFileName().isEvents(); return result; } private FileName declaringFileName() { return FileName.from(descriptor().getFile()); } /** * Tells if the message is an enrichment. */ public boolean isEnrichment() { MessageOptions options = descriptor().getOptions(); boolean result = isTopLevel() && options.hasExtension(enrichmentFor); return result; } public SimpleClassName validatingBuilderClass() { checkState(isCustom(), "No validating builder class available for the type `%s`.", this); SimpleClassName result = VBuilderClassName.of(this); return result; } /** * Obtains all nested declarations that match the passed predicate. */ ImmutableList<MessageType> getAllNested(Predicate<DescriptorProto> predicate) { ImmutableList.Builder<MessageType> result = ImmutableList.builder(); Iterable<MessageType> nestedDeclarations = getImmediateNested(); Deque<MessageType> deque = newLinkedList(nestedDeclarations); while (!deque.isEmpty()) { MessageType nestedDeclaration = deque.pollFirst(); assert nestedDeclaration != null; // Cannot be null since the queue is not empty. DescriptorProto nestedDescriptor = nestedDeclaration.descriptor() .toProto(); if (predicate.test(nestedDescriptor)) { result.add(nestedDeclaration); } deque.addAll(nestedDeclaration.getImmediateNested()); } return result.build(); } /** * Obtains immediate declarations of nested types of this declaration, or * empty list if no nested types are declared. */ private ImmutableList<MessageType> getImmediateNested() { ImmutableList<MessageType> result = descriptor().getNestedTypes() .stream() .map(MessageType::new) .collect(toImmutableList()); return result; } /** * Obtains fields declared in the message type. */ public ImmutableList<FieldDeclaration> fields() { ImmutableList<FieldDeclaration> result = descriptor().getFields() .stream() .map(d -> new FieldDeclaration(d, this)) .collect(toImmutableList()); return result; } /** * Returns the message location path for a top-level message definition. * * @return the message location path */ LocationPath path() { LocationPath path = new LocationPath(); path.add(FileDescriptorProto.MESSAGE_TYPE_FIELD_NUMBER); Descriptor descriptor = descriptor(); if (isNested()) { Deque<Integer> parentPath = new ArrayDeque<>(); Descriptor containingType = descriptor.getContainingType(); while (containingType != null) { parentPath.addFirst(containingType.getIndex()); containingType = containingType.getContainingType(); } path.addAll(parentPath); } path.add(descriptor.getIndex()); return path; } public Optional<String> leadingComments() { LocationPath messagePath = path(); return leadingComments(messagePath); } /** * Obtains a leading comments by the {@link LocationPath}. * * @param locationPath * the location path to get leading comments * @return the leading comments or empty {@code Optional} if there are no such comments or * a descriptor was generated without source code information */ Optional<String> leadingComments(LocationPath locationPath) { FileDescriptorProto file = descriptor() .getFile() .toProto(); if (!file.hasSourceCodeInfo()) { _warn("Unable to obtain proto source code info. " + "Please configure the Gradle Protobuf plugin as follows:%n%s", "`task.descriptorSetOptions.includeSourceInfo = true`."); return Optional.empty(); } DescriptorProtos.SourceCodeInfo.Location location = locationPath.toLocation(file); return location.hasLeadingComments() ? Optional.of(location.getLeadingComments()) : Optional.empty(); } }
package io.tetrapod.core.web; import io.netty.buffer.ByteBuf; import io.netty.channel.socket.SocketChannel; import io.tetrapod.core.*; import io.tetrapod.core.json.JSONObject; import io.tetrapod.core.rpc.Structure; import io.tetrapod.core.serialize.datasources.*; import io.tetrapod.protocol.core.*; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; import org.slf4j.*; abstract class WebSession extends Session { private static final Logger logger = LoggerFactory.getLogger(WebSession.class); protected final AtomicInteger requestCount = new AtomicInteger(0); public WebSession(SocketChannel channel, Session.Helper helper) { super(channel, helper); } abstract protected Object makeFrame(JSONObject jo, boolean keepAlive); protected Structure readRequest(RequestHeader header, JSONObject params) throws IOException { Structure request = StructureFactory.make(header.contractId, header.structId); if (request == null) { logger.error("Could not find request structure contractId={} structId-{}", header.contractId, header.structId); return null; } request.read(new WebJSONDataSource(params, request.tagWebNames())); commsLog("%s [%d] <- %s", this, header.requestId, request.dump()); return request; } @Override protected Object makeFrame(Structure header, Structure payload, byte envelope) { try { JSONObject jo = extractHeader(header); JSONDataSource jd = new WebJSONDataSource(jo, payload.tagWebNames()); payload.write(jd); return makeFrame(jo, true); } catch (IOException e) { logger.error("Could not make web frame for {}", header.dump()); return null; } } protected JSONObject toJSON(Structure header, ByteBuf payloadBuf, byte envelope) { try { JSONObject jo = extractHeader(header); Structure payload = StructureFactory.make(jo.optInt("_contractId"), jo.optInt("_structId")); ByteBufDataSource bd = new ByteBufDataSource(payloadBuf); payload.read(bd); JSONDataSource jd = new WebJSONDataSource(jo, payload.tagWebNames()); payload.write(jd); return jo; } catch (IOException e) { logger.error("Could not make web frame for {}", header.dump()); return null; } } @Override protected Object makeFrame(Structure header, ByteBuf payloadBuf, byte envelope) { JSONObject jo = toJSON(header, payloadBuf, envelope); if (jo != null) { return makeFrame(jo, true); } else { return null; } } protected JSONObject extractHeader(Structure header) { JSONObject jo = new JSONObject(); switch (header.getStructId()) { case RequestHeader.STRUCT_ID: RequestHeader reqH = (RequestHeader) header; jo.put("_contractId", reqH.contractId); jo.put("_structId", reqH.structId); jo.put("_requestId", reqH.requestId); break; case ResponseHeader.STRUCT_ID: ResponseHeader respH = (ResponseHeader) header; jo.put("_contractId", respH.contractId); jo.put("_structId", respH.structId); jo.put("_requestId", respH.requestId); break; case MessageHeader.STRUCT_ID: MessageHeader messH = (MessageHeader) header; jo.put("_contractId", messH.contractId); jo.put("_structId", messH.structId); jo.put("_topicId", messH.toType == MessageHeader.TO_TOPIC ? messH.toId : 0); break; } return jo; } }
package lt.repl; import sun.misc.Signal; import sun.misc.SignalHandler; /** * handle ctrl-c (INT) event */ public class CtrlCSignalHandler implements CtrlCHandler { private Runnable alert = null; @Override public void handle() { SignalHandler handler = new SignalHandler() { private int count = 0; @Override public void handle(Signal signal) { if (!signal.getName().equals("INT")) { return; } ++count; if (count == 2) { System.out.println(); System.exit(2); // SIGINT } else { System.out.println("\n(To exit, press ^C again or type :q)"); if (alert != null) { alert.run(); } new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } count = 0; } }).run(); } } }; Signal.handle(new Signal("INT"), handler); } @Override public void onAlert(Runnable alert) { this.alert = alert; } }
package d3kod.thehunt.world.logic; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.PointF; import android.hardware.SensorEvent; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.Matrix; import android.util.Log; import android.view.MotionEvent; import d3kod.graphics.extra.D3Maths; import d3kod.graphics.shader.ShaderProgramManager; import d3kod.graphics.sprite.SpriteManager; import d3kod.graphics.sprite.shapes.D3FadingShape; import d3kod.graphics.sprite.shapes.D3FadingText; import d3kod.graphics.text.GLText; import d3kod.graphics.texture.TextureManager; import d3kod.thehunt.MultisampleConfigChooser; import d3kod.thehunt.MyApplication; import d3kod.thehunt.PreyChangeDialog; import d3kod.thehunt.agent.Agent; import d3kod.thehunt.agent.DummyPrey; import d3kod.thehunt.agent.prey.Prey; import d3kod.thehunt.world.Camera; import d3kod.thehunt.world.HUD; import d3kod.thehunt.world.environment.Environment; import d3kod.thehunt.world.floating_text.PlokText; import d3kod.thehunt.world.floating_text.ToolText; import d3kod.thehunt.world.tools.CatchNet; import d3kod.thehunt.world.tools.Knife; import d3kod.thehunt.world.tools.Tool; public class TheHuntRenderer implements GLSurfaceView.Renderer { private static final String DEFAULT_TAG = "TheHuntRenderer"; private String TAG;// = "TheHuntRenderer"; private static final int SMOOTHING_SIZE = 30; public static boolean LOGGING_TIME = false; public static boolean SHOW_TILES = false; public static boolean SHOW_CURRENTS = false; public static boolean FEED_WITH_TOUCH = false; public static boolean NET_WITH_TOUCH = true; private float[] mProjMatrix = new float[16]; private float[] mVMatrix = new float[16]; private Environment mEnv; public Agent mPrey; public static final int TICKS_PER_SECOND = 30; private static final int RELEASE_DELAY = 1; // in seconds private static final int RELEASE_TICKS = RELEASE_DELAY*TICKS_PER_SECOND; private final int MILLISEC_PER_TICK = 1000 / TICKS_PER_SECOND; private final int MAX_FRAMESKIP = 5; private long next_game_tick; // private Context mContext; private long mslf; private long smoothMspf; private int smoothingCount; private int mCaughtCounter; private boolean mGraphicsInitialized = false; private TextureManager tm; private int releaseCountdown; private float mScreenToWorldRatioWidth; private float mScreenToWorldRatioHeight; private MotionEvent prev; private Camera mCamera; private State mState; private SpriteManager mD3GLES20; private ShaderProgramManager sm; private Tool mTool; private static int mScreenWidthPx; private static int mScreenHeightPx; public static float[] bgColor = { 0.8f, 0.8f, 0.8f, 1.0f}; private final static int worldWidthPx = 1500; private final static int worldHeightPx = 900; protected static final int YELLOW_TEXT_ENERGY = 60; protected static final int RED_TEXT_ENERGY = 30; private boolean mScrolling = false; private int mIgnoreNextTouch; private MyApplication mContext; private HUD mHUD; private int mScore; private TheHuntContextMenu mContextMenu; private float mScale; // private GLText mGLText; /** * The possible Prey type values (for example, returned from a {@link PreyChangeDialog}. * * @author Aleksandar Kodzhabashev (d3kod) * @see PreyChangeDialog * */ public static enum PreyType {NONE, DEFAULT}; public void onSensorChanged(SensorEvent event) { } public TheHuntRenderer(Context context) { this(context, DEFAULT_TAG); } public TheHuntRenderer(Context context, String tag) { TAG = tag; Log.v(TAG, "onCreate called!"); mContext = ((MyApplication) context.getApplicationContext()); mContext.setRunningRenderer(TAG); tm = new TextureManager(context); // prepareState(); // mEnv = null; // mTool = null; // mD3GLES20 = new SpriteManager(sm); // while (mPrey == null) { // if (mPrey == null) { // if (context instanceof TheHunt) { // ((TheHunt) context).showPreyChangeDialog(null); // else { // mPrey = new DummyPrey(mEnv, mD3GLES20); } private void prepareState() { sm = new ShaderProgramManager(); synchronized (mContext.stateLock) { loadSavedState(sm); } mTool = new CatchNet(mEnv, mD3GLES20); // mTool = new Knife(mEnv, mD3GLES20); mIgnoreNextTouch = -1; mCaughtCounter = 0; mGraphicsInitialized = false; mScale = 1; } private SpriteManager loadSavedState(ShaderProgramManager shaderManager) { Log.v(TAG, "Loading saved state"); SaveState state = mContext.getStateFromDB(TAG); // SaveState state = null; if (state == null) { Log.v(TAG, "SaveState is empty, creating new SaveState"); mD3GLES20 = new SpriteManager(shaderManager, mContext); mEnv = new Environment(worldWidthPx, worldHeightPx, mD3GLES20); mPrey = new Prey(mEnv, tm, mD3GLES20); // mPrey = new DummyPrey(mEnv, mD3GLES20); // saveState(); } else { // if (state.getSameAsLast()) { // Log.i(TAG, "SavedState is same as last, ignoring loadSavedState call"); // return mD3GLES20; // mD3GLES20 = state.getSpriteManager(); // mEnv = state.getEnv(); // mPrey = state.getAgent(); // ArrayList<D3Sprite> sprites = state.getSprites(); // Enum4 mD3GLES20 = new SpriteManager(shaderManager, mContext); mEnv = state.getEnv(); // mPrey = new DummyPrey(mEnv, mD3GLES20); mPrey = mEnv.getPrey(); // mPrey.setTextureManager(tm); // mEnv.initSprites(sprites); // mPrey = mEnv.getPrey(); Log.v(TAG, "SaveState loaded!"); } Log.v(TAG, "Finished loading saved state!"); return mD3GLES20; } private void saveState() { Log.v(TAG, "Saving state!"); // SaveState state = new SeventaveState(mEnv.getSprites()); SaveState state = new SaveState(mEnv); mContext.storeToDB(state); } /** * The Surface is created/init() */ public void onSurfaceCreated(GL10 unused, EGLConfig config) { GLES20.glClearColor(bgColor[0], bgColor[1], bgColor[2], bgColor[3]); GLES20.glEnable(GLES20.GL_BLEND); GLES20.glBlendFunc(GLES20.GL_ONE, GL10.GL_ONE_MINUS_SRC_ALPHA); } /** * If the surface changes, reset the view */ public void onSurfaceChanged(GL10 unused, int width, int height) { GLES20.glViewport(0, 0, width, height); mScreenWidthPx = width; mScreenHeightPx = height; mScreenToWorldRatioWidth = mScreenWidthPx/(float)worldWidthPx; mScreenToWorldRatioHeight = mScreenHeightPx/(float)worldHeightPx; mCamera = new Camera(mScreenToWorldRatioWidth, mScreenToWorldRatioHeight, worldWidthPx/(float)worldHeightPx, mD3GLES20); mHUD = new HUD(mCamera); Log.v(TAG, "mScreenWidth " + mScreenWidthPx + " mScreenHeight " + mScreenHeightPx); // if (mEnv == null) mEnv = new Environment(worldWidthPx, worldHeightPx, mD3GLES20); // if (mTool == null) mTool = new CatchNet(mEnv, tm, mD3GLES20); synchronized (mContext.stateLock) { if (!mGraphicsInitialized ) { //TODO why not initialize tool graphics as well? mD3GLES20.init(mContext); // mD3GLES20.putText1(new D3FadingText("Fafa", 1000.0f, 0)); tm = new TextureManager(mContext); mEnv.initGraphics(mD3GLES20); mCamera.initGraphic(); mHUD.initGraphics(mD3GLES20); // mHUD.setCaught(mCaughtCounter); mHUD.setScore(mCaughtCounter); mContextMenu = new TheHuntContextMenu(mD3GLES20); mContextMenu.initGraphic(); if (mPrey != null) { mPrey.setSpriteManager(mD3GLES20); mPrey.setTextureManager(tm); mPrey.initGraphic(); } mGraphicsInitialized = true; } } float ratio = (float) worldWidthPx / worldHeightPx; // if (width > height) Matrix.frustumM(mProjMatrix, 0, -ratio/mScale, ratio/mScale, mScale, mScale, 1, 10); // else Matrix.frustumM(mProjMatrix, 0, -mScale, mScale, -mScale/ratio, mScale/ratio, 1, 10); } /** * Here we do our drawing */ public void onDrawFrame(GL10 unused) { synchronized (mContext.stateLock) { if (mState == State.PAUSE) { return; } if (mContext.getRunningRenderer() != TAG) { if (mContext.getRunningRenderer() == "") { Log.v(TAG, "No renderer is running, let me run!"); mContext.setRunningRenderer(TAG); } else Log.v(TAG, "I'm not supposed to be running! Sorry..."); return; } // Log.v(TAG, "Obtained stateLock!"); int loops = 0; mslf = System.currentTimeMillis(); while (next_game_tick < System.currentTimeMillis() && loops < MAX_FRAMESKIP) { updateWorld(); next_game_tick += MILLISEC_PER_TICK; loops++; } if (loops >= MAX_FRAMESKIP) { Log.w(TAG, "Skipping " + loops + " frames!"); } float interpolation = (System.currentTimeMillis() + MILLISEC_PER_TICK - next_game_tick) / (float) MILLISEC_PER_TICK; drawWorld(interpolation); long mspf = System.currentTimeMillis() - mslf; smoothMspf = (smoothMspf*smoothingCount + mspf)/(smoothingCount+1); smoothingCount++; if (smoothingCount >= SMOOTHING_SIZE) { smoothingCount = 0; // TODO: Set HUD details (prey state, ms per frame, energy } } } public void updateWorld() { // Log.v(TAG, "Update world called!"); mEnv.update(); if (!mContextMenu.isHidden()) mContextMenu.update(); // mHUD.setEnvState(mEnv.getStateString(), mEnv.getStateColor()); if (mPrey != null) { PointF preyPos = mPrey.getPosition(); if (preyPos != null) { PointF curDirDelta = mEnv.data.getTileFromPos(preyPos).getDir().getDelta(); mPrey.updateVelocity(curDirDelta.x, curDirDelta.y); mPrey.update(); } preyPos = mPrey.getPosition(); if (mPrey.getCaught()) { if (releaseCountdown < 0) { releaseCountdown = RELEASE_TICKS; ++mCaughtCounter; } releaseCountdown if (releaseCountdown == 0) { mPrey.release(); releaseCountdown = -1; } } mCamera.setPreyPosition(preyPos); // mHUD.setPreyEnergy(mPrey.getEnergy(), mPrey.getMoodColor()); // mHUD.setPreyState(mPrey.getStateString()); } if (mTool != null) mTool.update(); mCamera.update(); mD3GLES20.updateAll(); mHUD.setScore(mCaughtCounter*10-mEnv.getPlayerPenalty()); mHUD.update(); } public void drawWorld(float interpolation) { if (mState != State.PLAY) return; // tm.clear(); if (mPreyChange) { mPreyChange = false; if (mPrey != null) mPrey.clearGraphic(); switch (mPreyChangeTo) { case NONE: mPrey = new DummyPrey(mEnv, mD3GLES20); break; case DEFAULT: mPrey = new Prey(mEnv, tm, mD3GLES20); break; } mPrey.initGraphic(); } int clearMask = GLES20.GL_COLOR_BUFFER_BIT; if (MultisampleConfigChooser.usesCoverageAa()) { final int GL_COVERAGE_BUFFER_BIT_NV = 0x8000; clearMask |= GL_COVERAGE_BUFFER_BIT_NV; } GLES20.glClear(clearMask); // float[] vpMatrix = new float[16]; // Matrix.multiplyMM(vpMatrix, 0, mProjMatrix, 0, mVMatrix, 0); // mGLText.drawTexture( 100, 100, vpMatrix); // Draw the Entire Texture // mGLText.begin(0.0f, 0.0f, 0.0f, 1.0f, vpMatrix); // mGLText.setScale(0.003f); // mGLText.setSpace(1f); // mGLText.drawC( "Test String :)", 0, 0, 10); // mGLText.end(); mVMatrix = mCamera.toViewMatrix(); mProjMatrix = mCamera.toProjMatrix(); if (mPrey != null && mPrey.getGraphic() != null) mCamera.setPreyPointerPosition(mPrey.getPredictedPosition()); mD3GLES20.drawAll(mVMatrix, mProjMatrix, interpolation); } public void handleTouch(final MotionEvent event, boolean doubleTouch) { //TODO: receive int, PointF instead of MotionEvent if (prev != null && prev.getX() == event.getX() && prev.getY() == event.getY() && prev.getAction() == event.getAction()) return; PointF location = fromScreenToWorld(event.getX(), event.getY()); if (doubleTouch && !mScrolling) { mScrolling = true; Log.v(TAG, "Scrolling is true"); if (mTool != null) mTool.stop(location); } else if (!doubleTouch && mScrolling) { mScrolling = false; mIgnoreNextTouch = MotionEvent.ACTION_UP; Log.v(TAG, "Scrolling is false"); } else { if (mScrolling) { if (prev != null) { float prevSpacing, thisSpacing; try { prevSpacing = D3Maths.distance(prev.getX(0), prev.getY(0), prev.getX(1), prev.getY(1)); thisSpacing = D3Maths.distance(event.getX(0), event.getY(0), event.getX(1), event.getY(1)); } catch (IllegalArgumentException e) { Log.e(TAG, "Illegal argument while scrolling/zooming " + e.getStackTrace()); prevSpacing = 0; thisSpacing = 0; } PointF prevWorld = fromScreenToWorld(prev.getX(), prev.getY()); mCamera.move(prevWorld.x - location.x, prevWorld.y - location.y, prevSpacing, thisSpacing); } } // else if (mLongPress) { // Log.v(TAG, "In long press!"); // if (event.getAction() == MotionEvent.ACTION_UP) { // Log.v(TAG, "Stopping long press"); // mLongPress = false; // switch(mContextMenu.getChange()) { // case 0: // mTool = new CatchNet(mEnv, mD3GLES20); break; // case 1: // mTool = new Knife(mEnv, mD3GLES20); break; // mContextMenu.hide(); //// mTool.cancel(); // else { // Log.v(TAG, "Handling long press"); // mContextMenu.handleTouch(location); // if (D3Maths.distance(location, locationMean) >) // setFaded else { if (event.getAction() == MotionEvent.ACTION_UP && mHUD.handleTouch(location, event.getAction())) { // there is an HUD action request String active = mHUD.getActivePaletteElement(); if (active == null) { Log.e(TAG, "Expected active pallete element, got null instead"); } else { Log.v(TAG, "Gonna change tool, class is " + mTool.getClass()); if (active == "Net" && mTool.getClass() != CatchNet.class) { Log.v(TAG, "Changing tool to Net"); mD3GLES20.putText(new ToolText("Net!", location.x, location.y)); mTool = new CatchNet(mEnv, mD3GLES20); } else if (active == "Knife" && mTool.getClass() != Knife.class) { mD3GLES20.putText(new ToolText("Knife!", location.x, location.y)); Log.v(TAG, "Changing tool to Knife"); mTool = new Knife(mEnv, mD3GLES20); } } } if (!mHUD.handleTouch(location, event.getAction()) && (mTool == null || !mTool.handleTouch(event.getAction(), location))) { // Log.v(TAG, "mTool can't handle touch. Ignoring if " + mIgnoreNextTouch); if (mIgnoreNextTouch != event.getAction() && // (event.getAction() == MotionEvent.ACTION_DOWN || // to place food while net is snatching event.getAction() == MotionEvent.ACTION_UP) { // to place food otherwise mD3GLES20.putText(new PlokText(location.x, location.y)); mEnv.putNoise(location.x, location.y, Environment.LOUDNESS_PLOK); mEnv.putFoodGM(location.x, location.y); } } if (mIgnoreNextTouch == event.getAction()) mIgnoreNextTouch = -1; } } prev = MotionEvent.obtain(event); } public static boolean motionEventDoubleTouchChanged(MotionEvent event) { String TAG = "motionEventDoubleTouchChanged"; int action = event.getAction(); int count; switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_POINTER_DOWN: count = event.getPointerCount(); // Number of 'fingers' at this time Log.v(TAG, "Down Count is " + count); if (count == 2) { return true; } break; case MotionEvent.ACTION_POINTER_UP: count = event.getPointerCount(); // Number of 'fingers' in this time Log.v(TAG, "UP Count is " + count); if (count == 2) { return true; } break; } return false; } public void pause() { // Log.v(TAG, "pause called!"); if (mContext.getRunningRenderer() == TAG) { Log.v(TAG, "Telling the context I'm not running any more..."); mContext.setRunningRenderer(""); } else { Log.v(TAG, "Running renderer not changed as it is " + mContext.getRunningRenderer()); } // tm.clear(); if (mState == State.PLAY) { mState = State.PAUSE; saveState(); } mState = State.PAUSE; Log.v(TAG, "State is " + mState); //TODO: use sparseArray // sm.clear(); // mContext.modeLock.unlock(); // Log.v(TAG, Thread.currentThread().getName() + " released modeLock!"); } public void resume() { synchronized (mContext.stateLock) { // if (mContext.getRunningRenderer() != TAG) { // if (mContext.getRunningRenderer() == "") { // Log.v(TAG, "No renderer is running, let me run!"); // mContext.setRunningRenderer(TAG); // else Log.v(TAG, "I'm not supposed to be running! Sorry..."); // return; // mContext.modeLock.lock(); // Log.v(TAG, Thread.currentThread().getName() + " aqcuired modeLock!"); mContext.setRunningRenderer(TAG); Log.v(TAG, "resume called!"); mState = State.RESUME; Log.v(TAG, "State is " + mState); next_game_tick = System.currentTimeMillis(); mslf = next_game_tick; smoothMspf = 0; smoothingCount = 0; // TODO: restore caught counter // mEnv = null; // mTool = null; // if (sm == null) { // Log.v(TAG, "ShaderProgramManager is null!"); // sm = new ShaderProgramManager(); // tm = new TextureManager(mContext); // db4o does magic and synchronizes the environment with the one it loaded onCreate, so this is not neccessary // loadSavedState(sm); // if (mD3GLES20 == null) { // mD3GLES20 = new SpriteManager(sm); // if (mDGLES20 == null) loadSavedState(sm); // sm = new ShaderProgramManager(); // sm = new ShaderProgramManager(); // mD3GLES20.setShaderManager(sm); // sm = new ShaderProgramManager(); // mD3GLES20 = new SpriteManager(sm); // mGraphicsInitialized = false; tm.printLoadedTextures(); prepareState(); tm.printLoadedTextures(); // Log.v(TAG, "ShaderProgramManager " + mD3GLES20.getShaderManager() + " " + sm); mState = State.PLAY; Log.v(TAG, "State is " + mState); } } public void release() { // TODO stuff to release } float[] normalizedInPoint = new float[4]; float[] outPoint = new float[4]; float[] mPVMatrix = new float[16]; private boolean mPreyChange; private PreyType mPreyChangeTo; private boolean mLongPress; public PointF fromScreenToWorld(float touchX, float touchY) { normalizedInPoint[0] = 2f*touchX/mScreenWidthPx - 1; normalizedInPoint[1] = 2f*(mScreenHeightPx - touchY)/mScreenHeightPx - 1; normalizedInPoint[2] = -1f; normalizedInPoint[3] = 1f; Matrix.multiplyMM(mPVMatrix, 0, mProjMatrix, 0, mVMatrix, 0); Matrix.invertM(mPVMatrix, 0, mPVMatrix, 0); Matrix.multiplyMV(outPoint, 0, mPVMatrix, 0, normalizedInPoint, 0); return new PointF(outPoint[0], outPoint[1]); } public void changePrey(int which) { mPreyChange = true; mPreyChangeTo = PreyType.values()[which]; } // public void reportLongPress(MotionEvent event) { // Log.v(TAG, "Long press reported"); // mLongPress = true; // PointF location = fromScreenToWorld(event.getX(), event.getY()); // mTool.stop(location); // mContextMenu.show(location); // Log.v(TAG, "Long press registered"); }
package net.sf.mpxj.mpp; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import net.sf.mpxj.AccrueType; import net.sf.mpxj.ConstraintType; import net.sf.mpxj.DateRange; import net.sf.mpxj.Day; import net.sf.mpxj.Duration; import net.sf.mpxj.MPPResourceField; import net.sf.mpxj.MPPTaskField; import net.sf.mpxj.MPXJException; import net.sf.mpxj.Priority; import net.sf.mpxj.ProjectCalendar; import net.sf.mpxj.ProjectCalendarException; import net.sf.mpxj.ProjectCalendarHours; import net.sf.mpxj.ProjectFile; import net.sf.mpxj.Rate; import net.sf.mpxj.Relation; import net.sf.mpxj.RelationType; import net.sf.mpxj.Resource; import net.sf.mpxj.ResourceAssignment; import net.sf.mpxj.ResourceField; import net.sf.mpxj.ResourceType; import net.sf.mpxj.SubProject; import net.sf.mpxj.Table; import net.sf.mpxj.Task; import net.sf.mpxj.TaskField; import net.sf.mpxj.TaskType; import net.sf.mpxj.TimeUnit; import net.sf.mpxj.View; import net.sf.mpxj.WorkContour; import net.sf.mpxj.utility.NumberUtility; import net.sf.mpxj.utility.Pair; import net.sf.mpxj.utility.RTFUtility; import org.apache.poi.poifs.filesystem.DirectoryEntry; import org.apache.poi.poifs.filesystem.DocumentEntry; import org.apache.poi.poifs.filesystem.DocumentInputStream; /** * This class is used to represent a Microsoft Project MPP9 file. This * implementation allows the file to be read, and the data it contains * exported as a set of MPX objects. These objects can be interrogated * to retrieve any required data, or stored as an MPX file. */ final class MPP9Reader implements MPPVariantReader { /** * This method is used to process an MPP9 file. This is the file format * used by Project 2000, 2002, and 2003. * * @param reader parent file reader * @param file parent MPP file * @param root Root of the POI file system. */ public void process (MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException { try { // Retrieve the high level document properties (never encoded) Props9 props9 = new Props9 (new DocumentInputStream (((DocumentEntry)root.getEntry("Props9")))); //System.out.println(props9); file.setProjectFilePath(props9.getUnicodeString(Props.PROJECT_FILE_PATH)); file.setEncoded(props9.getByte(Props.PASSWORD_FLAG) != 0); file.setEncryptionCode(props9.getByte(Props.ENCRYPTION_CODE)); // Test for password protection. In the single byte retrieved here: // 0x00 = no password // 0x01 = protection password has been supplied // 0x02 = write reservation password has been supplied // 0x03 = both passwords have been supplied if ((props9.getByte(Props.PASSWORD_FLAG) & 0x01) != 0) { // File is password protected for reading, let's read the password // and see if the correct read password was given to us. String readPassword = MPPUtility.decodePassword(props9.getByteArray(Props.PROTECTION_PASSWORD_HASH), file.getEncryptionCode()); // It looks like it is possible for a project file to have the password protection flag on without a password. In // this case MS Project treats the file as NOT protected. We need to do the same. It is worth noting that MS Project does // correct the problem if the file is re-saved (at least it did for me). if (readPassword != null && readPassword.length() > 0) { // See if the correct read password was given if (reader.getReadPassword() == null || reader.getReadPassword().matches(readPassword) == false) { // Passwords don't match throw new MPXJException (MPXJException.PASSWORD_PROTECTED_ENTER_PASSWORD); } } // Passwords matched so let's allow the reading to continue. } m_reader = reader; m_file = file; m_root = root; m_resourceMap = new HashMap<Integer, ProjectCalendar> (); m_projectDir = (DirectoryEntry)root.getEntry (" 19"); m_viewDir = (DirectoryEntry)root.getEntry (" 29"); DirectoryEntry outlineCodeDir = (DirectoryEntry)m_projectDir.getEntry ("TBkndOutlCode"); VarMeta outlineCodeVarMeta = new VarMeta9 (new DocumentInputStream (((DocumentEntry)outlineCodeDir.getEntry("VarMeta")))); m_outlineCodeVarData = new Var2Data (outlineCodeVarMeta, new DocumentInputStream (((DocumentEntry)outlineCodeDir.getEntry("Var2Data")))); m_fontBases = new HashMap<Integer, FontBase>(); m_taskSubProjects = new HashMap<Integer, SubProject> (); m_file.setMppFileType(9); m_file.setAutoFilter(props9.getBoolean(Props.AUTO_FILTER)); processPropertyData (); processCalendarData (); processResourceData (); processTaskData (); processConstraintData (); processAssignmentData (); processViewPropertyData(); processTableData (); processViewData (); processFilterData(); processGroupData(); processSavedViewState(); } finally { m_reader = null; m_file = null; m_root = null; m_resourceMap = null; m_projectDir = null; m_viewDir = null; m_outlineCodeVarData = null; m_fontBases = null; m_taskSubProjects = null; } } /** * This method extracts and collates global property data. * * @throws IOException */ private void processPropertyData () throws IOException, MPXJException { Props9 props = new Props9 (getEncryptableInputStream(m_projectDir, "Props")); //MPPUtility.fileDump("c:\\temp\\props.txt", props.toString().getBytes()); // Process the project header ProjectHeaderReader projectHeaderReader = new ProjectHeaderReader(); projectHeaderReader.process(m_file, props, m_root); // Process aliases processTaskFieldNameAliases(props.getByteArray(Props.TASK_FIELD_NAME_ALIASES)); processResourceFieldNameAliases(props.getByteArray(Props.RESOURCE_FIELD_NAME_ALIASES)); // Process custom field value lists processTaskFieldCustomValueLists(m_file, props.getByteArray(Props.TASK_FIELD_CUSTOM_VALUE_LISTS)); // Process subproject data processSubProjectData(props); // Process graphical indicators GraphicalIndicatorReader reader = new GraphicalIndicatorReader(); reader.process(m_file, props); } /** * Read sub project data from the file, and add it to a hash map * indexed by task ID. * * Project stores all subprojects that have ever been inserted into this project * in sequence and that is what used to count unique id offsets for each of the * subprojects. * * @param props file properties */ private void processSubProjectData (Props9 props) { byte[] subProjData = props.getByteArray(Props.SUBPROJECT_DATA); //System.out.println (MPPUtility.hexdump(subProjData, true, 16, "")); //MPPUtility.fileHexDump("c:\\temp\\dump.txt", subProjData); if (subProjData != null) { int index = 0; int offset = 0; int itemHeaderOffset; int uniqueIDOffset; int filePathOffset; int fileNameOffset; SubProject sp; byte[] itemHeader = new byte[20]; /*int blockSize = MPPUtility.getInt(subProjData, offset);*/ offset += 4; /*int unknown = MPPUtility.getInt(subProjData, offset);*/ offset += 4; int itemCountOffset = MPPUtility.getInt(subProjData, offset); offset += 4; while (offset < itemCountOffset) { index++; itemHeaderOffset = MPPUtility.getShort(subProjData, offset); offset += 4; MPPUtility.getByteArray(subProjData, itemHeaderOffset, itemHeader.length, itemHeader, 0); // System.out.println (); // System.out.println (); // System.out.println ("offset=" + offset); // System.out.println ("ItemHeaderOffset=" + itemHeaderOffset); // System.out.println ("type=" + MPPUtility.hexdump(itemHeader, 16, 1, false)); // System.out.println (MPPUtility.hexdump(itemHeader, false, 16, "")); byte subProjectType = itemHeader[16]; switch (subProjectType) { // Subproject that is no longer inserted. This is a placeholder in order to be // able to always guarantee unique unique ids. case 0x00: { offset += 8; break; } // task unique ID, 8 bytes, path, file name case (byte)0x99: case 0x09: case 0x0D: { uniqueIDOffset = MPPUtility.getShort(subProjData, offset); offset += 4; // sometimes offset of a task ID? offset += 4; filePathOffset = MPPUtility.getShort(subProjData, offset); offset += 4; fileNameOffset = MPPUtility.getShort(subProjData, offset); offset += 4; sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index); break; } // task unique ID, 8 bytes, path, file name case (byte)0x91: { uniqueIDOffset = MPPUtility.getShort(subProjData, offset); offset += 4; filePathOffset = MPPUtility.getShort(subProjData, offset); offset += 4; fileNameOffset = MPPUtility.getShort(subProjData, offset); offset += 4; // Unknown offset offset += 4; sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index); break; } case 0x11: case 0x03: { uniqueIDOffset = MPPUtility.getShort(subProjData, offset); offset += 4; filePathOffset = MPPUtility.getShort(subProjData, offset); offset += 4; fileNameOffset = MPPUtility.getShort(subProjData, offset); offset += 4; // Unknown offset //offset += 4; sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index); break; } // task unique ID, path, unknown, file name case (byte)0x81: case 0x41: { uniqueIDOffset = MPPUtility.getShort(subProjData, offset); offset += 4; filePathOffset = MPPUtility.getShort(subProjData, offset); offset += 4; // unknown offset to 2 bytes of data? offset += 4; fileNameOffset = MPPUtility.getShort(subProjData, offset); offset += 4; sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index); break; } // task unique ID, path, file name case 0x01: case 0x08: { uniqueIDOffset = MPPUtility.getShort(subProjData, offset); offset += 4; filePathOffset = MPPUtility.getShort(subProjData, offset); offset += 4; fileNameOffset = MPPUtility.getShort(subProjData, offset); offset += 4; sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index); break; } // task unique ID, path, file name case (byte)0xC0: { uniqueIDOffset = itemHeaderOffset; filePathOffset = MPPUtility.getShort(subProjData, offset); offset += 4; fileNameOffset = MPPUtility.getShort(subProjData, offset); offset += 4; // unknown offset offset += 4; sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index); break; } // resource, task unique ID, path, file name case 0x05: { uniqueIDOffset = MPPUtility.getShort(subProjData, offset); offset += 4; filePathOffset = MPPUtility.getShort(subProjData, offset); offset += 4; fileNameOffset = MPPUtility.getShort(subProjData, offset); offset += 4; sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index); m_file.setResourceSubProject(sp); break; } // path, file name case 0x02: case 0x04: { filePathOffset = MPPUtility.getShort(subProjData, offset); offset += 4; fileNameOffset = MPPUtility.getShort(subProjData, offset); offset += 4; sp = readSubProject(subProjData, -1, filePathOffset, fileNameOffset, index); m_file.setResourceSubProject(sp); break; } // task unique ID, 4 bytes, path, 4 bytes, file name case (byte)0x8D: { uniqueIDOffset = MPPUtility.getShort(subProjData, offset); offset += 8; filePathOffset = MPPUtility.getShort(subProjData, offset); offset += 8; fileNameOffset = MPPUtility.getShort(subProjData, offset); offset += 4; sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index); break; } // task unique ID, path, file name case 0x0A: { uniqueIDOffset = MPPUtility.getShort(subProjData, offset); offset += 4; filePathOffset = MPPUtility.getShort(subProjData, offset); offset += 4; fileNameOffset = MPPUtility.getShort(subProjData, offset); offset += 4; sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index); break; } // Appears when a subproject is collapsed case (byte)0x80: { offset += 12; break; } // deleted entry? case 0x10: { offset += 8; break; } // new resource pool entry case (byte)0x44: { filePathOffset = MPPUtility.getShort(subProjData, offset); offset += 4; offset += 4; fileNameOffset = MPPUtility.getShort(subProjData, offset); offset += 4; sp = readSubProject(subProjData, -1, filePathOffset, fileNameOffset, index); m_file.setResourceSubProject(sp); break; } // Any other value, assume 12 bytes to handle old/deleted data? default: { offset += 12; break; } } } } } /** * Method used to read the sub project details from a byte array. * * @param data byte array * @param uniqueIDOffset offset of unique ID * @param filePathOffset offset of file path * @param fileNameOffset offset of file name * @param subprojectIndex index of the subproject, used to calculate unique id offset * @return new SubProject instance */ private SubProject readSubProject (byte[] data, int uniqueIDOffset, int filePathOffset, int fileNameOffset, int subprojectIndex) { SubProject sp = new SubProject (); if (uniqueIDOffset != -1) { int prev = 0; int value = MPPUtility.getInt(data, uniqueIDOffset); while (value != SUBPROJECT_LISTEND) { switch (value) { case SUBPROJECT_TASKUNIQUEID0: case SUBPROJECT_TASKUNIQUEID1: case SUBPROJECT_TASKUNIQUEID2: case SUBPROJECT_TASKUNIQUEID3: // The previous value was for the subproject unique task id sp.setTaskUniqueID(new Integer(prev)); m_taskSubProjects.put(sp.getTaskUniqueID(), sp); prev = 0; break; default: if (prev != 0) { // The previous value was for an external task unique task id sp.addExternalTaskUniqueID(new Integer(prev)); m_taskSubProjects.put(new Integer(prev), sp); } prev = value; break; } // Read the next value uniqueIDOffset += 4; value = MPPUtility.getInt(data, uniqueIDOffset); } if (prev != 0) { // The previous value was for an external task unique task id sp.addExternalTaskUniqueID(new Integer(prev)); m_taskSubProjects.put(new Integer(prev), sp); } // Now get the unique id offset for this subproject value = 0x00800000 + ((subprojectIndex-1) * 0x00400000); sp.setUniqueIDOffset(new Integer(value)); } // First block header filePathOffset += 18; // String size as a 4 byte int filePathOffset += 4; // Full DOS path sp.setDosFullPath(MPPUtility.getString(data, filePathOffset)); filePathOffset += (sp.getDosFullPath().length()+1); // 24 byte block filePathOffset += 24; // 4 byte block size int size = MPPUtility.getInt(data, filePathOffset); filePathOffset +=4; if (size == 0) { sp.setFullPath(sp.getDosFullPath()); } else { // 4 byte unicode string size in bytes size = MPPUtility.getInt(data, filePathOffset); filePathOffset += 4; // 2 byte data filePathOffset += 2; // Unicode string sp.setFullPath(MPPUtility.getUnicodeString(data, filePathOffset, size)); filePathOffset += size; } // Second block header fileNameOffset += 18; // String size as a 4 byte int fileNameOffset += 4; // DOS file name sp.setDosFileName(MPPUtility.getString(data, fileNameOffset)); fileNameOffset += (sp.getDosFileName().length()+1); // 24 byte block fileNameOffset += 24; // 4 byte block size size = MPPUtility.getInt(data, fileNameOffset); fileNameOffset +=4; if (size == 0) { sp.setFileName(sp.getDosFileName()); } else { // 4 byte unicode string size in bytes size = MPPUtility.getInt(data, fileNameOffset); fileNameOffset += 4; // 2 byte data fileNameOffset += 2; // Unicode string sp.setFileName(MPPUtility.getUnicodeString(data, fileNameOffset, size)); fileNameOffset += size; } //System.out.println(sp.toString()); // Add to the list of subprojects m_file.addSubProject(sp); return (sp); } /** * This method process the data held in the props file specific to the * visual appearance of the project data. */ private void processViewPropertyData () throws IOException { Props9 props = new Props9 (getEncryptableInputStream(m_viewDir, "Props")); //System.out.println(props); byte[] data = props.getByteArray(Props.FONT_BASES); if (data != null) { processBaseFonts (data); } } /** * Create an index of base font numbers and their associated base * font instances. * @param data property data */ private void processBaseFonts (byte[] data) { int offset = 0; int blockCount = MPPUtility.getShort(data, 0); offset +=2; int size; String name; for (int loop=0; loop < blockCount; loop++) { /*unknownAttribute = MPPUtility.getShort(data, offset);*/ offset += 2; size = MPPUtility.getShort(data, offset); offset += 2; name = MPPUtility.getUnicodeString(data, offset); offset += 64; if (name.length() != 0) { FontBase fontBase = new FontBase(new Integer(loop), name, size); m_fontBases.put(fontBase.getIndex(), fontBase); } } } /** * Retrieve any task field aliases defined in the MPP file. * * @param data task field name alias data */ private void processTaskFieldNameAliases (byte[] data) { if (data != null) { int offset = 0; ArrayList<String> aliases = new ArrayList<String>(300); while (offset < data.length) { String alias = MPPUtility.getUnicodeString(data, offset); aliases.add(alias); offset += (alias.length()+1)*2; } m_file.setTaskFieldAlias(TaskField.TEXT1, aliases.get(118)); m_file.setTaskFieldAlias(TaskField.TEXT2, aliases.get(119)); m_file.setTaskFieldAlias(TaskField.TEXT3, aliases.get(120)); m_file.setTaskFieldAlias(TaskField.TEXT4, aliases.get(121)); m_file.setTaskFieldAlias(TaskField.TEXT5, aliases.get(122)); m_file.setTaskFieldAlias(TaskField.TEXT6, aliases.get(123)); m_file.setTaskFieldAlias(TaskField.TEXT7, aliases.get(124)); m_file.setTaskFieldAlias(TaskField.TEXT8, aliases.get(125)); m_file.setTaskFieldAlias(TaskField.TEXT9, aliases.get(126)); m_file.setTaskFieldAlias(TaskField.TEXT10, aliases.get(127 )); m_file.setTaskFieldAlias(TaskField.START1, aliases.get(128)); m_file.setTaskFieldAlias(TaskField.FINISH1, aliases.get(129)); m_file.setTaskFieldAlias(TaskField.START2, aliases.get(130)); m_file.setTaskFieldAlias(TaskField.FINISH2, aliases.get(131)); m_file.setTaskFieldAlias(TaskField.START3, aliases.get(132)); m_file.setTaskFieldAlias(TaskField.FINISH3, aliases.get(133)); m_file.setTaskFieldAlias(TaskField.START4, aliases.get(134)); m_file.setTaskFieldAlias(TaskField.FINISH4, aliases.get(135)); m_file.setTaskFieldAlias(TaskField.START5, aliases.get(136)); m_file.setTaskFieldAlias(TaskField.FINISH5, aliases.get(137)); m_file.setTaskFieldAlias(TaskField.START6, aliases.get(138)); m_file.setTaskFieldAlias(TaskField.FINISH6, aliases.get(139)); m_file.setTaskFieldAlias(TaskField.START7, aliases.get(140)); m_file.setTaskFieldAlias(TaskField.FINISH7, aliases.get(141)); m_file.setTaskFieldAlias(TaskField.START8, aliases.get(142)); m_file.setTaskFieldAlias(TaskField.FINISH8, aliases.get(143)); m_file.setTaskFieldAlias(TaskField.START9, aliases.get(144)); m_file.setTaskFieldAlias(TaskField.FINISH9, aliases.get(145)); m_file.setTaskFieldAlias(TaskField.START10, aliases.get(146)); m_file.setTaskFieldAlias(TaskField.FINISH10, aliases.get(147)); m_file.setTaskFieldAlias(TaskField.NUMBER1, aliases.get(149)); m_file.setTaskFieldAlias(TaskField.NUMBER2, aliases.get(150)); m_file.setTaskFieldAlias(TaskField.NUMBER3, aliases.get(151)); m_file.setTaskFieldAlias(TaskField.NUMBER4, aliases.get(152)); m_file.setTaskFieldAlias(TaskField.NUMBER5, aliases.get(153)); m_file.setTaskFieldAlias(TaskField.NUMBER6, aliases.get(154)); m_file.setTaskFieldAlias(TaskField.NUMBER7, aliases.get(155)); m_file.setTaskFieldAlias(TaskField.NUMBER8, aliases.get(156)); m_file.setTaskFieldAlias(TaskField.NUMBER9, aliases.get(157)); m_file.setTaskFieldAlias(TaskField.NUMBER10, aliases.get(158)); m_file.setTaskFieldAlias(TaskField.DURATION1, aliases.get(159)); m_file.setTaskFieldAlias(TaskField.DURATION2, aliases.get(161)); m_file.setTaskFieldAlias(TaskField.DURATION3, aliases.get(163)); m_file.setTaskFieldAlias(TaskField.DURATION4, aliases.get(165)); m_file.setTaskFieldAlias(TaskField.DURATION5, aliases.get(167)); m_file.setTaskFieldAlias(TaskField.DURATION6, aliases.get(169)); m_file.setTaskFieldAlias(TaskField.DURATION7, aliases.get(171)); m_file.setTaskFieldAlias(TaskField.DURATION8, aliases.get(173)); m_file.setTaskFieldAlias(TaskField.DURATION9, aliases.get(175)); m_file.setTaskFieldAlias(TaskField.DURATION10, aliases.get(177)); m_file.setTaskFieldAlias(TaskField.DATE1, aliases.get(184)); m_file.setTaskFieldAlias(TaskField.DATE2, aliases.get(185)); m_file.setTaskFieldAlias(TaskField.DATE3, aliases.get(186)); m_file.setTaskFieldAlias(TaskField.DATE4, aliases.get(187)); m_file.setTaskFieldAlias(TaskField.DATE5, aliases.get(188)); m_file.setTaskFieldAlias(TaskField.DATE6, aliases.get(189)); m_file.setTaskFieldAlias(TaskField.DATE7, aliases.get(190)); m_file.setTaskFieldAlias(TaskField.DATE8, aliases.get(191)); m_file.setTaskFieldAlias(TaskField.DATE9, aliases.get(192)); m_file.setTaskFieldAlias(TaskField.DATE10, aliases.get(193)); m_file.setTaskFieldAlias(TaskField.TEXT11, aliases.get(194)); m_file.setTaskFieldAlias(TaskField.TEXT12, aliases.get(195)); m_file.setTaskFieldAlias(TaskField.TEXT13, aliases.get(196)); m_file.setTaskFieldAlias(TaskField.TEXT14, aliases.get(197)); m_file.setTaskFieldAlias(TaskField.TEXT15, aliases.get(198)); m_file.setTaskFieldAlias(TaskField.TEXT16, aliases.get(199)); m_file.setTaskFieldAlias(TaskField.TEXT17, aliases.get(200)); m_file.setTaskFieldAlias(TaskField.TEXT18, aliases.get(201)); m_file.setTaskFieldAlias(TaskField.TEXT19, aliases.get(202)); m_file.setTaskFieldAlias(TaskField.TEXT20, aliases.get(203)); m_file.setTaskFieldAlias(TaskField.TEXT21, aliases.get(204)); m_file.setTaskFieldAlias(TaskField.TEXT22, aliases.get(205)); m_file.setTaskFieldAlias(TaskField.TEXT23, aliases.get(206)); m_file.setTaskFieldAlias(TaskField.TEXT24, aliases.get(207)); m_file.setTaskFieldAlias(TaskField.TEXT25, aliases.get(208)); m_file.setTaskFieldAlias(TaskField.TEXT26, aliases.get(209)); m_file.setTaskFieldAlias(TaskField.TEXT27, aliases.get(210)); m_file.setTaskFieldAlias(TaskField.TEXT28, aliases.get(211)); m_file.setTaskFieldAlias(TaskField.TEXT29, aliases.get(212)); m_file.setTaskFieldAlias(TaskField.TEXT30, aliases.get(213)); m_file.setTaskFieldAlias(TaskField.NUMBER11, aliases.get(214)); m_file.setTaskFieldAlias(TaskField.NUMBER12, aliases.get(215)); m_file.setTaskFieldAlias(TaskField.NUMBER13, aliases.get(216)); m_file.setTaskFieldAlias(TaskField.NUMBER14, aliases.get(217)); m_file.setTaskFieldAlias(TaskField.NUMBER15, aliases.get(218)); m_file.setTaskFieldAlias(TaskField.NUMBER16, aliases.get(219)); m_file.setTaskFieldAlias(TaskField.NUMBER17, aliases.get(220)); m_file.setTaskFieldAlias(TaskField.NUMBER18, aliases.get(221)); m_file.setTaskFieldAlias(TaskField.NUMBER19, aliases.get(222)); m_file.setTaskFieldAlias(TaskField.NUMBER20, aliases.get(223)); m_file.setTaskFieldAlias(TaskField.OUTLINE_CODE1, aliases.get(227)); m_file.setTaskFieldAlias(TaskField.OUTLINE_CODE2, aliases.get(228)); m_file.setTaskFieldAlias(TaskField.OUTLINE_CODE3, aliases.get(229)); m_file.setTaskFieldAlias(TaskField.OUTLINE_CODE4, aliases.get(230)); m_file.setTaskFieldAlias(TaskField.OUTLINE_CODE5, aliases.get(231)); m_file.setTaskFieldAlias(TaskField.OUTLINE_CODE6, aliases.get(232)); m_file.setTaskFieldAlias(TaskField.OUTLINE_CODE7, aliases.get(233)); m_file.setTaskFieldAlias(TaskField.OUTLINE_CODE8, aliases.get(234)); m_file.setTaskFieldAlias(TaskField.OUTLINE_CODE9, aliases.get(235)); m_file.setTaskFieldAlias(TaskField.OUTLINE_CODE10, aliases.get(236)); m_file.setTaskFieldAlias(TaskField.FLAG1, aliases.get(237)); m_file.setTaskFieldAlias(TaskField.FLAG2, aliases.get(238)); m_file.setTaskFieldAlias(TaskField.FLAG3, aliases.get(239)); m_file.setTaskFieldAlias(TaskField.FLAG4, aliases.get(240)); m_file.setTaskFieldAlias(TaskField.FLAG5, aliases.get(241)); m_file.setTaskFieldAlias(TaskField.FLAG6, aliases.get(242)); m_file.setTaskFieldAlias(TaskField.FLAG7, aliases.get(243)); m_file.setTaskFieldAlias(TaskField.FLAG8, aliases.get(244)); m_file.setTaskFieldAlias(TaskField.FLAG9, aliases.get(245)); m_file.setTaskFieldAlias(TaskField.FLAG10, aliases.get(246)); m_file.setTaskFieldAlias(TaskField.FLAG11, aliases.get(247)); m_file.setTaskFieldAlias(TaskField.FLAG12, aliases.get(248)); m_file.setTaskFieldAlias(TaskField.FLAG13, aliases.get(249)); m_file.setTaskFieldAlias(TaskField.FLAG14, aliases.get(250)); m_file.setTaskFieldAlias(TaskField.FLAG15, aliases.get(251)); m_file.setTaskFieldAlias(TaskField.FLAG16, aliases.get(252)); m_file.setTaskFieldAlias(TaskField.FLAG17, aliases.get(253)); m_file.setTaskFieldAlias(TaskField.FLAG18, aliases.get(254)); m_file.setTaskFieldAlias(TaskField.FLAG19, aliases.get(255)); m_file.setTaskFieldAlias(TaskField.FLAG20, aliases.get(256)); m_file.setTaskFieldAlias(TaskField.COST1, aliases.get(278)); m_file.setTaskFieldAlias(TaskField.COST2, aliases.get(279)); m_file.setTaskFieldAlias(TaskField.COST3, aliases.get(280)); m_file.setTaskFieldAlias(TaskField.COST4, aliases.get(281)); m_file.setTaskFieldAlias(TaskField.COST5, aliases.get(282)); m_file.setTaskFieldAlias(TaskField.COST6, aliases.get(283)); m_file.setTaskFieldAlias(TaskField.COST7, aliases.get(284)); m_file.setTaskFieldAlias(TaskField.COST8, aliases.get(285)); m_file.setTaskFieldAlias(TaskField.COST9, aliases.get(286)); m_file.setTaskFieldAlias(TaskField.COST10, aliases.get(287)); } } /** * Retrieve any task field value lists defined in the MPP file. * * @param file Parent MPX file * @param data task field name alias data */ private void processTaskFieldCustomValueLists (ProjectFile file, byte[] data) { if (data != null) { int index = 0; int offset = 0; // First the length int length = MPPUtility.getInt(data, offset); offset += 4; // Then the number of custom value lists int numberOfValueLists = MPPUtility.getInt(data, offset); offset += 4; // Then the value lists themselves TaskField field; int valueListOffset = 0; while (index < numberOfValueLists && offset < length) { // Each item consists of the Field ID (2 bytes), 40 0B marker (2 bytes), and the // offset to the value list (4 bytes) // Get the Field field = MPPTaskField.getInstance(MPPUtility.getShort(data, offset)); offset += 2; // Go past 40 0B marker offset += 2; // Get the value list offset valueListOffset = MPPUtility.getInt(data, offset); offset += 4; // Read the value list itself if (valueListOffset < data.length) { int tempOffset = valueListOffset; tempOffset += 8; // Get the data offset int dataOffset = MPPUtility.getInt(data, tempOffset) + valueListOffset; tempOffset += 4; // Get the end of the data offset int endDataOffset = MPPUtility.getInt(data, tempOffset) + valueListOffset; tempOffset += 4; // Get the end of the description int endDescriptionOffset = MPPUtility.getInt(data, tempOffset) + valueListOffset; // Get the values themselves int valuesLength = endDataOffset - dataOffset; byte[] values = new byte[valuesLength]; MPPUtility.getByteArray(data, dataOffset, valuesLength, values, 0); file.setTaskFieldValueList(field, getTaskFieldValues(file, field, values)); //System.out.println(MPPUtility.hexdump(values, true)); // Get the descriptions int descriptionsLength = endDescriptionOffset - endDataOffset; byte[] descriptions = new byte[descriptionsLength]; MPPUtility.getByteArray(data, endDataOffset, descriptionsLength, descriptions, 0); file.setTaskFieldDescriptionList(field, getTaskFieldDescriptions(descriptions)); //System.out.println(MPPUtility.hexdump(descriptions, true)); } index++; } } //System.out.println(file.getTaskFieldAliasMap().toString()); } /** * Retrieves the description value list associated with a custom task field. * This method will return null if no descriptions for the value list has * been defined for this field. * * @param data data block * @return list of descriptions */ public List<String> getTaskFieldDescriptions (byte[] data) { if (data == null || data.length == 0) { return null; } List<String> descriptions = new LinkedList<String>(); int offset = 0; while (offset < data.length) { String description = MPPUtility.getUnicodeString(data, offset); descriptions.add(description); offset += description.length() * 2 + 2; } return descriptions; } /** * Retrieves the description value list associated with a custom task field. * This method will return null if no descriptions for the value list has * been defined for this field. * * @param file parent project file * @param field task field * @param data data block * @return list of task field values */ public List<Object> getTaskFieldValues (ProjectFile file, TaskField field, byte[] data) { if (field == null || data == null || data.length == 0) { return null; } List<Object> list = new LinkedList<Object>(); int offset = 0; switch (field.getDataType()) { case DATE: while (offset+4 <= data.length) { Date date = MPPUtility.getTimestamp(data, offset); list.add(date); offset += 4; } break; case CURRENCY: while (offset+8 <= data.length) { Double number = NumberUtility.getDouble(MPPUtility.getDouble(data, offset) / 100.0); list.add(number); offset += 8; } break; case NUMERIC: while (offset+8 <= data.length) { Double number = NumberUtility.getDouble(MPPUtility.getDouble(data, offset)); list.add(number); offset += 8; } break; case DURATION: while (offset+6 <= data.length) { Duration duration = MPPUtility.getAdjustedDuration(file, MPPUtility.getInt(data, offset), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, offset + 4))); list.add(duration); offset += 6; } break; case STRING: while (offset < data.length) { String s = MPPUtility.getUnicodeString(data, offset); list.add(s); offset += s.length() * 2 + 2; } break; case BOOLEAN: while (offset+2 <= data.length) { boolean b = (MPPUtility.getShort(data, offset) == 0x01); list.add(Boolean.valueOf(b)); offset += 2; } break; default: return null; } return list; } /** * Retrieve any resource field aliases defined in the MPP file. * * @param data resource field name alias data */ private void processResourceFieldNameAliases (byte[] data) { if (data != null) { int offset = 0; ArrayList<String> aliases = new ArrayList<String>(250); while (offset < data.length) { String alias = MPPUtility.getUnicodeString(data, offset); aliases.add(alias); offset += (alias.length()+1)*2; } m_file.setResourceFieldAlias(ResourceField.TEXT1, aliases.get(52)); m_file.setResourceFieldAlias(ResourceField.TEXT2, aliases.get(53)); m_file.setResourceFieldAlias(ResourceField.TEXT3, aliases.get(54)); m_file.setResourceFieldAlias(ResourceField.TEXT4, aliases.get(55)); m_file.setResourceFieldAlias(ResourceField.TEXT5, aliases.get(56)); m_file.setResourceFieldAlias(ResourceField.TEXT6, aliases.get(57)); m_file.setResourceFieldAlias(ResourceField.TEXT7, aliases.get(58)); m_file.setResourceFieldAlias(ResourceField.TEXT8, aliases.get(59)); m_file.setResourceFieldAlias(ResourceField.TEXT9, aliases.get(60)); m_file.setResourceFieldAlias(ResourceField.TEXT10, aliases.get(61)); m_file.setResourceFieldAlias(ResourceField.TEXT11, aliases.get(62)); m_file.setResourceFieldAlias(ResourceField.TEXT12, aliases.get(63)); m_file.setResourceFieldAlias(ResourceField.TEXT13, aliases.get(64)); m_file.setResourceFieldAlias(ResourceField.TEXT14, aliases.get(65)); m_file.setResourceFieldAlias(ResourceField.TEXT15, aliases.get(66)); m_file.setResourceFieldAlias(ResourceField.TEXT16, aliases.get(67)); m_file.setResourceFieldAlias(ResourceField.TEXT17, aliases.get(68)); m_file.setResourceFieldAlias(ResourceField.TEXT18, aliases.get(69)); m_file.setResourceFieldAlias(ResourceField.TEXT19, aliases.get(70)); m_file.setResourceFieldAlias(ResourceField.TEXT20, aliases.get(71)); m_file.setResourceFieldAlias(ResourceField.TEXT21, aliases.get(72)); m_file.setResourceFieldAlias(ResourceField.TEXT22, aliases.get(73)); m_file.setResourceFieldAlias(ResourceField.TEXT23, aliases.get(74)); m_file.setResourceFieldAlias(ResourceField.TEXT24, aliases.get(75)); m_file.setResourceFieldAlias(ResourceField.TEXT25, aliases.get(76)); m_file.setResourceFieldAlias(ResourceField.TEXT26, aliases.get(77)); m_file.setResourceFieldAlias(ResourceField.TEXT27, aliases.get(78)); m_file.setResourceFieldAlias(ResourceField.TEXT28, aliases.get(79)); m_file.setResourceFieldAlias(ResourceField.TEXT29, aliases.get(80)); m_file.setResourceFieldAlias(ResourceField.TEXT30, aliases.get(81)); m_file.setResourceFieldAlias(ResourceField.START1, aliases.get(82)); m_file.setResourceFieldAlias(ResourceField.START2, aliases.get(83)); m_file.setResourceFieldAlias(ResourceField.START3, aliases.get(84)); m_file.setResourceFieldAlias(ResourceField.START4, aliases.get(85)); m_file.setResourceFieldAlias(ResourceField.START5, aliases.get(86)); m_file.setResourceFieldAlias(ResourceField.START6, aliases.get(87)); m_file.setResourceFieldAlias(ResourceField.START7, aliases.get(88)); m_file.setResourceFieldAlias(ResourceField.START8, aliases.get(89)); m_file.setResourceFieldAlias(ResourceField.START9, aliases.get(90)); m_file.setResourceFieldAlias(ResourceField.START10, aliases.get(91)); m_file.setResourceFieldAlias(ResourceField.FINISH1, aliases.get(92)); m_file.setResourceFieldAlias(ResourceField.FINISH2, aliases.get(93)); m_file.setResourceFieldAlias(ResourceField.FINISH3, aliases.get(94)); m_file.setResourceFieldAlias(ResourceField.FINISH4, aliases.get(95)); m_file.setResourceFieldAlias(ResourceField.FINISH5, aliases.get(96)); m_file.setResourceFieldAlias(ResourceField.FINISH6, aliases.get(97)); m_file.setResourceFieldAlias(ResourceField.FINISH7, aliases.get(98)); m_file.setResourceFieldAlias(ResourceField.FINISH8, aliases.get(99)); m_file.setResourceFieldAlias(ResourceField.FINISH9, aliases.get(100)); m_file.setResourceFieldAlias(ResourceField.FINISH10, aliases.get(101)); m_file.setResourceFieldAlias(ResourceField.NUMBER1, aliases.get(102)); m_file.setResourceFieldAlias(ResourceField.NUMBER2, aliases.get(103)); m_file.setResourceFieldAlias(ResourceField.NUMBER3, aliases.get(104)); m_file.setResourceFieldAlias(ResourceField.NUMBER4, aliases.get(105)); m_file.setResourceFieldAlias(ResourceField.NUMBER5, aliases.get(106)); m_file.setResourceFieldAlias(ResourceField.NUMBER6, aliases.get(107)); m_file.setResourceFieldAlias(ResourceField.NUMBER7, aliases.get(108)); m_file.setResourceFieldAlias(ResourceField.NUMBER8, aliases.get(109)); m_file.setResourceFieldAlias(ResourceField.NUMBER9, aliases.get(110)); m_file.setResourceFieldAlias(ResourceField.NUMBER10, aliases.get(111)); m_file.setResourceFieldAlias(ResourceField.NUMBER11, aliases.get(112)); m_file.setResourceFieldAlias(ResourceField.NUMBER12, aliases.get(113)); m_file.setResourceFieldAlias(ResourceField.NUMBER13, aliases.get(114)); m_file.setResourceFieldAlias(ResourceField.NUMBER14, aliases.get(115)); m_file.setResourceFieldAlias(ResourceField.NUMBER15, aliases.get(116)); m_file.setResourceFieldAlias(ResourceField.NUMBER16, aliases.get(117)); m_file.setResourceFieldAlias(ResourceField.NUMBER17, aliases.get(118)); m_file.setResourceFieldAlias(ResourceField.NUMBER18, aliases.get(119)); m_file.setResourceFieldAlias(ResourceField.NUMBER19, aliases.get(120)); m_file.setResourceFieldAlias(ResourceField.NUMBER20, aliases.get(121)); m_file.setResourceFieldAlias(ResourceField.DURATION1, aliases.get(122)); m_file.setResourceFieldAlias(ResourceField.DURATION2, aliases.get(123)); m_file.setResourceFieldAlias(ResourceField.DURATION3, aliases.get(124)); m_file.setResourceFieldAlias(ResourceField.DURATION4, aliases.get(125)); m_file.setResourceFieldAlias(ResourceField.DURATION5, aliases.get(126)); m_file.setResourceFieldAlias(ResourceField.DURATION6, aliases.get(127)); m_file.setResourceFieldAlias(ResourceField.DURATION7, aliases.get(128)); m_file.setResourceFieldAlias(ResourceField.DURATION8, aliases.get(129)); m_file.setResourceFieldAlias(ResourceField.DURATION9, aliases.get(130)); m_file.setResourceFieldAlias(ResourceField.DURATION10, aliases.get(131)); m_file.setResourceFieldAlias(ResourceField.DATE1, aliases.get(145)); m_file.setResourceFieldAlias(ResourceField.DATE2, aliases.get(146)); m_file.setResourceFieldAlias(ResourceField.DATE3, aliases.get(147)); m_file.setResourceFieldAlias(ResourceField.DATE4, aliases.get(148)); m_file.setResourceFieldAlias(ResourceField.DATE5, aliases.get(149)); m_file.setResourceFieldAlias(ResourceField.DATE6, aliases.get(150)); m_file.setResourceFieldAlias(ResourceField.DATE7, aliases.get(151)); m_file.setResourceFieldAlias(ResourceField.DATE8, aliases.get(152)); m_file.setResourceFieldAlias(ResourceField.DATE9, aliases.get(153)); m_file.setResourceFieldAlias(ResourceField.DATE10, aliases.get(154)); m_file.setResourceFieldAlias(ResourceField.OUTLINE_CODE1, aliases.get(155)); m_file.setResourceFieldAlias(ResourceField.OUTLINE_CODE2, aliases.get(156)); m_file.setResourceFieldAlias(ResourceField.OUTLINE_CODE3, aliases.get(157)); m_file.setResourceFieldAlias(ResourceField.OUTLINE_CODE4, aliases.get(158)); m_file.setResourceFieldAlias(ResourceField.OUTLINE_CODE5, aliases.get(159)); m_file.setResourceFieldAlias(ResourceField.OUTLINE_CODE6, aliases.get(160)); m_file.setResourceFieldAlias(ResourceField.OUTLINE_CODE7, aliases.get(161)); m_file.setResourceFieldAlias(ResourceField.OUTLINE_CODE8, aliases.get(162)); m_file.setResourceFieldAlias(ResourceField.OUTLINE_CODE9, aliases.get(163)); m_file.setResourceFieldAlias(ResourceField.OUTLINE_CODE10, aliases.get(164)); m_file.setResourceFieldAlias(ResourceField.FLAG10, aliases.get(165)); m_file.setResourceFieldAlias(ResourceField.FLAG1, aliases.get(166)); m_file.setResourceFieldAlias(ResourceField.FLAG2, aliases.get(167)); m_file.setResourceFieldAlias(ResourceField.FLAG3, aliases.get(168)); m_file.setResourceFieldAlias(ResourceField.FLAG4, aliases.get(169)); m_file.setResourceFieldAlias(ResourceField.FLAG5, aliases.get(170)); m_file.setResourceFieldAlias(ResourceField.FLAG6, aliases.get(171)); m_file.setResourceFieldAlias(ResourceField.FLAG7, aliases.get(172)); m_file.setResourceFieldAlias(ResourceField.FLAG8, aliases.get(173)); m_file.setResourceFieldAlias(ResourceField.FLAG9, aliases.get(174)); m_file.setResourceFieldAlias(ResourceField.FLAG11, aliases.get(175)); m_file.setResourceFieldAlias(ResourceField.FLAG12, aliases.get(176)); m_file.setResourceFieldAlias(ResourceField.FLAG13, aliases.get(177)); m_file.setResourceFieldAlias(ResourceField.FLAG14, aliases.get(178)); m_file.setResourceFieldAlias(ResourceField.FLAG15, aliases.get(179)); m_file.setResourceFieldAlias(ResourceField.FLAG16, aliases.get(180)); m_file.setResourceFieldAlias(ResourceField.FLAG17, aliases.get(181)); m_file.setResourceFieldAlias(ResourceField.FLAG18, aliases.get(182)); m_file.setResourceFieldAlias(ResourceField.FLAG19, aliases.get(183)); m_file.setResourceFieldAlias(ResourceField.FLAG20, aliases.get(184)); m_file.setResourceFieldAlias(ResourceField.COST1, aliases.get(207)); m_file.setResourceFieldAlias(ResourceField.COST2, aliases.get(208)); m_file.setResourceFieldAlias(ResourceField.COST3, aliases.get(209)); m_file.setResourceFieldAlias(ResourceField.COST4, aliases.get(210)); m_file.setResourceFieldAlias(ResourceField.COST5, aliases.get(211)); m_file.setResourceFieldAlias(ResourceField.COST6, aliases.get(212)); m_file.setResourceFieldAlias(ResourceField.COST7, aliases.get(213)); m_file.setResourceFieldAlias(ResourceField.COST8, aliases.get(214)); m_file.setResourceFieldAlias(ResourceField.COST9, aliases.get(215)); m_file.setResourceFieldAlias(ResourceField.COST10, aliases.get(216)); } } /** * This method maps the task unique identifiers to their index number * within the FixedData block. * * @param taskFixedMeta Fixed meta data for this task * @param taskFixedData Fixed data for this task * @return Mapping between task identifiers and block position */ private TreeMap<Integer, Integer> createTaskMap (FixedMeta taskFixedMeta, FixedData taskFixedData) { TreeMap<Integer, Integer> taskMap = new TreeMap<Integer, Integer> (); int itemCount = taskFixedMeta.getItemCount(); byte[] data; int uniqueID; Integer key; // First three items are not tasks, so let's skip them for (int loop=3; loop < itemCount; loop++) { data = taskFixedData.getByteArrayValue(loop); if (data != null) { byte[] metaData = taskFixedMeta.getByteArrayValue(loop); int metaDataItemSize = MPPUtility.getInt(metaData, 0); if (metaDataItemSize == 2 || metaDataItemSize == 6) { // Project stores the deleted tasks unique id's into the fixed data as well // and at least in one case the deleted task was listed twice in the list // the second time with data with it causing a phantom task to be shown. // See CalendarErrorPhantomTasks.mpp // So let's add the unique id for the deleted task into the map so we don't // accidentally include the task later. uniqueID = MPPUtility.getShort(data, 0); // Only a short stored for deleted tasks key = new Integer(uniqueID); if (taskMap.containsKey(key) == false) { taskMap.put(key, null); // use null so we can easily ignore this later } } else { if (data.length == 8 || data.length >= MINIMUM_EXPECTED_TASK_SIZE) { uniqueID = MPPUtility.getInt(data, 0); key = new Integer(uniqueID); if (taskMap.containsKey(key) == false) { taskMap.put(key, new Integer (loop)); } } } } } return (taskMap); } /** * This method maps the resource unique identifiers to their index number * within the FixedData block. * * @param rscFixedMeta resource fixed meta data * @param rscFixedData resource fixed data * @return map of resource IDs to resource data */ private TreeMap<Integer, Integer> createResourceMap (FixedMeta rscFixedMeta, FixedData rscFixedData) { TreeMap<Integer, Integer> resourceMap = new TreeMap<Integer, Integer> (); int itemCount = rscFixedMeta.getItemCount(); byte[] data; int uniqueID; for (int loop=0; loop < itemCount; loop++) { data = rscFixedData.getByteArrayValue(loop); if (data != null && data.length > 4) { uniqueID = MPPUtility.getShort (data, 0); resourceMap.put(new Integer (uniqueID), new Integer (loop)); } } return (resourceMap); } /** * The format of the calendar data is a 4 byte header followed * by 7x 60 byte blocks, one for each day of the week. Optionally * following this is a set of 64 byte blocks representing exceptions * to the calendar. */ private void processCalendarData () throws IOException { DirectoryEntry calDir = (DirectoryEntry)m_projectDir.getEntry ("TBkndCal"); VarMeta calVarMeta = new VarMeta9 (new DocumentInputStream (((DocumentEntry)calDir.getEntry("VarMeta")))); Var2Data calVarData = new Var2Data (calVarMeta, new DocumentInputStream (((DocumentEntry)calDir.getEntry("Var2Data")))); FixedMeta calFixedMeta = new FixedMeta (new DocumentInputStream (((DocumentEntry)calDir.getEntry("FixedMeta"))), 10); FixedData calFixedData = new FixedData (calFixedMeta, getEncryptableInputStream(calDir, "FixedData")); HashMap<Integer, ProjectCalendar> calendarMap = new HashMap<Integer, ProjectCalendar> (); int items = calFixedData.getItemCount(); byte[] fixedData; byte[] varData; Integer calendarID; int baseCalendarID; Integer resourceID; int offset; ProjectCalendar cal; List<Pair<ProjectCalendar, Integer>> baseCalendars = new LinkedList<Pair<ProjectCalendar, Integer>>(); for (int loop=0; loop < items; loop++) { fixedData = calFixedData.getByteArrayValue(loop); if (fixedData.length >= 8) { offset = 0; // Bug 890909, here we ensure that we have a complete 12 byte // block before attempting to process the data. while (offset+12 <= fixedData.length) { calendarID = new Integer (MPPUtility.getInt (fixedData, offset+0)); baseCalendarID = MPPUtility.getInt(fixedData, offset+4); // Ignore invalid and duplicate IDs. if (calendarID.intValue() != -1 && calendarID.intValue() != 0 && baseCalendarID != 0 && calendarMap.containsKey(calendarID) == false) { varData = calVarData.getByteArray (calendarID, CALENDAR_DATA); if (baseCalendarID == -1) { if (varData != null) { cal = m_file.addBaseCalendar(); } else { cal = m_file.addDefaultBaseCalendar(); } cal.setName(calVarData.getUnicodeString (calendarID, CALENDAR_NAME)); } else { if (varData != null) { cal = m_file.addResourceCalendar(); } else { cal = m_file.getDefaultResourceCalendar(); } baseCalendars.add(new Pair<ProjectCalendar, Integer>(cal, new Integer(baseCalendarID))); resourceID = new Integer (MPPUtility.getInt(fixedData, offset+8)); m_resourceMap.put (resourceID, cal); } cal.setUniqueID(calendarID); if (varData != null) { processCalendarHours (varData, cal, baseCalendarID == -1); processCalendarExceptions (varData, cal); } calendarMap.put (calendarID, cal); } offset += 12; } } } updateBaseCalendarNames (baseCalendars, calendarMap); } /** * For a given set of calendar data, this method sets the working * day status for each day, and if present, sets the hours for that * day. * * @param data calendar data block * @param cal calendar instance * @param isBaseCalendar true if this is a base calendar */ private void processCalendarHours (byte[] data, ProjectCalendar cal, boolean isBaseCalendar) { // Dump out the calendar related data and fields. //MPPUtility.dataDump(data, true, false, false, false, true, false, true); int offset; ProjectCalendarHours hours; int periodCount; int periodIndex; int index; int defaultFlag; Date start; long duration; Day day; for (index=0; index < 7; index++) { offset = 4 + (60 * index); defaultFlag = MPPUtility.getShort (data, offset); day = Day.getInstance(index+1); if (defaultFlag == 1) { if (isBaseCalendar == true) { cal.setWorkingDay(day, DEFAULT_WORKING_WEEK[index]); if (cal.isWorkingDay(day) == true) { hours = cal.addCalendarHours(Day.getInstance(index+1)); hours.addDateRange(new DateRange(ProjectCalendar.DEFAULT_START1, ProjectCalendar.DEFAULT_END1)); hours.addDateRange(new DateRange(ProjectCalendar.DEFAULT_START2, ProjectCalendar.DEFAULT_END2)); } } else { cal.setWorkingDay(day, ProjectCalendar.DEFAULT); } } else { periodCount = MPPUtility.getShort (data, offset+2); if (periodCount == 0) { cal.setWorkingDay(day, false); } else { cal.setWorkingDay(day, true); hours = cal.addCalendarHours(Day.getInstance(index+1)); for (periodIndex=0; periodIndex < periodCount; periodIndex++) { start = MPPUtility.getTime (data, offset + 8 + (periodIndex * 2)); duration = MPPUtility.getDuration (data, offset + 20 + (periodIndex * 4)); hours.addDateRange(new DateRange (start, new Date (start.getTime()+duration))); } } } } } /** * This method extracts any exceptions associated with a calendar. * * @param data calendar data block * @param cal calendar instance */ private void processCalendarExceptions (byte[] data, ProjectCalendar cal) { // Handle any exceptions int exceptionCount = MPPUtility.getShort (data, 0); if (exceptionCount != 0) { int index; int offset; ProjectCalendarException exception; long duration; int periodCount; Date start; for (index=0; index < exceptionCount; index++) { offset = 4 + (60 * 7) + (index * 64); exception = cal.addCalendarException(); exception.setFromDate(MPPUtility.getDate (data, offset)); exception.setToDate(MPPUtility.getDate (data, offset+2)); periodCount = MPPUtility.getShort (data, offset+6); if (periodCount == 0) { exception.setWorking (false); } else { exception.setWorking (true); start = MPPUtility.getTime (data, offset+12); duration = MPPUtility.getDuration (data, offset+24); exception.setFromTime1(start); exception.setToTime1(new Date (start.getTime() + duration)); if (periodCount > 1) { start = MPPUtility.getTime (data, offset+14); duration = MPPUtility.getDuration (data, offset+28); exception.setFromTime2(start); exception.setToTime2(new Date (start.getTime() + duration)); if (periodCount > 2) { start = MPPUtility.getTime (data, offset+16); duration = MPPUtility.getDuration (data, offset+32); exception.setFromTime3(start); exception.setToTime3(new Date (start.getTime() + duration)); if (periodCount > 3) { start = MPPUtility.getTime (data, offset+18); duration = MPPUtility.getDuration (data, offset+36); exception.setFromTime4(start); exception.setToTime4(new Date (start.getTime() + duration)); if (periodCount > 4) { start = MPPUtility.getTime (data, offset+20); duration = MPPUtility.getDuration (data, offset+40); exception.setFromTime5(start); exception.setToTime5(new Date (start.getTime() + duration)); } } } } } } } } /** * The way calendars are stored in an MPP9 file means that there * can be forward references between the base calendar unique ID for a * derived calendar, and the base calendar itself. To get around this, * we initially populate the base calendar name attribute with the * base calendar unique ID, and now in this method we can convert those * ID values into the correct names. * * @param baseCalendars list of calendars and base calendar IDs * @param map map of calendar ID values and calendar objects */ private void updateBaseCalendarNames (List<Pair<ProjectCalendar, Integer>> baseCalendars, HashMap<Integer, ProjectCalendar> map) { for (Pair<ProjectCalendar, Integer> pair : baseCalendars) { ProjectCalendar cal = pair.getFirst(); Integer baseCalendarID = pair.getSecond(); ProjectCalendar baseCal = map.get(baseCalendarID); if (baseCal != null && baseCal.getName() != null) { cal.setBaseCalendar(baseCal); } else { // Remove invalid calendar to avoid serious problems later. m_file.removeCalendar(cal); } } } /** * This method extracts and collates task data. The code below * goes through the modifier methods of the Task class in alphabetical * order extracting the data from the MPP file. Where there is no * mapping (e.g. the field is calculated on the fly, or we can't * find it in the data) the line is commented out. * * The missing boolean attributes are probably represented in the Props * section of the task data, which we have yet to decode. * * @throws IOException */ private void processTaskData () throws IOException { DirectoryEntry taskDir = (DirectoryEntry)m_projectDir.getEntry ("TBkndTask"); VarMeta taskVarMeta = new VarMeta9 (new DocumentInputStream (((DocumentEntry)taskDir.getEntry("VarMeta")))); Var2Data taskVarData = new Var2Data (taskVarMeta, new DocumentInputStream (((DocumentEntry)taskDir.getEntry("Var2Data")))); FixedMeta taskFixedMeta = new FixedMeta (new DocumentInputStream (((DocumentEntry)taskDir.getEntry("FixedMeta"))), 47); FixedData taskFixedData = new FixedData (taskFixedMeta, getEncryptableInputStream(taskDir, "FixedData"), 768, MINIMUM_EXPECTED_TASK_SIZE); //System.out.println(taskFixedData); //System.out.println(taskFixedMeta); //System.out.println(taskVarMeta); //System.out.println(taskVarData); TreeMap<Integer, Integer> taskMap = createTaskMap (taskFixedMeta, taskFixedData); // The var data may not contain all the tasks as tasks with no var data assigned will // not be saved in there. Most notably these are tasks with no name. So use the task map // which contains all the tasks. Object[] uniqueid = taskMap.keySet().toArray(); //taskVarMeta.getUniqueIdentifierArray(); Integer id; Integer offset; byte[] data; byte[] metaData; Task task; boolean autoWBS = true; LinkedList<Task> externalTasks = new LinkedList<Task>(); RecurringTaskReader recurringTaskReader = null; RTFUtility rtf = new RTFUtility (); String notes; for (int loop=0; loop < uniqueid.length; loop++) { id = (Integer)uniqueid[loop]; offset = taskMap.get(id); if (taskFixedData.isValidOffset(offset) == false) { continue; } data = taskFixedData.getByteArrayValue(offset.intValue()); if (data.length == 8) { task = m_file.addTask(); task.setNull(true); task.setUniqueID(id); task.setID (new Integer(MPPUtility.getInt (data, 4))); //System.out.println(task); continue; } if (data.length < MINIMUM_EXPECTED_TASK_SIZE) { continue; } metaData = taskFixedMeta.getByteArrayValue(offset.intValue()); //System.out.println (MPPUtility.hexdump(data, false, 16, "")); //System.out.println (MPPUtility.hexdump(metaData, false, 16, "")); //MPPUtility.dataDump(data, true, true, true, true, true, true, true); //MPPUtility.dataDump(metaData, true, true, true, true, true, true, true); //MPPUtility.varDataDump(taskVarData, id, true, true, true, true, true, true); byte[] recurringData = taskVarData.getByteArray(id, TASK_RECURRING_DATA); Task temp = m_file.getTaskByID(new Integer(MPPUtility.getInt(data, 4))); if (temp != null) { // Task with this id already exists... determine if this is the 'real' task by seeing // if this task has some var data. This is sort of hokey, but it's the best method i have // been able to see. if (taskVarMeta.getUniqueIdentifierSet().contains(id)) { // Since this new task contains var data, we are going to assume the first one is // a deleted task and this is the real one. m_file.removeTask(temp); } else { // Sometimes Project contains phantom tasks that co-exist on the same id as a valid // task. In this case don't want to include the phantom task. Seems to be a very rare case. continue; } } task = m_file.addTask(); task.setActualCost(NumberUtility.getDouble (MPPUtility.getDouble (data, 216) / 100)); task.setActualDuration(MPPUtility.getDuration (MPPUtility.getInt (data, 66), MPPUtility.getDurationTimeUnits(MPPUtility.getShort (data, 64)))); task.setActualFinish(MPPUtility.getTimestamp (data, 100)); task.setActualOvertimeCost (NumberUtility.getDouble(taskVarData.getDouble(id, TASK_ACTUAL_OVERTIME_COST) / 100)); task.setActualOvertimeWork(Duration.getInstance (taskVarData.getDouble(id, TASK_ACTUAL_OVERTIME_WORK)/60000, TimeUnit.HOURS)); task.setActualStart(MPPUtility.getTimestamp (data, 96)); task.setActualWork(Duration.getInstance (MPPUtility.getDouble (data, 184)/60000, TimeUnit.HOURS)); //task.setACWP(); // Calculated value //task.setAssignment(); // Calculated value //task.setAssignmentDelay(); // Calculated value //task.setAssignmentUnits(); // Calculated value task.setBaselineCost(NumberUtility.getDouble (MPPUtility.getDouble (data, 232) / 100)); task.setBaselineDuration(MPPUtility.getDuration (MPPUtility.getInt (data, 74), MPPUtility.getDurationTimeUnits (MPPUtility.getShort (data, 78)))); task.setBaselineFinish(MPPUtility.getTimestamp (data, 108)); task.setBaselineStart(MPPUtility.getTimestamp (data, 104)); task.setBaselineWork(Duration.getInstance (MPPUtility.getDouble (data, 176)/60000, TimeUnit.HOURS)); // From MS Project 2003 // task.setBaseline1Cost(NumberUtility.getDouble (MPPUtility.getDouble (data, 232) / 100)); // task.setBaseline1Duration(MPPUtility.getDuration (MPPUtility.getInt (data, 74), MPPUtility.getDurationTimeUnits (MPPUtility.getShort (data, 78)))); // task.setBaseline1Finish(MPPUtility.getTimestamp (data, 108)); // task.setBaseline1Start(MPPUtility.getTimestamp (data, 104)); // task.setBaseline1Work(Duration.getInstance (MPPUtility.getDouble (data, 176)/60000, TimeUnit.HOURS)); // task.setBaseline10Cost(NumberUtility.getDouble (MPPUtility.getDouble (data, 232) / 100)); // task.setBaseline10Duration(MPPUtility.getDuration (MPPUtility.getInt (data, 74), MPPUtility.getDurationTimeUnits (MPPUtility.getShort (data, 78)))); // task.setBaseline10Finish(MPPUtility.getTimestamp (data, 108)); // task.setBaseline10Start(MPPUtility.getTimestamp (data, 104)); // task.setBaseline10Work(Duration.getInstance (MPPUtility.getDouble (data, 176)/60000, TimeUnit.HOURS)); //task.setBCWP(); // Calculated value //task.setBCWS(); // Calculated value //task.setConfirmed(); // Calculated value task.setConstraintDate (MPPUtility.getTimestamp (data, 112)); task.setConstraintType (ConstraintType.getInstance (MPPUtility.getShort (data, 80))); task.setContact(taskVarData.getUnicodeString (id, TASK_CONTACT)); task.setCost(NumberUtility.getDouble (MPPUtility.getDouble(data, 200) / 100)); //task.setCostRateTable(); // Calculated value //task.setCostVariance(); // Populated below task.setCost1(NumberUtility.getDouble (taskVarData.getDouble (id, TASK_COST1) / 100)); task.setCost2(NumberUtility.getDouble (taskVarData.getDouble (id, TASK_COST2) / 100)); task.setCost3(NumberUtility.getDouble (taskVarData.getDouble (id, TASK_COST3) / 100)); task.setCost4(NumberUtility.getDouble (taskVarData.getDouble (id, TASK_COST4) / 100)); task.setCost5(NumberUtility.getDouble (taskVarData.getDouble (id, TASK_COST5) / 100)); task.setCost6(NumberUtility.getDouble (taskVarData.getDouble (id, TASK_COST6) / 100)); task.setCost7(NumberUtility.getDouble (taskVarData.getDouble (id, TASK_COST7) / 100)); task.setCost8(NumberUtility.getDouble (taskVarData.getDouble (id, TASK_COST8) / 100)); task.setCost9(NumberUtility.getDouble (taskVarData.getDouble (id, TASK_COST9) / 100)); task.setCost10(NumberUtility.getDouble (taskVarData.getDouble (id, TASK_COST10) / 100)); // From MS Project 2003 // task.setCPI(); task.setCreateDate(MPPUtility.getTimestamp (data, 130)); //task.setCritical(); // Calculated value //task.setCV(); // Calculated value //task.setCVPercent(); // Calculate value task.setDate1(taskVarData.getTimestamp (id, TASK_DATE1)); task.setDate2(taskVarData.getTimestamp (id, TASK_DATE2)); task.setDate3(taskVarData.getTimestamp (id, TASK_DATE3)); task.setDate4(taskVarData.getTimestamp (id, TASK_DATE4)); task.setDate5(taskVarData.getTimestamp (id, TASK_DATE5)); task.setDate6(taskVarData.getTimestamp (id, TASK_DATE6)); task.setDate7(taskVarData.getTimestamp (id, TASK_DATE7)); task.setDate8(taskVarData.getTimestamp (id, TASK_DATE8)); task.setDate9(taskVarData.getTimestamp (id, TASK_DATE9)); task.setDate10(taskVarData.getTimestamp (id, TASK_DATE10)); task.setDeadline (MPPUtility.getTimestamp (data, 164)); //task.setDelay(); // No longer supported by MS Project? task.setDuration (MPPUtility.getAdjustedDuration (m_file, MPPUtility.getInt (data, 60), MPPUtility.getDurationTimeUnits(MPPUtility.getShort (data, 64)))); //task.setDurationVariance(); // Calculated value task.setDuration1(MPPUtility.getAdjustedDuration (m_file, taskVarData.getInt(id, TASK_DURATION1), MPPUtility.getDurationTimeUnits(taskVarData.getShort(id, TASK_DURATION1_UNITS)))); task.setDuration2(MPPUtility.getAdjustedDuration (m_file, taskVarData.getInt(id, TASK_DURATION2), MPPUtility.getDurationTimeUnits(taskVarData.getShort(id, TASK_DURATION2_UNITS)))); task.setDuration3(MPPUtility.getAdjustedDuration (m_file, taskVarData.getInt(id, TASK_DURATION3), MPPUtility.getDurationTimeUnits(taskVarData.getShort(id, TASK_DURATION3_UNITS)))); task.setDuration4(MPPUtility.getAdjustedDuration (m_file, taskVarData.getInt(id, TASK_DURATION4), MPPUtility.getDurationTimeUnits(taskVarData.getShort(id, TASK_DURATION4_UNITS)))); task.setDuration5(MPPUtility.getAdjustedDuration (m_file, taskVarData.getInt(id, TASK_DURATION5), MPPUtility.getDurationTimeUnits(taskVarData.getShort(id, TASK_DURATION5_UNITS)))); task.setDuration6(MPPUtility.getAdjustedDuration (m_file, taskVarData.getInt(id, TASK_DURATION6), MPPUtility.getDurationTimeUnits(taskVarData.getShort(id, TASK_DURATION6_UNITS)))); task.setDuration7(MPPUtility.getAdjustedDuration (m_file, taskVarData.getInt(id, TASK_DURATION7), MPPUtility.getDurationTimeUnits(taskVarData.getShort(id, TASK_DURATION7_UNITS)))); task.setDuration8(MPPUtility.getAdjustedDuration (m_file, taskVarData.getInt(id, TASK_DURATION8), MPPUtility.getDurationTimeUnits(taskVarData.getShort(id, TASK_DURATION8_UNITS)))); task.setDuration9(MPPUtility.getAdjustedDuration (m_file, taskVarData.getInt(id, TASK_DURATION9), MPPUtility.getDurationTimeUnits(taskVarData.getShort(id, TASK_DURATION9_UNITS)))); task.setDuration10(MPPUtility.getAdjustedDuration (m_file, taskVarData.getInt(id, TASK_DURATION10), MPPUtility.getDurationTimeUnits(taskVarData.getShort(id, TASK_DURATION10_UNITS)))); // From MS Project 2003 // task.setEAC(); task.setEarlyFinish (MPPUtility.getTimestamp (data, 8)); task.setEarlyStart (MPPUtility.getTimestamp (data, 88)); // From MS Project 2003 // task.setEarnedValueMethod(); task.setEffortDriven((metaData[11] & 0x10) != 0); task.setEstimated(getDurationEstimated(MPPUtility.getShort (data, 64))); task.setExpanded(((metaData[12] & 0x02) == 0)); int externalTaskID = taskVarData.getInt(id, TASK_EXTERNAL_TASK_ID); if (externalTaskID != 0) { task.setExternalTaskID(new Integer(externalTaskID)); task.setExternalTask(true); externalTasks.add(task); } task.setFinish (MPPUtility.getTimestamp (data, 8)); // From MS Project 2003 //task.setFinishVariance(); // Calculated value task.setFinish1(taskVarData.getTimestamp (id, TASK_FINISH1)); task.setFinish2(taskVarData.getTimestamp (id, TASK_FINISH2)); task.setFinish3(taskVarData.getTimestamp (id, TASK_FINISH3)); task.setFinish4(taskVarData.getTimestamp (id, TASK_FINISH4)); task.setFinish5(taskVarData.getTimestamp (id, TASK_FINISH5)); task.setFinish6(taskVarData.getTimestamp (id, TASK_FINISH6)); task.setFinish7(taskVarData.getTimestamp (id, TASK_FINISH7)); task.setFinish8(taskVarData.getTimestamp (id, TASK_FINISH8)); task.setFinish9(taskVarData.getTimestamp (id, TASK_FINISH9)); task.setFinish10(taskVarData.getTimestamp (id, TASK_FINISH10)); task.setFixedCost(NumberUtility.getDouble (MPPUtility.getDouble (data, 208) / 100)); task.setFixedCostAccrual(AccrueType.getInstance(MPPUtility.getShort(data, 128))); task.setFlag1((metaData[37] & 0x20) != 0); task.setFlag2((metaData[37] & 0x40) != 0); task.setFlag3((metaData[37] & 0x80) != 0); task.setFlag4((metaData[38] & 0x01) != 0); task.setFlag5((metaData[38] & 0x02) != 0); task.setFlag6((metaData[38] & 0x04) != 0); task.setFlag7((metaData[38] & 0x08) != 0); task.setFlag8((metaData[38] & 0x10) != 0); task.setFlag9((metaData[38] & 0x20) != 0); task.setFlag10((metaData[38] & 0x40) != 0); task.setFlag11((metaData[38] & 0x80) != 0); task.setFlag12((metaData[39] & 0x01) != 0); task.setFlag13((metaData[39] & 0x02) != 0); task.setFlag14((metaData[39] & 0x04) != 0); task.setFlag15((metaData[39] & 0x08) != 0); task.setFlag16((metaData[39] & 0x10) != 0); task.setFlag17((metaData[39] & 0x20) != 0); task.setFlag18((metaData[39] & 0x40) != 0); task.setFlag19((metaData[39] & 0x80) != 0); task.setFlag20((metaData[40] & 0x01) != 0); task.setFreeSlack(MPPUtility.getAdjustedDuration (m_file, MPPUtility.getInt(data, 24), MPPUtility.getDurationTimeUnits(MPPUtility.getShort (data, 64)))); // From MS Project 2003 // task.setGroupBySummary(); task.setHideBar((metaData[10] & 0x80) != 0); processHyperlinkData (task, taskVarData.getByteArray(id, TASK_HYPERLINK)); task.setID (new Integer(MPPUtility.getInt (data, 4))); // From MS Project 2003 task.setIgnoreResourceCalendar(((metaData[10] & 0x02) != 0)); //task.setIndicators(); // Calculated value task.setLateFinish(MPPUtility.getTimestamp(data, 152)); task.setLateStart(MPPUtility.getTimestamp(data, 12)); task.setLevelAssignments((metaData[13] & 0x04) != 0); task.setLevelingCanSplit((metaData[13] & 0x02) != 0); task.setLevelingDelay (MPPUtility.getDuration (((double)MPPUtility.getInt (data, 82))/3, MPPUtility.getDurationTimeUnits(MPPUtility.getShort (data, 86)))); //task.setLinkedFields(); // Calculated value task.setMarked((metaData[9] & 0x40) != 0); task.setMilestone((metaData[8] & 0x20) != 0); task.setName(taskVarData.getUnicodeString (id, TASK_NAME)); task.setNumber1(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER1))); task.setNumber2(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER2))); task.setNumber3(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER3))); task.setNumber4(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER4))); task.setNumber5(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER5))); task.setNumber6(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER6))); task.setNumber7(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER7))); task.setNumber8(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER8))); task.setNumber9(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER9))); task.setNumber10(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER10))); task.setNumber11(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER11))); task.setNumber12(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER12))); task.setNumber13(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER13))); task.setNumber14(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER14))); task.setNumber15(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER15))); task.setNumber16(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER16))); task.setNumber17(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER17))); task.setNumber18(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER18))); task.setNumber19(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER19))); task.setNumber20(NumberUtility.getDouble (taskVarData.getDouble(id, TASK_NUMBER20))); //task.setObjects(); // Calculated value task.setOutlineCode1(m_outlineCodeVarData.getUnicodeString(new Integer(taskVarData.getInt (id, TASK_OUTLINECODE1)), OUTLINECODE_DATA)); task.setOutlineCode2(m_outlineCodeVarData.getUnicodeString(new Integer(taskVarData.getInt (id, TASK_OUTLINECODE2)), OUTLINECODE_DATA)); task.setOutlineCode3(m_outlineCodeVarData.getUnicodeString(new Integer(taskVarData.getInt (id, TASK_OUTLINECODE3)), OUTLINECODE_DATA)); task.setOutlineCode4(m_outlineCodeVarData.getUnicodeString(new Integer(taskVarData.getInt (id, TASK_OUTLINECODE4)), OUTLINECODE_DATA)); task.setOutlineCode5(m_outlineCodeVarData.getUnicodeString(new Integer(taskVarData.getInt (id, TASK_OUTLINECODE5)), OUTLINECODE_DATA)); task.setOutlineCode6(m_outlineCodeVarData.getUnicodeString(new Integer(taskVarData.getInt (id, TASK_OUTLINECODE6)), OUTLINECODE_DATA)); task.setOutlineCode7(m_outlineCodeVarData.getUnicodeString(new Integer(taskVarData.getInt (id, TASK_OUTLINECODE7)), OUTLINECODE_DATA)); task.setOutlineCode8(m_outlineCodeVarData.getUnicodeString(new Integer(taskVarData.getInt (id, TASK_OUTLINECODE8)), OUTLINECODE_DATA)); task.setOutlineCode9(m_outlineCodeVarData.getUnicodeString(new Integer(taskVarData.getInt (id, TASK_OUTLINECODE9)), OUTLINECODE_DATA)); task.setOutlineCode10(m_outlineCodeVarData.getUnicodeString(new Integer(taskVarData.getInt (id, TASK_OUTLINECODE10)), OUTLINECODE_DATA)); task.setOutlineLevel (new Integer(MPPUtility.getShort (data, 40))); //task.setOutlineNumber(); // Calculated value //task.setOverallocated(); // Calculated value task.setOvertimeCost(NumberUtility.getDouble(taskVarData.getDouble(id, TASK_OVERTIME_COST) / 100)); //task.setOvertimeWork(); // Calculated value? //task.getPredecessors(); // Calculated value task.setPercentageComplete(NumberUtility.getDouble(MPPUtility.getShort(data, 122))); task.setPercentageWorkComplete(NumberUtility.getDouble(MPPUtility.getShort(data, 124))); // From MS Project 2003 // task.setPhysicalPercentComplete(); task.setPreleveledFinish(MPPUtility.getTimestamp(data, 140)); task.setPreleveledStart(MPPUtility.getTimestamp(data, 136)); task.setPriority(Priority.getInstance(MPPUtility.getShort (data, 120))); //task.setProject(); // Calculated value task.setRecurring(recurringData!=null); //task.setRegularWork(); // Calculated value task.setRemainingCost(NumberUtility.getDouble (MPPUtility.getDouble (data, 224)/100)); task.setRemainingDuration(MPPUtility.getDuration (MPPUtility.getInt (data, 70), MPPUtility.getDurationTimeUnits(MPPUtility.getShort (data, 64)))); task.setRemainingOvertimeCost(NumberUtility.getDouble(taskVarData.getDouble(id, TASK_REMAINING_OVERTIME_COST) / 100)); task.setRemainingOvertimeWork(Duration.getInstance (taskVarData.getDouble(id, TASK_REMAINING_OVERTIME_WORK)/60000, TimeUnit.HOURS)); task.setRemainingWork(Duration.getInstance (MPPUtility.getDouble (data, 192)/60000, TimeUnit.HOURS)); //task.setResourceGroup(); // Calculated value from resource //task.setResourceInitials(); // Calculated value from resource //task.setResourceNames(); // Calculated value from resource //task.setResourcePhonetics(); // Calculated value from resource // From MS Project 2003 // task.setResourceType(); //task.setResponsePending(); // Calculated value task.setResume(MPPUtility.getTimestamp(data, 20)); //task.setResumeNoEarlierThan(); // No mapping in MSP2K? task.setRollup((metaData[10] & 0x08) != 0); // From MS Project 2003 // task.setSPI(); task.setStart (MPPUtility.getTimestamp (data, 88)); // From MS Project 2003 task.setStartSlack(MPPUtility.getAdjustedDuration (m_file, MPPUtility.getInt(data, 28), MPPUtility.getDurationTimeUnits(MPPUtility.getShort (data, 64)))); //task.setStartVariance(); // Calculated value task.setStart1(taskVarData.getTimestamp (id, TASK_START1)); task.setStart2(taskVarData.getTimestamp (id, TASK_START2)); task.setStart3(taskVarData.getTimestamp (id, TASK_START3)); task.setStart4(taskVarData.getTimestamp (id, TASK_START4)); task.setStart5(taskVarData.getTimestamp (id, TASK_START5)); task.setStart6(taskVarData.getTimestamp (id, TASK_START6)); task.setStart7(taskVarData.getTimestamp (id, TASK_START7)); task.setStart8(taskVarData.getTimestamp (id, TASK_START8)); task.setStart9(taskVarData.getTimestamp (id, TASK_START9)); task.setStart10(taskVarData.getTimestamp (id, TASK_START10)); // From MS Project 2003 // task.setStatus(); // task.setStatusIndicator(); task.setStop(MPPUtility.getTimestamp (data, 16)); //task.setSubprojectFile(); //task.setSubprojectReadOnly(); task.setSubprojectTasksUniqueIDOffset(new Integer (taskVarData.getInt(id, TASK_SUBPROJECT_TASKS_UNIQUEID_OFFSET))); task.setSubprojectTaskUniqueID(new Integer (taskVarData.getInt(id, TASK_SUBPROJECTUNIQUETASKID))); task.setSubprojectTaskID(new Integer (taskVarData.getInt(id, TASK_SUBPROJECTTASKID))); //task.setSuccessors(); // Calculated value //task.setSummary(); // Automatically generated by MPXJ //task.setSV(); // Calculated value // From MS Project 2003 // task.setSVPercent(); // task.setTCPI(); //task.setTeamStatusPending(); // Calculated value task.setText1(taskVarData.getUnicodeString (id, TASK_TEXT1)); task.setText2(taskVarData.getUnicodeString (id, TASK_TEXT2)); task.setText3(taskVarData.getUnicodeString (id, TASK_TEXT3)); task.setText4(taskVarData.getUnicodeString (id, TASK_TEXT4)); task.setText5(taskVarData.getUnicodeString (id, TASK_TEXT5)); task.setText6(taskVarData.getUnicodeString (id, TASK_TEXT6)); task.setText7(taskVarData.getUnicodeString (id, TASK_TEXT7)); task.setText8(taskVarData.getUnicodeString (id, TASK_TEXT8)); task.setText9(taskVarData.getUnicodeString (id, TASK_TEXT9)); task.setText10(taskVarData.getUnicodeString (id, TASK_TEXT10)); task.setText11(taskVarData.getUnicodeString (id, TASK_TEXT11)); task.setText12(taskVarData.getUnicodeString (id, TASK_TEXT12)); task.setText13(taskVarData.getUnicodeString (id, TASK_TEXT13)); task.setText14(taskVarData.getUnicodeString (id, TASK_TEXT14)); task.setText15(taskVarData.getUnicodeString (id, TASK_TEXT15)); task.setText16(taskVarData.getUnicodeString (id, TASK_TEXT16)); task.setText17(taskVarData.getUnicodeString (id, TASK_TEXT17)); task.setText18(taskVarData.getUnicodeString (id, TASK_TEXT18)); task.setText19(taskVarData.getUnicodeString (id, TASK_TEXT19)); task.setText20(taskVarData.getUnicodeString (id, TASK_TEXT20)); task.setText21(taskVarData.getUnicodeString (id, TASK_TEXT21)); task.setText22(taskVarData.getUnicodeString (id, TASK_TEXT22)); task.setText23(taskVarData.getUnicodeString (id, TASK_TEXT23)); task.setText24(taskVarData.getUnicodeString (id, TASK_TEXT24)); task.setText25(taskVarData.getUnicodeString (id, TASK_TEXT25)); task.setText26(taskVarData.getUnicodeString (id, TASK_TEXT26)); task.setText27(taskVarData.getUnicodeString (id, TASK_TEXT27)); task.setText28(taskVarData.getUnicodeString (id, TASK_TEXT28)); task.setText29(taskVarData.getUnicodeString (id, TASK_TEXT29)); task.setText30(taskVarData.getUnicodeString (id, TASK_TEXT30)); //task.setTotalSlack(); // Calculated value task.setType(TaskType.getInstance(MPPUtility.getShort(data, 126))); task.setUniqueID(id); //task.setUniqueIDPredecessors(); // Calculated value //task.setUniqueIDSuccessors(); // Calculated value //task.setUpdateNeeded(); // Calculated value task.setWBS(taskVarData.getUnicodeString (id, TASK_WBS)); //task.setWBSPredecessors(); // Calculated value //task.setWBSSuccessors(); // Calculated value task.setWork(Duration.getInstance (MPPUtility.getDouble (data, 168)/60000, TimeUnit.HOURS)); //task.setWorkContour(); // Calculated from resource //task.setWorkVariance(); // Calculated value task.setFinishSlack(MPPUtility.getAdjustedDuration (m_file, MPPUtility.getInt(data, 32), MPPUtility.getDurationTimeUnits(MPPUtility.getShort (data, 64)))); switch (task.getConstraintType()) { // Adjust the start and finish dates if the task // is constrained to start as late as possible. case AS_LATE_AS_POSSIBLE: { if (task.getStart().getTime() < task.getLateStart().getTime()) { task.setStart(task.getLateStart()); } if (task.getFinish().getTime() < task.getLateFinish().getTime()) { task.setFinish(task.getLateFinish()); } break; } case START_NO_LATER_THAN: { if (task.getFinish().getTime() < task.getStart().getTime()) { task.setFinish(task.getLateFinish()); } break; } case FINISH_NO_LATER_THAN: { if (task.getFinish().getTime() < task.getStart().getTime()) { task.setFinish(task.getLateFinish()); } break; } default: { break; } } // Retrieve task recurring data if (recurringData != null) { if (recurringTaskReader == null) { recurringTaskReader = new RecurringTaskReader(m_file); } recurringTaskReader.processRecurringTask(task, recurringData); } // Retrieve the task notes. notes = taskVarData.getString (id, TASK_NOTES); if (notes != null) { if (m_reader.getPreserveNoteFormatting() == false) { notes = rtf.strip(notes); } task.setNotes(notes); } // Set the calendar name int calendarID = MPPUtility.getInt(data, 160); if (calendarID != -1) { ProjectCalendar calendar = m_file.getBaseCalendarByUniqueID(new Integer(calendarID)); if (calendar != null) { task.setCalendar(calendar); } } // Set the sub project flag SubProject sp = m_taskSubProjects.get(task.getUniqueID()); task.setSubProject(sp); // Set the external flag if (sp != null) { task.setExternalTask(sp.isExternalTask(task.getUniqueID())); if (task.getExternalTask()) { task.setExternalTaskProject(sp.getFullPath()); } } // If we have a WBS value from the MPP file, don't autogenerate if (task.getWBS() != null) { autoWBS = false; } // If this is a split task, allocate space for the split durations if ((metaData[9]&0x80) == 0) { task.setSplits(new LinkedList<Duration>()); } // Process any enterprise columns processTaskEnterpriseColumns(task, taskVarData); // Fire the task read event m_file.fireTaskReadEvent(task); //System.out.println(task); //dumpUnknownData (task.getName(), UNKNOWN_TASK_DATA, data); } // Enable auto WBS if necessary m_file.setAutoWBS(autoWBS); // We have now read all of the tasks, so we are in a position // to perform post-processing to set up the relevant details // for each external task. if (!externalTasks.isEmpty()) { processExternalTasks (externalTasks); } } /** * Extracts task enterprise column values. * * @param task task instance * @param taskVarData task var data */ private void processTaskEnterpriseColumns (Task task, Var2Data taskVarData) { byte[] data = taskVarData.getByteArray(task.getUniqueID(), TASK_ENTERPRISE_COLUMNS); if (data != null) { PropsBlock props = new PropsBlock (data); //System.out.println(props); for (Integer key : props.keySet()) { int keyValue = key.intValue() - MPPTaskField.TASK_FIELD_BASE; TaskField field = MPPTaskField.getInstance(keyValue); if (field != null) { Object value = null; switch (field.getDataType()) { case CURRENCY: { value = new Double (props.getDouble(key) / 100); break; } case DATE: { value = props.getTimestamp(key); break; } case DURATION: { byte[] durationData = props.getByteArray(key); switch (field.getValue()) { case TaskField.BASELINE1_WORK_VALUE: case TaskField.BASELINE2_WORK_VALUE: case TaskField.BASELINE3_WORK_VALUE: case TaskField.BASELINE4_WORK_VALUE: case TaskField.BASELINE5_WORK_VALUE: case TaskField.BASELINE6_WORK_VALUE: case TaskField.BASELINE7_WORK_VALUE: case TaskField.BASELINE8_WORK_VALUE: case TaskField.BASELINE9_WORK_VALUE: case TaskField.BASELINE10_WORK_VALUE: { double durationValueInHours = MPPUtility.getDouble(durationData)/60000; value = Duration.getInstance(durationValueInHours, TimeUnit.HOURS); break; } default: { double durationValueInHours = ((double)MPPUtility.getInt(durationData, 0)) / 600; TimeUnit durationUnits = MPPUtility.getDurationTimeUnits(MPPUtility.getInt(durationData, 4)); Duration duration = Duration.getInstance(durationValueInHours, TimeUnit.HOURS); value = duration.convertUnits(durationUnits, m_file.getProjectHeader()); break; } } break; } case BOOLEAN: { field = null; int bits = props.getInt(key); task.set(TaskField.ENTERPRISE_FLAG1, new Boolean((bits & 0x00002) != 0)); task.set(TaskField.ENTERPRISE_FLAG2, new Boolean((bits & 0x00004) != 0)); task.set(TaskField.ENTERPRISE_FLAG3, new Boolean((bits & 0x00008) != 0)); task.set(TaskField.ENTERPRISE_FLAG4, new Boolean((bits & 0x00010) != 0)); task.set(TaskField.ENTERPRISE_FLAG5, new Boolean((bits & 0x00020) != 0)); task.set(TaskField.ENTERPRISE_FLAG6, new Boolean((bits & 0x00040) != 0)); task.set(TaskField.ENTERPRISE_FLAG7, new Boolean((bits & 0x00080) != 0)); task.set(TaskField.ENTERPRISE_FLAG8, new Boolean((bits & 0x00100) != 0)); task.set(TaskField.ENTERPRISE_FLAG9, new Boolean((bits & 0x00200) != 0)); task.set(TaskField.ENTERPRISE_FLAG10, new Boolean((bits & 0x00400) != 0)); task.set(TaskField.ENTERPRISE_FLAG11, new Boolean((bits & 0x00800) != 0)); task.set(TaskField.ENTERPRISE_FLAG12, new Boolean((bits & 0x01000) != 0)); task.set(TaskField.ENTERPRISE_FLAG13, new Boolean((bits & 0x02000) != 0)); task.set(TaskField.ENTERPRISE_FLAG14, new Boolean((bits & 0x04000) != 0)); task.set(TaskField.ENTERPRISE_FLAG15, new Boolean((bits & 0x08000) != 0)); task.set(TaskField.ENTERPRISE_FLAG16, new Boolean((bits & 0x10000) != 0)); task.set(TaskField.ENTERPRISE_FLAG17, new Boolean((bits & 0x20000) != 0)); task.set(TaskField.ENTERPRISE_FLAG18, new Boolean((bits & 0x40000) != 0)); task.set(TaskField.ENTERPRISE_FLAG19, new Boolean((bits & 0x80000) != 0)); task.set(TaskField.ENTERPRISE_FLAG20, new Boolean((bits & 0x100000) != 0)); break; } case NUMERIC: { value = new Double(props.getDouble(key)); break; } case STRING: { value = props.getUnicodeString(key); break; } default: { break; } } task.set(field, value); } } } } /** * Extracts resource enterprise column data. * * @param resource resource instance * @param resourceVarData resource var data */ private void processResourceEnterpriseColumns (Resource resource, Var2Data resourceVarData) { byte[] data = resourceVarData.getByteArray(resource.getUniqueID(), RESOURCE_ENTERPRISE_COLUMNS); if (data != null) { PropsBlock props = new PropsBlock (data); //System.out.println(props); for (Integer key : props.keySet()) { int keyValue = key.intValue() - MPPResourceField.RESOURCE_FIELD_BASE; //System.out.println("Key=" + keyValue); ResourceField field = MPPResourceField.getInstance(keyValue); if (field != null) { Object value = null; switch (field.getDataType()) { case CURRENCY: { value = new Double (props.getDouble(key) / 100); break; } case DATE: { value = props.getTimestamp(key); break; } case DURATION: { byte[] durationData = props.getByteArray(key); double durationValueInHours = ((double)MPPUtility.getInt(durationData, 0)) / 600; TimeUnit durationUnits = MPPUtility.getDurationTimeUnits(MPPUtility.getInt(durationData, 4)); Duration duration = Duration.getInstance(durationValueInHours, TimeUnit.HOURS); value = duration.convertUnits(durationUnits, m_file.getProjectHeader()); break; } case BOOLEAN: { field = null; int bits = props.getInt(key); resource.set(ResourceField.ENTERPRISE_FLAG1, new Boolean((bits & 0x00002) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG2, new Boolean((bits & 0x00004) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG3, new Boolean((bits & 0x00008) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG4, new Boolean((bits & 0x00010) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG5, new Boolean((bits & 0x00020) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG6, new Boolean((bits & 0x00040) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG7, new Boolean((bits & 0x00080) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG8, new Boolean((bits & 0x00100) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG9, new Boolean((bits & 0x00200) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG10, new Boolean((bits & 0x00400) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG11, new Boolean((bits & 0x00800) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG12, new Boolean((bits & 0x01000) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG13, new Boolean((bits & 0x02000) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG14, new Boolean((bits & 0x04000) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG15, new Boolean((bits & 0x08000) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG16, new Boolean((bits & 0x10000) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG17, new Boolean((bits & 0x20000) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG18, new Boolean((bits & 0x40000) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG19, new Boolean((bits & 0x80000) != 0)); resource.set(ResourceField.ENTERPRISE_FLAG20, new Boolean((bits & 0x100000) != 0)); break; } case NUMERIC: { value = new Double(props.getDouble(key)); break; } case STRING: { value = props.getUnicodeString(key); break; } default: { break; } } resource.set(field, value); } } } } /** * The project files to which external tasks relate appear not to be * held against each task, instead there appears to be the concept * of the "current" external task file, i.e. the last one used. * This method iterates through the list of tasks marked as external * and attempts to ensure that the correct external project data (in the * form of a SubProject object) is linked to the task. * * @param externalTasks list of tasks marked as external */ private void processExternalTasks (List<Task> externalTasks) { // Sort the list of tasks into ID order Collections.sort(externalTasks); // Find any external tasks which don't have a sub project // object, and set this attribute using the most recent // value. SubProject currentSubProject = null; for(Task currentTask : externalTasks) { SubProject sp = currentTask.getSubProject(); if (sp == null) { currentTask.setSubProject(currentSubProject); } else { currentSubProject = sp; } if (currentSubProject != null) { //System.out.println ("Task: " +currentTask.getUniqueID() + " " + currentTask.getName() + " File=" + currentSubProject.getFullPath() + " ID=" + currentTask.getExternalTaskID()); currentTask.setProject(currentSubProject.getFullPath()); } } } /** * This method is used to extract the task hyperlink attributes * from a block of data and call the appropriate modifier methods * to configure the specified task object. * * @param task task instance * @param data hyperlink data block */ private void processHyperlinkData (Task task, byte[] data) { if (data != null) { int offset = 12; String hyperlink; String address; String subaddress; offset += 12; hyperlink = MPPUtility.getUnicodeString(data, offset); offset += ((hyperlink.length()+1) * 2); offset += 12; address = MPPUtility.getUnicodeString(data, offset); offset += ((address.length()+1) * 2); offset += 12; subaddress = MPPUtility.getUnicodeString(data, offset); task.setHyperlink(hyperlink); task.setHyperlinkAddress(address); task.setHyperlinkSubAddress(subaddress); } } /** * This method is used to extract the resource hyperlink attributes * from a block of data and call the appropriate modifier methods * to configure the specified task object. * * @param resource resource instance * @param data hyperlink data block */ private void processHyperlinkData (Resource resource, byte[] data) { if (data != null) { int offset = 12; String hyperlink; String address; String subaddress; offset += 12; hyperlink = MPPUtility.getUnicodeString(data, offset); offset += ((hyperlink.length()+1) * 2); offset += 12; address = MPPUtility.getUnicodeString(data, offset); offset += ((address.length()+1) * 2); offset += 12; subaddress = MPPUtility.getUnicodeString(data, offset); resource.setHyperlink(hyperlink); resource.setHyperlinkAddress(address); resource.setHyperlinkSubAddress(subaddress); } } /** * This method extracts and collates constraint data. * * @throws IOException */ private void processConstraintData () throws IOException { DirectoryEntry consDir = (DirectoryEntry)m_projectDir.getEntry ("TBkndCons"); FixedMeta consFixedMeta = new FixedMeta (new DocumentInputStream (((DocumentEntry)consDir.getEntry("FixedMeta"))), 10); FixedData consFixedData = new FixedData (consFixedMeta, 20, getEncryptableInputStream(consDir, "FixedData")); int count = consFixedMeta.getItemCount(); int index; byte[] data; Task task1; Task task2; Relation rel; TimeUnit durationUnits; int constraintID; int lastConstraintID = -1; byte[] metaData; for (int loop=0; loop < count; loop++) { metaData = consFixedMeta.getByteArrayValue(loop); if (MPPUtility.getInt(metaData, 0) == 0) { index = consFixedData.getIndexFromOffset(MPPUtility.getInt(metaData, 4)); if (index != -1) { data = consFixedData.getByteArrayValue(index); constraintID = MPPUtility.getInt (data, 0); if (constraintID > lastConstraintID) { lastConstraintID = constraintID; int taskID1 = MPPUtility.getInt (data, 4); int taskID2 = MPPUtility.getInt (data, 8); if (taskID1 != taskID2) { task1 = m_file.getTaskByUniqueID (new Integer(taskID1)); task2 = m_file.getTaskByUniqueID (new Integer(taskID2)); if (task1 != null && task2 != null) { rel = task2.addPredecessor(task1); rel.setType (RelationType.getInstance(MPPUtility.getShort(data, 12))); durationUnits = MPPUtility.getDurationTimeUnits(MPPUtility.getShort (data, 14)); rel.setDuration(MPPUtility.getAdjustedDuration(m_file, MPPUtility.getInt (data, 16), durationUnits)); } } } } } } } /** * This method extracts and collates resource data. * * @throws IOException */ private void processResourceData () throws IOException { DirectoryEntry rscDir = (DirectoryEntry)m_projectDir.getEntry ("TBkndRsc"); VarMeta rscVarMeta = new VarMeta9 (new DocumentInputStream (((DocumentEntry)rscDir.getEntry("VarMeta")))); Var2Data rscVarData = new Var2Data (rscVarMeta, new DocumentInputStream (((DocumentEntry)rscDir.getEntry("Var2Data")))); FixedMeta rscFixedMeta = new FixedMeta (new DocumentInputStream (((DocumentEntry)rscDir.getEntry("FixedMeta"))), 37); FixedData rscFixedData = new FixedData (rscFixedMeta, getEncryptableInputStream(rscDir, "FixedData")); //System.out.println(rscVarMeta); //System.out.println(rscVarData); //System.out.println(rscFixedMeta); //System.out.println(rscFixedData); TreeMap<Integer, Integer> resourceMap = createResourceMap (rscFixedMeta, rscFixedData); Integer[] uniqueid = rscVarMeta.getUniqueIdentifierArray(); Integer id; Integer offset; byte[] data; byte[] metaData; Resource resource; RTFUtility rtf = new RTFUtility (); String notes; for (int loop=0; loop < uniqueid.length; loop++) { id = uniqueid[loop]; offset = resourceMap.get(id); if (rscFixedData.isValidOffset(offset) == false) { continue; } data = rscFixedData.getByteArrayValue(offset.intValue()); if (data.length < MINIMUM_EXPECTED_RESOURCE_SIZE) { continue; } //MPPUtility.dataDump(data, true, true, true, true, true, true, true); //MPPUtility.varDataDump(rscVarData, id, true, true, true, true, true, true); resource = m_file.addResource(); resource.setAccrueAt(AccrueType.getInstance (MPPUtility.getShort (data, 12))); resource.setActualCost(NumberUtility.getDouble(MPPUtility.getDouble(data, 132)/100)); resource.setActualOvertimeCost(NumberUtility.getDouble(MPPUtility.getDouble(data, 172)/100)); resource.setActualOvertimeWork(Duration.getInstance (MPPUtility.getDouble (data, 108)/60000, TimeUnit.HOURS)); resource.setActualWork(Duration.getInstance (MPPUtility.getDouble (data, 60)/60000, TimeUnit.HOURS)); resource.setAvailableFrom(MPPUtility.getTimestamp(data, 20)); resource.setAvailableTo(MPPUtility.getTimestamp(data, 24)); //resource.setBaseCalendar(); resource.setBaselineCost(1, NumberUtility.getDouble(rscVarData.getDouble (id, RESOURCE_BASELINE1_COST) / 100)); resource.setBaselineCost(2, NumberUtility.getDouble(rscVarData.getDouble (id, RESOURCE_BASELINE2_COST) / 100)); resource.setBaselineCost(3, NumberUtility.getDouble(rscVarData.getDouble (id, RESOURCE_BASELINE3_COST) / 100)); resource.setBaselineCost(4, NumberUtility.getDouble(rscVarData.getDouble (id, RESOURCE_BASELINE4_COST) / 100)); resource.setBaselineCost(5, NumberUtility.getDouble(rscVarData.getDouble (id, RESOURCE_BASELINE5_COST) / 100)); resource.setBaselineCost(6, NumberUtility.getDouble(rscVarData.getDouble (id, RESOURCE_BASELINE6_COST) / 100)); resource.setBaselineCost(7, NumberUtility.getDouble(rscVarData.getDouble (id, RESOURCE_BASELINE7_COST) / 100)); resource.setBaselineCost(8, NumberUtility.getDouble(rscVarData.getDouble (id, RESOURCE_BASELINE8_COST) / 100)); resource.setBaselineCost(9, NumberUtility.getDouble(rscVarData.getDouble (id, RESOURCE_BASELINE9_COST) / 100)); resource.setBaselineCost(10, NumberUtility.getDouble(rscVarData.getDouble (id, RESOURCE_BASELINE10_COST) / 100)); resource.setBaselineWork(1, Duration.getInstance (rscVarData.getDouble (id, RESOURCE_BASELINE1_WORK)/60000, TimeUnit.HOURS)); resource.setBaselineWork(2, Duration.getInstance (rscVarData.getDouble (id, RESOURCE_BASELINE2_WORK)/60000, TimeUnit.HOURS)); resource.setBaselineWork(3, Duration.getInstance (rscVarData.getDouble (id, RESOURCE_BASELINE3_WORK)/60000, TimeUnit.HOURS)); resource.setBaselineWork(4, Duration.getInstance (rscVarData.getDouble (id, RESOURCE_BASELINE4_WORK)/60000, TimeUnit.HOURS)); resource.setBaselineWork(5, Duration.getInstance (rscVarData.getDouble (id, RESOURCE_BASELINE5_WORK)/60000, TimeUnit.HOURS)); resource.setBaselineWork(6, Duration.getInstance (rscVarData.getDouble (id, RESOURCE_BASELINE6_WORK)/60000, TimeUnit.HOURS)); resource.setBaselineWork(7, Duration.getInstance (rscVarData.getDouble (id, RESOURCE_BASELINE7_WORK)/60000, TimeUnit.HOURS)); resource.setBaselineWork(8, Duration.getInstance (rscVarData.getDouble (id, RESOURCE_BASELINE8_WORK)/60000, TimeUnit.HOURS)); resource.setBaselineWork(9, Duration.getInstance (rscVarData.getDouble (id, RESOURCE_BASELINE9_WORK)/60000, TimeUnit.HOURS)); resource.setBaselineWork(10, Duration.getInstance (rscVarData.getDouble (id, RESOURCE_BASELINE10_WORK)/60000, TimeUnit.HOURS)); resource.setBaselineCost(NumberUtility.getDouble(MPPUtility.getDouble(data, 148)/100)); resource.setBaselineWork(Duration.getInstance (MPPUtility.getDouble (data, 68)/60000, TimeUnit.HOURS)); resource.setCode (rscVarData.getUnicodeString (id, RESOURCE_CODE)); resource.setCost(NumberUtility.getDouble(MPPUtility.getDouble(data, 140)/100)); resource.setCost1(NumberUtility.getDouble (rscVarData.getDouble (id, RESOURCE_COST1) / 100)); resource.setCost2(NumberUtility.getDouble (rscVarData.getDouble (id, RESOURCE_COST2) / 100)); resource.setCost3(NumberUtility.getDouble (rscVarData.getDouble (id, RESOURCE_COST3) / 100)); resource.setCost4(NumberUtility.getDouble (rscVarData.getDouble (id, RESOURCE_COST4) / 100)); resource.setCost5(NumberUtility.getDouble (rscVarData.getDouble (id, RESOURCE_COST5) / 100)); resource.setCost6(NumberUtility.getDouble (rscVarData.getDouble (id, RESOURCE_COST6) / 100)); resource.setCost7(NumberUtility.getDouble (rscVarData.getDouble (id, RESOURCE_COST7) / 100)); resource.setCost8(NumberUtility.getDouble (rscVarData.getDouble (id, RESOURCE_COST8) / 100)); resource.setCost9(NumberUtility.getDouble (rscVarData.getDouble (id, RESOURCE_COST9) / 100)); resource.setCost10(NumberUtility.getDouble (rscVarData.getDouble (id, RESOURCE_COST10) / 100)); resource.setCostPerUse(NumberUtility.getDouble(MPPUtility.getDouble(data, 84)/100)); resource.setDate1(rscVarData.getTimestamp (id, RESOURCE_DATE1)); resource.setDate2(rscVarData.getTimestamp (id, RESOURCE_DATE2)); resource.setDate3(rscVarData.getTimestamp (id, RESOURCE_DATE3)); resource.setDate4(rscVarData.getTimestamp (id, RESOURCE_DATE4)); resource.setDate5(rscVarData.getTimestamp (id, RESOURCE_DATE5)); resource.setDate6(rscVarData.getTimestamp (id, RESOURCE_DATE6)); resource.setDate7(rscVarData.getTimestamp (id, RESOURCE_DATE7)); resource.setDate8(rscVarData.getTimestamp (id, RESOURCE_DATE8)); resource.setDate9(rscVarData.getTimestamp (id, RESOURCE_DATE9)); resource.setDate10(rscVarData.getTimestamp (id, RESOURCE_DATE10)); resource.setDuration1(MPPUtility.getDuration (rscVarData.getInt(id, RESOURCE_DURATION1), MPPUtility.getDurationTimeUnits(rscVarData.getShort(id, RESOURCE_DURATION1_UNITS)))); resource.setDuration2(MPPUtility.getDuration (rscVarData.getInt(id, RESOURCE_DURATION2), MPPUtility.getDurationTimeUnits(rscVarData.getShort(id, RESOURCE_DURATION2_UNITS)))); resource.setDuration3(MPPUtility.getDuration (rscVarData.getInt(id, RESOURCE_DURATION3), MPPUtility.getDurationTimeUnits(rscVarData.getShort(id, RESOURCE_DURATION3_UNITS)))); resource.setDuration4(MPPUtility.getDuration (rscVarData.getInt(id, RESOURCE_DURATION4), MPPUtility.getDurationTimeUnits(rscVarData.getShort(id, RESOURCE_DURATION4_UNITS)))); resource.setDuration5(MPPUtility.getDuration (rscVarData.getInt(id, RESOURCE_DURATION5), MPPUtility.getDurationTimeUnits(rscVarData.getShort(id, RESOURCE_DURATION5_UNITS)))); resource.setDuration6(MPPUtility.getDuration (rscVarData.getInt(id, RESOURCE_DURATION6), MPPUtility.getDurationTimeUnits(rscVarData.getShort(id, RESOURCE_DURATION6_UNITS)))); resource.setDuration7(MPPUtility.getDuration (rscVarData.getInt(id, RESOURCE_DURATION7), MPPUtility.getDurationTimeUnits(rscVarData.getShort(id, RESOURCE_DURATION7_UNITS)))); resource.setDuration8(MPPUtility.getDuration (rscVarData.getInt(id, RESOURCE_DURATION8), MPPUtility.getDurationTimeUnits(rscVarData.getShort(id, RESOURCE_DURATION8_UNITS)))); resource.setDuration9(MPPUtility.getDuration (rscVarData.getInt(id, RESOURCE_DURATION9), MPPUtility.getDurationTimeUnits(rscVarData.getShort(id, RESOURCE_DURATION9_UNITS)))); resource.setDuration10(MPPUtility.getDuration (rscVarData.getInt(id, RESOURCE_DURATION10), MPPUtility.getDurationTimeUnits(rscVarData.getShort(id, RESOURCE_DURATION10_UNITS)))); resource.setEmailAddress(rscVarData.getUnicodeString (id, RESOURCE_EMAIL)); resource.setFinish1(rscVarData.getTimestamp (id, RESOURCE_FINISH1)); resource.setFinish2(rscVarData.getTimestamp (id, RESOURCE_FINISH2)); resource.setFinish3(rscVarData.getTimestamp (id, RESOURCE_FINISH3)); resource.setFinish4(rscVarData.getTimestamp (id, RESOURCE_FINISH4)); resource.setFinish5(rscVarData.getTimestamp (id, RESOURCE_FINISH5)); resource.setFinish6(rscVarData.getTimestamp (id, RESOURCE_FINISH6)); resource.setFinish7(rscVarData.getTimestamp (id, RESOURCE_FINISH7)); resource.setFinish8(rscVarData.getTimestamp (id, RESOURCE_FINISH8)); resource.setFinish9(rscVarData.getTimestamp (id, RESOURCE_FINISH9)); resource.setFinish10(rscVarData.getTimestamp (id, RESOURCE_FINISH10)); resource.setGroup(rscVarData.getUnicodeString (id, RESOURCE_GROUP)); processHyperlinkData (resource, rscVarData.getByteArray(id, RESOURCE_HYPERLINK)); resource.setID (new Integer(MPPUtility.getInt (data, 4))); resource.setInitials (rscVarData.getUnicodeString (id, RESOURCE_INITIALS)); //resource.setLinkedFields(); // Calculated value resource.setMaterialLabel(rscVarData.getUnicodeString(id, RESOURCE_MATERIAL_LABEL)); resource.setMaxUnits(NumberUtility.getDouble(MPPUtility.getDouble(data, 44)/100)); resource.setName (rscVarData.getUnicodeString (id, RESOURCE_NAME)); resource.setNtAccount(rscVarData.getUnicodeString (id, RESOURCE_NT_ACCOUNT)); resource.setNumber1(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER1))); resource.setNumber2(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER2))); resource.setNumber3(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER3))); resource.setNumber4(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER4))); resource.setNumber5(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER5))); resource.setNumber6(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER6))); resource.setNumber7(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER7))); resource.setNumber8(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER8))); resource.setNumber9(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER9))); resource.setNumber10(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER10))); resource.setNumber11(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER11))); resource.setNumber12(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER12))); resource.setNumber13(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER13))); resource.setNumber14(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER14))); resource.setNumber15(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER15))); resource.setNumber16(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER16))); resource.setNumber17(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER17))); resource.setNumber18(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER18))); resource.setNumber19(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER19))); resource.setNumber20(NumberUtility.getDouble (rscVarData.getDouble(id, RESOURCE_NUMBER20))); //resource.setObjects(); // Calculated value resource.setOutlineCode1(m_outlineCodeVarData.getUnicodeString(new Integer(rscVarData.getInt (id, RESOURCE_OUTLINECODE1)), OUTLINECODE_DATA)); resource.setOutlineCode2(m_outlineCodeVarData.getUnicodeString(new Integer(rscVarData.getInt (id, RESOURCE_OUTLINECODE2)), OUTLINECODE_DATA)); resource.setOutlineCode3(m_outlineCodeVarData.getUnicodeString(new Integer(rscVarData.getInt (id, RESOURCE_OUTLINECODE3)), OUTLINECODE_DATA)); resource.setOutlineCode4(m_outlineCodeVarData.getUnicodeString(new Integer(rscVarData.getInt (id, RESOURCE_OUTLINECODE4)), OUTLINECODE_DATA)); resource.setOutlineCode5(m_outlineCodeVarData.getUnicodeString(new Integer(rscVarData.getInt (id, RESOURCE_OUTLINECODE5)), OUTLINECODE_DATA)); resource.setOutlineCode6(m_outlineCodeVarData.getUnicodeString(new Integer(rscVarData.getInt (id, RESOURCE_OUTLINECODE6)), OUTLINECODE_DATA)); resource.setOutlineCode7(m_outlineCodeVarData.getUnicodeString(new Integer(rscVarData.getInt (id, RESOURCE_OUTLINECODE7)), OUTLINECODE_DATA)); resource.setOutlineCode8(m_outlineCodeVarData.getUnicodeString(new Integer(rscVarData.getInt (id, RESOURCE_OUTLINECODE8)), OUTLINECODE_DATA)); resource.setOutlineCode9(m_outlineCodeVarData.getUnicodeString(new Integer(rscVarData.getInt (id, RESOURCE_OUTLINECODE9)), OUTLINECODE_DATA)); resource.setOutlineCode10(m_outlineCodeVarData.getUnicodeString(new Integer(rscVarData.getInt (id, RESOURCE_OUTLINECODE10)), OUTLINECODE_DATA)); //resource.setOverallocated(); // Calculated value resource.setOvertimeCost(NumberUtility.getDouble(MPPUtility.getDouble(data, 164)/100)); resource.setOvertimeRate(new Rate (MPPUtility.getDouble(data, 36), TimeUnit.HOURS)); resource.setOvertimeWork(Duration.getInstance (MPPUtility.getDouble (data, 76)/60000, TimeUnit.HOURS)); resource.setPeakUnits(NumberUtility.getDouble(MPPUtility.getDouble(data, 124)/100)); //resource.setPercentageWorkComplete(); // Calculated value resource.setRegularWork(Duration.getInstance (MPPUtility.getDouble (data, 100)/60000, TimeUnit.HOURS)); resource.setRemainingCost(NumberUtility.getDouble(MPPUtility.getDouble(data, 156)/100)); resource.setRemainingOvertimeCost(NumberUtility.getDouble(MPPUtility.getDouble(data, 180)/100)); resource.setRemainingWork(Duration.getInstance (MPPUtility.getDouble (data, 92)/60000, TimeUnit.HOURS)); resource.setStandardRate(new Rate (MPPUtility.getDouble(data, 28), TimeUnit.HOURS)); resource.setStart1(rscVarData.getTimestamp (id, RESOURCE_START1)); resource.setStart2(rscVarData.getTimestamp (id, RESOURCE_START2)); resource.setStart3(rscVarData.getTimestamp (id, RESOURCE_START3)); resource.setStart4(rscVarData.getTimestamp (id, RESOURCE_START4)); resource.setStart5(rscVarData.getTimestamp (id, RESOURCE_START5)); resource.setStart6(rscVarData.getTimestamp (id, RESOURCE_START6)); resource.setStart7(rscVarData.getTimestamp (id, RESOURCE_START7)); resource.setStart8(rscVarData.getTimestamp (id, RESOURCE_START8)); resource.setStart9(rscVarData.getTimestamp (id, RESOURCE_START9)); resource.setStart10(rscVarData.getTimestamp (id, RESOURCE_START10)); resource.setSubprojectResourceUniqueID(new Integer (rscVarData.getInt(id, RESOURCE_SUBPROJECTRESOURCEID))); resource.setText1(rscVarData.getUnicodeString (id, RESOURCE_TEXT1)); resource.setText2(rscVarData.getUnicodeString (id, RESOURCE_TEXT2)); resource.setText3(rscVarData.getUnicodeString (id, RESOURCE_TEXT3)); resource.setText4(rscVarData.getUnicodeString (id, RESOURCE_TEXT4)); resource.setText5(rscVarData.getUnicodeString (id, RESOURCE_TEXT5)); resource.setText6(rscVarData.getUnicodeString (id, RESOURCE_TEXT6)); resource.setText7(rscVarData.getUnicodeString (id, RESOURCE_TEXT7)); resource.setText8(rscVarData.getUnicodeString (id, RESOURCE_TEXT8)); resource.setText9(rscVarData.getUnicodeString (id, RESOURCE_TEXT9)); resource.setText10(rscVarData.getUnicodeString (id, RESOURCE_TEXT10)); resource.setText11(rscVarData.getUnicodeString (id, RESOURCE_TEXT11)); resource.setText12(rscVarData.getUnicodeString (id, RESOURCE_TEXT12)); resource.setText13(rscVarData.getUnicodeString (id, RESOURCE_TEXT13)); resource.setText14(rscVarData.getUnicodeString (id, RESOURCE_TEXT14)); resource.setText15(rscVarData.getUnicodeString (id, RESOURCE_TEXT15)); resource.setText16(rscVarData.getUnicodeString (id, RESOURCE_TEXT16)); resource.setText17(rscVarData.getUnicodeString (id, RESOURCE_TEXT17)); resource.setText18(rscVarData.getUnicodeString (id, RESOURCE_TEXT18)); resource.setText19(rscVarData.getUnicodeString (id, RESOURCE_TEXT19)); resource.setText20(rscVarData.getUnicodeString (id, RESOURCE_TEXT20)); resource.setText21(rscVarData.getUnicodeString (id, RESOURCE_TEXT21)); resource.setText22(rscVarData.getUnicodeString (id, RESOURCE_TEXT22)); resource.setText23(rscVarData.getUnicodeString (id, RESOURCE_TEXT23)); resource.setText24(rscVarData.getUnicodeString (id, RESOURCE_TEXT24)); resource.setText25(rscVarData.getUnicodeString (id, RESOURCE_TEXT25)); resource.setText26(rscVarData.getUnicodeString (id, RESOURCE_TEXT26)); resource.setText27(rscVarData.getUnicodeString (id, RESOURCE_TEXT27)); resource.setText28(rscVarData.getUnicodeString (id, RESOURCE_TEXT28)); resource.setText29(rscVarData.getUnicodeString (id, RESOURCE_TEXT29)); resource.setText30(rscVarData.getUnicodeString (id, RESOURCE_TEXT30)); resource.setType((MPPUtility.getShort(data, 14)==0?ResourceType.WORK:ResourceType.MATERIAL)); resource.setUniqueID(id); resource.setWork(Duration.getInstance (MPPUtility.getDouble (data, 52)/60000, TimeUnit.HOURS)); metaData = rscFixedMeta.getByteArrayValue(offset.intValue()); resource.setFlag1((metaData[28] & 0x40) != 0); resource.setFlag2((metaData[28] & 0x80) != 0); resource.setFlag3((metaData[29] & 0x01) != 0); resource.setFlag4((metaData[29] & 0x02) != 0); resource.setFlag5((metaData[29] & 0x04) != 0); resource.setFlag6((metaData[29] & 0x08) != 0); resource.setFlag7((metaData[29] & 0x10) != 0); resource.setFlag8((metaData[29] & 0x20) != 0); resource.setFlag9((metaData[29] & 0x40) != 0); resource.setFlag10((metaData[28] & 0x20) != 0); resource.setFlag11((metaData[29] & 0x20) != 0); resource.setFlag12((metaData[30] & 0x01) != 0); resource.setFlag13((metaData[30] & 0x02) != 0); resource.setFlag14((metaData[30] & 0x04) != 0); resource.setFlag15((metaData[30] & 0x08) != 0); resource.setFlag16((metaData[30] & 0x10) != 0); resource.setFlag17((metaData[30] & 0x20) != 0); resource.setFlag18((metaData[30] & 0x40) != 0); resource.setFlag19((metaData[30] & 0x80) != 0); resource.setFlag20((metaData[31] & 0x01) != 0); notes = rscVarData.getString (id, RESOURCE_NOTES); if (notes != null) { if (m_reader.getPreserveNoteFormatting() == false) { notes = rtf.strip(notes); } resource.setNotes(notes); } // Configure the resource calendar resource.setResourceCalendar(m_resourceMap.get(id)); // Process any enterprise columns processResourceEnterpriseColumns(resource, rscVarData); m_file.fireResourceReadEvent(resource); } } /** * This method extracts and collates resource assignment data. * * @throws IOException */ private void processAssignmentData () throws IOException { DirectoryEntry assnDir = (DirectoryEntry)m_projectDir.getEntry ("TBkndAssn"); VarMeta assnVarMeta = new VarMeta9 (new DocumentInputStream (((DocumentEntry)assnDir.getEntry("VarMeta")))); Var2Data assnVarData = new Var2Data (assnVarMeta, new DocumentInputStream (((DocumentEntry)assnDir.getEntry("Var2Data")))); FixedMeta assnFixedMeta = new FixedMeta (new DocumentInputStream (((DocumentEntry)assnDir.getEntry("FixedMeta"))), 34); FixedData assnFixedData = new FixedData (142, getEncryptableInputStream(assnDir, "FixedData")); Set<Integer> set = assnVarMeta.getUniqueIdentifierSet(); int count = assnFixedMeta.getItemCount(); for (int loop=0; loop < count; loop++) { byte[] meta = assnFixedMeta.getByteArrayValue(loop); if (meta[0] != 0) { continue; } int offset = MPPUtility.getInt(meta, 4); byte[] data = assnFixedData.getByteArrayValue(assnFixedData.getIndexFromOffset(offset)); if (data == null) { continue; } int id = MPPUtility.getInt(data, 0); final Integer varDataId = new Integer(id); if (set.contains(varDataId) == false) { continue; } Integer taskID = new Integer(MPPUtility.getInt (data, 4)); Task task = m_file.getTaskByUniqueID (taskID); if (task != null) { byte[] incompleteWork = assnVarData.getByteArray(assnVarMeta.getOffset(varDataId, INCOMPLETE_WORK)); if (task.getSplits() != null && task.getSplits().isEmpty()) { byte[] completeWork = assnVarData.getByteArray(assnVarMeta.getOffset(varDataId, COMPLETE_WORK)); processSplitData(task, completeWork, incompleteWork); } Integer resourceID = new Integer(MPPUtility.getInt (data, 8)); Resource resource = m_file.getResourceByUniqueID (resourceID); if (resource != null) { ResourceAssignment assignment = task.addResourceAssignment (resource); assignment.setActualCost(NumberUtility.getDouble (MPPUtility.getDouble(data, 110)/100)); assignment.setActualWork(MPPUtility.getDuration((MPPUtility.getDouble(data, 70))/100, TimeUnit.HOURS)); assignment.setCost(NumberUtility.getDouble (MPPUtility.getDouble(data, 102)/100)); assignment.setDelay(MPPUtility.getDuration(MPPUtility.getShort(data, 24), TimeUnit.HOURS)); assignment.setFinish(MPPUtility.getTimestamp(data, 16)); //assignment.setOvertimeWork(); // Can't find in data block //assignment.setPlannedCost(); // Not sure what this field maps on to in MSP //assignment.setPlannedWork(); // Not sure what this field maps on to in MSP assignment.setRemainingWork(MPPUtility.getDuration((MPPUtility.getDouble(data, 86))/100, TimeUnit.HOURS)); assignment.setStart(MPPUtility.getTimestamp(data, 12)); assignment.setUnits(new Double((MPPUtility.getDouble(data, 54))/100)); assignment.setWork(MPPUtility.getDuration((MPPUtility.getDouble(data, 62))/100, TimeUnit.HOURS)); if (incompleteWork != null) { assignment.setWorkContour(WorkContour.getInstance(MPPUtility.getShort(incompleteWork, 28))); } } } } } /** * The task split data is represented in two blocks of data, one representing * the completed time, and the other representing the incomplete time. * * The completed task split data is stored in a block with a 32 byte header, * followed by 20 byte blocks, each representing one split. The first two * bytes of the header contains a count of the number of 20 byte blocks. * * The incomplete task split data is represented as a 44 byte header * (which also contains unrelated assignment information, such as the * work contour) followed by a list of 28 byte blocks, each block representing * one split. The first two bytes of the header contains a count of the * number of 28 byte blocks. * * @param task parent task * @param completeHours completed split data * @param incompleteHours incomplete split data */ private void processSplitData (Task task, byte[] completeHours, byte[] incompleteHours) { //System.out.println (MPPUtility.hexdump(completeHours, false, 16, "")); //MPPUtility.dataDump(completeHours, false, true, false, false, false, false, false); //System.out.println (MPPUtility.hexdump(incompleteHours, false, 16, "")); //MPPUtility.dataDump(incompleteHours, false, true, false, false, false, false, false); LinkedList<Duration> splits = new LinkedList<Duration> (); Duration splitsComplete = null; if (completeHours != null) { int splitCount = MPPUtility.getShort(completeHours, 0); if (splitCount != 0) { int offset = 32; for (int loop=0; loop < splitCount; loop++) { double splitTime = MPPUtility.getInt(completeHours, offset); if (splitTime != 0) { splitTime /= 4800; Duration splitDuration = Duration.getInstance(splitTime, TimeUnit.HOURS); splits.add(splitDuration); } offset += 20; } double splitTime = MPPUtility.getInt(completeHours, 24); splitTime /= 4800; Duration splitDuration = Duration.getInstance(splitTime, TimeUnit.HOURS); splits.add(splitDuration); } } if (incompleteHours != null) { int splitCount = MPPUtility.getShort(incompleteHours, 0); // Deal with the case where the final task split is partially complete if (splitCount == 0) { double splitTime = MPPUtility.getInt(incompleteHours, 24); splitTime /= 4800; double timeOffset = 0; if (splits.isEmpty() == false) { timeOffset = splits.removeLast().getDuration(); } splitTime += timeOffset; Duration splitDuration = Duration.getInstance(splitTime, TimeUnit.HOURS); splits.add(splitDuration); } else { double timeOffset = 0; if (splits.isEmpty() == false) { if (splitCount % 2 != 0 || splits.size() % 2 == 0) { timeOffset = splits.removeLast().getDuration(); } else { timeOffset = splits.getLast().getDuration(); } } // Store the time up to which the splits are completed. splitsComplete = Duration.getInstance(timeOffset, TimeUnit.HOURS); int offset = 44; for (int loop=0; loop < splitCount; loop++) { double splitTime = MPPUtility.getInt(incompleteHours, offset+24); splitTime /= 4800; splitTime += timeOffset; Duration splitDuration = Duration.getInstance(splitTime, TimeUnit.HOURS); splits.add(splitDuration); offset += 28; } } } // We must have a minimum of 3 entries for this to be a valid split task if (splits.size() > 2) { task.getSplits().addAll(splits); task.setSplitCompleteDuration(splitsComplete); } else { task.setSplits(null); task.setSplitCompleteDuration(null); } } /** * This method is used to determine if a duration is estimated. * * @param type Duration units value * @return boolean Estimated flag */ private boolean getDurationEstimated (int type) { return ((type & DURATION_CONFIRMED_MASK) != 0); } /** * This method extracts view data from the MPP file. * * @throws IOException */ private void processViewData () throws IOException { DirectoryEntry dir = (DirectoryEntry)m_viewDir.getEntry ("CV_iew"); VarMeta viewVarMeta = new VarMeta9 (new DocumentInputStream (((DocumentEntry)dir.getEntry("VarMeta")))); Var2Data viewVarData = new Var2Data (viewVarMeta, new DocumentInputStream (((DocumentEntry)dir.getEntry("Var2Data")))); FixedMeta fixedMeta = new FixedMeta (new DocumentInputStream (((DocumentEntry)dir.getEntry("FixedMeta"))), 10); FixedData fixedData = new FixedData (122, getEncryptableInputStream(dir, "FixedData")); int items = fixedMeta.getItemCount(); View view; ViewFactory factory = new ViewFactory9 (); int lastOffset = -1; for (int loop=0; loop < items; loop++) { byte[] fm = fixedMeta.getByteArrayValue(loop); int offset = MPPUtility.getShort(fm, 4); if (offset > lastOffset) { byte[] fd = fixedData.getByteArrayValue(fixedData.getIndexFromOffset(offset)); if (fd != null) { view = factory.createView(m_file, fm, fd, viewVarData, m_fontBases); m_file.addView(view); //System.out.print(view); } lastOffset = offset; } } } /** * This method extracts table data from the MPP file. * * @throws IOException */ private void processTableData () throws IOException { DirectoryEntry dir = (DirectoryEntry)m_viewDir.getEntry ("CTable"); FixedData fixedData = new FixedData (110, getEncryptableInputStream(dir, "FixedData")); VarMeta varMeta = new VarMeta9 (new DocumentInputStream (((DocumentEntry)dir.getEntry("VarMeta")))); Var2Data varData = new Var2Data (varMeta, new DocumentInputStream (((DocumentEntry)dir.getEntry("Var2Data")))); TableFactory factory = new TableFactory(TABLE_COLUMN_DATA_STANDARD, TABLE_COLUMN_DATA_ENTERPRISE, TABLE_COLUMN_DATA_BASELINE); int items = fixedData.getItemCount(); for (int loop=0; loop < items; loop++) { byte[] data = fixedData.getByteArrayValue(loop); Table table = factory.createTable(m_file, data, varMeta, varData); m_file.addTable(table); //System.out.println(table); } } /** * Read filter definitions. * * @throws IOException */ private void processFilterData () throws IOException { DirectoryEntry dir = (DirectoryEntry)m_viewDir.getEntry ("CFilter"); FixedData fixedData = new FixedData (110, getEncryptableInputStream(dir, "FixedData"), true); VarMeta varMeta = new VarMeta9 (new DocumentInputStream (((DocumentEntry)dir.getEntry("VarMeta")))); Var2Data varData = new Var2Data (varMeta, new DocumentInputStream (((DocumentEntry)dir.getEntry("Var2Data")))); //System.out.println(fixedMeta); //System.out.println(fixedData); //System.out.println(varMeta); //System.out.println(varData); FilterReader reader = new FilterReader9(); reader.process(m_file, fixedData, varData); } /** * Read group definitions. * * @throws IOException */ private void processGroupData () throws IOException { DirectoryEntry dir = (DirectoryEntry)m_viewDir.getEntry ("CGrouping"); FixedData fixedData = new FixedData (110, getEncryptableInputStream(dir, "FixedData")); VarMeta varMeta = new VarMeta9 (new DocumentInputStream (((DocumentEntry)dir.getEntry("VarMeta")))); Var2Data varData = new Var2Data (varMeta, new DocumentInputStream (((DocumentEntry)dir.getEntry("Var2Data")))); // System.out.println(fixedMeta); // System.out.println(fixedData); // System.out.println(varMeta); // System.out.println(varData); GroupReader reader = new GroupReader9(); reader.process(m_file, fixedData, varData, m_fontBases); } /** * Read saved view state from an MPP file. * * @throws IOException */ private void processSavedViewState () throws IOException { DirectoryEntry dir = (DirectoryEntry)m_viewDir.getEntry ("CEdl"); VarMeta varMeta = new VarMeta9 (new DocumentInputStream (((DocumentEntry)dir.getEntry("VarMeta")))); Var2Data varData = new Var2Data (varMeta, new DocumentInputStream (((DocumentEntry)dir.getEntry("Var2Data")))); //System.out.println(varMeta); //System.out.println(varData); ViewStateReader reader = new ViewStateReader9(); reader.process(m_file, varData); } /** * Method used to instantiate the appropriate input stream reader, * a standard one, or one which can deal with "encrypted" data. * * @param directory directory entry * @param name file name * @return new input stream * @throws IOException */ private InputStream getEncryptableInputStream (DirectoryEntry directory, String name) throws IOException { DocumentEntry entry = (DocumentEntry)directory.getEntry(name); InputStream stream; if (m_file.getEncoded()) { stream = new EncryptedDocumentInputStream(entry); // Set the encryption mask ((EncryptedDocumentInputStream)stream).setMask(m_file.getEncryptionCode()); } else { stream = new DocumentInputStream (entry); } return (stream); } // private static void dumpUnknownData (String name, int[][] spec, byte[] data) // System.out.println (name); // for (int loop=0; loop < spec.length; loop++) // System.out.println (spec[loop][0] + ": "+ MPPUtility.hexdump(data, spec[loop][0], spec[loop][1], false)); // System.out.println (); // private static final int[][] UNKNOWN_TASK_DATA = new int[][] // {36, 4}, // {42, 18}, // {116, 4}, // {134, 14}, // {144, 4}, // {148, 4}, // {152, 4}, // {156, 4}, // {248, 8}, // private static final int[][] UNKNOWN_RESOURCE_DATA = new int[][] // {14, 6}, // {108, 16}, private MPPReader m_reader; private ProjectFile m_file; private DirectoryEntry m_root; private HashMap<Integer, ProjectCalendar> m_resourceMap; private Var2Data m_outlineCodeVarData; private Map<Integer, FontBase> m_fontBases; private Map<Integer, SubProject> m_taskSubProjects; private DirectoryEntry m_projectDir; private DirectoryEntry m_viewDir; // Signals the end of the list of subproject task unique ids private static final int SUBPROJECT_LISTEND = 0x00000303; // Signals that the previous value was for the subproject task unique id // TODO: figure out why the different value exist. private static final int SUBPROJECT_TASKUNIQUEID0 = 0x00000000; private static final int SUBPROJECT_TASKUNIQUEID1 = 0x0B340000; private static final int SUBPROJECT_TASKUNIQUEID2 = 0x0ABB0000; private static final int SUBPROJECT_TASKUNIQUEID3 = 0x05A10000; /** * Calendar data types. */ private static final Integer CALENDAR_NAME = new Integer (1); private static final Integer CALENDAR_DATA = new Integer (3); /** * Task data types. */ private static final Integer TASK_ACTUAL_OVERTIME_WORK = new Integer (3); private static final Integer TASK_REMAINING_OVERTIME_WORK = new Integer (4); private static final Integer TASK_OVERTIME_COST = new Integer (5); private static final Integer TASK_ACTUAL_OVERTIME_COST = new Integer (6); private static final Integer TASK_REMAINING_OVERTIME_COST = new Integer (7); private static final Integer TASK_SUBPROJECT_TASKS_UNIQUEID_OFFSET = new Integer (8); private static final Integer TASK_SUBPROJECTUNIQUETASKID = new Integer (9); private static final Integer TASK_SUBPROJECTTASKID = new Integer (79); private static final Integer TASK_WBS = new Integer (10); private static final Integer TASK_NAME = new Integer (11); private static final Integer TASK_CONTACT = new Integer (12); private static final Integer TASK_TEXT1 = new Integer (14); private static final Integer TASK_TEXT2 = new Integer (15); private static final Integer TASK_TEXT3 = new Integer (16); private static final Integer TASK_TEXT4 = new Integer (17); private static final Integer TASK_TEXT5 = new Integer (18); private static final Integer TASK_TEXT6 = new Integer (19); private static final Integer TASK_TEXT7 = new Integer (20); private static final Integer TASK_TEXT8 = new Integer (21); private static final Integer TASK_TEXT9 = new Integer (22); private static final Integer TASK_TEXT10 = new Integer (23); private static final Integer TASK_START1 = new Integer (24); private static final Integer TASK_FINISH1 = new Integer (25); private static final Integer TASK_START2 = new Integer (26); private static final Integer TASK_FINISH2 = new Integer (27); private static final Integer TASK_START3 = new Integer (28); private static final Integer TASK_FINISH3 = new Integer (29); private static final Integer TASK_START4 = new Integer (30); private static final Integer TASK_FINISH4 = new Integer (31); private static final Integer TASK_START5 = new Integer (32); private static final Integer TASK_FINISH5 = new Integer (33); private static final Integer TASK_START6 = new Integer (34); private static final Integer TASK_FINISH6 = new Integer (35); private static final Integer TASK_START7 = new Integer (36); private static final Integer TASK_FINISH7 = new Integer (37); private static final Integer TASK_START8 = new Integer (38); private static final Integer TASK_FINISH8 = new Integer (39); private static final Integer TASK_START9 = new Integer (40); private static final Integer TASK_FINISH9 = new Integer (41); private static final Integer TASK_START10 = new Integer (42); private static final Integer TASK_FINISH10 = new Integer (43); private static final Integer TASK_NUMBER1 = new Integer (45); private static final Integer TASK_NUMBER2 = new Integer (46); private static final Integer TASK_NUMBER3 = new Integer (47); private static final Integer TASK_NUMBER4 = new Integer (48); private static final Integer TASK_NUMBER5 = new Integer (49); private static final Integer TASK_NUMBER6 = new Integer (50); private static final Integer TASK_NUMBER7 = new Integer (51); private static final Integer TASK_NUMBER8 = new Integer (52); private static final Integer TASK_NUMBER9 = new Integer (53); private static final Integer TASK_NUMBER10 = new Integer (54); private static final Integer TASK_DURATION1 = new Integer (55); private static final Integer TASK_DURATION1_UNITS = new Integer (56); private static final Integer TASK_DURATION2 = new Integer (57); private static final Integer TASK_DURATION2_UNITS = new Integer (58); private static final Integer TASK_DURATION3 = new Integer (59); private static final Integer TASK_DURATION3_UNITS = new Integer (60); private static final Integer TASK_DURATION4 = new Integer (61); private static final Integer TASK_DURATION4_UNITS = new Integer (62); private static final Integer TASK_DURATION5 = new Integer (63); private static final Integer TASK_DURATION5_UNITS = new Integer (64); private static final Integer TASK_DURATION6 = new Integer (65); private static final Integer TASK_DURATION6_UNITS = new Integer (66); private static final Integer TASK_DURATION7 = new Integer (67); private static final Integer TASK_DURATION7_UNITS = new Integer (68); private static final Integer TASK_DURATION8 = new Integer (69); private static final Integer TASK_DURATION8_UNITS = new Integer (70); private static final Integer TASK_DURATION9 = new Integer (71); private static final Integer TASK_DURATION9_UNITS = new Integer (72); private static final Integer TASK_DURATION10 = new Integer (73); private static final Integer TASK_DURATION10_UNITS = new Integer (74); private static final Integer TASK_RECURRING_DATA = new Integer (76); private static final Integer TASK_EXTERNAL_TASK_ID = new Integer (79); private static final Integer TASK_DATE1 = new Integer (80); private static final Integer TASK_DATE2 = new Integer (81); private static final Integer TASK_DATE3 = new Integer (82); private static final Integer TASK_DATE4 = new Integer (83); private static final Integer TASK_DATE5 = new Integer (84); private static final Integer TASK_DATE6 = new Integer (85); private static final Integer TASK_DATE7 = new Integer (86); private static final Integer TASK_DATE8 = new Integer (87); private static final Integer TASK_DATE9 = new Integer (88); private static final Integer TASK_DATE10 = new Integer (89); private static final Integer TASK_TEXT11 = new Integer (90); private static final Integer TASK_TEXT12 = new Integer (91); private static final Integer TASK_TEXT13 = new Integer (92); private static final Integer TASK_TEXT14 = new Integer (93); private static final Integer TASK_TEXT15 = new Integer (94); private static final Integer TASK_TEXT16 = new Integer (95); private static final Integer TASK_TEXT17 = new Integer (96); private static final Integer TASK_TEXT18 = new Integer (97); private static final Integer TASK_TEXT19 = new Integer (98); private static final Integer TASK_TEXT20 = new Integer (99); private static final Integer TASK_TEXT21 = new Integer (100); private static final Integer TASK_TEXT22 = new Integer (101); private static final Integer TASK_TEXT23 = new Integer (102); private static final Integer TASK_TEXT24 = new Integer (103); private static final Integer TASK_TEXT25 = new Integer (104); private static final Integer TASK_TEXT26 = new Integer (105); private static final Integer TASK_TEXT27 = new Integer (106); private static final Integer TASK_TEXT28 = new Integer (107); private static final Integer TASK_TEXT29 = new Integer (108); private static final Integer TASK_TEXT30 = new Integer (109); private static final Integer TASK_NUMBER11 = new Integer (110); private static final Integer TASK_NUMBER12 = new Integer (111); private static final Integer TASK_NUMBER13 = new Integer (112); private static final Integer TASK_NUMBER14 = new Integer (113); private static final Integer TASK_NUMBER15 = new Integer (114); private static final Integer TASK_NUMBER16 = new Integer (115); private static final Integer TASK_NUMBER17 = new Integer (116); private static final Integer TASK_NUMBER18 = new Integer (117); private static final Integer TASK_NUMBER19 = new Integer (118); private static final Integer TASK_NUMBER20 = new Integer (119); private static final Integer TASK_OUTLINECODE1 = new Integer (123); private static final Integer TASK_OUTLINECODE2 = new Integer (124); private static final Integer TASK_OUTLINECODE3 = new Integer (125); private static final Integer TASK_OUTLINECODE4 = new Integer (126); private static final Integer TASK_OUTLINECODE5 = new Integer (127); private static final Integer TASK_OUTLINECODE6 = new Integer (128); private static final Integer TASK_OUTLINECODE7 = new Integer (129); private static final Integer TASK_OUTLINECODE8 = new Integer (130); private static final Integer TASK_OUTLINECODE9 = new Integer (131); private static final Integer TASK_OUTLINECODE10 = new Integer (132); private static final Integer TASK_HYPERLINK = new Integer (133); private static final Integer TASK_COST1 = new Integer (134); private static final Integer TASK_COST2 = new Integer (135); private static final Integer TASK_COST3 = new Integer (136); private static final Integer TASK_COST4 = new Integer (137); private static final Integer TASK_COST5 = new Integer (138); private static final Integer TASK_COST6 = new Integer (139); private static final Integer TASK_COST7 = new Integer (140); private static final Integer TASK_COST8 = new Integer (141); private static final Integer TASK_COST9 = new Integer (142); private static final Integer TASK_COST10 = new Integer (143); private static final Integer TASK_NOTES = new Integer (144); private static final Integer TASK_ENTERPRISE_COLUMNS = new Integer(163); /** * Resource data types. */ private static final Integer RESOURCE_NAME = new Integer (1); private static final Integer RESOURCE_INITIALS = new Integer (3); private static final Integer RESOURCE_GROUP = new Integer (4); private static final Integer RESOURCE_CODE = new Integer (5); private static final Integer RESOURCE_EMAIL = new Integer (6); private static final Integer RESOURCE_MATERIAL_LABEL = new Integer (8); private static final Integer RESOURCE_NT_ACCOUNT = new Integer (9); private static final Integer RESOURCE_TEXT1 = new Integer (10); private static final Integer RESOURCE_TEXT2 = new Integer (11); private static final Integer RESOURCE_TEXT3 = new Integer (12); private static final Integer RESOURCE_TEXT4 = new Integer (13); private static final Integer RESOURCE_TEXT5 = new Integer (14); private static final Integer RESOURCE_TEXT6 = new Integer (15); private static final Integer RESOURCE_TEXT7 = new Integer (16); private static final Integer RESOURCE_TEXT8 = new Integer (17); private static final Integer RESOURCE_TEXT9 = new Integer (18); private static final Integer RESOURCE_TEXT10 = new Integer (19); private static final Integer RESOURCE_TEXT11 = new Integer (20); private static final Integer RESOURCE_TEXT12 = new Integer (21); private static final Integer RESOURCE_TEXT13 = new Integer (22); private static final Integer RESOURCE_TEXT14 = new Integer (23); private static final Integer RESOURCE_TEXT15 = new Integer (24); private static final Integer RESOURCE_TEXT16 = new Integer (25); private static final Integer RESOURCE_TEXT17 = new Integer (26); private static final Integer RESOURCE_TEXT18 = new Integer (27); private static final Integer RESOURCE_TEXT19 = new Integer (28); private static final Integer RESOURCE_TEXT20 = new Integer (29); private static final Integer RESOURCE_TEXT21 = new Integer (30); private static final Integer RESOURCE_TEXT22 = new Integer (31); private static final Integer RESOURCE_TEXT23 = new Integer (32); private static final Integer RESOURCE_TEXT24 = new Integer (33); private static final Integer RESOURCE_TEXT25 = new Integer (34); private static final Integer RESOURCE_TEXT26 = new Integer (35); private static final Integer RESOURCE_TEXT27 = new Integer (36); private static final Integer RESOURCE_TEXT28 = new Integer (37); private static final Integer RESOURCE_TEXT29 = new Integer (38); private static final Integer RESOURCE_TEXT30 = new Integer (39); private static final Integer RESOURCE_START1 = new Integer (40); private static final Integer RESOURCE_START2 = new Integer (41); private static final Integer RESOURCE_START3 = new Integer (42); private static final Integer RESOURCE_START4 = new Integer (43); private static final Integer RESOURCE_START5 = new Integer (44); private static final Integer RESOURCE_START6 = new Integer (45); private static final Integer RESOURCE_START7 = new Integer (46); private static final Integer RESOURCE_START8 = new Integer (47); private static final Integer RESOURCE_START9 = new Integer (48); private static final Integer RESOURCE_START10 = new Integer (49); private static final Integer RESOURCE_FINISH1 = new Integer (50); private static final Integer RESOURCE_FINISH2 = new Integer (51); private static final Integer RESOURCE_FINISH3 = new Integer (52); private static final Integer RESOURCE_FINISH4 = new Integer (53); private static final Integer RESOURCE_FINISH5 = new Integer (54); private static final Integer RESOURCE_FINISH6 = new Integer (55); private static final Integer RESOURCE_FINISH7 = new Integer (56); private static final Integer RESOURCE_FINISH8 = new Integer (57); private static final Integer RESOURCE_FINISH9 = new Integer (58); private static final Integer RESOURCE_FINISH10 = new Integer (59); private static final Integer RESOURCE_NUMBER1 = new Integer (60); private static final Integer RESOURCE_NUMBER2 = new Integer (61); private static final Integer RESOURCE_NUMBER3 = new Integer (62); private static final Integer RESOURCE_NUMBER4 = new Integer (63); private static final Integer RESOURCE_NUMBER5 = new Integer (64); private static final Integer RESOURCE_NUMBER6 = new Integer (65); private static final Integer RESOURCE_NUMBER7 = new Integer (66); private static final Integer RESOURCE_NUMBER8 = new Integer (67); private static final Integer RESOURCE_NUMBER9 = new Integer (68); private static final Integer RESOURCE_NUMBER10 = new Integer (69); private static final Integer RESOURCE_NUMBER11 = new Integer (70); private static final Integer RESOURCE_NUMBER12 = new Integer (71); private static final Integer RESOURCE_NUMBER13 = new Integer (72); private static final Integer RESOURCE_NUMBER14 = new Integer (73); private static final Integer RESOURCE_NUMBER15 = new Integer (74); private static final Integer RESOURCE_NUMBER16 = new Integer (75); private static final Integer RESOURCE_NUMBER17 = new Integer (76); private static final Integer RESOURCE_NUMBER18 = new Integer (77); private static final Integer RESOURCE_NUMBER19 = new Integer (78); private static final Integer RESOURCE_NUMBER20 = new Integer (79); private static final Integer RESOURCE_DURATION1 = new Integer (80); private static final Integer RESOURCE_DURATION2 = new Integer (81); private static final Integer RESOURCE_DURATION3 = new Integer (82); private static final Integer RESOURCE_DURATION4 = new Integer (83); private static final Integer RESOURCE_DURATION5 = new Integer (84); private static final Integer RESOURCE_DURATION6 = new Integer (85); private static final Integer RESOURCE_DURATION7 = new Integer (86); private static final Integer RESOURCE_DURATION8 = new Integer (87); private static final Integer RESOURCE_DURATION9 = new Integer (88); private static final Integer RESOURCE_DURATION10 = new Integer (89); private static final Integer RESOURCE_DURATION1_UNITS = new Integer (90); private static final Integer RESOURCE_DURATION2_UNITS = new Integer (91); private static final Integer RESOURCE_DURATION3_UNITS = new Integer (92); private static final Integer RESOURCE_DURATION4_UNITS = new Integer (93); private static final Integer RESOURCE_DURATION5_UNITS = new Integer (94); private static final Integer RESOURCE_DURATION6_UNITS = new Integer (95); private static final Integer RESOURCE_DURATION7_UNITS = new Integer (96); private static final Integer RESOURCE_DURATION8_UNITS = new Integer (97); private static final Integer RESOURCE_DURATION9_UNITS = new Integer (98); private static final Integer RESOURCE_DURATION10_UNITS = new Integer (99); private static final Integer RESOURCE_SUBPROJECTRESOURCEID = new Integer (102); private static final Integer RESOURCE_DATE1 = new Integer (103); private static final Integer RESOURCE_DATE2 = new Integer (104); private static final Integer RESOURCE_DATE3 = new Integer (105); private static final Integer RESOURCE_DATE4 = new Integer (106); private static final Integer RESOURCE_DATE5 = new Integer (107); private static final Integer RESOURCE_DATE6 = new Integer (108); private static final Integer RESOURCE_DATE7 = new Integer (109); private static final Integer RESOURCE_DATE8 = new Integer (110); private static final Integer RESOURCE_DATE9 = new Integer (111); private static final Integer RESOURCE_DATE10 = new Integer (112); private static final Integer RESOURCE_OUTLINECODE1 = new Integer (113); private static final Integer RESOURCE_OUTLINECODE2 = new Integer (114); private static final Integer RESOURCE_OUTLINECODE3 = new Integer (115); private static final Integer RESOURCE_OUTLINECODE4 = new Integer (116); private static final Integer RESOURCE_OUTLINECODE5 = new Integer (117); private static final Integer RESOURCE_OUTLINECODE6 = new Integer (118); private static final Integer RESOURCE_OUTLINECODE7 = new Integer (119); private static final Integer RESOURCE_OUTLINECODE8 = new Integer (120); private static final Integer RESOURCE_OUTLINECODE9 = new Integer (121); private static final Integer RESOURCE_OUTLINECODE10 = new Integer (122); private static final Integer RESOURCE_HYPERLINK = new Integer (123); private static final Integer RESOURCE_NOTES = new Integer (124); private static final Integer RESOURCE_COST1 = new Integer (125); private static final Integer RESOURCE_COST2 = new Integer (126); private static final Integer RESOURCE_COST3 = new Integer (127); private static final Integer RESOURCE_COST4 = new Integer (128); private static final Integer RESOURCE_COST5 = new Integer (129); private static final Integer RESOURCE_COST6 = new Integer (130); private static final Integer RESOURCE_COST7 = new Integer (131); private static final Integer RESOURCE_COST8 = new Integer (132); private static final Integer RESOURCE_COST9 = new Integer (133); private static final Integer RESOURCE_COST10 = new Integer (134); private static final Integer RESOURCE_ENTERPRISE_COLUMNS = new Integer(143); private static final Integer RESOURCE_BASELINE1_WORK = new Integer(144); private static final Integer RESOURCE_BASELINE2_WORK = new Integer(148); private static final Integer RESOURCE_BASELINE3_WORK = new Integer(152); private static final Integer RESOURCE_BASELINE4_WORK = new Integer(156); private static final Integer RESOURCE_BASELINE5_WORK = new Integer(160); private static final Integer RESOURCE_BASELINE6_WORK = new Integer(164); private static final Integer RESOURCE_BASELINE7_WORK = new Integer(168); private static final Integer RESOURCE_BASELINE8_WORK = new Integer(172); private static final Integer RESOURCE_BASELINE9_WORK = new Integer(176); private static final Integer RESOURCE_BASELINE10_WORK = new Integer(180); private static final Integer RESOURCE_BASELINE1_COST = new Integer(145); private static final Integer RESOURCE_BASELINE2_COST = new Integer(149); private static final Integer RESOURCE_BASELINE3_COST = new Integer(153); private static final Integer RESOURCE_BASELINE4_COST = new Integer(157); private static final Integer RESOURCE_BASELINE5_COST = new Integer(161); private static final Integer RESOURCE_BASELINE6_COST = new Integer(165); private static final Integer RESOURCE_BASELINE7_COST = new Integer(169); private static final Integer RESOURCE_BASELINE8_COST = new Integer(173); private static final Integer RESOURCE_BASELINE9_COST = new Integer(177); private static final Integer RESOURCE_BASELINE10_COST = new Integer(181); private static final Integer TABLE_COLUMN_DATA_STANDARD = new Integer (1); private static final Integer TABLE_COLUMN_DATA_ENTERPRISE = new Integer (2); private static final Integer TABLE_COLUMN_DATA_BASELINE = null; private static final Integer OUTLINECODE_DATA = new Integer (1); private static final Integer INCOMPLETE_WORK = new Integer(7); private static final Integer COMPLETE_WORK = new Integer(9); /** * Mask used to isolate confirmed flag from the duration units field. */ private static final int DURATION_CONFIRMED_MASK = 0x20; /** * Default working week. */ private static final boolean[] DEFAULT_WORKING_WEEK = { false, true, true, true, true, true, false }; private static final int MINIMUM_EXPECTED_TASK_SIZE = 240; private static final int MINIMUM_EXPECTED_RESOURCE_SIZE = 188; }
package net.sf.mpxj.mpp; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.text.DecimalFormat; import java.util.Calendar; import java.util.Date; import net.sf.mpxj.CurrencySymbolPosition; import net.sf.mpxj.Duration; import net.sf.mpxj.ProjectFile; import net.sf.mpxj.TimeUnit; import net.sf.mpxj.utility.DateUtility; /** * This class provides common functionality used by each of the classes * that read the different sections of the MPP file. */ final class MPPUtility { /** * Private constructor to prevent instantiation. */ private MPPUtility () { // private constructor to prevent instantiation } /** * This method decodes a byte array with the given encryption code * using XOR encryption. * * @param data Source data * @param encryptionCode Encryption code */ public static final void decodeBuffer(byte[] data, byte encryptionCode) { for (int i = 0; i < data.length; i++) { data[i] = (byte)(data[i] ^ encryptionCode); } } /** * The mask used by Project to hide the password. The data must first * be decoded using the XOR key and then the password can be read by reading * the characters in given order starting with 1 and going up to 16. * * 00000: 00 00 04 00 00 00 05 00 07 00 12 00 10 00 06 00 * 00016: 14 00 00 00 00 00 08 00 16 00 00 00 00 00 02 00 * 00032: 00 00 15 00 00 00 11 00 00 00 00 00 00 00 09 00 * 00048: 03 00 00 00 00 00 00 00 00 00 00 00 01 00 13 00 */ private static final int[] PASSWORD_MASK = { 60, 30, 48, 2, 6, 14, 8, 22, 44, 12, 38, 10, 62, 16, 34, 24 }; private static final int MINIMUM_PASSWORD_DATA_LENGTH = 64; /** * Decode the password from the given data. Will decode the data block as well. * * @param data encrypted data block * @param encryptionCode encryption code * * @return password */ public static final String decodePassword(byte[] data, byte encryptionCode) { String result; if (data.length < MINIMUM_PASSWORD_DATA_LENGTH) { result = null; } else { MPPUtility.decodeBuffer(data, encryptionCode); StringBuffer buffer = new StringBuffer(); char c; for (int i = 0; i < PASSWORD_MASK.length; i++) { int index = PASSWORD_MASK[i]; c = (char)data[index]; if (c == 0) { break; } buffer.append(c); } result = buffer.toString(); } return (result); } /** * This method extracts a portion of a byte array and writes it into * another byte array. * * @param data Source data * @param offset Offset into source data * @param size Required size to be extracted from the source data * @param buffer Destination buffer * @param bufferOffset Offset into destination buffer */ public static final void getByteArray (byte[] data, int offset, int size, byte[] buffer, int bufferOffset) { System.arraycopy(data, offset, buffer, bufferOffset, size); } /** * This method reads a single byte from the input array. * * @param data byte array of data * @param offset offset of byte data in the array * @return byte value */ public static final int getByte (byte[] data, int offset) { int result = (data[offset] & 0xFF); return result; } /** * This method reads a single byte from the input array. * The byte is assumed to be at the start of the array. * * @param data byte array of data * @return byte value */ public static final int getByte (byte[] data) { return (getByte(data, 0)); } /** * This method reads a two byte integer from the input array. * * @param data the input array * @param offset offset of integer data in the array * @return integer value */ public static final int getShort (byte[] data, int offset) { int result = 0; int i = offset; for ( int shiftBy = 0; shiftBy < 16; shiftBy += 8 ) { result |= ( ( data[i] & 0xff ) ) << shiftBy; ++i; } return result; } /** * This method reads a two byte integer from the input array. * The integer is assumed to be at the start of the array. * * @param data the input array * @return integer value */ public static final int getShort (byte[] data) { return (getShort(data, 0)); } /** * This method reads a four byte integer from the input array. * * @param data the input array * @param offset offset of integer data in the array * @return integer value */ public static final int getInt (byte[] data, int offset) { int result = 0; int i = offset; for ( int shiftBy = 0; shiftBy < 32; shiftBy += 8 ) { result |= ( ( data[i] & 0xff ) ) << shiftBy; ++i; } return result; } /** * This method reads a four byte integer from the input array. * The integer is assumed to be at the start of the array. * * @param data the input array * @return integer value */ public static final int getInt (byte[] data) { return (getInt(data, 0)); } /** * This method reads an eight byte integer from the input array. * * @param data the input array * @param offset offset of integer data in the array * @return integer value */ public static final long getLong (byte[] data, int offset) { long result = 0; int i = offset; for ( int shiftBy = 0; shiftBy < 64; shiftBy += 8 ) { result |= ( (long)( data[i] & 0xff ) ) << shiftBy; ++i; } return result; } /** * This method reads a six byte long from the input array. * * @param data the input array * @param offset offset of integer data in the array * @return integer value */ public static final long getLong6 (byte[] data, int offset) { long result = 0; int i = offset; for ( int shiftBy = 0; shiftBy < 48; shiftBy += 8 ) { result |= ( (long)( data[i] & 0xff ) ) << shiftBy; ++i; } return result; } /** * This method reads a six byte long from the input array. * The integer is assumed to be at the start of the array. * * @param data the input array * @return integer value */ public static final long getLong6 (byte[] data) { return (getLong6(data, 0)); } /** * This method reads a eight byte integer from the input array. * The integer is assumed to be at the start of the array. * * @param data the input array * @return integer value */ public static final long getLong (byte[] data) { return (getLong(data, 0)); } /** * This method reads an eight byte double from the input array. * * @param data the input array * @param offset offset of double data in the array * @return double value */ public static final double getDouble (byte[] data, int offset) { return (Double.longBitsToDouble(getLong(data, offset))); } /** * This method reads an eight byte double from the input array. * The double is assumed to be at the start of the array. * * @param data the input array * @return double value */ public static final double getDouble (byte[] data) { return (Double.longBitsToDouble(getLong(data, 0))); } /** * Reads a date value. Note that an NA is represented as 65535 in the * MPP file. We represent this in Java using a null value. The actual * value in the MPP file is number of days since 31/12/1983. * * @param data byte array of data * @param offset location of data as offset into the array * @return date value */ public static final Date getDate (byte[] data, int offset) { Date result; long days = getShort(data, offset); if (days == 65535) { result = null; } else { result = DateUtility.getDateFromLong(EPOCH + (days * MS_PER_DAY)); } return (result); } /** * Reads a time value. The time is represented as tenths of a * minute since midnight. * * @param data byte array of data * @param offset location of data as offset into the array * @return time value */ public static final Date getTime (byte[] data, int offset) { int time = getShort(data, offset) / 10; Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, (time / 60)); cal.set(Calendar.MINUTE, (time % 60)); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return (cal.getTime()); } /** * Reads a time value. The time is represented as tenths of a * minute since midnight. * * @param data byte array of data * @return time value */ public static final Date getTime (byte[] data) { return (getTime(data, 0)); } /** * Reads a duration value in milliseconds. The time is represented as * tenths of a minute since midnight. * * @param data byte array of data * @param offset location of data as offset into the array * @return duration value */ public static final long getDuration (byte[] data, int offset) { return ((getShort(data, offset) * MS_PER_MINUTE) / 10); } /** * Reads a combined date and time value. * * @param data byte array of data * @param offset location of data as offset into the array * @return time value */ public static final Date getTimestamp (byte[] data, int offset) { Date result; long days = getShort(data, offset + 2); if (days == 65535) { result = null; } else { long time = getShort(data, offset); if (time == 65535) { time = 0; } result = DateUtility.getTimestampFromLong((EPOCH + (days * MS_PER_DAY) + ((time * MS_PER_MINUTE) / 10))); } return (result); } /** * Reads a combined date and time value. * The value is assumed to be at the start of the array. * * @param data byte array of data * @return time value */ public static final Date getTimestamp (byte[] data) { return (getTimestamp(data, 0)); } /** * Reads a string of two byte characters from the input array. * This method assumes that the string finishes either at the * end of the array, or when char zero is encountered. * The value is assumed to be at the start of the array. * * @param data byte array of data * @return string value */ public static final String getUnicodeString (byte[] data) { return (getUnicodeString(data, 0)); } /** * Reads a string of two byte characters from the input array. * This method assumes that the string finishes either at the * end of the array, or when char zero is encountered. * The value starts at the position specified by the offset * parameter. * * @param data byte array of data * @param offset start point of unicode string * @return string value */ public static final String getUnicodeString (byte[] data, int offset) { StringBuffer buffer = new StringBuffer(); char c; for (int loop = offset; loop < (data.length - 1); loop += 2) { c = (char)getShort(data, loop); if (c == 0) { break; } buffer.append(c); } return (buffer.toString()); } /** * Reads a string of two byte characters from the input array. * This method assumes that the string finishes either at the * end of the array, or when char zero is encountered, or * when a string of a certain length in bytes has been read. * The value starts at the position specified by the offset * parameter. * * @param data byte array of data * @param offset start point of unicode string * @param length length in bytes of the string * @return string value */ public static final String getUnicodeString (byte[] data, int offset, int length) { StringBuffer buffer = new StringBuffer(); char c; int loop = offset; int byteLength = 0; while (loop < (data.length - 1) && byteLength < length) { c = (char)getShort(data, loop); if (c == 0) { break; } buffer.append(c); loop += 2; byteLength += 2; } return (buffer.toString()); } /** * Reads a string of single byte characters from the input array. * This method assumes that the string finishes either at the * end of the array, or when char zero is encountered. * The value is assumed to be at the start of the array. * * @param data byte array of data * @return string value */ public static final String getString (byte[] data) { return (getString(data, 0)); } /** * Reads a string of single byte characters from the input array. * This method assumes that the string finishes either at the * end of the array, or when char zero is encountered. * Reading begins at the supplied offset into the array. * * @param data byte array of data * @param offset offset into the array * @return string value */ public static final String getString (byte[] data, int offset) { StringBuffer buffer = new StringBuffer(); char c; for (int loop = 0; offset+loop < data.length; loop++) { c = (char)data[offset+loop]; if (c == 0) { break; } buffer.append(c); } return (buffer.toString()); } /** * Reads a duration value. This method relies on the fact that * the units of the duration have been specified elsewhere. * * @param value Duration value * @param type type of units of the duration * @return Duration instance */ public static final Duration getDuration (int value, TimeUnit type) { return (getDuration((double)value, type)); } /** * Reads a duration value. This method relies on the fact that * the units of the duration have been specified elsewhere. * * @param value Duration value * @param type type of units of the duration * @return Duration instance */ public static final Duration getDuration (double value, TimeUnit type) { double duration; switch (type) { case MINUTES: case ELAPSED_MINUTES: { duration = value / 10; break; } case HOURS: case ELAPSED_HOURS: { duration = value / 600; break; } case DAYS: case ELAPSED_DAYS: { duration = value / 4800; break; } case WEEKS: case ELAPSED_WEEKS: { duration = value / 24000; break; } case MONTHS: case ELAPSED_MONTHS: { duration = value / 96000; break; } default: { duration = value; break; } } return (Duration.getInstance(duration, type)); } /** * This method converts between the duration units representation * used in the MPP file, and the standard MPX duration units. * If the supplied units are unrecognised, the units default to days. * * @param type MPP units * @return MPX units */ public static final TimeUnit getDurationTimeUnits (int type) { TimeUnit units; switch (type & DURATION_UNITS_MASK) { case 3: { units = TimeUnit.MINUTES; break; } case 4: { units = TimeUnit.ELAPSED_MINUTES; break; } case 5: { units = TimeUnit.HOURS; break; } case 6: { units = TimeUnit.ELAPSED_HOURS; break; } case 8: { units = TimeUnit.ELAPSED_DAYS; break; } case 9: { units = TimeUnit.WEEKS; break; } case 10: { units = TimeUnit.ELAPSED_WEEKS; break; } case 11: { units = TimeUnit.MONTHS; break; } case 12: { units = TimeUnit.ELAPSED_MONTHS; break; } case 19: { units = TimeUnit.PERCENT; break; } default: case 7: case 21: // duration in days of a recurring task { units = TimeUnit.DAYS; break; } } return (units); } /** * Given a duration and the time units for the duration extracted from an MPP * file, this method creates a new Duration to represent the given * duration. This instance has been adjusted to take into account the * number of "hours per day" specified for the current project. * * @param file parent file * @param duration duration length * @param timeUnit duration units * @return Duration instance */ public static Duration getAdjustedDuration (ProjectFile file, int duration, TimeUnit timeUnit) { Duration result; switch (timeUnit) { case DAYS: { double unitsPerDay = file.getProjectHeader().getMinutesPerDay().doubleValue() * 10d; double totalDays = 0; if (unitsPerDay != 0) { totalDays = duration / unitsPerDay; } result = Duration.getInstance(totalDays, timeUnit); break; } case ELAPSED_DAYS: { double unitsPerDay = 24d * 600d; double totalDays = duration / unitsPerDay; result = Duration.getInstance(totalDays, timeUnit); break; } case ELAPSED_WEEKS: { double unitsPerWeek = (60 * 24 * 7 * 10); double totalWeeks = duration / unitsPerWeek; result = Duration.getInstance(totalWeeks, timeUnit); break; } case ELAPSED_MONTHS: { double unitsPerMonth = (60 * 24 * 29 * 10); double totalMonths = duration / unitsPerMonth; result = Duration.getInstance(totalMonths, timeUnit); break; } default: { result = getDuration(duration, timeUnit); break; } } return (result); } /** * This method maps from the value used to specify default work units in the * MPP file to a standard TimeUnit. * * @param value Default work units * @return TimeUnit value */ public static TimeUnit getWorkTimeUnits (int value) { TimeUnit result; switch (value) { case 1: { result = TimeUnit.MINUTES; break; } case 3: { result = TimeUnit.DAYS; break; } case 4: { result = TimeUnit.WEEKS; break; } case 2:default: { result = TimeUnit.HOURS; break; } } return (result); } /** * This method maps the currency symbol position from the * representation used in the MPP file to the representation * used by MPX. * * @param value MPP symbol position * @return MPX symbol position */ public static CurrencySymbolPosition getSymbolPosition (int value) { CurrencySymbolPosition result; switch (value) { case 1: { result = CurrencySymbolPosition.AFTER; break; } case 2: { result = CurrencySymbolPosition.BEFORE_WITH_SPACE; break; } case 3: { result = CurrencySymbolPosition.AFTER_WITH_SPACE; break; } case 0:default: { result = CurrencySymbolPosition.BEFORE; break; } } return (result); } /** * Utility method to remove ampersands embedded in names. * * @param name name text * @return name text without embedded ampersands */ public static final String removeAmpersands (String name) { if (name != null) { if (name.indexOf('&') != -1) { StringBuffer sb = new StringBuffer(); int index = 0; char c; while (index < name.length()) { c = name.charAt(index); if (c != '&') { sb.append(c); } ++index; } name = sb.toString(); } } return (name); } /** * This method allows a subsection of a byte array to be copied. * * @param data source data * @param offset offset into the source data * @param size length of the source data to copy * @return new byte array containing copied data */ public static final byte[] cloneSubArray (byte[] data, int offset, int size) { byte[] newData = new byte[size]; System.arraycopy(data, offset, newData, 0, size); return (newData); } /** * This method generates a formatted version of the data contained * in a byte array. The data is written both in hex, and as ASCII * characters. * * @param buffer data to be displayed * @param offset offset of start of data to be displayed * @param length length of data to be displayed * @param ascii flag indicating whether ASCII equivalent chars should also be displayed * @return formatted string */ public static final String hexdump (byte[] buffer, int offset, int length, boolean ascii) { StringBuffer sb = new StringBuffer(); if (buffer != null) { char c; int loop; int count = offset + length; for (loop = offset; loop < count; loop++) { sb.append(" "); sb.append(HEX_DIGITS[(buffer[loop] & 0xF0) >> 4]); sb.append(HEX_DIGITS[buffer[loop] & 0x0F]); } if (ascii == true) { sb.append(" "); for (loop = offset; loop < count; loop++) { c = (char)buffer[loop]; if ((c > 200) || (c < 27)) { c = ' '; } sb.append(c); } } } return (sb.toString()); } /** * This method generates a formatted version of the data contained * in a byte array. The data is written both in hex, and as ASCII * characters. * * @param buffer data to be displayed * @param ascii flag indicating whether ASCII equivalent chars should also be displayed * @return formatted string */ public static final String hexdump (byte[] buffer, boolean ascii) { int length = 0; if (buffer != null) { length = buffer.length; } return (hexdump(buffer, 0, length, ascii)); } /** * This method generates a formatted version of the data contained * in a byte array. The data is written both in hex, and as ASCII * characters. The data is organised into fixed width columns. * * @param buffer data to be displayed * @param ascii flag indicating whether ASCII equivalent chars should also be displayed * @param columns number of columns * @param prefix prefix to be added before the start of the data * @return formatted string */ public static final String hexdump (byte[] buffer, boolean ascii, int columns, String prefix) { StringBuffer sb = new StringBuffer(); if (buffer != null) { int index = 0; DecimalFormat df = new DecimalFormat("00000"); while (index < buffer.length) { if (index + columns > buffer.length) { columns = buffer.length - index; } sb.append (prefix); sb.append (df.format(index)); sb.append (":"); sb.append (hexdump(buffer, index, columns, ascii)); sb.append ('\n'); index += columns; } } return (sb.toString()); } /** * This method generates a formatted version of the data contained * in a byte array. The data is written both in hex, and as ASCII * characters. The data is organised into fixed width columns. * * @param buffer data to be displayed * @param offset offset into buffer * @param length number of bytes to display * @param ascii flag indicating whether ASCII equivalent chars should also be displayed * @param columns number of columns * @param prefix prefix to be added before the start of the data * @return formatted string */ public static final String hexdump (byte[] buffer, int offset, int length, boolean ascii, int columns, String prefix) { StringBuffer sb = new StringBuffer(); if (buffer != null) { int index = offset; DecimalFormat df = new DecimalFormat("00000"); while (index < (offset+length)) { if (index + columns > (offset+length)) { columns = (offset+length) - index; } sb.append (prefix); sb.append (df.format(index)); sb.append (":"); sb.append (hexdump(buffer, index, columns, ascii)); sb.append ('\n'); index += columns; } } return (sb.toString()); } /** * Writes a hex dump to a file for a large byte array. * * @param fileName output file name * @param data target data */ public static final void fileHexDump (String fileName, byte[] data) { try { FileOutputStream os = new FileOutputStream(fileName); os.write(hexdump(data, true, 16, "").getBytes()); os.close(); } catch (IOException ex) { ex.printStackTrace(); } } /** * Writes a hex dump to a file from a POI input stream. * Note that this assumes that the complete size of the data in * the stream is returned by the available() method. * * @param fileName output file name * @param is input stream */ public static final void fileHexDump (String fileName, InputStream is) { try { byte[] data = new byte[is.available()]; is.read(data); fileHexDump(fileName, data); } catch (IOException ex) { ex.printStackTrace(); } } /** * Writes a large byte array to a file. * * @param fileName output file name * @param data target data */ public static final void fileDump (String fileName, byte[] data) { try { FileOutputStream os = new FileOutputStream(fileName); os.write(data); os.close(); } catch (IOException ex) { ex.printStackTrace(); } } /** * Dump out all the possible variables within the given data block. * * @param data data to dump from * @param dumpShort true to dump all the data as shorts * @param dumpInt true to dump all the data as ints * @param dumpDouble true to dump all the data as Doubles * @param dumpTimeStamp true to dump all the data as TimeStamps * @param dumpDuration true to dump all the data as Durations (long) * @param dumpDate true to dump all the data as Dates * @param dumpTime true to dump all the data as Dates (time) */ public static final void dataDump(byte[] data, boolean dumpShort, boolean dumpInt, boolean dumpDouble, boolean dumpTimeStamp, boolean dumpDuration, boolean dumpDate, boolean dumpTime) { System.out.println("DATA"); if (data != null) { System.out.println (MPPUtility.hexdump(data, false, 16, "")); for (int i = 0; i < data.length; i++) { if (dumpShort) { try { int sh = MPPUtility.getShort(data, i); System.out.println(i + ":" + sh); } catch (Exception ex) { // Silently ignore exceptions } } if (dumpInt) { try { int sh = MPPUtility.getInt(data, i); System.out.println(i + ":" + sh); } catch (Exception ex) { // Silently ignore exceptions } } if (dumpDouble) { try { double d = MPPUtility.getDouble(data, i); System.out.println(i + ":" + d); } catch (Exception ex) { // Silently ignore exceptions } } if (dumpTimeStamp) { try { Date d = MPPUtility.getTimestamp(data, i); if (d != null) { System.out.println(i + ":" + d.toString()); } } catch (Exception ex) { // Silently ignore exceptions } } if (dumpDuration) { try { long d = MPPUtility.getDuration(data, i); System.out.println(i + ":" + d); } catch (Exception ex) { // Silently ignore exceptions } } if (dumpDate) { try { Date d = MPPUtility.getDate(data, i); if (d != null) { System.out.println(i + ":" + d.toString()); } } catch (Exception ex) { // Silently ignore exceptions } } if (dumpTime) { try { Date d = MPPUtility.getTime(data, i); if (d != null) { System.out.println(i + ":" + d.toString()); } } catch (Exception ex) { // Silently ignore exceptions } } } } } /** * Dump out all the possible variables within the given data block. * * @param data data to dump from * @param id unique ID * @param dumpShort true to dump all the data as shorts * @param dumpInt true to dump all the data as ints * @param dumpDouble true to dump all the data as Doubles * @param dumpTimeStamp true to dump all the data as TimeStamps * @param dumpUnicodeString true to dump all the data as Unicode strings * @param dumpString true to dump all the data as strings */ public static final void varDataDump(Var2Data data, Integer id, boolean dumpShort, boolean dumpInt, boolean dumpDouble, boolean dumpTimeStamp, boolean dumpUnicodeString, boolean dumpString) { System.out.println("VARDATA"); for (int i = 0; i < 500; i++) { if (dumpShort) { try { int sh = data.getShort(id, Integer.valueOf(i)); System.out.println(i + ":" + sh); } catch (Exception ex) { // Silently ignore exceptions } } if (dumpInt) { try { int sh = data.getInt(id, Integer.valueOf(i)); System.out.println(i + ":" + sh); } catch (Exception ex) { // Silently ignore exceptions } } if (dumpDouble) { try { double d = data.getDouble(id, Integer.valueOf(i)); System.out.println(i + ":" + d); System.out.println(i + ":" + d/60000); } catch (Exception ex) { // Silently ignore exceptions } } if (dumpTimeStamp) { try { Date d = data.getTimestamp(id, Integer.valueOf(i)); if (d != null) { System.out.println(i + ":" + d.toString()); } } catch (Exception ex) { // Silently ignore exceptions } } if (dumpUnicodeString) { try { String s = data.getUnicodeString(id, Integer.valueOf(i)); if (s != null) { System.out.println(i + ":" + s); } } catch (Exception ex) { // Silently ignore exceptions } } if (dumpString) { try { String s = data.getString(id, Integer.valueOf(i)); if (s != null) { System.out.println(i + ":" + s); } } catch (Exception ex) { // Silently ignore exceptions } } } } /** * Get the epoch date. * * @return epoch date. */ public static Date getEpochDate() { return EPOCH_DATE; } /** * Epoch date for MPP date calculation is 31/12/1983. This constant * is that date expressed in milliseconds using the Java date epoch. */ private static final long EPOCH = 441676800000L; /** * Epoch Date as a Date instance. */ private static Date EPOCH_DATE = DateUtility.getTimestampFromLong(EPOCH); /** * Number of milliseconds per day. */ private static final long MS_PER_DAY = 24 * 60 * 60 * 1000; /** * Number of milliseconds per minute. */ private static final long MS_PER_MINUTE = 60 * 1000; /** * Constants used to convert bytes to hex digits. */ private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; /** * Mask used to remove flags from the duration units field. */ private static final int DURATION_UNITS_MASK = 0x1F; }
package edu.wustl.catissuecore.action; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.Action; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import edu.wustl.catissuecore.actionForm.LoginForm; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.util.logger.Logger; public class LoginAction extends Action { /** * Overrides the execute method of Action class. * Initializes the various drop down fields in Institute.jsp Page. * */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String loginName = null; String password = null; HttpSession session = null; if (form == null) { Logger.out.debug("Form is Null"); return (mapping.findForward(Constants.FAILURE)); } LoginForm loginForm = (LoginForm) form; Logger.out.info("Inside Login Action, Just before validation"); loginName = loginForm.getLoginName(); password = loginForm.getPassword(); try { boolean loginOK = login(loginName,password); if (loginOK) { Logger.out.info(">>>>>>>>>>>>> SUCESSFUL LOGIN <<<<<<<<< "); session = request.getSession(true); return mapping.findForward(Constants.SUCCESS); } else { Logger.out.info("User " + loginName + " Invalid user. Sending back to the login Page"); ActionErrors errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.incorrectLoginNamePassword")); //Report any errors we have discovered if (!errors.isEmpty()) { saveErrors(request, errors); } return (mapping.findForward(Constants.FAILURE)); } } catch (Exception e){ Logger.out.info("Exception: "+e.getMessage()); ActionErrors errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR, new ActionError( "errors.exceptionErrorMessage")); //Report any errors we have discovered if (!errors.isEmpty()) { saveErrors(request, errors); } return (mapping.findForward(Constants.FAILURE)); } } private boolean login(String loginName, String password) { boolean bool=false; if(loginName.equals("admin") && password.equals("admin")) { bool=true; } return bool; } }
package com.orgecc.calltimer; import java.lang.reflect.Array; import java.util.Collection; import java.util.Date; import java.util.Map; import org.slf4j.Logger; class BaseCallTimer implements CallTimer { private static final String HEADER = "YYYY-MM-DD HH:mm:ss.sss\tlevel\tTBID\tms\tinsize\toutsize\touttype\tmethod\tclass"; private static final String MSG_FORMAT = "%s\t%s\t%s\t%s\t%s\t%s"; private static final String TO_STRING_FORMAT = "%s:%s [%s %s.%s inputSize=%s, outputSize=%s, output=%s, callEnded=%s]"; private static final String THREAD_NAME_FORMAT = "%s(%s.%s%s) %s [%s]"; /** * Month, day, hour, minute, second, millisecond, as in '1231-235959.999'. */ private static final String DATE_TIME_FORMAT = "%1$tm%1$td-%1$tH%1$tM%1$tS.%1$TL"; private static final String TYPE_PREFIX_TO_OMIT = "java.lang."; private static final int NO_THREAD = -1; static Logger saveHeader( final Logger logger ) { logger.warn( HEADER ); return logger; } static String normalizeOutMessage( final String str ) { return ( str.startsWith( TYPE_PREFIX_TO_OMIT ) ? str.substring( TYPE_PREFIX_TO_OMIT .length() ) : str ).replace( '\t', ' ' ); } @SuppressWarnings( "rawtypes" ) private static Integer getSize( final Object output ) { if ( output instanceof String ) { return ( (String) output ).length(); } if ( output instanceof Collection ) { return ( (Collection) output ).size(); } if ( output instanceof Map ) { return ( (Map) output ).size(); } if ( output.getClass().isArray() ) { return Array.getLength( output ); } return null; } long startNanos; long startMillis; String className; String methodName; long inputSize; private String outputSize; private Object output; boolean callEnded; final transient Ticker ticker; final transient Logger logger; private transient long originalThreadId = NO_THREAD; private transient String originalThreadName; BaseCallTimer( final Ticker ticker, final Logger logger ) { this.ticker = ticker; this.logger = logger; } void saveEvent( final Throwable throwable, final String msg ) { if ( throwable == null ) { this.logger.info( msg ); return; } this.logger.error( msg ); } public final CallTimer callStart() { return callStart( 0 ); } public final CallTimer callStart( final byte[] bytes ) { return callStart( bytes == null ? 0 : bytes.length ); } public final CallTimer callStart( final long inputSize ) { this.startNanos = this.ticker.read(); this.startMillis = System.currentTimeMillis(); this.inputSize = inputSize; this.outputSize = null; this.output = null; this.callEnded = false; return setCallName( null, null ); } public final CallTimer setCallName( final String className, final String methodName, final int paramCount ) { return setCallName( className, methodName + "#" + paramCount ); } public final CallTimer setCallName( final String className, final String methodName ) { this.className = className == null ? "-" : className.replace( ' ', '-' ); this.methodName = methodName == null ? "-" : methodName.replace( ' ', '-' ); return this; } public final CallTimer setInputSize( final long inputSize ) { this.inputSize = inputSize; return this; } public final CallTimer setOutputSize( final long outputSize ) { this.outputSize = Long.toString( outputSize ); return this; } public final CallTimer setThreadDetails() { return setThreadDetails( null ); } public final CallTimer setThreadDetails( final String extraDetails ) { final Thread currentThread = Thread.currentThread(); if ( NO_THREAD == this.originalThreadId ) { this.originalThreadId = currentThread.getId(); this.originalThreadName = currentThread.getName(); } else if ( this.originalThreadId != currentThread.getId() ) { this.logger.error( String.format( "Expected thread ID: %s; name: %s; details: '%s'", this.originalThreadId, this.originalThreadName, extraDetails ) ); } assert currentThread.getId() == this.originalThreadId : String.format( "Thread ID mismatch: expected '%s'; actual '%s'", this.originalThreadId, currentThread.getId() ); final String name = String.format( THREAD_NAME_FORMAT, extraDetails == null ? "" : extraDetails + "; ", this.className, this.methodName, this.inputSize == 0 ? "" : ":" + String.valueOf( this.inputSize ), String.format( DATE_TIME_FORMAT, new Date( this.startMillis ) ), this.originalThreadName ); Thread.currentThread().setName( name ); return this; } private CallTimer setOutput( final Object output ) { this.output = output; return this; } private String normalizeOutputAndSize() { if ( this.output == null ) { if ( this.outputSize == null ) { this.outputSize = "-"; return "NULL"; } assert this.outputSize != null; // = method returned a serialized representation of the result class return "SER"; } assert this.output != null; final String result = normalizeOutMessage( this.output.getClass().getName() ); final Integer size = getSize( this.output ); this.outputSize = size == null ? "?" : size.toString(); return result; } final long durationInMillis() { return ( this.ticker.read() - this.startNanos ) / 1000000; } public void callEnd( final Throwable throwable ) { final long durationInMillis = durationInMillis(); if ( this.callEnded ) { return; } final String outputInfo; if ( throwable == null ) { outputInfo = normalizeOutputAndSize(); } else { outputInfo = "** " + normalizeOutMessage( throwable.toString() ) + " **"; this.outputSize = "E"; } this.output = null; final String msg = String.format( MSG_FORMAT, durationInMillis, this.inputSize, this.outputSize, outputInfo, this.methodName, this.className ); saveEvent( throwable, msg ); this.callEnded = true; restoreThreadName(); } protected final void restoreThreadName() { if ( NO_THREAD == this.originalThreadId ) { // Method 'setThreadDetails' hasn't been called return; } final Thread currentThread = Thread.currentThread(); if ( currentThread.getId() == this.originalThreadId ) { currentThread.setName( this.originalThreadName ); this.originalThreadId = NO_THREAD; this.originalThreadName = null; return; } this.logger.error( String.format( "Expected thread ID: %s; actual: %s; original name: %s", this.originalThreadId, currentThread.getId(), this.originalThreadName ) ); } public final void callEnd() { callEnd( (Throwable) null ); } public final void callEnd( final byte[] output ) { callEnd( output == null ? 0 : output.length ); } public final void callEnd( final long outputSize ) { setOutputSize( outputSize ).callEnd(); } public final void callEnd( final Object output ) { setOutput( output ).callEnd(); } @Override public String toString() { return String.format( TO_STRING_FORMAT, this.getClass().getSimpleName(), this.ticker, new Date( this.startMillis ), this.className, this.methodName, this.inputSize, this.outputSize, this.output, this.callEnded ); } @Override protected final void finalize() throws Throwable { if ( !this.callEnded ) { callEnd( new Throwable( "CALL NOT ENDED" ) ); } super.finalize(); } }
package io.tetrapod.core.logging; import java.io.*; import java.lang.reflect.Field; import java.time.*; import java.util.TimeZone; import org.slf4j.*; import io.tetrapod.core.*; import io.tetrapod.core.rpc.*; import io.tetrapod.core.serialize.datasources.*; import io.tetrapod.protocol.core.*; public class CommsLogEntry { public static final Logger logger = LoggerFactory.getLogger(CommsLogEntry.class); public final CommsLogHeader header; public final Structure struct; public final Object payload; public CommsLogEntry(CommsLogHeader header, Structure struct, Object payload) { assert header != null; assert struct != null; assert payload != null; this.header = header; this.struct = struct; this.payload = payload; } private static Structure readPayload(IOStreamDataSource data, CommsLogHeader header, int contractId, int structId) throws IOException { Structure payload = StructureFactory.make(contractId, structId); assert payload != null; if (payload != null) { payload.read(data); } return payload; } public static CommsLogEntry read(IOStreamDataSource data) throws IOException { CommsLogHeader header = new CommsLogHeader(); header.read(data); if (header.type == null) throw new IOException(); switch (header.type) { case MESSAGE: { MessageHeader msgHeader = new MessageHeader(); msgHeader.read(data); return new CommsLogEntry(header, msgHeader, readPayload(data, header, msgHeader.contractId, msgHeader.structId)); } case REQUEST: { RequestHeader reqHeader = new RequestHeader(); reqHeader.read(data); return new CommsLogEntry(header, reqHeader, readPayload(data, header, reqHeader.contractId, reqHeader.structId)); } case RESPONSE: { ResponseHeader resHeader = new ResponseHeader(); resHeader.read(data); return new CommsLogEntry(header, resHeader, readPayload(data, header, resHeader.contractId, resHeader.structId)); } case EVENT: throw new RuntimeException("Not yet supported"); } return null; } public void write(DataOutputStream out) throws IOException { assert header != null; assert struct != null; assert payload != null; IOStreamDataSource data = IOStreamDataSource.forWriting(out); header.write(data); struct.write(data); Structure struct = getPayloadStruct(); sanitize(struct); struct.write(data); } private Structure getPayloadStruct() { Structure struct = null; if (payload instanceof Structure) { struct = (Structure) payload; } else { struct = makeStructFromHeader(); if (struct != null) { try { struct.read(TempBufferDataSource.forReading((byte[]) payload)); } catch (IOException e) {} } } if (struct == null) { struct = new MissingStructDef(); } return struct; } private Structure makeStructFromHeader() { switch (header.type) { case MESSAGE: return StructureFactory.make(((MessageHeader) struct).contractId, ((MessageHeader) struct).structId); case REQUEST: return StructureFactory.make(((RequestHeader) struct).contractId, ((RequestHeader) struct).structId); case RESPONSE: return StructureFactory.make(((ResponseHeader) struct).contractId, ((ResponseHeader) struct).structId); default: return null; } } private void sanitize(Structure struct) throws IOException { try { for (Field f : struct.getClass().getFields()) { if (struct.isSensitive(f.getName())) { if (f.getType().isPrimitive()) { if (f.getType() == int.class) { f.setInt(struct, 0); } else if (f.getType() == long.class) { f.setLong(struct, 0L); } else if (f.getType() == byte.class) { f.setByte(struct, (byte) 0); } else if (f.getType() == short.class) { f.setShort(struct, (short) 0); } else if (f.getType() == boolean.class) { f.setBoolean(struct, false); } else if (f.getType() == boolean.class) { f.setChar(struct, (char) 0); } else if (f.getType() == double.class) { f.setDouble(struct, 0.0); } else if (f.getType() == float.class) { f.setFloat(struct, 0.0f); } } else { f.set(struct, null); } } } } catch (Exception e) { throw new IOException(e); } } public boolean matches(long minTime, long maxTime, long contextId) { if (header.timestamp >= minTime && header.timestamp <= maxTime) { switch (header.type) { case MESSAGE: { MessageHeader h = (MessageHeader) struct; return h.contextId == contextId; } case REQUEST: { RequestHeader h = (RequestHeader) struct; return h.contextId == contextId; } case RESPONSE: { ResponseHeader h = (ResponseHeader) struct; return h.contextId == contextId; } case EVENT: return false; } } return false; } public static String getNameFor(ResponseHeader header) { return StructureFactory.getName(header.contractId, header.structId); } public static String getNameFor(MessageHeader header) { return StructureFactory.getName(header.contractId, header.structId); } public static String getNameFor(RequestHeader header) { return StructureFactory.getName(header.contractId, header.structId); } @Override public String toString() { String ses = (header.sesType == SessionType.WEB ? "Http" : "Wire"); String direction = header.sending ? "->" : "<-"; long contextId = 0; String details = null; LocalDateTime dt = LocalDateTime.ofInstant(Instant.ofEpochSecond(header.timestamp / 1000), TimeZone.getDefault().toZoneId()); String time = dt.toString(); String name = null; Structure s = getPayloadStruct(); String payloadDetails = ""; if (s != null && s.getStructId() != Success.STRUCT_ID && s.getStructId() != io.tetrapod.core.rpc.Error.STRUCT_ID) { try { payloadDetails = s.dump(); } catch (Exception e) { logger.error(e.getMessage(), e); } } switch (header.type) { case MESSAGE: { MessageHeader h = (MessageHeader) struct; //boolean isBroadcast = h.toChildId == 0 && h.topicId != 1; name = getNameFor(h); details = String.format("to %d.%d t%d f%d", h.toParentId, h.toChildId, h.topicId, h.flags); break; } case REQUEST: { RequestHeader h = (RequestHeader) struct; contextId = h.contextId; name = getNameFor(h); details = String.format("from %d.%d, requestId=%d", h.fromParentId, h.fromChildId, h.requestId); break; } case RESPONSE: { ResponseHeader h = (ResponseHeader) struct; contextId = h.contextId; if (s != null && s.getStructId() == io.tetrapod.core.rpc.Error.STRUCT_ID) { io.tetrapod.core.rpc.Error e = (io.tetrapod.core.rpc.Error) s; name = Contract.getErrorCode(e.code, e.getContractId()); } else { name = getNameFor(h); } details = String.format("requestId=%d", h.requestId); break; } default: { details = ""; } } return String.format("%s [%016X] [%s-%d] %s %s (%s) %s", time, contextId, ses, header.sessionId, direction, name, details, payloadDetails); //return String.format("[%d] %s : %s : %s", header.timestamp, header.type, struct.dump(), ((Structure) payload).dump()); // System.out.println(header.timestamp + " " + header.type + " : " + struct.dump()); // if (payload instanceof Structure) { // System.out.println("\t" + ((Structure) payload).dump()); } }
package io.tetrapod.core.logging; import java.io.*; import java.lang.reflect.Field; import java.time.*; import java.util.TimeZone; import org.slf4j.*; import io.tetrapod.core.*; import io.tetrapod.core.rpc.*; import io.tetrapod.core.serialize.datasources.*; import io.tetrapod.protocol.core.*; public class CommsLogEntry { public static final Logger logger = LoggerFactory.getLogger(CommsLogEntry.class); public final CommsLogHeader header; public final Structure struct; public final Object payload; public CommsLogEntry(CommsLogHeader header, Structure struct, Object payload) { assert header != null; assert struct != null; assert payload != null; this.header = header; this.struct = struct; this.payload = payload; } private static Structure readPayload(IOStreamDataSource data, CommsLogHeader header, int contractId, int structId) throws IOException { Structure payload = StructureFactory.make(contractId, structId); if (payload != null) { payload.read(data); } else { logger.warn("Couldn't make structure for contractId={} structId={}", contractId, structId); } return payload; } public static CommsLogEntry read(IOStreamDataSource data) throws IOException { CommsLogHeader header = new CommsLogHeader(); header.read(data); if (header.type == null) throw new IOException(); switch (header.type) { case MESSAGE: { MessageHeader msgHeader = new MessageHeader(); msgHeader.read(data); return new CommsLogEntry(header, msgHeader, readPayload(data, header, msgHeader.contractId, msgHeader.structId)); } case REQUEST: { RequestHeader reqHeader = new RequestHeader(); reqHeader.read(data); return new CommsLogEntry(header, reqHeader, readPayload(data, header, reqHeader.contractId, reqHeader.structId)); } case RESPONSE: { ResponseHeader resHeader = new ResponseHeader(); resHeader.read(data); return new CommsLogEntry(header, resHeader, readPayload(data, header, resHeader.contractId, resHeader.structId)); } case EVENT: return null; } return null; } public void write(DataOutputStream out) throws IOException { assert header != null; assert struct != null; assert payload != null; IOStreamDataSource data = IOStreamDataSource.forWriting(out); header.write(data); struct.write(data); Structure struct = getPayloadStruct(); sanitize(struct); struct.write(data); } private Structure getPayloadStruct() { byte[] data = null; if (payload instanceof Structure) { try { TempBufferDataSource out = TempBufferDataSource.forWriting(); ((Structure) payload).write(out); data = (byte[]) out.getUnderlyingObject(); } catch (IOException e) {} } else { data = (byte[]) payload; } Structure struct = makeStructFromHeader(); if (struct != null) { try { struct.read(TempBufferDataSource.forReading(data)); } catch (IOException e) {} } if (struct == null) { struct = new MissingStructDef(); } return struct; } private Structure makeStructFromHeader() { switch (header.type) { case MESSAGE: return StructureFactory.make(((MessageHeader) struct).contractId, ((MessageHeader) struct).structId); case REQUEST: return StructureFactory.make(((RequestHeader) struct).contractId, ((RequestHeader) struct).structId); case RESPONSE: return StructureFactory.make(((ResponseHeader) struct).contractId, ((ResponseHeader) struct).structId); default: return null; } } private void sanitize(Structure struct) throws IOException { try { for (Field f : struct.getClass().getFields()) { if (struct.isSensitive(f.getName())) { if (f.getType().isPrimitive()) { if (f.getType() == int.class) { f.setInt(struct, 0); } else if (f.getType() == long.class) { f.setLong(struct, 0L); } else if (f.getType() == byte.class) { f.setByte(struct, (byte) 0); } else if (f.getType() == short.class) { f.setShort(struct, (short) 0); } else if (f.getType() == boolean.class) { f.setBoolean(struct, false); } else if (f.getType() == boolean.class) { f.setChar(struct, (char) 0); } else if (f.getType() == double.class) { f.setDouble(struct, 0.0); } else if (f.getType() == float.class) { f.setFloat(struct, 0.0f); } } else { f.set(struct, null); } } } } catch (Exception e) { throw new IOException(e); } } public boolean matches(long minTime, long maxTime, long contextId) { if (header.timestamp >= minTime && header.timestamp <= maxTime) { switch (header.type) { case MESSAGE: { MessageHeader h = (MessageHeader) struct; return contextId == 0 || h.contextId == contextId; } case REQUEST: { RequestHeader h = (RequestHeader) struct; return contextId == 0 || h.contextId == contextId; } case RESPONSE: { ResponseHeader h = (ResponseHeader) struct; return contextId == 0 || h.contextId == contextId; } case EVENT: return false; } } return false; } public static String getNameFor(ResponseHeader header) { return StructureFactory.getName(header.contractId, header.structId); } public static String getNameFor(MessageHeader header) { return StructureFactory.getName(header.contractId, header.structId); } public static String getNameFor(RequestHeader header) { return StructureFactory.getName(header.contractId, header.structId); } @Override public String toString() { String ses = (header.sesType == SessionType.WEB ? "Http" : "Wire"); String direction = header.sending ? "->" : "<-"; long contextId = 0; String details = null; LocalDateTime dt = LocalDateTime.ofInstant(Instant.ofEpochSecond(header.timestamp / 1000), TimeZone.getDefault().toZoneId()); String time = dt.toString(); String name = null; Structure s = getPayloadStruct(); String payloadDetails = ""; if (s != null && s.getStructId() != Success.STRUCT_ID && s.getStructId() != io.tetrapod.core.rpc.Error.STRUCT_ID) { try { payloadDetails = s.dump(); } catch (Exception e) { logger.error(e.getMessage(), e); } } switch (header.type) { case MESSAGE: { MessageHeader h = (MessageHeader) struct; contextId = h.contextId; //boolean isBroadcast = h.toChildId == 0 && h.topicId != 1; name = getNameFor(h); details = String.format("to %d.%d t%d f%d", h.toParentId, h.toChildId, h.topicId, h.flags); break; } case REQUEST: { RequestHeader h = (RequestHeader) struct; contextId = h.contextId; name = getNameFor(h); details = String.format("from %d.%d, requestId=%d", h.fromParentId, h.fromChildId, h.requestId); break; } case RESPONSE: { ResponseHeader h = (ResponseHeader) struct; contextId = h.contextId; if (s != null && s.getStructId() == io.tetrapod.core.rpc.Error.STRUCT_ID) { io.tetrapod.core.rpc.Error e = (io.tetrapod.core.rpc.Error) s; name = Contract.getErrorCode(e.code, e.getContractId()); } else { name = getNameFor(h); } details = String.format("requestId=%d", h.requestId); break; } default: { details = ""; } } return String.format("%s [%016X] [%s-%d] %s %s (%s) %s", time, contextId, ses, header.sessionId, direction, name, details, payloadDetails); //return String.format("[%d] %s : %s : %s", header.timestamp, header.type, struct.dump(), ((Structure) payload).dump()); // System.out.println(header.timestamp + " " + header.type + " : " + struct.dump()); // if (payload instanceof Structure) { // System.out.println("\t" + ((Structure) payload).dump()); } }
package com.xwray.groupie; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.DiffUtil; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * An adapter that holds a list of Groups. */ public class GroupAdapter<VH extends ViewHolder> extends RecyclerView.Adapter<VH> implements GroupDataObserver { private final List<Group> groups = new ArrayList<>(); private OnItemClickListener onItemClickListener; private OnItemLongClickListener onItemLongClickListener; private int spanCount = 1; private Item lastItemForViewTypeLookup; private AsyncDiffUtil.Callback diffUtilCallbacks = new AsyncDiffUtil.Callback() { @Override public void onDispatchAsyncResult(@NonNull Collection<? extends Group> newGroups) { setNewGroups(newGroups); } @Override public void onInserted(int position, int count) { notifyItemRangeInserted(position, count); } @Override public void onRemoved(int position, int count) { notifyItemRangeRemoved(position, count); } @Override public void onMoved(int fromPosition, int toPosition) { notifyItemMoved(fromPosition, toPosition); } @Override public void onChanged(int position, int count, Object payload) { notifyItemRangeChanged(position, count, payload); } }; private AsyncDiffUtil asyncDiffUtil = new AsyncDiffUtil(diffUtilCallbacks); private final GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { try { return getItem(position).getSpanSize(spanCount, position); } catch (IndexOutOfBoundsException e) { // Bug in support lib? TODO investigate further return spanCount; } } }; @NonNull public GridLayoutManager.SpanSizeLookup getSpanSizeLookup() { return spanSizeLookup; } public void setSpanCount(int spanCount) { this.spanCount = spanCount; } public int getSpanCount() { return spanCount; } /** * Updates the adapter with a new list that will be diffed on a background thread * and displayed once diff results are calculated. * * NOTE: This update method is NOT compatible with partial updates (change notifications * driven by individual groups and items). If you update using this method, all partial * updates will no longer work and you must use this method to update exclusively. * <br/> <br/> * If you want to receive a callback once the update is complete call the * {@link #updateAsync(List, boolean, OnAsyncUpdateListener)} version * * This will default detectMoves to true. * * @param newGroups List of {@link Group} */ @SuppressWarnings("unused") public void updateAsync(@NonNull final List<? extends Group> newGroups) { this.updateAsync(newGroups, true, null); } /** * Updates the adapter with a new list that will be diffed on a background thread * and displayed once diff results are calculated. * * NOTE: This update method is NOT compatible with partial updates (change notifications * driven by individual groups and items). If you update using this method, all partial * updates will no longer work and you must use this method to update exclusively. * <br/> <br/> * * This will default detectMoves to true. * * @see #updateAsync(List, boolean, OnAsyncUpdateListener) * @param newGroups List of {@link Group} */ @SuppressWarnings("unused") public void updateAsync(@NonNull final List<? extends Group> newGroups, @Nullable final OnAsyncUpdateListener onAsyncUpdateListener) { this.updateAsync(newGroups, true, onAsyncUpdateListener); } /** * Updates the adapter with a new list that will be diffed on a background thread * and displayed once diff results are calculated. * * NOTE: This update method is NOT compatible with partial updates (change notifications * driven by individual groups and items). If you update using this method, all partial * updates will no longer work and you must use this method to update exclusively. * * @param newGroups List of {@link Group} * @param onAsyncUpdateListener Optional callback for when the async update is complete * @param detectMoves Boolean is passed to {@link DiffUtil#calculateDiff(DiffUtil.Callback, boolean)}. Set to true * if you want DiffUtil to detect moved items. */ @SuppressWarnings("unused") public void updateAsync(@NonNull final List<? extends Group> newGroups, boolean detectMoves, @Nullable final OnAsyncUpdateListener onAsyncUpdateListener) { final List<Group> oldGroups = new ArrayList<>(groups); final int oldBodyItemCount = getItemCount(oldGroups); final int newBodyItemCount = getItemCount(newGroups); final DiffCallback diffUtilCallback = new DiffCallback(oldBodyItemCount, newBodyItemCount, oldGroups, newGroups); asyncDiffUtil.calculateDiff(newGroups, diffUtilCallback, onAsyncUpdateListener, detectMoves); } /** * Updates the adapter with a new list that will be diffed on the <em>main</em> thread * and displayed once diff results are calculated. Not recommended for huge lists. * * This will default detectMoves to true. * * @param newGroups List of {@link Group} */ @SuppressWarnings("unused") public void update(@NonNull final Collection<? extends Group> newGroups) { update(newGroups, true); } /** * Updates the adapter with a new list that will be diffed on the <em>main</em> thread * and displayed once diff results are calculated. Not recommended for huge lists. * @param newGroups List of {@link Group} * @param detectMoves is passed to {@link DiffUtil#calculateDiff(DiffUtil.Callback, boolean)}. Set to false * if you don't want DiffUtil to detect moved items. */ @SuppressWarnings("unused") public void update(@NonNull final Collection<? extends Group> newGroups, boolean detectMoves) { final List<Group> oldGroups = new ArrayList<>(groups); final int oldBodyItemCount = getItemCount(oldGroups); final int newBodyItemCount = getItemCount(newGroups); final DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff( new DiffCallback(oldBodyItemCount, newBodyItemCount, oldGroups, newGroups), detectMoves ); setNewGroups(newGroups); diffResult.dispatchUpdatesTo(diffUtilCallbacks); } /** * Optionally register an {@link OnItemClickListener} that listens to click at the root of * each Item where {@link Item#isClickable()} returns true * * @param onItemClickListener The click listener to set */ public void setOnItemClickListener(@Nullable OnItemClickListener onItemClickListener) { this.onItemClickListener = onItemClickListener; } /** * Optionally register an {@link OnItemLongClickListener} that listens to long click at the root of * each Item where {@link Item#isLongClickable()} returns true * * @param onItemLongClickListener The long click listener to set */ public void setOnItemLongClickListener(@Nullable OnItemLongClickListener onItemLongClickListener) { this.onItemLongClickListener = onItemLongClickListener; } @Override @NonNull public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); Item<VH> item = getItemForViewType(viewType); View itemView = inflater.inflate(item.getLayout(), parent, false); return item.createViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull VH holder, int position) { // Never called (all binds go through the version with payload) } @Override public void onBindViewHolder(@NonNull VH holder, int position, @NonNull List<Object> payloads) { Item contentItem = getItem(position); contentItem.bind(holder, position, payloads, onItemClickListener, onItemLongClickListener); } @Override public void onViewRecycled(@NonNull VH holder) { Item contentItem = holder.getItem(); contentItem.unbind(holder); } @Override public boolean onFailedToRecycleView(@NonNull VH holder) { Item contentItem = holder.getItem(); return contentItem.isRecyclable(); } @Override public int getItemViewType(int position) { lastItemForViewTypeLookup = getItem(position); if (lastItemForViewTypeLookup == null) throw new RuntimeException("Invalid position " + position); return lastItemForViewTypeLookup.getViewType(); } @Override public long getItemId(int position) { return getItem(position).getId(); } public @NonNull Item getItem(@NonNull VH holder) { return holder.getItem(); } private static Item getItem(Collection<? extends Group> groups, int position) { int count = 0; for (Group group : groups) { if (position < count + group.getItemCount()) { return group.getItem(position - count); } else { count += group.getItemCount(); } } throw new IndexOutOfBoundsException("Requested position " + position + "in group adapter " + "but there are only " + count + " items"); } public @NonNull Item getItem(int position) { return getItem(groups, position); } public int getAdapterPosition(@NonNull Item contentItem) { int count = 0; for (Group group : groups) { int index = group.getPosition(contentItem); if (index >= 0) return index + count; count += group.getItemCount(); } return -1; } /** * The position in the flat list of individual items at which the group starts * * @param group * @return */ public int getAdapterPosition(@NonNull Group group) { int index = groups.indexOf(group); if (index == -1) return -1; int position = 0; for (int i = 0; i < index; i++) { position += groups.get(i).getItemCount(); } return position; } /** * Returns the number of top-level groups present in the adapter. */ public int getGroupCount() { return groups.size(); } private static int getItemCount(Collection<? extends Group> groups) { int count = 0; for (Group group : groups) { count += group.getItemCount(); } return count; } @Override public int getItemCount() { return getItemCount(groups); } public int getItemCount(int groupIndex) { if (groupIndex >= groups.size()) { throw new IndexOutOfBoundsException("Requested group index " + groupIndex + " but there are " + groups.size() + " groups"); } return groups.get(groupIndex).getItemCount(); } public void clear() { for (Group group : groups) { group.unregisterGroupDataObserver(this); } groups.clear(); notifyDataSetChanged(); } public void add(@NonNull Group group) { if (group == null) throw new RuntimeException("Group cannot be null"); int itemCountBeforeGroup = getItemCount(); group.registerGroupDataObserver(this); groups.add(group); notifyItemRangeInserted(itemCountBeforeGroup, group.getItemCount()); } /** * Adds the contents of the list of groups, in order, to the end of the adapter contents. * All groups in the list must be non-null. * * @param groups */ public void addAll(@NonNull Collection<? extends Group> groups) { if (groups.contains(null)) throw new RuntimeException("List of groups can't contain null!"); int itemCountBeforeGroup = getItemCount(); int additionalSize = 0; for (Group group : groups) { additionalSize += group.getItemCount(); group.registerGroupDataObserver(this); } this.groups.addAll(groups); notifyItemRangeInserted(itemCountBeforeGroup, additionalSize); } public void remove(@NonNull Group group) { if (group == null) throw new RuntimeException("Group cannot be null"); int position = groups.indexOf(group); remove(position, group); } public void removeAll(@NonNull Collection<? extends Group> groups) { for (Group group : groups) { remove(group); } } public void removeGroup(int index) { Group group = getGroup(index); remove(index, group); } private void remove(int position, @NonNull Group group) { int itemCountBeforeGroup = getItemCountBeforeGroup(position); group.unregisterGroupDataObserver(this); groups.remove(position); notifyItemRangeRemoved(itemCountBeforeGroup, group.getItemCount()); } public void add(int index, @NonNull Group group) { if (group == null) throw new RuntimeException("Group cannot be null"); group.registerGroupDataObserver(this); groups.add(index, group); int itemCountBeforeGroup = getItemCountBeforeGroup(index); notifyItemRangeInserted(itemCountBeforeGroup, group.getItemCount()); } /** * Get group, given a raw position in the list. * * @param position * @return */ @SuppressWarnings("WeakerAccess") @NonNull public Group getGroup(int position) { int previous = 0; int size; for (Group group : groups) { size = group.getItemCount(); if (position - previous < size) return group; previous += group.getItemCount(); } throw new IndexOutOfBoundsException("Requested position " + position + " in group adapter " + "but there are only " + previous + " items"); } private int getItemCountBeforeGroup(int groupIndex) { int count = 0; for (Group group : groups.subList(0, groupIndex)) { count += group.getItemCount(); } return count; } @NonNull public Group getGroup(Item contentItem) { for (Group group : groups) { if (group.getPosition(contentItem) >= 0) { return group; } } throw new IndexOutOfBoundsException("Item is not present in adapter or in any group"); } private void setNewGroups(@NonNull Collection<? extends Group> newGroups) { for (Group group : groups) { group.unregisterGroupDataObserver(this); } groups.clear(); groups.addAll(newGroups); for (Group group : newGroups) { group.registerGroupDataObserver(this); } } @Override public void onChanged(@NonNull Group group) { notifyItemRangeChanged(getAdapterPosition(group), group.getItemCount()); } @Override public void onItemInserted(@NonNull Group group, int position) { notifyItemInserted(getAdapterPosition(group) + position); } @Override public void onItemChanged(@NonNull Group group, int position) { notifyItemChanged(getAdapterPosition(group) + position); } @Override public void onItemChanged(@NonNull Group group, int position, Object payload) { notifyItemChanged(getAdapterPosition(group) + position, payload); } @Override public void onItemRemoved(@NonNull Group group, int position) { notifyItemRemoved(getAdapterPosition(group) + position); } @Override public void onItemRangeChanged(@NonNull Group group, int positionStart, int itemCount) { notifyItemRangeChanged(getAdapterPosition(group) + positionStart, itemCount); } @Override public void onItemRangeChanged(@NonNull Group group, int positionStart, int itemCount, Object payload) { notifyItemRangeChanged(getAdapterPosition(group) + positionStart, itemCount, payload); } @Override public void onItemRangeInserted(@NonNull Group group, int positionStart, int itemCount) { notifyItemRangeInserted(getAdapterPosition(group) + positionStart, itemCount); } @Override public void onItemRangeRemoved(@NonNull Group group, int positionStart, int itemCount) { notifyItemRangeRemoved(getAdapterPosition(group) + positionStart, itemCount); } @Override public void onItemMoved(@NonNull Group group, int fromPosition, int toPosition) { int groupAdapterPosition = getAdapterPosition(group); notifyItemMoved(groupAdapterPosition + fromPosition, groupAdapterPosition + toPosition); } /** * This idea was copied from Epoxy. :wave: Bright idea guys! * <p> * Find the model that has the given view type so we can create a viewholder for that model. * <p> * To make this efficient, we rely on the RecyclerView implementation detail that {@link * GroupAdapter#getItemViewType(int)} is called immediately before {@link * GroupAdapter#onCreateViewHolder(android.view.ViewGroup, int)}. We cache the last model * that had its view type looked up, and unless that implementation changes we expect to have a * very fast lookup for the correct model. * <p> * To be safe, we fallback to searching through all models for a view type match. This is slow and * shouldn't be needed, but is a guard against RecyclerView behavior changing. */ private Item<VH> getItemForViewType(int viewType) { if (lastItemForViewTypeLookup != null && lastItemForViewTypeLookup.getViewType() == viewType) { // We expect this to be a hit 100% of the time return lastItemForViewTypeLookup; } // To be extra safe in case RecyclerView implementation details change... for (int i = 0; i < getItemCount(); i++) { Item item = getItem(i); if (item.getViewType() == viewType) { return item; } } throw new IllegalStateException("Could not find model for view type: " + viewType); } private static class DiffCallback extends DiffUtil.Callback { private final int oldBodyItemCount; private final int newBodyItemCount; private final Collection<? extends Group> oldGroups; private final Collection<? extends Group> newGroups; DiffCallback(int oldBodyItemCount, int newBodyItemCount, Collection<? extends Group> oldGroups, Collection<? extends Group> newGroups) { this.oldBodyItemCount = oldBodyItemCount; this.newBodyItemCount = newBodyItemCount; this.oldGroups = oldGroups; this.newGroups = newGroups; } @Override public int getOldListSize() { return oldBodyItemCount; } @Override public int getNewListSize() { return newBodyItemCount; } @Override public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) { Item oldItem = getItem(oldGroups, oldItemPosition); Item newItem = getItem(newGroups, newItemPosition); return newItem.isSameAs(oldItem); } @Override public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) { Item oldItem = getItem(oldGroups, oldItemPosition); Item newItem = getItem(newGroups, newItemPosition); return newItem.equals(oldItem); } @Nullable @Override public Object getChangePayload(int oldItemPosition, int newItemPosition) { Item oldItem = getItem(oldGroups, oldItemPosition); Item newItem = getItem(newGroups, newItemPosition); return oldItem.getChangePayload(newItem); } } }
package ucar.nc2.iosp.grid; import ucar.nc2.*; import ucar.nc2.iosp.AbstractIOServiceProvider; import ucar.nc2.constants._Coordinate; import ucar.nc2.constants.FeatureType; import ucar.nc2.dt.fmr.FmrcCoordSys; import ucar.nc2.units.DateFormatter; import ucar.nc2.util.CancelTask; import ucar.grid.*; import java.io.*; import java.util.*; public class GridIndexToNC { /** logger */ static private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(GridIndexToNC.class); /** map of horizontal coordinate systems */ private HashMap hcsHash = new HashMap(10); // GridHorizCoordSys /** date formattter */ private DateFormatter formatter = new DateFormatter(); /** debug flag */ private boolean debug = false; /** flag for using GridParameter description for variable names */ private boolean useDescriptionForVariableName = true; //TODO: how to make format specific names if these are static /** * Make the level name * * @param gr grid record * @param lookup lookup table * * @return name for the level */ public static String makeLevelName(GridRecord gr, GridTableLookup lookup) { String vname = lookup.getLevelName(gr); boolean isGrib1 = true; // same for GEMPAK if (isGrib1) { return vname; } // for grib2, we need to add the layer to disambiguate return lookup.isLayer(gr) ? vname + "_layer" : vname; } /** * Make the variable name * * @param gr grid record * @param lookup lookup table * * @return variable name */ public String makeVariableName(GridRecord gr, GridTableLookup lookup) { GridParameter param = lookup.getParameter(gr); String levelName = makeLevelName(gr, lookup); String paramName = (useDescriptionForVariableName) ? param.getDescription() : param.getName(); return (levelName.length() == 0) ? paramName : paramName + "_" + levelName; } /** * TODO: moved to GridVariable = made sense since it knows what it is * Make a long name for the variable * * @param gr grid record * @param lookup lookup table * * @return long variable name public static String makeLongName(GridRecord gr, GridTableLookup lookup) { GridParameter param = lookup.getParameter(gr); String levelName = makeLevelName(gr, lookup); return (levelName.length() == 0) ? param.getDescription() : param.getDescription() + " @ " + makeLevelName(gr, lookup); } */ /** * Fill in the netCDF file * * @param index grid index * @param lookup lookup table * @param version version of data * @param ncfile netCDF file to fill in * @param fmrcCoordSys forecast model run CS * @param cancelTask cancel task * * @throws IOException Problem reading from the file */ public void open(GridIndex index, GridTableLookup lookup, int version, NetcdfFile ncfile, FmrcCoordSys fmrcCoordSys, CancelTask cancelTask) throws IOException { // create the HorizCoord Systems : one for each gds List hcsList = index.getHorizCoordSys(); boolean needGroups = (hcsList.size() > 1); for (int i = 0; i < hcsList.size(); i++) { GridDefRecord gdsIndex = (GridDefRecord) hcsList.get(i); Group g = null; if (needGroups) { //g = new Group(ncfile, null, "proj" + i); g = new Group(ncfile, null, gdsIndex.getGroupName()); ncfile.addGroup(null, g); } // (GridDefRecord gdsIndex, String grid_name, String shape_name, Group g) GridHorizCoordSys hcs = new GridHorizCoordSys(gdsIndex, lookup, g); hcsHash.put(gdsIndex.getParam(gdsIndex.GDS_KEY), hcs); } // run through each record GridRecord firstRecord = null; List records = index.getGridRecords(); if (GridServiceProvider.debugOpen) { System.out.println(" number of products = " + records.size()); } for (int i = 0; i < records.size(); i++) { GridRecord gribRecord = (GridRecord) records.get(i); if (firstRecord == null) { firstRecord = gribRecord; } GridHorizCoordSys hcs = (GridHorizCoordSys) hcsHash.get( gribRecord.getGridDefRecordId()); String name = makeVariableName(gribRecord, lookup); GridVariable pv = (GridVariable) hcs.varHash.get(name); // combo gds, param name and level name if (null == pv) { String pname = lookup.getParameter(gribRecord).getDescription(); pv = new GridVariable(name, pname, hcs, lookup); hcs.varHash.put(name, pv); // keep track of all products with same parameter name ArrayList plist = (ArrayList) hcs.productHash.get(pname); if (null == plist) { plist = new ArrayList(); hcs.productHash.put(pname, plist); } plist.add(pv); } pv.addProduct(gribRecord); } // global stuff ncfile.addAttribute(null, new Attribute("Conventions", "CF-1.0")); /* TODO: figure out what to do with these String creator = lookup.getFirstCenterName() + " subcenter = "+lookup.getFirstSubcenterId(); if (creator != null) ncfile.addAttribute(null, new Attribute("Originating_center", creator) ); String genType = lookup.getTypeGenProcessName( firstRecord); if (genType != null) ncfile.addAttribute(null, new Attribute("Generating_Process_or_Model", genType) ); if (null != lookup.getFirstProductStatusName()) ncfile.addAttribute(null, new Attribute("Product_Status", lookup.getFirstProductStatusName()) ); ncfile.addAttribute(null, new Attribute("Product_Type", lookup.getFirstProductTypeName()) ); */ // dataset discovery ncfile.addAttribute(null, new Attribute("cdm_data_type", FeatureType.GRID.toString())); String gridType = lookup.getGridType(); //ncfile.addAttribute(null, new Attribute("creator_name", creator)); ncfile.addAttribute(null, new Attribute("file_format", gridType+"-"+version)); ncfile.addAttribute(null, new Attribute("location", ncfile.getLocation())); ncfile.addAttribute( null, new Attribute( "history", "Direct read of "+gridType+" into NetCDF-Java 2.2 API")); ncfile.addAttribute( null, new Attribute( _Coordinate.ModelRunDate, formatter.toDateTimeStringISO(lookup.getFirstBaseTime()))); if (fmrcCoordSys != null) { makeDefinedCoordSys(ncfile, lookup, fmrcCoordSys); /* else if (GribServiceProvider.useMaximalCoordSys) makeMaximalCoordSys(ncfile, lookup, cancelTask); */ } else { makeDenseCoordSys(ncfile, lookup, cancelTask); } if (GridServiceProvider.debugMissing) { int count = 0; Iterator iterHcs = hcsHash.values().iterator(); while (iterHcs.hasNext()) { GridHorizCoordSys hcs = (GridHorizCoordSys) iterHcs.next(); ArrayList gribvars = new ArrayList(hcs.varHash.values()); for (int i = 0; i < gribvars.size(); i++) { GridVariable gv = (GridVariable) gribvars.get(i); count += gv.dumpMissingSummary(); } } System.out.println(" total missing= " + count); } if (GridServiceProvider.debugMissingDetails) { Iterator iterHcs = hcsHash.values().iterator(); while (iterHcs.hasNext()) { // loop over HorizCoordSys GridHorizCoordSys hcs = (GridHorizCoordSys) iterHcs.next(); System.out.println("******** Horiz Coordinate= " + hcs.getGridName()); String lastVertDesc = null; ArrayList gribvars = new ArrayList(hcs.varHash.values()); Collections.sort(gribvars, new CompareGridVariableByVertName()); for (int i = 0; i < gribvars.size(); i++) { GridVariable gv = (GridVariable) gribvars.get(i); String vertDesc = gv.getVertName(); if ( !vertDesc.equals(lastVertDesc)) { System.out.println("---Vertical Coordinate= " + vertDesc); lastVertDesc = vertDesc; } gv.dumpMissing(); } } } } /** * Make coordinate system without missing data - means that we * have to make a coordinate axis for each unique set * of time or vertical levels. * * @param ncfile netCDF file * @param lookup lookup table * @param cancelTask cancel task * * @throws IOException problem reading file */ private void makeDenseCoordSys(NetcdfFile ncfile, GridTableLookup lookup, CancelTask cancelTask) throws IOException { ArrayList timeCoords = new ArrayList(); ArrayList vertCoords = new ArrayList(); // loop over HorizCoordSys Iterator iterHcs = hcsHash.values().iterator(); while (iterHcs.hasNext()) { GridHorizCoordSys hcs = (GridHorizCoordSys) iterHcs.next(); // loop over GridVariables in the HorizCoordSys // create the time and vertical coordinates Iterator iter = hcs.varHash.values().iterator(); while (iter.hasNext()) { GridVariable pv = (GridVariable) iter.next(); List recordList = pv.getRecords(); GridRecord record = (GridRecord) recordList.get(0); String vname = makeLevelName(record, lookup); // look to see if vertical already exists GridVertCoord useVertCoord = null; for (int i = 0; i < vertCoords.size(); i++) { GridVertCoord gvcs = (GridVertCoord) vertCoords.get(i); if (vname.equals(gvcs.getLevelName())) { if (gvcs.matchLevels(recordList)) { // must have the same levels useVertCoord = gvcs; } } } if (useVertCoord == null) { // nope, got to create it useVertCoord = new GridVertCoord(recordList, vname, lookup); vertCoords.add(useVertCoord); } pv.setVertCoord(useVertCoord); // look to see if time coord already exists GridTimeCoord useTimeCoord = null; for (int i = 0; i < timeCoords.size(); i++) { GridTimeCoord gtc = (GridTimeCoord) timeCoords.get(i); if (gtc.matchLevels(recordList)) { // must have the same levels useTimeCoord = gtc; } } if (useTimeCoord == null) { // nope, got to create it useTimeCoord = new GridTimeCoord(recordList, lookup); timeCoords.add(useTimeCoord); } pv.setTimeCoord(useTimeCoord); } //// assign time coordinate names // find time dimensions with largest length GridTimeCoord tcs0 = null; int maxTimes = 0; for (int i = 0; i < timeCoords.size(); i++) { GridTimeCoord tcs = (GridTimeCoord) timeCoords.get(i); if (tcs.getNTimes() > maxTimes) { tcs0 = tcs; maxTimes = tcs.getNTimes(); } } // add time dimensions, give time dimensions unique names int seqno = 1; for (int i = 0; i < timeCoords.size(); i++) { GridTimeCoord tcs = (GridTimeCoord) timeCoords.get(i); if (tcs != tcs0) { tcs.setSequence(seqno++); } tcs.addDimensionsToNetcdfFile(ncfile, hcs.getGroup()); } // add x, y dimensions hcs.addDimensionsToNetcdfFile(ncfile); // add vertical dimensions, give them unique names Collections.sort(vertCoords); int vcIndex = 0; String listName = null; int start = 0; for (vcIndex = 0; vcIndex < vertCoords.size(); vcIndex++) { GridVertCoord gvcs = (GridVertCoord) vertCoords.get(vcIndex); String vname = gvcs.getLevelName(); if (listName == null) { listName = vname; // initial } if ( !vname.equals(listName)) { makeVerticalDimensions(vertCoords.subList(start, vcIndex), ncfile, hcs.getGroup()); listName = vname; start = vcIndex; } } makeVerticalDimensions(vertCoords.subList(start, vcIndex), ncfile, hcs.getGroup()); // create a variable for each entry, but check for other products with same desc // to disambiguate by vertical coord ArrayList products = new ArrayList(hcs.productHash.values()); Collections.sort(products, new CompareGridVariableListByName()); for (int i = 0; i < products.size(); i++) { ArrayList plist = (ArrayList) products.get(i); // all the products with the same name if (plist.size() == 1) { GridVariable pv = (GridVariable) plist.get(0); Variable v = pv.makeVariable(ncfile, hcs.getGroup(), useDescriptionForVariableName); ncfile.addVariable(hcs.getGroup(), v); } else { Collections.sort( plist, new CompareGridVariableByNumberVertLevels()); /* find the one with the most vertical levels int maxLevels = 0; GridVariable maxV = null; for (int j = 0; j < plist.size(); j++) { GridVariable pv = (GridVariable) plist.get(j); if (pv.getVertCoord().getNLevels() > maxLevels) { maxLevels = pv.getVertCoord().getNLevels(); maxV = pv; } } */ // finally, add the variables for (int k = 0; k < plist.size(); k++) { GridVariable pv = (GridVariable) plist.get(k); //int nlevels = pv.getVertNlevels(); //boolean useDesc = (k == 0) && (nlevels > 1); // keep using the level name if theres only one level // TODO: is there a better way to do this? boolean useDesc = (k==0 && useDescriptionForVariableName); ncfile.addVariable(hcs.getGroup(), pv.makeVariable(ncfile, hcs.getGroup(), useDesc)); } } // multipe vertical levels } // create variable // add coordinate variables at the end for (int i = 0; i < timeCoords.size(); i++) { GridTimeCoord tcs = (GridTimeCoord) timeCoords.get(i); tcs.addToNetcdfFile(ncfile, hcs.getGroup()); } hcs.addToNetcdfFile(ncfile); for (int i = 0; i < vertCoords.size(); i++) { GridVertCoord gvcs = (GridVertCoord) vertCoords.get(i); gvcs.addToNetcdfFile(ncfile, hcs.getGroup()); } } // loop over hcs } /** * Make a vertical dimensions * * @param vertCoordList vertCoords all with the same name * @param ncfile netCDF file to add to * @param group group in ncfile */ private void makeVerticalDimensions(List vertCoordList, NetcdfFile ncfile, Group group) { // find biggest vert coord GridVertCoord gvcs0 = null; int maxLevels = 0; for (int i = 0; i < vertCoordList.size(); i++) { GridVertCoord gvcs = (GridVertCoord) vertCoordList.get(i); if (gvcs.getNLevels() > maxLevels) { gvcs0 = gvcs; maxLevels = gvcs.getNLevels(); } } int seqno = 1; for (int i = 0; i < vertCoordList.size(); i++) { GridVertCoord gvcs = (GridVertCoord) vertCoordList.get(i); if (gvcs != gvcs0) { gvcs.setSequence(seqno++); } gvcs.addDimensionsToNetcdfFile(ncfile, group); } } /** * Make coordinate system from a Definition object * * @param ncfile netCDF file to add to * @param lookup lookup table * @param fmr FmrcCoordSys * * @throws IOException problem reading from file */ private void makeDefinedCoordSys(NetcdfFile ncfile, GridTableLookup lookup, FmrcCoordSys fmr) throws IOException { ArrayList timeCoords = new ArrayList(); ArrayList vertCoords = new ArrayList(); ArrayList removeVariables = new ArrayList(); // loop over HorizCoordSys Iterator iterHcs = hcsHash.values().iterator(); while (iterHcs.hasNext()) { GridHorizCoordSys hcs = (GridHorizCoordSys) iterHcs.next(); // loop over GridVariables in the HorizCoordSys // create the time and vertical coordinates Iterator iterKey = hcs.varHash.keySet().iterator(); while (iterKey.hasNext()) { String key = (String) iterKey.next(); GridVariable pv = (GridVariable) hcs.varHash.get(key); GridRecord record = pv.getFirstRecord(); // we dont know the name for sure yet, so have to try several String searchName = findVariableName(ncfile, record, lookup, fmr); System.out.println("Search name = " + searchName); if (searchName == null) { // cant find - just remove System.out.println("removing " + searchName); removeVariables.add(key); // cant remove (concurrentModException) so save for later continue; } pv.setVarName(searchName); // get the vertical coordinate for this variable, if it exists FmrcCoordSys.VertCoord vc_def = fmr.findVertCoordForVariable(searchName); if (vc_def != null) { String vc_name = vc_def.getName(); // look to see if GridVertCoord already made GridVertCoord useVertCoord = null; for (int i = 0; i < vertCoords.size(); i++) { GridVertCoord gvcs = (GridVertCoord) vertCoords.get(i); if (vc_name.equals(gvcs.getLevelName())) { useVertCoord = gvcs; } } if (useVertCoord == null) { // nope, got to create it useVertCoord = new GridVertCoord(record, vc_name, lookup, vc_def.getValues1(), vc_def.getValues2()); useVertCoord.addDimensionsToNetcdfFile(ncfile, hcs.getGroup()); vertCoords.add(useVertCoord); } pv.setVertCoord(useVertCoord); } else { pv.setVertCoord(new GridVertCoord(searchName)); // fake } // get the time coordinate for this variable FmrcCoordSys.TimeCoord tc_def = fmr.findTimeCoordForVariable(searchName, lookup.getFirstBaseTime()); String tc_name = tc_def.getName(); // look to see if GridTimeCoord already made GridTimeCoord useTimeCoord = null; for (int i = 0; i < timeCoords.size(); i++) { GridTimeCoord gtc = (GridTimeCoord) timeCoords.get(i); if (tc_name.equals(gtc.getName())) { useTimeCoord = gtc; } } if (useTimeCoord == null) { // nope, got to create it useTimeCoord = new GridTimeCoord(tc_name, tc_def.getOffsetHours(), lookup); useTimeCoord.addDimensionsToNetcdfFile(ncfile, hcs.getGroup()); timeCoords.add(useTimeCoord); } pv.setTimeCoord(useTimeCoord); } // any need to be removed? for (int i = 0; i < removeVariables.size(); i++) { String key = (String) removeVariables.get(i); hcs.varHash.remove(key); } // add x, y dimensions hcs.addDimensionsToNetcdfFile(ncfile); // create a variable for each entry Iterator iter2 = hcs.varHash.values().iterator(); while (iter2.hasNext()) { GridVariable pv = (GridVariable) iter2.next(); Variable v = pv.makeVariable(ncfile, hcs.getGroup(), true); ncfile.addVariable(hcs.getGroup(), v); } // add coordinate variables at the end for (int i = 0; i < timeCoords.size(); i++) { GridTimeCoord tcs = (GridTimeCoord) timeCoords.get(i); tcs.addToNetcdfFile(ncfile, hcs.getGroup()); } hcs.addToNetcdfFile(ncfile); for (int i = 0; i < vertCoords.size(); i++) { GridVertCoord gvcs = (GridVertCoord) vertCoords.get(i); gvcs.addToNetcdfFile(ncfile, hcs.getGroup()); } } // loop over hcs if (debug) { System.out.println("GridIndexToNC.makeDefinedCoordSys for " + ncfile.getLocation()); } } /** * Find the variable name for the grid * * @param ncfile netCDF file * @param gr grid record * @param lookup lookup table * @param fmr FmrcCoordSys * * @return name for the grid */ private String findVariableName(NetcdfFile ncfile, GridRecord gr, GridTableLookup lookup, FmrcCoordSys fmr) { // first lookup with name & vert name String name = AbstractIOServiceProvider.createValidNetcdfObjectName(makeVariableName(gr, lookup)); if (fmr.hasVariable(name)) { return name; } // now try just the name String pname = AbstractIOServiceProvider.createValidNetcdfObjectName( lookup.getParameter(gr).getDescription()); if (fmr.hasVariable(pname)) { return pname; } logger.warn( "GridIndexToNC: FmrcCoordSys does not have the variable named =" + name + " or " + pname + " for file " + ncfile.getLocation()); return null; } /** * Comparable object for grid variable * * * @author IDV Development Team * @version $Revision: 1.3 $ */ private class CompareGridVariableListByName implements Comparator { /** * Compare the two lists of names * * @param o1 first list * @param o2 second list * * @return comparison */ public int compare(Object o1, Object o2) { ArrayList list1 = (ArrayList) o1; ArrayList list2 = (ArrayList) o2; GridVariable gv1 = (GridVariable) list1.get(0); GridVariable gv2 = (GridVariable) list2.get(0); return gv1.getName().compareToIgnoreCase(gv2.getName()); } } /** * Comparator for grids by vertical variable name * * @author IDV Development Team * @version $Revision: 1.3 $ */ private class CompareGridVariableByVertName implements Comparator { /** * Compare the two lists of names * * @param o1 first list * @param o2 second list * * @return comparison */ public int compare(Object o1, Object o2) { GridVariable gv1 = (GridVariable) o1; GridVariable gv2 = (GridVariable) o2; return gv1.getVertName().compareToIgnoreCase(gv2.getVertName()); } } /** * Comparator for grid variables by number of vertical levels * * @author IDV Development Team * @version $Revision: 1.3 $ */ private class CompareGridVariableByNumberVertLevels implements Comparator { /** * Compare the two lists of names * * @param o1 first list * @param o2 second list * * @return comparison */ public int compare(Object o1, Object o2) { GridVariable gv1 = (GridVariable) o1; GridVariable gv2 = (GridVariable) o2; int n1 = gv1.getVertCoord().getNLevels(); int n2 = gv2.getVertCoord().getNLevels(); if (n1 == n2) { // break ties for consistency return gv1.getVertCoord().getLevelName().compareTo( gv2.getVertCoord().getLevelName()); } else { return n2 - n1; // highest number first } } } /** * Should use the description for the variable name. * @param value false to use name instead of description */ public void setUseDescriptionForVariableName(boolean value) { useDescriptionForVariableName = value; } }
package ru.job4j.concurrent; /** * Wget. * * @author Ivan Belyaev * @version 1.0 * @since 12.05.2020 */ public class Wget { /** * Entry point. * @param args command line arguments. Not used. * @throws InterruptedException exception. */ public static void main(String[] args) throws InterruptedException { Thread progress = new Thread( () -> { for (int index = 0; index <= 100; index++) { if (Thread.currentThread().isInterrupted()) { break; } System.out.print("\rLoading : " + index + "%"); try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.printf("%nLoading interrupted%n"); Thread.currentThread().interrupt(); } } } ); progress.start(); Thread.sleep(10000); progress.interrupt(); progress.join(); } }
package de.aima13.whoami.modules; import de.aima13.whoami.Analyzable; import de.aima13.whoami.support.Utilities; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.SortedMap; public class CodeStatistics implements Analyzable { private final FileExtension[] fileExtensions; private class FileExtension { public String ext; public String lang; } public CodeStatistics() { fileExtensions = Utilities.loadDataFromJson("/data/CodeStatistics_FileExtensions.json", FileExtension[].class); for (FileExtension fileExtension : fileExtensions) { System.out.println(fileExtension.ext + "->" + fileExtension.lang); } System.exit(0); } @Override public List<String> getFilter() { List<String> filter = new ArrayList<>(); for (FileExtension fileExtension : this.fileExtensions) { filter.add("**." + fileExtension.ext); } return filter; } @Override public void setFileInputs(List<Path> files) throws Exception { } @Override public String getHtml() { return null; } @Override public String getReportTitle() { return null; } @Override public String getCsvPrefix() { return null; } @Override public SortedMap<String, String> getCsvContent() { return null; } @Override public void run() { } }
package com.raizunne.miscellany.gui; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import com.raizunne.miscellany.MiscBlocks; import com.raizunne.miscellany.MiscItems; import com.raizunne.miscellany.gui.button.ButtonLeft; import com.raizunne.miscellany.gui.button.ButtonMenu; import com.raizunne.miscellany.gui.button.ButtonNormal; import com.raizunne.miscellany.gui.button.ButtonRight; import com.raizunne.miscellany.util.BookResources; public class GuiManualBooks extends GuiScreen{ public static final ResourceLocation texture = new ResourceLocation("miscellany", "textures/gui/bookTemplate.png"); public static final ResourceLocation resources1 = new ResourceLocation("miscellany", "textures/gui/bookResources1.png"); public static final ResourceLocation craftingGrid = new ResourceLocation ("miscellany", "textures/gui/craftingGrid.png"); public final int xSizeofTexture = 228; public final int ySizeofTexture = 166; public String currentSection; public int subSection; public boolean entry; public int maxPages; public String prevSection; public boolean brew; public GuiManualBooks(){ super(); currentSection="index"; subSection=1; entry=false; } public GuiManualBooks(EntityPlayer player){ checkIfClient(player); } public boolean checkIfClient(EntityPlayer player){ if(player.isClientWorld()){ return true; }else{ return false; } } @Override public void drawScreen(int x, int y, float f) { FontRenderer fontrenderer = Minecraft.getMinecraft().fontRenderer; RenderItem itemRenderer = new RenderItem(); drawDefaultBackground(); GL11.glColor4f(1F, 1F, 1F, 1F); mc.renderEngine.bindTexture(texture); int posX = (width - xSizeofTexture) / 2; int posY = (height - ySizeofTexture) / 2; drawTexturedModalRect(posX, posY, 0, 0, xSizeofTexture, ySizeofTexture); if(!entry || currentSection=="index" || currentSection=="items" || currentSection=="machines" || currentSection=="alchemy" || currentSection=="Blocks" || currentSection=="equipment"){ mc.renderEngine.bindTexture(resources1); drawTexturedModalRect(posX + 7, posY + 7, 0, 0, 99,84); fontrenderer.drawSplitString("Raizunne's Miscellany is still a very work in progress, the mod has a few items and other " + "miscellaneous stuff in it." , posX+7, posY+90, 100, 0); } if(entry && currentSection=="sacredChalice" && subSection==0){ //CHALICE fontrenderer.drawString("Sacred Chalice", posX + 10, posY + 8, 0x000000, false); fontrenderer.drawSplitString(BookResources.chalice1, posX + 10, posY + 80, 98, 0); fontrenderer.drawSplitString(BookResources.chalice2, posX + 121, posY + 17, 98, 0); drawCrafting(Items.gold_ingot, Items.water_bucket, Items.gold_ingot, null, Blocks.gold_block, null, Items.gold_ingot, Items.gold_ingot, Items.gold_ingot, MiscItems.sacredChalice, 20, 20, x, y); }else if(entry && currentSection=="shake" && subSection==0){ //SHAKE fontrenderer.drawString("Flight Flask", posX + 10, posY + 8, 0x000000, false); fontrenderer.drawSplitString(BookResources.shake1, posX + 10, posY + 93, 98, 0); fontrenderer.drawSplitString(BookResources.shake2, posX + 121, posY + 17, 98, 0); drawAlchemy(Items.speckled_melon, Items.bread, Items.sugar, MiscItems.potionFlask, MiscItems.Shake, 20, 20, x, y); }else if(entry && currentSection=="brewer" && subSection==0){ //BREWER fontrenderer.drawString("Reactive Brewer", posX + 10, posY + 8, 0x000000, false); fontrenderer.drawSplitString(BookResources.brewer1, posX + 10, posY + 80, 98, 0); fontrenderer.drawSplitString(BookResources.brewer2, posX + 121, posY + 17, 98, 0); drawCrafting(Blocks.stone_slab, Blocks.stone_slab, Blocks.stone_slab, null, Blocks.hardened_clay, null, Blocks.hardened_clay, Blocks.hardened_clay, Blocks.hardened_clay, MiscBlocks.brewer, 20, 20, x, y); }else if(entry && currentSection=="knowledge" && subSection==0){ //KNOWLEDGE fontrenderer.drawString("Knowledge Flask", posX + 10, posY + 8, 0x000000, false); fontrenderer.drawSplitString(BookResources.knowledge1, posX + 10, posY + 93, 98, 0); fontrenderer.drawSplitString(BookResources.knowledge2, posX + 121, posY + 17, 98, 0); drawAlchemy(Blocks.emerald_block, Items.book, Blocks.emerald_block, MiscItems.potionFlask, MiscItems.knowledgeFlask, 20, 20, x, y); }else if(entry && currentSection=="flight" && subSection==0){ //FLIGHT fontrenderer.drawString("Flight Flask", posX + 10, posY + 8, 0x000000, false); fontrenderer.drawSplitString(BookResources.flight1, posX + 10, posY + 93, 98, 0); fontrenderer.drawSplitString(BookResources.flight2, posX + 121, posY + 17, 98, 0); drawAlchemy(Items.diamond, Items.feather, Items.diamond, MiscItems.potionFlask, MiscItems.flightFlask, 20, 20, x, y); }else if(entry && currentSection=="anit-wither" && subSection==0){ //ANTIWITHER fontrenderer.drawString("Anti-Wither Flask", posX + 10, posY + 8, 0x000000, false); fontrenderer.drawSplitString(BookResources.wither1, posX + 10, posY + 93, 98, 0); fontrenderer.drawSplitString(BookResources.wither2, posX + 121, posY + 17, 98, 0); drawAlchemy(Items.diamond, Items.skull, Blocks.red_flower, MiscItems.potionFlask, MiscItems.WitherAnti, 20, 20, x, y); }else if(entry && currentSection=="heart" && subSection==0){ //Heart Flask fontrenderer.drawString("Heart Flask", posX + 10, posY + 8, 0x000000, false); fontrenderer.drawSplitString(BookResources.heart1, posX + 10, posY + 93, 98, 0); fontrenderer.drawSplitString(BookResources.heart2, posX + 121, posY + 17, 98, 0); drawAlchemy(Items.speckled_melon, Items.blaze_powder, Items.speckled_melon, MiscItems.potionFlask, MiscItems.theheart, 20, 20, x, y); }else if(entry && currentSection=="gem" && subSection==0){ //KNOWLEDGE GEM fontrenderer.drawString("Knowledge Gem", posX + 10, posY + 8, 0x000000, false); fontrenderer.drawSplitString(BookResources.gem1, posX + 10, posY + 80, 98, 0); fontrenderer.drawSplitString(BookResources.gem2, posX + 121, posY + 17, 98, 0); fontrenderer.drawSplitString(BookResources.gem3, posX + 121, posY + 105, 98, 0); drawCrafting(null, Items.emerald, null, Items.emerald, Items.diamond, Items.emerald, null, Items.emerald, null, MiscItems.knowledgegem, 20, 20, x, y); }else if(entry && currentSection=="gem" && subSection==1){ //KNOWLEDGE GEM PAGE 2 fontrenderer.drawString("Knowledge Gem", posX + 10, posY + 8, 0x000000, false); fontrenderer.drawSplitString(EnumChatFormatting.DARK_PURPLE + "Upgrades", posX + 10, posY + 80, 98, 0); fontrenderer.drawSplitString(BookResources.gemLevel1, posX + 10, posY + 92, 98, 0); fontrenderer.drawSplitString(BookResources.gemLevel2, posX + 121, posY + 17, 98, 0); fontrenderer.drawSplitString(BookResources.gemLevel3, posX + 121, posY + 95, 98, 0); drawCrafting(null, Items.emerald, null, Items.emerald, MiscItems.knowledgegem, Items.emerald, null, Items.emerald, null, MiscItems.knowledgegem, 20, 20, x, y); }else if(entry && currentSection=="foodpackager" && subSection==0){ fontrenderer.drawString("Food Packager", posX + 10, posY + 8, 0x000000, false); fontrenderer.drawSplitString(BookResources.packager1, posX + 10, posY + 80, 98, 0); fontrenderer.drawSplitString(BookResources.packager2, posX + 121, posY + 17, 98, 0); drawCrafting(Items.iron_ingot, Items.iron_ingot, Items.iron_ingot, Items.gold_ingot, Blocks.furnace, Items.gold_ingot, Items.iron_ingot, Items.iron_ingot, Items.iron_ingot, MiscBlocks.packager, 20, 20, x, y); } if(brew){ RenderHelper.disableStandardItemLighting(); fontrenderer.drawString("Brewer Recipe", posX+21, posY+80, 0x939393, false); if(x > posX + 12 && x < posX + 104 && y > posY + 80 && y < posY + 86){ String[] desc = { "Put the top three", "items inside of the", "Brewer and a Potion", "Flask on the bottom slot." }; @SuppressWarnings("rawtypes") List temp = Arrays.asList(desc); zLevel = 2; drawHoveringText(temp, x, y, fontrenderer); } RenderHelper.enableGUIStandardItemLighting(); } super.drawScreen(x, y, f); } @Override public boolean doesGuiPauseGame() { return false; } @Override public void initGui() { buttonList = new ArrayList(); int posX = (width - xSizeofTexture) / 2; int posY = (height - ySizeofTexture) / 2; // System.out.println(currentSection); int color1 = 0xA3007A; int color2 = 0x720056; ButtonLeft prevButton = new ButtonLeft(0, posX + 0, posY + 167, 18, 12, "Prev", true); ButtonRight nextButton = new ButtonRight(1, posX + 210, posY + 167, 18, 12, "Next", true); ButtonNormal returnIndex = new ButtonNormal(2, posX + 87, posY + 167, 50, 14, "Return", true); ButtonMenu items = new ButtonMenu(11, posX + 124, posY + 18, 90, 12, "Items", color1, color2, true); ButtonMenu machines = new ButtonMenu(12, posX + 124, posY + 42, 90, 12, "Machines", color1, color2, true); ButtonMenu alchemy = new ButtonMenu(13, posX + 124, posY + 30, 90, 12, "Advanced Alchemy", color1, color2, true); ButtonMenu blocks = new ButtonMenu(14, posX + 124, posY + 54, 90, 12, "Blocks", color1, color2, true); ButtonMenu equipment = new ButtonMenu(15, posX + 124, posY + 66, 90, 12, "Equipment", color1, color2, true); ButtonMenu items1 = new ButtonMenu(31, posX + 124, posY + 18, 90, 12, "Sacred Chalice", color1, color2, true); ButtonMenu items2 = new ButtonMenu(32, posX + 124, posY + 30, 90, 12, "Shake", color1, color2, true); ButtonMenu items3 = new ButtonMenu(33, posX + 124, posY + 42, 90, 12, "Knowledge Gem", color1, color2, true); ButtonMenu blocks1 = new ButtonMenu(51, posX + 124, posY + 18, 90, 12, "Present", color1, color2, true); ButtonMenu machines1 = new ButtonMenu(71, posX + 124, posY + 18, 90, 12, "Food Packager", color1, color2, true); ButtonMenu equipment1 = new ButtonMenu(91, posX + 124, posY + 18, 90, 12, "Redstonic JetBoots", color1, color2, true); ButtonMenu alchemy1 = new ButtonMenu(112, posX + 124, posY + 18, 90, 12, "Reactive Brewer", color1, color2, true); ButtonMenu alchemy2 = new ButtonMenu(113, posX + 124, posY + 30, 90, 12, "Knowledge Potion", color1, color2, true); ButtonMenu alchemy3 = new ButtonMenu(114, posX + 124, posY + 42, 90, 12, "Flight Potion", color1, color2, true); ButtonMenu alchemy4 = new ButtonMenu(115, posX + 124, posY + 54, 90, 12, "Anti-Wither Potion", color1, color2, true); ButtonMenu alchemy5 = new ButtonMenu(116, posX + 124, posY + 66, 90, 12, "Heart Potion", color1, color2, true); if(currentSection=="index"|| currentSection==null || currentSection=="0"){ buttonList.removeAll(buttonList); buttonList.add(items); buttonList.add(machines); buttonList.add(alchemy); }else if(entry){ buttonList.removeAll(buttonList); if(maxPages!=subSection){ buttonList.add(nextButton); } if(subSection != 0){ buttonList.add(prevButton); } buttonList.add(returnIndex); }else if(!entry&&currentSection=="index"&&currentSection==null || currentSection=="0"){ buttonList.remove(returnIndex); } if(currentSection=="items"){ buttonList.removeAll(buttonList); buttonList.add(returnIndex); buttonList.add(items1); buttonList.add(items2); buttonList.add(items3); }else if(currentSection=="blocks"){ buttonList.removeAll(buttonList); buttonList.add(returnIndex); buttonList.add(blocks1); }else if(currentSection=="machines"){ buttonList.removeAll(buttonList); buttonList.add(returnIndex); buttonList.add(machines1); }else if(currentSection=="equipment"){ buttonList.removeAll(buttonList); buttonList.add(returnIndex); buttonList.add(equipment1); }else if(currentSection=="alchemy"){ buttonList.removeAll(buttonList); buttonList.add(returnIndex); buttonList.add(alchemy1); buttonList.add(alchemy2); buttonList.add(alchemy3); buttonList.add(alchemy4); buttonList.add(alchemy5); } } @Override protected void actionPerformed(GuiButton button){ switch(button.id){ case 0: if(currentSection!="index" && maxPages==subSection){ subSection=subSection-1; } break; case 1: if(currentSection!="index" && subSection!=maxPages){ subSection=subSection+1; } break; case 2: String s = currentSection; if(s=="items" || s=="blocks" || s=="machines" || s=="alchemy" || s=="equipment"){ currentSection="index"; }else{ currentSection=prevSection; } subSection=0; entry=false; brew=false; break; //MENUS case 11: currentSection="items"; subSection=0; entry=false; break; case 12: currentSection="machines"; subSection=0; entry=false; break; case 13: currentSection="alchemy"; subSection=0; entry=false; break; case 14: currentSection="blocks"; subSection=0; entry=false; break; case 15: currentSection="equipment"; subSection=0; entry=false; break; //ITEMS case 31: currentSection="sacredChalice"; subSection=0; entry=true; maxPages=0; prevSection="items"; break; case 32: currentSection="shake"; prevSection="items"; subSection=0; entry=true; maxPages=0; brew = true; break; case 33: currentSection="gem"; prevSection="items"; subSection=0; entry=true; maxPages=1; break; //MACHINES case 71: currentSection="foodpackager"; prevSection="machines"; subSection=0; entry=true; maxPages=0; break; //ALCHEMY case 112: currentSection="brewer"; subSection=0; entry=true; maxPages=0; prevSection="alchemy"; break; case 113: currentSection="knowledge"; subSection=0; entry=true; maxPages=0; prevSection="alchemy"; brew=true; break; case 114: currentSection="flight"; subSection=0; entry=true; maxPages=0; prevSection="alchemy"; brew=true; break; case 115: currentSection="anit-wither"; prevSection="alchemy"; subSection=0; entry=true; maxPages=0; brew=true; break; case 116: currentSection="heart"; prevSection="alchemy"; subSection=0; entry=true; maxPages=0; brew=true; break; } } @Override protected void mouseClicked(int x, int y, int mouseId) { int posX = (width - xSizeofTexture) / 2; int posY = (height - ySizeofTexture) / 2; int totalx = x - posX; int totaly = y - posY; super.mouseClicked(x, y, mouseId); this.initGui(); } public void drawCrafting(Object i1, Object i2, Object i3, Object i4, Object i5, Object i6, Object i7, Object i8, Object i9, Object pro,int xPos, int yPos, int mousex, int mousey){ FontRenderer itemsInGrid = Minecraft.getMinecraft().fontRenderer; RenderHelper.disableStandardItemLighting(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glEnable(GL11.GL_BLEND); int posX = (this.width - xSizeofTexture) / 2; int posY = (this.height - ySizeofTexture) / 2; int xPosCrafting = posX + yPos; int yPosCrafting = posY + xPos; ItemStack slot1 = null, slot2 = null, slot3 = null, slot4 = null, slot5 = null, slot6 = null, slot7 = null, slot8 = null, slot9 = null, product = null; if(i1 instanceof Item){ slot1 = new ItemStack((Item)i1); }else if(i1 instanceof Block){ slot1 = new ItemStack((Block)i1); } if(i2 instanceof Item){ slot2 = new ItemStack((Item)i2); }else if(i2 instanceof Block){ slot2 = new ItemStack((Block)i2); } if(i3 instanceof Item){ slot3 = new ItemStack((Item)i3); }else if(i3 instanceof Block){ slot3 = new ItemStack((Block)i3); } if(i4 instanceof Item){ slot4 = new ItemStack((Item)i4); }else if(i4 instanceof Block){ slot4 = new ItemStack((Block)i4); } if(i5 instanceof Item){ slot5 = new ItemStack((Item)i5); }else if(i5 instanceof Block){ slot5 = new ItemStack((Block)i5); } if(i6 instanceof Item){ slot6 = new ItemStack((Item)i6); }else if(i6 instanceof Block){ slot6 = new ItemStack((Block)i6); } if(i7 instanceof Item){ slot7 = new ItemStack((Item)i7); }else if(i7 instanceof Block){ slot7 = new ItemStack((Block)i7); } if(i8 instanceof Item){ slot8 = new ItemStack((Item)i8); }else if(i8 instanceof Block){ slot8 = new ItemStack((Block)i8); } if(i1 instanceof Item){ slot9 = new ItemStack((Item)i9); }else if(i9 instanceof Block){ slot9 = new ItemStack((Block)i9); } if(pro instanceof Item){ product = new ItemStack((Item)pro); }else if(pro instanceof Block){ product = new ItemStack((Block)pro); } Minecraft.getMinecraft().getTextureManager().bindTexture(craftingGrid); drawTexturedModalRect(xPosCrafting, yPosCrafting, 0, 0, 76, 56); if(slot1!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot1, xPosCrafting + 1, yPosCrafting + 1); } if(slot2!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot2, xPosCrafting + 20, yPosCrafting + 1); } if(slot3!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot3, xPosCrafting + 39, yPosCrafting + 1); } if(slot4!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot4, xPosCrafting + 1, yPosCrafting + 20); } if(slot5!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot5, xPosCrafting + 20, yPosCrafting + 20); } if(slot6!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot6, xPosCrafting + 39, yPosCrafting + 20); } if(slot7!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot7, xPosCrafting + 1, yPosCrafting + 39); } if(slot8!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot8, xPosCrafting + 20, yPosCrafting + 39); } if(slot9!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot9, xPosCrafting + 39, yPosCrafting + 39); } RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), product, xPosCrafting + 59, yPosCrafting + 8); RenderHelper.disableStandardItemLighting(); if(slot1!=null){ if(mousex>xPosCrafting+2 && mousex<xPosCrafting+16 && mousey>yPosCrafting+2 && mousey<yPosCrafting+16){ renderToolTip(slot1, mousex, mousey); } } if(slot2!=null){ if(mousex>xPosCrafting+21 && mousex<xPosCrafting+35 && mousey>yPosCrafting+2 && mousey<yPosCrafting+16){ renderToolTip(slot2, mousex, mousey); } } if(slot3!=null){ if(mousex>xPosCrafting+40 && mousex<xPosCrafting+54 && mousey>yPosCrafting+2 && mousey<yPosCrafting+16){ renderToolTip(slot3, mousex, mousey); } } if(slot4!=null){ if(mousex>xPosCrafting+2 && mousex<xPosCrafting+16 && mousey>yPosCrafting+21 && mousey<yPosCrafting+35){ renderToolTip(slot4, mousex, mousey); } } if(slot5!=null){ if(mousex>xPosCrafting+21 && mousex<xPosCrafting+35 && mousey>yPosCrafting+21 && mousey<yPosCrafting+35){ renderToolTip(slot5, mousex, mousey); } } if(slot6!=null){ if(mousex>xPosCrafting+40 && mousex<xPosCrafting+54 && mousey>yPosCrafting+21 && mousey<yPosCrafting+35){ renderToolTip(slot6, mousex, mousey); } } if(slot7!=null){ if(mousex>xPosCrafting+2 && mousex<xPosCrafting+16 && mousey>yPosCrafting+40 && mousey<yPosCrafting+54){ renderToolTip(slot7, mousex, mousey); } } if(slot8!=null){ if(mousex>xPosCrafting+21 && mousex<xPosCrafting+35 && mousey>yPosCrafting+40 && mousey<yPosCrafting+54){ renderToolTip(slot8, mousex, mousey); } } if(slot9!=null){ if(mousex>xPosCrafting+40 && mousex<xPosCrafting+54 && mousey>yPosCrafting+40 && mousey<yPosCrafting+54){ renderToolTip(slot9, mousex, mousey); } } if(mousex>xPosCrafting+58 && mousex<xPosCrafting+67 && mousey>yPosCrafting+38 && mousey<yPosCrafting+42 || mousex>xPosCrafting+63 && mousex<xPosCrafting+69 && mousey>yPosCrafting+33 && mousey<yPosCrafting+68 || mousex>xPosCrafting+62 && mousex<xPosCrafting+72 && mousey>yPosCrafting+26 && mousey<yPosCrafting+33){ String[] desc = { "Produces" }; @SuppressWarnings("rawtypes") List temp = Arrays.asList(desc); drawHoveringText(temp, mousex, mousey, itemsInGrid); } RenderHelper.disableStandardItemLighting(); GL11.glEnable(GL11.GL_DEPTH_TEST); if(mousex>xPosCrafting+60 && mousex<xPosCrafting+74 && mousey>yPosCrafting+9 && mousey<yPosCrafting+23){ renderToolTip(product, mousex, mousey); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDisable(GL11.GL_LIGHTING); } } public void drawAlchemy(Object i1, Object i2, Object i3, Object i4, Object pro, int xPos, int yPos, int mousex, int mousey){ FontRenderer itemsInGrid = Minecraft.getMinecraft().fontRenderer; RenderHelper.disableStandardItemLighting(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glEnable(GL11.GL_BLEND); int posX = (this.width - xSizeofTexture) / 2; int posY = (this.height - ySizeofTexture) / 2; int xPosCrafting = posX + yPos; int yPosCrafting = posY + xPos; ItemStack slot1 = null, slot2 = null, slot3 = null, slot4 = null, product = null; if(i1 instanceof Item){ slot1 = new ItemStack((Item)i1); }else if(i1 instanceof Block){ slot1 = new ItemStack((Block)i1); } if(i2 instanceof Item){ slot2 = new ItemStack((Item)i2); }else if(i2 instanceof Block){ slot2 = new ItemStack((Block)i2); } if(i3 instanceof Item){ slot3 = new ItemStack((Item)i3); }else if(i3 instanceof Block){ slot3 = new ItemStack((Block)i3); } if(i4 instanceof Item){ slot4 = new ItemStack((Item)i4); }else if(i4 instanceof Block){ slot4 = new ItemStack((Block)i4); } if(pro instanceof Item){ product = new ItemStack((Item)pro); }else if(pro instanceof Block){ product = new ItemStack((Block)pro); } Minecraft.getMinecraft().getTextureManager().bindTexture(craftingGrid); drawTexturedModalRect(xPosCrafting, yPosCrafting, 97, 0, 81, 56); if(slot1!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot1, xPosCrafting + 1, yPosCrafting + 7); } if(slot2!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot2, xPosCrafting + 27, yPosCrafting + 1); } if(slot3!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot3, xPosCrafting + 53, yPosCrafting + 7); } if(slot4!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), slot4, xPosCrafting + 27, yPosCrafting + 39); } if(product!=null){ RenderHelper.disableStandardItemLighting(); itemRender.renderItemAndEffectIntoGUI(itemsInGrid, Minecraft.getMinecraft().getTextureManager(), product, xPosCrafting + 64, yPosCrafting + 29); } if(slot1!=null){ if(mousex>xPosCrafting+1 && mousex<xPosCrafting+17 && mousey>yPosCrafting+7 && mousey<yPosCrafting+23){ renderToolTip(slot1, mousex, mousey); } } if(slot2!=null){ if(mousex>xPosCrafting+27 && mousex<xPosCrafting+43 && mousey>yPosCrafting+1 && mousey<yPosCrafting+17){ renderToolTip(slot2, mousex, mousey); } } if(slot3!=null){ if(mousex>xPosCrafting+53 && mousex<xPosCrafting+69 && mousey>yPosCrafting+7 && mousey<yPosCrafting+23){ renderToolTip(slot3, mousex, mousey); } } if(slot4!=null){ if(mousex>xPosCrafting+27 && mousex<xPosCrafting+43 && mousey>yPosCrafting+39 && mousey<yPosCrafting+55){ renderToolTip(slot4, mousex, mousey); } } if(product!=null){ if(mousex>xPosCrafting+64 && mousex<xPosCrafting+80 && mousey>yPosCrafting+29 && mousey<yPosCrafting+45){ renderToolTip(product, mousex, mousey); } } if(mousex>xPosCrafting+30 && mousex<xPosCrafting+18 && mousey>yPosCrafting+40 && mousey<yPosCrafting+38){ String[] desc = { "Brews" }; @SuppressWarnings("rawtypes") List temp = Arrays.asList(desc); drawHoveringText(temp, mousex, mousey, itemsInGrid); } RenderHelper.disableStandardItemLighting(); GL11.glEnable(GL11.GL_DEPTH_TEST); } }
package com.joelapenna.foursquared.app; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Checkin; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.Foursquared; import com.joelapenna.foursquared.FriendsActivity; import com.joelapenna.foursquared.MainActivity; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.location.LocationUtils; import com.joelapenna.foursquared.preferences.Preferences; import com.joelapenna.foursquared.util.StringFormatters; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.location.Location; import android.location.LocationManager; import android.os.SystemClock; import android.preference.PreferenceManager; import android.text.TextUtils; import android.util.Log; import android.widget.RemoteViews; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * This service will run every N minutes (specified by the user in settings). An alarm * handles running the service. * * When the service runs, we call /checkins. From the list of checkins, we cut down the * list of relevant checkins as follows: * <ul> * <li>Not one of our own checkins.</li> * <li>We haven't turned pings off for the user. This can be toggled on/off in the * UserDetailsActivity activity, per user.</li> * <li>The checkin is younger than the last time we ran this service.</li> * </ul> * * Note that the server might override the pings attribute to 'off' for certain checkins, * usually if the checkin is far away from our current location. * * Pings will not be cleared from the notification bar until a subsequent run can * generate at least one new ping. A new batch of pings will clear all * previous pings so as to not clutter the notification bar. * * @date May 21, 2010 * @author Mark Wyszomierski (markww@gmail.com) */ public class PingsService extends WakefulIntentService { public static final String TAG = "PingsService"; private static final boolean DEBUG = false; public static final int NOTIFICATION_ID_CHECKINS = 15; public PingsService() { super("PingsService"); } @Override public void onCreate() { super.onCreate(); } @Override protected void doWakefulWork(Intent intent) { Log.i(TAG, "Foursquare pings service running..."); // The user must have logged in once previously for this to work, // and not leave the app in a logged-out state. Foursquared foursquared = (Foursquared) getApplication(); Foursquare foursquare = foursquared.getFoursquare(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); if (!foursquared.isReady()) { Log.i(TAG, "User not logged in, cannot proceed."); return; } // Before running, make sure the user still wants pings on. // For example, the user could have turned pings on from // this device, but then turned it off on a second device. This // service would continue running then, continuing to notify the // user. if (!checkUserStillWantsPings(foursquared.getUserId(), foursquare)) { // Turn off locally. Log.i(TAG, "Pings have been turned off for user, cancelling service."); prefs.edit().putBoolean(Preferences.PREFERENCE_PINGS, false).commit(); cancelPings(this); return; } // Get the users current location and then request nearby checkins. Group<Checkin> checkins = null; Location location = getLastGeolocation(); if (location != null) { try { checkins = foursquare.checkins( LocationUtils.createFoursquareLocation(location)); } catch (Exception ex) { Log.e(TAG, "Error getting checkins in pings service.", ex); } } else { Log.e(TAG, "Could not find location in pings service, cannot proceed."); } if (checkins != null) { Log.i(TAG, "Checking " + checkins.size() + " checkins for pings."); // Don't accept any checkins that are older than the last time we ran. long lastRunTime = prefs.getLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()); Date dateLast = new Date(lastRunTime); Log.i(TAG, "Last service run time: " + dateLast.toLocaleString() + " (" + lastRunTime + ")."); // Now build the list of 'new' checkins. List<Checkin> newCheckins = new ArrayList<Checkin>(); for (Checkin it : checkins) { if (DEBUG) Log.d(TAG, "Checking checkin of " + it.getUser().getFirstname()); // Ignore ourselves. The server should handle this by setting the pings flag off but.. if (it.getUser() != null && it.getUser().getId().equals(foursquared.getUserId())) { if (DEBUG) Log.d(TAG, " Ignoring checkin of ourselves."); continue; } // Check that our user wanted to see pings from this user. if (!it.getPing()) { if (DEBUG) Log.d(TAG, " Pings are off for this user."); continue; } // If it's an 'off the grid' checkin, ignore. if (it.getVenue() == null && it.getShout() == null) { if (DEBUG) Log.d(TAG, " Checkin is off the grid, ignoring."); continue; } // Check against date times. try { Date dateCheckin = StringFormatters.DATE_FORMAT.parse(it.getCreated()); if (DEBUG) { Log.d(TAG, " Comaring date times for checkin."); Log.d(TAG, " Last run time: " + dateLast.toLocaleString()); Log.d(TAG, " Checkin time: " + dateCheckin.toLocaleString()); } if (dateCheckin.after(dateLast)) { if (DEBUG) Log.d(TAG, " Checkin is younger than our last run time, passes all tests!!"); newCheckins.add(it); } else { if (DEBUG) Log.d(TAG, " Checkin is older than last run time."); } } catch (ParseException ex) { if (DEBUG) Log.e(TAG, " Error parsing checkin timestamp: " + it.getCreated(), ex); } } Log.i(TAG, "Found " + newCheckins.size() + " new checkins."); notifyUser(newCheckins); } else { // Checkins were null, so don't record this as the last run time in order to try // fetching checkins we may have missed on the next run. // Thanks to logan.johnson@gmail.com for the fix. Log.i(TAG, "Checkins were null, won't update last run timestamp."); return; } // Record this as the last time we ran. prefs.edit().putLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()).commit(); } private Location getLastGeolocation() { LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); List<String> providers = manager.getAllProviders(); Location bestLocation = null; for (String it : providers) { Location location = manager.getLastKnownLocation(it); if (location != null) { if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) { bestLocation = location; } } } return bestLocation; } private void notifyUser(List<Checkin> newCheckins) { // If we have no new checkins to show, nothing to do. We would also be leaving the // previous batch of pings alive (if any) which is ok. if (newCheckins.size() < 1) { return; } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); // Clear all previous pings notifications before showing new ones. NotificationManager mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); mgr.cancelAll(); // We'll only ever show a single entry, so we collapse data depending on how many // new checkins we received on this refresh. RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.pings_list_item); if (newCheckins.size() == 1) { // A single checkin, show full checkin preview. Checkin checkin = newCheckins.get(0); String checkinMsgLine1 = StringFormatters.getCheckinMessageLine1(checkin, true); String checkinMsgLine2 = StringFormatters.getCheckinMessageLine2(checkin); String checkinMsgLine3 = StringFormatters.getCheckinMessageLine3(checkin); contentView.setTextViewText(R.id.text1, checkinMsgLine1); if (!TextUtils.isEmpty(checkinMsgLine2)) { contentView.setTextViewText(R.id.text2, checkinMsgLine2); contentView.setTextViewText(R.id.text3, checkinMsgLine3); } else { contentView.setTextViewText(R.id.text2, checkinMsgLine3); } } else { // More than one new checkin, collapse them. String checkinMsgLine1 = newCheckins.size() + " new Foursquare checkins!"; StringBuilder sbCheckinMsgLine2 = new StringBuilder(1024); for (Checkin it : newCheckins) { sbCheckinMsgLine2.append(StringFormatters.getUserAbbreviatedName(it.getUser())); sbCheckinMsgLine2.append(", "); } if (sbCheckinMsgLine2.length() > 0) { sbCheckinMsgLine2.delete(sbCheckinMsgLine2.length()-2, sbCheckinMsgLine2.length()); } String checkinMsgLine3 = "at " + StringFormatters.DATE_FORMAT_TODAY.format(new Date()); contentView.setTextViewText(R.id.text1, checkinMsgLine1); contentView.setTextViewText(R.id.text2, sbCheckinMsgLine2.toString()); contentView.setTextViewText(R.id.text3, checkinMsgLine3); } PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, FriendsActivity.class), 0); Notification notification = new Notification( R.drawable.notification_icon, "Foursquare Checkin", System.currentTimeMillis()); notification.contentView = contentView; notification.contentIntent = pi; notification.flags |= Notification.FLAG_AUTO_CANCEL; if (prefs.getBoolean(Preferences.PREFERENCE_PINGS_VIBRATE, false)) { notification.defaults |= Notification.DEFAULT_VIBRATE; } if (newCheckins.size() > 1) { notification.number = newCheckins.size(); } mgr.notify(NOTIFICATION_ID_CHECKINS, notification); } private boolean checkUserStillWantsPings(String userId, Foursquare foursquare) { try { User user = foursquare.user(userId, false, false, null); if (user != null) { return user.getSettings().getPings().equals("on"); } } catch (Exception ex) { // Assume they still want it on. } return true; } public static void setupPings(Context context) { // If the user has pings on, set an alarm every N minutes, where N is their // requested refresh rate. We default to 30 if some problem reading set interval. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getBoolean(Preferences.PREFERENCE_PINGS, false)) { int refreshRateInMinutes = getRefreshIntervalInMinutes(prefs); if (DEBUG) { Log.d(TAG, "User has pings on, attempting to setup alarm with interval: " + refreshRateInMinutes + ".."); } // We want to mark this as the last run time so we don't get any notifications // before the service is started. prefs.edit().putLong( Preferences.PREFERENCE_PINGS_SERVICE_LAST_RUN_TIME, System.currentTimeMillis()).commit(); // Schedule the alarm. AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + (refreshRateInMinutes * 60 * 1000), refreshRateInMinutes * 60 * 1000, makePendingIntentAlarm(context)); } } public static void cancelPings(Context context) { AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); mgr.cancel(makePendingIntentAlarm(context)); } private static PendingIntent makePendingIntentAlarm(Context context) { return PendingIntent.getBroadcast(context, 0, new Intent(context, PingsOnAlarmReceiver.class), 0); } public static void clearAllNotifications(Context context) { NotificationManager mgr = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); mgr.cancelAll(); } public static void generatePingsTest(Context context) { Intent intent = new Intent(context, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pi = PendingIntent.getActivity(context, 0, intent, 0); NotificationManager mgr = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE); RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.pings_list_item); contentView.setTextViewText(R.id.text1, "Ping title line"); contentView.setTextViewText(R.id.text2, "Ping message line 2"); contentView.setTextViewText(R.id.text3, "Ping message line 3"); Notification notification = new Notification( R.drawable.notification_icon, "Foursquare Checkin", System.currentTimeMillis()); notification.contentView = contentView; notification.contentIntent = pi; notification.defaults |= Notification.DEFAULT_VIBRATE; mgr.notify(-1, notification); } private static int getRefreshIntervalInMinutes(SharedPreferences prefs) { int refreshRateInMinutes = 30; try { refreshRateInMinutes = Integer.parseInt(prefs.getString( Preferences.PREFERENCE_PINGS_INTERVAL, String.valueOf(refreshRateInMinutes))); } catch (NumberFormatException ex) { Log.e(TAG, "Error parsing pings interval time, defaulting to: " + refreshRateInMinutes); } return refreshRateInMinutes; } }
package com.miloshpetrov.sol2.game.ship; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.*; import com.badlogic.gdx.physics.box2d.joints.PrismaticJoint; import com.badlogic.gdx.physics.box2d.joints.PrismaticJointDef; import com.miloshpetrov.sol2.common.SolColor; import com.miloshpetrov.sol2.common.SolMath; import com.miloshpetrov.sol2.game.*; import com.miloshpetrov.sol2.game.dra.*; import com.miloshpetrov.sol2.game.gun.*; import com.miloshpetrov.sol2.game.input.Pilot; import com.miloshpetrov.sol2.game.item.*; import com.miloshpetrov.sol2.game.particle.LightSrc; import java.util.ArrayList; import java.util.List; public class ShipBuilder { public static final float SHIP_DENSITY = 3f; public static final float AVG_BATTLE_TIME = 30f; public static final float AVG_ALLY_LIFE_TIME = 75f; private final PathLoader myPathLoader; public ShipBuilder() { myPathLoader = new PathLoader("hulls"); } public FarShip buildNewFar(SolGame game, Vector2 pos, Vector2 spd, float angle, float rotSpd, Pilot pilot, String items, HullConfig hullConfig, RemoveController removeController, boolean hasRepairer, float money, TradeConfig tradeConfig, boolean giveAmmo) { if (spd == null) spd = new Vector2(); ItemContainer ic = new ItemContainer(); game.getItemMan().fillContainer(ic, items); EngineItem.Config ec = hullConfig.engineConfig; EngineItem ei = ec == null ? null : ec.example.copy(); TradeContainer tc = tradeConfig == null ? null : new TradeContainer(tradeConfig); GunItem g1 = null; GunItem g2 = null; Shield shield = null; Armor armor = null; for (List<SolItem> group : ic) { for (SolItem i : group) { if (i instanceof Shield) { shield = (Shield) i; continue; } if (i instanceof Armor) { armor = (Armor) i; continue; } if (i instanceof GunItem) { GunItem g = (GunItem) i; if (g1 == null && hullConfig.m1Fixed == g.config.fixed) { g1 = g; continue; } if (hullConfig.g2Pos != null && g2 == null && hullConfig.m2Fixed == g.config.fixed) g2 = g; continue; } } } if (giveAmmo) { addAbilityCharges(ic, hullConfig, pilot); addAmmo(ic, g1, pilot); addAmmo(ic, g2, pilot); } return new FarShip(new Vector2(pos), new Vector2(spd), angle, rotSpd, pilot, ic, hullConfig, hullConfig.maxLife, g1, g2, removeController, ei, hasRepairer ? new ShipRepairer() : null, money, tc, shield, armor); } private void addAmmo(ItemContainer ic, GunItem g, Pilot pilot) { if (g == null) return; GunConfig gc = g.config; ClipConfig cc = gc.clipConf; if (cc.infinite) return; float clipUseTime = cc.size * gc.timeBetweenShots + gc.reloadTime; float lifeTime = pilot.getFraction() == Fraction.LAANI ? AVG_ALLY_LIFE_TIME : AVG_BATTLE_TIME; int count = 1 + (int) (lifeTime / clipUseTime) + SolMath.intRnd(0, 2); for (int i = 0; i < count; i++) { if (ic.canAdd(cc.example)) ic.add(cc.example.copy()); } } private void addAbilityCharges(ItemContainer ic, HullConfig hc, Pilot pilot) { if (hc.ability != null) { SolItem ex = hc.ability.getChargeExample(); if (ex != null) { int count; if (pilot.isPlayer()) { count = 3; } else { float lifeTime = pilot.getFraction() == Fraction.LAANI ? AVG_ALLY_LIFE_TIME : AVG_BATTLE_TIME; count = (int) (lifeTime / hc.ability.getRechargeTime() * SolMath.rnd(.3f, 1)); } for (int i = 0; i < count; i++) ic.add(ex.copy()); } } } public SolShip build(SolGame game, Vector2 pos, Vector2 spd, float angle, float rotSpd, Pilot pilot, ItemContainer container, HullConfig hullConfig, float life, GunItem gun1, GunItem gun2, RemoveController removeController, EngineItem engine, ShipRepairer repairer, float money, TradeContainer tradeContainer, Shield shield, Armor armor) { ArrayList<Dra> dras = new ArrayList<Dra>(); ShipHull hull = buildHull(game, pos, spd, angle, rotSpd, hullConfig, life, dras); SolShip ship = new SolShip(game, pilot, hull, removeController, dras, container, repairer, money, tradeContainer, shield, armor); hull.getBody().setUserData(ship); for (Door door : hull.getDoors()) door.getBody().setUserData(ship); if (engine != null) { hull.setEngine(game, ship, engine); } if (gun1 != null) { GunMount m1 = hull.getGunMount(false); if (m1.isFixed() == gun1.config.fixed) m1.setGun(game, ship, gun1, hullConfig.g1UnderShip); } if (gun2 != null) { GunMount m2 = hull.getGunMount(true); if (m2 != null) { if (m2.isFixed() == gun2.config.fixed) m2.setGun(game, ship, gun2, hullConfig.g2UnderShip); } } return ship; } private ShipHull buildHull(SolGame game, Vector2 pos, Vector2 spd, float angle, float rotSpd, HullConfig hullConfig, float life, ArrayList<Dra> dras) { BodyDef.BodyType bodyType = hullConfig.type == HullConfig.Type.STATION ? BodyDef.BodyType.KinematicBody : BodyDef.BodyType.DynamicBody; DraLevel level = hullConfig.type == HullConfig.Type.STD ? DraLevel.BODIES : DraLevel.BIG_BODIES; Body body = myPathLoader.getBodyAndSprite(game, "hulls", hullConfig.texName, hullConfig.size, bodyType, pos, angle, dras, SHIP_DENSITY, level, hullConfig.tex); Fixture shieldFixture = createShieldFixture(hullConfig, body); GunMount m1 = new GunMount(hullConfig.g1Pos, hullConfig.m1Fixed); GunMount m2 = hullConfig.g2Pos == null ? null : new GunMount(hullConfig.g2Pos, hullConfig.m2Fixed); List<LightSrc> lCs = new ArrayList<LightSrc>(); for (Vector2 p : hullConfig.lightSrcPoss) { LightSrc lc = new LightSrc(game, .35f, true, .7f, p, game.getCols().hullLights); lc.collectDras(dras); lCs.add(lc); } ArrayList<ForceBeacon> beacons = new ArrayList<ForceBeacon>(); for (Vector2 relPos : hullConfig.forceBeaconPoss) { ForceBeacon fb = new ForceBeacon(game, relPos, pos, spd); fb.collectDras(dras); beacons.add(fb); } ArrayList<Door> doors = new ArrayList<Door>(); for (Vector2 doorRelPos : hullConfig.doorPoss) { Door door = createDoor(game, pos, angle, body, doorRelPos); door.collectDras(dras); doors.add(door); } Fixture base = getBase(hullConfig.hasBase, body); ShipHull hull = new ShipHull(game, hullConfig, body, m1, m2, base, lCs, life, beacons, doors, shieldFixture); body.setLinearVelocity(spd); body.setAngularVelocity(rotSpd * SolMath.degRad); return hull; } private Fixture createShieldFixture(HullConfig hullConfig, Body body) { CircleShape shieldShape = new CircleShape(); shieldShape.setRadius(Shield.SIZE_PERC * hullConfig.size); FixtureDef shieldDef = new FixtureDef(); shieldDef.shape = shieldShape; shieldDef.isSensor = true; Fixture shieldFixture = body.createFixture(shieldDef); shieldShape.dispose(); return shieldFixture; } private Door createDoor(SolGame game, Vector2 pos, float angle, Body body, Vector2 doorRelPos) { World w = game.getObjMan().getWorld(); TextureAtlas.AtlasRegion tex = game.getTexMan().getTex("smallGameObjs/door", null); PrismaticJoint joint = createDoorJoint(body, w, pos, doorRelPos, angle); RectSprite s = new RectSprite(tex, Door.DOOR_LEN, 0, 0, new Vector2(doorRelPos), DraLevel.BODIES, 0, 0, SolColor.W, false); return new Door(joint, s); } private PrismaticJoint createDoorJoint(Body shipBody, World w, Vector2 shipPos, Vector2 doorRelPos, float shipAngle) { Body doorBody = createDoorBody(w, shipPos, doorRelPos, shipAngle); PrismaticJointDef jd = new PrismaticJointDef(); jd.initialize(shipBody, doorBody, shipPos, Vector2.Zero); jd.localAxisA.set(1, 0); jd.collideConnected = false; jd.enableLimit = true; jd.enableMotor = true; jd.lowerTranslation = 0; jd.upperTranslation = Door.DOOR_LEN; jd.maxMotorForce = 2; return (PrismaticJoint) w.createJoint(jd); } private Body createDoorBody(World world, Vector2 shipPos, Vector2 doorRelPos, float shipAngle) { BodyDef bd = new BodyDef(); bd.type = BodyDef.BodyType.DynamicBody; bd.angle = shipAngle * SolMath.degRad; bd.angularDamping = 0; bd.linearDamping = 0; SolMath.toWorld(bd.position, doorRelPos, shipAngle, shipPos, false); Body body = world.createBody(bd); PolygonShape shape = new PolygonShape(); shape.setAsBox(Door.DOOR_LEN/2, .03f); body.createFixture(shape, SHIP_DENSITY); shape.dispose(); return body; } private static Fixture getBase(boolean hasBase, Body body) { if (!hasBase) return null; Fixture base = null; Vector2 v = SolMath.getVec(); float lowestX = Float.MAX_VALUE; for (Fixture f : body.getFixtureList()) { Shape s = f.getShape(); if (!(s instanceof PolygonShape)) continue; PolygonShape poly = (PolygonShape) s; int pointCount = poly.getVertexCount(); for (int i = 0; i < pointCount; i++) { poly.getVertex(i, v); if (v.x < lowestX) { base = f; lowestX = v.x; } } } SolMath.free(v); return base; } public Vector2 getOrigin(String name) { return myPathLoader.getOrigin(name + ".png", 1); } }
package org.objenesis; /** * Guess the best instantiator for a given class. Currently, the selection doesn't depend on the class. It relies on the * <ul> * <li>JVM version</li> * <li>JVM vendor</li> * <li>JVM vendor version</li> * </ul> * However, instantiator a stateful and so dedicated to their class. * * @see ObjectInstantiator */ public class AutomaticInstantiatorStrategy implements InstantiatorStrategy { private static final String JROCKIT = "BEA JRockit"; private static final String GNU = "GNU libgcj"; /** JVM version */ private static final String VM_VERSION = System.getProperty("java.runtime.version"); /** Vendor version */ private static final String VENDOR_VERSION = System.getProperty("java.vm.version"); /** Vendor name */ private static final String VENDOR = System.getProperty("java.vm.vendor"); /** JVM name */ private static final String JVM_NAME = System.getProperty("java.vm.name"); public ObjectInstantiator newInstantiatorOf(Class type) { if(VM_VERSION.startsWith("1.3")) { if(JVM_NAME.startsWith(JROCKIT)) { throw new RuntimeException("Unsupported JVM: " + JVM_NAME + "/" + VM_VERSION); } return new Sun13Instantiator(type); } if(JVM_NAME.startsWith(GNU)) { return new GCJInstantiator(type); } // It's JVM 1.4 and above since we are not supporting below 1.3 // This instantiator should also work for JRockit except for old 1.4 JVM return new SunReflectionFactoryInstantiator(type); } }
package io.mangoo.core; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.quartz.CronExpression; import org.quartz.Job; import org.quartz.JobDetail; import org.quartz.Trigger; import org.reflections.Reflections; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.lalyos.jfiglet.FigletFont; import com.google.common.io.Resources; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.Stage; import com.icegreen.greenmail.util.GreenMail; import com.icegreen.greenmail.util.ServerSetup; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import io.mangoo.admin.MangooAdminController; import io.mangoo.annotations.Schedule; import io.mangoo.configuration.Config; import io.mangoo.enums.Default; import io.mangoo.enums.Key; import io.mangoo.enums.Mode; import io.mangoo.enums.RouteType; import io.mangoo.interfaces.MangooLifecycle; import io.mangoo.interfaces.MangooRoutes; import io.mangoo.routing.Route; import io.mangoo.routing.Router; import io.mangoo.routing.handlers.DispatcherHandler; import io.mangoo.routing.handlers.ExceptionHandler; import io.mangoo.routing.handlers.FallbackHandler; import io.mangoo.routing.handlers.WebSocketHandler; import io.mangoo.scheduler.MangooScheduler; import io.undertow.Handlers; import io.undertow.Undertow; import io.undertow.server.RoutingHandler; import io.undertow.server.handlers.PathHandler; import io.undertow.server.handlers.resource.ClassPathResourceManager; import io.undertow.server.handlers.resource.ResourceHandler; import io.undertow.util.Methods; /** * Convenient methods for everything to start up a mangoo I/O application * * @author svenkubiak * */ public class Bootstrap { private static final Logger LOG = LoggerFactory.getLogger(Bootstrap.class); private static final int INITIAL_SIZE = 255; private LocalDateTime start; private PathHandler pathHandler; private ResourceHandler resourceHandler; private Config config; private String host; private Mode mode; private Injector injector; private boolean error; private int port; public Bootstrap() { this.start = LocalDateTime.now(); } public Mode prepareMode() { String applicationMode = System.getProperty(Key.APPLICATION_MODE.toString()); if (StringUtils.isNotBlank(applicationMode)) { switch (applicationMode.toLowerCase(Locale.ENGLISH)) { case "dev" : this.mode = Mode.DEV; break; case "test" : this.mode = Mode.TEST; break; default : this.mode = Mode.PROD; break; } } else { this.mode = Mode.PROD; } return this.mode; } public Injector prepareInjector() { this.injector = Guice.createInjector(Stage.PRODUCTION, getModules()); return this.injector; } public void applicationInitialized() { this.injector.getInstance(MangooLifecycle.class).applicationInitialized(); } public void prepareConfig() { this.config = this.injector.getInstance(Config.class); if (!this.config.hasValidSecret()) { LOG.error("Please make sure that your application.yaml has an application.secret property which has at least 16 characters"); this.error = true; } } public void prepareRoutes() { if (!this.error) { try { MangooRoutes mangooRoutes = (MangooRoutes) this.injector.getInstance(Class.forName(Default.ROUTES_CLASS.toString())); mangooRoutes.routify(); } catch (ClassNotFoundException e) { LOG.error("Failed to load routes. Please check, that conf/Routes.java exisits in your application", e); this.error = true; } for (Route route : Router.getRoutes()) { if (RouteType.REQUEST.equals(route.getRouteType())) { Class<?> controllerClass = route.getControllerClass(); checkRoute(route, controllerClass); } } if (!this.error) { initPathHandler(); } } } private void checkRoute(Route route, Class<?> controllerClass) { boolean found = false; for (Method method : controllerClass.getMethods()) { if (method.getName().equals(route.getControllerMethod())) { found = true; } } if (!found) { LOG.error("Could not find controller method '" + route.getControllerMethod() + "' in controller class '" + controllerClass.getSimpleName() + "'"); this.error = true; } } private void initPathHandler() { this.pathHandler = new PathHandler(initRoutingHandler()); for (Route route : Router.getRoutes()) { if (RouteType.WEBSOCKET.equals(route.getRouteType())) { this.pathHandler.addExactPath(route.getUrl(), Handlers.websocket(new WebSocketHandler(route.getControllerClass()))); } else if (RouteType.RESOURCE_PATH.equals(route.getRouteType())) { this.pathHandler.addPrefixPath(route.getUrl(), getResourceHandler(route.getUrl())); } } } private RoutingHandler initRoutingHandler() { RoutingHandler routingHandler = Handlers.routing(); routingHandler.setFallbackHandler(new FallbackHandler()); Router.mapRequest(Methods.GET).toUrl("/@routes").onClassAndMethod(MangooAdminController.class, "routes"); Router.mapRequest(Methods.GET).toUrl("/@config").onClassAndMethod(MangooAdminController.class, "config"); Router.mapRequest(Methods.GET).toUrl("/@health").onClassAndMethod(MangooAdminController.class, "health"); Router.mapRequest(Methods.GET).toUrl("/@cache").onClassAndMethod(MangooAdminController.class, "cache"); Router.mapRequest(Methods.GET).toUrl("/@metrics").onClassAndMethod(MangooAdminController.class, "metrics"); Router.mapRequest(Methods.GET).toUrl("/@scheduler").onClassAndMethod(MangooAdminController.class, "scheduler"); for (Route route : Router.getRoutes()) { if (RouteType.REQUEST.equals(route.getRouteType())) { routingHandler.add(route.getRequestMethod(), route.getUrl(), new DispatcherHandler(route.getControllerClass(), route.getControllerMethod())); } else if (RouteType.RESOURCE_FILE.equals(route.getRouteType())) { routingHandler.add(Methods.GET, route.getUrl(), getResourceHandler(null)); } } return routingHandler; } private ResourceHandler getResourceHandler(String postfix) { if (StringUtils.isBlank(postfix)) { if (this.resourceHandler == null) { this.resourceHandler = new ResourceHandler(new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), Default.FILES_FOLDER.toString() + "/")); } return this.resourceHandler; } return new ResourceHandler(new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), Default.FILES_FOLDER.toString() + postfix)); } public void startUndertow() { if (!this.error) { this.host = this.config.getString(Key.APPLICATION_HOST, Default.APPLICATION_HOST.toString()); this.port = this.config.getInt(Key.APPLICATION_PORT, Default.APPLICATION_PORT.toInt()); Undertow server = Undertow.builder() .addHttpListener(this.port, this.host) .setHandler(Handlers.exceptionHandler(this.pathHandler).addExceptionHandler(Throwable.class, new ExceptionHandler())) .build(); server.start(); } } private List<Module> getModules() { List<Module> modules = new ArrayList<Module>(); if (!this.error) { try { Class<?> module = Class.forName(Default.MODULE_CLASS.toString()); AbstractModule abstractModule; abstractModule = (AbstractModule) module.getConstructor().newInstance(); modules.add(abstractModule); modules.add(new Modules()); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException | ClassNotFoundException e) { LOG.error("Failed to load modules. Check that conf/Module.java exisits in your application", e); this.error = true; } } return modules; } public void showLogo() { if (!this.error) { StringBuilder logo = new StringBuilder(INITIAL_SIZE); try { logo.append("\n").append(FigletFont.convertOneLine("mangoo I/O")).append("\n\n").append("https://mangoo.io | @mangoo_io | " + getVersion() + "\n"); } catch (IOException e) {//NOSONAR //intentionally left blank } LOG.info(logo.toString()); LOG.info("mangoo I/O application started @{}:{} in {} ms in {} mode. Enjoy.", this.host, this.port, ChronoUnit.MILLIS.between(this.start, LocalDateTime.now()), this.mode.toString()); } } public void applicationStarted() { this.injector.getInstance(MangooLifecycle.class).applicationStarted(); } public GreenMail startGreenMail() { GreenMail greenMail = null; if (!this.error && !Mode.PROD.equals(Application.getMode())) { greenMail = new GreenMail(new ServerSetup( this.config.getInt(Key.SMTP_PORT, Default.SMTP_PORT.toInt()), this.config.getString(Key.SMTP_HOST, Default.LOCALHOST.toString()), Default.FAKE_SMTP_PROTOCOL.toString())); greenMail.start(); } return greenMail; } public void startQuartzScheduler() { if (!this.error) { Set<Class<?>> jobs = new Reflections(this.config.getSchedulerPackage()).getTypesAnnotatedWith(Schedule.class); if (jobs != null && !jobs.isEmpty() && this.config.isSchedulerAutostart()) { MangooScheduler mangooScheduler = this.injector.getInstance(MangooScheduler.class); for (Class<?> clazz : jobs) { Schedule schedule = clazz.getDeclaredAnnotation(Schedule.class); if (CronExpression.isValidExpression(schedule.cron())) { JobDetail jobDetail = mangooScheduler.createJobDetail(clazz.getName(), Default.SCHEDULER_JOB_GROUP.toString(), clazz.asSubclass(Job.class)); Trigger trigger = mangooScheduler.createTrigger(clazz.getName() + "-trigger", Default.SCHEDULER_TRIGGER_GROUP.toString(), schedule.description(), schedule.cron()); mangooScheduler.schedule(jobDetail, trigger); LOG.info("Successfully scheduled job " + clazz.getName() + " with cron " + schedule.cron()); } else { LOG.error("Invalid or missing cron expression for job: " + clazz.getName()); this.error = true; } } if (!this.error) { mangooScheduler.start(); } } } } public void prepareLogging() { if (Mode.PROD.equals(this.mode)) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); try { URL resource = Resources.getResource(Default.LOGBACK_PROD_FILE.toString()); if (resource != null) { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(context); context.reset(); configurator.doConfigure(resource); } } catch (JoranException | IllegalArgumentException e) { //NOSONAR //intentionally left blank } } } private String getVersion() { String version = Default.VERSION.toString(); try (InputStream inputStream = Resources.getResource(Default.VERSION_PROPERTIES.toString()).openStream()) { Properties properties = new Properties(); properties.load(inputStream); version = String.valueOf(properties.get(Key.VERSION.toString())); } catch (IOException e) { LOG.error("Failed to get application version", e); } return version; } public boolean isApplicationStarted() { return !this.error; } }
package io.openkit.leaderboards; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import io.openkit.OKHTTPClient; import io.openkit.OKLog; import io.openkit.OKScore; import io.openkit.OKUser; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class OKScoreCache extends SQLiteOpenHelper{ private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "OKCACHEDB"; private static final String TABLE_SCORES = "OKCACHE"; private static final String KEY_ID = "id"; private static final String KEY_LEADERBOARD_ID = "leaderboardID"; private static final String KEY_SCOREVALUE = "scoreValue"; private static final String KEY_METADATA = "metadata"; private static final String KEY_DISPLAYSTRING = "displayString"; private static final String KEY_SUBMITTED = "submitted"; public OKScoreCache(Context ctx) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String createCacheTable = "CREATE TABLE IF NOT EXISTS " + TABLE_SCORES + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LEADERBOARD_ID + " INTEGER, "+ KEY_SCOREVALUE + " BIGINT, " + KEY_METADATA + " INTEGER, " + KEY_DISPLAYSTRING + " VARCHAR(255), " + KEY_SUBMITTED + " BOOLEAN);"; db.execSQL(createCacheTable); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES); onCreate(db); } public void insertScore(OKScore score) { ContentValues values = new ContentValues(); values.put(KEY_DISPLAYSTRING, score.getDisplayString()); values.put(KEY_LEADERBOARD_ID, score.getOKLeaderboardID()); values.put(KEY_METADATA, score.getMetadata()); values.put(KEY_SCOREVALUE, score.getScoreValue()); values.put(KEY_SUBMITTED, score.isSubmitted()); SQLiteDatabase db = this.getWritableDatabase(); long rowID = db.insert(TABLE_SCORES, null, values); score.setOKScoreID((int)rowID); db.close(); OKLog.v("Inserted score into db: " + score); } public void deleteScore(OKScore score) { if(score.getOKScoreID() <=0) { OKLog.v("Tried to delete a score from cache without an ID"); return; } SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_SCORES , KEY_ID + " = ?", new String[] { String.valueOf(score.getOKScoreID()) }); db.close(); } public void updateCachedScoreSubmitted(OKScore score) { if(score.getOKScoreID() <=0) { OKLog.v("Tried to update a score from cache without an ID"); return; } ContentValues values = new ContentValues(); values.put(KEY_SUBMITTED, score.isSubmitted()); SQLiteDatabase db = this.getWritableDatabase(); db.update(TABLE_SCORES , values, KEY_ID + " = ?", new String[] { String.valueOf(score.getOKScoreID()) }); db.close(); } public List<OKScore> getCachedScoresForLeaderboardID(int leaderboardID, boolean submittedScoresOnly) { String queryFormat; if(submittedScoresOnly) { queryFormat = "SELECT * FROM %s WHERE leaderboardID=%d AND submitted=1"; } else { queryFormat = "SELECT * FROM %s WHERE leaderboardID=%d"; } String selectQuery = String.format(queryFormat, TABLE_SCORES, leaderboardID); return getScoresWithQuerySQL(selectQuery); } public List<OKScore> getUnsubmittedCachedScores() { String queryFormat = "SELECT * FROM %s WHERE submitted=0"; String selectQuery = String.format(queryFormat, TABLE_SCORES); return getScoresWithQuerySQL(selectQuery); } public List<OKScore> getAllCachedScores() { String queryFormat = "SELECT * FROM %s"; String selectQuery = String.format(queryFormat, TABLE_SCORES); return getScoresWithQuerySQL(selectQuery); } private List<OKScore> getScoresWithQuerySQL(String querySQL) { List<OKScore> scoresList = new ArrayList<OKScore>(); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(querySQL, null); if(cursor.moveToFirst()) { do { OKScore score = new OKScore(); score.setOKScoreID(cursor.getInt(0)); score.setOKLeaderboardID(cursor.getInt(1)); score.setScoreValue(cursor.getLong(2)); score.setMetadata(cursor.getInt(3)); score.setDisplayString(cursor.getString(4)); int submitted = cursor.getInt(5); if(submitted == 0) { score.setSubmitted(false); } else { score.setSubmitted(true); } scoresList.add(score); } while (cursor.moveToNext()); } db.close(); return scoresList; } public void clearCachedSubmittedScores() { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DELETE FROM " + TABLE_SCORES + " WHERE " + KEY_SUBMITTED + "=1"); db.close(); //logScoreCache(); } // Unused for now, use clearCachedSubmittedScores() instead. This drops the entire table, where as clearCachedSubmitted() is used to clear // out scores that have been submitted when a userID changes /* private void clearCache() { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORES); this.onCreate(db); }*/ /* private void logScoreCache() { List<OKScore> scoreList = getAllCachedScores(); OKLog.d("Score cache contains:"); for(int x =0; x < scoreList.size(); x++) { OKLog.d("1: " + scoreList.get(x)); } }*/ private void submitCachedScore(final OKScore score) { if(OKUser.getCurrentUser() != null) { score.setOKUser(OKUser.getCurrentUser()); score.cachedScoreSubmit(new OKScore.ScoreRequestResponseHandler() { @Override public void onSuccess() { OKLog.v("Submitted cached score successfully: " + score); updateCachedScoreSubmitted(score); } @Override public void onFailure(Throwable error) { // If the server responds with an error code in the 400s, delete the score from the cache if(OKHTTPClient.isErrorCodeInFourHundreds(error)) { OKLog.v("Deleting score from cache because server responded with error code in 400s"); deleteScore(score); } } }); } else { OKLog.v("Tried to submit cached score without having an OKUser logged in"); } } public void submitAllCachedScores() { if(OKUser.getCurrentUser() == null) { return; } List<OKScore> cachedScores = getUnsubmittedCachedScores(); for(int x = 0; x < cachedScores.size(); x++) { OKScore score = cachedScores.get(x); submitCachedScore(score); } } public boolean storeScoreInCacheIfBetterThanLocalCachedScores(OKScore score) { List<OKScore> cachedScores; // If there is a user logged in, we should compare against scores that have already been submitted to decide whether // to submit the new score, and not all scores. E.g. if there is an unsubmitted score for some reason that has a higher value than the // one to submit, we should still submit it. This is because for some reason there might be an unsubmitted score stored that will never // get submitted for some unknown reason. if(OKUser.getCurrentUser() != null) { cachedScores = getCachedScoresForLeaderboardID(score.getOKLeaderboardID(), true); } else { cachedScores = getCachedScoresForLeaderboardID(score.getOKLeaderboardID(), false); } if(cachedScores.size() <= 1) { insertScore(score); return true; } else { // Sort the scores in descending order Comparator<OKScore> descendingComparator = new Comparator<OKScore>() { @Override public int compare(OKScore s1, OKScore s2) { return (s1.getScoreValue()>s2.getScoreValue() ? -1 : (s1.getScoreValue()==s2.getScoreValue() ? 0 : 1)); } }; Collections.sort(cachedScores,descendingComparator); OKScore higestScore = cachedScores.get(0); OKScore lowestScore = cachedScores.get(cachedScores.size()-1); if(score.getScoreValue() > higestScore.getScoreValue()) { deleteScore(higestScore); insertScore(score); return true; } else if (score.getScoreValue() < lowestScore.getScoreValue()) { deleteScore(lowestScore); insertScore(score); return true; } } return false; } }
package com.aerospike.client.cluster; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Arrays; import java.util.HashMap; import com.aerospike.client.AerospikeException; import com.aerospike.client.Host; import com.aerospike.client.Info; import com.aerospike.client.Log; import com.aerospike.client.util.Util; public final class NodeValidator { String name; Host[] aliases; InetSocketAddress address; boolean useNewInfo = true; public NodeValidator(Host host, int timeoutMillis) throws AerospikeException { setAliases(host); setAddress(timeoutMillis); } private void setAliases(Host host) throws AerospikeException { try { InetAddress[] addresses = InetAddress.getAllByName(host.name); int count = 0; aliases = new Host[addresses.length]; for (InetAddress address : addresses) { aliases[count++] = new Host(address.getHostAddress(), host.port); } } catch (UnknownHostException uhe) { throw new AerospikeException.Connection("Invalid host: " + host); } } private void setAddress(int timeoutMillis) throws AerospikeException { for (Host alias : aliases) { try { InetSocketAddress address = new InetSocketAddress(alias.name, alias.port); Connection conn = new Connection(address, timeoutMillis); try { HashMap<String,String> map = Info.request(conn, "node", "build"); String buildVersion = map.get("build"); if (map != null) { this.name = map.get("node"); this.address = address; //check new info protocol support for >= 2.6.6 build String[] vNumber = buildVersion.split("\\."); try { int initialVersionNumber = Integer.parseInt(vNumber[0]); this.useNewInfo = initialVersionNumber >= 3 || (initialVersionNumber >= 2 && (Integer.parseInt(vNumber[1]) >= 6 && Integer.parseInt(vNumber[2]) >= 6 )); } catch (NumberFormatException e) { return; } return; } } finally { conn.close(); } } catch (Exception e) { // Try next address. if (Log.debugEnabled()) { Log.debug("Alias " + alias + " failed: " + Util.getErrorMessage(e)); } } } throw new AerospikeException.Connection("Failed to connect to host aliases: " + Arrays.toString(aliases)); } }
package org.jetel.component; import java.io.IOException; import java.security.InvalidParameterException; import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.data.DataRecord; import org.jetel.data.Defaults; import org.jetel.data.parser.JExcelXLSDataParser; import org.jetel.data.parser.XLSParser; import org.jetel.exception.BadDataFormatException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.ParserExceptionHandlerFactory; import org.jetel.exception.PolicyType; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.Node; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.graph.runtime.WatchDog; import org.jetel.util.MultiFileReader; import org.jetel.util.NumberIterator; import org.jetel.util.SynchronizeUtils; import org.jetel.util.property.ComponentXMLAttributes; import org.jetel.util.string.StringUtils; import org.w3c.dom.Element; public class XLSReader extends Node { public final static String COMPONENT_TYPE = "XLS_READER"; static Log logger = LogFactory.getLog(XLSReader.class); /** XML attribute names */ public static final String XML_STARTROW_ATTRIBUTE = "startRow"; public static final String XML_FINALROW_ATTRIBUTE = "finalRow"; public static final String XML_NUMRECORDS_ATTRIBUTE = "numRecords"; public static final String XML_MAXERRORCOUNT_ATTRIBUTE = "maxErrorCount"; public final static String XML_FILE_ATTRIBUTE = "fileURL"; public final static String XML_DATAPOLICY_ATTRIBUTE = "dataPolicy"; public final static String XML_SHEETNAME_ATTRIBUTE = "sheetName"; public final static String XML_SHEETNUMBER_ATTRIBUTE = "sheetNumber"; public final static String XML_METADATAROW_ATTRIBUTE = "metadataRow"; public final static String XML_FIELDMAP_ATTRIBUTE = "fieldMap"; public final static String XML_CHARSET_ATTRIBUTE = "charset"; private static final String XML_INCREMENTAL_FILE_ATTRIBUTE = "incrementalFile"; private static final String XML_INCREMENTAL_KEY_ATTRIBUTE = "incrementalKey"; private final static String DEFAULT_SHEET = "0"; private final static String XLS_CELL_CODE_INDICATOR = " private final static int OUTPUT_PORT = 0; private final static int CLOVER_FIELDS = 0; private final static int XLS_FIELDS = 1; private String fileURL; private int startRow = 0; private int finalRow = -1; private int numRecords = -1; private int maxErrorCount = -1; private String incrementalFile; private String incrementalKey; private XLSParser parser; private MultiFileReader reader; private PolicyType policyType = PolicyType.STRICT; private String sheetName = null; private String sheetNumber = null; private int metadataRow = 0; private String[][] fieldMap; /** * @param id */ public XLSReader(String id, String fileURL, String[][] fieldMap) { super(id); this.fileURL = fileURL; this.fieldMap = fieldMap; this.parser = new JExcelXLSDataParser(); } public XLSReader(String id, String fileURL, String[][] fieldMap, String charset) { super(id); this.fileURL = fileURL; this.fieldMap = fieldMap; this.parser = new JExcelXLSDataParser(charset); } /* (non-Javadoc) * @see org.jetel.graph.Node#getType() */ @Override public String getType() { return COMPONENT_TYPE; } @Override public Result execute() throws Exception { DataRecord record = new DataRecord(getOutputPort(OUTPUT_PORT).getMetadata()); record.init(); int errorCount = 0; while (((record) != null) && runIt) { try { record = reader.getNext(record); if (record!=null){ writeRecordBroadcast(record); } }catch(BadDataFormatException bdfe){ if(policyType == PolicyType.STRICT) { throw bdfe; } else { logger.info(bdfe.getMessage()); if(maxErrorCount != -1 && ++errorCount > maxErrorCount) { logger.error("DataParser (" + getName() + "): Max error count exceeded."); break; } } } SynchronizeUtils.cloverYield(); } broadcastEOF(); return runIt ? Result.FINISHED_OK : Result.ABORTED; } @Override public void free() { if(!isInitialized()) return; super.free(); storeValues(); reader.close(); } /** * Stores all values as incremental reading. */ private void storeValues() { WatchDog watchDog = getGraph().getWatchDog(); if (watchDog != null && watchDog.getStatus() == Result.FINISHED_OK) { try { reader.storeIncrementalReading(); } catch (IOException e) { throw new RuntimeException(e); } } } /* * (non-Javadoc) * * @see org.jetel.graph.GraphElement#checkConfig() */ @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { super.checkConfig(status); if(!checkInputPorts(status, 0, 0) || !checkOutputPorts(status, 1, Integer.MAX_VALUE)) { return status; } checkMetadata(status, getOutMetadata()); try {//check sheetNumber parameter if (sheetNumber != null) { Iterator<Integer> number = new NumberIterator(sheetNumber,0,Integer.MAX_VALUE); if (!number.hasNext()) { throw new IllegalArgumentException("There is no sheet with requested number"); } }else if (sheetName == null) { sheetNumber = "0"; } if (sheetNumber != null) { parser.setSheetNumber(sheetNumber); }else{ parser.setSheetName(sheetName); } //because of stdin try{//sheet number OK, check file name reader = new MultiFileReader(parser, getGraph() != null ? getGraph().getProjectURL() : null, fileURL); //reader.init(getOutputPort(OUTPUT_PORT).getMetadata()); reader.close(); /*}catch(ComponentNotReadyException e){ ConfigurationProblem problem = new ConfigurationProblem( "Problem with file URL: " + fileURL + " or not valid " + "sheet number: \"" + sheetNumber + "\" nor sheet name: \"" + sheetName + "\"", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); problem.setAttributeName(XML_FILE_ATTRIBUTE); status.add(problem); }*/ } catch (IllegalArgumentException e) { ConfigurationProblem problem = new ConfigurationProblem(e.getMessage(), ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); problem.setAttributeName(XML_SHEETNUMBER_ATTRIBUTE); status.add(problem); } return status; } public static Node fromXML(TransformationGraph graph, Element nodeXML) throws XMLConfigurationException { XLSReader aXLSReader = null; ComponentXMLAttributes xattribs = new ComponentXMLAttributes(nodeXML, graph); try { String[] fMap =null; String[][] fieldMap = null; if (xattribs.exists(XML_FIELDMAP_ATTRIBUTE)){ fMap = StringUtils.split(xattribs.getString(XML_FIELDMAP_ATTRIBUTE)); // fMap = xattribs.getString(XML_FIELDMAP_ATTRIBUTE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX); fieldMap = new String[fMap.length][2]; for (int i=0;i<fieldMap.length;i++){ fieldMap[i] = fMap[i].split(Defaults.ASSIGN_SIGN + "|="); } } if (xattribs.exists(XML_CHARSET_ATTRIBUTE)){ aXLSReader = new XLSReader(xattribs.getString(Node.XML_ID_ATTRIBUTE), xattribs.getString(XML_FILE_ATTRIBUTE),fieldMap, xattribs.getString(XML_CHARSET_ATTRIBUTE)); }else{ aXLSReader = new XLSReader(xattribs.getString(Node.XML_ID_ATTRIBUTE), xattribs.getString(XML_FILE_ATTRIBUTE),fieldMap); } aXLSReader.setPolicyType(xattribs.getString(XML_DATAPOLICY_ATTRIBUTE, null)); aXLSReader.setStartRow(xattribs.getInteger(XML_STARTROW_ATTRIBUTE,1)); if (xattribs.exists(XML_FINALROW_ATTRIBUTE)){ aXLSReader.setFinalRow(xattribs.getInteger(XML_FINALROW_ATTRIBUTE)); } if (xattribs.exists(XML_NUMRECORDS_ATTRIBUTE)){ aXLSReader.setNumRecords(xattribs.getInteger(XML_NUMRECORDS_ATTRIBUTE)); } if (xattribs.exists(XML_MAXERRORCOUNT_ATTRIBUTE)){ aXLSReader.setMaxErrorCount(xattribs.getInteger(XML_MAXERRORCOUNT_ATTRIBUTE)); } if (xattribs.exists(XML_SHEETNUMBER_ATTRIBUTE)){ aXLSReader.setSheetNumber(xattribs.getString(XML_SHEETNUMBER_ATTRIBUTE)); }else if (xattribs.exists(XML_SHEETNAME_ATTRIBUTE)){ aXLSReader.setSheetName(xattribs.getString(XML_SHEETNAME_ATTRIBUTE)); } if (xattribs.exists(XML_METADATAROW_ATTRIBUTE)){ aXLSReader.setMetadataRow(xattribs.getInteger(XML_METADATAROW_ATTRIBUTE)); } if (xattribs.exists(XML_INCREMENTAL_FILE_ATTRIBUTE)){ aXLSReader.setIncrementalFile(xattribs.getString(XML_INCREMENTAL_FILE_ATTRIBUTE)); } if (xattribs.exists(XML_INCREMENTAL_KEY_ATTRIBUTE)){ aXLSReader.setIncrementalKey(xattribs.getString(XML_INCREMENTAL_KEY_ATTRIBUTE)); } } catch (Exception ex) { throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex); } return aXLSReader; } /** * Description of the Method * * @return Description of the Returned Value * @since May 21, 2002 */ public void toXML(Element xmlElement) { super.toXML(xmlElement); xmlElement.setAttribute(XML_FILE_ATTRIBUTE, this.fileURL); xmlElement.setAttribute(XML_DATAPOLICY_ATTRIBUTE, policyType.toString()); if (fieldMap != null){ String[] fm = new String[fieldMap.length]; for (int i=0;i<fm.length;i++){ fm[i] = StringUtils.stringArraytoString(fieldMap[i],Defaults.ASSIGN_SIGN); } xmlElement.setAttribute(XML_FIELDMAP_ATTRIBUTE,StringUtils.stringArraytoString(fm,Defaults.Component.KEY_FIELDS_DELIMITER)); } xmlElement.setAttribute(XML_STARTROW_ATTRIBUTE,String.valueOf(parser.getFirstRow())); if (finalRow > -1) { xmlElement.setAttribute(XML_FINALROW_ATTRIBUTE,String.valueOf(this.finalRow)); } if (maxErrorCount > -1) { xmlElement.setAttribute(XML_MAXERRORCOUNT_ATTRIBUTE,String.valueOf(this.maxErrorCount)); } if (parser.getMetadataRow() > -1) { xmlElement.setAttribute(XML_METADATAROW_ATTRIBUTE, String.valueOf(parser.getMetadataRow())); } if (sheetName != null) { xmlElement.setAttribute(XML_SHEETNAME_ATTRIBUTE,this.sheetName); }else{ xmlElement.setAttribute(XML_SHEETNUMBER_ATTRIBUTE,String.valueOf(parser.getSheetNumber())); } if (parser instanceof JExcelXLSDataParser && ((JExcelXLSDataParser)parser).getCharset() != null){ xmlElement.setAttribute(XML_CHARSET_ATTRIBUTE, ((JExcelXLSDataParser)parser).getCharset()); } } public void setPolicyType(String strPolicyType) { setPolicyType(PolicyType.valueOfIgnoreCase(strPolicyType)); } public void setPolicyType(PolicyType policyType) { this.policyType = policyType; parser.setExceptionHandler(ParserExceptionHandlerFactory.getHandler(policyType)); } public int getStartRow() { return startRow; } /** * @param startRow The startRow to set. */ public void setStartRow(int startRecord) { if(startRecord < 1 || (finalRow != -1 && startRecord > finalRow)) { throw new InvalidParameterException("Invalid StartRecord parameter."); } this.startRow = startRecord; parser.setFirstRow(startRecord-1); } /** * @return Returns the finalRow. */ public int getFinalRow() { return finalRow; } /** * @param finalRow The finalRow to set. */ public void setFinalRow(int finalRecord) { if(finalRecord < 0 || (startRow != -1 && startRow > finalRecord)) { throw new InvalidParameterException("Invalid finalRow parameter."); } this.finalRow = finalRecord; parser.setLastRow(finalRow - 1); } /** * @param finalRow The finalRow to set. */ public void setMaxErrorCount(int maxErrorCount) { if(maxErrorCount < 0) { throw new InvalidParameterException("Invalid maxErrorCount parameter."); } this.maxErrorCount = maxErrorCount; } /* (non-Javadoc) * @see org.jetel.graph.GraphElement#init() */ @Override public void init() throws ComponentNotReadyException { if(isInitialized()) return; super.init(); if (sheetNumber != null) { parser.setSheetNumber(sheetNumber); }else if (sheetName != null) { parser.setSheetName(sheetName); }else{ parser.setSheetNumber(DEFAULT_SHEET); } //set proper mapping type between clover and xls fields if (fieldMap != null){ String[] cloverFields = new String[fieldMap.length]; String[] xlsFields = new String[fieldMap.length]; for (int i=0;i<fieldMap.length;i++){ cloverFields[i] = fieldMap[i][CLOVER_FIELDS]; if (cloverFields[i].startsWith(Defaults.CLOVER_FIELD_INDICATOR)) { cloverFields[i] = cloverFields[i].substring(Defaults.CLOVER_FIELD_INDICATOR.length()); } if (fieldMap[i].length > 1) { xlsFields[i] = fieldMap[i][XLS_FIELDS]; }else { xlsFields[i] = null; } } parser.setCloverFields(cloverFields); if (xlsFields[0] != null){ if (xlsFields[0].startsWith("$") || xlsFields[0].startsWith(XLS_CELL_CODE_INDICATOR)){ for (int i=0;i<xlsFields.length;i++){ xlsFields[i] = xlsFields[i].substring(1); } parser.setMappingType(XLSParser.CLOVER_FIELDS_AND_XLS_NUMBERS); parser.setXlsFields(xlsFields); }else{ parser.setMappingType(XLSParser.CLOVER_FIELDS_AND_XLS_NAMES); parser.setXlsFields(xlsFields); } }else { parser.setMappingType(XLSParser.ONLY_CLOVER_FIELDS); } }else if (metadataRow != 0){ parser.setMappingType(XLSParser.MAP_NAMES); }else{ parser.setMappingType(XLSParser.NO_METADATA_INFO); } reader = new MultiFileReader(parser, getGraph() != null ? getGraph().getProjectURL() : null, fileURL); reader.setLogger(logger); reader.setNumRecords(numRecords); reader.setIncrementalFile(incrementalFile); reader.setIncrementalKey(incrementalKey); reader.init(getOutputPort(OUTPUT_PORT).getMetadata()); } @Override public synchronized void reset() throws ComponentNotReadyException { super.reset(); reader.reset(); } public void setSheetName(String sheetName) { this.sheetName = sheetName; } public void setMetadataRow(int metadaRow) { this.metadataRow = metadaRow; try { parser.setMetadataRow(metadataRow - 1); } catch (ComponentNotReadyException e) { throw new InvalidParameterException("Invalid metadaRow parameter."); } } public void setSheetNumber(String sheetNumber) { this.sheetNumber = sheetNumber; } public void setNumRecords(int numRecords) { this.numRecords = numRecords; } public void setIncrementalFile(String incrementalFile) { this.incrementalFile = incrementalFile; } public void setIncrementalKey(String incrementalKey) { this.incrementalKey = incrementalKey; } }
package codearea.skin; import static codearea.control.TwoDimensional.Bias.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.function.BiConsumer; import javafx.beans.property.BooleanProperty; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.geometry.Bounds; import javafx.geometry.VPos; import javafx.scene.control.IndexRange; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.shape.Path; import javafx.scene.shape.PathElement; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import codearea.control.Paragraph; import codearea.control.StyledText; import codearea.control.TwoLevelNavigator; import com.sun.javafx.scene.text.HitInfo; import com.sun.javafx.scene.text.TextLayout; import com.sun.javafx.text.PrismTextLayout; import com.sun.javafx.text.TextLine; public class ParagraphGraphic<S> extends TextFlow { private static Method mGetTextLayout; private static Method mGetLines; static { try { mGetTextLayout = TextFlow.class.getDeclaredMethod("getTextLayout"); mGetLines = PrismTextLayout.class.getDeclaredMethod("getLines"); } catch (NoSuchMethodException | SecurityException e) { throw new RuntimeException(e); } mGetTextLayout.setAccessible(true); mGetLines.setAccessible(true); } // FIXME: changing it currently has not effect, because // Text.impl_selectionFillProperty().set(newFill) doesn't work // properly for Text node inside a TextFlow (as of JDK8-b100). private final ObjectProperty<Paint> highlightTextFill = new SimpleObjectProperty<Paint>(Color.WHITE); private final Paragraph<S> paragraph; private int caretPosition; private IndexRange selection; private final Path caretShape = new Path(); private final Path selectionShape = new Path(); public ParagraphGraphic(Paragraph<S> par, BiConsumer<Text, S> applyStyle) { this.paragraph = par; // selection highlight selectionShape.setManaged(false); selectionShape.setVisible(true); selectionShape.setFill(Color.DODGERBLUE); selectionShape.setStrokeWidth(0); getChildren().add(selectionShape); // caret caretShape.setManaged(false); caretShape.setStrokeWidth(1); getChildren().add(caretShape); // XXX: see the note at highlightTextFill // highlightTextFill.addListener(new ChangeListener<Paint>() { // @Override // public void changed(ObservableValue<? extends Paint> observable, // Paint oldFill, Paint newFill) { // for(PumpedUpText text: textNodes()) // text.impl_selectionFillProperty().set(newFill); // populate with text nodes for(StyledText<S> segment: par.getSegments()) { Text t = new Text(segment.toString()); t.setTextOrigin(VPos.TOP); t.getStyleClass().add("text"); applyStyle.accept(t, segment.getStyle()); // XXX: binding selectionFill to textFill, // see the note at highlightTextFill t.impl_selectionFillProperty().bind(t.fillProperty()); // keep the caret graphic up to date t.fontProperty().addListener(obs -> updateCaretShape()); // keep the selection graphic up to date t.fontProperty().addListener(obs -> updateSelectionShape()); getChildren().add(t); } setCaretPosition(0); setSelection(0, 0); } public void dispose() { // do nothing } public Paragraph<S> getParagraph() { return paragraph; } void setCaretPosition(int pos) { if(pos < 0 || pos > paragraph.length()) throw new IndexOutOfBoundsException(); caretPosition = pos; updateCaretShape(); } void setSelection(IndexRange selection) { this.selection = selection; updateSelectionShape(); } void setSelection(int start, int end) { setSelection(new IndexRange(start, end)); } public BooleanProperty caretVisibleProperty() { return caretShape.visibleProperty(); } public ObjectProperty<Paint> highlightFillProperty() { return selectionShape.fillProperty(); } public ObjectProperty<Paint> highlightTextFillProperty() { return highlightTextFill; } HitInfo hit(int lineIndex, double x) { return hit(x, getLineCenter(lineIndex)); } HitInfo hit(double x, double y) { HitInfo hit = textLayout().getHitInfo((float)x, (float)y); if(hit.getCharIndex() == paragraph.length()) // clicked beyond the end of line hit.setLeading(true); // prevent going to the start of the next line return hit; } public double getCaretOffsetX() { Bounds bounds = caretShape.getLayoutBounds(); return (bounds.getMinX() + bounds.getMaxX()) / 2; } public int getLineCount() { return getLines().length; } public int currentLineIndex() { TextLine[] lines = getLines(); TwoLevelNavigator navigator = new TwoLevelNavigator(() -> lines.length, i -> lines[i].getLength()); return navigator.offsetToPosition(caretPosition, Forward).getMajor(); } private float getLineCenter(int index) { return getLineY(index) + getLines()[index].getBounds().getHeight() / 2; } private float getLineY(int index) { TextLine[] lines = getLines(); float spacing = (float) getLineSpacing(); float lineY = 0; for(int i = 0; i < index; ++i) { lineY += lines[i].getBounds().getHeight() + spacing; } return lineY; } private TextLayout textLayout() { return (TextLayout) invoke(mGetTextLayout, this); } private TextLine[] getLines() { return (TextLine[]) invoke(mGetLines, textLayout()); } private static Object invoke(Method m, Object obj, Object... args) { try { return m.invoke(obj, args); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RuntimeException(e); } } private void updateCaretShape() { PathElement[] shape = textLayout().getCaretShape(caretPosition, true, 0, 0); caretShape.getElements().setAll(shape); } private void updateSelectionShape() { int start = selection.getStart(); int end = selection.getEnd(); PathElement[] shape = textLayout().getRange(start, end, TextLayout.TYPE_TEXT, 0, 0); selectionShape.getElements().setAll(shape); } }
package org.xbill.DNS; import java.io.*; import java.text.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A representation of a domain name. * * @author Brian Wellington */ public class Name implements Comparable { private static final int LABEL_NORMAL = 0; private static final int LABEL_COMPRESSION = 0xC0; private static final int LABEL_EXTENDED = 0x40; private static final int LABEL_MASK = 0xC0; private static final int EXT_LABEL_BITSTRING = 1; private Object [] name; private byte labels; private boolean qualified; private int hashcode; /** The root name */ public static final Name root = Name.fromConstantString("."); /** The maximum number of labels in a Name */ static final int MAXLABELS = 128; /* The number of labels initially allocated. */ private static final int STARTLABELS = 4; /* Used for printing non-printable characters */ private static DecimalFormat byteFormat = new DecimalFormat(); /* Used to efficiently convert bytes to lowercase */ private static byte lowercase[] = new byte[256]; static { byteFormat.setMinimumIntegerDigits(3); for (int i = 0; i < lowercase.length; i++) { if (i < 'A' || i > 'Z') lowercase[i] = (byte)i; else lowercase[i] = (byte)(i - 'A' + 'a'); } } private Name() { } private final void grow(int n) { if (n > MAXLABELS) throw new ArrayIndexOutOfBoundsException("name too long"); Object [] newarray = new Object[n]; System.arraycopy(name, 0, newarray, 0, labels); name = newarray; } private final void grow() { grow(labels * 2); } private final void compact() { for (int i = labels - 1; i > 0; i if (!(name[i] instanceof BitString) || !(name[i - 1] instanceof BitString)) continue; BitString bs = (BitString) name[i]; BitString bs2 = (BitString) name[i - 1]; if (bs.nbits == 256) continue; int nbits = bs.nbits + bs2.nbits; bs.join(bs2); if (nbits <= 256) { System.arraycopy(name, i, name, i - 1, labels - i); labels } } } /** * Create a new name from a string and an origin * @param s The string to be converted * @param origin If the name is unqualified, the origin to be appended * @deprecated As of dnsjava 1.3.0, replaced by <code>Name.fromString</code>. */ public Name(String s, Name origin) { Name n; try { n = Name.fromString(s, origin); } catch (TextParseException e) { StringBuffer sb = new StringBuffer(); sb.append(s); if (origin != null) { sb.append("."); sb.append(origin); } sb.append(": "); sb.append(e.getMessage()); System.err.println(sb.toString()); name = null; labels = 0; return; } labels = n.labels; name = n.name; qualified = n.qualified; if (!qualified) { /* * This isn't exactly right, but it's close. * Partially qualified names are evil. */ if (Options.check("pqdn")) qualified = false; else qualified = (labels > 1); } } /** * Create a new name from a string * @param s The string to be converted * @deprecated as of dnsjava 1.3.0, replaced by <code>Name.fromString</code>. */ public Name(String s) { this (s, null); } /** * Create a new name from a string and an origin. This does not automatically * make the name absolute; it will be absolute if it has a trailing dot or an * absolute origin is appended. * @param s The string to be converted * @param origin If the name is unqualified, the origin to be appended. * @throws TextParseException The name is invalid. */ public static Name fromString(String s, Name origin) throws TextParseException { Name name = new Name(); name.labels = 0; name.name = new Object[1]; boolean seenBitString = false; if (s.equals("@")) { if (origin != null) name.append(origin); name.qualified = true; return name; } else if (s.equals(".")) { name.qualified = true; return name; } int labelstart = -1; int pos = 0; byte [] label = new byte[64]; boolean escaped = false; int digits = 0; int intval = 0; boolean bitstring = false; for (int i = 0; i < s.length(); i++) { byte b = (byte) s.charAt(i); if (escaped) { if (pos == 0 && b == '[') bitstring = true; if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10 + (b - '0'); intval += (b - '0'); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); if (pos >= label.length) throw new TextParseException("label too long"); label[pos++] = b; escaped = false; } else if (b == '\\') { escaped = true; digits = 0; intval = 0; } else if (b == '.') { if (labelstart == -1) throw new TextParseException("invalid label"); byte [] newlabel = new byte[pos]; System.arraycopy(label, 0, newlabel, 0, pos); if (name.labels == MAXLABELS) throw new TextParseException("too many labels"); if (name.labels == name.name.length) name.grow(); if (bitstring) { bitstring = false; name.name[name.labels++] = new BitString(newlabel); } else name.name[name.labels++] = newlabel; labelstart = -1; pos = 0; } else { if (labelstart == -1) labelstart = i; if (pos >= label.length) throw new TextParseException("label too long"); label[pos++] = b; } } if (labelstart == -1) name.qualified = true; else { byte [] newlabel = new byte[pos]; System.arraycopy(label, 0, newlabel, 0, pos); if (name.labels == MAXLABELS) throw new TextParseException("too many labels"); if (name.labels == name.name.length) name.grow(); if (bitstring) { bitstring = false; name.name[name.labels++] = new BitString(newlabel); } else name.name[name.labels++] = newlabel; } if (!name.qualified && origin != null) name.append(origin); if (seenBitString) name.compact(); return (name); } /** * Create a new name from a string. This does not automatically make the name * absolute; it will be absolute if it has a trailing dot. * @param s The string to be converted * @throws TextParseException The name is invalid. */ public static Name fromString(String s) throws TextParseException { return fromString(s, null); } public static Name fromConstantString(String s) { try { return fromString(s, null); } catch (TextParseException e) { throw new IllegalArgumentException("Invalid name '" + s + "'"); } } /** * Create a new name from DNS wire format * @param in A stream containing the input data */ public Name(DataByteInputStream in) throws IOException { int len, start, pos, count = 0, savedpos; Name name2; boolean seenBitString = false; labels = 0; name = new Object[STARTLABELS]; start = in.getPos(); loop: while ((len = in.readUnsignedByte()) != 0) { count++; switch(len & LABEL_MASK) { case LABEL_NORMAL: byte [] b = new byte[len]; in.read(b); if (labels == name.length) grow(); name[labels++] = b; break; case LABEL_COMPRESSION: pos = in.readUnsignedByte(); pos += ((len & ~LABEL_MASK) << 8); if (Options.check("verbosecompression")) System.err.println("currently " + in.getPos() + ", pointer to " + pos); if (pos >= in.getPos()) throw new WireParseException("bad compression"); savedpos = in.getPos(); in.setPos(pos); if (Options.check("verbosecompression")) System.err.println("current name '" + this + "', seeking to " + pos); try { name2 = new Name(in); } finally { in.setPos(savedpos); } if (labels + name2.labels > name.length) grow(labels + name2.labels); System.arraycopy(name2.name, 0, name, labels, name2.labels); labels += name2.labels; break loop; case LABEL_EXTENDED: int type = len & ~LABEL_MASK; switch (type) { case EXT_LABEL_BITSTRING: int bits = in.readUnsignedByte(); if (bits == 0) bits = 256; int bytes = (bits + 7) / 8; byte [] data = new byte[bytes]; in.read(data); if (labels == name.length) grow(); name[labels++] = new BitString(bits, data); seenBitString = true; break; default: throw new WireParseException( "Unknown name format"); } /* switch */ break; } /* switch */ } qualified = true; if (seenBitString) compact(); } /** * Create a new name by removing labels from the beginning of an existing Name * @param d An existing Name * @param n The number of labels to remove from the beginning in the copy */ /* Skips n labels and creates a new name */ public Name(Name d, int n) { name = new Object[d.labels - n]; labels = (byte) (d.labels - n); System.arraycopy(d.name, n, name, 0, labels); qualified = d.qualified; } /** * Generates a new Name with the first n labels replaced by a wildcard * @return The wildcard name */ public Name wild(int n) { Name wild = new Name(this, n - 1); wild.name[0] = new byte[] {(byte)'*'}; return wild; } /** * Generates a new Name to be used when following a DNAME. * @return The new name, or null if the DNAME is invalid. */ public Name fromDNAME(DNAMERecord dname) { Name dnameowner = dname.getName(); Name dnametarget = dname.getTarget(); int nlabels; int saved; if (!subdomain(dnameowner)) return null; saved = labels - dnameowner.labels; nlabels = saved + dnametarget.labels; if (nlabels > MAXLABELS) return null; Name newname = new Name(); newname.labels = (byte)nlabels; newname.name = new Object[labels]; System.arraycopy(this.name, 0, newname.name, 0, saved); System.arraycopy(dnametarget.name, 0, newname.name, saved, dnametarget.labels); newname.qualified = true; newname.compact(); return newname; } /** * Is this name a wildcard? */ public boolean isWild() { if (labels == 0 || (name[0] instanceof BitString)) return false; byte [] b = (byte []) name[0]; return (b.length == 1 && b[0] == '*'); } /** * Is this name fully qualified? */ public boolean isQualified() { return qualified; } /** * Appends the specified name to the end of the current Name */ private void append(Name d) { if (labels + d.labels > name.length) grow(labels + d.labels); System.arraycopy(d.name, 0, name, labels, d.labels); labels += d.labels; qualified = d.qualified; compact(); } /** * The length of the name. */ public short length() { short total = 0; for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) total += (((BitString)name[i]).bytes() + 2); else total += (((byte [])name[i]).length + 1); } return ++total; } /** * The number of labels in the name. */ public byte labels() { return labels; } /** * Is the current Name a subdomain of the specified name? */ public boolean subdomain(Name domain) { if (domain == null || domain.labels > labels) return false; Name tname = new Name(this, labels - domain.labels); return (tname.equals(domain)); } private String byteString(byte [] array) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { /* Ick. */ short b = (short)(array[i] & 0xFF); if (b <= 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == '(' || b == ')' || b == '.' || b == ';' || b == '\\' || b == '@' || b == '$') { sb.append('\\'); sb.append((char)b); } else sb.append((char)b); } return sb.toString(); } /** * Convert Name to a String */ public String toString() { StringBuffer sb = new StringBuffer(); if (labels == 0) sb.append("."); for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) sb.append(name[i]); else sb.append(byteString((byte [])name[i])); if (qualified || i < labels - 1) sb.append("."); } return sb.toString(); } /** * Convert the nth label in a Name to a String * @param n The label to be converted to a String */ public String getLabelString(int n) { if (name[n] instanceof BitString) return name[n].toString(); else return byteString((byte [])name[n]); } /** * Convert Name to DNS wire format */ public void toWire(DataByteOutputStream out, Compression c) throws IOException { boolean log = (c != null && Options.check("verbosecompression")); for (int i = 0; i < labels; i++) { Name tname; if (i == 0) tname = this; else tname = new Name(this, i); int pos = -1; if (c != null) { pos = c.get(tname); if (log) System.err.println("Looking for " + tname + ", found " + pos); } if (pos >= 0) { pos |= (LABEL_MASK << 8); out.writeShort(pos); return; } else { if (c != null) { c.add(out.getPos(), tname); if (log) System.err.println("Adding " + tname + " at " + out.getPos()); } if (name[i] instanceof BitString) { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } else out.writeString((byte []) name[i]); } } out.writeByte(0); } /** * Convert Name to canonical DNS wire format (all lowercase) */ public void toWireCanonical(DataByteOutputStream out) throws IOException { for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } else { byte [] b = (byte []) name[i]; byte [] bc = new byte[b.length]; for (int j = 0; j < b.length; j++) bc[j] = lowercase[b[j]]; out.writeString(bc); } } out.writeByte(0); } /** * Are these two Names equivalent? */ public boolean equals(Object arg) { if (arg == this) return true; if (arg == null || !(arg instanceof Name)) return false; Name d = (Name) arg; if (d.labels != labels) return false; for (int i = 0; i < labels; i++) { if (name[i].getClass() != d.name[i].getClass()) return false; if (name[i] instanceof BitString) { if (!name[i].equals(d.name[i])) return false; } else { byte [] b1 = (byte []) name[i]; byte [] b2 = (byte []) d.name[i]; if (b1.length != b2.length) return false; for (int j = 0; j < b1.length; j++) { if (lowercase[b1[j]] != lowercase[b2[j]]) return false; } } } return true; } /** * Computes a hashcode based on the value */ public int hashCode() { if (hashcode != 0) return (hashcode); int code = labels; for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) { BitString b = (BitString) name[i]; for (int j = 0; j < b.bytes(); j++) code += ((code << 3) + b.data[j]); } else { byte [] b = (byte []) name[i]; for (int j = 0; j < b.length; j++) code += ((code << 3) + lowercase[b[j]]); } } hashcode = code; return hashcode; } /** * Compares this Name to another Object. * @param The Object to be compared. * @return The value 0 if the argument is a name equivalent to this name; * a value less than 0 if the argument is less than this name in the canonical * ordering, and a value greater than 0 if the argument is greater than this * name in the canonical ordering. * @throws ClassCastException if the argument is not a String. */ public int compareTo(Object o) { Name arg = (Name) o; int compares = labels > arg.labels ? arg.labels : labels; for (int i = 1; i <= compares; i++) { Object label = name[labels - i]; Object alabel = arg.name[arg.labels - i]; if (label.getClass() != alabel.getClass()) { if (label instanceof BitString) return (-1); else return (1); } if (label instanceof BitString) { BitString bs = (BitString)label; BitString abs = (BitString)alabel; int bits = bs.nbits > abs.nbits ? abs.nbits : bs.nbits; int n = bs.compareBits(abs, bits); if (n != 0) return (n); if (bs.nbits == abs.nbits) continue; /* * If label X has more bits than label Y, then the * name with X is greater if Y is the first label * of its name. Otherwise, the name with Y is greater. */ if (bs.nbits > abs.nbits) return (i == arg.labels ? 1 : -1); else return (i == labels ? -1 : 1); } else { byte [] b = (byte []) label; byte [] ab = (byte []) alabel; for (int j = 0; j < b.length && j < ab.length; j++) { int n = lowercase[b[j]] - lowercase[ab[j]]; if (n != 0) return (n); } if (b.length != ab.length) return (b.length - ab.length); } } return (labels - arg.labels); } }
package com.Acrobot.ChestShop.Listeners.Player; import com.Acrobot.Breeze.Utils.BlockUtil; import com.Acrobot.Breeze.Utils.InventoryUtil; import com.Acrobot.Breeze.Utils.MaterialUtil; import com.Acrobot.Breeze.Utils.PriceUtil; import com.Acrobot.ChestShop.Configuration.Messages; import com.Acrobot.ChestShop.Configuration.Properties; import com.Acrobot.ChestShop.Containers.AdminInventory; import com.Acrobot.ChestShop.Events.PreTransactionEvent; import com.Acrobot.ChestShop.Events.TransactionEvent; import com.Acrobot.ChestShop.Permission; import com.Acrobot.ChestShop.Plugins.ChestShop; import com.Acrobot.ChestShop.Security; import com.Acrobot.ChestShop.Signs.ChestShopSign; import com.Acrobot.ChestShop.Utils.uBlock; import com.Acrobot.ChestShop.Utils.uName; import org.bukkit.Bukkit; import org.bukkit.GameMode; import org.bukkit.Material; import org.bukkit.OfflinePlayer; import org.bukkit.block.Block; import org.bukkit.block.Chest; import org.bukkit.block.Sign; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import static com.Acrobot.Breeze.Utils.BlockUtil.isChest; import static com.Acrobot.Breeze.Utils.BlockUtil.isSign; import static com.Acrobot.ChestShop.Events.TransactionEvent.TransactionType; import static com.Acrobot.ChestShop.Events.TransactionEvent.TransactionType.BUY; import static com.Acrobot.ChestShop.Events.TransactionEvent.TransactionType.SELL; import static com.Acrobot.ChestShop.Signs.ChestShopSign.*; import static org.bukkit.event.block.Action.LEFT_CLICK_BLOCK; import static org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK; /** * @author Acrobot */ public class PlayerInteract implements Listener { @EventHandler(priority = EventPriority.HIGHEST) public static void onInteract(PlayerInteractEvent event) { Block block = event.getClickedBlock(); if (block == null) { return; } Action action = event.getAction(); Player player = event.getPlayer(); if (isChest(block) && Properties.USE_BUILT_IN_PROTECTION) { if (Properties.TURN_OFF_DEFAULT_PROTECTION_WHEN_PROTECTED_EXTERNALLY) { return; } if (!canOpenOtherShops(player) && !ChestShop.canAccess(player, block)) { player.sendMessage(Messages.prefix(Messages.ACCESS_DENIED)); event.setCancelled(true); } return; } if (!isSign(block) || player.getItemInHand().getType() == Material.SIGN) { // Blocking accidental sign edition return; } Sign sign = (Sign) block.getState(); if (!ChestShopSign.isValid(sign)) { return; } if (ChestShopSign.canAccess(player, sign)) { if (!Properties.ALLOW_SIGN_CHEST_OPEN || player.isSneaking() || player.getGameMode() == GameMode.CREATIVE) { return; } if (!Properties.ALLOW_LEFT_CLICK_DESTROYING || action != LEFT_CLICK_BLOCK) { event.setCancelled(true); showChestGUI(player, block); } return; } if (action == RIGHT_CLICK_BLOCK) { event.setCancelled(true); } PreTransactionEvent pEvent = preparePreTransactionEvent(sign, player, action); if (pEvent == null) { return; } Bukkit.getPluginManager().callEvent(pEvent); if (pEvent.isCancelled()) { return; } TransactionEvent tEvent = new TransactionEvent(pEvent, sign); Bukkit.getPluginManager().callEvent(tEvent); } private static PreTransactionEvent preparePreTransactionEvent(Sign sign, Player player, Action action) { String ownerName = uName.getName(sign.getLine(NAME_LINE)); OfflinePlayer owner = Bukkit.getOfflinePlayer(ownerName); String priceLine = sign.getLine(PRICE_LINE); Action buy = Properties.REVERSE_BUTTONS ? LEFT_CLICK_BLOCK : RIGHT_CLICK_BLOCK; double price = (action == buy ? PriceUtil.getBuyPrice(priceLine) : PriceUtil.getSellPrice(priceLine)); Chest chest = uBlock.findConnectedChest(sign); Inventory ownerInventory = (ChestShopSign.isAdminShop(sign) ? new AdminInventory() : chest != null ? chest.getInventory() : null); ItemStack item = MaterialUtil.getItem(sign.getLine(ITEM_LINE)); if (item == null) { player.sendMessage(Messages.prefix(Messages.INVALID_SHOP_DETECTED)); return null; } int amount = Integer.parseInt(sign.getLine(QUANTITY_LINE)); if (amount < 1) { amount = 1; } if (Properties.SHIFT_SELLS_EVERYTHING && player.isSneaking() && price != PriceUtil.NO_PRICE) { int newAmount = getItemAmount(item, ownerInventory, player, action); if (newAmount > 0) { price = (price / amount) * newAmount; amount = newAmount; } } item.setAmount(amount); ItemStack[] items = {item}; TransactionType transactionType = (action == buy ? BUY : SELL); return new PreTransactionEvent(ownerInventory, player.getInventory(), items, price, player, owner, sign, transactionType); } private static int getItemAmount(ItemStack item, Inventory inventory, Player player, Action action) { Action buy = Properties.REVERSE_BUTTONS ? LEFT_CLICK_BLOCK : RIGHT_CLICK_BLOCK; if (action == buy) { return InventoryUtil.getAmount(item, inventory); } else { return InventoryUtil.getAmount(item, player.getInventory()); } } public static boolean canOpenOtherShops(Player player) { return Permission.has(player, Permission.ADMIN) || Permission.has(player, Permission.MOD); } private static void showChestGUI(Player player, Block signBlock) { Chest chest = uBlock.findConnectedChest(signBlock); if (chest == null) { player.sendMessage(Messages.prefix(Messages.NO_CHEST_DETECTED)); return; } if (!canOpenOtherShops(player) && !Security.canAccess(player, signBlock)) { return; } BlockUtil.openBlockGUI(chest, player); } }
package org.xbill.DNS; import java.io.*; import java.text.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A representation of a domain name. * * @author Brian Wellington */ public class Name implements Comparable { private static final int LABEL_NORMAL = 0; private static final int LABEL_COMPRESSION = 0xC0; private static final int LABEL_MASK = 0xC0; private byte [] name; private byte labels; private long offsets; private int hashcode; private static final byte [] emptyLabel = new byte[] {(byte)0}; private static final byte [] wildLabel = new byte[] {(byte)1, (byte)'*'}; /** The root name */ public static final Name root; /** The maximum length of a Name */ private static final int MAXNAME = 255; /** The maximum length of labels a label a Name */ private static final int MAXLABEL = 63; /** The maximum number of labels in a Name */ private static final int MAXLABELS = 128; /** The maximum number of cached offsets */ private static final int MAXOFFSETS = 8; /* Used for printing non-printable characters */ private static final DecimalFormat byteFormat = new DecimalFormat(); /* Used to efficiently convert bytes to lowercase */ private static final byte lowercase[] = new byte[256]; /* Used in wildcard names. */ private static final Name wild; static { byteFormat.setMinimumIntegerDigits(3); for (int i = 0; i < lowercase.length; i++) { if (i < 'A' || i > 'Z') lowercase[i] = (byte)i; else lowercase[i] = (byte)(i - 'A' + 'a'); } root = new Name(); wild = new Name(); root.appendSafe(emptyLabel, 0, 1); wild.appendSafe(wildLabel, 0, 1); } private Name() { } private final void dump(String prefix) { String s; try { s = toString(); } catch (Exception e) { s = "<unprintable>"; } System.out.println(prefix + ": " + s); for (int i = 0; i < labels; i++) System.out.print(offset(i) + " "); System.out.println(""); for (int i = 0; name != null && i < name.length; i++) System.out.print((name[i] & 0xFF) + " "); System.out.println(""); } private final void setoffset(int n, int offset) { if (n >= MAXOFFSETS) return; int shift = 8 * (7 - n); offsets &= (~(0xFFL << shift)); offsets |= ((long)offset << shift); } private final int offset(int n) { if (n < MAXOFFSETS) { int shift = 8 * (7 - n); return ((int)(offsets >>> shift) & 0xFF); } else { int pos = offset(MAXOFFSETS - 1); for (int i = MAXOFFSETS - 1; i < n; i++) pos += (name[pos] + 1); return (pos); } } private static final void copy(Name src, Name dst) { dst.name = src.name; dst.labels = src.labels; dst.offsets = src.offsets; } private final void append(byte [] array, int start, int n) throws NameTooLongException { int length = (name == null ? 0 : (name.length - offset(0))); int alength = 0; for (int i = 0, pos = start; i < n; i++) { int len = array[pos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); len++; pos += len; alength += len; } int newlength = length + alength; if (newlength > MAXNAME) throw new NameTooLongException(); int newlabels = labels + n; if (newlabels > MAXLABELS) throw new IllegalStateException("too many labels"); byte [] newname = new byte[newlength]; if (length != 0) System.arraycopy(name, offset(0), newname, 0, length); System.arraycopy(array, start, newname, length, alength); name = newname; for (int i = 0, pos = length; i < n; i++) { setoffset(labels + i, pos); pos += (newname[pos] + 1); } labels = (byte) newlabels; } private final void appendFromString(byte [] array, int start, int n) throws TextParseException { try { append(array, start, n); } catch (NameTooLongException e) { throw new TextParseException("Name too long"); } } private final void appendSafe(byte [] array, int start, int n) { try { append(array, start, n); } catch (NameTooLongException e) { } } /** * Create a new name from a string and an origin * @param s The string to be converted * @param origin If the name is not absolute, the origin to be appended * @deprecated As of dnsjava 1.3.0, replaced by <code>Name.fromString</code>. */ public Name(String s, Name origin) { Name n; try { n = Name.fromString(s, origin); } catch (TextParseException e) { StringBuffer sb = new StringBuffer(s); if (origin != null) sb.append("." + origin); sb.append(": "+ e.getMessage()); System.err.println(sb.toString()); return; } if (!n.isAbsolute() && !Options.check("pqdn") && n.labels > 1 && n.labels < MAXLABELS - 1) { /* * This isn't exactly right, but it's close. * Partially qualified names are evil. */ n.appendSafe(emptyLabel, 0, 1); } copy(n, this); } /** * Create a new name from a string * @param s The string to be converted * @deprecated as of dnsjava 1.3.0, replaced by <code>Name.fromString</code>. */ public Name(String s) { this (s, null); } /** * Create a new name from a string and an origin. This does not automatically * make the name absolute; it will be absolute if it has a trailing dot or an * absolute origin is appended. * @param s The string to be converted * @param origin If the name is not absolute, the origin to be appended. * @throws TextParseException The name is invalid. */ public static Name fromString(String s, Name origin) throws TextParseException { Name name = new Name(); if (s.equals("")) throw new TextParseException("empty name"); else if (s.equals("@")) { if (origin == null) return name; return origin; } else if (s.equals(".")) return (root); int labelstart = -1; int pos = 1; byte [] label = new byte[MAXLABEL + 1]; boolean escaped = false; int digits = 0; int intval = 0; boolean absolute = false; for (int i = 0; i < s.length(); i++) { byte b = (byte) s.charAt(i); if (escaped) { if (b >= '0' && b <= '9' && digits < 3) { digits++; intval *= 10 + (b - '0'); intval += (b - '0'); if (digits < 3) continue; b = (byte) intval; } else if (digits > 0 && digits < 3) throw new TextParseException("bad escape"); if (pos >= MAXLABEL) throw new TextParseException("label too long"); labelstart = pos; label[pos++] = b; escaped = false; } else if (b == '\\') { escaped = true; digits = 0; intval = 0; } else if (b == '.') { if (labelstart == -1) throw new TextParseException("invalid label"); label[0] = (byte)(pos - 1); name.appendFromString(label, 0, 1); labelstart = -1; pos = 1; } else { if (labelstart == -1) labelstart = i; if (pos >= MAXLABEL) throw new TextParseException("label too long"); label[pos++] = b; } } if (labelstart == -1) { name.appendFromString(emptyLabel, 0, 1); absolute = true; } else { label[0] = (byte)(pos - 1); name.appendFromString(label, 0, 1); } if (origin != null && !absolute) name.appendFromString(origin.name, 0, origin.labels); return (name); } /** * Create a new name from a string. This does not automatically make the name * absolute; it will be absolute if it has a trailing dot. * @param s The string to be converted * @throws TextParseException The name is invalid. */ public static Name fromString(String s) throws TextParseException { return fromString(s, null); } public static Name fromConstantString(String s) { try { return fromString(s, null); } catch (TextParseException e) { throw new IllegalArgumentException("Invalid name '" + s + "'"); } } /** * Create a new name from DNS wire format * @param in A stream containing the input data */ public Name(DataByteInputStream in) throws IOException { int len, pos, savedpos; Name name2; boolean done = false; byte [] label = new byte[MAXLABEL + 1]; while (!done) { len = in.readUnsignedByte(); switch (len & LABEL_MASK) { case LABEL_NORMAL: if (labels >= MAXLABELS) throw new WireParseException("too many labels"); if (len == 0) { append(emptyLabel, 0, 1); done = true; } else { label[0] = (byte)len; in.readArray(label, 1, len); append(label, 0, 1); } break; case LABEL_COMPRESSION: pos = in.readUnsignedByte(); pos += ((len & ~LABEL_MASK) << 8); if (Options.check("verbosecompression")) System.err.println("currently " + in.getPos() + ", pointer to " + pos); savedpos = in.getPos(); if (pos >= savedpos) throw new WireParseException("bad compression"); in.setPos(pos); if (Options.check("verbosecompression")) System.err.println("current name '" + this + "', seeking to " + pos); try { name2 = new Name(in); } finally { in.setPos(savedpos); } append(name2.name, 0, name2.labels); done = true; break; } } } /** * Create a new name by removing labels from the beginning of an existing Name * @param src An existing Name * @param n The number of labels to remove from the beginning in the copy */ public Name(Name src, int n) { if (n > src.labels) throw new IllegalArgumentException("attempted to remove too " + "many labels"); name = src.name; labels = (byte)(src.labels - n); for (int i = 0; i < MAXOFFSETS && i < src.labels - n; i++) setoffset(i, src.offset(i + n)); } /** * Creates a new name by concatenating two existing names. * @param prefix The prefix name. * @param suffix The suffix name. * @return The concatenated name. * @throws NameTooLongException The name is too long. */ public static Name concatenate(Name prefix, Name suffix) throws NameTooLongException { if (prefix.isAbsolute()) return (prefix); Name newname = new Name(); copy(prefix, newname); newname.append(suffix.name, suffix.offset(0), suffix.labels); return newname; } /** * Generates a new Name with the first n labels replaced by a wildcard * @return The wildcard name */ public Name wild(int n) { if (n < 1) throw new IllegalArgumentException("must replace 1 or more " + "labels"); try { Name newname = new Name(); copy(wild, newname); newname.append(name, offset(n), labels - n); return newname; } catch (NameTooLongException e) { throw new IllegalStateException ("Name.wild: concatenate failed"); } } /** * Generates a new Name to be used when following a DNAME. * @param dname The DNAME record to follow. * @return The constructed name. * @throws NameTooLongException The resulting name is too long. */ public Name fromDNAME(DNAMERecord dname) throws NameTooLongException { Name dnameowner = dname.getName(); Name dnametarget = dname.getTarget(); if (!subdomain(dnameowner)) return null; int plabels = labels - dnameowner.labels; int plength = length() - dnameowner.length(); int pstart = offset(0); int dlabels = dnametarget.labels; int dlength = dnametarget.length(); if (plength + dlength > MAXNAME) throw new NameTooLongException(); Name newname = new Name(); newname.labels = (byte)(plabels + dlabels); newname.name = new byte[plength + dlength]; System.arraycopy(name, pstart, newname.name, 0, plength); System.arraycopy(dnametarget.name, 0, newname.name, plength, dlength); for (int i = 0, pos = 0; i < MAXOFFSETS && i < newname.labels; i++) { newname.setoffset(i, pos); pos += (newname.name[pos] + 1); } return newname; } /** * Is this name a wildcard? */ public boolean isWild() { if (labels == 0) return false; return (name[0] == (byte)1 && name[1] == (byte)'*'); } /** * Is this name fully qualified (that is, absolute)? * @deprecated As of dnsjava 1.3.0, replaced by <code>isAbsolute</code>. */ public boolean isQualified() { return (isAbsolute()); } /** * Is this name absolute? */ public boolean isAbsolute() { if (labels == 0) return false; return (name[name.length - 1] == 0); } /** * The length of the name. */ public short length() { return (short)(name.length - offset(0)); } /** * The number of labels in the name. */ public byte labels() { return labels; } /** * Is the current Name a subdomain of the specified name? */ public boolean subdomain(Name domain) { if (domain == null || domain.labels > labels) return false; if (domain.labels == labels) return equals(domain); return domain.equals(name, offset(labels - domain.labels)); } private String byteString(byte [] array, int pos) { StringBuffer sb = new StringBuffer(); int len = array[pos++]; for (int i = pos; i < pos + len; i++) { short b = (short)(array[i] & 0xFF); if (b <= 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == '(' || b == ')' || b == '.' || b == ';' || b == '\\' || b == '@' || b == '$') { sb.append('\\'); sb.append((char)b); } else sb.append((char)b); } return sb.toString(); } /** * Convert Name to a String */ public String toString() { if (labels == 0) return "@"; else if (labels == 1 && name[offset(0)] == 0) return "."; StringBuffer sb = new StringBuffer(); for (int i = 0, pos = offset(0); i < labels; i++) { int len = name[pos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); if (len == 0) break; sb.append(byteString(name, pos)); sb.append('.'); pos += (1 + len); } if (!isAbsolute()) sb.deleteCharAt(sb.length() - 1); return sb.toString(); } /** * Convert the nth label in a Name to a String * @param n The label to be converted to a String */ public String getLabelString(int n) { int pos = offset(n); return byteString(name, pos); } public void toWire(DataByteOutputStream out, Compression c) throws IOException { if (!isAbsolute()) throw new IllegalArgumentException("toWire() called on " + "non-absolute name"); for (int i = 0; i < labels - 1; i++) { Name tname; if (i == 0) tname = this; else tname = new Name(this, i); int pos = -1; if (c != null) pos = c.get(tname); if (pos >= 0) { pos |= (LABEL_MASK << 8); out.writeShort(pos); return; } else { if (c != null) c.add(out.getPos(), tname); out.writeString(name, offset(i)); } } out.writeByte(0); } /** * Convert Name to canonical DNS wire format (all lowercase) * @param out The output stream to which the message is written. * @throws IOException An error occurred writing the name. */ public void toWireCanonical(DataByteOutputStream out) throws IOException { byte [] b = toWireCanonical(); out.write(b); } /** * Convert Name to canonical DNS wire format (all lowercase) * @throws IOException An error occurred writing the name. */ public byte [] toWireCanonical() throws IOException { if (labels == 0) return (new byte[0]); byte [] b = new byte[name.length - offset(0)]; for (int i = 0, pos = offset(0); i < labels; i++) { int len = name[pos]; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); b[pos] = name[pos++]; for (int j = 0; j < len; j++) b[pos] = lowercase[name[pos++]]; } return b; } private final boolean equals(byte [] b, int bpos) { for (int i = 0, pos = offset(0); i < labels; i++) { if (name[pos] != b[bpos]) return false; int len = name[pos++]; bpos++; if (len > MAXLABEL) throw new IllegalStateException("invalid label"); for (int j = 0; j < len; j++) if (lowercase[name[pos++]] != lowercase[b[bpos++]]) return false; } return true; } /** * Are these two Names equivalent? */ public boolean equals(Object arg) { if (arg == this) return true; if (arg == null || !(arg instanceof Name)) return false; Name d = (Name) arg; if (d.labels != labels) return false; return equals(d.name, d.offset(0)); } /** * Computes a hashcode based on the value */ public int hashCode() { if (hashcode != 0) return (hashcode); int code = labels; for (int i = offset(0); i < name.length; i++) code += ((code << 3) + lowercase[name[i]]); hashcode = code; return hashcode; } /** * Compares this Name to another Object. * @param o The Object to be compared. * @return The value 0 if the argument is a name equivalent to this name; * a value less than 0 if the argument is less than this name in the canonical * ordering, and a value greater than 0 if the argument is greater than this * name in the canonical ordering. * @throws ClassCastException if the argument is not a Name. */ public int compareTo(Object o) { Name arg = (Name) o; if (this == arg) return (0); int compares = labels > arg.labels ? arg.labels : labels; for (int i = 1; i <= compares; i++) { int start = offset(labels - i); int astart = arg.offset(arg.labels - i); int length = name[start]; int alength = arg.name[astart]; for (int j = 0; j < length && j < alength; j++) { int n = lowercase[name[j + start]] - lowercase[arg.name[j + astart]]; if (n != 0) return (n); } if (length != alength) return (length - alength); } return (labels - arg.labels); } }
package com.ociweb.grove; import static com.ociweb.iot.grove.GroveTwig.*; import com.ociweb.iot.maker.Hardware; import com.ociweb.iot.maker.CommandChannel; import com.ociweb.iot.maker.DeviceRuntime; import com.ociweb.iot.maker.IoTSetup; import com.ociweb.iot.maker.Port; import static com.ociweb.iot.maker.Port.*; import com.ociweb.gl.api.GreenCommandChannel; public class IoTApp implements IoTSetup { //Connection constants // // by using constants such as these you can easily use the right value to reference where the sensor was plugged in private static final Port THUMBJOYSTICK_PORT_Y = A0; private static final Port THUMBJOYSTICK_PORT_X = A1; @Override public void declareConnections(Hardware c) { //Connection specifications // // specify each of the connections on the harware, eg which component is plugged into which connection. c.connect(ThumbJoystick, THUMBJOYSTICK_PORT_Y); c.connect(ThumbJoystick, THUMBJOYSTICK_PORT_X); } @Override public void declareBehavior(DeviceRuntime runtime) { final CommandChannel channel1 = runtime.newCommandChannel(GreenCommandChannel.DYNAMIC_MESSAGING); runtime.addAnalogListener((port, time, durationMillis, average, value)->{ switch (port){ case A0: //the C value should be roughly between 200 to 800 unless pressed if (value < 1023){ System.out.println("X: "+value); } else { System.out.println("Pressed"); } break; case A1: System.out.println("Y: "+value); break; default: System.out.println("Please ensure that you are connecting to the correct port (A0)"); break; } }); } }
package org.xbill.DNS; import java.io.*; import java.text.*; import java.util.*; import org.xbill.DNS.utils.*; /** * A representation of a domain name. * * @author Brian Wellington */ public class Name { private static final int LABEL_NORMAL = 0; private static final int LABEL_COMPRESSION = 0xC0; private static final int LABEL_EXTENDED = 0x40; private static final int LABEL_MASK = 0xC0; private static final int EXT_LABEL_BITSTRING = 1; private Object [] name; private byte labels; private boolean qualified; /** The root name */ public static final Name root = new Name("."); /** The maximum number of labels in a Name */ static final int MAXLABELS = 128; /* The number of labels initially allocated. */ private static final int STARTLABELS = 4; /* Used for printing non-printable characters */ private static DecimalFormat byteFormat = new DecimalFormat(); static { byteFormat.setMinimumIntegerDigits(3); } private Name() { } private final void grow(int n) { if (n > MAXLABELS) throw new ArrayIndexOutOfBoundsException("name too long"); Object [] newarray = new Object[n]; System.arraycopy(name, 0, newarray, 0, labels); name = newarray; } private final void grow() { grow(labels * 2); } /** * Create a new name from a string and an origin * @param s The string to be converted * @param origin If the name is unqalified, the origin to be appended */ public Name(String s, Name origin) { labels = 0; name = new Object[STARTLABELS]; if (s.equals("@") && origin != null) { append(origin); qualified = true; return; } try { MyStringTokenizer st = new MyStringTokenizer(s, "."); while (st.hasMoreTokens()) { String token = st.nextToken(); if (labels == name.length) grow(); if (token.charAt(0) == '[') name[labels++] = new BitString(token); else name[labels++] = token.getBytes(); } if (st.hasMoreDelimiters()) qualified = true; else { if (origin != null) { append(origin); qualified = true; } else { /* This isn't exactly right, but it's close. * Partially qualified names are evil. */ if (Options.check("pqdn")) qualified = false; else qualified = (labels > 1); } } } catch (Exception e) { StringBuffer sb = new StringBuffer(); sb.append(s); if (origin != null) { sb.append("."); sb.append(origin); } if (e instanceof ArrayIndexOutOfBoundsException) sb.append(" has too many labels"); else if (e instanceof IOException) sb.append(" contains an invalid binary label"); else sb.append(" is invalid"); System.err.println(sb.toString()); name = null; labels = 0; } } /** * Create a new name from a string * @param s The string to be converted */ public Name(String s) { this (s, null); } /** * Create a new name from DNS wire format * @param in A stream containing the input data * @param c The compression context. This should be null unless a full * message is being parsed. */ public Name(DataByteInputStream in, Compression c) throws IOException { int len, start, pos, count = 0; Name name2; labels = 0; name = new Object[STARTLABELS]; start = in.getPos(); loop: while ((len = in.readUnsignedByte()) != 0) { switch(len & LABEL_MASK) { case LABEL_NORMAL: byte [] b = new byte[len]; in.read(b); if (labels == name.length) grow(); name[labels++] = b; count++; break; case LABEL_COMPRESSION: pos = in.readUnsignedByte(); pos += ((len & ~LABEL_MASK) << 8); name2 = (c == null) ? null : c.get(pos); if (Options.check("verbosecompression")) System.err.println("Looking at " + pos + ", found " + name2); if (name2 == null) throw new WireParseException("bad compression"); else { if (labels + name2.labels > name.length) grow(labels + name2.labels); System.arraycopy(name2.name, 0, name, labels, name2.labels); labels += name2.labels; } break loop; case LABEL_EXTENDED: int type = len & ~LABEL_MASK; switch (type) { case EXT_LABEL_BITSTRING: int bits = in.readUnsignedByte(); if (bits == 0) bits = 256; int bytes = (bits + 7) / 8; byte [] data = new byte[bytes]; in.read(data); if (labels == name.length) grow(); name[labels++] = new BitString(bits, data); count++; break; default: throw new WireParseException( "Unknown name format"); } /* switch */ break; } /* switch */ } if (c != null) { pos = start; if (Options.check("verbosecompression")) System.out.println("name = " + this + ", count = " + count); for (int i = 0; i < count; i++) { Name tname = new Name(this, i); c.add(pos, tname); if (Options.check("verbosecompression")) System.err.println("Adding " + tname + " at " + pos); if (name[i] instanceof BitString) pos += (((BitString)name[i]).bytes() + 2); else pos += (((byte [])name[i]).length + 1); } } qualified = true; } /** * Create a new name by removing labels from the beginning of an existing Name * @param d An existing Name * @param n The number of labels to remove from the beginning in the copy */ /* Skips n labels and creates a new name */ public Name(Name d, int n) { name = new Object[d.labels - n]; labels = (byte) (d.labels - n); System.arraycopy(d.name, n, name, 0, labels); qualified = d.qualified; } /** * Generates a new Name with the first n labels replaced by a wildcard * @return The wildcard name */ public Name wild(int n) { Name wild = new Name(this, n - 1); wild.name[0] = new byte[] {(byte)'*'}; return wild; } /** * Generates a new Name to be used when following a DNAME. * @return The new name, or null if the DNAME is invalid. */ public Name fromDNAME(DNAMERecord dname) { Name dnameowner = dname.getName(); Name dnametarget = dname.getTarget(); int nlabels; int saved; if (!subdomain(dnameowner)) return null; saved = labels - dnameowner.labels; nlabels = saved + dnametarget.labels; if (nlabels > MAXLABELS) return null; Name newname = new Name(); newname.labels = (byte)nlabels; newname.name = new Object[labels]; System.arraycopy(this.name, 0, newname.name, 0, saved); System.arraycopy(dnametarget.name, 0, newname.name, saved, dnametarget.labels); newname.qualified = true; return newname; } /** * Is this name a wildcard? */ public boolean isWild() { if (labels == 0 || (name[0] instanceof BitString)) return false; byte [] b = (byte []) name[0]; return (b.length == 1 && b[0] == '*'); } /** * Is this name fully qualified? */ public boolean isQualified() { return qualified; } /** * Appends the specified name to the end of the current Name */ public void append(Name d) { if (labels + d.labels > name.length) grow(labels + d.labels); System.arraycopy(d.name, 0, name, labels, d.labels); labels += d.labels; qualified = d.qualified; } /** * The length */ public short length() { short total = 0; for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) total += (((BitString)name[i]).bytes() + 2); else total += (((byte [])name[i]).length + 1); } return ++total; } /** * The number of labels */ public byte labels() { return labels; } /** * Is the current Name a subdomain of the specified name? */ public boolean subdomain(Name domain) { if (domain == null || domain.labels > labels) return false; Name tname = new Name(this, labels - domain.labels); return (tname.equals(domain)); } private String byteString(byte [] array) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < array.length; i++) { /* Ick. */ short b = (short)(array[i] & 0xFF); if (b <= 0x20 || b >= 0x7f) { sb.append('\\'); sb.append(byteFormat.format(b)); } else if (b == '"' || b == '(' || b == ')' || b == '.' || b == ';' || b == '\\' || b == '@' || b == '$') { sb.append('\\'); sb.append((char)b); } else sb.append((char)b); } return sb.toString(); } /** * Convert Name to a String */ public String toString() { StringBuffer sb = new StringBuffer(); if (labels == 0) sb.append("."); for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) sb.append(name[i]); else sb.append(byteString((byte [])name[i])); if (qualified || i < labels - 1) sb.append("."); } return sb.toString(); } /** * Convert the nth label in a Name to a String * @param n The label to be converted to a String */ public String getLabelString(int n) { if (name[n] instanceof BitString) return name[n].toString(); else return byteString((byte [])name[n]); } /** * Convert Name to DNS wire format */ public void toWire(DataByteOutputStream out, Compression c) throws IOException { for (int i = 0; i < labels; i++) { Name tname; if (i == 0) tname = this; else tname = new Name(this, i); int pos = -1; if (c != null) { pos = c.get(tname); if (Options.check("verbosecompression")) System.err.println("Looking for " + tname + ", found " + pos); } if (pos >= 0) { pos |= (LABEL_MASK << 8); out.writeShort(pos); return; } else { if (c != null) { c.add(out.getPos(), tname); if (Options.check("verbosecompression")) System.err.println("Adding " + tname + " at " + out.getPos()); } if (name[i] instanceof BitString) { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } else out.writeString((byte []) name[i]); } } out.writeByte(0); } /** * Convert Name to canonical DNS wire format (all lowercase) */ public void toWireCanonical(DataByteOutputStream out) throws IOException { for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) { out.writeByte(LABEL_EXTENDED | EXT_LABEL_BITSTRING); out.writeByte(((BitString)name[i]).wireBits()); out.write(((BitString)name[i]).data); } else out.writeStringCanonical(new String((byte []) name[i])); } out.writeByte(0); } private static final byte toLower(byte b) { if (b < 'A' || b > 'Z') return b; else return (byte)(b - 'A' + 'a'); } /** * Are these two Names equivalent? */ public boolean equals(Object arg) { if (arg == null || !(arg instanceof Name)) return false; if (arg == this) return true; Name d = (Name) arg; if (d.labels != labels) return false; for (int i = 0; i < labels; i++) { if (name[i].getClass() != d.name[i].getClass()) return false; if (name[i] instanceof BitString) { if (!name[i].equals(d.name[i])) return false; } else { byte [] b1 = (byte []) name[i]; byte [] b2 = (byte []) d.name[i]; if (b1.length != b2.length) return false; for (int j = 0; j < b1.length; j++) { if (toLower(b1[j]) != toLower(b2[j])) return false; } } } return true; } /** * Computes a hashcode based on the value */ public int hashCode() { int code = labels; for (int i = 0; i < labels; i++) { if (name[i] instanceof BitString) { BitString b = (BitString) name[i]; for (int j = 0; j < b.bytes(); j++) code += ((code << 3) + b.data[j]); } else { byte [] b = (byte []) name[i]; for (int j = 0; j < b.length; j++) code += ((code << 3) + toLower(b[j])); } } return code; } public int compareTo(Object o) { Name arg = (Name) o; int compares = labels > arg.labels ? arg.labels : labels; for (int i = 1; i <= compares; i++) { Object label = name[labels - i]; Object alabel = arg.name[arg.labels - i]; if (label.getClass() != alabel.getClass()) { if (label instanceof BitString) return (-1); else return (1); } if (label instanceof BitString) { BitString bs = (BitString)label; BitString abs = (BitString)alabel; int bits = bs.nbits > abs.nbits ? abs.nbits : bs.nbits; int n = bs.compareBits(abs, bits); if (n != 0) return (n); if (bs.nbits == abs.nbits) continue; /* * If label X has more bits than label Y, then the * name with X is greater if Y is the first label * of its name. Otherwise, the name with Y is greater. */ if (bs.nbits > abs.nbits) return (i == arg.labels ? 1 : -1); else return (i == labels ? -1 : 1); } else { byte [] b = (byte []) label; byte [] ab = (byte []) alabel; for (int j = 0; j < b.length && j < ab.length; j++) { int n = toLower(b[j]) - toLower(ab[j]); if (n != 0) return (n); } if (b.length != ab.length) return (b.length - ab.length); } } return (labels - arg.labels); } }
package org.xbill.DNS; import java.io.*; import java.net.*; import java.util.*; import org.xbill.DNS.utils.*; /** * Transaction signature handling. This class generates and verifies * TSIG records on messages, which provide transaction security, * @see TSIGRecord * * @author Brian Wellington */ public class TSIG { /** * The domain name representing the HMAC-MD5 algorithm (the only supported * algorithm) */ public static final String HMAC = "HMAC-MD5.SIG-ALG.REG.INT"; /** The default fudge value for outgoing packets. Can be overriden by the * tsigfudge option. */ public static final short FUDGE = 300; private Name name; private byte [] key; private hmacSigner axfrSigner = null; static { if (Options.check("verbosehmac")) hmacSigner.verbose = true; } /** * Creates a new TSIG object, which can be used to sign or verify a message. * @param name The name of the shared key * @param key The shared key's data */ public TSIG(String name, byte [] key) { this.name = new Name(name); this.key = key; } /** * Generates a TSIG record for a message and adds it to the message * @param m The message * @param old If this message is a response, the TSIG from the request */ public void apply(Message m, TSIGRecord old) throws IOException { Date timeSigned = new Date(); short fudge; hmacSigner h = new hmacSigner(key); Name alg = new Name(HMAC); if (Options.check("tsigfudge")) { String s = Options.value("tsigfudge"); try { fudge = Short.parseShort(s); } catch (NumberFormatException e) { fudge = FUDGE; } } else fudge = FUDGE; try { if (old != null) { DataByteOutputStream dbs = new DataByteOutputStream(); dbs.writeShort((short)old.getSignature().length); h.addData(dbs.toByteArray()); h.addData(old.getSignature()); } /* Digest the message */ h.addData(m.toWire()); DataByteOutputStream out = new DataByteOutputStream(); name.toWireCanonical(out); out.writeShort(DClass.ANY); /* class */ out.writeInt(0); /* ttl */ alg.toWireCanonical(out); long time = timeSigned.getTime() / 1000; short timeHigh = (short) (time >> 32); int timeLow = (int) (time); out.writeShort(timeHigh); out.writeInt(timeLow); out.writeShort(fudge); out.writeShort(0); /* No error */ out.writeShort(0); /* No other data */ h.addData(out.toByteArray()); } catch (IOException e) { return; } Record r = new TSIGRecord(name, DClass.ANY, 0, alg, timeSigned, fudge, h.sign(), m.getHeader().getID(), Rcode.NOERROR, null); m.addRecord(r, Section.ADDITIONAL); } /** * Verifies a TSIG record on an incoming message. Since this is only called * in the context where a TSIG is expected to be present, it is an error * if one is not present. * @param m The message * @param b The message in unparsed form. This is necessary since TSIG * signs the message in wire format, and we can't recreate the exact wire * format (with the same name compression). * @param old If this message is a response, the TSIG from the request */ public boolean verify(Message m, byte [] b, TSIGRecord old) { TSIGRecord tsig = m.getTSIG(); hmacSigner h = new hmacSigner(key); if (tsig == null) return false; /*System.out.println("found TSIG");*/ try { if (old != null && tsig.getError() != Rcode.BADKEY && tsig.getError() != Rcode.BADSIG) { DataByteOutputStream dbs = new DataByteOutputStream(); dbs.writeShort((short)old.getSignature().length); h.addData(dbs.toByteArray()); h.addData(old.getSignature()); /*System.out.println("digested query TSIG");*/ } m.getHeader().decCount(Section.ADDITIONAL); byte [] header = m.getHeader().toWire(); m.getHeader().incCount(Section.ADDITIONAL); h.addData(header); int len = b.length - header.length; len -= tsig.wireLength; h.addData(b, header.length, len); /*System.out.println("digested message");*/ DataByteOutputStream out = new DataByteOutputStream(); tsig.getName().toWireCanonical(out); out.writeShort(tsig.dclass); out.writeInt(tsig.ttl); tsig.getAlg().toWireCanonical(out); long time = tsig.getTimeSigned().getTime() / 1000; short timeHigh = (short) (time >> 32); int timeLow = (int) (time); out.writeShort(timeHigh); out.writeInt(timeLow); out.writeShort(tsig.getFudge()); out.writeShort(tsig.getError()); if (tsig.getOther() != null) { out.writeShort(tsig.getOther().length); out.write(tsig.getOther()); } else out.writeShort(0); h.addData(out.toByteArray()); /*System.out.println("digested variables");*/ } catch (IOException e) { return false; } if (axfrSigner != null) { DataByteOutputStream dbs = new DataByteOutputStream(); dbs.writeShort((short)tsig.getSignature().length); axfrSigner.addData(dbs.toByteArray()); axfrSigner.addData(tsig.getSignature()); } if (h.verify(tsig.getSignature())) return true; else return false; } /** Prepares the TSIG object to verify an AXFR */ public void verifyAXFRStart() { axfrSigner = new hmacSigner(key); } /** * Verifies a TSIG record on an incoming message that is part of an AXFR. * TSIG records must be present on the first and last messages, and * at least every 100 records in between (the last rule is not enforced). * @param m The message * @param b The message in unparsed form * @param old The TSIG from the AXFR request * @param required True if this message is required to include a TSIG. * @param first True if this message is the first message of the AXFR */ public boolean verifyAXFR(Message m, byte [] b, TSIGRecord old, boolean required, boolean first) { TSIGRecord tsig = m.getTSIG(); hmacSigner h = axfrSigner; if (first) return verify(m, b, old); try { if (tsig != null) m.getHeader().decCount(Section.ADDITIONAL); byte [] header = m.getHeader().toWire(); if (tsig != null) m.getHeader().incCount(Section.ADDITIONAL); h.addData(header); int len = b.length - header.length; if (tsig != null) len -= tsig.wireLength; h.addData(b, header.length, len); if (tsig == null) { if (required) return false; else return true; } DataByteOutputStream out = new DataByteOutputStream(); long time = tsig.getTimeSigned().getTime() / 1000; short timeHigh = (short) (time >> 32); int timeLow = (int) (time); out.writeShort(timeHigh); out.writeInt(timeLow); out.writeShort(tsig.getFudge()); h.addData(out.toByteArray()); } catch (IOException e) { return false; } if (h.verify(tsig.getSignature()) == false) { return false; } h.clear(); DataByteOutputStream dbs = new DataByteOutputStream(); dbs.writeShort((short)old.getSignature().length); h.addData(dbs.toByteArray()); h.addData(tsig.getSignature()); return true; } }
/** * This class is designed to contain common methods for the Consent Withdraw process. * This class will be used in CollectionProtocolRegistration, SpecimenCollectionGroup and Specimen Bizlogic classes. * * @author mandar_deshmukh * */ package edu.wustl.catissuecore.util; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import edu.wustl.catissuecore.bean.ConsentBean; import edu.wustl.catissuecore.bizlogic.BizLogicFactory; import edu.wustl.catissuecore.bizlogic.CollectionProtocolBizLogic; import edu.wustl.catissuecore.bizlogic.NewSpecimenBizLogic; import edu.wustl.catissuecore.domain.CollectionProtocol; import edu.wustl.catissuecore.domain.CollectionProtocolRegistration; import edu.wustl.catissuecore.domain.ConsentTier; import edu.wustl.catissuecore.domain.ConsentTierResponse; import edu.wustl.catissuecore.domain.ConsentTierStatus; import edu.wustl.catissuecore.domain.DisposalEventParameters; import edu.wustl.catissuecore.domain.ReturnEventParameters; import edu.wustl.catissuecore.domain.Specimen; import edu.wustl.catissuecore.domain.SpecimenCollectionGroup; import edu.wustl.catissuecore.domain.SpecimenPosition; import edu.wustl.catissuecore.domain.StorageContainer; import edu.wustl.catissuecore.domain.User; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.beans.NameValueBean; import edu.wustl.common.beans.SessionDataBean; import edu.wustl.common.bizlogic.IBizLogic; import edu.wustl.common.dao.DAO; import edu.wustl.common.util.dbManager.DAOException; /** * This class is designed to contain common methods for the Consent Withdraw process. * This class will be used in CollectionProtocolRegistration, SpecimenCollectionGroup and Specimen Bizlogic classes. * * @author mandar_deshmukh * */ public class ConsentUtil { /** * This method updates the SpecimenCollectionGroup instance by setting all the consent tierstatus to with * @param scg Instance of SpecimenCollectionGroup to be updated. * @param oldScg Instance of OldSpecimenCollectionGroup to be updated. * @param consentTierID Identifier of ConsentTier to be withdrawn. * @param withdrawOption Action to be performed on the withdrawn collectiongroup. * @param dao DAO instance. Used for inserting disposal event. * @param sessionDataBean SessionDataBean instance. Used for inserting disposal event. * @throws DAOException */ public static void updateSCG(SpecimenCollectionGroup scg, SpecimenCollectionGroup oldscg, long consentTierID, String withdrawOption, DAO dao, SessionDataBean sessionDataBean) throws DAOException { Collection newScgStatusCollection = new HashSet(); Collection consentTierStatusCollection =scg.getConsentTierStatusCollection(); Iterator itr = consentTierStatusCollection.iterator() ; while(itr.hasNext() ) { ConsentTierStatus consentTierstatus = (ConsentTierStatus)itr.next(); //compare consent tier id of scg with cpr consent tier of response if(consentTierstatus.getConsentTier().getId().longValue() == consentTierID) { consentTierstatus.setStatus(Constants.WITHDRAWN); updateSpecimensInSCG(scg,oldscg,consentTierID,withdrawOption , dao, sessionDataBean ); } newScgStatusCollection.add(consentTierstatus ); // set updated consenttierstatus in scg } scg.setConsentTierStatusCollection( newScgStatusCollection); if(!(withdrawOption.equals(Constants.WITHDRAW_RESPONSE_RESET))) { scg.setActivityStatus(Constants.ACTIVITY_STATUS_DISABLED); } } /** * This method updates the SpecimenCollectionGroup instance by setting all the consent tierstatus to with * @param scg Instance of SpecimenCollectionGroup to be updated. * @param consentTierID Identifier of ConsentTier to be withdrawn. * @param withdrawOption Action to be performed on the withdrawn collectiongroup. * @param dao DAO instance. Used for inserting disposal event. * @param sessionDataBean SessionDataBean instance. Used for inserting disposal event. * */ public static void updateSCG(SpecimenCollectionGroup scg, long consentTierID, String withdrawOption, DAO dao, SessionDataBean sessionDataBean) throws DAOException { updateSCG(scg, scg, consentTierID,withdrawOption,dao, sessionDataBean); } /* * This method updates the specimens for the given SCG and sets the consent status to withdraw. */ private static void updateSpecimensInSCG(SpecimenCollectionGroup scg, SpecimenCollectionGroup oldscg, long consentTierID, String consentWithdrawalOption, DAO dao, SessionDataBean sessionDataBean) throws DAOException { Collection specimenCollection =(Collection)dao.retrieveAttribute(SpecimenCollectionGroup.class.getName(),scg.getId(),"elements(specimenCollection)"); Collection updatedSpecimenCollection = new HashSet(); Iterator specimenItr = specimenCollection.iterator() ; while(specimenItr.hasNext()) { Specimen specimen = (Specimen)specimenItr.next(); updateSpecimenStatus(specimen, consentWithdrawalOption, consentTierID, dao, sessionDataBean); updatedSpecimenCollection.add(specimen ); } scg.setSpecimenCollection(updatedSpecimenCollection); } /** * This method updates the Specimen instance by setting all the consenttierstatus to withdraw. * @param specimen Instance of Specimen to be updated. * @param consentWithdrawalOption Action to be performed on the withdrawn specimen. * @param consentTierID Identifier of ConsentTier to be withdrawn. * @param dao DAO instance. Used for inserting disposal event. * @param sessionDataBean SessionDataBean instance. Used for inserting disposal event. * @throws DAOException */ public static void updateSpecimenStatus(Specimen specimen, String consentWithdrawalOption, long consentTierID, DAO dao, SessionDataBean sessionDataBean) throws DAOException { Collection consentTierStatusCollection = specimen.getConsentTierStatusCollection(); Collection updatedSpecimenStatusCollection = new HashSet(); Iterator specimenStatusItr = consentTierStatusCollection.iterator() ; while(specimenStatusItr.hasNext() ) { ConsentTierStatus consentTierstatus = (ConsentTierStatus)specimenStatusItr.next() ; if(consentTierstatus.getConsentTier().getId().longValue() == consentTierID) { if(consentWithdrawalOption != null) { consentTierstatus.setStatus(Constants.WITHDRAWN ); withdrawResponse(specimen, consentWithdrawalOption, dao, sessionDataBean); } } updatedSpecimenStatusCollection.add(consentTierstatus ); } specimen.setConsentTierStatusCollection( updatedSpecimenStatusCollection); updateChildSpecimens(specimen, consentWithdrawalOption, consentTierID, dao, sessionDataBean); } /* * This method performs an action on specimen based on user response. */ private static void withdrawResponse(Specimen specimen, String consentWithdrawalOption, DAO dao, SessionDataBean sessionDataBean) { if(consentWithdrawalOption.equalsIgnoreCase(Constants.WITHDRAW_RESPONSE_DISCARD)) { addDisposalEvent(specimen, dao, sessionDataBean); } else if(consentWithdrawalOption.equalsIgnoreCase(Constants.WITHDRAW_RESPONSE_RETURN)) { addReturnEvent(specimen, dao, sessionDataBean); } //only if consentWithdrawalOption is not reset or noaction. if(!consentWithdrawalOption.equalsIgnoreCase(Constants.WITHDRAW_RESPONSE_RESET) && !consentWithdrawalOption.equalsIgnoreCase(Constants.WITHDRAW_RESPONSE_NOACTION) ) { specimen.setActivityStatus(Constants.ACTIVITY_STATUS_DISABLED); specimen.setAvailable(new Boolean(false) ); if(specimen.getSpecimenPosition() != null && specimen.getSpecimenPosition().getStorageContainer() !=null) // locations cleared { Map containerMap = null; try { containerMap = StorageContainerUtil.getContainerMapFromCache(); } catch (Exception e) { e.printStackTrace(); } StorageContainerUtil.insertSinglePositionInContainerMap(specimen.getSpecimenPosition().getStorageContainer(),containerMap,specimen.getSpecimenPosition().getPositionDimensionOne().intValue(), specimen.getSpecimenPosition().getPositionDimensionTwo().intValue() ); } specimen.setSpecimenPosition(null); // specimen.setPositionDimensionOne(null); // specimen.setPositionDimensionTwo(null); // specimen.setStorageContainer(null); specimen.setAvailableQuantity(null); specimen.setInitialQuantity(null); } } private static void addReturnEvent(Specimen specimen, DAO dao, SessionDataBean sessionDataBean) { try { Collection eventCollection = specimen.getSpecimenEventCollection(); if(!isEventAdded(eventCollection, "ReturnEventParameters")) { ReturnEventParameters returnEvent = new ReturnEventParameters(); returnEvent.setSpecimen(specimen ); dao.insert(returnEvent,sessionDataBean,true,true) ; eventCollection.add(returnEvent); specimen.setSpecimenEventCollection(eventCollection); } } catch(Exception excp) { excp.printStackTrace(); } } /* * This method adds a disposal event to the specimen. */ private static void addDisposalEvent(Specimen specimen, DAO dao, SessionDataBean sessionDataBean) { try { Collection eventCollection = specimen.getSpecimenEventCollection(); if(!isEventAdded(eventCollection, "DisposalEventParameters")) { new NewSpecimenBizLogic().disposeSpecimen(sessionDataBean, specimen, dao); } } catch(Exception excp) { excp.printStackTrace(); } } private static void updateChildSpecimens(Specimen specimen, String consentWithdrawalOption, long consentTierID, DAO dao, SessionDataBean sessionDataBean) throws DAOException { Long specimenId = (Long)specimen.getId(); Collection childSpecimens = (Collection)dao.retrieveAttribute(Specimen.class.getName(),specimenId,"elements(childrenSpecimen)"); //Collection childSpecimens = specimen.getChildrenSpecimen(); if(childSpecimens!=null) { Iterator childItr = childSpecimens.iterator(); while(childItr.hasNext() ) { Specimen childSpecimen = (Specimen)childItr.next(); consentWithdrawForchildSpecimens(childSpecimen , dao, sessionDataBean, consentWithdrawalOption, consentTierID); } } } private static void consentWithdrawForchildSpecimens(Specimen specimen, DAO dao, SessionDataBean sessionDataBean, String consentWithdrawalOption, long consentTierID) throws DAOException { if(specimen!=null) { updateSpecimenStatus(specimen, consentWithdrawalOption, consentTierID, dao, sessionDataBean); Collection childSpecimens = specimen.getChildrenSpecimen(); Iterator itr = childSpecimens.iterator(); while(itr.hasNext() ) { Specimen childSpecimen = (Specimen)itr.next(); consentWithdrawForchildSpecimens(childSpecimen, dao, sessionDataBean, consentWithdrawalOption, consentTierID); } } } /** * This method is used to copy the consents from parent specimen to the child specimen. * * @param specimen Instance of specimen. It is the child specimen to which the consents will be set. * @param parentSpecimen Instance of specimen. It is the parent specimen from which the consents will be copied. * @throws DAOException */ public static void setConsentsFromParent(Specimen specimen, Specimen parentSpecimen, DAO dao) throws DAOException { Collection consentTierStatusCollection = new HashSet(); Collection parentStatusCollection = (Collection)dao.retrieveAttribute(Specimen.class.getName(), parentSpecimen.getId(),"elements(consentTierStatusCollection)"); Iterator parentStatusCollectionIterator = parentStatusCollection.iterator(); while(parentStatusCollectionIterator.hasNext() ) { ConsentTierStatus cts = (ConsentTierStatus)parentStatusCollectionIterator.next(); ConsentTierStatus newCts = new ConsentTierStatus(); newCts.setStatus(cts.getStatus()); newCts.setConsentTier(cts.getConsentTier()); consentTierStatusCollection.add(newCts); } specimen.setConsentTierStatusCollection( consentTierStatusCollection); } /* * This method checks if the given event is already added to the specimen. */ private static boolean isEventAdded(Collection eventCollection, String eventType) { boolean result = false; Iterator eventCollectionIterator = eventCollection.iterator(); while(eventCollectionIterator.hasNext() ) { Object event = eventCollectionIterator.next(); if(event.getClass().getSimpleName().equals(eventType)) { result= true; break; } } return result; } /** * This method updates the specimens status for the given SCG. * @param specimenCollectionGroup * @param oldSpecimenCollectionGroup * @param dao * @param sessionDataBean * @throws DAOException */ public static void updateSpecimenStatusInSCG(SpecimenCollectionGroup specimenCollectionGroup,SpecimenCollectionGroup oldSpecimenCollectionGroup, DAO dao) throws DAOException { Collection newConsentTierStatusCollection = specimenCollectionGroup.getConsentTierStatusCollection(); Collection oldConsentTierStatusCollection = oldSpecimenCollectionGroup.getConsentTierStatusCollection(); Iterator itr = newConsentTierStatusCollection.iterator() ; while(itr.hasNext() ) { ConsentTierStatus consentTierStatus = (ConsentTierStatus)itr.next(); String statusValue = consentTierStatus.getStatus(); long consentTierID = consentTierStatus.getConsentTier().getId().longValue(); updateSCGSpecimenCollection(specimenCollectionGroup, oldSpecimenCollectionGroup, consentTierID, statusValue, newConsentTierStatusCollection, oldConsentTierStatusCollection,dao); } } /* * This method updates the specimen consent status. */ private static void updateSCGSpecimenCollection(SpecimenCollectionGroup specimenCollectionGroup, SpecimenCollectionGroup oldSpecimenCollectionGroup, long consentTierID, String statusValue, Collection newSCGConsentCollection, Collection oldSCGConsentCollection,DAO dao) throws DAOException { Collection specimenCollection = (Collection)dao.retrieveAttribute(SpecimenCollectionGroup.class.getName(), specimenCollectionGroup.getId(),"elements(specimenCollection)"); //oldSpecimenCollectionGroup.getSpecimenCollection(); Collection updatedSpecimenCollection = new HashSet(); String applyChangesTo = specimenCollectionGroup.getApplyChangesTo(); Iterator specimenItr = specimenCollection.iterator() ; while(specimenItr.hasNext() ) { Specimen specimen = (Specimen)specimenItr.next(); updateSpecimenConsentStatus(specimen, applyChangesTo, consentTierID, statusValue, newSCGConsentCollection, oldSCGConsentCollection, dao ); updatedSpecimenCollection.add(specimen ); } specimenCollectionGroup.setSpecimenCollection(updatedSpecimenCollection ); } public static void updateSpecimenConsentStatus(Specimen specimen, String applyChangesTo, long consentTierID, String statusValue, Collection newConsentCollection, Collection oldConsentCollection,DAO dao) throws DAOException { if(applyChangesTo.equalsIgnoreCase(Constants.APPLY_ALL)) updateSpecimenConsentStatus(specimen, consentTierID, statusValue, applyChangesTo, dao); else if(applyChangesTo.equalsIgnoreCase(Constants.APPLY)) { //To pass both collections checkConflictingConsents(newConsentCollection, oldConsentCollection, specimen, dao); } } /** * This method updates the Specimen instance by setting all the consenttierstatus to withdraw. * @param specimen Instance of Specimen to be updated. * @param consentWithdrawalOption Action to be performed on the withdrawn specimen. * @param consentTierID Identifier of ConsentTier to be withdrawn. * @throws DAOException */ private static void updateSpecimenConsentStatus(Specimen specimen, long consentTierID, String statusValue, String applyChangesTo, DAO dao) throws DAOException { Collection consentTierStatusCollection = specimen.getConsentTierStatusCollection(); Collection updatedSpecimenStatusCollection = new HashSet(); Iterator specimenStatusItr = consentTierStatusCollection.iterator() ; while(specimenStatusItr.hasNext() ) { ConsentTierStatus consentTierstatus = (ConsentTierStatus)specimenStatusItr.next() ; if(consentTierstatus.getConsentTier().getId().longValue() == consentTierID) { consentTierstatus.setStatus(statusValue); } updatedSpecimenStatusCollection.add(consentTierstatus); } specimen.setConsentTierStatusCollection(updatedSpecimenStatusCollection); //to update child specimens Collection childSpecimens = specimen.getChildrenSpecimen(); Iterator childItr = childSpecimens.iterator(); while(childItr.hasNext() ) { Specimen childSpecimen = (Specimen)childItr.next(); consentStatusUpdateForchildSpecimens(childSpecimen , consentTierID, statusValue ,applyChangesTo, dao); } } private static void consentStatusUpdateForchildSpecimens(Specimen specimen, long consentTierID, String statusValue, String applyChangesTo, DAO dao) throws DAOException { if(specimen!=null) { updateSpecimenConsentStatus(specimen, consentTierID, statusValue, applyChangesTo, dao); Collection childSpecimens = specimen.getChildrenSpecimen(); Iterator itr = childSpecimens.iterator(); while(itr.hasNext() ) { Specimen childSpecimen = (Specimen)itr.next(); consentStatusUpdateForchildSpecimens(childSpecimen, consentTierID, statusValue, applyChangesTo, dao); } } } /* * This method verifies the consents of SCG and specimen for any conflicts. */ private static void checkConflictingConsents(Collection newConsentCollection, Collection oldConsentCollection, Specimen specimen, DAO dao ) throws DAOException { /* if oldSCG.c1 == S.c1 then update specimen with new SCG.c1 * OR * if oldS.c1 == cS.c1 then update child specimen with new S.c1 */ Iterator oldConsentItr = oldConsentCollection.iterator(); while(oldConsentItr.hasNext() ) { ConsentTierStatus oldConsentStatus = (ConsentTierStatus)oldConsentItr.next() ; Collection specimenConsentStatusCollection = specimen.getConsentTierStatusCollection(); Iterator specimenConsentStatusItr = specimenConsentStatusCollection.iterator() ; Collection updatedSpecimenConsentStatusCollection = new HashSet(); while(specimenConsentStatusItr.hasNext() ) { ConsentTierStatus specimenConsentStatus = (ConsentTierStatus)specimenConsentStatusItr.next() ; if(oldConsentStatus.getConsentTier().getId().longValue() == specimenConsentStatus.getConsentTier().getId().longValue() ) { if(oldConsentStatus.getStatus().equals(specimenConsentStatus.getStatus())) { Iterator newConsentItr = newConsentCollection.iterator(); while(newConsentItr.hasNext() ) { ConsentTierStatus newConsentStatus = (ConsentTierStatus)newConsentItr.next() ; if(newConsentStatus.getConsentTier().getId().longValue() == specimenConsentStatus.getConsentTier().getId().longValue() ) { specimenConsentStatus.setStatus(newConsentStatus.getStatus()); } } } } updatedSpecimenConsentStatusCollection.add(specimenConsentStatus); } specimen.setConsentTierStatusCollection(updatedSpecimenConsentStatusCollection); } //to update child specimens Collection childSpecimens = specimen.getChildrenSpecimen(); Iterator childItr = childSpecimens.iterator(); while(childItr.hasNext() ) { Specimen childSpecimen = (Specimen)childItr.next(); consentStatusUpdateForchildSpecimens(childSpecimen , newConsentCollection, oldConsentCollection, dao); } } private static void consentStatusUpdateForchildSpecimens(Specimen specimen, Collection newConsentCollection, Collection oldConsentCollection, DAO dao) throws DAOException { if(specimen!=null) { checkConflictingConsents(newConsentCollection, oldConsentCollection, specimen, dao); Collection childSpecimens = specimen.getChildrenSpecimen(); Iterator itr = childSpecimens.iterator(); while(itr.hasNext() ) { Specimen childSpecimen = (Specimen)itr.next(); consentStatusUpdateForchildSpecimens(childSpecimen, newConsentCollection, oldConsentCollection, dao); } } } /** * This function is used for retriving Specimen collection group from Collection protocol registration Object * @param specimenObj * @param finalDataList * @throws DAOException */ public static void getSpecimenDetails(CollectionProtocolRegistration collectionProtocolRegistration, List finalDataList) throws DAOException { IBizLogic bizLogic = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC); Collection specimencollectionGroup = (Collection)bizLogic.retrieveAttribute(CollectionProtocolRegistration.class.getName(),collectionProtocolRegistration.getId(), "elements(specimenCollectionGroupCollection)"); //Collection specimencollectionGroup = collectionProtocolRegistration.getSpecimenCollectionGroupCollection(); Iterator specimenCollGroupIterator = specimencollectionGroup.iterator(); while(specimenCollGroupIterator.hasNext()) { SpecimenCollectionGroup specimenCollectionGroupObj =(SpecimenCollectionGroup)specimenCollGroupIterator.next(); getDetailsOfSpecimen(specimenCollectionGroupObj, finalDataList); } } /** * This function is used for retriving specimen and sub specimen's attributes. * @param specimenObj * @param finalDataList * @throws DAOException */ private static void getDetailsOfSpecimen(SpecimenCollectionGroup specimenCollGroupObj, List finalDataList) throws DAOException { // lazy Resolved specimenCollGroupObj.getSpecimenCollection(); IBizLogic bizLogic = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC); Collection specimenCollection = (Collection)bizLogic.retrieveAttribute(SpecimenCollectionGroup.class.getName(), specimenCollGroupObj.getId(), "elements(specimenCollection)"); Iterator specimenIterator = specimenCollection.iterator(); while(specimenIterator.hasNext()) { Specimen specimenObj =(Specimen)specimenIterator.next(); List specimenDetailList=new ArrayList(); if(specimenObj.getActivityStatus().equals(Constants.ACTIVITY_STATUS_ACTIVE)) { specimenDetailList.add(specimenObj.getLabel()); specimenDetailList.add(specimenObj.getType()); if(specimenObj.getSpecimenPosition()==null) { specimenDetailList.add(Constants.VIRTUALLY_LOCATED); } else { SpecimenPosition position= (SpecimenPosition)bizLogic.retrieveAttribute(Specimen.class.getName(), specimenObj.getId(),"specimenPosition"); String storageLocation=position.getStorageContainer().getName()+": X-Axis-"+position.getPositionDimensionOne()+", Y-Axis-"+position.getPositionDimensionTwo(); specimenDetailList.add(storageLocation); } specimenDetailList.add(specimenObj.getClassName()); finalDataList.add(specimenDetailList); } } } /** * Adding name,value pair in NameValueBean for Witness Name * @param collProtId Get Witness List for this ID * @return consentWitnessList */ public static List witnessNameList(String collProtId) throws DAOException { IBizLogic bizLogic = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC); String colName = Constants.ID; List collProtList = bizLogic.retrieve(CollectionProtocol.class.getName(), colName, collProtId); CollectionProtocol collectionProtocol = (CollectionProtocol)collProtList.get(0); //Setting the consent witness String witnessFullName=""; List consentWitnessList = new ArrayList(); consentWitnessList.add(new NameValueBean(Constants.SELECT_OPTION,"-1")); Collection userCollection = null; if(collectionProtocol.getId()!= null) { userCollection = (Collection)bizLogic.retrieveAttribute(CollectionProtocol.class.getName(),collectionProtocol.getId(), "elements(coordinatorCollection)"); } Iterator iter = userCollection.iterator(); while(iter.hasNext()) { User user = (User)iter.next(); witnessFullName = user.getLastName()+", "+user.getFirstName(); consentWitnessList.add(new NameValueBean(witnessFullName,user.getId())); } //Setting the PI User principalInvestigator = (User)bizLogic.retrieveAttribute(CollectionProtocol.class.getName(),collectionProtocol.getId(), "principalInvestigator"); String piFullName=principalInvestigator.getLastName()+", "+principalInvestigator.getFirstName(); consentWitnessList.add(new NameValueBean(piFullName,principalInvestigator.getId())); return consentWitnessList; } /** * This function adds the columns to the List * @return columnList */ public static List<String> columnNames() { List<String> columnList = new ArrayList<String>(); columnList.add(Constants.LABLE); columnList.add(Constants.TYPE); columnList.add(Constants.STORAGE_CONTAINER_LOCATION); columnList.add(Constants.CLASS_NAME); return columnList; } /** * Adding name,value pair in NameValueBean for Witness Name * @param collProtId Get Witness List for this ID * @return consentWitnessList */ public static Collection getConsentList(String collectionProtocolID) throws DAOException { CollectionProtocolBizLogic collectionProtocolBizLogic = (CollectionProtocolBizLogic)BizLogicFactory.getInstance().getBizLogic(Constants.COLLECTION_PROTOCOL_FORM_ID); List collProtList = collectionProtocolBizLogic.retrieve(CollectionProtocol.class.getName(), Constants.ID, collectionProtocolID); CollectionProtocol collectionProtocol = (CollectionProtocol)collProtList.get(0); Collection consentTierCollection = (Collection)collectionProtocolBizLogic.retrieveAttribute(CollectionProtocol.class.getName(), collectionProtocol.getId(), "elements(consentTierCollection)"); return consentTierCollection; } /** * For ConsentTracking Preparing consentResponseForScgValues for populating Dynamic contents on the UI * @param partiResponseCollection This Containes the collection of ConsentTier Response at CPR level * @param statusResponseCollection This Containes the collection of ConsentTier Response at Specimen level * @return tempMap */ public static Map prepareSCGResponseMap(Collection statusResponseCollection, Collection partiResponseCollection,String statusResponse, String statusResponseId) { Map tempMap = new HashMap(); Long consentTierID; Long consentID; if(partiResponseCollection!=null ||statusResponseCollection!=null) { int i = 0; Iterator statusResponsIter = statusResponseCollection.iterator(); while(statusResponsIter.hasNext()) { ConsentTierStatus consentTierstatus=(ConsentTierStatus)statusResponsIter.next(); consentTierID=consentTierstatus.getConsentTier().getId(); Iterator participantResponseIter = partiResponseCollection.iterator(); while(participantResponseIter.hasNext()) { ConsentTierResponse consentTierResponse=(ConsentTierResponse)participantResponseIter.next(); consentID=consentTierResponse.getConsentTier().getId(); if(consentTierID.longValue()==consentID.longValue()) { ConsentTier consent = consentTierResponse.getConsentTier(); String idKey="ConsentBean:"+i+"_consentTierID"; String statementKey="ConsentBean:"+i+"_statement"; String participantResponsekey = "ConsentBean:"+i+"_participantResponse"; String participantResponceIdKey="ConsentBean:"+i+"_participantResponseID"; String statusResponsekey = "ConsentBean:"+i+statusResponse; String statusResponseIDkey ="ConsentBean:"+i+statusResponseId; tempMap.put(idKey, consent.getId()); tempMap.put(statementKey,consent.getStatement()); tempMap.put(participantResponsekey, consentTierResponse.getResponse()); tempMap.put(participantResponceIdKey, consentTierResponse.getId()); tempMap.put(statusResponsekey, consentTierstatus.getStatus()); tempMap.put(statusResponseIDkey, consentTierstatus.getId()); i++; break; } } } return tempMap; } else { return null; } } /** * @param consentTierResponseCollection * @param iter */ public static void createConsentResponseColl(Collection consentTierResponseCollection, Iterator iter) { while(iter.hasNext()) { ConsentBean consentBean = (ConsentBean)iter.next(); ConsentTierResponse consentTierResponse = new ConsentTierResponse(); //Setting response consentTierResponse.setResponse(consentBean.getParticipantResponse()); if(consentBean.getParticipantResponseID()!=null&&consentBean.getParticipantResponseID().trim().length()>0) { consentTierResponse.setId(Long.parseLong(consentBean.getParticipantResponseID())); } //Setting consent tier ConsentTier consentTier = new ConsentTier(); consentTier.setId(Long.parseLong(consentBean.getConsentTierID())); consentTier.setStatement(consentBean.getStatement()); consentTierResponse.setConsentTier(consentTier); consentTierResponseCollection.add(consentTierResponse); } } }
/** * created at Jan 3, 2002 * @author Jeka */ package com.intellij.compiler.impl; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompilerBundle; import com.intellij.openapi.module.Module; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.java.LanguageLevel; import com.intellij.util.ThrowableRunnable; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.FileFilter; import java.util.*; public class CompilerUtil { public static String quotePath(String path) { if(path != null && path.indexOf(' ') != -1) { path = path.replaceAll("\\\\", "\\\\\\\\"); path = '"' + path + '"'; } return path; } public static void collectFiles(Collection<File> container, File rootDir, FileFilter fileFilter) { final File[] files = rootDir.listFiles(fileFilter); if (files == null) { return; } for (File file : files) { if (file.isDirectory()) { collectFiles(container, file, fileFilter); } else { container.add(file); } } } public static Map<Module, List<VirtualFile>> buildModuleToFilesMap(CompileContext context, VirtualFile[] files) { return buildModuleToFilesMap(context, Arrays.asList(files)); } public static Map<Module, List<VirtualFile>> buildModuleToFilesMap(final CompileContext context, final List<VirtualFile> files) { //assertion: all files are different final Map<Module, List<VirtualFile>> map = new THashMap<Module, List<VirtualFile>>(); ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { for (VirtualFile file : files) { final Module module = context.getModuleByFile(file); if (module == null) { continue; // looks like file invalidated } List<VirtualFile> moduleFiles = map.get(module); if (moduleFiles == null) { moduleFiles = new ArrayList<VirtualFile>(); map.put(module, moduleFiles); } moduleFiles.add(file); } } }); return map; } /** * must not be called inside ReadAction * @param files */ public static void refreshIOFiles(@NotNull final Collection<File> files) { for (File file1 : files) { final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file1); if (file != null) { file.refresh(false, false); } } } public static void refreshIOFilesInterruptibly(@NotNull CompileContext context, @NotNull Collection<File> files, @Nullable String title) { List<VirtualFile> virtualFiles = new ArrayList<VirtualFile>(files.size()); for (File file : files) { context.getProgressIndicator().checkCanceled(); VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); if (virtualFile == null) continue; virtualFiles.add(virtualFile); } refreshFilesInterruptibly(context, virtualFiles, title); } public static void refreshFilesInterruptibly(@NotNull final CompileContext context, @NotNull final Collection<VirtualFile> files, @Nullable String title) { ThrowableRunnable<RuntimeException> runnable = new ThrowableRunnable<RuntimeException>() { public void run() { int i =0; for (VirtualFile file : files) { context.getProgressIndicator().checkCanceled(); if (files.size() > 100) { context.getProgressIndicator().setFraction(++i * 1.0 / files.size()); context.getProgressIndicator().setText2(file.getPath()); } file.refresh(false, true); } } }; if (files.size() > 100) { CompileDriver.runInContext(context, title, runnable); } else { runnable.run(); } //LocalFileSystem.getInstance().refreshFiles(files); //if (true) return; //ThrowableRunnable<RuntimeException> runnable = new ThrowableRunnable<RuntimeException>() { // public void run() throws RuntimeException { // boolean async = !ApplicationManager.getApplication().isDispatchThread(); // final CountDownLatch latch = new CountDownLatch(files.size()); // final int[] i = {0}; // for (final VirtualFile virtualFile : files) { // context.getProgressIndicator().checkCanceled(); // virtualFile.refresh(async, true, new Runnable() { // public void run() { // latch.countDown(); // context.getProgressIndicator().setFraction(++i[0] * 1.0 / files.size()); // context.getProgressIndicator().setText2(virtualFile.getPath()); // try { // while (true) { // latch.await(100, TimeUnit.MILLISECONDS); // if (latch.getCount() == 0) break; // context.getProgressIndicator().checkCanceled(); // catch (InterruptedException ignored) { } public static void refreshIODirectories(@NotNull final Collection<File> files) { for (File file1 : files) { final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file1); if (file != null) { file.refresh(false, true); } } } public static void refreshIOFile(final File file) { final VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); if (vFile != null) { vFile.refresh(false, false); } } public static void addLocaleOptions(final List<String> commandLine, final boolean launcherUsed) { // need to specify default encoding so that javac outputs messages in 'correct' language //noinspection HardCodedStringLiteral commandLine.add((launcherUsed? "-J" : "") + "-D" + CharsetToolkit.FILE_ENCODING_PROPERTY + "=" + CharsetToolkit.getDefaultSystemCharset().name()); // javac's VM should use the same default locale that IDEA uses in order for javac to print messages in 'correct' language //noinspection HardCodedStringLiteral final String lang = System.getProperty("user.language"); if (lang != null) { //noinspection HardCodedStringLiteral commandLine.add((launcherUsed? "-J" : "") + "-Duser.language=" + lang); } //noinspection HardCodedStringLiteral final String country = System.getProperty("user.country"); if (country != null) { //noinspection HardCodedStringLiteral commandLine.add((launcherUsed? "-J" : "") + "-Duser.country=" + country); } //noinspection HardCodedStringLiteral final String region = System.getProperty("user.region"); if (region != null) { //noinspection HardCodedStringLiteral commandLine.add((launcherUsed? "-J" : "") + "-Duser.region=" + region); } } public static void addSourceCommandLineSwitch(final Sdk jdk, LanguageLevel chunkLanguageLevel, @NonNls final List<String> commandLine) { final String versionString = jdk.getVersionString(); if (versionString == null || "".equals(versionString)) { throw new IllegalArgumentException(CompilerBundle.message("javac.error.unknown.jdk.version", jdk.getName())); } final LanguageLevel applicableLanguageLevel = getApplicableLanguageLevel(versionString, chunkLanguageLevel); if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_6)) { commandLine.add("-source"); commandLine.add("1.6"); } else if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_5)) { commandLine.add("-source"); commandLine.add("1.5"); } else if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_4)) { commandLine.add("-source"); commandLine.add("1.4"); } else if (applicableLanguageLevel.equals(LanguageLevel.JDK_1_3)) { if (!(isOfVersion(versionString, "1.3") || isOfVersion(versionString, "1.2") || isOfVersion(versionString, "1.1"))) { //noinspection HardCodedStringLiteral commandLine.add("-source"); commandLine.add("1.3"); } } } @NotNull public static LanguageLevel getApplicableLanguageLevel(String versionString, @NotNull LanguageLevel languageLevel) { final boolean is5OrNewer = isOfVersion(versionString, "1.5") || isOfVersion(versionString, "5.0") || isOfVersion(versionString, "1.6.") || isOfVersion(versionString, "1.7."); if (LanguageLevel.JDK_1_5.equals(languageLevel) && !is5OrNewer) { languageLevel = LanguageLevel.JDK_1_4; } if (LanguageLevel.JDK_1_4.equals(languageLevel) && !isOfVersion(versionString, "1.4") && !is5OrNewer) { languageLevel = LanguageLevel.JDK_1_3; } return languageLevel; } public static boolean isOfVersion(String versionString, String checkedVersion) { return versionString.contains(checkedVersion); } }
package edu.wustl.query.actionForm; import java.util.LinkedList; import java.util.List; import edu.wustl.common.actionForm.AbstractActionForm; import edu.wustl.common.domain.AbstractDomainObject; import edu.wustl.common.querysuite.queryobject.IAbstractQuery; import edu.wustl.common.querysuite.queryobject.IOperation; import edu.wustl.common.querysuite.queryobject.impl.AbstractQuery; import edu.wustl.common.querysuite.queryobject.impl.CompositeQuery; import edu.wustl.common.querysuite.queryobject.impl.Intersection; import edu.wustl.common.querysuite.queryobject.impl.Minus; import edu.wustl.common.querysuite.queryobject.impl.ParameterizedQuery; import edu.wustl.common.querysuite.queryobject.impl.Union; import edu.wustl.common.util.Utility; import edu.wustl.query.domain.Workflow; import edu.wustl.query.domain.WorkflowItem; import edu.wustl.query.util.global.CompositeQueryOperations; import edu.wustl.query.util.global.Constants; /** * @author chitra_garg * */ /** * @author chitra_garg * */ public class WorkflowForm extends AbstractActionForm { /** * @return that get count or composite query */ public String[] getQueryTypeControl() { return queryTypeControl; } /** * @param queryTypeControl=array containing get count or composite query */ public void setQueryTypeControl(String[] queryTypeControl) { this.queryTypeControl = queryTypeControl; } /** * @return operands array . Each element of array is underscore separated operands * corresponding to each row of table displayed in UI */ public String[] getOperands() { return operands; } /** * @param operands=array of operand's id separated by underscore values */ public void setOperands(String[] operands) { this.operands = operands; } /** * @return operators array . Each element of array is underscore separated operators * corresponding to each row of table displayed in UI */ public String[] getOperators() { return operators; } /** * @param operators= array of operators's id separated by underscore values */ public void setOperators(String[] operators) { this.operators = operators; } /** * @return the displayQueryTitle array . Each element of array is underscore separated displayQueryTitle * corresponding to each row of table displayed in UI */ public String[] getDisplayQueryTitle() { return displayQueryTitle; } /** * @param displayQueryTitle title corresponding * to each row of table displayed in UI */ public void setDisplayQueryTitle(String[] displayQueryTitle) { this.displayQueryTitle = displayQueryTitle; } /** * @return queryTypeControl=array containing get count or composite query */ public String[] getDisplayQueryType() { return displayQueryType; } /** * @param displayQueryType=array of query type * each row of the array corresponds to one row in work flow UI */ public void setDisplayQueryType(String[] displayQueryType) { this.displayQueryType = displayQueryType; } /** * Default serialVersionUID */ private static final long serialVersionUID = 1L; /** * Query ID array corresponding * to each row in UI */ protected String[] queryId; /** *queryTitle of queries array * selected from the work flow pop up */ protected String[] queryTitle; /** *Composite Query or * parameterized Query of query for each row in UI */ protected String[] queryType; /** * check box controls from UI */ protected boolean[] chkbox; /** * Name of the workFlow */ private String name; /** * @return Query Id array */ public String[] getQueryId() { return queryId; } /** * @param queryId=set the value of Query ID * array corresponding to each row in UI */ public void setQueryId(String[] queryId) { this.queryId = queryId; } /** * @return queryTitle of queries array * selected from the work flow pop up */ public String[] getQueryTitle() { return queryTitle; } /** * @param queryTitle */ public void setQueryTitle(String[] queryTitle) { this.queryTitle = queryTitle; } /** * @return queryType of queries array * selected from the work flow pop up */ public String[] getQueryType() { return queryType; } /** * @param queryType=composite Query or * parameterized Query of query for each row in UI */ public void setQueryType(String[] queryType) { this.queryType = queryType; } /** * @return hidden control that contains the * value of Query title */ public String[] getQueryTitleControl() { return queryTitleControl; } /** * @param queryTitleControl hidden control that contains the * value of Query title * This function sets the value of this hidden control */ public void setQueryTitleControl(String[] queryTitleControl) { this.queryTitleControl = queryTitleControl; } /** * @return QueryIdControlarray */ public String[] getQueryIdControl() { return queryIdControl; } /** * @param queryIdControl hidden field in UI * for the Query id */ public void setQueryIdControl(String[] queryIdControl) { this.queryIdControl = queryIdControl; } /** * @return operands array.underscore separated for each row of table */ public String[] getSelectedqueryId() { return selectedqueryId; } /** * @param operands array.underscore separated for each row of table */ public void setSelectedqueryId(String[] selectedqueryId) { this.selectedqueryId = selectedqueryId; } /** * @return number of check boxes created */ public boolean[] getChkbox() { return chkbox; } /** * @param chkbox=check box controls from UI */ public void setChkbox(boolean[] chkbox) { this.chkbox = chkbox; } /** * hidden control in UI that contains the * value of Query title */ protected String[] queryTitleControl; /** *hidden field in UI * for the Query id */ protected String[] queryIdControl; /** * array containing get count or composite query */ protected String[] queryTypeControl; protected String[] identifier; /** * array containing operand's ids */ protected String[] operands; /** * array containing operators */ protected String[] operators; protected String[] displayQueryTitle; protected String[] displayQueryType; protected String[] selectedqueryId; /** * Method to get name of the workflow * @return name of type String */ public String getName() { return this.name; } /** * Method to set name of the workflow * @param name of type String */ public void setName(String name) { this.name = name; } /** * Method to get form id * @return name of type String */ @Override public int getFormId() { return Constants.WORKFLOW_FORM_ID; } /** * Contains the query execution ID */ int[] queryExecId; /** * @return query Execution id */ public int[] getQueryExecId() { return queryExecId; } /** * @param queryExecId=query Execution Id */ public void setQueryExecId(int[] queryExecId) { this.queryExecId = queryExecId; } /* (non-Javadoc) * @see edu.wustl.common.actionForm.AbstractActionForm#reset() * reset method to set default values */ @Override protected void reset() { } /** * for queryIds */ String[] queryIdForRow; public String[] getQueryIdForRow() { return queryIdForRow; } public void setQueryIdForRow(String[] queryIdForRow) { this.queryIdForRow = queryIdForRow; } /** * for postfix expression */ String[] expression; /** * @return postfix expression */ public String[] getExpression() { return expression; } /** * @param expression post-fix expression */ public void setExpression(String[] expression) { this.expression = expression; } /** * for post-fix expression */ String[] queryIdList; /** * @return queryIdList for post fix expression */ public String[] getQueryIdList() { return queryIdList; } /** * @param queryIdList =queryIdList for post fix expression */ public void setQueryIdList(String[] queryIdList) { this.queryIdList = queryIdList; } /** * @param domain object from which form object will generate * Method to populate formBean from domain object */ public void setAllValues(AbstractDomainObject abstractDomain) { Workflow workflow = (Workflow) abstractDomain; LinkedList<String> opretionList = new LinkedList<String>(); LinkedList<String> operandList = new LinkedList<String>(); this.id = workflow.getId(); this.name = Utility.toString(workflow.getName()); List<WorkflowItem> workflowItemList = workflow.getWorkflowItemList(); // display title int size= workflowItemList.size(); String[] displayQueryTitle = new String[size]; String[] displayQueryType = new String[size]; String[] identifier = new String[workflowItemList.size()]; String[] queryName=new String[workflowItemList.size()]; String[] expression=new String[workflowItemList.size()]; for (int i = 0; i < workflowItemList.size(); i++) { WorkflowItem workflowItem = workflowItemList.get(i); //to initalize identifier array //this.identifier[i]=workflowItem.getQuery().getId(); LinkedList<String> operatorsList = new LinkedList<String>(); LinkedList<Long> operandsList = new LinkedList<Long>(); IAbstractQuery abstractQuery = workflowItem.getQuery(); identifier[i]=String.valueOf(abstractQuery.getId()); generateOperatorAndOperandList(operatorsList, operandsList, abstractQuery); expression[i]=generatePostfixExpression(workflowItem,operatorsList,operandsList,abstractQuery); setoperandList(operandList, operandsList); setOperatorList(opretionList, operatorsList); displayQueryTitle[i]=genetrateDisplayQueryTitle(workflowItem); displayQueryType[i]=((AbstractQuery)abstractQuery).getType(); } String[] operands = new String[operandList.size()];//oprands array String[] operators = new String[opretionList.size()];//operator array //initialize operator and operand array opretionList.toArray(operators); operandList.toArray(operands); // starts selectedqueryId same as operandsArray String[] selectedqueryId = operands; this.selectedqueryId = selectedqueryId; this.displayQueryType=displayQueryType; this.displayQueryTitle = displayQueryTitle; //this.queryTypeControl=queryTypeControl; System.out.println(""); this.operands = operands; this.operators = operators; boolean[] chkbox = new boolean[workflowItemList.size()]; this.chkbox = chkbox; this.identifier=identifier; this.expression=expression; this.queryIdForRow=identifier; } private String generatePostfixExpression(WorkflowItem workflowItem, LinkedList<String> operatorsList, LinkedList<Long> operandsList, IAbstractQuery abstractQuery) { String exp=""; for(int i=0;i<operandsList.size();i++) { exp=exp+operandsList.get(i)+"_"; } //exp=exp+operandsList.get(operandsList.size()); for(int i=0;i<operatorsList.size();i++) { if(!operatorsList.get(i).equals("None")) { String shortOperator=null; if(operatorsList.get(i).equals("Union")) { shortOperator="+"; } if(operatorsList.get(i).equals("Intersection")) { shortOperator="*"; } if(operatorsList.get(i).equals("Minus")) { shortOperator="-"; } exp=exp+shortOperator+"_"; } } exp=exp.substring(0, exp.lastIndexOf('_')); return exp; } /** * @param workflowItem * @return query title */ private String genetrateDisplayQueryTitle(WorkflowItem workflowItem) { // if(workflowItem.getQuery() instanceof CompositeQuery) // String queryConst = "[ Query"; // String queryTitle = ""; // queryTitle = queryTitle + queryConst + " : " + ((ParameterizedQuery)(((CompositeQuery)workflowItem.getQuery()).getOperation().getOperandOne())).getName()+ " ]" // + " "+setOperationForCompositeQuery(((CompositeQuery)workflowItem.getQuery()).getOperation())+" "; // return queryTitle + queryConst + " : " + ((ParameterizedQuery)(((CompositeQuery)workflowItem.getQuery()).getOperation().getOperandTwo())).getName() + " ]"; // else if(workflowItem.getQuery() instanceof ParameterizedQuery) // return ((ParameterizedQuery)workflowItem.getQuery()).getName(); return workflowItem.getQuery().getName(); //return null; } private void setOperatorList(LinkedList<String> opretionList, LinkedList<String> operatorsList) { if (operatorsList != null) { String operationString = ""; for (String operation : operatorsList) { operationString = operationString + operation + "_"; } if (operationString != null && !(operationString.equals(""))) { opretionList.add(operationString.substring(0, operationString.lastIndexOf('_'))); } } } private void setoperandList(LinkedList<String> operandList, LinkedList<Long> operandsList) { if (operandsList != null) { String operandString = ""; for (Long operand : operandsList) { operandString = operandString + operand + "_"; } if (operandString != null) { operandList.add(operandString.substring(0, operandString.lastIndexOf('_'))); } } } private void generateOperatorAndOperandList(LinkedList<String> operatorsList, LinkedList<Long> operandsList, IAbstractQuery abstractQuery) { if (abstractQuery instanceof ParameterizedQuery) { operatorsList.add(CompositeQueryOperations.NONE.getOperation()); operandsList.add(abstractQuery.getId()); } else { generateOperatorAndOperandListForCompositeQuery(operatorsList, operandsList, abstractQuery); } } private void generateOperatorAndOperandListForCompositeQuery(LinkedList<String> operatorsList, LinkedList<Long> operandsList, IAbstractQuery abstractQuery) { if (abstractQuery instanceof CompositeQuery) { CompositeQuery compositeQuery = (CompositeQuery) abstractQuery; IOperation operation = compositeQuery.getOperation(); String operationName = setOperationForCompositeQuery(operation); generateOperatorAndOperandListForCompositeQuery(operatorsList, operandsList, operation .getOperandOne()); generateOperatorAndOperandListForCompositeQuery(operatorsList, operandsList, operation .getOperandTwo()); operatorsList.add(operationName); } else { operandsList.add(abstractQuery.getId()); } } /** * @param operation = operation on the CQ * @return operation object according to the String of operation to perform * * This method re */ private String setOperationForCompositeQuery(IOperation operation) { String operationName = null; if (operation instanceof Union) { operationName = "Union"; } else if (operation instanceof Intersection) { operationName = "Intersection"; } else if (operation instanceof Minus) { operationName = "Minus"; } return operationName; } public String[] getIdentifier() { return identifier; } public void setIdentifier(String[] identifier) { this.identifier = identifier; } }
package org.voovan.http.client; import org.voovan.Global; import org.voovan.http.HttpRequestType; import org.voovan.http.message.HttpStatic; import org.voovan.http.message.Request; import org.voovan.http.message.Response; import org.voovan.http.message.packet.Cookie; import org.voovan.http.message.packet.Header; import org.voovan.http.message.packet.Part; import org.voovan.http.server.HttpRequest; import org.voovan.http.server.HttpSessionState; import org.voovan.http.server.WebServerHandler; import org.voovan.http.server.WebSocketDispatcher; import org.voovan.http.websocket.WebSocketFrame; import org.voovan.http.websocket.WebSocketRouter; import org.voovan.http.websocket.WebSocketSession; import org.voovan.http.websocket.WebSocketType; import org.voovan.http.websocket.exception.WebSocketFilterException; import org.voovan.network.IoSession; import org.voovan.network.SSLManager; import org.voovan.network.exception.ReadMessageException; import org.voovan.network.exception.SendMessageException; import org.voovan.network.handler.SynchronousHandler; import org.voovan.network.messagesplitter.HttpMessageSplitter; import org.voovan.network.tcp.TcpSocket; import org.voovan.tools.TEnv; import org.voovan.tools.TObject; import org.voovan.tools.TString; import org.voovan.tools.hashwheeltimer.HashWheelTask; import org.voovan.tools.json.JSON; import org.voovan.tools.log.Logger; import org.voovan.tools.pool.PooledObject; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.security.NoSuchAlgorithmException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.function.Consumer; public class HttpClient extends PooledObject implements Closeable{ public final static String DEFAULT_USER_AGENT = "Voovan Http Client " + Global.getVersion(); private TcpSocket socket; private HttpRequest httpRequest; private Map<String, Object> parameters; private String charset="UTF-8"; private String urlString; private String initLocation; private boolean isSSL = false; private boolean isWebSocket = false; private WebSocketRouter webSocketRouter; private String hostString; private SynchronousHandler synchronousHandler; private AsyncHandler asyncHandler; private boolean paramInUrl = false; /** * * @param urlString URL */ public HttpClient(String urlString) { this.urlString = urlString; init(urlString, 5); } /** * * @param urlString URL * @param timeout */ public HttpClient(String urlString,int timeout) { this.urlString = urlString; init(urlString, timeout); } /** * * @param urlString URL * @param charset * @param timeout */ public HttpClient(String urlString,String charset,int timeout) { this.urlString = urlString; this.charset = charset; init(urlString, timeout); } /** * * @param urlString URL * @param charset */ public HttpClient(String urlString,String charset) { this.urlString = urlString; this.charset = charset; init(urlString, 5); } private boolean trySSL(String urlString){ boolean isSSL = urlString.toLowerCase().startsWith("https: if(!isSSL){ isSSL = urlString.toLowerCase().startsWith("wss: } return isSSL; } /** * * @param urlString * @param timeout */ private void init(String urlString, int timeout){ try { isSSL = trySSL(urlString); hostString = urlString; int port = 80; if(hostString.toLowerCase().startsWith("ws")){ hostString = "http"+hostString.substring(2,hostString.length()); } if(hostString.toLowerCase().startsWith("http")){ URL url = new URL(hostString); hostString = url.getHost(); port = url.getPort(); } int parhStart = urlString.indexOf("/", 8); if(parhStart > 8) { this.initLocation = urlString.substring(parhStart); } if(port==-1 && !isSSL){ port = 80; }else if(port==-1 && isSSL){ port = 443; } parameters = new LinkedHashMap<String, Object>(); socket = new TcpSocket(hostString, port==-1?80:port, timeout*1000); socket.filterChain().add(new HttpClientFilter(this)); socket.messageSplitter(new HttpMessageSplitter()); if(isSSL){ try { SSLManager sslManager = new SSLManager("TLS"); socket.setSSLManager(sslManager); } catch (NoSuchAlgorithmException e) { Logger.error(e); throw new HttpClientException("HttpClient init SSL failed:", e); } } socket.syncStart(); httpRequest = new HttpRequest(this.charset, socket.getSession()); initHeader(); asyncHandler = new AsyncHandler(this); synchronousHandler = (SynchronousHandler) socket.handler(); // Session.attachment //[0] HttpSessionState //[1] SocketFilterChain //[2] WebSocketFilter //[3] Response Object[] attachment = new Object[4]; attachment[0] = new HttpSessionState(); attachment[3] = new Response(); socket.getSession().setAttachment(attachment); } catch (IOException e) { Logger.error("HttpClient init failed",e); throw new HttpClientException("HttpClient init failed, on connect to " + urlString, e); } } /** * URL , POST * @return true:, false: */ public boolean isParamInUrl() { return paramInUrl; } /** * URL , POST * @param paramInUrl true:, false: * @return HttpClient */ public HttpClient setParamInUrl(boolean paramInUrl) { this.paramInUrl = paramInUrl; return this; } /** * http * @return HttpClient */ public HttpClient initHeader(){ httpRequest.header().put("Host", hostString); httpRequest.header().put("Pragma", "no-collection"); httpRequest.header().put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); httpRequest.header().put("User-Agent", DEFAULT_USER_AGENT); httpRequest.header().put("Accept-Encoding","gzip"); httpRequest.header().put("Connection","keep-alive"); return this; } /** * Socket * @return Socket */ protected TcpSocket getSocket(){ return socket; } public HttpRequest getHttpRequest() { return httpRequest; } /** * * @param buffer ByteBuffer */ public void sendStream(ByteBuffer buffer) { socket.getSession().send(buffer); } /** * * @return ByteBuffer * @throws IOException IO */ public ByteBuffer loadStream() throws IOException { IoSession session = socket.getSession(); ByteBuffer tmpBuffer = ByteBuffer.allocate(socket.getReadBufferSize()); session.getSocketSelector().select(); int readSize = session.read(tmpBuffer); if(session.getAttribute("SocketException") instanceof Exception){ session.close(); return null; }else if(readSize > 0) { return tmpBuffer; } else if(readSize == 0){ tmpBuffer.flip(); }else if(readSize == -1){ return null; } return tmpBuffer; } /** * * @param method Http * @return HttpClient */ public HttpClient setMethod(String method){ httpRequest.protocol().setMethod(method.toUpperCase()); return this; } /** * * @param bodyType Http * @return Request.BodyType */ public HttpClient setBodyType(Request.RequestType bodyType){ // ContentType ContentType if(!httpRequest.header().contain("Content-Type")) { if (bodyType == Request.RequestType.BODY_MULTIPART) { httpRequest.header().put("Content-Type", "multipart/form-data;"); } else if (bodyType == Request.RequestType.BODY_URLENCODED) { httpRequest.header().put("Content-Type", "application/x-www-form-urlencoded"); } } return this; } /** * * @param data * @return HttpClient */ public HttpClient setData(byte[] data){ if(data!=null) { httpRequest.body().write(data); } return this; } /** * * @param data * @return HttpClient */ public HttpClient setData(String data){ return setData(null, data, charset); } /** * * @param contentType ContentType * @param data * @return HttpClient */ public HttpClient setData(String contentType, String data){ return setData(null, data, charset); } /** * * @param contentType ContentType * @param data * @param charset * @return HttpClient */ public HttpClient setData(String contentType, String data, String charset){ if(data!=null) { if(contentType!=null) { httpRequest.header().put("Content-Type", contentType); } httpRequest.body().write(data, charset); } return this; } /** * * @param data * @param charset * @return HttpClient */ public HttpClient setJsonData(Object data, String charset){ return setData("application/json", JSON.toJSON(data), charset); } /** * * @param data * @return HttpClient */ public HttpClient setJsonData(Object data){ return setData("application/json", JSON.toJSON(data), charset); } /** * * @return Header */ public Header getHeader(){ return httpRequest.header(); } /** * * @param name Header * @param value Header * @return HttpClient */ public HttpClient putHeader(String name ,String value){ httpRequest.header().put(name, value); return this; } /** * Cookie * @return Cookie */ public List<Cookie> getCookies(){ return httpRequest.cookies(); } /** * * @return */ public Map<String,Object> getParameters(){ return parameters; } /** * * @param name * @param value * @return HttpClient */ public HttpClient putParameters(String name, String value){ parameters.put(name, value); return this; } /** * POST * Form Actiong="POST" enctype="multipart/form-data" * @param part POST * @return HttpClient */ public HttpClient addPart(Part part){ httpRequest.parts().add(part); return this; } /** * * @param name * @param file */ public void uploadFile(String name, File file){ setBodyType(Request.RequestType.BODY_MULTIPART); parameters.put(name, file); } /** * QueryString * Map QueryString * @param parameters Map * @param charset * @return */ public static String buildQueryString(Map<String,Object> parameters, String charset){ String queryString = ""; StringBuilder queryStringBuilder = new StringBuilder(); try { for (Entry<String, Object> parameter : parameters.entrySet()) { queryStringBuilder.append(parameter.getKey()); queryStringBuilder.append("="); queryStringBuilder.append(URLEncoder.encode(TObject.nullDefault(parameter.getValue(),"").toString(), charset)); queryStringBuilder.append("&"); } queryString = queryStringBuilder.toString(); queryString = queryStringBuilder.length()>0? TString.removeSuffix(queryString):queryString; } catch (IOException e) { Logger.error("HttpClient getQueryString error",e); } return queryString.isEmpty()? "" : queryString; } /** * QueryString * Map QueryString * @return */ private String getQueryString(){ return buildQueryString(parameters,charset); } private void buildRequest(String urlString){ httpRequest.protocol().setPath(urlString.isEmpty()?"/":urlString); //1. Body,URL if (httpRequest.getBodyType() == Request.RequestType.NORMAL || paramInUrl) { String queryString = getQueryString(); if(!TString.isNullOrEmpty(queryString)) { String requestPath = httpRequest.protocol().getPath(); if (requestPath.contains("?")) { queryString = "&" + queryString; } else { queryString = "?" + queryString; } httpRequest.protocol().setPath(httpRequest.protocol().getPath() + queryString); } } //2.Body Part else if(httpRequest.getBodyType() == Request.RequestType.BODY_MULTIPART){ try{ for (Entry<String, Object> parameter : parameters.entrySet()) { Part part = new Part(); part.header().put("name", parameter.getKey()); if(parameter.getValue() instanceof String) { part.body().changeToBytes(); part.body().write(URLEncoder.encode(parameter.getValue().toString(), charset).getBytes(charset)); }else if(parameter.getValue() instanceof File){ File file = (File) parameter.getValue(); part.body().changeToFile(file); part.header().put("filename", file.getName()); } httpRequest.parts().add(part); } } catch (IOException e) { Logger.error("HttpClient buildRequest error",e); } } //3.Body else if(httpRequest.getBodyType() == Request.RequestType.BODY_URLENCODED){ String queryString = getQueryString(); httpRequest.body().write(queryString, charset); } // Body if (httpRequest.protocol().getMethod().equals(HttpStatic.POST_STRING) && httpRequest.parts().size() > 0) { setBodyType(Request.RequestType.BODY_MULTIPART); } else if (httpRequest.protocol().getMethod().equals(HttpStatic.POST_STRING) && parameters.size() > 0) { setBodyType(Request.RequestType.BODY_URLENCODED); } else { setBodyType(Request.RequestType.NORMAL); } } /** * * @param location URL * @return Response * @throws SendMessageException * @throws ReadMessageException */ public Response send(String location) throws SendMessageException, ReadMessageException { return commonSend(location, null); } /** * , * @param location URL * @param async * @throws SendMessageException * @throws ReadMessageException */ public void asyncSend(String location, Consumer<Response> async) throws SendMessageException, ReadMessageException { commonSend(location, async); } /** * * @param location URL * @param async * @return Response * @throws SendMessageException * @throws ReadMessageException */ private synchronized Response commonSend(String location, Consumer<Response> async) throws SendMessageException, ReadMessageException { IoSession session = socket.getSession(); if (isWebSocket) { throw new SendMessageException("The WebSocket is connect, you can't send an http request."); } if(!TEnv.wait(socket.getReadTimeout(), false, ()->asyncHandler.isRunning())) { throw new SendMessageException("asyncHandler failed by timeout, the lastest isn't resposne, Socket will be disconnect"); } // Request buildRequest(TString.isNullOrEmpty(location) ? initLocation : location); session.getReadByteBufferChannel().clear(); session.getSendByteBufferChannel().clear(); synchronousHandler.reset(); // handler if(async != null) { asyncHandler.setAsync(async); socket.handler(asyncHandler); } else { session.socketContext().handler(synchronousHandler); } try { session.syncSend(httpRequest); } catch (Exception e) { throw new SendMessageException("HttpClient send to socket error", e); } Response response = null; if (async == null) { try { Object readObject = socket.syncRead(); if (readObject instanceof ReadMessageException) { throw (ReadMessageException)readObject; } else if (readObject instanceof Exception) { throw new ReadMessageException((Exception) readObject); } else { response = (Response) readObject; } return response; } catch (ReadMessageException e) { if (!isWebSocket) { throw e; } } finally { reset(response); } } return null; } /** * * @return Response * @throws SendMessageException * @throws ReadMessageException */ public Response send() throws SendMessageException, ReadMessageException { return send("/"); } /** * , * @param async * @throws SendMessageException * @throws ReadMessageException */ public void asyncSend(Consumer<Response> async) throws SendMessageException, ReadMessageException { asyncSend("/", async); } /** * * @param buffer * @return * @throws IOException IO */ public int sendBinary(ByteBuffer buffer) throws IOException { return this.httpRequest.send(buffer); } /** * * cookie request * @param response */ protected void reset(Response response){ // cookie Request if(response!=null && response.cookies()!=null && !response.cookies().isEmpty()){ httpRequest.cookies().addAll(response.cookies()); } reset(); } public void reset(){ httpRequest.body().changeToBytes(); parameters.clear(); List<Cookie> cookies = httpRequest.cookies(); httpRequest.clear(); //socketSession will be null httpRequest.cookies().addAll(cookies); // Header initHeader(); asyncHandler.reset(); } /** * * @param location URL * @return true: , false: * @throws SendMessageException * @throws ReadMessageException */ private void doWebSocketUpgrade(String location) throws SendMessageException, ReadMessageException { socket.setReadTimeout(-1); IoSession session = socket.getSession(); httpRequest.header().put("Host", hostString); httpRequest.header().put("Connection","Upgrade"); httpRequest.header().put("Upgrade", "websocket"); httpRequest.header().put("Pragma","no-collection"); httpRequest.header().put("Origin", this.urlString); httpRequest.header().put("Sec-WebSocket-Version","13"); httpRequest.header().put("Sec-WebSocket-Key","c1Mm+c0b28erlzCWWYfrIg=="); asyncSend(location, response -> { if(response.protocol().getStatus() == 101){ // WebSocket initWebSocket(); } }); } /** * Websocket * @param location URL * @param webSocketRouter WebSocker * @throws SendMessageException * @throws ReadMessageException */ public void webSocket(String location, WebSocketRouter webSocketRouter) throws SendMessageException, ReadMessageException { location = location == null ? initLocation : location; this.webSocketRouter = webSocketRouter; doWebSocketUpgrade(location); } /** * Websocket * @param webSocketRouter WebSocker * @throws SendMessageException * @throws ReadMessageException */ public void webSocket(WebSocketRouter webSocketRouter) throws SendMessageException, ReadMessageException { webSocket(null, webSocketRouter); } /** * WebSocket * HttpFilter */ protected void initWebSocket( ){ // WebSocket isWebSocket = true; IoSession session = socket.getSession(); WebSocketSession webSocketSession = new WebSocketSession(socket.getSession(), webSocketRouter, WebSocketType.CLIENT); WebSocketHandler webSocketHandler = new WebSocketHandler(this, webSocketSession, webSocketRouter); webSocketSession.setWebSocketRouter(webSocketRouter); //Socket, WebSocket socket.handler(webSocketHandler); HttpSessionState httpSessionState = WebServerHandler.getSessionState(session); httpSessionState.setType(HttpRequestType.WEBSOCKET); Object result = null; //onOpen result = webSocketRouter.onOpen(webSocketSession); if(result!=null) { ByteBuffer buffer = null; try { buffer = (ByteBuffer) WebSocketDispatcher.filterEncoder(webSocketSession, result); WebSocketFrame webSocketFrame = WebSocketFrame.newInstance(true, WebSocketFrame.Opcode.TEXT, true, buffer); sendWebSocketData(webSocketFrame); Global.getHashWheelTimer().addTask(new HashWheelTask() { @Override public void run() { try { sendWebSocketData(WebSocketFrame.newInstance(true, WebSocketFrame.Opcode.PING, false, null)); } catch (SendMessageException e) { e.printStackTrace(); } finally { this.cancel(); } } }, socket.getReadTimeout() / 1000, true); } catch (WebSocketFilterException e) { Logger.error(e); } catch (SendMessageException e) { Logger.error(e); } } } /** * WebSocket * @param webSocketFrame WebSocket * @throws SendMessageException */ private void sendWebSocketData(WebSocketFrame webSocketFrame) throws SendMessageException { socket.getSession().syncSend(webSocketFrame); } /** * HTTP */ @Override public void close(){ if(socket!=null) { Response response = ((Response) ((Object[])socket.getSession().getAttachment())[3]); response.release(); socket.close(); } } /** * * @return */ public boolean isConnect(){ if(socket!=null) { return socket.isConnected(); } else { return false; } } /** * * UTF-8, 5s * @param urlString URL * @return HttpClient , null HttpClient */ public static HttpClient newInstance(String urlString) { HttpClient httpClient = new HttpClient(urlString); if(!httpClient.isConnect()) { return null; } return httpClient; } /** * * 5s * @param urlString URL * @param timeout * @return HttpClient , null HttpClient */ public static HttpClient newInstance(String urlString, int timeout) { HttpClient httpClient = new HttpClient(urlString, timeout); if(!httpClient.isConnect()) { return null; } return httpClient; } /** * * 5s * @param urlString URL * @param charset * @return HttpClient , null HttpClient */ public static HttpClient newInstance(String urlString, String charset) { HttpClient httpClient = new HttpClient(urlString, charset); if(!httpClient.isConnect()) { return null; } return httpClient; } /** * * @param urlString URL * @param charset * @param timeout * @return HttpClient , null HttpClient */ public static HttpClient newInstance(String urlString, String charset, int timeout) { HttpClient httpClient = new HttpClient(urlString, charset, timeout); if(!httpClient.isConnect()) { return null; } return httpClient; } }
// FlexReader.java package loci.formats.in; import java.io.IOException; import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; import loci.common.*; import loci.formats.*; import loci.formats.meta.*; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; public class FlexReader extends FormatReader { // -- Constants -- /** Custom IFD entry for Flex XML. */ protected static final int FLEX = 65200; // -- Fields -- /** Scale factor for each image. */ protected double[][][] factors; /** Camera binning values. */ private int binX, binY; private int plateCount; private int wellCount; private int fieldCount; private Vector<String> channelNames; private Vector<Float> xPositions, yPositions; private Vector<String> measurementFiles; /** * List of .flex files belonging to this dataset. * Indices into the array are the well row and well column. */ private String[][] flexFiles; private Hashtable[][][] ifds; /** Specifies the row and column index into 'flexFiles' for a given well. */ private int[][] wellNumber; // -- Constructor -- /** Constructs a new Flex reader. */ public FlexReader() { super("Evotec Flex", "flex"); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream in) throws IOException { return false; } /* @see loci.formats.IFormatReader#getUsedFiles() */ public String[] getUsedFiles() { FormatTools.assertId(currentId, true, 1); Vector<String> files = new Vector<String>(); for (int i=0; i<flexFiles.length; i++) { for (int j=0; j<flexFiles[i].length; j++) { if (flexFiles[i][j] != null) files.add(flexFiles[i][j]); } } for (String file : measurementFiles) { files.add(file); } return files.toArray(new String[0]); } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); int[] lengths = new int[] {fieldCount, wellCount, plateCount}; int[] pos = FormatTools.rasterToPosition(lengths, getSeries()); int imageNumber = getImageCount() * pos[0] + no; int wellRow = wellNumber[pos[1]][0]; int wellCol = wellNumber[pos[1]][1]; Hashtable ifd = ifds[wellRow][wellCol][imageNumber]; RandomAccessInputStream s = new RandomAccessInputStream(flexFiles[wellRow][wellCol]); int nBytes = TiffTools.getBitsPerSample(ifd)[0] / 8; // expand pixel values with multiplication by factor[no] byte[] bytes = TiffTools.getSamples(ifd, s, buf, x, y, w, h); s.close(); int bpp = FormatTools.getBytesPerPixel(getPixelType()); int num = bytes.length / bpp; for (int i=num-1; i>=0; i int q = nBytes == 1 ? bytes[i] & 0xff : DataTools.bytesToInt(bytes, i * bpp, bpp, isLittleEndian()); q = (int) (q * factors[wellRow][wellCol][imageNumber]); DataTools.unpackBytes(q, buf, i * bpp, bpp, isLittleEndian()); } return buf; } // -- IFormatHandler API methods -- /* @see loci.formats.IFormatHandler#close() */ public void close() throws IOException { super.close(); factors = null; binX = binY = 0; plateCount = wellCount = fieldCount = 0; channelNames = null; measurementFiles = null; } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { debug("FlexReader.initFile(" + id + ")"); super.initFile(id); measurementFiles = new Vector<String>(); boolean doGrouping = true; Location currentFile = new Location(id).getAbsoluteFile(); int nRows = 0, nCols = 0; Hashtable<String, String> v = new Hashtable<String, String>(); try { String name = currentFile.getName(); int wellRow = Integer.parseInt(name.substring(0, 3)); int wellCol = Integer.parseInt(name.substring(3, 6)); if (wellRow > nRows) nRows = wellRow; if (wellCol > nCols) nCols = wellCol; v.put(wellRow + "," + wellCol, currentFile.getAbsolutePath()); } catch (NumberFormatException e) { if (debug) trace(e); doGrouping = false; } if (!isGroupFiles()) doGrouping = false; if (isGroupFiles()) findMeasurementFiles(currentFile); MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); if (doGrouping) { // group together .flex files that are in the same directory Location dir = currentFile.getParentFile(); String[] files = dir.list(); for (String file : files) { // file names should be nnnnnnnnn.flex, where 'n' is 0-9 if (file.endsWith(".flex") && file.length() == 14 && !id.endsWith(file)) { int wellRow = Integer.parseInt(file.substring(0, 3)); int wellCol = Integer.parseInt(file.substring(3, 6)); if (wellRow > nRows) nRows = wellRow; if (wellCol > nCols) nCols = wellCol; String path = new Location(dir, file).getAbsolutePath(); v.put(wellRow + "," + wellCol, path); } else if (!file.startsWith(".") && !id.endsWith(file)) { doGrouping = false; break; } } if (doGrouping) { flexFiles = new String[nRows][nCols]; ifds = new Hashtable[nRows][nCols][]; factors = new double[nRows][nCols][]; wellCount = v.size(); wellNumber = new int[wellCount][2]; RandomAccessInputStream s = null; boolean firstFile = true; int nextWell = 0; for (int row=0; row<flexFiles.length; row++) { for (int col=0; col<flexFiles[row].length; col++) { flexFiles[row][col] = v.get((row + 1) + "," + (col + 1)); if (flexFiles[row][col] == null) continue; wellNumber[nextWell][0] = row; wellNumber[nextWell++][1] = col; s = new RandomAccessInputStream(flexFiles[row][col]); ifds[row][col] = TiffTools.getIFDs(s); s.close(); parseFlexFile(row, col, firstFile, store); if (firstFile) firstFile = false; } } } } if (!doGrouping) { wellCount = 1; flexFiles = new String[1][1]; ifds = new Hashtable[1][1][]; factors = new double[1][1][]; wellNumber = new int[][] {{0, 0}}; flexFiles[0][0] = currentFile.getAbsolutePath(); RandomAccessInputStream s = new RandomAccessInputStream(flexFiles[0][0]); ifds[0][0] = TiffTools.getIFDs(s); s.close(); parseFlexFile(0, 0, true, store); } wellCount = v.size() == 0 ? 1 : v.size(); MetadataTools.populatePixels(store, this); store.setInstrumentID("Instrument:0", 0); int[] lengths = new int[] {fieldCount, wellCount, plateCount}; /* debug */ System.out.println("fieldCount = " + fieldCount); System.out.println("wellCount = " + wellCount); System.out.println("wellNumber.size = " + wellNumber.length + "x" + wellNumber[0].length); /* end debug */ for (int i=0; i<getSeriesCount(); i++) { int[] pos = FormatTools.rasterToPosition(lengths, i); store.setImageID("Image:" + i, i); store.setImageInstrumentRef("Instrument:0", i); store.setImageName("Well Row #" + wellNumber[pos[1]][0] + ", Column #" + wellNumber[pos[1]][1] + "; Field #" + pos[0], i); store.setWellSampleIndex(new Integer(i), pos[2], pos[1], pos[0]); store.setWellSampleImageRef("Image:" + i, pos[2], pos[1], pos[0]); if (pos[0] < xPositions.size()) { store.setWellSamplePosX(xPositions.get(pos[0]), pos[2], pos[1], pos[0]); } if (pos[0] < yPositions.size()) { store.setWellSamplePosY(yPositions.get(pos[0]), pos[2], pos[1], pos[0]); } store.setWellRow(new Integer(wellNumber[pos[1]][0]), pos[2], pos[1]); store.setWellColumn(new Integer(wellNumber[pos[1]][1]), pos[2], pos[1]); } } // -- Helper methods -- /** * Parses XML metadata from the Flex file corresponding to the given well. * If the 'firstFile' flag is set, then the core metadata is also * populated. */ private void parseFlexFile(int wellRow, int wellCol, boolean firstFile, MetadataStore store) throws FormatException, IOException { if (flexFiles[wellRow][wellCol] == null) return; if (channelNames == null) channelNames = new Vector<String>(); if (xPositions == null) xPositions = new Vector<Float>(); if (yPositions == null) yPositions = new Vector<Float>(); // parse factors from XML String xml = (String) TiffTools.getIFDValue(ifds[wellRow][wellCol][0], FLEX); // HACK - workaround for Windows and Mac OS X bug where // SAX parser fails due to improperly handled mu (181) characters. byte[] c = xml.getBytes(); for (int i=0; i<c.length; i++) { if (c[i] > '~' || (c[i] != '\t' && c[i] < ' ')) c[i] = ' '; } Vector n = new Vector(); Vector f = new Vector(); DefaultHandler handler = new FlexHandler(n, f, store, firstFile); DataTools.parseXML(c, handler); if (firstFile) populateCoreMetadata(wellRow, wellCol, n); int totalPlanes = getSeriesCount() * getImageCount(); // verify factor count int nsize = n.size(); int fsize = f.size(); if (debug && (nsize != fsize || nsize != totalPlanes)) { LogTools.println("Warning: mismatch between image count, " + "names and factors (count=" + totalPlanes + ", names=" + nsize + ", factors=" + fsize + ")"); } for (int i=0; i<nsize; i++) addGlobalMeta("Name " + i, n.get(i)); for (int i=0; i<fsize; i++) addGlobalMeta("Factor " + i, f.get(i)); // parse factor values factors[wellRow][wellCol] = new double[totalPlanes]; int max = 0; for (int i=0; i<fsize; i++) { String factor = (String) f.get(i); double q = 1; try { q = Double.parseDouble(factor); } catch (NumberFormatException exc) { if (debug) { LogTools.println("Warning: invalid factor #" + i + ": " + factor); } } factors[wellRow][wellCol][i] = q; if (q > factors[wellRow][wellCol][max]) max = i; } Arrays.fill(factors[wellRow][wellCol], fsize, factors[wellRow][wellCol].length, 1); // determine pixel type if (factors[wellRow][wellCol][max] > 256) { core[0].pixelType = FormatTools.UINT32; } else if (factors[wellRow][wellCol][max] > 1) { core[0].pixelType = FormatTools.UINT16; } for (int i=1; i<core.length; i++) { core[i].pixelType = getPixelType(); } } /** Populate core metadata using the given list of image names. */ private void populateCoreMetadata(int wellRow, int wellCol, Vector<String> imageNames) throws FormatException { if (getSizeZ() == 0 && getSizeC() == 0 && getSizeT() == 0) { Vector<String> uniqueChannels = new Vector<String>(); for (int i=0; i<imageNames.size(); i++) { String name = imageNames.get(i); String[] tokens = name.split("_"); if (tokens.length > 1) { // fields are indexed from 1 int fieldIndex = Integer.parseInt(tokens[0]); if (fieldIndex > fieldCount) fieldCount = fieldIndex; } String channel = tokens[tokens.length - 1]; if (!uniqueChannels.contains(channel)) uniqueChannels.add(channel); } if (fieldCount == 0) fieldCount = 1; core[0].sizeC = (int) Math.max(uniqueChannels.size(), 1); core[0].sizeZ = 1; core[0].sizeT = imageNames.size() / (fieldCount * getSizeC()); } if (getSizeC() == 0) { core[0].sizeC = (int) Math.max(channelNames.size(), 1); } if (getSizeZ() == 0) core[0].sizeZ = 1; if (getSizeT() == 0) core[0].sizeT = 1; if (plateCount == 0) plateCount = 1; if (wellCount == 0) wellCount = 1; if (fieldCount == 0) fieldCount = 1; core[0].imageCount = getSizeZ() * getSizeC() * getSizeT(); int seriesCount = plateCount * wellCount * fieldCount; if (getImageCount() * seriesCount < ifds[wellRow][wellCol].length) { core[0].imageCount = ifds[wellRow][wellCol].length / seriesCount; core[0].sizeZ = 1; core[0].sizeC = 1; core[0].sizeT = ifds[wellRow][wellCol].length / seriesCount; } Hashtable ifd = ifds[wellRow][wellCol][0]; core[0].sizeX = (int) TiffTools.getImageWidth(ifd); core[0].sizeY = (int) TiffTools.getImageLength(ifd); core[0].dimensionOrder = "XYCZT"; core[0].rgb = false; core[0].interleaved = false; core[0].indexed = false; core[0].littleEndian = TiffTools.isLittleEndian(ifd); if (seriesCount > 1) { CoreMetadata oldCore = core[0]; core = new CoreMetadata[seriesCount]; Arrays.fill(core, oldCore); } } /** * Search for measurement files (.mea, .res) that correspond to the * given Flex file. */ private void findMeasurementFiles(Location flexFile) throws IOException { // we're assuming that the directory structure looks something like this: // top level directory // top level flex dir top level measurement dir // plate #0 ... plate #n plate #0 ... plate #n // .flex ... .flex .mea .res // or that the .mea and .res are in the same directory as the .flex files Location plateDir = flexFile.getParentFile(); String[] files = plateDir.list(); for (String file : files) { String lfile = file.toLowerCase(); if (lfile.endsWith(".mea") || lfile.endsWith(".res")) { measurementFiles.add(new Location(plateDir, file).getAbsolutePath()); } } if (measurementFiles.size() > 0) return; Location flexDir = plateDir.getParentFile(); Location topDir = flexDir.getParentFile(); Location measurementDir = null; String[] topDirList = topDir.list(); for (String file : topDirList) { if (!flexDir.getAbsolutePath().endsWith(file)) { measurementDir = new Location(topDir, file); break; } } if (measurementDir == null) return; String[] measurementPlates = measurementDir.list(); String plateName = plateDir.getName(); plateDir = null; for (String file : measurementPlates) { if (file.indexOf(plateName) != -1 || plateName.indexOf(file) != -1) { plateDir = new Location(measurementDir, file); break; } } if (plateDir == null) return; files = plateDir.list(); for (String file : files) { measurementFiles.add(new Location(plateDir, file).getAbsolutePath()); } } // -- Helper classes -- /** SAX handler for parsing XML. */ public class FlexHandler extends DefaultHandler { private Vector names, factors; private MetadataStore store; private int nextLightSource = 0; private int nextLaser = -1; private int nextArrayImage = 0; private int nextSlider = 0; private int nextFilter = 0; private int nextCamera = 0; private int nextObjective = -1; private int nextSublayout = 0; private int nextField = 0; private int nextStack = 0; private int nextPlane = 0; private int nextKinetic = 0; private int nextDispensing = 0; private int nextImage = 0; private int nextLightSourceCombination = 0; private int nextLightSourceRef = 0; private int nextPlate = 0; private int nextWell = 0; private int nextSliderRef = 0; private int nextFilterCombination = 0; private String parentQName; private String currentQName; private boolean populateCore = true; public FlexHandler(Vector names, Vector factors, MetadataStore store, boolean populateCore) { this.names = names; this.factors = factors; this.store = store; this.populateCore = populateCore; } public void characters(char[] ch, int start, int length) { String value = new String(ch, start, length); if (currentQName.equals("PlateName")) { store.setPlateName(value, nextPlate - 1); addGlobalMeta("Plate " + (nextPlate - 1) + " Name", value); } else if (parentQName.equals("Plate")) { addGlobalMeta("Plate " + (nextPlate - 1) + " " + currentQName, value); } else if (parentQName.equals("WellShape")) { addGlobalMeta("Plate " + (nextPlate - 1) + " WellShape " + currentQName, value); } else if (currentQName.equals("Wavelength")) { store.setLaserWavelength(new Integer(value), 0, nextLaser); addGlobalMeta("Laser " + nextLaser + " Wavelength", value); } else if (currentQName.equals("Magnification")) { store.setObjectiveCalibratedMagnification(new Float(value), 0, nextObjective); } else if (currentQName.equals("NumAperture")) { store.setObjectiveLensNA(new Float(value), 0, nextObjective); } else if (currentQName.equals("Immersion")) { store.setObjectiveImmersion(value, 0, nextObjective); } else if (currentQName.equals("OffsetX") || currentQName.equals("OffsetY")) { addGlobalMeta("Sublayout " + (nextSublayout - 1) + " Field " + (nextField - 1) + " " + currentQName, value); Float offset = new Float(value); if (currentQName.equals("OffsetX")) xPositions.add(offset); else yPositions.add(offset); } else if (currentQName.equals("OffsetZ")) { addGlobalMeta("Stack " + (nextStack - 1) + " Plane " + (nextPlane - 1) + " OffsetZ", value); } else if (currentQName.equals("Power")) { addGlobalMeta("LightSourceCombination " + (nextLightSourceCombination - 1) + " LightSourceRef " + (nextLightSourceRef - 1) + " Power", value); } else if (parentQName.equals("Image")) { addGlobalMeta("Image " + (nextImage - 1) + " " + currentQName, value); if (currentQName.equals("DateTime") && nextImage == 1) { store.setImageCreationDate(value, 0); } else if (currentQName.equals("CameraBinningX")) { binX = Integer.parseInt(value); } else if (currentQName.equals("CameraBinningY")) { binY = Integer.parseInt(value); } else if (currentQName.equals("LightSourceCombinationRef")) { if (!channelNames.contains(value)) channelNames.add(value); } } else if (parentQName.equals("ImageResolutionX")) { store.setDimensionsPhysicalSizeX(new Float(value), nextImage - 1, 0); } else if (parentQName.equals("ImageResolutionY")) { store.setDimensionsPhysicalSizeY(new Float(value), nextImage - 1, 0); } else if (parentQName.equals("Well")) { addGlobalMeta("Well " + (nextWell - 1) + " " + currentQName, value); } } public void startElement(String uri, String localName, String qName, Attributes attributes) { currentQName = qName; if (qName.equals("Array")) { int len = attributes.getLength(); for (int i=0; i<len; i++, nextArrayImage++) { String name = attributes.getQName(i); if (name.equals("Name")) { names.add(attributes.getValue(i)); //if (nextArrayImage == 0) { // store.setImageName(attributes.getValue(i), 0); } else if (name.equals("Factor")) factors.add(attributes.getValue(i)); //else if (name.equals("Description") && nextArrayImage == 0) { // store.setImageDescription(attributes.getValue(i), 0); } } else if (qName.equals("LightSource")) { parentQName = qName; String id = attributes.getValue("ID"); String type = attributes.getValue("LightSourceType"); addGlobalMeta("LightSource " + nextLightSource + " ID", id); addGlobalMeta("LightSource " + nextLightSource + " Type", type); if (type.equals("Laser")) nextLaser++; nextLightSource++; } else if (qName.equals("Slider")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Slider " + nextSlider + " " + attributes.getQName(i), attributes.getValue(i)); } nextSlider++; } else if (qName.equals("Filter")) { for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Filter " + nextFilter + " " + attributes.getQName(i), attributes.getValue(i)); } nextFilter++; } else if (qName.equals("Camera")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Camera " + nextCamera + " " + attributes.getQName(i), attributes.getValue(i)); } nextCamera++; } else if (qName.startsWith("PixelSize") && parentQName.equals("Camera")) { for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Camera " + (nextCamera - 1) + " " + qName + " " + attributes.getQName(i), attributes.getValue(i)); } } else if (qName.equals("Objective")) { parentQName = qName; nextObjective++; // link Objective to Image using ObjectiveSettings store.setObjectiveID("Objective:" + nextObjective, 0, 0); store.setObjectiveSettingsObjective("Objective:" + nextObjective, 0); store.setObjectiveCorrection("Unknown", 0, 0); } else if (qName.equals("Sublayout")) { parentQName = qName; nextField = 0; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Sublayout " + nextSublayout + " " + attributes.getQName(i), attributes.getValue(i)); } nextSublayout++; } else if (qName.equals("Field")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Sublayout " + (nextSublayout - 1) + " Field " + nextField + " " + attributes.getQName(i), attributes.getValue(i)); } nextField++; int fieldNo = Integer.parseInt(attributes.getValue("No")); if (fieldNo > fieldCount) fieldCount++; } else if (qName.equals("Stack")) { nextPlane = 0; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Stack " + nextStack + " " + attributes.getQName(i), attributes.getValue(i)); } nextStack++; } else if (qName.equals("Plane")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Stack " + (nextStack - 1) + " Plane " + nextPlane + " " + attributes.getQName(i), attributes.getValue(i)); } nextPlane++; int planeNo = Integer.parseInt(attributes.getValue("No")); if (planeNo > getSizeZ() && populateCore) core[0].sizeZ++; } else if (qName.equals("Kinetic")) { for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Kinetic " + nextKinetic + " " + attributes.getQName(i), attributes.getValue(i)); } nextKinetic++; } else if (qName.equals("Dispensing")) { for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Dispensing " + nextDispensing + " " + attributes.getQName(i), attributes.getValue(i)); } nextDispensing++; } else if (qName.equals("LightSourceCombination")) { nextLightSourceRef = 0; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("LightSourceCombination " + nextLightSourceCombination + " " + attributes.getQName(i), attributes.getValue(i)); } nextLightSourceCombination++; } else if (qName.equals("LightSourceRef")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("LightSourceCombination " + (nextLightSourceCombination - 1) + " LightSourceRef " + nextLightSourceRef + " " + attributes.getQName(i), attributes.getValue(i)); } nextLightSourceRef++; } else if (qName.equals("FilterCombination")) { parentQName = qName; nextSliderRef = 0; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("FilterCombination " + nextFilterCombination + " " + attributes.getQName(i), attributes.getValue(i)); } nextFilterCombination++; } else if (qName.equals("SliderRef")) { for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("FilterCombination " + (nextFilterCombination - 1) + " SliderRef " + nextSliderRef + " " + attributes.getQName(i), attributes.getValue(i)); } nextSliderRef++; } else if (qName.equals("Image")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Image " + nextImage + " " + attributes.getQName(i), attributes.getValue(i)); } nextImage++; //Implemented for FLEX v1.7 and below String x = attributes.getValue("CameraBinningX"); String y = attributes.getValue("CameraBinningY"); if (x != null) binX = Integer.parseInt(x); if (y != null) binY = Integer.parseInt(y); } else if (qName.equals("Plate") || qName.equals("WellShape") || qName.equals("Well")) { parentQName = qName; if (qName.equals("Plate")) { nextPlate++; plateCount++; } else if (qName.equals("Well")) { nextWell++; wellCount++; } } else if (qName.equals("WellCoordinate")) { int ndx = nextWell - 1; addGlobalMeta("Well" + ndx + " Row", attributes.getValue("Row")); addGlobalMeta("Well" + ndx + " Col", attributes.getValue("Col")); //store.setWellRow(new Integer(attributes.getValue("Row")), 0, ndx); //store.setWellColumn(new Integer(attributes.getValue("Col")), 0, ndx); } else if (qName.equals("Status")) { addGlobalMeta("Status", attributes.getValue("StatusString")); } else if(qName.equals("ImageResolutionX")) { parentQName = qName; //TODO: definition of the dimension type and unit Where to store? for (int i=0; i<attributes.getLength(); i++) { //addGlobalMeta("Image " + nextImage + " " + attributes.getQName(i), attributes.getValue(i)); } } else if(qName.equals("ImageResolutionY")) { parentQName = qName; //TODO: definition of the dimension type and unit Where to store? for (int i=0; i<attributes.getLength(); i++) { //addGlobalMeta("Image " + nextImage + " " + attributes.getQName(i),attributes.getValue(i)); } } } } }
// FlexReader.java package loci.formats.in; import java.io.IOException; import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; import loci.common.*; import loci.formats.*; import loci.formats.meta.*; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; public class FlexReader extends FormatReader { // -- Constants -- /** Custom IFD entry for Flex XML. */ protected static final int FLEX = 65200; // -- Fields -- /** Scale factor for each image. */ protected double[][][] factors; /** Camera binning values. */ private int binX, binY; private int plateCount; private int wellCount; private int fieldCount; private Vector<String> channelNames; private Vector<Float> xPositions, yPositions; /** * List of .flex files belonging to this dataset. * Indices into the array are the well row and well column. */ private String[][] flexFiles; private Hashtable[][][] ifds; /** Specifies the row and column index into 'flexFiles' for a given well. */ private int[][] wellNumber; // -- Constructor -- /** Constructs a new Flex reader. */ public FlexReader() { super("Evotec Flex", "flex"); } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream in) throws IOException { return false; } /* @see loci.formats.IFormatReader#getUsedFiles() */ public String[] getUsedFiles() { FormatTools.assertId(currentId, true, 1); Vector<String> files = new Vector<String>(); for (int i=0; i<flexFiles.length; i++) { for (int j=0; j<flexFiles[i].length; j++) { if (flexFiles[i][j] != null) files.add(flexFiles[i][j]); } } return files.toArray(new String[0]); } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); int[] lengths = new int[] {fieldCount, wellCount, plateCount}; int[] pos = FormatTools.rasterToPosition(lengths, getSeries()); int imageNumber = getImageCount() * pos[0] + no; int wellRow = wellNumber[pos[1]][0]; int wellCol = wellNumber[pos[1]][1]; Hashtable ifd = ifds[wellRow][wellCol][imageNumber]; RandomAccessInputStream s = new RandomAccessInputStream(flexFiles[wellRow][wellCol]); int nBytes = TiffTools.getBitsPerSample(ifd)[0] / 8; // expand pixel values with multiplication by factor[no] byte[] bytes = TiffTools.getSamples(ifd, s, buf, x, y, w, h); s.close(); int bpp = FormatTools.getBytesPerPixel(getPixelType()); int num = bytes.length / bpp; for (int i=num-1; i>=0; i int q = nBytes == 1 ? bytes[i] & 0xff : DataTools.bytesToInt(bytes, i * bpp, bpp, isLittleEndian()); q = (int) (q * factors[wellRow][wellCol][imageNumber]); DataTools.unpackBytes(q, buf, i * bpp, bpp, isLittleEndian()); } return buf; } // -- IFormatHandler API methods -- /* @see loci.formats.IFormatHandler#close() */ public void close() throws IOException { super.close(); factors = null; binX = binY = 0; plateCount = wellCount = fieldCount = 0; channelNames = null; } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { debug("FlexReader.initFile(" + id + ")"); super.initFile(id); boolean doGrouping = true; Location currentFile = new Location(id).getAbsoluteFile(); int nRows = 0, nCols = 0; Hashtable<String, String> v = new Hashtable<String, String>(); try { String name = currentFile.getName(); int wellRow = Integer.parseInt(name.substring(0, 3)); int wellCol = Integer.parseInt(name.substring(3, 6)); if (wellRow > nRows) nRows = wellRow; if (wellCol > nCols) nCols = wellCol; v.put(wellRow + "," + wellCol, currentFile.getAbsolutePath()); } catch (NumberFormatException e) { if (debug) trace(e); doGrouping = false; } if (!isGroupFiles()) doGrouping = false; MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); if (doGrouping) { // group together .flex files that are in the same directory Location dir = currentFile.getParentFile(); String[] files = dir.list(); for (String file : files) { // file names should be nnnnnnnnn.flex, where 'n' is 0-9 if (file.endsWith(".flex") && file.length() == 14 && !id.endsWith(file)) { int wellRow = Integer.parseInt(file.substring(0, 3)); int wellCol = Integer.parseInt(file.substring(3, 6)); if (wellRow > nRows) nRows = wellRow; if (wellCol > nCols) nCols = wellCol; String path = new Location(dir, file).getAbsolutePath(); v.put(wellRow + "," + wellCol, path); } else if (!file.startsWith(".") && !id.endsWith(file)) { doGrouping = false; break; } } if (doGrouping) { flexFiles = new String[nRows][nCols]; ifds = new Hashtable[nRows][nCols][]; factors = new double[nRows][nCols][]; wellCount = v.size(); wellNumber = new int[wellCount][2]; RandomAccessInputStream s = null; boolean firstFile = true; int nextWell = 0; for (int row=0; row<flexFiles.length; row++) { for (int col=0; col<flexFiles[row].length; col++) { flexFiles[row][col] = v.get((row + 1) + "," + (col + 1)); if (flexFiles[row][col] == null) continue; wellNumber[nextWell][0] = row; wellNumber[nextWell++][1] = col; s = new RandomAccessInputStream(flexFiles[row][col]); ifds[row][col] = TiffTools.getIFDs(s); s.close(); parseFlexFile(row, col, firstFile, store); if (firstFile) firstFile = false; } } } } if (!doGrouping) { wellCount = 1; flexFiles = new String[1][1]; ifds = new Hashtable[1][1][]; factors = new double[1][1][]; flexFiles[0][0] = currentFile.getAbsolutePath(); RandomAccessInputStream s = new RandomAccessInputStream(flexFiles[0][0]); ifds[0][0] = TiffTools.getIFDs(s); s.close(); parseFlexFile(0, 0, true, store); } MetadataTools.populatePixels(store, this); store.setInstrumentID("Instrument:0", 0); int[] lengths = new int[] {fieldCount, wellCount, plateCount}; for (int i=0; i<getSeriesCount(); i++) { int[] pos = FormatTools.rasterToPosition(lengths, i); store.setImageID("Image:" + i, i); store.setImageInstrumentRef("Instrument:0", i); store.setImageName("Well Row #" + wellNumber[pos[1]][0] + ", Column #" + wellNumber[pos[1]][1] + "; Field #" + pos[0], i); store.setWellSampleIndex(new Integer(i), pos[2], pos[1], pos[0]); store.setWellSampleImageRef("Image:" + i, pos[2], pos[1], pos[0]); if (pos[0] < xPositions.size()) { store.setWellSamplePosX(xPositions.get(pos[0]), pos[2], pos[1], pos[0]); } if (pos[0] < yPositions.size()) { store.setWellSamplePosY(yPositions.get(pos[0]), pos[2], pos[1], pos[0]); } store.setWellRow(new Integer(wellNumber[pos[1]][0]), pos[2], pos[1]); store.setWellColumn(new Integer(wellNumber[pos[1]][1]), pos[2], pos[1]); } } // -- Helper methods -- /** * Parses XML metadata from the Flex file corresponding to the given well. * If the 'firstFile' flag is set, then the core metadata is also * populated. */ private void parseFlexFile(int wellRow, int wellCol, boolean firstFile, MetadataStore store) throws FormatException, IOException { if (flexFiles[wellRow][wellCol] == null) return; if (channelNames == null) channelNames = new Vector<String>(); if (xPositions == null) xPositions = new Vector<Float>(); if (yPositions == null) yPositions = new Vector<Float>(); // parse factors from XML String xml = (String) TiffTools.getIFDValue(ifds[wellRow][wellCol][0], FLEX); // HACK - workaround for Windows and Mac OS X bug where // SAX parser fails due to improperly handled mu (181) characters. byte[] c = xml.getBytes(); for (int i=0; i<c.length; i++) { if (c[i] > '~' || (c[i] != '\t' && c[i] < ' ')) c[i] = ' '; } Vector n = new Vector(); Vector f = new Vector(); DefaultHandler handler = new FlexHandler(n, f, store, firstFile); DataTools.parseXML(c, handler); if (firstFile) populateCoreMetadata(wellRow, wellCol, n); int totalPlanes = getSeriesCount() * getImageCount(); // verify factor count int nsize = n.size(); int fsize = f.size(); if (debug && (nsize != fsize || nsize != totalPlanes)) { LogTools.println("Warning: mismatch between image count, " + "names and factors (count=" + totalPlanes + ", names=" + nsize + ", factors=" + fsize + ")"); } for (int i=0; i<nsize; i++) addGlobalMeta("Name " + i, n.get(i)); for (int i=0; i<fsize; i++) addGlobalMeta("Factor " + i, f.get(i)); // parse factor values factors[wellRow][wellCol] = new double[totalPlanes]; int max = 0; for (int i=0; i<fsize; i++) { String factor = (String) f.get(i); double q = 1; try { q = Double.parseDouble(factor); } catch (NumberFormatException exc) { if (debug) { LogTools.println("Warning: invalid factor #" + i + ": " + factor); } } factors[wellRow][wellCol][i] = q; if (q > factors[wellRow][wellCol][max]) max = i; } Arrays.fill(factors[wellRow][wellCol], fsize, factors[wellRow][wellCol].length, 1); // determine pixel type if (factors[wellRow][wellCol][max] > 256) { core[0].pixelType = FormatTools.UINT32; } else if (factors[wellRow][wellCol][max] > 1) { core[0].pixelType = FormatTools.UINT16; } for (int i=1; i<core.length; i++) { core[i].pixelType = getPixelType(); } } /** Populate core metadata using the given list of image names. */ private void populateCoreMetadata(int wellRow, int wellCol, Vector<String> imageNames) throws FormatException { if (getSizeZ() == 0 && getSizeC() == 0 && getSizeT() == 0) { Vector<String> uniqueChannels = new Vector<String>(); for (int i=0; i<imageNames.size(); i++) { String name = imageNames.get(i); String[] tokens = name.split("_"); if (tokens.length > 1) { // fields are indexed from 1 int fieldIndex = Integer.parseInt(tokens[0]); if (fieldIndex > fieldCount) fieldCount = fieldIndex; } String channel = tokens[tokens.length - 1]; if (!uniqueChannels.contains(channel)) uniqueChannels.add(channel); } if (fieldCount == 0) fieldCount = 1; core[0].sizeC = (int) Math.max(uniqueChannels.size(), 1); core[0].sizeZ = 1; core[0].sizeT = imageNames.size() / (fieldCount * getSizeC()); } if (getSizeC() == 0) { core[0].sizeC = (int) Math.max(channelNames.size(), 1); } if (getSizeZ() == 0) core[0].sizeZ = 1; if (getSizeT() == 0) core[0].sizeT = 1; if (plateCount == 0) plateCount = 1; if (wellCount == 0) wellCount = 1; if (fieldCount == 0) fieldCount = 1; core[0].imageCount = getSizeZ() * getSizeC() * getSizeT(); int seriesCount = plateCount * wellCount * fieldCount; if (getImageCount() * seriesCount < ifds[wellRow][wellCol].length) { core[0].imageCount = ifds[wellRow][wellCol].length / seriesCount; core[0].sizeZ = 1; core[0].sizeC = 1; core[0].sizeT = ifds[wellRow][wellCol].length / seriesCount; } Hashtable ifd = ifds[wellRow][wellCol][0]; core[0].sizeX = (int) TiffTools.getImageWidth(ifd); core[0].sizeY = (int) TiffTools.getImageLength(ifd); core[0].dimensionOrder = "XYCZT"; core[0].rgb = false; core[0].interleaved = false; core[0].indexed = false; core[0].littleEndian = TiffTools.isLittleEndian(ifd); if (seriesCount > 1) { CoreMetadata oldCore = core[0]; core = new CoreMetadata[seriesCount]; Arrays.fill(core, oldCore); } } // -- Helper classes -- /** SAX handler for parsing XML. */ public class FlexHandler extends DefaultHandler { private Vector names, factors; private MetadataStore store; private int nextLightSource = 0; private int nextLaser = -1; private int nextArrayImage = 0; private int nextSlider = 0; private int nextFilter = 0; private int nextCamera = 0; private int nextObjective = -1; private int nextSublayout = 0; private int nextField = 0; private int nextStack = 0; private int nextPlane = 0; private int nextKinetic = 0; private int nextDispensing = 0; private int nextImage = 0; private int nextLightSourceCombination = 0; private int nextLightSourceRef = 0; private int nextPlate = 0; private int nextWell = 0; private int nextSliderRef = 0; private int nextFilterCombination = 0; private String parentQName; private String currentQName; private boolean populateCore = true; public FlexHandler(Vector names, Vector factors, MetadataStore store, boolean populateCore) { this.names = names; this.factors = factors; this.store = store; this.populateCore = populateCore; } public void characters(char[] ch, int start, int length) { String value = new String(ch, start, length); if (currentQName.equals("PlateName")) { store.setPlateName(value, nextPlate - 1); addGlobalMeta("Plate " + (nextPlate - 1) + " Name", value); } else if (parentQName.equals("Plate")) { addGlobalMeta("Plate " + (nextPlate - 1) + " " + currentQName, value); } else if (parentQName.equals("WellShape")) { addGlobalMeta("Plate " + (nextPlate - 1) + " WellShape " + currentQName, value); } else if (currentQName.equals("Wavelength")) { store.setLaserWavelength(new Integer(value), 0, nextLaser); addGlobalMeta("Laser " + nextLaser + " Wavelength", value); } else if (currentQName.equals("Magnification")) { store.setObjectiveCalibratedMagnification(new Float(value), 0, nextObjective); } else if (currentQName.equals("NumAperture")) { store.setObjectiveLensNA(new Float(value), 0, nextObjective); } else if (currentQName.equals("Immersion")) { store.setObjectiveImmersion(value, 0, nextObjective); } else if (currentQName.equals("OffsetX") || currentQName.equals("OffsetY")) { addGlobalMeta("Sublayout " + (nextSublayout - 1) + " Field " + (nextField - 1) + " " + currentQName, value); Float offset = new Float(value); if (currentQName.equals("OffsetX")) xPositions.add(offset); else yPositions.add(offset); } else if (currentQName.equals("OffsetZ")) { addGlobalMeta("Stack " + (nextStack - 1) + " Plane " + (nextPlane - 1) + " OffsetZ", value); } else if (currentQName.equals("Power")) { addGlobalMeta("LightSourceCombination " + (nextLightSourceCombination - 1) + " LightSourceRef " + (nextLightSourceRef - 1) + " Power", value); } else if (parentQName.equals("Image")) { addGlobalMeta("Image " + (nextImage - 1) + " " + currentQName, value); if (currentQName.equals("DateTime") && nextImage == 1) { store.setImageCreationDate(value, 0); } else if (currentQName.equals("CameraBinningX")) { binX = Integer.parseInt(value); } else if (currentQName.equals("CameraBinningY")) { binY = Integer.parseInt(value); } else if (currentQName.equals("LightSourceCombinationRef")) { if (!channelNames.contains(value)) channelNames.add(value); } } else if (parentQName.equals("ImageResolutionX")) { store.setDimensionsPhysicalSizeX(new Float(value), nextImage - 1, 0); } else if (parentQName.equals("ImageResolutionY")) { store.setDimensionsPhysicalSizeY(new Float(value), nextImage - 1, 0); } else if (parentQName.equals("Well")) { addGlobalMeta("Well " + (nextWell - 1) + " " + currentQName, value); } } public void startElement(String uri, String localName, String qName, Attributes attributes) { currentQName = qName; if (qName.equals("Array")) { int len = attributes.getLength(); for (int i=0; i<len; i++, nextArrayImage++) { String name = attributes.getQName(i); if (name.equals("Name")) { names.add(attributes.getValue(i)); //if (nextArrayImage == 0) { // store.setImageName(attributes.getValue(i), 0); } else if (name.equals("Factor")) factors.add(attributes.getValue(i)); //else if (name.equals("Description") && nextArrayImage == 0) { // store.setImageDescription(attributes.getValue(i), 0); } } else if (qName.equals("LightSource")) { parentQName = qName; String id = attributes.getValue("ID"); String type = attributes.getValue("LightSourceType"); addGlobalMeta("LightSource " + nextLightSource + " ID", id); addGlobalMeta("LightSource " + nextLightSource + " Type", type); if (type.equals("Laser")) nextLaser++; nextLightSource++; } else if (qName.equals("Slider")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Slider " + nextSlider + " " + attributes.getQName(i), attributes.getValue(i)); } nextSlider++; } else if (qName.equals("Filter")) { for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Filter " + nextFilter + " " + attributes.getQName(i), attributes.getValue(i)); } nextFilter++; } else if (qName.equals("Camera")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Camera " + nextCamera + " " + attributes.getQName(i), attributes.getValue(i)); } nextCamera++; } else if (qName.startsWith("PixelSize") && parentQName.equals("Camera")) { for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Camera " + (nextCamera - 1) + " " + qName + " " + attributes.getQName(i), attributes.getValue(i)); } } else if (qName.equals("Objective")) { parentQName = qName; nextObjective++; // link Objective to Image using ObjectiveSettings store.setObjectiveID("Objective:" + nextObjective, 0, 0); store.setObjectiveSettingsObjective("Objective:" + nextObjective, 0); store.setObjectiveCorrection("Unknown", 0, 0); } else if (qName.equals("Sublayout")) { parentQName = qName; nextField = 0; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Sublayout " + nextSublayout + " " + attributes.getQName(i), attributes.getValue(i)); } nextSublayout++; } else if (qName.equals("Field")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Sublayout " + (nextSublayout - 1) + " Field " + nextField + " " + attributes.getQName(i), attributes.getValue(i)); } nextField++; int fieldNo = Integer.parseInt(attributes.getValue("No")); if (fieldNo > fieldCount) fieldCount++; } else if (qName.equals("Stack")) { nextPlane = 0; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Stack " + nextStack + " " + attributes.getQName(i), attributes.getValue(i)); } nextStack++; } else if (qName.equals("Plane")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Stack " + (nextStack - 1) + " Plane " + nextPlane + " " + attributes.getQName(i), attributes.getValue(i)); } nextPlane++; int planeNo = Integer.parseInt(attributes.getValue("No")); if (planeNo > getSizeZ() && populateCore) core[0].sizeZ++; } else if (qName.equals("Kinetic")) { for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Kinetic " + nextKinetic + " " + attributes.getQName(i), attributes.getValue(i)); } nextKinetic++; } else if (qName.equals("Dispensing")) { for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Dispensing " + nextDispensing + " " + attributes.getQName(i), attributes.getValue(i)); } nextDispensing++; } else if (qName.equals("LightSourceCombination")) { nextLightSourceRef = 0; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("LightSourceCombination " + nextLightSourceCombination + " " + attributes.getQName(i), attributes.getValue(i)); } nextLightSourceCombination++; } else if (qName.equals("LightSourceRef")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("LightSourceCombination " + (nextLightSourceCombination - 1) + " LightSourceRef " + nextLightSourceRef + " " + attributes.getQName(i), attributes.getValue(i)); } nextLightSourceRef++; } else if (qName.equals("FilterCombination")) { parentQName = qName; nextSliderRef = 0; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("FilterCombination " + nextFilterCombination + " " + attributes.getQName(i), attributes.getValue(i)); } nextFilterCombination++; } else if (qName.equals("SliderRef")) { for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("FilterCombination " + (nextFilterCombination - 1) + " SliderRef " + nextSliderRef + " " + attributes.getQName(i), attributes.getValue(i)); } nextSliderRef++; } else if (qName.equals("Image")) { parentQName = qName; for (int i=0; i<attributes.getLength(); i++) { addGlobalMeta("Image " + nextImage + " " + attributes.getQName(i), attributes.getValue(i)); } nextImage++; //Implemented for FLEX v1.7 and below String x = attributes.getValue("CameraBinningX"); String y = attributes.getValue("CameraBinningY"); if (x != null) binX = Integer.parseInt(x); if (y != null) binY = Integer.parseInt(y); } else if (qName.equals("Plate") || qName.equals("WellShape") || qName.equals("Well")) { parentQName = qName; if (qName.equals("Plate")) { nextPlate++; plateCount++; } else if (qName.equals("Well")) { nextWell++; wellCount++; } } else if (qName.equals("WellCoordinate")) { int ndx = nextWell - 1; addGlobalMeta("Well" + ndx + " Row", attributes.getValue("Row")); addGlobalMeta("Well" + ndx + " Col", attributes.getValue("Col")); //store.setWellRow(new Integer(attributes.getValue("Row")), 0, ndx); //store.setWellColumn(new Integer(attributes.getValue("Col")), 0, ndx); } else if (qName.equals("Status")) { addGlobalMeta("Status", attributes.getValue("StatusString")); } else if(qName.equals("ImageResolutionX")) { parentQName = qName; //TODO: definition of the dimension type and unit Where to store? for (int i=0; i<attributes.getLength(); i++) { //addGlobalMeta("Image " + nextImage + " " + attributes.getQName(i), attributes.getValue(i)); } } else if(qName.equals("ImageResolutionY")) { parentQName = qName; //TODO: definition of the dimension type and unit Where to store? for (int i=0; i<attributes.getLength(); i++) { //addGlobalMeta("Image " + nextImage + " " + attributes.getQName(i),attributes.getValue(i)); } } } } }
package coatapp.coat; import android.os.AsyncTask; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class ForecastRequestTask extends AsyncTask<String, Void, String> { private static String getForecastRequest(String urlToRead) throws Exception { StringBuilder result = new StringBuilder(); URL url = new URL(urlToRead); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { result.append(line); } rd.close(); return result.toString(); } @Override protected String doInBackground(String... params) { String forecastRequestResponse = ""; try { forecastRequestResponse = getForecastRequest(params[0]); } catch (Exception e) { e.printStackTrace(); } return forecastRequestResponse; } @Override protected void onPostExecute(String message) { //process message } }
package com.Ryan.Calculator; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import java.math.BigInteger; public class MainActivity extends Activity { public Complex currentValue=Complex.ZERO; /** Called when the activity is first created. */ @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) { getActionBar().hide(); if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.ICE_CREAM_SANDWICH) findViewById(R.id.mainLayout).setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE); } setZero(); } public Complex parseComplex(String num) { if (num==null || num.indexOf("Error", 0)==0 || num.indexOf("ERROR", 0)==0) return Complex.ZERO; if ("Not prime".equals(num) || "Not prime or composite".equals(num) || "Not Gaussian prime".equals(num)) return Complex.ZERO; if ("Prime".equals(num) || "Gaussian prime".equals(num)) return Complex.ONE; if (num.charAt(num.length()-1)=='\u03C0') { if (num.length()==1) return Complex.PI; else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation return Complex.negate(Complex.PI); // Return negative pi return Complex.multiply(parseComplex(num.substring(0, num.length()-1)), Complex.PI); } if (num.charAt(num.length()-1)=='e') { if (num.length()==1) return Complex.E; else if (num.length()==2 && num.charAt(0)=='-') // If the string is two long and the first character is a negation return Complex.negate(Complex.E); // Return negative e return Complex.multiply(parseComplex(num.substring(0, num.length()-1)), Complex.E); } try { return Complex.parseString(num); } catch (NumberFormatException e) { setText("ERROR: Invalid number"); View v=findViewById(R.id.mainCalculateButton); v.setOnClickListener(null); // Cancel existing computation v.setVisibility(View.GONE); // Remove the button return Complex.ERROR; } } public String inIntTermsOfPi(double num) { if (num==0) return "0"; double tmp=num/Math.PI; int n=(int)tmp; if (n==tmp) { if (n==-1) // If it is a negative, but otherwise 1 return "-\u03C0"; // Return negative pi return (n==1 ? "" : Integer.toString(n))+"\u03C0"; } else return Double.toString(num); } public String inIntTermsOfPi(Complex num) { if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i" return "0"; if (num.isReal()) return inIntTermsOfPi(num.real); if (num.isImaginary()) { if (num.imaginary==1) return "i"; else if (num.imaginary==-1) return "-i"; return inIntTermsOfPi(num.imaginary) + 'i'; } String out=inIntTermsOfPi(num.real); if (num.imaginary>0) out+="+"; out+=inIntTermsOfPi(num.imaginary)+'i'; return out; } public String inIntTermsOfE(double num) { if (num==0) return "0"; double tmp=num/Math.E; int n=(int)tmp; if (n==tmp) { if (n==-1) // If it is a negative, but otherwise 1 return "-e"; // Return negative e return (n==1 ? "" : Integer.toString((int)tmp))+"e"; } else return Double.toString(num); } public String inIntTermsOfE(Complex num) { if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i" return "0"; if (num.isReal()) return inIntTermsOfE(num.real); if (num.isImaginary()) { if (num.imaginary==1) return "i"; else if (num.imaginary==-1) return "-i"; return inIntTermsOfE(num.imaginary) + 'i'; } String out=inIntTermsOfE(num.real); if (num.imaginary>0) out+="+"; out+=inIntTermsOfE(num.imaginary)+'i'; return out; } public String inIntTermsOfAny(double num) { if (Double.isNaN(num)) // "Last-resort" check return "ERROR: Nonreal or non-numeric result."; // Trap NaN and return a generic error for it. // Because of that check, we can guarantee that NaN's will not be floating around for more than one expression. String out=inIntTermsOfPi(num); if (!out.equals(Double.toString(num))) return out; else return inIntTermsOfE(num); } public String inIntTermsOfAny(Complex num) { if (num.equals(Complex.ZERO)) // Special case: Prevents "0+0i" return "0"; if (num.isReal()) return inIntTermsOfAny(num.real); if (num.isImaginary()) { if (num.imaginary==1) return "i"; else if (num.imaginary==-1) return "-i"; return inIntTermsOfAny(num.imaginary) + 'i'; } String out=inIntTermsOfAny(num.real); if (num.imaginary>0) out+="+"; out+=inIntTermsOfAny(num.imaginary)+'i'; return out; } public void zero(View v) { setZero(); } public void setZero(EditText ev) { setText("0", ev); } public void setZero() { setZero((EditText) findViewById(R.id.mainTextField)); } public void setText(String n, EditText ev) { ev.setText(n); ev.setSelection(0, n.length()); // Ensure the cursor is at the end } public void setText(String n) { setText(n, (EditText) findViewById(R.id.mainTextField)); } public void terms(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(parseComplex(ev.getText().toString())), ev); } public void decimal(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(Complex.toString(parseComplex(ev.getText().toString())), ev); } public Complex getValue(final EditText ev) // Parses the content of ev into a double. { return parseComplex(ev.getText().toString().trim()); } public void doCalculate(final EditText ev, OnClickListener ocl) // Common code for buttons that use the mainCalculateButton. { doCalculate(ev, ocl, Complex.ZERO); } public void doCalculate(final EditText ev, OnClickListener ocl, Complex n) // Common code for buttons that use the mainCalculateButton, setting the default value to n rather than zero. { setText(inIntTermsOfAny(n), ev); final Button b=(Button)findViewById(R.id.mainCalculateButton); b.setVisibility(View.VISIBLE); b.setOnClickListener(ocl); } public void add(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num = ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(currentValue.addTo(parseComplex(num))), ev); v.setVisibility(View.GONE); } }); } public void subtract(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(currentValue.subtractTo(parseComplex(num))), ev); v.setVisibility(View.GONE); } }); } public void subtract2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(parseComplex(num).subtractTo(currentValue)), ev); v.setVisibility(View.GONE); } }); } public void multiply(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; setText(inIntTermsOfAny(currentValue.multiplyTo(parseComplex(num))), ev); v.setVisibility(View.GONE); } }); } public void divide(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; Complex n=parseComplex(num); if (n.equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(currentValue.divideTo(n)), ev); v.setVisibility(View.GONE); } }, Complex.ONE); } public void divide2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; Complex n=parseComplex(num); if (n.equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(n.divideTo(currentValue)), ev); v.setVisibility(View.GONE); } }, Complex.ONE); } public void remainder(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); if (!Complex.round(currentValue).equals(currentValue)) { setText("Error: Parameter is not an integer: "+ev.getText(), ev); return; } doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; v.setVisibility(View.GONE); Complex tmp=parseComplex(num); if (!Complex.round(tmp).equals(tmp)) setText("Error: Parameter is not an integer: "+num, ev); else if (Complex.round(tmp).equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(Complex.round(currentValue).modulo(Complex.round(tmp))), ev); } }, Complex.ONE); } public void remainder2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=getValue(ev); if (!Complex.round(currentValue).equals(currentValue)) { setText("Error: Parameter is not an integer: "+ev.getText(), ev); return; } doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString().trim(); if ("".equals(num)) return; v.setVisibility(View.GONE); Complex tmp=parseComplex(num); if (!Complex.round(tmp).equals(tmp)) setText("Error: Parameter is not an integer: "+num, ev); else if (Complex.round(currentValue).equals(Complex.ZERO)) setText("Error: Divide by zero."); else setText(inIntTermsOfAny(Complex.round(tmp).modulo(Complex.round(currentValue))), ev); } }, Complex.ONE); } public void e(View v) { setText("e"); } public void pi(View v) { setText("\u03C0"); } public void i(View v) { setText("i"); } public void negate(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.negate(parseComplex(ev.getText().toString()))), ev); } public void sin(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.sin(parseComplex(ev.getText().toString()))), ev); } public void cos(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.cos(parseComplex(ev.getText().toString()))), ev); } public void tan(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.tan(parseComplex(ev.getText().toString()))), ev); } public void arcsin(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.asin(parseComplex(ev.getText().toString()))), ev); } public void arccos(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.acos(parseComplex(ev.getText().toString()))), ev); } public void arctan(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.atan(parseComplex(ev.getText().toString()))), ev); } public void exp(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfE(Complex.exp(parseComplex(ev.getText().toString()))), ev); } public void degrees(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText((Complex.toDegrees(parseComplex(ev.getText().toString()))).toString(), ev); } public void radians(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfPi(Complex.toRadians(parseComplex(ev.getText().toString()))), ev); } public void radians2(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex tmp=parseComplex(ev.getText().toString()); tmp=Complex.divide(tmp, new Complex(180)); setText(Complex.toString(tmp)+'\u03C0', ev); } public void ln(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfE(Complex.ln(parseComplex(ev.getText().toString()))), ev); } public void log(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.log10(parseComplex(ev.getText().toString()))), ev); } public void logb(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num = ev.getText().toString(); if ("".equals(num)) return; setText(inIntTermsOfAny(Complex.log(currentValue, parseComplex(num))), ev); v.setVisibility(View.GONE); } }, new Complex(10)); } public void logb2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev,new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString(); if ("".equals(num)) return; setText(inIntTermsOfAny(Complex.log(parseComplex(num), currentValue)), ev); v.setVisibility(View.GONE); } }, new Complex(10)); } public void round(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(Complex.toString(Complex.round(parseComplex(ev.getText().toString())))); } public void sqrt(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex n=parseComplex(ev.getText().toString()); setText(inIntTermsOfAny(Complex.sqrt(n)), ev); } public void cbrt(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.cbrt(parseComplex(ev.getText().toString()))), ev); } public void ceil(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(Complex.toString(Complex.ceil(parseComplex(ev.getText().toString()))), ev); } public void floor(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(Complex.toString(Complex.floor(parseComplex(ev.getText().toString()))), ev); } public void pow(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num = ev.getText().toString(); if (!"".equals(num)) setText(inIntTermsOfAny(Complex.pow(currentValue, parseComplex(num))), ev); v.setVisibility(View.GONE); } }, currentValue); } public void pow2(View v) { final EditText ev=(EditText)findViewById(R.id.mainTextField); currentValue=parseComplex(ev.getText().toString()); doCalculate(ev, new OnClickListener() { @Override public void onClick(View v) { v.setOnClickListener(null); String num=ev.getText().toString(); if (!"".equals(num)) setText(inIntTermsOfAny(Complex.pow(parseComplex(num), currentValue)), ev); v.setVisibility(View.GONE); } }, currentValue); } public void abs (View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.abs(parseComplex(ev.getText().toString()))), ev); } public void sinh(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.sinh(parseComplex(ev.getText().toString()))), ev); } public void expm(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.expm1(parseComplex(ev.getText().toString()))), ev); } public void cosh(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.cosh(parseComplex(ev.getText().toString()))), ev); } public void tanh(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.tanh(parseComplex(ev.getText().toString()))), ev); } public void lnp(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); setText(inIntTermsOfAny(Complex.ln1p(parseComplex(ev.getText().toString()))), ev); } public void square(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex num=parseComplex(ev.getText().toString()); setText(inIntTermsOfAny(num.square()), ev); } public void cube(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex num=parseComplex(ev.getText().toString()); setText(inIntTermsOfAny(Complex.multiply(num.square(), num)), ev); } public void isPrime(View v) // Standard primality, not Gaussian { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex m=parseComplex(ev.getText().toString()); if (!m.isReal()) { if (!m.isImaginary()) // M is zero setText("Not prime"); else setText("Error: Cannot compute standard is prime for complex numbers"); return; } double num=m.real; int n=(int)Math.floor(num); if (n!=num || n<1 || isDivisible(n,2)) { setText("Not prime"); return; } if (n==1) { setText("Not prime or composite"); return; } for (int i=3; i<=Math.sqrt(n); i+=2) { if (isDivisible(n, i)) { setText("Not prime"); return; } } setText("Prime"); } public void isGaussianPrime(View v) // Computes whether a prime number is a Gaussian prime { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex m=parseComplex(ev.getText().toString()); boolean prime=false; if (Math.floor(m.real)==m.real && Math.floor(m.imaginary)==m.imaginary) { if (m.isReal()) { int n=(int)Math.abs(m.real); if (isDivisible(n-3, 4)) { prime=true; for (int i = 3; i <= Math.sqrt(n); i += 2) { if (isDivisible(n, i)) { prime = false; break; } } } } else if (m.isImaginary()) { int n=(int)Math.abs(m.imaginary); if (isDivisible(n-3, 4)) { prime=true; for (int i=3; i<=Math.sqrt(n); i+=2) { if (isDivisible(n, i)) { prime=false; break; } } } } else { double norm=m.magnitude(); int n=(int) Math.floor(norm); if (n==norm) { if (n!=1 && !isDivisible(n, 2)) { prime=true; for (int i=3; i<=Math.sqrt(n); i+=2) { if (isDivisible(n, i)) { prime=false; break; } } } } } } setText(prime ? "Gaussian prime" : "Not Gaussian prime"); } public boolean isDivisible(int num, int den) { return num%den==0; } public double fastPow(double val, int power) { if (val==2) return fastPow(power).doubleValue(); switch (power) { case 0: return 1; case 1: return val; case 2: return val*val; default: if (power<0) return 1/fastPow(val, -1*power); if (power%2==0) return fastPow(fastPow(val, 2), power>>1); return val*fastPow(val, power-1); } } public BigInteger fastPow(int pow) // 2 as base { return BigInteger.ZERO.flipBit(pow); } public void raise2(View v) { EditText ev=(EditText)findViewById(R.id.mainTextField); Complex num=parseComplex(ev.getText().toString()); if (num.isReal() && Math.round(num.real)==num.real) // Integer power. Use the fastpow() and a BigInteger. setText(fastPow((int)Math.round(num.real)).toString(), ev); else setText(Complex.toString(Complex.pow(2, num)), ev); } }
package com.bnsantos.drawing; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.v4.content.ContextCompat; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.ImageView; import java.util.ArrayList; import java.util.List; public class DrawingView extends ImageView { public static final int PENCIL_MODE = 1; public static final int CIRCLE_MODE = 2; public static final int RECTANGLE_MODE = 3; public static final int ERASER_MODE = 4; private Paint mDrawPaint, mCanvasPaint; private int mPaintColor; private float mStrokeWidth; private Canvas mDrawCanvas; private Bitmap mBackgroundBitmap; private Bitmap mCanvasBitmap; private int mMode = PENCIL_MODE; /* Drawing elements */ private MyPath mCurrentPath; private Circle mCurrentCircle; private Rectangle mCurrentRectangle; private List<Action> mActions; private List<Action> mUndoActions; public DrawingView(Context context, AttributeSet attrs) { super(context, attrs); mPaintColor = ContextCompat.getColor(context, R.color.palette_black); mStrokeWidth = (int) context.getResources().getDimension(R.dimen.m_brush); setupDrawing(); } private void setupDrawing(){ mDrawPaint = new Paint(); mDrawPaint.setColor(mPaintColor); mDrawPaint.setAntiAlias(true); mDrawPaint.setStrokeWidth(mStrokeWidth); mDrawPaint.setStyle(Paint.Style.STROKE); mDrawPaint.setStrokeJoin(Paint.Join.ROUND); mDrawPaint.setStrokeCap(Paint.Cap.ROUND); mActions = new ArrayList<>(); mUndoActions = new ArrayList<>(); mCurrentPath = new MyPath(false, mDrawPaint); mCanvasPaint = new Paint(Paint.DITHER_FLAG); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); mCanvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); mDrawCanvas = new Canvas(mCanvasBitmap); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(mCanvasBitmap, 0, 0, mCanvasPaint); if(mCurrentPath!=null){ canvas.drawPath(mCurrentPath, mDrawPaint); } if(mCurrentCircle!=null){ canvas.drawCircle(mCurrentCircle.centerX, mCurrentCircle.centerY, mCurrentCircle.radius, mDrawPaint); } if(mCurrentRectangle!=null){ canvas.drawRect(mCurrentRectangle.left(), mCurrentRectangle.top(), mCurrentRectangle.right(), mCurrentRectangle.bottom(), mDrawPaint); } } private void recreateCanvasBitmap(){ //TODO case when the image was not loaded in background if(mBackgroundBitmap==null){ mBackgroundBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.RGB_565); mBackgroundBitmap.eraseColor(Color.WHITE); } mCanvasBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); mDrawCanvas = new Canvas(mCanvasBitmap); mDrawCanvas.drawBitmap(mBackgroundBitmap, 0, 0, mCanvasPaint); if(mActions!=null) { for (Action action : mActions) { action.drawAction(mDrawCanvas); } } invalidate(); } @Override public boolean onTouchEvent(MotionEvent event) { float touchX = event.getX(); float touchY = event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: onTouchDown(touchX, touchY); break; case MotionEvent.ACTION_MOVE: onTouchMode(touchX, touchY); break; case MotionEvent.ACTION_UP: onTouchUp(); break; default: return super.onTouchEvent(event); } invalidate(); return true; } private void onTouchDown(float touchX, float touchY) { switch (mMode){ case CIRCLE_MODE: mCurrentCircle = new Circle(touchX, touchY, mDrawPaint); break; case RECTANGLE_MODE: mCurrentRectangle = new Rectangle(touchX, touchY, mDrawPaint); break; default: //PENCIL_MODE if(mMode==ERASER_MODE) { mDrawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); } else { mDrawPaint.setXfermode(null); } mCurrentPath = new MyPath(mMode==ERASER_MODE, mDrawPaint); mCurrentPath.reset(); mCurrentPath.moveTo(touchX, touchY); } } private void onTouchMode(float touchX, float touchY) { switch (mMode){ case CIRCLE_MODE: mCurrentCircle.setRadius(touchX, touchY); break; case RECTANGLE_MODE: mCurrentRectangle.setFinalPoint(touchX, touchY); break; default: //PENCIL_MODE mCurrentPath.lineTo(touchX, touchY); } } private void onTouchUp() { switch (mMode){ case CIRCLE_MODE: mActions.add(mCurrentCircle); mCurrentCircle.drawAction(mDrawCanvas); mCurrentCircle = null; break; case RECTANGLE_MODE: mActions.add(mCurrentRectangle); mCurrentRectangle.drawAction(mDrawCanvas); mCurrentRectangle = null; break; default: //PENCIL_MODE mActions.add(mCurrentPath); mCurrentPath.drawAction(mDrawCanvas); mCurrentPath = null; } } public void setColor(String newColor){ invalidate(); mPaintColor = Color.parseColor(newColor); mDrawPaint.setColor(mPaintColor); } public void setWidth(float width) { mStrokeWidth = width; mDrawPaint.setStrokeWidth(mStrokeWidth); } public void undo(){ if(mActions!=null&&mActions.size()>0){ mUndoActions.add(mActions.remove(mActions.size()-1)); recreateCanvasBitmap(); } } public void clearAll(){ if(mActions!=null&&mActions.size()>0){ mActions.clear(); } if(mUndoActions!=null&&mUndoActions.size()>0){ mUndoActions.clear(); } recreateCanvasBitmap(); } public void redo(){ if(mUndoActions!=null&&mUndoActions.size()>0){ mActions.add(mUndoActions.remove(mUndoActions.size()-1)); recreateCanvasBitmap(); } } @Override public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if(bitmapDrawable.getBitmap() != null) { mBackgroundBitmap = bitmapDrawable.getBitmap(); } } if(!(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0)) { mBackgroundBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel mBackgroundBitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); } } public void setOption(int option){ mMode = option; if(mMode<PENCIL_MODE||mMode>ERASER_MODE){ mMode = PENCIL_MODE; } } private class MyPath extends Path implements Action{ public boolean erase; public Paint actionPaint; public MyPath(boolean erase, Paint paint) { super(); this.erase = erase; this.actionPaint = new Paint(paint); } @Override public void drawAction(Canvas canvas) { if(erase) { mDrawPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); } else { mDrawPaint.setXfermode(null); } canvas.drawPath(this, actionPaint); } } private class Circle implements Action{ public float centerX, centerY; public float startX, startY; public float radius; public Paint actionPaint; public Circle(float x, float y, Paint actionPaint) { this.startX = x; this.startY = y; this.actionPaint = new Paint(actionPaint); } public void setRadius(float currentX, float currentY) { this.radius = (float) Math.sqrt(Math.pow(startX - currentX, 2) + Math.pow(startY- currentY, 2))/2.0f; this.centerX = (this.startX + currentX)/2.0f; this.centerY = (this.startY + currentY)/2.0f; } @Override public void drawAction(Canvas canvas) { canvas.drawCircle(centerX, centerY, radius, actionPaint); } } private class Rectangle implements Action{ public float startX; public float startY; public float endX; public float endY; public Paint actionPaint; public Rectangle(float touchX, float touchY, Paint actionPaint) { startX = touchX; startY = touchY; endX = touchX; endY = touchY; this.actionPaint = new Paint(actionPaint); } public void setFinalPoint(float touchX, float touchY) { endX = touchX; endY = touchY; } public float left(){ return (startX < endX) ? startX : endX; } public float right(){ return (startX < endX) ? endX : startX; } public float top(){ return (startY < endY) ? startY : endY; } public float bottom(){ return (startY < endY) ? endY : startY; } @Override public void drawAction(Canvas canvas) { canvas.drawRect(left(), top(), right(), bottom(), actionPaint); } } private interface Action{ void drawAction(Canvas canvas); } }
package com.example.baard; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.util.Log; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.reflect.Type; import java.util.concurrent.ExecutionException; public class FileController { private static final String FILENAME = "BAARD.sav"; /** * Constructor for FileController */ public FileController() { } /** * Check for internet connection * @param context The Application Context at the time of calling. Use getApplicationContext() * @return Boolean true if Network is available */ private boolean isNetworkAvailable(Context context) { ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); boolean isAvailable = false; if (networkInfo != null && networkInfo.isConnected()) { // Network is present and connected isAvailable = true; } return isAvailable; } /** * Stores the user both locally and server if network is available * @param context The Application Context at the time of calling. Use getApplicationContext() * @param user The user to be stored */ public void saveUser(Context context, User user) { saveUserToFile(context, user); if (isNetworkAvailable(context)) { saveUserToServer(user); } } /** * Load user from server if network is available else from local file * @param context The Application Context at the time of calling. Use getApplicationContext() * @return The user stored */ public User loadUser(Context context, String username) { if (isNetworkAvailable(context)) { User user = loadUserFromServer(username); saveUserToFile(context, user); return user; } return loadUserFromFile(context); } /** * Loads the user stored locally on the device * Taken from lonelytwitter lab exercises * @param context The Application Context at the time of calling. Use getApplicationContext() * @return User stored in the file */ private User loadUserFromFile(Context context) { User user = null; try { FileInputStream fis = context.openFileInput(FILENAME); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); Gson gson = new Gson(); Type UserType = new TypeToken<User>() {}.getType(); user = gson.fromJson(in,UserType); //https://github.com/google/gson/blob/master/UserGuide.md#TOC-Collections-Examples } catch (FileNotFoundException ignored) { } return user; } /** * Saves the specified user to file locally * Taken from lonelytwitter lab exercises * @param context The Application Context at the time of calling. Use getApplicationContext() * @param user User to be stored in the file */ private void saveUserToFile(Context context, User user) { try { FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE); OutputStreamWriter writer = new OutputStreamWriter(fos); Gson gson = new Gson(); gson.toJson(user,writer); writer.flush(); fos.close(); } catch (IOException e) { throw new RuntimeException(); } } /** * Load the user from the server * @return User stored on server */ private User loadUserFromServer(String username) { ElasticSearchController.GetUserTask getUserTask = new ElasticSearchController.GetUserTask(); getUserTask.execute(username); try { return getUserTask.get(); } catch (ExecutionException | InterruptedException e) { } return null; // TODO: deal with this null } /** * Save user to server * @param user The user to be saved */ private void saveUserToServer(User user) { ElasticSearchController.UpdateUserTask updateUserTask = new ElasticSearchController.UpdateUserTask(); updateUserTask.execute(user); } /** * Saves the received requests list of the desired friend * @param context The Application Context at the time of calling. Use getApplicationContext() * @param myUsername String username of the current user * @param friendUsername String username of the friend we're trying to follow * @return boolean true if other user found; false if friend not found. */ public boolean sendFriendRequest(Context context, String myUsername, String friendUsername) { User friend = loadUserFromServer(friendUsername); User me = loadUser(context, myUsername); if (friend != null) { friend.getReceivedRequests().add(me); saveUserToServer(friend); return true; } else { return false; } } }
package com.pr0gramm.app.ui; import android.annotation.SuppressLint; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.MenuItem; import android.view.View; import com.google.common.base.Optional; import com.pr0gramm.app.DialogBuilder; import com.pr0gramm.app.R; import com.pr0gramm.app.Settings; import com.pr0gramm.app.SyncBroadcastReceiver; import com.pr0gramm.app.feed.FeedFilter; import com.pr0gramm.app.feed.FeedProxy; import com.pr0gramm.app.feed.FeedType; import com.pr0gramm.app.services.BookmarkService; import com.pr0gramm.app.services.SingleShotService; import com.pr0gramm.app.services.UserService; import com.pr0gramm.app.ui.dialogs.ErrorDialogFragment; import com.pr0gramm.app.ui.dialogs.UpdateDialogFragment; import com.pr0gramm.app.ui.fragments.DrawerFragment; import com.pr0gramm.app.ui.fragments.FeedFragment; import com.pr0gramm.app.ui.fragments.PostPagerFragment; import org.joda.time.Duration; import org.joda.time.Instant; import org.joda.time.Minutes; import org.joda.time.Seconds; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nullable; import javax.inject.Inject; import roboguice.activity.RoboActionBarActivity; import roboguice.inject.InjectView; import rx.functions.Actions; import static com.google.common.base.MoreObjects.firstNonNull; import static com.pr0gramm.app.ui.dialogs.ErrorDialogFragment.defaultOnError; import static com.pr0gramm.app.ui.fragments.BusyDialogFragment.busyDialog; import static rx.android.observables.AndroidObservable.bindActivity; /** * This is the main class of our pr0gramm app. */ public class MainActivity extends RoboActionBarActivity implements DrawerFragment.OnFeedFilterSelected, FragmentManager.OnBackStackChangedListener, ScrollHideToolbarListener.ToolbarActivity, MainActionHandler { private static final Logger logger = LoggerFactory.getLogger(MainActivity.class); private final Handler handler = new Handler(Looper.getMainLooper()); private final ErrorDialogFragment.OnErrorDialogHandler errorHandler = new ActivityErrorHandler(this); @InjectView(R.id.drawer_layout) private DrawerLayout drawerLayout; @InjectView(R.id.toolbar) private Toolbar toolbar; @Nullable @InjectView(R.id.toolbar_container) private View toolbarContainer; @Inject private UserService userService; @Inject private BookmarkService bookmarkService; @Inject private Settings settings; @Inject private SharedPreferences shared; @Inject private SingleShotService singleShotService; private ActionBarDrawerToggle drawerToggle; private ScrollHideToolbarListener scrollHideToolbarListener; private boolean startedWithIntent; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // use toolbar as action bar setSupportActionBar(toolbar); // and hide it away on scrolling scrollHideToolbarListener = new ScrollHideToolbarListener( firstNonNull(toolbarContainer, toolbar)); // prepare drawer layout drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.app_name, R.string.app_name); drawerLayout.setDrawerListener(drawerToggle); drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); //noinspection ConstantConditions getSupportActionBar().setDisplayHomeAsUpEnabled(true); drawerToggle.syncState(); // listen to fragment changes getSupportFragmentManager().addOnBackStackChangedListener(this); if (savedInstanceState == null) { createDrawerFragment(); Intent intent = getIntent(); if (intent == null || Intent.ACTION_MAIN.equals(intent.getAction())) { // load feed-fragment into view gotoFeedFragment(new FeedFilter(), true); } else { startedWithIntent = true; onNewIntent(intent); } } if (singleShotService.isFirstTimeInVersion("changelog")) { ChangeLogDialog dialog = new ChangeLogDialog(); dialog.show(getSupportFragmentManager(), null); } else { // start the update check. UpdateDialogFragment.checkForUpdates(this, false); } addOriginalContentBookmarkOnce(); if (singleShotService.isFirstTime("mpeg_decoder_hint")) { DialogBuilder.start(this) .content("Wenn du Probleme beim Abspielen von Videos hast, teste die neue Option 'Softwaredekoder' unter Kompatibilität in den Einstellungen! Bitte gib Feedback!") .positive(R.string.okay) .show(); } } /** * Adds a bookmark if there currently are no bookmarks. */ private void addOriginalContentBookmarkOnce() { if (!singleShotService.isFirstTime("add_original_content_bookmarks")) return; bindActivity(this, bookmarkService.get().first()).subscribe(bookmarks -> { if (bookmarks.isEmpty()) { FeedFilter filter = new FeedFilter() .withFeedType(FeedType.PROMOTED) .withTags("original content"); bookmarkService.create(filter); } }, Actions.empty()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); if (!Intent.ACTION_VIEW.equals(intent.getAction())) return; handleUri(intent.getData()); } @Override protected void onStart() { super.onStart(); // trigger updates while the activity is running sendSyncRequest.run(); } @Override protected void onStop() { handler.removeCallbacks(sendSyncRequest); super.onStop(); } @Override protected void onDestroy() { getSupportFragmentManager().removeOnBackStackChangedListener(this); try { super.onDestroy(); } catch (RuntimeException ignored) { } } @Override public void onBackStackChanged() { updateToolbarBackButton(); updateActionbarTitle(); DrawerFragment drawer = getDrawerFragment(); if (drawer != null) { FeedFilter currentFilter = getCurrentFeedFilter(); // show the current item in the drawer drawer.updateCurrentFilters(currentFilter); } } private void updateActionbarTitle() { String title; FeedFilter filter = getCurrentFeedFilter(); if (filter == null) { title = getString(R.string.pr0gramm); } else { title = FeedFilterFormatter.format(this, filter); } setTitle(title); } /** * Returns the current feed filter. Might be null, if no filter could be detected. */ @Nullable private FeedFilter getCurrentFeedFilter() { // get the filter of the visible fragment. FeedFilter currentFilter = null; Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.content); if (fragment != null) { if (fragment instanceof FeedFragment) { currentFilter = ((FeedFragment) fragment).getCurrentFilter(); } if (fragment instanceof PostPagerFragment) { currentFilter = ((PostPagerFragment) fragment).getCurrentFilter(); } } return currentFilter; } private void updateToolbarBackButton() { FragmentManager fm = getSupportFragmentManager(); drawerToggle.setDrawerIndicatorEnabled(fm.getBackStackEntryCount() == 0); drawerToggle.syncState(); } private void createDrawerFragment() { DrawerFragment fragment = new DrawerFragment(); getSupportFragmentManager().beginTransaction() .replace(R.id.left_drawer, fragment) .commit(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (!drawerToggle.isDrawerIndicatorEnabled()) { if (item.getItemId() == android.R.id.home) { getSupportFragmentManager().popBackStack(); return true; } } return drawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawers(); return; } // at the end, go back to the "top" page before stopping everything. if (getSupportFragmentManager().getBackStackEntryCount() == 0 && !startedWithIntent) { FeedFilter filter = getCurrentFeedFilter(); if (filter != null && !isTopFilter(filter)) { gotoFeedFragment(new FeedFilter(), true); return; } } super.onBackPressed(); } private boolean isTopFilter(FeedFilter filter) { return filter.isBasic() && filter.getFeedType() == FeedType.PROMOTED; } @Override protected void onResume() { super.onResume(); ErrorDialogFragment.setGlobalErrorDialogHandler(errorHandler); onBackStackChanged(); } @Override protected void onPause() { ErrorDialogFragment.unsetGlobalErrorDialogHandler(errorHandler); super.onPause(); } @Override public void onPostClicked(FeedProxy feed, int idx) { if (idx < 0 || idx >= feed.getItemCount()) return; Fragment fragment = PostPagerFragment.newInstance(feed, idx); getSupportFragmentManager().beginTransaction() .replace(R.id.content, fragment) .addToBackStack(null) .commitAllowingStateLoss(); } @Override public void onLogoutClicked() { bindActivity(this, userService.logout()) .lift(busyDialog(this)) .subscribe(Actions.empty(), defaultOnError()); } @Override public void onFeedFilterSelectedInNavigation(FeedFilter filter) { gotoFeedFragment(filter, true); drawerLayout.closeDrawers(); } @Override public void onOtherNavigationItemClicked() { drawerLayout.closeDrawers(); } @Override public void onFeedFilterSelected(FeedFilter filter) { gotoFeedFragment(filter, false); } @Override public void pinFeedFilter(FeedFilter filter, String title) { bookmarkService.create(filter, title).subscribe(Actions.empty(), defaultOnError()); drawerLayout.openDrawer(GravityCompat.START); } private void gotoFeedFragment(FeedFilter newFilter, boolean clear) { gotoFeedFragment(newFilter, clear, Optional.<Long>absent()); } private void gotoFeedFragment(FeedFilter newFilter, boolean clear, Optional<Long> start) { if (isFinishing()) return; if (clear) { clearBackStack(); } Fragment fragment = FeedFragment.newInstance(newFilter, start); // and show the fragment @SuppressLint("CommitTransaction") FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction() .replace(R.id.content, fragment); if (!clear) transaction.addToBackStack(null); try { transaction.commit(); } catch (IllegalStateException ignored) { } // trigger a back-stack changed after adding the fragment. new Handler().post(this::onBackStackChanged); } private DrawerFragment getDrawerFragment() { return (DrawerFragment) getSupportFragmentManager() .findFragmentById(R.id.left_drawer); } private void clearBackStack() { getSupportFragmentManager().popBackStackImmediate( null, FragmentManager.POP_BACK_STACK_INCLUSIVE); } @Override public ScrollHideToolbarListener getScrollHideToolbarListener() { return scrollHideToolbarListener; } /** * Handles a uri to something on pr0gramm * * @param uri The uri to handle */ private void handleUri(Uri uri) { Optional<FeedFilterWithStart> result = FeedFilterWithStart.fromUri(uri); if (result.isPresent()) { FeedFilter filter = result.get().getFilter(); Optional<Long> start = result.get().getStart(); boolean clear = getSupportFragmentManager().getBackStackEntryCount() == 0; gotoFeedFragment(filter, clear, start); } else { gotoFeedFragment(new FeedFilter(), true); } } @SuppressWarnings("Convert2Lambda") private final Runnable sendSyncRequest = new Runnable() { private Instant lastUpdate = new Instant(0); @Override public void run() { Instant now = Instant.now(); if (Seconds.secondsBetween(lastUpdate, now).getSeconds() > 45) { Intent intent = new Intent(MainActivity.this, SyncBroadcastReceiver.class); MainActivity.this.sendBroadcast(intent); } // reschedule Duration delay = Minutes.minutes(1).toStandardDuration(); handler.postDelayed(this, delay.getMillis()); // and remember the last update time lastUpdate = now; } }; }
package com.sanchez.fmf.util; import com.sanchez.fmf.model.MarketListItemModel; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Random; public class MarketUtils { public static ArrayList<MarketListItemModel> getExampleMarkets() { ArrayList<MarketListItemModel> mModels = new ArrayList<>(); String alphabet = " 1234567890 abcdefghijklmnopqrstuvwxyz "; Random r = new Random(); DecimalFormat df = new DecimalFormat(" for (int i = 0; i < 50; i++) { double dist = r.nextDouble() * 50; int marketLength = r.nextInt(50) + 1; StringBuilder sb = new StringBuilder(); for(int j = 0; j < marketLength; j++) { sb.append(alphabet.charAt(r.nextInt(alphabet.length()))); } mModels.add(new MarketListItemModel(Integer.toString(i), sb.toString(), Double.parseDouble(df.format(dist)))); } return mModels; } }
package fr.free.nrw.commons.nearby; import android.graphics.Bitmap; import android.net.Uri; import android.support.annotation.DrawableRes; import java.util.HashMap; import java.util.Map; import fr.free.nrw.commons.R; import fr.free.nrw.commons.location.LatLng; public class Place { public final String name; private final Label label; private final String longDescription; private final Uri secondaryImageUrl; public final LatLng location; public Bitmap image; public Bitmap secondaryImage; public String distance; public final Sitelinks siteLinks; public Place(String name, Label label, String longDescription, Uri secondaryImageUrl, LatLng location, Sitelinks siteLinks) { this.name = name; this.label = label; this.longDescription = longDescription; this.secondaryImageUrl = secondaryImageUrl; this.location = location; this.siteLinks = siteLinks; } public Label getLabel() { return label; } public String getLongDescription() { return longDescription; } public void setDistance(String distance) { this.distance = distance; } @Override public boolean equals(Object o) { if (o instanceof Place) { Place that = (Place) o; return this.name.equals(that.name) && this.location.equals(that.location); } else { return false; } } @Override public int hashCode() { return this.name.hashCode() * 31 + this.location.hashCode(); } @Override public String toString() { return String.format("Place(%s@%s)", name, location); } public enum Label { BUILDING("building", R.drawable.round_icon_generic_building), HOUSE("house", R.drawable.round_icon_house), COTTAGE("cottage", R.drawable.round_icon_house), FARMHOUSE("farmhouse", R.drawable.round_icon_house), CHURCH("church", R.drawable.round_icon_church), RAILWAY_STATION("railway station", R.drawable.round_icon_railway_station), GATEHOUSE("gatehouse", R.drawable.round_icon_gatehouse), MILESTONE("milestone", R.drawable.round_icon_milestone), INN("inn", R.drawable.round_icon_house), CITY("city", R.drawable.round_icon_city), SECONDARY_SCHOOL("secondary school", R.drawable.round_icon_school), EDU("edu", R.drawable.round_icon_school), ISLE("isle", R.drawable.round_icon_island), MOUNTAIN("mountain", R.drawable.round_icon_mountain), AIRPORT("airport", R.drawable.round_icon_airport), BRIDGE("bridge", R.drawable.round_icon_bridge), ROAD("road", R.drawable.round_icon_road), FOREST("forest", R.drawable.round_icon_forest), PARK("park", R.drawable.round_icon_park), RIVER("river", R.drawable.round_icon_river), WATERFALL("waterfall", R.drawable.round_icon_waterfall), UNKNOWN("?", R.drawable.round_icon_unknown); private static final Map<String, Label> TEXT_TO_DESCRIPTION = new HashMap<>(Label.values().length); static { for (Label label : values()) { TEXT_TO_DESCRIPTION.put(label.text, label); } } private final String text; @DrawableRes private final int icon; Label(String text, @DrawableRes int icon) { this.text = text; this.icon = icon; } public String getText() { return text; } @DrawableRes public int getIcon() { return icon; } public static Label fromText(String text) { Label label = TEXT_TO_DESCRIPTION.get(text); return label == null ? UNKNOWN : label; } } }
package it.unical.mat.embasp.base; /** represents a generic output for a solver*/ public abstract class Output implements Cloneable { /**Variable in witch results are stored*/ protected String output; public Output(String initial_output) { output = initial_output; } public Output() { output = new String(); } public String getOutput() { return output; } public void setOutput(String output) { this.output = output; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } }
package lic.swifter.box.util; import android.content.Context; public class DisplayUtil { public static int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5); } public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } }
package net.squanchy; import android.app.Application; import android.support.annotation.MainThread; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.core.CrashlyticsCore; import com.google.firebase.database.FirebaseDatabase; import com.twitter.sdk.android.core.TwitterAuthConfig; import com.twitter.sdk.android.core.TwitterCore; import com.twitter.sdk.android.tweetui.TweetUi; import net.danlew.android.joda.JodaTimeAndroid; import net.squanchy.analytics.Analytics; import net.squanchy.fonts.TypefaceManager; import net.squanchy.injection.ApplicationComponent; import io.fabric.sdk.android.Fabric; import timber.log.Timber; public class SquanchyApplication extends Application { private ApplicationComponent applicationComponent; @Override public void onCreate() { super.onCreate(); JodaTimeAndroid.init(this); setupTracking(); FirebaseDatabase.getInstance().setPersistenceEnabled(true); TypefaceManager.init(); } private void setupTracking() { setupFabric(); Analytics analytics = Analytics.from(this); analytics.enableExceptionLogging(); if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } } private void setupFabric() { TwitterAuthConfig authConfig = new TwitterAuthConfig( getString(R.string.api_value_twitter_api_key), getString(R.string.api_value_twitter_secret) ); CrashlyticsCore crashlyticsCore = new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build(); Fabric.with( this, new Crashlytics.Builder().core(crashlyticsCore).build(), new TwitterCore(authConfig), new TweetUi() ); } @MainThread public ApplicationComponent applicationComponent() { if (applicationComponent == null) { applicationComponent = ApplicationComponent.Factory.create(); } return applicationComponent; } }
package tk.djcrazy.libCC98; import android.text.Html; import android.util.Log; import com.google.inject.Inject; import com.google.inject.Singleton; import ch.boye.httpclientandroidlib.ParseException; import ch.boye.httpclientandroidlib.client.ClientProtocolException; import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import tk.djcrazy.libCC98.data.BoardEntity; import tk.djcrazy.libCC98.data.BoardStatus; import tk.djcrazy.libCC98.data.Gender; import tk.djcrazy.libCC98.data.HotTopicEntity; import tk.djcrazy.libCC98.data.InboxInfo; import tk.djcrazy.libCC98.data.LoginType; import tk.djcrazy.libCC98.data.PmInfo; import tk.djcrazy.libCC98.data.PostContentEntity; import tk.djcrazy.libCC98.data.PostEntity; import tk.djcrazy.libCC98.data.SearchResultEntity; import tk.djcrazy.libCC98.data.UserProfileEntity; import tk.djcrazy.libCC98.data.UserStatue; import tk.djcrazy.libCC98.data.UserStatueEntity; import tk.djcrazy.libCC98.exception.NoUserFoundException; import tk.djcrazy.libCC98.exception.ParseContentException; import tk.djcrazy.libCC98.util.DateFormatUtil; import tk.djcrazy.libCC98.util.RegexUtil; import tk.djcrazy.libCC98.util.StringUtil; import static tk.djcrazy.libCC98.CC98ParseRepository.HOT_TOPIC_BOARD_ID_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.HOT_TOPIC_BOARD_NAME_WITH_AUTHOR_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.HOT_TOPIC_CLICK_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.HOT_TOPIC_ID_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.HOT_TOPIC_NAME_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.HOT_TOPIC_POST_TIME_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.HOT_TOPIC_WRAPPER; import static tk.djcrazy.libCC98.CC98ParseRepository.NEW_TOPIC_AUTHOR_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.NEW_TOPIC_BOARD_ID; import static tk.djcrazy.libCC98.CC98ParseRepository.NEW_TOPIC_FACE_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.NEW_TOPIC_ID_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.NEW_TOPIC_TIME; import static tk.djcrazy.libCC98.CC98ParseRepository.NEW_TOPIC_TITLE_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.NEW_TOPIC_TOTAL_POST; import static tk.djcrazy.libCC98.CC98ParseRepository.NEW_TOPIC_WRAPPER_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_CONTENT_GENDER_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_CONTENT_INFO_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_CONTENT_POST_CONTENT_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_CONTENT_POST_FACE_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_CONTENT_POST_TIME_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_CONTENT_POST_TITLE_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_CONTENT_USERNAME_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_CONTENT_USER_AVATAR_LINK_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_CONTENT_WHOLE_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_LIST_LAST_REPLY_AUTHOR_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_LIST_LAST_REPLY_TIME_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_LIST_POST_AUTHOR_NAME_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_LIST_POST_BOARD_ID_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_LIST_POST_ENTITY_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_LIST_POST_ID_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_LIST_POST_NAME_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_LIST_POST_TYPE_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.POST_LIST_REPLY_NUM_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.P_BOARD_ID_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.P_BOARD_LAST_REPLY_AUTHOR_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.P_BOARD_LAST_REPLY_TIME_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.P_BOARD_LAST_REPLY_TOPIC_ID_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.P_BOARD_LAST_REPLY_TOPIC_NAME_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.P_BOARD_NAME_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.P_BOARD_POST_NUMBER_TODAY; import static tk.djcrazy.libCC98.CC98ParseRepository.P_BOARD_SINGLE_BOARD_WRAPPER_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.TODAY_BOARD_ENTITY_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.TODAY_BOARD_ID_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.TODAY_BOARD_NAME_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.TODAY_BOARD_TOPIC_NUM_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.TODAY_POST_NUMBER_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.USER_PROFILE_AVATAR_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.USER_PROFILE_GENERAL_PROFILE_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.USER_PROFILE_ONLINE_INFO_REGEX; import static tk.djcrazy.libCC98.CC98ParseRepository.USER_PROFILE_PERSON_PROFILE_REGEX; import static tk.djcrazy.libCC98.util.DateFormatUtil.convertStringToDateInPostContent; import static tk.djcrazy.libCC98.util.RegexUtil.getMatchedString; import static tk.djcrazy.libCC98.util.RegexUtil.getMatchedStringList; import static tk.djcrazy.libCC98.util.StringUtil.filterHtmlDecode; @Singleton public class NewCC98Parser { private static final String TAG = "CC98ParserImpl"; @Inject private ICC98UrlManager cc98UrlManager; /** * Parse the HTML, and put posts and their poster id in a list of * NameValuePair * * @param html * String (must not be null) * @return A list of the pair of poster id and their posts * @throws tk.djcrazy.libCC98.exception.ParseContentException * @throws java.text.ParseException */ public List<PostContentEntity> parsePostContentList(String html) throws ParseContentException, java.text.ParseException { List<PostContentEntity> list = new ArrayList<PostContentEntity>(); // get some information of the topic List<String> postInfoList = getMatchedStringList(POST_CONTENT_INFO_REGEX, html, 3); PostContentEntity postInfoEntity = new PostContentEntity(); postInfoEntity.setPostTopic(filterHtmlDecode(postInfoList.get(0))); postInfoEntity.setBoardName(Html.fromHtml(postInfoList.get(1)).toString()); postInfoEntity.setTotalPage((int) Math.ceil(Integer.parseInt(postInfoList.get(2)) / 10.0)); list.add(postInfoEntity); // get each reply info List<String> contentHtml = getMatchedStringList(POST_CONTENT_WHOLE_REGEX, html, -1); for (String reply : contentHtml) { PostContentEntity entity = new PostContentEntity(); try { entity.setUserName(Html.fromHtml(getMatchedString(POST_CONTENT_USERNAME_REGEX, reply)) .toString()); entity.setPostContent(getMatchedString(POST_CONTENT_POST_CONTENT_REGEX, reply)); entity.setPostTitle(getMatchedString(POST_CONTENT_POST_TITLE_REGEX, reply)); entity.setPostFace(getMatchedString(POST_CONTENT_POST_FACE_REGEX, reply)); entity.setPostTime(convertStringToDateInPostContent(getMatchedString( POST_CONTENT_POST_TIME_REGEX, reply))); } catch (Exception e) { e.printStackTrace(); } try { String avatarLink = getMatchedString(POST_CONTENT_USER_AVATAR_LINK_REGEX, reply); if (!avatarLink.contains("http: avatarLink = cc98UrlManager.getClientUrl() + avatarLink; } entity.setUserAvatarLink(avatarLink); } catch (ParseContentException e) { entity.setUserAvatarLink("file:///android_asset/pic/no_avatar.jpg"); } { String sex = getMatchedString(POST_CONTENT_GENDER_REGEX, reply); if ("Male".equals(sex)) { entity.setGender(Gender.MALE); } else { entity.setGender(Gender.FEMALE); } } list.add(entity); } return list; } /** * Parse the HTML to obtain posts names and their URL. * * @param html * @return * @throws tk.djcrazy.libCC98.exception.ParseContentException * @throws java.text.ParseException */ public List<PostEntity> parsePostList(String html) throws ParseContentException, java.text.ParseException { List<PostEntity> list = new ArrayList<PostEntity>(); List<String> contentList = getMatchedStringList(POST_LIST_POST_ENTITY_REGEX, html, -1); for (String post : contentList) { PostEntity entity = new PostEntity(); entity.setPostName(Html.fromHtml(getMatchedString(POST_LIST_POST_NAME_REGEX, post)) .toString()); entity.setPostType(getMatchedString(POST_LIST_POST_TYPE_REGEX, post)); entity.setReplyNumber(getMatchedString(POST_LIST_REPLY_NUM_REGEX, post).replaceAll( "<.*?>", "")); entity.setPostAuthorName(Html.fromHtml( getMatchedString(POST_LIST_POST_AUTHOR_NAME_REGEX, post)).toString()); entity.setLastReplyAuthor(Html.fromHtml( getMatchedString(POST_LIST_LAST_REPLY_AUTHOR_REGEX, post)).toString()); entity.setLastReplyTime(DateFormatUtil.convertStringToDateInPostList(getMatchedString( POST_LIST_LAST_REPLY_TIME_REGEX, post))); entity.setPostId(getMatchedString(POST_LIST_POST_ID_REGEX, post)); entity.setBoardId(getMatchedString(POST_LIST_POST_BOARD_ID_REGEX, post)); list.add(entity); } return list; } /** * * @param html * @return * @throws tk.djcrazy.libCC98.exception.ParseContentException * @throws java.text.ParseException */ public List<BoardEntity> parsePersonalBoardList(String html) throws ParseContentException, java.text.ParseException { List<BoardEntity> nList = new ArrayList<BoardEntity>(); String boardinfo = html; List<String> board = getMatchedStringList(P_BOARD_SINGLE_BOARD_WRAPPER_REGEX, boardinfo, 0); for (String string : board) { BoardEntity entity = new BoardEntity(); entity.setBoardID(getMatchedString(P_BOARD_ID_REGEX, string)); try { entity.setChildBoardNumber(Integer.parseInt(getMatchedString(CC98ParseRepository.P_IS_PARENT_BOARD_REGEX, string))); } catch (ParseContentException e) { entity.setChildBoardNumber(0); } try { entity.setPostNumberToday(Integer.parseInt(getMatchedString( P_BOARD_POST_NUMBER_TODAY, string))); entity.setBoardName(Html.fromHtml(getMatchedString(P_BOARD_NAME_REGEX, string)) .toString()); entity.setLastReplyBoardId(getMatchedString(CC98ParseRepository.P_BOARD_LAST_REPLY_BOARDID_REGEX, string)); entity.setLastReplyAuthor(Html.fromHtml( getMatchedString(P_BOARD_LAST_REPLY_AUTHOR_REGEX, string)).toString()); entity.setLastReplyTime(DateFormatUtil.convertStrToDateInPBoard(getMatchedString( P_BOARD_LAST_REPLY_TIME_REGEX, string))); entity.setLastReplyTopicID(getMatchedString(P_BOARD_LAST_REPLY_TOPIC_ID_REGEX, string)); entity.setLastReplyTopicName(Html.fromHtml( getMatchedString(P_BOARD_LAST_REPLY_TOPIC_NAME_REGEX, string)).toString()); } catch (Exception e) { e.printStackTrace(); } nList.add(entity); } return nList; } /** * * @param html * @return * @throws tk.djcrazy.libCC98.exception.ParseContentException * @throws java.text.ParseException */ public List<BoardEntity> parseBoardList(String html) throws ParseContentException, java.text.ParseException { List<BoardEntity> nList = new ArrayList<BoardEntity>(); String boardinfo = html; List<String> board = getMatchedStringList(CC98ParseRepository.LIST_BOARD_SINGLE_BOARD_WRAPPER_REGEX, boardinfo, 0); for (String string : board) { BoardEntity entity = new BoardEntity(); entity.setBoardID(getMatchedString(CC98ParseRepository.LIST_BOARD_ID_REGEX, string)); try { entity.setChildBoardNumber(Integer.parseInt(getMatchedString(CC98ParseRepository.LIST_IS_PARENT_BOARD_REGEX, string))); } catch (ParseContentException e) { entity.setChildBoardNumber(0); } try { entity.setBoardName(Html.fromHtml(getMatchedString(CC98ParseRepository.LIST_BOARD_NAME_REGEX, string).replace("<.*?>", "")) .toString()); entity.setLastReplyAuthor(Html.fromHtml( getMatchedString(CC98ParseRepository.LIST_BOARD_LAST_REPLY_AUTHOR_REGEX, string)).toString()); entity.setLastReplyBoardId(getMatchedString(CC98ParseRepository.LIST_BOARD_LAST_REPLY_BOARDID_REGEX, string)); entity.setLastReplyTime(DateFormatUtil.convertStrToDateInPBoard(getMatchedString( CC98ParseRepository.LIST_BOARD_LAST_REPLY_TIME_REGEX, string))); entity.setLastReplyTopicID(getMatchedString(CC98ParseRepository.LIST_BOARD_LAST_REPLY_TOPIC_ID_REGEX, string)); entity.setLastReplyTopicName(Html.fromHtml( getMatchedString(CC98ParseRepository.LIST_BOARD_LAST_REPLY_TOPIC_NAME_REGEX, string)).toString()); entity.setPostNumberToday(Integer.parseInt(getMatchedString( CC98ParseRepository.LIST_BOARD_POST_NUMBER_TODAY, string))); } catch (Exception e) { Log.e(NewCC98Parser.class.getSimpleName(), "parseBoardList failed", e); } nList.add(entity); } return nList; } public String parseUserAvatar(String html, LoginType loginType, String proxyHost) { try { String url = getMatchedString(USER_PROFILE_AVATAR_REGEX, html); if (!url.startsWith("http") && !url.startsWith("ftp")) { url = cc98UrlManager.getClientUrl(loginType, proxyHost) + url; } return url; } catch (Exception e) { return cc98UrlManager.getClientUrl(loginType, proxyHost) + "PresetFace/male_1.gif"; } } /** * @author DJ * @param html * @return * @throws tk.djcrazy.libCC98.exception.ParseContentException */ public UserProfileEntity parseUserProfile(String html) throws ParseContentException { UserProfileEntity entity = new UserProfileEntity(); // avatar link { String url = getMatchedString(USER_PROFILE_AVATAR_REGEX, html); if (!url.startsWith("http") && !url.startsWith("ftp")) { url = cc98UrlManager.getClientUrl() + url; } entity.setUserAvatarLink(url); } // general profile { String info = getMatchedString(USER_PROFILE_GENERAL_PROFILE_REGEX, html); String[] details = info.split("<br>"); entity.setUserNickName(details[0]); entity.setUserLevel(details[1]); entity.setUserGroup(details[2]); entity.setGoodPosts(details[3]); entity.setTotalPosts(details[4]); entity.setUserPrestige(details[5]); entity.setRegisterTime(details[6]); entity.setLoginTimes(details[7]); entity.setDeletedPosts(details[8]); entity.setDeletedRatio(details[9]); entity.setLastLoginTime(details[10]); } // personal profile try { String info = getMatchedString(USER_PROFILE_PERSON_PROFILE_REGEX, html); String[] details = info.split("<br>"); details[1] = details[1].replaceAll("<.*?>", ""); details[2] = details[2].replaceAll("<.*?>", ""); details[3] = details[3].replaceAll("<.*?>", ""); details[4] = details[4].replaceAll("<.*?>", ""); details[5] = details[5].replaceAll("&nbsp;", " "); details[5] = details[5].replaceAll("<.*?>", ""); details[6] = details[6].replaceAll("<.*?>", ""); Pattern pattern = Pattern.compile("(?<=alt=).*?", Pattern.DOTALL); Matcher matcher = pattern.matcher(details[2]); if (matcher.find()) { details[2] = matcher.group(); } entity.setUserGender(details[0]); entity.setUserBirthday(details[1]); entity.setUserConstellation(details[2]); entity.setUserEmail(details[3]); entity.setUserQQ(details[4]); entity.setUserMSN(details[5]); entity.setUserPage(details[6]); } catch (Exception e) { e.printStackTrace(); } // bbs master info { String string = getMatchedString(USER_PROFILE_AVATAR_REGEX, html); string = string.replaceAll("\t|\n|\r|<br>|&nbsp;|<.*?>| ", ""); entity.setBbsMasterInfo(string); } // online status entity.setOnlineTime(getMatchedString(USER_PROFILE_ONLINE_INFO_REGEX, html)); return entity; } public List<HotTopicEntity> parseHotTopicList(String page) throws ParseContentException { List<HotTopicEntity> list = new ArrayList<HotTopicEntity>(); List<String> topicList = getMatchedStringList(HOT_TOPIC_WRAPPER, page, -1); for (String topic : topicList) { HotTopicEntity entity = new HotTopicEntity(); entity.setTopicName(filterHtmlDecode(getMatchedString(HOT_TOPIC_NAME_REGEX, topic))); entity.setPostId(getMatchedString(HOT_TOPIC_ID_REGEX, topic)); entity.setPostTime(getMatchedString(HOT_TOPIC_POST_TIME_REGEX, topic)); entity.setBoardId(getMatchedString(HOT_TOPIC_BOARD_ID_REGEX, topic)); // click number { List<String> numList = getMatchedStringList(HOT_TOPIC_CLICK_REGEX, topic, 3); entity.setFocusNumber(Integer.parseInt(numList.get(0))); entity.setReplyNumber(Integer.parseInt(numList.get(1))); entity.setClickNumber(Integer.parseInt(numList.get(2))); } // board name, author { List<String> bList = getMatchedStringList(HOT_TOPIC_BOARD_NAME_WITH_AUTHOR_REGEX, topic, -1); entity.setBoardName(bList.get(0)); if (bList.size() < 2) { entity.setPostAuthor(""); } else { entity.setPostAuthor(bList.get(1)); } } list.add(entity); } return list; } /** * Store information of the msgs in a list * * @author zsy * @param html * The html of the inbox page * @return A list of PmInfo */ public InboxInfo parsePmList(String html) { InboxInfo info = new InboxInfo(); InboxInfo info = new InboxInfo(); String regexString = ""; if (html.indexOf("") > 0) { regexString = "(?<=<img src=pic/m_)\\w+(?=\\.gif>)|(?<=target=_blank>)[^:]+(?=</a>)|(?<=\\s>).*?(?=</a></td>)|" + "(?<=<a href=\"messanger.asp\\?action=(read|outread)&id=)\\d+?(?=&sender)|(?<=target=_blank>).*?(?=</a></td>)"; } else { regexString = "(?<=<img src=pic/m_)\\w+(?=\\.gif>)|(?<=target=\"_blank\">)[^:]+(?=</a>)|(?<=\\s>).*?(?=</a></td>)|" + "(?<=<a href=\"messanger.asp\\?action=(read|outread)&id=)\\d+?(?=&sender)|(?<=target=_blank>).*?(?=</a></td>)|" + "(?<=gray;\">).+(?=</span>)"; } html = html.substring(html.indexOf("</span>")); List<PmInfo> pmList = new ArrayList<PmInfo>(); Matcher m1 = Pattern.compile(regexString).matcher(html); getInboxList(pmList, m1); // Get total page number Pattern p2 = Pattern.compile("(?<=/<b>)\\d+(?=</b>)"); Matcher m2 = p2.matcher(html); if (m2.find()) { // Get the total page number of the pm inbox. info.setTotalInPage(Integer.parseInt(m2.group())); } // Get total pm count Pattern p3 = Pattern.compile("(?<=<b>)\\d+(?=</b></td>)"); Matcher m3 = p3.matcher(html); if (m3.find()) { info.setTotalPmIn(Integer.parseInt(m3.group())); } info.setPmInfos(pmList); return info; } /** * Get a list of PmInfo. * * @author zsy * * @param pmList * @param m1 */ private void getInboxList(List<PmInfo> pmList, Matcher m1) { while (m1.find()) { String isNewString = m1.group(); boolean isNew = isNewString.equals("olds") || isNewString.equals("issend_1") ? false : true; m1.find(); String sender = m1.group(); m1.find(); String topic = m1.group(); m1.find(); int pmId = Integer.parseInt(m1.group()); m1.find(); String time = m1.group(); pmList.add(new PmInfo.Builder(pmId).fromWho(sender).topicTitle(topic).sendTime(time) .newTopic(isNew).userAvatar("").build()); } } /* * (non-Javadoc) * * @see tk.djcrazy.libCC98.ICC98Parser#parseQueryResult(java.lang.String) */ public List<SearchResultEntity> parseQueryResult(String html) throws ParseContentException, java.text.ParseException { List<SearchResultEntity> list = new ArrayList<SearchResultEntity>(); String totalPost; try { totalPost = getMatchedString(NEW_TOPIC_TOTAL_POST, html); } catch (Exception e) { e.printStackTrace(); totalPost = "0"; return list; } List<String> entityList = getMatchedStringList(NEW_TOPIC_WRAPPER_REGEX, html, -1); for (int i = 0; i < entityList.size(); i++) { String string = entityList.get(i); SearchResultEntity entity = new SearchResultEntity(); entity.setTitle(StringUtil.filterHtmlDecode(getMatchedString(NEW_TOPIC_TITLE_REGEX, string))); try { entity.setAuthorName(getMatchedString(NEW_TOPIC_AUTHOR_REGEX, string)); } catch (Exception e) { entity.setAuthorName(""); } entity.setBoardId(getMatchedString(NEW_TOPIC_BOARD_ID, string)); entity.setFaceId(getMatchedString(NEW_TOPIC_FACE_REGEX, string)); entity.setPostTime(DateFormatUtil.convertStringToDateInQueryResult(getMatchedString( NEW_TOPIC_TIME, string).replaceAll("&nbsp;", " ").replaceAll("\n|\t|\r", " ") .trim())); entity.setTotalResult(totalPost); entity.setPostId(getMatchedString(NEW_TOPIC_ID_REGEX, string)); list.add(entity); } return list; } public List<UserStatueEntity> parseUserFriendList(String html) throws ParseException, IOException, ParseContentException { if (html == null) { throw new IllegalArgumentException("Null pointer!"); } List<UserStatueEntity> list = new ArrayList<UserStatueEntity>(); Pattern userRegexPattern = Pattern.compile("&nbsp;<a href=dispuser\\.asp\\?name=.*?<br>", Pattern.DOTALL); Pattern userNamePattern = Pattern.compile("(?<= >).*?(?=</a>)", Pattern.DOTALL); Pattern userStatuePattern = Pattern.compile("(?<=\\[).*?(?=\\])", Pattern.DOTALL); Matcher matcher = userRegexPattern.matcher(html); while (matcher.find()) { String mString = matcher.group(); UserStatueEntity mEntity = new UserStatueEntity(); Matcher mMatcher = userNamePattern.matcher(mString); if (mMatcher.find()) { mEntity.setUserName(mMatcher.group()); } mMatcher = userStatuePattern.matcher(mString); if (mMatcher.find()) { String string = mMatcher.group().replaceAll("<.*?>", ""); if (string.contains("")) { mEntity.setStatue(UserStatue.OFF_LINE); } else { mEntity.setStatue(UserStatue.ON_LINE); mEntity.setOnlineTime(string); } } list.add(mEntity); } return list; } public List<BoardStatus> parseTodayBoardList(String content) throws ParseContentException { int postNum = Integer.parseInt(getMatchedString(TODAY_POST_NUMBER_REGEX, content)); List<BoardStatus> list = new ArrayList<BoardStatus>(); List<String> contentList = getMatchedStringList(TODAY_BOARD_ENTITY_REGEX, content, -1); for (int i = 0; i < contentList.size(); i++) { String string = contentList.get(i); BoardStatus status = new BoardStatus(); status.setBoardId(getMatchedString(TODAY_BOARD_ID_REGEX, string)); status.setBoardName(getMatchedString(TODAY_BOARD_NAME_REGEX, string)); status.setPostNumberToday(Integer.parseInt(getMatchedString( TODAY_BOARD_TOPIC_NUM_REGEX, string))); status.setTotalPostToday(postNum); status.setRating(i + 1); list.add(status); } return list; } public String parseMsgContent(String html) { Pattern p = Pattern.compile("(?<=<span id=\"ubbcode1\" >).*?(?=</span>)"); Matcher m = p.matcher(html); if (!m.find()) { throw new IllegalStateException("can not get msg content"); } return m.group(); } public String parseUploadPicture(String html) throws ParseContentException { return RegexUtil.getMatchedString( CC98ParseRepository.UPLOAD_PIC_ADDRESS_REGEX, html) .replace(",1", ""); } }
package com.galvarez.ttw.screens; import static java.lang.Math.max; import static java.lang.String.format; import java.util.Map; import java.util.Map.Entry; import com.artemis.Entity; import com.artemis.World; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.galvarez.ttw.ThingsThatWereGame; import com.galvarez.ttw.model.DiscoverySystem; import com.galvarez.ttw.model.Faction; import com.galvarez.ttw.model.components.Discoveries; import com.galvarez.ttw.model.components.InfluenceSource; import com.galvarez.ttw.model.components.Research; import com.galvarez.ttw.model.data.Discovery; import com.galvarez.ttw.model.map.Terrain; import com.galvarez.ttw.rendering.ui.FramedMenu; import com.galvarez.ttw.screens.overworld.OverworldScreen; /** * This screen appears when user tries to pause or escape from the main game * screen. * * @author Guillaume Alvarez */ public final class DiscoveryMenuScreen extends AbstractPausedScreen<OverworldScreen> { private final FramedMenu topMenu, lastDiscovery, terrains, discoveryChoices; private final Discoveries empire; private final InfluenceSource source; private final DiscoverySystem discoverySystem; private final Entity entity; public DiscoveryMenuScreen(ThingsThatWereGame game, World world, SpriteBatch batch, OverworldScreen gameScreen, Entity empire, DiscoverySystem discoverySystem) { super(game, world, batch, gameScreen); this.entity = empire; this.empire = empire.getComponent(Discoveries.class); this.source = empire.getComponent(InfluenceSource.class); this.discoverySystem = discoverySystem; topMenu = new FramedMenu(skin, 800, 600); lastDiscovery = new FramedMenu(skin, 800, 600); terrains = new FramedMenu(skin, 800, 600); discoveryChoices = new FramedMenu(skin, 800, 600); } @Override protected void initMenu() { topMenu.clear(); topMenu.addButton("Resume game", this::resumeGame); topMenu.addToStage(stage, 30, stage.getHeight() - 30, false); lastDiscovery.clear(); if (empire.last == null) { lastDiscovery.addLabel("- No last discovery -"); } else { lastDiscovery.addLabel("- Last discovery (effect doubled): " + empire.last.target.name + " -"); lastDiscovery.addLabel("Discovered from " + previousString(empire.last)); lastDiscovery.addLabel("Effects:"); for (String effect : discoverySystem.effectsStrings(empire.last.target)) lastDiscovery.addLabel(" - " + effect); } lastDiscovery.addToStage(stage, 30, topMenu.getY() - 30, false); terrains.clear(); terrains.addLabel("- Terrains influence costs -"); for (Terrain t : Terrain.values()) { Integer mod = source.modifiers.terrainBonus.get(t); int cost = max(1, mod != null ? t.moveCost() - mod : t.moveCost()); terrains.addLabel(format("%s: %d (%s)", t.getDesc(), cost, mod != null && mod != 0 ? -mod : "no modifier")); } terrains.addToStage(stage, 30, lastDiscovery.getY() - 30, false); discoveryChoices.clear(); if (empire.next != null) { discoveryChoices.addLabel("Progress toward new discovery from " + previousString(empire.next) + ": " + empire.next.progress + "% (+" + empire.progressPerTurn + "%/turn)"); } else { Map<Faction, Research> possible = discoverySystem.possibleDiscoveries(entity, empire); if (possible.isEmpty()) { discoveryChoices.addLabel("No discoveries to combine!"); } else { discoveryChoices.addLabel("Which faction do you choose to make new discoveries?"); for (Entry<Faction, Research> next : possible.entrySet()) discoveryChoices.addButton( action(next.getKey()), previousString(next.getValue()) + " (~" + discoverySystem.guessNbTurns(empire, entity, next.getValue().target) + " turns)", new Runnable() { @Override public void run() { empire.next = next.getValue(); resumeGame(); } }, true); } } discoveryChoices.addToStage(stage, 30, terrains.getY() - 30, false); } private static String action(Faction faction) { switch (faction) { case CULTURAL: return "Cultural faction advises to meditate on "; case ECONOMIC: return "Economic faction recommends we pursue profit in "; case MILITARY: return "Military faction commands us to investigate "; default: throw new IllegalStateException("Unknown faction " + faction); } } private static String previousString(Research next) { if (next.previous.isEmpty()) return "our environment"; StringBuilder sb = new StringBuilder(); for (Discovery previous : next.previous) sb.append(previous.name).append(", "); sb.setLength(sb.length() - 2); return sb.toString(); } }
package com.haw.projecthorse.level.mainmenu; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Pixmap.Format; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Stage; import com.badlogic.gdx.scenes.scene2d.ui.Table; import com.badlogic.gdx.scenes.scene2d.ui.TextButton; import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener; import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.haw.projecthorse.gamemanager.GameManagerFactory; import com.haw.projecthorse.gamemanager.settings.SettingsImpl; import com.haw.projecthorse.level.HorseScreen; /** * @author Lars * MainMenu. Shown when game starts * Using a libgdx.stage and tables within to create an ui-layout * */ public class MainMenu implements HorseScreen { private Table table;// = new Table(); private Stage stage; private TextButtonStyle buttonStyle; // Defines style how buttons appear private Texture upTexture; // Loaded into upRegion private Texture downTexture; private TextureRegion upRegion; // Aussehen des buttons wenn nicht gedrckt; private TextureRegion downRegion; // Aussehen des buttons wenn nicht // gedrckt; private BitmapFont buttonFont = new BitmapFont(); // Standard 15pt Arial // Font. (inside // libgdx.jar file) private TextButton buttonCredits; private TextButton buttonSpiel1; private TextButton buttonSpiel2; private TextButton buttonSpiel3; private Viewport viewport; private OrthographicCamera cam; private Batch batch; private int height = SettingsImpl.getInstance().getScreenHeight(); private int width = SettingsImpl.getInstance().getScreenWidth(); public MainMenu() { initCameraAndViewport(); initBatch(); initStage(viewport, batch); initTable(); // Table = Gridlayout initButtons(); // To be called after initTable (adds itself to table) setupEventListeners(); stage.addActor(table); } private void initCameraAndViewport() { cam = new OrthographicCamera(width, height); cam.setToOrtho(false); // Set to Y-Up - Coord system viewport = new FitViewport(width, height, cam); } private void initBatch() { batch = new SpriteBatch(); batch.setProjectionMatrix(cam.combined); } private void initButtons() { // Setup Style: // 1. Load & Set gfx Pixmap pixel = new Pixmap(128, 64, Format.RGBA8888); // Create a pixmap // to use as a // background // texture pixel.setColor(Color.BLUE); pixel.fill(); upTexture = new Texture(pixel, Format.RGBA8888, true); pixel.setColor(Color.CYAN); pixel.fill(); downTexture = new Texture(pixel, Format.RGBA8888, true); pixel.dispose(); //No longer needed upRegion = new TextureRegion(upTexture, 128, 64); downRegion = new TextureRegion(downTexture, 128, 64); buttonStyle = new TextButtonStyle(); buttonStyle.up = new TextureRegionDrawable(upRegion); buttonStyle.down = new TextureRegionDrawable(downRegion); buttonStyle.font = buttonFont; buttonSpiel1 = new TextButton("Spielstand 1", buttonStyle); buttonSpiel2 = new TextButton("Spielstand 2", buttonStyle); buttonSpiel3 = new TextButton("Spielstand 3", buttonStyle); buttonCredits = new TextButton("Credits", buttonStyle); // actor.addListener(new ChangeListener() { // public void changed (ChangeEvent event, Actor actor) { // System.out.println("Changed!"); table.add(buttonSpiel1); table.add(buttonSpiel2); table.add(buttonSpiel3); table.add(buttonCredits); } private void loadSavegame(int id){ //TODO add loading method System.out.println("Loading Game " + id +" - loadSavegame not yet implemented"); } private void loadCredits(){ //TODO: Implement Creditscreen System.out.println("CreditScreen not yet implemented - Todo"); } private void setupEventListeners(){ buttonSpiel1.addListener(new ChangeListener(){ public void changed(ChangeEvent event, Actor actor) { GameManagerFactory.getInstance().navigateToWorldMap(); System.out.println("buttonSpiel1 pressed"); loadSavegame(1); } }); buttonSpiel2.addListener(new ChangeListener(){ public void changed(ChangeEvent event, Actor actor) { System.out.println("buttonSpiel2 pressed"); loadSavegame(2); GameManagerFactory.getInstance().navigateToLevel("4"); } }); buttonSpiel3.addListener(new ChangeListener(){ public void changed(ChangeEvent event, Actor actor) { System.out.println("buttonSpiel3 pressed"); loadSavegame(3); GameManagerFactory.getInstance().navigateToWorldMap(); } }); buttonCredits.addListener(new ChangeListener(){ public void changed(ChangeEvent event, Actor actor) { System.out.println("buttonCredits pressed"); loadCredits(); } }); } private void initStage(Viewport viewport, Batch batch) { stage = new Stage(viewport, batch); Gdx.input.setInputProcessor(stage); // Now Stage is processing inputs } private void initTable() { table = new Table(); table.debug(); // Show debug lines table.setFillParent(true); } @Override public void resize(int width, int height) { stage.getViewport().update(width, height, true); } @Override public void render(float delta) { stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); Table.drawDebug(stage); // show debug lines } @Override public void dispose() { stage.dispose(); } @Override public void show() { // TODO Auto-generated method stub } @Override public void hide() { // TODO Auto-generated method stub } @Override public void pause() { // TODO Auto-generated method stub } @Override public void resume() { // TODO Auto-generated method stub } }