answer
stringlengths
17
10.2M
package com.daveme.intellij.chocolateCakePHP.util; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.patterns.PlatformPatterns; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.jetbrains.php.PhpIndex; import com.jetbrains.php.lang.psi.elements.PhpClass; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; public class PsiUtil { @NotNull public static Collection<PsiFile> convertVirtualFilesToPsiFiles(@NotNull Project project, @NotNull Collection<VirtualFile> files) { Collection<PsiFile> psiFiles = new HashSet<>(); PsiManager psiManager = PsiManager.getInstance(project); for (VirtualFile file : files) { PsiFile psiFile = psiManager.findFile(file); if(psiFile != null) { psiFiles.add(psiFile); } } return psiFiles; } public static PsiFile convertVirtualFileToPsiFile(@NotNull Project project, @NotNull VirtualFile file) { PsiManager psiManager = PsiManager.getInstance(project); return psiManager.findFile(file); } @Nullable public static String getFileNameWithoutExtension(PsiElement psiElement) { PsiFile file = psiElement.getContainingFile(); if (file == null) { return null; } VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) { return null; } return virtualFile.getNameWithoutExtension(); } @NotNull public static Collection<PhpClass> getControllerFieldClasses(String fieldName, Project project) { Collection<PhpClass> result = new ArrayList<>(); PhpIndex phpIndex = PhpIndex.getInstance(project); Collection<PhpClass> modelClasses = phpIndex.getClassesByFQN(fieldName); Collection<PhpClass> componentClasses = phpIndex.getClassesByFQN(fieldName + "Component"); result.addAll(modelClasses); result.addAll(componentClasses); return result; } @NotNull public static PsiElement[] getClassesAsArray(@NotNull PsiElement psiElement, String className) { Collection<PhpClass> helperClasses = getClasses(psiElement, className); return helperClasses.toArray(new PsiElement[helperClasses.size()]); } @NotNull public static Collection<PhpClass> getClasses(@NotNull PsiElement psiElement, String className) { PhpIndex phpIndex = PhpIndex.getInstance(psiElement.getProject()); return phpIndex.getClassesByFQN(className); } @Nullable public static PsiElement findParent(PsiElement element, Class clazz) { while (true) { PsiElement parent = element.getParent(); if (parent == null) { break; } if (PlatformPatterns.psiElement(clazz).accepts(parent)) { return parent; } element = parent; } return null; } @Nullable public static PsiElement findFirstChild(PsiElement element, Class clazz) { PsiElement[] children = element.getChildren(); for (PsiElement child : children) { if (PlatformPatterns.psiElement(clazz).accepts(child)) { return child; } PsiElement grandChild = findFirstChild(child, clazz); if (grandChild != null) { return grandChild; } } return null; } public static void dumpAllParents(PsiElement element) { System.out.print("element: "+element.getClass()+" {"); while (true) { PsiElement parent = element.getParent(); if (parent == null) { break; } System.out.print("(" + StringUtil.allInterfaces(parent.getClass())); System.out.print("), "); element = parent; } System.out.println("}"); } }
package com.github.gummywormz.AutoJARC.Background; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * Gets MD5 hash of a specified file * @author Paul Alves */ public class GetHash { /** * Gets the MD5 hash of the file * @param f File to get hash of * @return The hash as a string * @throws FileNotFoundException * @throws IOException */ public static String getHash(File f) throws FileNotFoundException, IOException{ MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException ex) { return "Extreme error occurred. This statement should never be reached"; } FileInputStream in = new FileInputStream(f); byte[] buff = new byte[1024]; int read = 0; while ((read = in.read(buff)) != -1) { md.update(buff, 0, read); } byte[] mdbytes = md.digest(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < mdbytes.length; i++) { sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); } in.close(); return sb.toString(); } }
// Package package com.hp.hpl.jena.ontology.impl.test; // Imports import java.io.*; import java.util.*; import com.hp.hpl.jena.graph.*; import com.hp.hpl.jena.graph.impl.*; import com.hp.hpl.jena.mem.GraphMem; import com.hp.hpl.jena.ontology.*; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.reasoner.*; import com.hp.hpl.jena.reasoner.ReasonerRegistry; import com.hp.hpl.jena.vocabulary.OWL; import junit.framework.*; /** * <p> * Unit tests that are derived from user bug reports * </p> * * @author Ian Dickinson, HP Labs * (<a href="mailto:[email protected]" >email</a>) * @version CVS $Id: TestBugReports.java,v 1.19 2003-10-22 10:41:26 ian_dickinson Exp $ */ public class TestBugReports extends TestCase { // Constants public static String NS = "http://example.org/test // Static variables // Instance variables public TestBugReports( String name ) { super( name ); } // Constructors // External signature methods /** * Bug report by Mariano Rico Almodvar [[email protected]] on June 16th. Said to raise exception. */ public void test_mra_01() { OntModel m = ModelFactory.createOntologyModel( OntModelSpec.DAML_MEM, null, null); String myDicURI = "http://somewhere/myDictionaries/1.0 String damlURI = "http://www.daml.org/2001/03/daml+oil m.setNsPrefix("DAML", damlURI); String c1_uri = myDicURI + "C1"; OntClass c1 = m.createClass(c1_uri); DatatypeProperty p1 = m.createDatatypeProperty( myDicURI + "P1"); p1.setDomain(c1); ByteArrayOutputStream strOut = new ByteArrayOutputStream(); m.write(strOut,"RDF/XML-ABBREV", myDicURI); //m.write(System.out,"RDF/XML-ABBREV", myDicURI); } /** Bug report from Holger Knublauch on July 25th 2003. Cannot convert owl:Class to an OntClass */ public void test_hk_01() { // synthesise a mini-document String base = "http://jena.hpl.hp.com/test String doc = "<rdf:RDF" + " xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns " xmlns:owl=\"http://www.w3.org/2002/07/owl " <owl:Ontology rdf:about=\"\">" + " <owl:imports rdf:resource=\"http: " </owl:Ontology>" + "</rdf:RDF>"; // read in the base ontology, which includes the owl language definition // note OWL_MEM => no reasoner is used OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM, null ); m.read( new ByteArrayInputStream( doc.getBytes() ), base ); // we need a resource corresponding to OWL Class but in m Resource owlClassRes = m.getResource( OWL.Class.getURI() ); // now can we see this as an OntClass? OntClass c = (OntClass) owlClassRes.as( OntClass.class ); assertNotNull( "OntClass c should not be null", c ); //(OntClass) (ontModel.getProfile().CLASS()).as(OntClass.class); } /** Bug report from Hoger Knublauch on Aug 19th 2003. NPE when setting all distinct members */ public void test_hk_02() { OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM); spec.setReasoner(null); OntModel ontModel = ModelFactory.createOntologyModel(spec, null); // ProfileRegistry.OWL_LANG); ontModel.createAllDifferent(); assertTrue(ontModel.listAllDifferent().hasNext()); AllDifferent allDifferent = (AllDifferent)ontModel.listAllDifferent().next(); //allDifferent.setDistinct(ontModel.createList()); assertFalse(allDifferent.listDistinctMembers().hasNext()); } /** Bug report from Holger Knublauch on Aug 19th, 2003. Initialisation error */ public void test_hk_03() { OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM); spec.setReasoner(null); OntModel ontModel = ModelFactory.createOntologyModel(spec, null); OntProperty property = ontModel.createObjectProperty("http://www.aldi.de#property"); /*MinCardinalityRestriction testClass = */ontModel.createMinCardinalityRestriction( null, property, 42); } /** Bug report from Holger Knublauch on Aug 19th, 2003. Document manager alt mechanism breaks relative name translation */ public void test_hk_04() { OntModel m = ModelFactory.createOntologyModel(); m.getDocumentManager().addAltEntry( "http://jena.hpl.hp.com/testing/ontology/relativenames", "file:testing/ontology/relativenames.rdf"); m.read( "http://jena.hpl.hp.com/testing/ontology/relativenames" ); assertTrue( " assertFalse( "file: #A should not be a class", m.getResource( "file:testing/ontology/relativenames.rdf#A" ).canAs( OntClass.class ) ); } /** Bug report from Holger Knublach: not all elements of a union are removed */ public void test_hk_05() { OntModelSpec spec = new OntModelSpec(OntModelSpec.OWL_MEM); spec.setReasoner(null); OntModel ontModel = ModelFactory.createOntologyModel(spec, null); String ns = "http://foo.bar/fu OntClass a = ontModel.createClass(ns+"A"); OntClass b = ontModel.createClass(ns+"B"); int oldCount = getStatementCount( ontModel ); RDFList members = ontModel.createList(new RDFNode[] {a, b}); IntersectionClass intersectionClass = ontModel.createIntersectionClass(null, members); intersectionClass.remove(); assertEquals("Before and after statement counts are different", oldCount, getStatementCount( ontModel )); } /** * Bug report by [email protected], 30-July-2003. A literal can be * turned into an individual. */ public void test_fc_01() { OntModel m = ModelFactory.createOntologyModel(); ObjectProperty p = m.createObjectProperty( NS + "p" ); Restriction r = m.createRestriction( p ); HasValueRestriction hv = r.convertToHasValueRestriction( m.createLiteral( 1 ) ); RDFNode n = hv.getHasValue(); assertFalse( "Should not be able to convert literal to individual", n.canAs( Individual.class ) ); } /** * Bug report by Christoph Kunze ([email protected]). 18/Aug/03 * No transaction support in ontmodel. */ public void test_ck_01() { Graph g = new GraphMem() { TransactionHandler m_t = new MockTransactionHandler(); public TransactionHandler getTransactionHandler() {return m_t;} }; Model m0 = ModelFactory.createModelForGraph( g ); OntModel m1 = ModelFactory.createOntologyModel( OntModelSpec.OWL_LITE_MEM, m0 ); assertFalse( "Transaction not started yet", ((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_inTransaction ); m1.begin(); assertTrue( "Transaction started", ((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_inTransaction ); m1.abort(); assertFalse( "Transaction aborted", ((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_inTransaction ); assertTrue( "Transaction aborted", ((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_aborted); m1.begin(); assertTrue( "Transaction started", ((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_inTransaction ); m1.commit(); assertFalse( "Transaction committed", ((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_inTransaction ); assertTrue( "Transaction committed", ((MockTransactionHandler) m1.getGraph().getTransactionHandler()).m_committed); } /** * Bug report by Christoph Kunz, 26/Aug/03. CCE when creating a statement from * a vocabulary * */ public void test_ck_02() { OntModel vocabModel = ModelFactory.createOntologyModel(); ObjectProperty p = vocabModel.createObjectProperty("p"); OntClass A = vocabModel.createClass( "A"); OntModel workModel = ModelFactory.createOntologyModel(); Individual sub = workModel.createIndividual("uri1", A); Individual obj = workModel.createIndividual("uri2", A); workModel.createStatement(sub, p, obj); } /** Bug report from Christoph Kunz - reification problems and UnsupportedOperationException */ public void test_ck_03() { // part A - surprising reification OntModel model1 = ModelFactory.createOntologyModel(OntModelSpec.DAML_MEM, null); OntModel model2 = ModelFactory.createOntologyModel(OntModelSpec.DAML_MEM_RULE_INF, null); Individual sub = model1.createIndividual("http://mytest#i1", model1.getProfile().CLASS()); OntProperty pred = model1.createOntProperty("http://mytest Individual obj = model1.createIndividual("http://mytest#i2", model1.getProfile().CLASS()); OntProperty probabilityP = model1.createOntProperty("http://mytest#prob"); Statement st = model1.createStatement(sub, pred, obj); model1.add(st); st.createReifiedStatement().addProperty(probabilityP, 0.9); assertTrue( "st should be reified", st.isReified() ); Statement st2 = model2.createStatement(sub, pred, obj); model2.add(st2); st2.createReifiedStatement().addProperty(probabilityP, 0.3); assertTrue( "st2 should be reified", st2.isReified() ); sub.addProperty(probabilityP, 0.3); sub.removeAll(probabilityP).addProperty(probabilityP, 0.3); //!!! exception // Part B - exception in remove All Individual sub2 = model2.createIndividual("http://mytest#i1", model1.getProfile().CLASS()); sub.addProperty(probabilityP, 0.3); sub.removeAll(probabilityP); //!!! exception sub2.addProperty(probabilityP, 0.3); sub2.removeAll(probabilityP); //!!! exception } /** * Bug report by sjooseng [[email protected]]. CCE in listOneOf in Enumerated * Class with DAML profile. */ public void test_sjooseng_01() { String source = "<rdf:RDF xmlns:daml='http://www.daml.org/2001/03/daml+oil " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema " <daml:Class rdf:about='http://localhost:8080/kc2c " <daml:subClassOf>" + " <daml:Restriction>" + " <daml:onProperty rdf:resource='http://localhost:8080/kc2c " <daml:hasClass>" + " <daml:Class>" + " <daml:oneOf rdf:parseType=\"daml:collection\">" + " <daml:Thing rdf:about='http://localhost:8080/kc2c " <daml:Thing rdf:about='http://localhost:8080/kc2c " </daml:oneOf>" + " </daml:Class>" + " </daml:hasClass>" + " </daml:Restriction>" + " </daml:subClassOf>" + " </daml:Class>" + " <daml:ObjectProperty rdf:about='http://localhost:8080/kc2c " <rdfs:label>p1</rdfs:label>" + " </daml:ObjectProperty>" + "</rdf:RDF>" ; OntModel m = ModelFactory.createOntologyModel( ProfileRegistry.DAML_LANG ); m.read( new ByteArrayInputStream( source.getBytes() ), "http://localhost:8080/kc2c" ); OntClass kc1 = m.getOntClass( "http://localhost:8080/kc2c boolean found = false; Iterator it = kc1.listSuperClasses( false ); while ( it.hasNext() ) { OntClass oc = (OntClass)it.next(); if ( oc.isRestriction() ) { Restriction r = oc.asRestriction(); if ( r.isSomeValuesFromRestriction() ) { SomeValuesFromRestriction sr = r.asSomeValuesFromRestriction(); OntClass sc = (OntClass) sr.getSomeValuesFrom(); if ( sc.isEnumeratedClass() ) { EnumeratedClass ec = sc.asEnumeratedClass(); assertEquals( "Enumeration size should be 2", 2, ec.getOneOf().size() ); found = true; } } } } assertTrue( found ); } /** Problem reported by Andy Seaborne - combine abox and tbox in RDFS with ontmodel */ public void test_afs_01() { String sourceT = "<rdf:RDF " + " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema " xmlns:owl=\"http://www.w3.org/2002/07/owl " <owl:Class rdf:about='http://example.org/foo " </owl:Class>" + "</rdf:RDF>" ; String sourceA = "<rdf:RDF " + " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema " xmlns:owl=\"http://www.w3.org/2002/07/owl " <rdf:Description rdf:about='http://example.org/foo " <rdf:type rdf:resource='http://example.org/foo " </rdf:Description>" + "</rdf:RDF>" ; Model tBox = ModelFactory.createDefaultModel(); tBox.read( new ByteArrayInputStream( sourceT.getBytes() ), "http://example.org/foo" ); Model aBox = ModelFactory.createDefaultModel(); aBox.read( new ByteArrayInputStream( sourceA.getBytes() ), "http://example.org/foo" ); Reasoner reasoner = ReasonerRegistry.getOWLReasoner(); reasoner = reasoner.bindSchema( tBox ); OntModelSpec spec = new OntModelSpec( OntModelSpec.OWL_MEM_RULE_INF ); spec.setReasoner( reasoner ); OntModel m = ModelFactory.createOntologyModel( spec, aBox ); List inds = new ArrayList(); for (Iterator i = m.listIndividuals(); i.hasNext(); ) { inds.add( i.next() ); } assertTrue( "x should be an individual", inds.contains( m.getResource( "http://example.org/foo } /** Bug report by Thorsten Ottmann [[email protected]] - problem accessing elements of DAML list */ public void test_to_01() { String sourceT = "<rdf:RDF " + " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema " xmlns:daml='http://www.daml.org/2001/03/daml+oil " <daml:Class rdf:about='http://example.org/foo " <daml:intersectionOf rdf:parseType=\"daml:collection\">" + " <daml:Class rdf:ID=\"B\" />" + " <daml:Class rdf:ID=\"C\" />" + " </daml:intersectionOf>" + " </daml:Class>" + "</rdf:RDF>" ; OntModel m = ModelFactory.createOntologyModel( OntModelSpec.DAML_MEM, null ); m.read( new ByteArrayInputStream( sourceT.getBytes() ), "http://example.org/foo" ); OntClass A = m.getOntClass( "http://example.org/foo assertNotNull( A ); IntersectionClass iA = A.asIntersectionClass(); assertNotNull( iA ); RDFList intersection = iA.getOperands(); assertNotNull( intersection ); assertEquals( 2, intersection.size() ); assertTrue( intersection.contains( m.getOntClass( "http://example.org/foo assertTrue( intersection.contains( m.getOntClass( "http://example.org/foo } /** Bug report by Thorsten Liebig [[email protected]] - SymmetricProperty etc not visible in list ont properties */ public void test_tl_01() { String sourceT = "<rdf:RDF " + " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns " xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema " xmlns:owl=\"http://www.w3.org/2002/07/owl " <owl:SymmetricProperty rdf:about='http://example.org/foo " </owl:SymmetricProperty>" + " <owl:TransitiveProperty rdf:about='http://example.org/foo " </owl:TransitiveProperty>" + " <owl:InverseFunctionalProperty rdf:about='http://example.org/foo " </owl:InverseFunctionalProperty>" + "</rdf:RDF>" ; OntModel m = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM_RULE_INF, null ); m.read( new ByteArrayInputStream( sourceT.getBytes() ), "http://example.org/foo" ); boolean foundP1 = false; boolean foundP2 = false; boolean foundP3 = false; // iterator of properties should include p1-3 for (Iterator i = m.listOntProperties(); i.hasNext(); ) { Resource r = (Resource) i.next(); foundP1 = foundP1 || r.getURI().equals( "http://example.org/foo foundP2 = foundP2 || r.getURI().equals( "http://example.org/foo foundP3 = foundP3 || r.getURI().equals( "http://example.org/foo } assertTrue( "p1 not listed", foundP1 ); assertTrue( "p2 not listed", foundP2 ); assertTrue( "p3 not listed", foundP3 ); foundP1 = false; foundP2 = false; foundP3 = false; // iterator of object properties should include p1-3 for (Iterator i = m.listObjectProperties(); i.hasNext(); ) { Resource r = (Resource) i.next(); foundP1 = foundP1 || r.getURI().equals( "http://example.org/foo foundP2 = foundP2 || r.getURI().equals( "http://example.org/foo foundP3 = foundP3 || r.getURI().equals( "http://example.org/foo } assertTrue( "p1 not listed", foundP1 ); assertTrue( "p2 not listed", foundP2 ); assertTrue( "p3 not listed", foundP3 ); } // Internal implementation methods private int getStatementCount( OntModel ontModel ) { int count = 0; for (Iterator it = ontModel.listStatements(); it.hasNext(); it.next()) { count++; } return count; } // Inner class definitions class MockTransactionHandler extends SimpleTransactionHandler { boolean m_inTransaction = false; boolean m_aborted = false; boolean m_committed = false; public void begin() {m_inTransaction = true;} public void abort() {m_inTransaction = false; m_aborted = true;} public void commit() {m_inTransaction = false; m_committed = true;} } }
package com.hp.hpl.jena.reasoner.rulesys.test; import com.hp.hpl.jena.mem.GraphMem; import com.hp.hpl.jena.reasoner.*; import com.hp.hpl.jena.reasoner.rulesys.*; import com.hp.hpl.jena.reasoner.test.TestUtil; import com.hp.hpl.jena.datatypes.xsd.XSDDatatype; import com.hp.hpl.jena.graph.*; import com.hp.hpl.jena.graph.impl.LiteralLabel; import com.hp.hpl.jena.rdf.model.*; import com.hp.hpl.jena.shared.ClosedException; import com.hp.hpl.jena.util.ModelLoader; import com.hp.hpl.jena.util.PrintUtil; import com.hp.hpl.jena.util.iterator.ExtendedIterator; import com.hp.hpl.jena.vocabulary.*; import junit.framework.TestCase; import junit.framework.TestSuite; import java.io.IOException; import java.util.*; import org.apache.log4j.Logger; public class TestFBRules extends TestCase { /** log4j logger */ protected static Logger logger = Logger.getLogger(TestFBRules.class); // Useful constants protected Node p = Node.createURI("p"); protected Node q = Node.createURI("q"); protected Node n1 = Node.createURI("n1"); protected Node n2 = Node.createURI("n2"); protected Node n3 = Node.createURI("n3"); protected Node n4 = Node.createURI("n4"); protected Node res = Node.createURI("res"); protected Node r = Node.createURI("r"); protected Node s = Node.createURI("s"); protected Node t = Node.createURI("t"); protected Node a = Node.createURI("a"); protected Node b = Node.createURI("b"); protected Node c = Node.createURI("c"); protected Node d = Node.createURI("d"); protected Node C1 = Node.createURI("C1"); protected Node C2 = Node.createURI("C2"); protected Node C3 = Node.createURI("C3"); protected Node sP = RDFS.subPropertyOf.getNode(); protected Node sC = RDFS.subClassOf.getNode(); protected Node ty = RDF.type.getNode(); /** * Boilerplate for junit */ public TestFBRules( String name ) { super( name ); } /** * Boilerplate for junit. * This is its own test suite */ public static TestSuite suite() { return new TestSuite( TestFBRules.class ); // TestSuite suite = new TestSuite(); // suite.addTest(new TestFBRules( "testNumericFunctors" )); // return suite; } /** * Override in subclasses to test other reasoners. */ public Reasoner createReasoner(List rules) { FBRuleReasoner reasoner = new FBRuleReasoner(rules); reasoner.tablePredicate(RDFS.Nodes.subClassOf); reasoner.tablePredicate(RDF.Nodes.type); reasoner.tablePredicate(p); return reasoner; } /** * Check parser extension for f/b distinction. */ public void testParser() { String rf = "(?a rdf:type ?t) -> (?t rdf:type rdfs:Class)."; String rb = "(?t rdf:type rdfs:Class) <- (?a rdf:type ?t)."; assertTrue( ! Rule.parseRule(rf).isBackward() ); assertTrue( Rule.parseRule(rb).isBackward() ); } /** * Minimal rule tester to check basic pattern match, forward style. */ public void testRuleMatcher() { String rules = "[r1: (?a p ?b), (?b q ?c) -> (?a, q, ?c)]" + "[r2: (?a p ?b), (?b p ?c) -> (?a, p, ?c)]" + "[r3: (?a p ?a), (n1 p ?c), (n1, p, ?a) -> (?a, p, ?c)]" + "[r4: (n4 ?p ?a) -> (n4, ?a, ?p)]"; List ruleList = Rule.parseRules(rules); InfGraph infgraph = createReasoner(ruleList).bind(new GraphMem()); infgraph.add(new Triple(n1, p, n2)); infgraph.add(new Triple(n2, p, n3)); infgraph.add(new Triple(n2, q, n3)); infgraph.add(new Triple(n4, p, n4)); TestUtil.assertIteratorValues(this, infgraph.find(null, null, null), new Triple[] { new Triple(n1, p, n2), new Triple(n2, p, n3), new Triple(n2, q, n3), new Triple(n4, p, n4), new Triple(n1, p, n3), new Triple(n1, q, n3), new Triple(n4, n4, p), }); } /** * Test functor handling */ public void testEmbeddedFunctors() { String rules = "(?C rdf:type owl:Restriction), (?C owl:onProperty ?P), (?C owl:allValuesFrom ?D) -> (?C rb:restriction all(?P, ?D))." + "(?C rb:restriction all(eg:p, eg:D)) -> (?C rb:restriction 'allOK')." + "[ -> (eg:foo eg:prop functor(eg:bar, 1)) ]" + "[ (?x eg:prop functor(eg:bar, ?v)) -> (?x eg:propbar ?v) ]" + "[ (?x eg:prop functor(?v, ?*)) -> (?x eg:propfunc ?v) ]" + ""; List ruleList = Rule.parseRules(rules); Model data = ModelFactory.createDefaultModel(); Resource R1 = data.createResource(PrintUtil.egNS + "R1"); Resource D = data.createResource(PrintUtil.egNS + "D"); Property p = data.createProperty(PrintUtil.egNS, "p"); Property prop = data.createProperty(PrintUtil.egNS, "prop"); Property propbar = data.createProperty(PrintUtil.egNS, "propbar"); Property propfunc = data.createProperty(PrintUtil.egNS, "propfunc"); Property rbr = data.createProperty(ReasonerVocabulary.RBNamespace, "restriction"); R1.addProperty(RDF.type, OWL.Restriction) .addProperty(OWL.onProperty, p) .addProperty(OWL.allValuesFrom, D); Reasoner reasoner = createReasoner(ruleList); InfGraph infgraph = reasoner.bind(data.getGraph()); Model infModel = ModelFactory.createModelForGraph(infgraph); Resource foo = infModel.createResource(PrintUtil.egNS + "foo"); Resource bar = infModel.createResource(PrintUtil.egNS + "bar"); RDFNode flit = infModel.getResource(R1.getURI()).getRequiredProperty(rbr).getObject(); assertNotNull(flit); assertEquals(flit.toString(), "allOK"); // assertTrue(flit instanceof Literal); // Functor func = (Functor)((Literal)flit).getValue(); // assertEquals("all", func.getName()); // assertEquals(p.getNode(), func.getArgs()[0]); // assertEquals(D.getNode(), func.getArgs()[1]); Literal one = (Literal)foo.getRequiredProperty(propbar).getObject(); assertEquals(new Integer(1), one.getValue()); } /** * The the minimal machinery for supporting builtins */ public void testBuiltins() { String rules = //"[testRule1: (n1 ?p ?a) -> print('rule1test', ?p, ?a)]" + "[r1: (n1 p ?x), addOne(?x, ?y) -> (n1 q ?y)]" + "[r2: (n1 p ?x), lessThan(?x, 3) -> (n2 q ?x)]" + "[axiom1: -> (n1 p 1)]" + "[axiom2: -> (n1 p 4)]" + ""; List ruleList = Rule.parseRules(rules); InfGraph infgraph = createReasoner(ruleList).bind(new GraphMem()); TestUtil.assertIteratorValues(this, infgraph.find(n1, q, null), new Triple[] { new Triple(n1, q, Util.makeIntNode(2)), new Triple(n1, q, Util.makeIntNode(5)) }); TestUtil.assertIteratorValues(this, infgraph.find(n2, q, null), new Triple[] { new Triple(n2, q, Util.makeIntNode(1)) }); } /** * Test schmea partial binding machinery, forward subset. */ public void testSchemaBinding() { String rules = "[testRule1: (n1 p ?a) -> (n2, p, ?a)]" + "[testRule2: (n1 q ?a) -> (n2, q, ?a)]" + "[testRule3: (n2 p ?a), (n2 q ?a) -> (res p ?a)]" + "[testBRule4: (n3 p ?a) <- (n1, p, ?a)]"; List ruleList = Rule.parseRules(rules); Graph schema = new GraphMem(); schema.add(new Triple(n1, p, n3)); Graph data = new GraphMem(); data.add(new Triple(n1, q, n4)); data.add(new Triple(n1, q, n3)); Reasoner reasoner = createReasoner(ruleList); Reasoner boundReasoner = reasoner.bindSchema(schema); InfGraph infgraph = boundReasoner.bind(data); TestUtil.assertIteratorValues(this, infgraph.find(null, null, null), new Triple[] { new Triple(n1, p, n3), new Triple(n2, p, n3), new Triple(n3, p, n3), new Triple(n1, q, n4), new Triple(n2, q, n4), new Triple(n1, q, n3), new Triple(n2, q, n3), new Triple(res, p, n3) }); } /** * The the "remove" builtin */ public void testRemoveBuiltin() { String rules = "[rule1: (?x p ?y), (?x q ?y) -> remove(0)]" + ""; List ruleList = Rule.parseRules(rules); InfGraph infgraph = createReasoner(ruleList).bind(new GraphMem()); infgraph.add(new Triple(n1, p, Util.makeIntNode(1))); infgraph.add(new Triple(n1, p, Util.makeIntNode(2))); infgraph.add(new Triple(n1, q, Util.makeIntNode(2))); TestUtil.assertIteratorValues(this, infgraph.find(n1, null, null), new Triple[] { new Triple(n1, p, Util.makeIntNode(1)), new Triple(n1, q, Util.makeIntNode(2)) }); } /** * Test the rebind operation. */ public void testRebind() { String rules = "[rule1: (?x p ?y) -> (?x q ?y)]"; List ruleList = Rule.parseRules(rules); Graph data = new GraphMem(); data.add(new Triple(n1, p, n2)); InfGraph infgraph = createReasoner(ruleList).bind(data); TestUtil.assertIteratorValues(this, infgraph.find(n1, null, null), new Triple[] { new Triple(n1, p, n2), new Triple(n1, q, n2) }); Graph ndata = new GraphMem(); ndata.add(new Triple(n1, p, n3)); infgraph.rebind(ndata); TestUtil.assertIteratorValues(this, infgraph.find(n1, null, null), new Triple[] { new Triple(n1, p, n3), new Triple(n1, q, n3) }); } /** * Test the close operation. */ public void testClose() { String rules = "[rule1: (?x p ?y) -> (?x q ?y)]"; List ruleList = Rule.parseRules(rules); Graph data = new GraphMem(); data.add(new Triple(n1, p, n2)); InfGraph infgraph = createReasoner(ruleList).bind(data); TestUtil.assertIteratorValues(this, infgraph.find(n1, null, null), new Triple[] { new Triple(n1, p, n2), new Triple(n1, q, n2) }); infgraph.close(); boolean foundException = false; try { infgraph.find(n1, null, null); } catch (ClosedException e) { foundException = true; } assertTrue("Close detected", foundException); } /** * Test example pure backchaining rules */ public void testBackchain1() { Graph data = new GraphMem(); data.add(new Triple(p, sP, q)); data.add(new Triple(q, sP, r)); data.add(new Triple(C1, sC, C2)); data.add(new Triple(C2, sC, C3)); data.add(new Triple(a, ty, C1)); List rules = Rule.parseRules( "[rdfs8: (?a rdfs:subClassOf ?c) <- (?a rdfs:subClassOf ?b), (?b rdfs:subClassOf ?c)]" + "[rdfs9: (?a rdf:type ?y) <- (?x rdfs:subClassOf ?y), (?a rdf:type ?x)]" + "[-> (rdf:type rdfs:range rdfs:Class)]" + "[rdfs3: (?y rdf:type ?c) <- (?x ?p ?y), (?p rdfs:range ?c)]" + "[rdfs7: (?a rdfs:subClassOf ?a) <- (?a rdf:type rdfs:Class)]" ); Reasoner reasoner = createReasoner(rules); InfGraph infgraph = reasoner.bind(data); TestUtil.assertIteratorValues(this, infgraph.find(a, ty, null), new Object[] { new Triple(a, ty, C1), new Triple(a, ty, C2), new Triple(a, ty, C3) } ); TestUtil.assertIteratorValues(this, infgraph.find(C1, sC, a), new Object[] { } ); } /** * Test complex rule head unification */ public void testBackchain2() { Graph data = new GraphMem(); data.add(new Triple(c, q, d)); List rules = Rule.parseRules( "[r1: (c r ?x) <- (?x p f(?x b))]" + "[r2: (?y p f(a ?y)) <- (c q ?y)]" ); Reasoner reasoner = createReasoner(rules); InfGraph infgraph = reasoner.bind(data); TestUtil.assertIteratorValues(this, infgraph.find(c, r, null), new Object[] { } ); data.add(new Triple(c, q, a)); rules = Rule.parseRules( "[r1: (c r ?x) <- (?x p f(?x a))]" + "[r2: (?y p f(a ?y)) <- (c q ?y)]" ); reasoner = createReasoner(rules); infgraph = reasoner.bind(data); TestUtil.assertIteratorValues(this, infgraph.find(c, r, null), new Object[] { new Triple(c, r, a) } ); data = new GraphMem(); data.add(new Triple(a, q, a)); data.add(new Triple(a, q, b)); data.add(new Triple(a, q, c)); data.add(new Triple(b, q, d)); data.add(new Triple(b, q, b)); rules = Rule.parseRules( "[r1: (c r ?x) <- (?x p ?x)]" + "[r2: (?x p ?y) <- (a q ?x), (b q ?y)]" ); reasoner = createReasoner(rules); infgraph = reasoner.bind(data); TestUtil.assertIteratorValues(this, infgraph.find(c, r, null), new Object[] { new Triple(c, r, b) } ); rules = Rule.parseRules( "[r1: (c r ?x) <- (?x p ?x)]" + "[r2: (a p ?x) <- (a q ?x)]" ); reasoner = createReasoner(rules); infgraph = reasoner.bind(data); TestUtil.assertIteratorValues(this, infgraph.find(c, r, null), new Object[] { new Triple(c, r, a) } ); } /** * Test restriction example */ public void testBackchain3() { Graph data = new GraphMem(); data.add(new Triple(a, ty, r)); data.add(new Triple(a, p, b)); data.add(new Triple(r, sC, C1)); data.add(new Triple(C1, ty, OWL.Restriction.asNode())); data.add(new Triple(C1, OWL.onProperty.asNode(), p)); data.add(new Triple(C1, OWL.allValuesFrom.asNode(), c)); List rules = Rule.parseRules( "[rdfs9: (?a rdf:type ?y) <- (?x rdfs:subClassOf ?y) (?a rdf:type ?x)]" + "[restriction2: (?C owl:equivalentClass all(?P, ?D)) <- (?C rdf:type owl:Restriction), (?C owl:onProperty ?P), (?C owl:allValuesFrom ?D)]" + "[rs2: (?X rdf:type all(?P,?C)) <- (?D owl:equivalentClass all(?P,?C)), (?X rdf:type ?D)]" + "[rp4: (?Y rdf:type ?C) <- (?X rdf:type all(?P, ?C)), (?X ?P ?Y)]" ); Reasoner reasoner = createReasoner(rules); InfGraph infgraph = reasoner.bind(data); TestUtil.assertIteratorValues(this, infgraph.find(b, ty, c), new Object[] { new Triple(b, ty, c) } ); } /** * Test example hybrid rule. */ public void testHybrid1() { Graph data = new GraphMem(); data.add(new Triple(a, p, b)); data.add(new Triple(p, ty, s)); List rules = Rule.parseRules( "[r1: (?p rdf:type s) -> [r1b: (?x ?p ?y) <- (?y ?p ?x)]]" ); Reasoner reasoner = createReasoner(rules); InfGraph infgraph = reasoner.bind(data); TestUtil.assertIteratorValues(this, infgraph.find(null, p, null), new Object[] { new Triple(a, p, b), new Triple(b, p, a) } ); } /** * Test example hybrid rule. */ public void testHybrid2() { Graph data = new GraphMem(); data.add(new Triple(a, r, b)); data.add(new Triple(p, ty, s)); List rules = Rule.parseRules( "[a1: -> (a rdf:type t)]" + "[r0: (?x r ?y) -> (?x p ?y)]" + "[r1: (?p rdf:type s) -> [r1b: (?x ?p ?y) <- (?y ?p ?x)]]" + "[r2: (?p rdf:type s) -> [r2b: (?x ?p ?x) <- (?x rdf:type t)]]" ); Reasoner reasoner = createReasoner(rules); FBRuleInfGraph infgraph = (FBRuleInfGraph) reasoner.bind(data); infgraph.setDerivationLogging(true); infgraph.prepare(); assertTrue("Forward rule count", infgraph.getNRulesFired() == 3); TestUtil.assertIteratorValues(this, infgraph.find(null, p, null), new Object[] { new Triple(a, p, a), new Triple(a, p, b), new Triple(b, p, a) } ); // Suppressed until LP engine implements rule counting, if ever // assertTrue("Backward rule count", infgraph.getNRulesFired() == 8); // Check derivation tracing as well // Suppressed until LP engine implements derivation tracing Iterator di = infgraph.getDerivation(new Triple(b, p, a)); assertTrue(di.hasNext()); RuleDerivation d = (RuleDerivation)di.next(); assertTrue(d.getRule().getName().equals("r1b")); TestUtil.assertIteratorValues(this, d.getMatches().iterator(), new Object[] { new Triple(a, p, b) }); assertTrue(! di.hasNext()); } /** * Test example hybrid rules for rdfs. */ public void testHybridRDFS() { Graph data = new GraphMem(); data.add(new Triple(a, p, b)); data.add(new Triple(p, RDFS.range.asNode(), C1)); List rules = Rule.parseRules( "[rdfs2: (?p rdfs:domain ?c) -> [(?x rdf:type ?c) <- (?x ?p ?y)] ]" + "[rdfs3: (?p rdfs:range ?c) -> [(?y rdf:type ?c) <- (?x ?p ?y)] ]" + "[rdfs5a: (?a rdfs:subPropertyOf ?b), (?b rdfs:subPropertyOf ?c) -> (?a rdfs:subPropertyOf ?c)]" + "[rdfs5b: (?a rdf:type rdf:Property) -> (?a rdfs:subPropertyOf ?a)]" + "[rdfs6: (?p rdfs:subPropertyOf ?q) -> [ (?a ?q ?b) <- (?a ?p ?b)] ]" + "[rdfs7: (?a rdf:type rdfs:Class) -> (?a rdfs:subClassOf ?a)]" + "[rdfs8: (?a rdfs:subClassOf ?b), (?b rdfs:subClassOf ?c) -> (?a rdfs:subClassOf ?c)]" + "[rdfs9: (?x rdfs:subClassOf ?y) -> [ (?a rdf:type ?y) <- (?a rdf:type ?x)] ]" + "" ); Reasoner reasoner = createReasoner(rules); InfGraph infgraph = reasoner.bind(data); // ((FBRuleInfGraph)infgraph).setTraceOn(true); TestUtil.assertIteratorValues(this, infgraph.find(b, ty, null), new Object[] { new Triple(b, ty, C1) } ); } /** * Test example hybrid rules for rdfs. */ public void testHybridRDFS2() { Graph data = new GraphMem(); data.add(new Triple(a, p, b)); data.add(new Triple(p, sP, r)); data.add(new Triple(r, RDFS.range.asNode(), C1)); List rules = Rule.parseRules( "[rdfs3: (?p rdfs:range ?c) -> [(?y rdf:type ?c) <- (?x ?p ?y)] ]" + "[rdfs6: (?p rdfs:subPropertyOf ?q) -> [ (?a ?q ?b) <- (?a ?p ?b)] ]" + "" ); Reasoner reasoner = createReasoner(rules); InfGraph infgraph = reasoner.bind(data); // ((FBRuleInfGraph)infgraph).setTraceOn(true); TestUtil.assertIteratorValues(this, infgraph.find(b, ty, C1), new Object[] { new Triple(b, ty, C1) } ); } /** * Test access to makeInstance machinery from a Brule. */ public void testMakeInstance() { Graph data = new GraphMem(); data.add(new Triple(a, ty, C1)); List rules = Rule.parseRules( "[r1: (?x p ?t) <- (?x rdf:type C1), makeInstance(?x, p, C2, ?t)]" + "[r2: (?t rdf:type C2) <- (?x rdf:type C1), makeInstance(?x, p, C2, ?t)]" + "" ); Reasoner reasoner = createReasoner(rules); InfGraph infgraph = reasoner.bind(data); Node valueInstance = getValue(infgraph, a, p); assertNotNull(valueInstance); Node valueInstance2 = getValue(infgraph, a, p); assertEquals(valueInstance, valueInstance2); Node valueType = getValue(infgraph, valueInstance, RDF.type.asNode()); assertEquals(valueType, C2); } /** * Test access to makeInstance machinery from a Brule. */ public void testMakeInstances() { Graph data = new GraphMem(); data.add(new Triple(a, ty, C1)); List rules = Rule.parseRules( "[r1: (?x p ?t) <- (?x rdf:type C1), makeInstance(?x, p, ?t)]" + "" ); Reasoner reasoner = createReasoner(rules); InfGraph infgraph = reasoner.bind(data); Node valueInstance = getValue(infgraph, a, p); assertNotNull(valueInstance); Node valueInstance2 = getValue(infgraph, a, p); assertEquals(valueInstance, valueInstance2); } /** * Test case for makeInstance which failed during development. */ public void testMakeInstanceBug() { Graph data = new GraphMem(); data.add(new Triple(a, ty, r)); data.add(new Triple(r, sC, Functor.makeFunctorNode("some", new Node[] {p, C1}))); List rules = Rule.parseRules( "[some1: (?C rdfs:subClassOf some(?P, ?D)) ->" + "[some1b: (?X ?P ?T) <- (?X rdf:type ?C), unbound(?T), noValue(?X, ?P), makeInstance(?X, ?P, ?D, ?T) ]" + "[some1b2: (?T rdf:type ?D) <- (?X rdf:type ?C), bound(?T), makeInstance(?X, ?P, ?D, ?T) ]" + "]"); Reasoner reasoner = createReasoner(rules); InfGraph infgraph = reasoner.bind(data); Node valueInstance = getValue(infgraph, a, p); assertNotNull(valueInstance); Node valueType = getValue(infgraph, valueInstance, ty); assertEquals(valueType, C1); } /** * Test numeric functors */ public void testNumericFunctors() { String rules = "[r1: (?x p f(a, ?x)) -> (?x q f(?x)) ]" + "[r1: (?x p f(a, 0)) -> (?x s res) ]" + ""; List ruleList = Rule.parseRules(rules); Graph data = new GraphMem(); data.add(new Triple(n1, p, Util.makeIntNode(2)) ); data.add(new Triple(n2, p, Functor.makeFunctorNode("f", new Node[] { a, Util.makeIntNode(0) }))); data.add(new Triple(n3, p, Functor.makeFunctorNode("f", new Node[] { a, Node.createLiteral(new LiteralLabel("0", "", XSDDatatype.XSDnonNegativeInteger)) } ))); InfGraph infgraph = createReasoner(ruleList).bind(data); TestUtil.assertIteratorValues(this, infgraph.find(null, s, null), new Triple[] { new Triple(n2, s, res), new Triple(n3, s, res), }); } /** * Test the builtins themselves */ public void testBuiltins2() { // Numeric comparisions Node lt = Node.createURI("lt"); Node gt = Node.createURI("gt"); Node le = Node.createURI("le"); Node ge = Node.createURI("ge"); Node eq = Node.createURI("eq"); Node ne = Node.createURI("ne"); String rules = "[r1: (?x q ?vx), (?y q ?vy), lessThan(?vx, ?vy) -> (?x lt ?y)]" + "[r2: (?x q ?vx), (?y q ?vy), greaterThan(?vx, ?vy) -> (?x gt ?y)]" + "[r3: (?x q ?vx), (?y q ?vy), le(?vx, ?vy) -> (?x le ?y)]" + "[r4: (?x q ?vx), (?y q ?vy), ge(?vx, ?vy) -> (?x ge ?y)]" + "[r5: (?x q ?vx), (?y q ?vy), notEqual(?vx, ?vy) -> (?x ne ?y)]" + "[r6: (?x q ?vx), (?y q ?vy), equal(?vx, ?vy) -> (?x eq ?y)]" + ""; List ruleList = Rule.parseRules(rules); Graph data = new GraphMem(); data.add(new Triple(n1, q, Util.makeIntNode(2)) ); data.add(new Triple(n2, q, Util.makeIntNode(2)) ); data.add(new Triple(n3, q, Util.makeIntNode(3)) ); InfGraph infgraph = createReasoner(ruleList).bind(data); TestUtil.assertIteratorValues(this, infgraph.find(n1, null, n2), new Triple[] { new Triple(n1, eq, n2), new Triple(n1, le, n2), new Triple(n1, ge, n2), }); TestUtil.assertIteratorValues(this, infgraph.find(n1, null, n3), new Triple[] { new Triple(n1, ne, n3), new Triple(n1, lt, n3), new Triple(n1, le, n3), }); TestUtil.assertIteratorValues(this, infgraph.find(n3, null, n1), new Triple[] { new Triple(n3, ne, n1), new Triple(n3, gt, n1), new Triple(n3, ge, n1), }); // Floating point comparisons data = new GraphMem(); data.add(new Triple(n1, q, Util.makeIntNode(2)) ); data.add(new Triple(n2, q, Util.makeDoubleNode(2.2)) ); data.add(new Triple(n3, q, Util.makeDoubleNode(2.3)) ); infgraph = createReasoner(ruleList).bind(data); TestUtil.assertIteratorValues(this, infgraph.find(n1, null, n2), new Triple[] { new Triple(n1, ne, n2), new Triple(n1, le, n2), new Triple(n1, lt, n2), }); TestUtil.assertIteratorValues(this, infgraph.find(n2, null, n3), new Triple[] { new Triple(n2, ne, n3), new Triple(n2, le, n3), new Triple(n2, lt, n3), }); // Arithmetic rules = "[r1: (?x p ?a), (?x q ?b), sum(?a, ?b, ?c) -> (?x s ?c)]" + "[r2: (?x p ?a), (?x q ?b), product(?a, ?b, ?c) -> (?x t ?c)]" + ""; ruleList = Rule.parseRules(rules); data = new GraphMem(); data.add(new Triple(n1, p, Util.makeIntNode(3)) ); data.add(new Triple(n1, q, Util.makeIntNode(5)) ); infgraph = createReasoner(ruleList).bind(data); TestUtil.assertIteratorValues(this, infgraph.find(n1, null, null), new Triple[] { new Triple(n1, p, Util.makeIntNode(3)), new Triple(n1, q, Util.makeIntNode(5)), new Triple(n1, s, Util.makeIntNode(8)), new Triple(n1, t, Util.makeIntNode(15)), }); // Note type checking rules = "[r1: (?x p ?y), isLiteral(?y) -> (?x s 'literal')]" + "[r1: (?x p ?y), notLiteral(?y) -> (?x s 'notLiteral')]" + "[r1: (?x p ?y), isBNode(?y) -> (?x s 'bNode')]" + "[r1: (?x p ?y), notBNode(?y) -> (?x s 'notBNode')]" + ""; ruleList = Rule.parseRules(rules); data = new GraphMem(); data.add(new Triple(n1, p, Util.makeIntNode(3)) ); data.add(new Triple(n2, p, res)); data.add(new Triple(n3, p, Node.createAnon())); infgraph = createReasoner(ruleList).bind(data); TestUtil.assertIteratorValues(this, infgraph.find(n1, s, null), new Triple[] { new Triple(n1, s, Node.createLiteral("literal", "", null)), new Triple(n1, s, Node.createLiteral("notBNode", "", null)), }); TestUtil.assertIteratorValues(this, infgraph.find(n2, s, null), new Triple[] { new Triple(n2, s, Node.createLiteral("notLiteral", "", null)), new Triple(n2, s, Node.createLiteral("notBNode", "", null)), }); TestUtil.assertIteratorValues(this, infgraph.find(n3, s, null), new Triple[] { new Triple(n3, s, Node.createLiteral("notLiteral", "", null)), new Triple(n3, s, Node.createLiteral("bNode", "", null)), }); // Data type checking rules = "[r1: (?x p ?y), isDType(?y, rdfs:Literal) -> (?x s 'isLiteral')]" + "[r1: (?x p ?y), isDType(?y, http://www.w3.org/2001/XMLSchema#int) -> (?x s 'isXSDInt')]" + "[r1: (?x p ?y), isDType(?y, http://www.w3.org/2001/XMLSchema#string) -> (?x s 'isXSDString')]" + "[r1: (?x p ?y), notDType(?y, rdfs:Literal) -> (?x s 'notLiteral')]" + "[r1: (?x p ?y), notDType(?y, http://www.w3.org/2001/XMLSchema#int) -> (?x s 'notXSDInt')]" + "[r1: (?x p ?y), notDType(?y, http://www.w3.org/2001/XMLSchema#string) -> (?x s 'notXSDString')]" + ""; ruleList = Rule.parseRules(rules); data = new GraphMem(); data.add(new Triple(n1, p, Util.makeIntNode(3)) ); data.add(new Triple(n2, p, Node.createLiteral("foo", "", null)) ); data.add(new Triple(n3, p, Node.createLiteral("foo", "", XSDDatatype.XSDstring)) ); data.add(new Triple(n4, p, n4)); infgraph = createReasoner(ruleList).bind(data); TestUtil.assertIteratorValues(this, infgraph.find(null, s, null), new Triple[] { new Triple(n1, s, Node.createLiteral("isLiteral", "", null)), new Triple(n1, s, Node.createLiteral("isXSDInt", "", null)), new Triple(n1, s, Node.createLiteral("notXSDString", "", null)), new Triple(n2, s, Node.createLiteral("isLiteral", "", null)), new Triple(n2, s, Node.createLiteral("notXSDInt", "", null)), new Triple(n2, s, Node.createLiteral("notXSDString", "", null)), new Triple(n3, s, Node.createLiteral("isLiteral", "", null)), new Triple(n3, s, Node.createLiteral("notXSDInt", "", null)), new Triple(n3, s, Node.createLiteral("isXSDString", "", null)), new Triple(n4, s, Node.createLiteral("notLiteral", "", null)), new Triple(n4, s, Node.createLiteral("notXSDInt", "", null)), new Triple(n4, s, Node.createLiteral("notXSDString", "", null)), }); // Literal counting rules = "[r1: (?x p ?y), countLiteralValues(?x, p, ?c) -> (?x s ?c)]"; ruleList = Rule.parseRules(rules); data = new GraphMem(); data.add(new Triple(n1, p, Util.makeIntNode(2)) ); data.add(new Triple(n1, p, Util.makeIntNode(2)) ); data.add(new Triple(n1, p, Util.makeIntNode(3)) ); data.add(new Triple(n1, p, n2) ); infgraph = createReasoner(ruleList).bind(data); TestUtil.assertIteratorValues(this, infgraph.find(n1, s, null), new Triple[] { new Triple(n1, s, Util.makeIntNode(2)), }); } /** * Helper - returns the single object value for an s/p pair, asserts an error * if there is more than one. */ private Node getValue(Graph g, Node s, Node p) { ExtendedIterator i = g.find(s, p, null); assertTrue(i.hasNext()); Node result = ((Triple)i.next()).getObject(); if (i.hasNext()) { assertTrue("multiple values not expected", false); i.close(); } return result; } /** * Investigate a suspicious case in the OWL ruleset, is the backchainer * returning duplicate values? */ public void testDuplicatesEC4() throws IOException { Model premisesM = ModelLoader.loadModel("file:testing/wg/equivalentClass/premises004.rdf"); Graph data = premisesM.getGraph(); Reasoner reasoner = new OWLFBRuleReasoner(OWLFBRuleReasonerFactory.theInstance()); InfGraph infgraph = reasoner.bind(data); Node rbPrototypeProp = Node.createURI(ReasonerVocabulary.RBNamespace+"prototype"); int count = 0; for (Iterator i = infgraph.find(null, rbPrototypeProp, null); i.hasNext(); ) { Object t = i.next(); System.out.println(" - " + PrintUtil.print(t)); count++; } // listFBGraph("direct databind case", (FBRuleInfGraph)infgraph); assertTrue(count == 5); infgraph = reasoner.bindSchema(data).bind(new GraphMem()); count = 0; for (Iterator i = infgraph.find(null, rbPrototypeProp, null); i.hasNext(); ) { Object t = i.next(); System.out.println(" - " + PrintUtil.print(t)); count++; } // listFBGraph("bindSchema case", (FBRuleInfGraph)infgraph); assertTrue(count == 5); } /** * Check cost of creating an empty OWL closure. */ public void temp() { Graph data = new GraphMem(); Graph data2 = new GraphMem(); Reasoner reasoner = new OWLFBRuleReasoner(OWLFBRuleReasonerFactory.theInstance()); FBRuleInfGraph infgraph = (FBRuleInfGraph)reasoner.bind(data); FBRuleInfGraph infgraph2 = (FBRuleInfGraph)reasoner.bind(data2); long t1 = System.currentTimeMillis(); infgraph.prepare(); long t2 = System.currentTimeMillis(); System.out.println("Prepare on empty graph = " + (t2-t1) +"ms"); t1 = System.currentTimeMillis(); infgraph2.prepare(); t2 = System.currentTimeMillis(); System.out.println("Prepare on empty graph = " + (t2-t1) +"ms"); } /** * Helper function to list a graph out to logger.info */ public void listGraph(Graph g) { for (Iterator i = g.find(null,null,null); i.hasNext();) { Triple t = (Triple)i.next(); logger.info(PrintUtil.print(t)); } logger.info(" } /** * Helper function to list the interesting parts of an FBInfGraph. */ public void listFBGraph(String message, FBRuleInfGraph graph) { logger.info(message); logger.info("Raw graph data"); listGraph(graph.getRawGraph()); logger.info("Static deductions"); listGraph(graph.getDeductionsGraph()); } }
package com.idunnololz.widgets; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.SparseArray; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.view.animation.Transformation; /** * This class defines an ExpandableListView which supports animations for * collapsing and expanding groups. */ public class AnimatedExpandableListView extends ExpandableListView { /* * A detailed explanation for how this class works: * * Animating the ExpandableListView was no easy task. The way that this * class does it is by exploiting how an ExpandableListView works. * * Normally when {@link ExpandableListView#collapseGroup(int)} or * {@link ExpandableListView#expandGroup(int)} is called, the view toggles * the flag for a group and calls notifyDataSetChanged to cause the ListView * to refresh all of it's view. This time however, depending on whether a * group is expanded or collapsed, certain childViews will either be ignored * or added to the list. * * Knowing this, we can come up with a way to animate our views. For * instance for group expansion, we tell the adapter to animate the * children of a certain group. We then expand the group which causes the * ExpandableListView to refresh all views on screen. The way that * ExpandableListView does this is by calling getView() in the adapter. * However since the adapter knows that we are animating a certain group, * instead of returning the real views for the children of the group being * animated, it will return a fake dummy view. This dummy view will then * draw the real child views within it's dispatchDraw function. The reason * we do this is so that we can animate all of it's children by simply * animating the dummy view. After we complete the animation, we tell the * adapter to stop animating the group and call notifyDataSetChanged. Now * the ExpandableListView is forced to refresh it's views again, except this * time, it will get the real views for the expanded group. * * So, to list it all out, when {@link #expandGroupWithAnimation(int)} is * called the following happens: * * 1. The ExpandableListView tells the adapter to animate a certain group. * 2. The ExpandableListView calls expandGroup. * 3. ExpandGroup calls notifyDataSetChanged. * 4. As an result, getChildView is called for expanding group. * 5. Since the adapter is in "animating mode", it will return a dummy view. * 6. This dummy view draws the actual children of the expanding group. * 7. This dummy view's height is animated from 0 to it's expanded height. * 8. Once the animation completes, the adapter is notified to stop * animating the group and notifyDataSetChanged is called again. * 9. This forces the ExpandableListView to refresh all of it's views again. * 10.This time when getChildView is called, it will return the actual * child views. * * For animating the collapse of a group is a bit more difficult since we * can't call collapseGroup from the start as it would just ignore the * child items, giving up no chance to do any sort of animation. Instead * what we have to do is play the animation first and call collapseGroup * after the animation is done. * * So, to list it all out, when {@link #collapseGroupWithAnimation(int)} is * called the following happens: * * 1. The ExpandableListView tells the adapter to animate a certain group. * 2. The ExpandableListView calls notifyDataSetChanged. * 3. As an result, getChildView is called for expanding group. * 4. Since the adapter is in "animating mode", it will return a dummy view. * 5. This dummy view draws the actual children of the expanding group. * 6. This dummy view's height is animated from it's current height to 0. * 7. Once the animation completes, the adapter is notified to stop * animating the group and notifyDataSetChanged is called again. * 8. collapseGroup is finally called. * 9. This forces the ExpandableListView to refresh all of it's views again. * 10.This time when the ListView will not get any of the child views for * the collapsed group. */ /** * The duration of the expand/collapse animations */ private static final int ANIMATION_DURATION = 300; private AnimatedExpandableListAdapter adapter; public AnimatedExpandableListView(Context context) { super(context); } public AnimatedExpandableListView(Context context, AttributeSet attrs) { super(context, attrs); } public AnimatedExpandableListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * @see ExpandableListView#setAdapter(ExpandableListAdapter) */ public void setAdapter(ExpandableListAdapter adapter) { super.setAdapter(adapter); // Make sure that the adapter extends AnimatedExpandableListAdapter if(adapter instanceof AnimatedExpandableListAdapter) { this.adapter = (AnimatedExpandableListAdapter) adapter; this.adapter.setParent(this); } else { throw new ClassCastException(adapter.toString() + " must implement AnimatedExpandableListAdapter"); } } /** * Expands the given group with an animation. * @param groupPos The position of the group to expand * @return Returns true if the group was expanded. False if the group was * already expanded. */ public boolean expandGroupWithAnimation(int groupPos) { int groupFlatPos = getFlatListPosition(getPackedPositionForGroup(groupPos)); if (groupFlatPos != -1) { int childIndex = groupFlatPos - getFirstVisiblePosition(); if (childIndex < getChildCount()) { // Get the view for the group is it is on screen... View v = getChildAt(childIndex); if (v.getBottom() >= getBottom()) { // If the user is not going to be able to see the animation // we just expand the group without an animation. // This resolves the case where getChildView will not be // called if the children of the group is not on screen return expandGroup(groupPos); } } } // Let the adapter know that we are starting the animation... adapter.startExpandAnimation(groupPos, 0); // Finally call expandGroup (note that expandGroup will call // notifyDataSetChanged so we don't need to) return expandGroup(groupPos); } /** * Collapses the given group with an animation. * @param groupPos The position of the group to collapse * @return Returns true if the group was collapsed. False if the group was * already collapsed. */ public boolean collapseGroupWithAnimation(int groupPos) { int groupFlatPos = getFlatListPosition(getPackedPositionForGroup(groupPos)); if (groupFlatPos != -1) { int childIndex = groupFlatPos - getFirstVisiblePosition(); if (childIndex < getChildCount()) { // Get the view for the group is it is on screen... View v = getChildAt(childIndex); if (v.getBottom() >= getBottom()) { // If the user is not going to be able to see the animation // we just collapse the group without an animation. // This resolves the case where getChildView will not be // called if the children of the group is not on screen return collapseGroup(groupPos); } } } // Get the position of the firstChild visible from the top of the screen long packedPos = getExpandableListPosition(getFirstVisiblePosition()); int firstChildPos = getPackedPositionChild(packedPos); int firstGroupPos = getPackedPositionGroup(packedPos); // If the first visible view on the screen is a child view AND it's a // child of the group we are trying to collapse, then set that // as the first child position of the group... see // {@link #startCollapseAnimation(int, int)} for why this is necessary firstChildPos = firstChildPos == -1 || firstGroupPos != groupPos ? 0 : firstChildPos; // Let the adapter know that we are going to start animating the // collapse animation. adapter.startCollapseAnimation(groupPos, firstChildPos); // Force the listview to refresh it's views adapter.notifyDataSetChanged(); return isGroupExpanded(groupPos); } private int getAnimationDuration() { return ANIMATION_DURATION; } /** * Used for holding information regarding the group. */ private static class GroupInfo { boolean animating = false; boolean expanding = false; int firstChildPosition; /** * This variable contains the last known height value of the dummy view. * We save this information so that if the user collapses a group * before it fully expands, the collapse animation will start from the * CURRENT height of the dummy view and not from the full expanded * height. */ int dummyHeight = -1; } /** * A specialized adapter for use with the AnimatedExpandableListView. All * adapters used with AnimatedExpandableListView MUST extend this class. */ public static abstract class AnimatedExpandableListAdapter extends BaseExpandableListAdapter { private SparseArray<GroupInfo> groupInfo = new SparseArray<GroupInfo>(); private AnimatedExpandableListView parent; private void setParent(AnimatedExpandableListView parent) { this.parent = parent; } public int getRealChildType(int groupPosition, int childPosition) { return 0; } public int getRealChildTypeCount() { return 1; } public abstract View getRealChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent); public abstract int getRealChildrenCount(int groupPosition); private GroupInfo getGroupInfo(int groupPosition) { GroupInfo info = groupInfo.get(groupPosition); if (info == null) { info = new GroupInfo(); groupInfo.put(groupPosition, info); } return info; } private void startExpandAnimation(int groupPosition, int firstChildPosition) { GroupInfo info = getGroupInfo(groupPosition); info.animating = true; info.firstChildPosition = firstChildPosition; info.expanding = true; } private void startCollapseAnimation(int groupPosition, int firstChildPosition) { GroupInfo info = getGroupInfo(groupPosition); info.animating = true; info.firstChildPosition = firstChildPosition; info.expanding = false; } private void stopAnimation(int groupPosition) { GroupInfo info = getGroupInfo(groupPosition); info.animating = false; } /** * Override {@link #getRealChildType(int, int)} instead. */ @Override public final int getChildType(int groupPosition, int childPosition) { GroupInfo info = getGroupInfo(groupPosition); if (info.animating) { // If we are animating this group, then all of it's children // are going to be dummy views which we will say is type 0. return 0; } else { // If we are not animating this group, then we will add 1 to // the type it has so that no type id conflicts will occur // unless getRealChildType() returns MAX_INT return getRealChildType(groupPosition, childPosition) + 1; } } /** * Override {@link #getRealChildTypeCount()} instead. */ @Override public final int getChildTypeCount() { // Return 1 more than the childTypeCount to account for DummyView return getRealChildTypeCount() + 1; } /** * Override {@link #getChildView(int, int, boolean, View, ViewGroup)} instead. */ @Override public final View getChildView(final int groupPosition, int childPosition, boolean isLastChild, View convertView, final ViewGroup parent) { final GroupInfo info = getGroupInfo(groupPosition); if (info.animating) { // If this group is animating, return the a DummyView... if (convertView == null) { convertView = new DummyView(parent.getContext()); convertView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, 0)); } if (childPosition < info.firstChildPosition) { // The reason why we do this is to support the collapse // this group when the group view is not visible but the // children of this group are. When notifyDataSetChanged // is called, the ExpandableListView tries to keep the // list position the same by saving the first visible item // and jumping back to that item after the views have been // refreshed. Now the problem is, if a group has 2 items // and the first visible item is the 2nd child of the group // and this group is collapsed, then the dummy view will be // used for the group. But now the group only has 1 item // which is the dummy view, thus when the ListView is trying // to restore the scroll position, it will try to jump to // the second item of the group. But this group no longer // has a second item, so it is forced to jump to the next // group. This will cause a very ugly visual glitch. So // the way that we counteract this is by creating as many // dummy views as we need to maintain the scroll position // of the ListView after notifyDataSetChanged has been // called. convertView.getLayoutParams().height = 0; return convertView; } final ExpandableListView listView = (ExpandableListView) parent; DummyView dummyView = (DummyView) convertView; // Clear the views that the dummy view draws. dummyView.clearViews(); // Set the style of the divider dummyView.setDivider(listView.getDivider(), parent.getMeasuredWidth(), listView.getDividerHeight()); // Make measure specs to measure child views final int measureSpecW = MeasureSpec.makeMeasureSpec(parent.getWidth(), MeasureSpec.EXACTLY); final int measureSpecH = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); int totalHeight = 0; int clipHeight = parent.getHeight(); final int len = getRealChildrenCount(groupPosition); for (int i = info.firstChildPosition; i < len; i++) { View childView = getRealChildView(groupPosition, i, (i == len - 1), null, parent); childView.measure(measureSpecW, measureSpecH); totalHeight += childView.getMeasuredHeight(); if (totalHeight < clipHeight) { // we only need to draw enough views to fool the user... dummyView.addFakeView(childView); } else { dummyView.addFakeView(childView); // if this group has too many views, we don't want to // calculate the height of everything... just do a light // approximation and break int averageHeight = totalHeight / (i + 1); totalHeight += (len - i - 1) * averageHeight; break; } } if (info.expanding) { ExpandAnimation ani = new ExpandAnimation(dummyView, 0, totalHeight, info); ani.setDuration(this.parent.getAnimationDuration()); ani.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { stopAnimation(groupPosition); notifyDataSetChanged(); } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationStart(Animation animation) {} }); dummyView.startAnimation(ani); } else { if (info.dummyHeight == -1) { info.dummyHeight = totalHeight; } ExpandAnimation ani = new ExpandAnimation(dummyView, info.dummyHeight, 0, info); ani.setDuration(this.parent.getAnimationDuration()); ani.setAnimationListener(new AnimationListener() { @Override public void onAnimationEnd(Animation animation) { stopAnimation(groupPosition); listView.collapseGroup(groupPosition); notifyDataSetChanged(); info.dummyHeight = -1; } @Override public void onAnimationRepeat(Animation animation) {} @Override public void onAnimationStart(Animation animation) {} }); dummyView.startAnimation(ani); } return convertView; } else { return getRealChildView(groupPosition, childPosition, isLastChild, convertView, parent); } } @Override public final int getChildrenCount(int groupPosition) { GroupInfo info = getGroupInfo(groupPosition); if (info.animating) { return info.firstChildPosition + 1; } else { return getRealChildrenCount(groupPosition); } } } private static class DummyView extends View { private List<View> views = new ArrayList<View>(); private Drawable divider; private int dividerWidth; private int dividerHeight; public DummyView(Context context) { super(context); } public void setDivider(Drawable divider, int dividerWidth, int dividerHeight) { this.divider = divider; this.dividerWidth = dividerWidth; this.dividerHeight = dividerHeight; divider.setBounds(0, 0, dividerWidth, dividerHeight); } /** * Add a view for the DummyView to draw. * @param childView View to draw */ public void addFakeView(View childView) { childView.layout(0, 0, getWidth(), getHeight()); views.add(childView); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); final int len = views.size(); for(int i = 0; i < len; i++) { View v = views.get(i); v.layout(left, top, right, bottom); } } public void clearViews() { views.clear(); } @Override public void dispatchDraw(Canvas canvas) { canvas.save(); divider.setBounds(0, 0, dividerWidth, dividerHeight); final int len = views.size(); for(int i = 0; i < len; i++) { View v = views.get(i); v.draw(canvas); canvas.translate(0, v.getMeasuredHeight()); divider.draw(canvas); canvas.translate(0, dividerHeight); } canvas.restore(); } } private static class ExpandAnimation extends Animation { private int baseHeight; private int delta; private View view; private GroupInfo groupInfo; private ExpandAnimation(View v, int startHeight, int endHeight, GroupInfo info) { baseHeight = startHeight; delta = endHeight - startHeight; view = v; groupInfo = info; view.getLayoutParams().height = startHeight; view.requestLayout(); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); if (interpolatedTime < 1.0f) { int val = baseHeight + (int) (delta * interpolatedTime); view.getLayoutParams().height = val; groupInfo.dummyHeight = val; view.requestLayout(); } else { int val = baseHeight + delta; view.getLayoutParams().height = val; groupInfo.dummyHeight = val; view.requestLayout(); } } } }
package datastructures; import java.util.Comparator; import java.util.HashMap; /** * A priority queue/map hybrid backed by a mutable d-ary heap. Supports O(1) * find-min, O(lg n) insert, O(lg n) delete (for any element), O(lg n) update, * and O(1) lookup by key. * * @param <K> the key type * @param <V> the value type */ public class DHeapPriorityMap<K, V> { private static final int DEFAULT_D = 4; private static final int DEFAULT_CAPACITY = 8; private final Comparator<? super V> comparator; private final HashMap<K, Integer> indices; private Entry<K, V>[] array; private final int d; private int size; /** * Constructs a map with the default initial capacity (8) and the default * fan-out for the underlying heap (4). Priority will be determined by the * natural ordering of the map's values. */ public DHeapPriorityMap() { this(DEFAULT_CAPACITY, DEFAULT_D, null); } /** * Constructs a map with the default initial capacity (8) and the default * fan-out for the underlying heap (4). Priority will be determined by the * supplied comparator. * * @param comparator the comparator which will be used to determine priority */ public DHeapPriorityMap(Comparator<? super V> comparator) { this(DEFAULT_CAPACITY, DEFAULT_D, comparator); } public DHeapPriorityMap(int capacity, int d) { this(capacity, d, null); } @SuppressWarnings("unchecked") public DHeapPriorityMap(int capacity, int d, Comparator<? super V> comparator) { if (capacity < 0) { throw new IllegalArgumentException("Capacity must not be negative"); } if (d < 2) { throw new IllegalArgumentException("Value of d must be 2 or greater"); } this.d = d; this.comparator = comparator; array = new Entry[capacity]; indices = new HashMap<K, Integer>(capacity); } /** * Returns {@code true} if the map contains no entries. * * @return {@code true} if the map contains no entries */ public boolean isEmpty() { return size == 0; } /** * Returns the number of entries in the map. * * @return the number of entries in the map */ public int size() { return size; } /** * Returns the key of the entry with the highest priority (this is the entry * with the smallest value if a comparator is not provided). * * @return the key of the entry with the highest priority (could be {@code * null}) or {@code null} if the map is empty */ public K peekKey() { return (size == 0) ? null : array[0].key; } /** * Returns the value of the entry with the highest priority (this is the * entry with the smallest value if a comparator is not provided). * * @return the value of the entry with the highest priority or {@code null} * if the map is empty */ public V peekValue() { return (size == 0) ? null : array[0].value; } /** * Returns the value mapped to the specified key. * * @param key the key whose value is to be returned * @return the value mapped to the key or {@code null} if the map does not * contain the key */ public V get(Object key) { Integer i = indices.get(key); return (i == null) ? null : array[i].value; } /** * Inserts a key along with its associated value. If the map already * contains the key, the old value is replaced. * * @param key the key to be inserted * @param value the value associated with the key * @return the value previously associated with the key or {@code null} if * the map did not contain the key * @throws ClassCastException if the value cannot be compared with the * values in the map * @throws NullPointerException if the value is null */ public V put(K key, V value) { if (value == null) { throw new NullPointerException(); } V old = update(key, value); if (old != null) { return old; } int end = size; if (end == array.length) { grow(end + 1); } ++size; if (comparator != null) { siftUpComparator(end, new Entry<K, V>(key, value)); } else { siftUp(end, new Entry<K, V>(key, value)); } return null; } /** * Removes the entry with the highest priority. * * @return {@code true} if the map changed as a result of the call */ public boolean remove() { if (size == 0) { return false; } K deletedKey = array[0].key; int end = --size; if (comparator != null) { siftDownComparator(0, array[end]); } else { siftDown(0, array[end]); } array[end] = null; indices.remove(deletedKey); return true; } /** * Removes the entry for the specified key. * * @param key the key of the entry to be removed * @return the value which was mapped to the key or {@code null} if the map * did not have an entry for the key */ @SuppressWarnings("unchecked") public V remove(Object key) { Integer find = indices.get(key); if (find == null) { return null; } int i = find; // Avoids additional unboxing. Entry<K, V> deleted = array[i]; int end = --size; Entry<K, V> last = array[end]; if (comparator != null) { if (comparator.compare(last.value, deleted.value) <= 0) { siftUpComparator(i, last); } else { siftDownComparator(i, last); } } else { if (((Comparable<? super V>) last.value).compareTo(deleted.value) <= 0) { siftUp(i, last); } else { siftDown(i, last); } } array[end] = null; indices.remove(deleted.key); return deleted.value; } /** Empties the map. */ public void clear() { for (int i = 0; i < size; ++i) { array[i] = null; } size = 0; indices.clear(); } private int parent(int i) { return (i - 1) / d; } private int firstBranch(int i) { return d * i + 1; } /** Finds the highest-priority branch of a given element. */ @SuppressWarnings("unchecked") private int successor(int i) { int best = firstBranch(i); V bestVal = array[best].value; int end = best + d; if (end - size > 0) { // Overflow-safe equivalent of (end > size). end = size; } for (int j = best + 1; j < end; ++j) { V val = array[j].value; if (((Comparable<? super V>) val).compareTo(bestVal) < 0) { best = j; bestVal = val; } } return best; } /** Comparator version of successor. */ private int successorComparator(int i) { int best = firstBranch(i); V bestVal = array[best].value; int end = best + d; if (end - size > 0) { // Overflow-safe equivalent of (end > size). end = size; } for (int j = best + 1; j < end; ++j) { V val = array[j].value; if (comparator.compare(val, bestVal) < 0) { best = j; bestVal = val; } } return best; } /** Moves an element up the heap while updating the index table. */ @SuppressWarnings("unchecked") private void siftUp(int i, Entry<K, V> e) { Comparable<? super V> val = (Comparable<? super V>) e.value; while (i > 0) { int parent = parent(i); Entry<K, V> p = array[parent]; if (val.compareTo(p.value) >= 0) { break; } array[i] = p; indices.put(p.key, i); i = parent; } array[i] = e; indices.put(e.key, i); } /** Comparator version of siftUp. */ private void siftUpComparator(int i, Entry<K, V> e) { while (i > 0) { int parent = parent(i); Entry<K, V> p = array[parent]; if (comparator.compare(e.value, p.value) >= 0) { break; } array[i] = p; indices.put(p.key, i); i = parent; } array[i] = e; indices.put(e.key, i); } /** Moves an element down the heap while updating the index table. */ @SuppressWarnings("unchecked") private void siftDown(int i, Entry<K, V> e) { if (size > 1) { Comparable<? super V> val = (Comparable<? super V>) e.value; int limit = parent(size - 1); while (i <= limit) { int successor = successor(i); Entry<K, V> s = array[successor]; if (val.compareTo(s.value) <= 0) { break; } array[i] = s; indices.put(s.key, i); i = successor; } } array[i] = e; indices.put(e.key, i); } /** Comparator version of siftDown. */ private void siftDownComparator(int i, Entry<K, V> e) { if (size > 1) { int limit = parent(size - 1); while (i <= limit) { int successor = successorComparator(i); Entry<K, V> s = array[successor]; if (comparator.compare(e.value, s.value) <= 0) { break; } array[i] = s; indices.put(s.key, i); i = successor; } } array[i] = e; indices.put(e.key, i); } /** * Updates the value mapped to the specified key and fixes the heap if * necessary. Returns the old value or, if the key is not present, null. */ @SuppressWarnings("unchecked") private V update(K key, V value) { Integer find = indices.get(key); if (find == null) { return null; } int i = find; // Avoids additional unboxing. Entry<K, V> e = array[i]; V old = e.value; e.value = value; if (comparator != null) { if (comparator.compare(value, old) <= 0) { siftUpComparator(i, e); } else { siftDownComparator(i, e); } } else { if (((Comparable<? super V>) value).compareTo(old) <= 0) { siftUp(i, e); } else { siftDown(i, e); } } return old; } @SuppressWarnings("unchecked") private void grow(int minCapacity) { if (minCapacity < 0) { throw new OutOfMemoryError(); } int oldCapacity = array.length; int newCapacity = oldCapacity + (oldCapacity >> 1); newCapacity = (newCapacity < 0) ? Integer.MAX_VALUE : Math.max(minCapacity, newCapacity); Entry<K, V>[] resized = new Entry[newCapacity]; System.arraycopy(array, 0, resized, 0, size); array = resized; } private static class Entry<K, V> { final K key; V value; Entry(K key, V value) { this.key = key; this.value = value; } } }
package ibis.satin.impl.loadBalancing; import ibis.ipl.IbisIdentifier; import ibis.ipl.ReadMessage; import ibis.ipl.SendPortIdentifier; import ibis.satin.impl.Config; import ibis.satin.impl.Satin; import ibis.satin.impl.spawnSync.IRVector; import ibis.satin.impl.spawnSync.InvocationRecord; import ibis.satin.impl.spawnSync.ReturnRecord; import ibis.satin.impl.spawnSync.Stamp; import java.io.IOException; import java.util.ArrayList; public class LoadBalancing implements Config { static final class StealRequest { int opcode; SendPortIdentifier sp; } final class StealRequestHandler extends Thread { static final boolean CONTINUOUS_STATS = false; static final long CONTINUOUS_STATS_INTERVAL = 60 * 1000; public StealRequestHandler() { setDaemon(true); setName("Satin StealRequestHandler"); } public void run() { long lastPrintTime = 0; if (CONTINUOUS_STATS) { lastPrintTime = System.currentTimeMillis(); } while (true) { if (CONTINUOUS_STATS && System.currentTimeMillis() - lastPrintTime > CONTINUOUS_STATS_INTERVAL) { lastPrintTime = System.currentTimeMillis(); s.stats.printDetailedStats(s.ident); s.comm.ibis.printStatistics(System.out); } StealRequest sr = null; synchronized (stealQueue) { if (stealQueue.size() > 0) { sr = stealQueue.remove(0); } else { try { stealQueue.wait(); } catch (Exception e) { // ignore } continue; } } // don't hold lock while sending reply lbComm.handleStealRequest(sr.sp, sr.opcode); } } } private LBCommunication lbComm; private Satin s; private volatile boolean receivedResults = false; /** Used to store reply messages. */ private volatile boolean gotStealReply = false; private InvocationRecord stolenJob = null; private final IRVector resultList; private final ArrayList<StealRequest> stealQueue; /** * Used for fault tolerance, we must know who the current victim is, * in case it crashes. */ private IbisIdentifier currentVictim = null; public LoadBalancing(Satin s) { this.s = s; if (QUEUE_STEALS) { stealQueue = new ArrayList<StealRequest>(); new StealRequestHandler().start(); } else { stealQueue = null; } resultList = new IRVector(s); lbComm = new LBCommunication(s, this); } public void gotJobResult(InvocationRecord ir, IbisIdentifier sender) { synchronized (s) { // This might be a job that came in after a STEAL_WAIT_TIMEOUT. // If this is the case, this job has to be added to the queue, // it is not the result of the current steal request. if (!sender.equals(currentVictim)) { ftLogger.warn("SATIN '" + s.ident + "': received a job from " + sender + " who caused a timeout before."); if (ir != null) { s.q.addToTail(ir); } return; } gotStealReply = true; stolenJob = ir; currentVictim = null; s.notifyAll(); } } public void addToOutstandingJobList(InvocationRecord r) { Satin.assertLocked(s); s.outstandingJobs.add(r); } /** * does a synchronous steal. If blockOnServer is true, it blocks on server * side until work is available, or we must exit. This is used in * MasterWorker algorithms. */ public InvocationRecord stealJob(Victim v, boolean blockOnServer) { if (ASSERTS && stolenJob != null) { throw new Error( "EEEK, trying to steal while an unhandled stolen job is available."); } if (s.exiting) return null; synchronized (s) { if (s.comm.paused) { long start = System.currentTimeMillis(); while (s.comm.paused) { try { s.wait(); // soBcastLogger.info("currently paused, waiting"); } catch (Exception e) { // ignore } } long end = System.currentTimeMillis(); System.err.println("paused for " + (end - start) + " ms"); } } s.stats.stealTimer.start(); s.stats.stealAttempts++; try { lbComm.sendStealRequest(v, true, blockOnServer); return waitForStealReply(); } catch (IOException e) { ftLogger.info("SATIN '" + s.ident + "': got exception during steal request", e); return null; } finally { s.stats.stealTimer.stop(); } } public void handleDelayedMessages() { if (!receivedResults) return; synchronized (s) { while (true) { InvocationRecord r = resultList.removeIndex(0); if (r == null) { break; } if (r.eek != null) { s.aborts.handleInlet(r); } r.decrSpawnCounter(); if (!FT_NAIVE) { r.jobFinished(); } } receivedResults = false; } } private void waitForStealReplyMessage() { long start = System.currentTimeMillis(); while (true) { synchronized (s) { boolean gotTimeout = System.currentTimeMillis() - start >= STEAL_WAIT_TIMEOUT; if (gotTimeout && !gotStealReply) { ftLogger .warn("SATIN '" + s.ident + "': a timeout occurred while waiting for a steal reply, timeout = " + STEAL_WAIT_TIMEOUT / 1000 + " seconds."); } // At least handle aborts! Otherwise an older abort // can kill a job that was stolen later. s.aborts.handleDelayedMessages(); if (gotStealReply || gotTimeout) { // Immediately reset gotStealReply, a reply has arrived. gotStealReply = false; s.currentVictimCrashed = false; return; } if (s.currentVictimCrashed) { s.currentVictimCrashed = false; ftLogger.debug("SATIN '" + s.ident + "': current victim crashed"); return; } if (s.exiting) { return; } if (!HANDLE_MESSAGES_IN_LATENCY) { // a normal blocking steal try { s.wait(500); } catch (InterruptedException e) { // ignore } } } if (HANDLE_MESSAGES_IN_LATENCY) { s.handleDelayedMessages(); // Thread.yield(); } } } private InvocationRecord waitForStealReply() { waitForStealReplyMessage(); /* If successfull, we now have a job in stolenJob. */ if (stolenJob == null) { return null; } /* I love it when a plan comes together! We stole a job. */ s.stats.stealSuccess++; InvocationRecord myJob = stolenJob; stolenJob = null; return myJob; } private void addToJobResultList(InvocationRecord r) { Satin.assertLocked(s); resultList.add(r); } private InvocationRecord getStolenInvocationRecord(Stamp stamp) { Satin.assertLocked(s); return s.outstandingJobs.remove(stamp); } protected void addJobResult(ReturnRecord rr, Throwable eek, Stamp stamp) { synchronized (s) { receivedResults = true; InvocationRecord r = null; if (rr != null) { r = getStolenInvocationRecord(rr.getStamp()); } else { r = getStolenInvocationRecord(stamp); } if (r != null) { if (rr != null) { rr.assignTo(r); } else { r.eek = eek; } if (r.eek != null) { // we have an exception, add it to the list. // the list will be read during the sync s.aborts.addToExceptionList(r); } else { addToJobResultList(r); } } else { abortLogger.debug("SATIN '" + s.ident + "': got result for aborted job, ignoring."); } } } // throws an IO exception when the ibis that tried to steal the job dies protected InvocationRecord stealJobFromLocalQueue(SendPortIdentifier ident, boolean blocking) throws IOException { InvocationRecord result = null; while (true) { result = s.q.getFromTail(); if (result != null) { result.setStealer(ident.ibisIdentifier()); // store the job in the outstanding list addToOutstandingJobList(result); return result; } if (!blocking || s.exiting) { return null; // the steal request failed } try { s.wait(); } catch (Exception e) { // Ignore. } Victim v = s.victims.getVictim(ident.ibisIdentifier()); if (v == null) { throw new IOException("the stealing ibis died"); } } } public void sendResult(InvocationRecord r, ReturnRecord rr) { lbComm.sendResult(r, rr); } public void handleStealRequest(SendPortIdentifier ident, int opcode) { lbComm.handleStealRequest(ident, opcode); } public void queueStealRequest(SendPortIdentifier ident, int opcode) { StealRequest r = new StealRequest(); r.opcode = opcode; r.sp = ident; synchronized (stealQueue) { stealQueue.add(r); stealQueue.notifyAll(); } } public void handleReply(ReadMessage m, int opcode) { lbComm.handleReply(m, opcode); } public void handleJobResult(ReadMessage m, int opcode) { lbComm.handleJobResult(m, opcode); } public void sendStealRequest(Victim v, boolean synchronous, boolean blocking) throws IOException { lbComm.sendStealRequest(v, synchronous, blocking); } /** * Used for fault tolerance, we must know who the current victim is, * in case it crashes. */ public IbisIdentifier getCurrentVictim() { return currentVictim; } public void setCurrentVictim(IbisIdentifier ident) { if (stealLogger.isDebugEnabled()) { stealLogger.debug("setCurrentVictim: " + ident); } currentVictim = ident; } }
package no.kantega.publishing.common; import javax.swing.text.AttributeSet; import javax.swing.text.MutableAttributeSet; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.parser.ParserDelegator; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Enumeration; public class StripHTML extends HTMLEditorKit.ParserCallback { private StringBuffer sb; private String tag = null; private boolean skipTags = true; private boolean all = false; private boolean checkedStart = false; private boolean checkedEnd = false; public StripHTML() { sb = new StringBuffer(); } public String convert(String html) { Reader in = new StringReader(html); try { this.parse(in); } catch (Exception e) { } finally { try { in.close(); } catch (IOException e) { } } return this.getText(); } public void parse(Reader in) throws IOException { ParserDelegator delegator = new ParserDelegator(); delegator.parse(in, this, Boolean.TRUE); } private boolean skipTag(HTML.Tag t) { if (!skipTags) return false; return (t == HTML.Tag.HTML || t == HTML.Tag.HEAD || t == HTML.Tag.BODY); } @Override public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) { if (skipTag(t)) return; if (checkedStart && !all) { sb.append("<").append(t.toString()).append(getAttributes(a)).append(">"); return; // only strip first tag } if (t.toString().equals(tag)) { checkedStart = true; } else { sb.append("<").append(t.toString()).append(getAttributes(a)).append(">"); } } @Override public void handleEndTag(HTML.Tag t, int pos) { if (skipTag(t)) return; if (checkedEnd && !all) { sb.append("</" + t.toString() + ">"); return; } if (t.toString().equals(tag)) { checkedEnd = true; } else { sb.append("</" + t.toString() + ">"); } } @Override public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) { if (t.toString().equals(tag)) { // do nothing } else { sb.append("<").append(t.toString()).append(getAttributes(a)).append(">"); } } @Override public void handleText(char[] text, int pos) { sb.append(text); } public String getText() { return sb.toString(); } public void clear() { sb.setLength(0); } public void setTag(String tag) { this.tag = tag; } public void setAll(boolean all) { this.all = all; } public void setSkipTags(boolean skipTags) { this.skipTags = skipTags; } private String getAttributes(AttributeSet attributes) { StringBuffer retValue = new StringBuffer(); Enumeration e = attributes.getAttributeNames(); while (e.hasMoreElements()) { Object name = e.nextElement(); String value = (String) attributes.getAttribute(name); retValue.append(" ").append(name).append("=").append("\"").append(value).append("\""); } return retValue.toString(); } public static void main(String args[]) { StripHTML parser = new StripHTML(); String html = "<p><a href=\"#\">link</a></p>"; parser.tag = "p"; parser.all = false; System.out.println(parser.convert(html)); html = "<p>Dette er en test<br><ul class=\"klassebold klasseselected\"><li>1</li><li>2</li></ul><p>paragraf</p></p>"; parser.clear(); parser.tag = "p"; parser.all = false; System.out.println(parser.convert(html)); parser.clear(); parser.all = true; System.out.println(parser.convert(html)); parser.clear(); parser.all = false; parser.setSkipTags(false); System.out.println(parser.convert(html)); } }
package ibis.satin.impl.sharedObjects; import ibis.ipl.IbisIdentifier; import ibis.ipl.ReadMessage; import ibis.satin.SharedObject; import ibis.satin.impl.Config; import ibis.satin.impl.Satin; import ibis.satin.impl.spawnSync.InvocationRecord; import java.util.HashMap; import java.util.Vector; class SharedObjectInfo { long lastBroadcastTime; IbisIdentifier[] destinations; SharedObject sharedObject; } public final class SharedObjects implements Config { /* use these to avoid locking */ protected volatile boolean gotSORequests = false; protected boolean receivingMcast = false; /** List that stores requests for shared object transfers */ protected SORequestList SORequestList = new SORequestList(); /** Used for storing pending shared object invocations (SOInvocationRecords) */ private Vector<SOInvocationRecord> soInvocationList = new Vector<SOInvocationRecord>(); private Satin s; /** A hash containing all shared objects: * (String objectID, SharedObject object) */ private HashMap<String, SharedObjectInfo> sharedObjects = new HashMap<String, SharedObjectInfo>(); private SOCommunication soComm; public SharedObjects(Satin s) { this.s = s; soComm = new SOCommunication(s); soComm.init(); } /** Add an object to the object table */ public void addObject(SharedObject object) { SharedObjectInfo i = new SharedObjectInfo(); i.sharedObject = object; synchronized (s) { sharedObjects.put(object.getObjectId(), i); } // notify waiters (see waitForObject) synchronized (soInvocationList) { soInvocationList.notifyAll(); } soLogger.debug("SATIN '" + s.ident + "': " + "object added, id = " + object.getObjectId()); } /** Return a reference to a shared object */ public SharedObject getSOReference(String objectId) { synchronized (s) { s.stats.getSOReferencesTimer.start(); try { SharedObjectInfo i = sharedObjects.get(objectId); if (i == null) { soLogger.debug("SATIN '" + s.ident + "': " + "object not found in getSOReference"); return null; } return i.sharedObject; } finally { s.stats.getSOReferencesTimer.stop(); } } } /** Return a reference to a shared object */ public SharedObjectInfo getSOInfo(String objectId) { synchronized (s) { return sharedObjects.get(objectId); } } void registerMulticast(SharedObject object, IbisIdentifier[] destinations) { synchronized (s) { SharedObjectInfo i = sharedObjects.get(object.getObjectId()); if (i == null) { soLogger.warn("OOPS, object not found in registerMulticast"); return; } i.destinations = destinations; i.lastBroadcastTime = System.currentTimeMillis(); } } /** * Execute all the so invocations stored in the so invocations list */ private void handleSOInvocations() { while (true) { SOInvocationRecord soir; synchronized (soInvocationList) { if (soInvocationList.size() == 0) { return; } soir = soInvocationList.remove(0); } s.stats.handleSOInvocationsTimer.start(); SharedObject so = getSOReference(soir.getObjectId()); if (so == null) { s.stats.handleSOInvocationsTimer.stop(); return; } // No need to hold the satin lock here. // Object transfer requests cannot be handled // in the middle of a method invocation, // as transfers are delayed until a safe point is // reached soir.invoke(so); s.stats.handleSOInvocationsTimer.stop(); } } /** * Check if the given shared object is in the table, if not, ship it from * source. This is called from the generated code. */ public void setSOReference(String objectId, IbisIdentifier source) throws SOReferenceSourceCrashedException { s.handleDelayedMessages(); SharedObject obj = getSOReference(objectId); if (obj == null) { if (source == null) { throw new Error( "internal error, source is null in setSOReference"); } soComm.fetchObject(objectId, source, null); } } /** * Add a shared object invocation record to the so invocation record list; * the invocation will be executed later */ public void addSOInvocation(SOInvocationRecord soir) { SharedObject so = getSOReference(soir.getObjectId()); if (so == null) { // we don't have the object. Drop the invocation. return; } synchronized (soInvocationList) { soInvocationList.add(soir); soInvocationList.notifyAll(); } } /** returns false if the job must be aborted */ public boolean executeGuard(InvocationRecord r) { s.stats.soGuardTimer.start(); try { doExecuteGuard(r); } catch (SOReferenceSourceCrashedException e) { //the source has crashed - abort the job return false; } finally { s.stats.soGuardTimer.stop(); } return true; } /** * Execute the guard of the invocation record r, wait for updates, if * necessary, ship objects if necessary */ private void doExecuteGuard(InvocationRecord r) throws SOReferenceSourceCrashedException { // restore shared object references if (!FT_NAIVE && r.isOrphan()) { // If the owner of the invocation is dead, replace by its replacer. IbisIdentifier owner = s.ft.lookupOwner(r); if (ASSERTS && owner == null) { grtLogger.fatal("SATIN '" + s.ident + "': orphan not locked in the table"); System.exit(1); // Failed assertion } r.setOwner(owner); r.setOrphan(false); } r.setSOReferences(); if (r.guard()) return; soLogger.info("SATIN '" + s.ident + "': " + "guard not satisfied, getting updates.."); // try to ship the object(s) from the owner of the job Vector<String> objRefs = r.getSOReferences(); if (objRefs == null || objRefs.isEmpty()) { soLogger.fatal("SATIN '" + s.ident + "': " + "a guard is not satisfied, but the spawn does not " + "have shared objects.\n" + "This is not a correct Satin program."); System.exit(1); } // A shared object update may have arrived // during one of the fetches. while (true) { s.handleDelayedMessages(); if (r.guard()) { return; } String ref = objRefs.remove(0); soComm.fetchObject(ref, r.getOwner(), r); } } public void addToSORequestList(IbisIdentifier requester, String objID, boolean demand) { Satin.assertLocked(s); SORequestList.add(requester, objID, demand); gotSORequests = true; } public void handleDelayedMessages() { if (gotSORequests) { soComm.handleSORequests(); } handleSOInvocations(); soComm.sendAccumulatedSOInvocations(); } public void handleSORequest(ReadMessage m, boolean demand) { soComm.handleSORequest(m, demand); } public void handleSOTransfer(ReadMessage m) { soComm.handleSOTransfer(m); } public void handleSONack(ReadMessage m) { soComm.handleSONack(m); } public void handleJoins(IbisIdentifier[] joiners) { soComm.handleJoins(joiners); } public void handleMyOwnJoin() { soComm.handleMyOwnJoin(); } public void removeSOConnection(IbisIdentifier id) { soComm.removeSOConnection(id); } public void broadcastSOInvocation(SOInvocationRecord r) { SharedObject so = getSOReference(r.getObjectId()); if (so != null && so.isUnshared()) { // Write method invoked while object is not shared yet. // Don't broadcast: noone has the object yet. soLogger.debug("No broadcast from writeMethod: object " + r.getObjectId() + " is not shared yet"); return; } soComm.broadcastSOInvocation(r); } public void broadcastSharedObject(SharedObject object) { soComm.broadcastSharedObject(object); } public void handleCrash(IbisIdentifier id) { soComm.handleCrash(id); } public void exit() { soComm.exit(); } boolean waitForObject(String objectId, IbisIdentifier source, InvocationRecord r, long timeout) { long start = System.currentTimeMillis(); while (true) { if (System.currentTimeMillis() - start > timeout) return false; synchronized (soInvocationList) { try { soInvocationList.wait(500); } catch (InterruptedException e) { // Ignore } } s.handleDelayedMessages(); if (r == null) { if (s.so.getSOInfo(objectId) != null) { soLogger.debug("SATIN '" + s.ident + "': received new object from a bcast"); return true; // got it! } } else { if (r.guard()) { soLogger.debug("SATIN '" + s.ident + "': received object, guard satisfied"); return true; } } } } }
package io.liveoak.spi.state; import java.net.URI; import java.net.URISyntaxException; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.IllegalFormatException; import java.util.List; import java.util.Set; /** * Opaque state of a resource. * * <p>State objects are used to instill new state into a server-side resource.</p> * * @author Bob McWhirter */ public interface ResourceState { /** * Retrieve the ID of the resource. * * @return The ID of the resource. */ String id(); /** * Set the ID of the resource. * * @param id The ID of the resource. */ void id(String id); void uri(URI uri); default URI uri() { ResourceState self = getPropertyAsResourceState("self"); if (self == null) { return null; } Object href = self.getProperty("href"); if (href == null) { return null; } if (href instanceof URI) { return (URI) href; } try { return new URI(String.valueOf(href)); } catch (URISyntaxException e) { throw new RuntimeException("Invalid self/href: " + href); } } /** * Add a property to the state. * * <p>Property values may be either simple scalar * values, or complex {@link ResourceState} objects</p> * * @param name The name of the property. * @param value The value of the property. */ void putProperty(String name, Object value); /** * Retrieve a property value. * * @param name The property name. * @return The value of the property, as either a simple scalar, or as a * more complex {@link ResourceState}. */ Object getProperty(String name); /** * Retreive a property value as String * * @param name The property name. * @return The value of the property, as a String * @throw RuntimeException if value of the named property is not a String */ default String getPropertyAsString(String name) { Object val = getProperty(name); if (val == null) { return null; } if (val instanceof String || val instanceof Number || val instanceof Boolean) { return String.valueOf(val); } throw new RuntimeException("Value can't be returned as String: " + val + " [" + val.getClass() + "]"); } default Integer getPropertyAsInteger(String name) { Object val = getProperty(name); if (val == null) { return null; } if (val instanceof Integer || val instanceof Long || val instanceof Short) { return ((Number) val).intValue(); } if (val instanceof String) { return Integer.valueOf((String) val); } throw new RuntimeException("Value can't be returned as Integer: " + val + " [" + val.getClass() + "]"); } default Long getPropertyAsLong(String name) { Object val = getProperty(name); if (val == null) { return null; } if (val instanceof Integer || val instanceof Long || val instanceof Short) { return ((Number) val).longValue(); } if (val instanceof String) { return Long.valueOf((String) val); } throw new RuntimeException("Value can't be returned as Long: " + val + " [" + val.getClass() + "]"); } default Boolean getPropertyAsBoolean(String name) { Object val = getProperty(name); if (val == null) { return null; } if (val instanceof Boolean) { return ((Boolean) val).booleanValue(); } if (val instanceof String) { return Boolean.valueOf((String) val); } throw new RuntimeException("Value can't be returned as Boolean: " + val + " [" + val.getClass() + "]"); } default Date getPropertyAsDate(String name) { Object val = getProperty(name); if (val == null) { return null; } if (val instanceof Date || val instanceof Timestamp) { return (Date) val; } if (val instanceof Calendar) { return ((Calendar) val).getTime(); } if (val instanceof Long) { return new Date(((Long) val).longValue()); } if (val instanceof String) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); try { return sdf.parse((String) val); } catch (Exception ignored) {} } throw new RuntimeException("Value can't be returned as Date: " + val + " [" + val.getClass() + "]"); } default boolean isListPropertyOrNull(String name) { Object val = getProperty(name); return val == null || val instanceof List; } default List getPropertyAsList(String name) { Object val = getProperty(name); if (val == null) { return null; } if (val instanceof List) { return (List) val; } ArrayList ret = new ArrayList(); ret.add(val); return ret; } default ResourceState getPropertyAsResourceState(String name) { Object val = getProperty(name); if (val == null) { return null; } if (val instanceof ResourceState) { return (ResourceState) val; } throw new RuntimeException("Value can't be returned as ResourceState: " + val + " [" + val.getClass() + "]"); } Object removeProperty(String name); Set<String> getPropertyNames(); void addMember(ResourceState member); List<ResourceState> members(); }
package com.jcwhatever.nucleus.npc.traits; import com.jcwhatever.nucleus.Nucleus; import com.jcwhatever.nucleus.collections.players.PlayerSet; import com.jcwhatever.nucleus.providers.npc.INpc; import com.jcwhatever.nucleus.providers.npc.INpcProvider; import com.jcwhatever.nucleus.providers.npc.ai.goals.INpcGoals; import com.jcwhatever.nucleus.providers.npc.navigator.INpcNav; import com.jcwhatever.nucleus.providers.npc.traits.NpcTrait; import com.jcwhatever.nucleus.providers.npc.traits.NpcTraitType; import com.jcwhatever.nucleus.utils.PreCon; import com.jcwhatever.nucleus.utils.entity.EntityUtils; import com.jcwhatever.nucleus.utils.validate.IValidator; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import java.util.Set; import javax.annotation.Nullable; /** * The NPC that automatically attacks nearby players. * * <p>Players can be whitelisted or blacklisted from attacks.</p> * * <p>Trait is registered with the lookup name "NpcTraitPack:Aggressive"</p> */ public class AggressiveTrait extends NpcTraitType { @Override public Plugin getPlugin() { return NpcTraitPack.getPlugin(); } @Override public String getName() { return "Aggressive"; } @Override protected Aggressive createTrait(INpc npc) { return new Aggressive(npc, this); } public static class Aggressive extends NpcTrait implements Runnable { private boolean _isWhitelist; private Set<Player> _filter; private LivingEntity _target; private boolean _isEnabled = true; /** * Constructor. * * @param npc The NPC the trait is for. * @param type The parent type that instantiated the trait. */ Aggressive(INpc npc, NpcTraitType type) { super(npc, type); } /** * Determine if the trait is enabled. */ public boolean isEnabled() { return _isEnabled; } /** * Set the enabled state. * * @param isEnabled True to enable, otherwise false. * * @return Self for chaining. */ public Aggressive setEnabled(boolean isEnabled) { _isEnabled = isEnabled; if (_target != null) { getNpc().getNavigator().cancel(); _target = null; } return this; } /** * Set the target filter policy to whitelist mode. */ public Aggressive whiteList() { _isWhitelist = true; return this; } /** * Set the target filter policy to blacklist mode. */ public Aggressive blackList() { _isWhitelist = false; return this; } /** * Whitelist or blacklist a player as a valid target of aggression. * * @param player The player. * * @return Self for chaining. */ public Aggressive addFilter(Player player) { if (_filter == null) { _filter = new PlayerSet(getType().getPlugin(), 10); } _filter.add(player); return this; } /** * Remove a player from the pool of valid/invalid target players. * * @param player The player. * * @return Self for chaining. */ public Aggressive removeFilter(Player player) { if (_filter != null) _filter.remove(player); return this; } /** * Clear all target filters. */ public Aggressive clearFilters() { if (_filter != null) _filter.clear(); return this; } /** * Determine if the current target filter and filter policy would allow * the specified player to be attacked. * * @param player The player to check. */ public boolean canAttack(Player player) { PreCon.notNull(player); return _isWhitelist ? _filter != null && _filter.contains(player) : _filter == null || !_filter.contains(player); } /** * Manually set a target. * * @param target The target of aggression. * * @return Self for chaining. */ public Aggressive setTarget(@Nullable Entity target) { if (!getNpc().isSpawned()) return this; Entity currentTarget = getTarget(); if (target == currentTarget) return this; if (target instanceof Player && !canAttack((Player)target)) return this; INpcNav navigator = getNpc().getNavigator(); INpcGoals goals = getNpc().getGoals(); goals.pause(); INpc vehicle = getNpc().getNPCVehicle(); if (vehicle != null && vehicle.isSpawned()) { vehicle.getNavigator() .setHostile(true) .setTarget(target); } navigator.setHostile(true).setTarget(target); goals.pause(); return this; } /** * Get the current target of aggression. * * @return The {@link org.bukkit.entity.Entity} or null if there is no target. */ @Nullable public Entity getTarget() { if (!getNpc().isSpawned()) return null; return getNpc().getNavigator().getTargetEntity(); } @Override public void run() { if (!_isEnabled || !getNpc().isSpawned()) return; if (_target == null || _target.isDead() || !_target.isValid()) { final INpcProvider provider = Nucleus.getProviderManager().getNpcProvider(); assert provider != null; _target = EntityUtils.getClosestLivingEntity(getNpc().getEntity(), 16, new IValidator<LivingEntity>() { @Override public boolean isValid(LivingEntity entity) { return entity instanceof Player && canAttack((Player) entity) && !provider.isNpc(entity); } }); if (_target == null) return; setTarget(_target); } getNpc().lookAt(_target); INpc vehicle = getNpc().getNPCVehicle(); if (vehicle != null) { vehicle.lookAt(_target); } if (!getNpc().getNavigator().isRunning()) { setTarget(_target); } } } }
package it.unimi.dsi.sux4j.mph; import static it.unimi.dsi.bits.Fast.log2; import static it.unimi.dsi.sux4j.mph.HypergraphSorter.GAMMA; import it.unimi.dsi.Util; import it.unimi.dsi.bits.BitVector; import it.unimi.dsi.bits.BitVectors; import it.unimi.dsi.bits.Fast; import it.unimi.dsi.bits.LongArrayBitVector; import it.unimi.dsi.bits.TransformationStrategies; import it.unimi.dsi.bits.TransformationStrategy; import it.unimi.dsi.fastutil.ints.IntArrayList; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import it.unimi.dsi.fastutil.longs.LongArrayList; import it.unimi.dsi.fastutil.objects.AbstractObject2LongFunction; import it.unimi.dsi.fastutil.objects.ObjectArrayList; import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet; import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet; import it.unimi.dsi.io.OfflineIterable; import it.unimi.dsi.lang.MutableString; import it.unimi.dsi.logging.ProgressLogger; import it.unimi.dsi.sux4j.bits.Rank9; import it.unimi.dsi.sux4j.io.ChunkedHashStore; import it.unimi.dsi.util.LongBigList; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import org.apache.log4j.Logger; /** A distributor based on a z-fast trie. * */ public class ZFastTrieDistributor<T> extends AbstractObject2LongFunction<T> { private final static Logger LOGGER = Util.getLogger( ZFastTrieDistributor.class ); private static final long serialVersionUID = 1L; private static final boolean DEBUG = false; private static final boolean DDEBUG = false; private static final boolean DDDEBUG = false; private static final boolean ASSERTS = true; /** An integer representing the exit-on-the-left behaviour. */ private final static int LEFT = 0; /** An integer representing the exit-on-the-right behaviour. */ private final static int RIGHT = 1; /** A ranking structure on the vector containing leaves plus p0,p1, etc. */ private final Rank9 leaves; /** The transformation used to map object to bit vectors. */ private final TransformationStrategy<? super T> transformationStrategy; /** For each external node and each possible path, the related behaviour. */ private final MWHCFunction<BitVector> behaviour; /** The number of elements of the set upon which the trie is built. */ private final int size; private MWHCFunction<BitVector> signatures; private TwoStepsLcpMonotoneMinimalPerfectHashFunction<BitVector> ranker; private long logWMask; private int logW; private long signatureMask; private int numDelimiters; private IntOpenHashSet mistakeSignatures; private MWHCFunction<BitVector> corrections; /** Whether the underlying probabilistic trie is empty. */ private boolean emptyTrie; /** Whether there are no delimiters. */ private boolean noDelimiters; private long seed; /** An intermediate class containing the compacted trie generated by the delimiters. */ private final static class IntermediateTrie<T> { /** The root of the trie. */ protected final Node root; /** The number of elements of the set upon which the trie is built. */ protected final int numElements; /** The values associated to the keys in {@link #externalKeysFile}. */ private LongBigList externalValues; /** The string representing the parent of each key in {@link #externalKeysFile}. */ private IntArrayList externalParentRepresentations; private long w; private int logW; private int logLogW; private long logWMask; private int signatureSize; private long signatureMask; private OfflineIterable<BitVector, LongArrayBitVector> internalNodeKeys; private OfflineIterable<BitVector, LongArrayBitVector> internalNodeRepresentations; private LongBigList internalNodeSignatures; private ObjectLinkedOpenHashSet<BitVector> delimiters; private ObjectLinkedOpenHashSet<BitVector> leaves; /** A node in the trie. */ private static class Node { /** Left child. */ private Node left; /** Right child. */ private Node right; /** The path compacted in this node (<code>null</code> if there is no compaction at this node). */ private final LongArrayBitVector path; /** Creates a node. * * @param left the left child. * @param right the right child. * @param path the path compacted at this node. */ public Node( final Node left, final Node right, final LongArrayBitVector path ) { this.left = left; this.right = right; this.path = path; } /** Returns true if this node is a leaf. * * @return true if this node is a leaf. */ public boolean isLeaf() { return right == null && left == null; } public String toString() { return "[" + path + "]"; } } void labelIntermediateTrie( final Node node, final LongArrayBitVector path, final ObjectLinkedOpenHashSet<BitVector> delimiters, final OfflineIterable<BitVector, LongArrayBitVector> representations, final OfflineIterable<BitVector, LongArrayBitVector> keys, final LongBigList internalNodeSignatures, final long seed, final boolean left ) throws IOException { if ( ASSERTS ) assert ( node.left != null ) == ( node.right != null ); long parentPathLength = Math.max( 0, path.length() - 1 ); if ( node.left != null ) { path.append( node.path ); labelIntermediateTrie( node.left, path.append( 0, 1 ), delimiters, representations, keys, internalNodeSignatures, seed, true ); path.remove( (int)( path.length() - 1 ) ); final long h = Hashes.jenkins( path, seed ); final long p = ( -1L << Fast.mostSignificantBit( parentPathLength ^ path.length() ) & path.length() ); if ( ASSERTS ) assert p <= path.length() : p + " > " + path.length(); if ( ASSERTS ) assert path.length() == 0 || p > parentPathLength : p + " <= " + parentPathLength; keys.add( LongArrayBitVector.copy( path.subVector( 0, p ) ) ); representations.add( path.copy() ); if ( ASSERTS ) assert Fast.length( path.length() ) <= logW; if ( DDDEBUG ) System.err.println( "Entering " + path + " with key (" + p + "," + path.subVector( 0, p ).hashCode() + ") " + path.subVector( 0, p ) + ", signature " + ( h & signatureMask ) + " and length " + ( path.length() & logWMask ) + "(value: " + (( h & signatureMask ) << logW | ( path.length() & logWMask )) + ")" ); internalNodeSignatures.add( ( h & signatureMask ) << logW | ( path.length() & logWMask ) ); labelIntermediateTrie( node.right, path.append( 1, 1 ), delimiters, representations, keys, internalNodeSignatures, seed, false ); path.length( path.length() - node.path.length() - 1 ); } else { if ( left ) delimiters.add( LongArrayBitVector.copy( path.subVector( 0, path.lastOne() + 1 ) ) ); else delimiters.add( LongArrayBitVector.copy( path ) ); } } public IntermediateTrie( final Iterable<? extends T> elements, final int log2BucketSize, final TransformationStrategy<? super T> transformationStrategy, final long seed ) throws IOException { Iterator<? extends T> iterator = elements.iterator(); final long bucketSizeMask = ( 1L << log2BucketSize ) - 1; final ProgressLogger pl = new ProgressLogger( LOGGER ); pl.itemsName = "keys"; pl.displayFreeMemory = true; leaves = DDEBUG ? new ObjectLinkedOpenHashSet<BitVector>() : null; if ( iterator.hasNext() ) { pl.start( "Building trie..." ); LongArrayBitVector prev = LongArrayBitVector.copy( transformationStrategy.toBitVector( iterator.next() ) ); pl.lightUpdate(); LongArrayBitVector prevDelimiter = LongArrayBitVector.getInstance(); Node node, root = null; BitVector curr; int pos, prefix, count = 1; long maxLength = prev.length(); while( iterator.hasNext() ) { // Check order curr = transformationStrategy.toBitVector( iterator.next() ).fast(); pl.lightUpdate(); prefix = (int)curr.longestCommonPrefixLength( prev ); if ( prefix == prev.length() && prefix == curr.length() ) throw new IllegalArgumentException( "The input bit vectors are not distinct" ); if ( prefix == prev.length() || prefix == curr.length() ) throw new IllegalArgumentException( "The input bit vectors are not prefix-free" ); if ( prev.getBoolean( prefix ) ) throw new IllegalArgumentException( "The input bit vectors are not lexicographically sorted" ); if ( ( count & bucketSizeMask ) == 0 ) { // Found delimiter. Insert into trie. if ( root == null ) { root = new Node( null, null, prev.copy() ); if ( DDEBUG ) leaves.add( prev.copy() ); prevDelimiter.replace( prev ); } else { prefix = (int)prev.longestCommonPrefixLength( prevDelimiter ); pos = 0; node = root; Node n = null; while( node != null ) { final long pathLength = node.path.length(); if ( prefix < pathLength ) { n = new Node( node.left, node.right, node.path.copy( prefix + 1, pathLength ) ); node.path.length( prefix ); node.path.trim(); node.left = n; node.right = new Node( null, null, prev.copy( pos + prefix + 1, prev.length() ) ); break; } prefix -= pathLength + 1; pos += pathLength + 1; node = node.right; if ( ASSERTS ) assert node == null || prefix >= 0 : prefix + " <= " + 0; } if ( ASSERTS ) assert node != null; if ( DDEBUG ) leaves.add( prev.copy() ); prevDelimiter.replace( prev ); } } prev.replace( curr ); maxLength = Math.max( maxLength, prev.length() ); count++; } pl.done(); numElements = count; logLogW = Fast.ceilLog2( Fast.ceilLog2( maxLength ) ); logW = 1 << logLogW; w = 1L << logW; logWMask = ( 1L << logW ) - 1; signatureSize = logLogW + log2BucketSize; signatureMask = ( 1L << signatureSize ) - 1; if ( ASSERTS ) assert logW + signatureSize <= Long.SIZE; this.root = root; if ( DEBUG ) System.err.println( "w: " + w ); if ( DDEBUG ) { System.err.println( "Leaves (" + leaves.size() + "): " + leaves ); System.err.println( this ); } internalNodeRepresentations = new OfflineIterable<BitVector, LongArrayBitVector>( BitVectors.OFFLINE_SERIALIZER, LongArrayBitVector.getInstance() ); if ( root != null ) { LOGGER.info( "Computing approximate structure..." ); internalNodeSignatures = LongArrayBitVector.getInstance().asLongBigList( logW + signatureSize ); internalNodeKeys = new OfflineIterable<BitVector, LongArrayBitVector>( BitVectors.OFFLINE_SERIALIZER, LongArrayBitVector.getInstance() ); delimiters = new ObjectLinkedOpenHashSet<BitVector>(); labelIntermediateTrie( root, LongArrayBitVector.getInstance(), delimiters, internalNodeRepresentations, internalNodeKeys, internalNodeSignatures, seed, true ); if ( DDEBUG ) { System.err.println( "Delimiters (" + delimiters.size() + "): " + delimiters ); Iterator<BitVector> d = delimiters.iterator(), l = leaves.iterator(); for( int i = 0; i < delimiters.size(); i++ ) { BitVector del = d.next(), leaf = l.next(); assert del.longestCommonPrefixLength( leaf ) == del.length() : del.longestCommonPrefixLength( leaf ) + " != " + del.length() + "\n" + del + "\n" + leaf + "\n"; } assert ! l.hasNext(); System.err.println( "Internal node representations: " + internalNodeRepresentations ); System.err.println( "Internal node signatures: " + internalNodeSignatures ); } pl.start( "Computing function keys..." ); externalValues = LongArrayBitVector.getInstance().asLongBigList( 1 ); externalParentRepresentations = new IntArrayList( numElements ); iterator = elements.iterator(); // The stack of nodes visited the last time final Node stack[] = new Node[ (int)maxLength ]; // The length of the path compacted in the trie up to the corresponding node, excluded final int[] len = new int[ (int)maxLength ]; stack[ 0 ] = root; int depth = 0, behaviour, c = 0; boolean first = true; BitVector currFromPos, path; LongArrayBitVector nodePath; while( iterator.hasNext() ) { curr = transformationStrategy.toBitVector( iterator.next() ).fast(); pl.lightUpdate(); if ( DDDEBUG ) System.err.println( "Analysing key " + curr + "..." ); if ( ! first ) { // Adjust stack using lcp between present string and previous one prefix = (int)prev.longestCommonPrefixLength( curr ); while( depth > 0 && len[ depth ] > prefix ) depth } else first = false; node = stack[ depth ]; pos = len[ depth ]; for(;;) { nodePath = node.path; currFromPos = curr.subVector( pos ); prefix = (int)currFromPos.longestCommonPrefixLength( nodePath ); if ( DDDEBUG ) System.err.println( "prefix: " + prefix + " nodePath.length(): " + nodePath.length() + ( prefix < nodePath.length() ? " bit: " + String.valueOf( nodePath.getBoolean( prefix ) ) : "" ) + " node.isLeaf(): " + node.isLeaf() ); if ( prefix < nodePath.length() || node.isLeaf() ) { // Exit. LEFT or RIGHT, depending on the bit at the end of the common prefix. The // path is the remaining path at the current position for external nodes, or a prefix of length // at most pathLength for internal nodes. behaviour = prefix < nodePath.length() && ! nodePath.getBoolean( prefix ) ? RIGHT : LEFT; path = curr; externalValues.add( behaviour ); externalParentRepresentations.add( depth == 0 ? pos : pos - 1 ); if ( DDDEBUG ) { System.err.println( "Computed " + ( node.isLeaf() ? "leaf " : "" ) + "mapping " + c + " <" + node.hashCode() + ", " + path + "> -> " + behaviour ); System.err.println( "Root: " + root + " node: " + node + " representation length: " + ( depth == 0 ? pos : pos - 1 ) ); } break; } pos += nodePath.length() + 1; if ( pos > curr.length() ) { assert false; break; } // System.err.println( curr.getBoolean( pos - 1 ) ? "Turning right" : "Turning left" ); node = curr.getBoolean( pos - 1 ) ? node.right : node.left; // Update stack len[ ++depth ] = pos; stack[ depth ] = node; } prev.replace( curr ); c++; } pl.done(); } } else { // No elements. this.root = null; this.numElements = 0; } } private void recToString( final Node n, final MutableString printPrefix, final MutableString result, final MutableString path, final int level ) { if ( n == null ) return; result.append( printPrefix ).append( '(' ).append( level ).append( ')' ); if ( n.path != null ) { path.append( n.path ); result.append( " path: (" ).append( n.path.length() ).append( ") :" ).append( n.path ); } result.append( '\n' ); path.append( '0' ); recToString( n.left, printPrefix.append( '\t' ).append( "0 => " ), result, path, level + 1 ); path.charAt( path.length() - 1, '1' ); recToString( n.right, printPrefix.replace( printPrefix.length() - 5, printPrefix.length(), "1 => "), result, path, level + 1 ); path.delete( path.length() - 1, path.length() ); printPrefix.delete( printPrefix.length() - 6, printPrefix.length() ); path.delete( (int)( path.length() - n.path.length() ), path.length() ); } public String toString() { MutableString s = new MutableString(); recToString( root, new MutableString(), s, new MutableString(), 0 ); return s.toString(); } } /** Creates a partial compacted trie using given elements, bucket size, transformation strategy, and temporary directory. * * @param elements the elements among which the trie must be able to rank. * @param log2BucketSize the logarithm of the size of a bucket. * @param transformationStrategy a transformation strategy that must turn the elements in <code>elements</code> into a list of * distinct, lexicographically increasing (in iteration order) bit vectors. */ public ZFastTrieDistributor( final Iterable<? extends T> elements, final int log2BucketSize, final TransformationStrategy<? super T> transformationStrategy, final ChunkedHashStore<BitVector> chunkedHashStore ) throws IOException { this.transformationStrategy = transformationStrategy; this.seed = chunkedHashStore.seed(); final IntermediateTrie<T> intermediateTrie = new IntermediateTrie<T>( elements, log2BucketSize, transformationStrategy, seed ); size = intermediateTrie.numElements; emptyTrie = intermediateTrie.internalNodeRepresentations.length() == 0; noDelimiters = intermediateTrie.delimiters == null || intermediateTrie.delimiters.isEmpty(); if ( noDelimiters ) { behaviour = null; signatures = null; leaves = null; return; } logWMask = intermediateTrie.logWMask; logW = intermediateTrie.logW; signatureMask = intermediateTrie.signatureMask; behaviour = new MWHCFunction<BitVector>( TransformationStrategies.wrap( elements, transformationStrategy ), TransformationStrategies.identity(), intermediateTrie.externalValues, 1, chunkedHashStore ); intermediateTrie.externalValues = null; if ( ! emptyTrie ) { numDelimiters = intermediateTrie.delimiters.size(); if ( DDEBUG ) { System.err.println( "Internal node representations: " + intermediateTrie.internalNodeRepresentations ); System.err.println( "Internal node keys: " + intermediateTrie.internalNodeKeys ); } signatures = new MWHCFunction<BitVector>( intermediateTrie.internalNodeKeys, TransformationStrategies.identity(), intermediateTrie.internalNodeSignatures, intermediateTrie.logW + intermediateTrie.signatureSize ); intermediateTrie.internalNodeSignatures = null; intermediateTrie.internalNodeKeys.close(); intermediateTrie.internalNodeKeys = null; ObjectOpenHashSet<LongArrayBitVector> rankers = new ObjectOpenHashSet<LongArrayBitVector>(); for( BitVector bv: intermediateTrie.internalNodeRepresentations ) { rankers.add( LongArrayBitVector.copy( bv.subVector( 0, bv.lastOne() + 1 ) ) ); rankers.add( LongArrayBitVector.copy( bv ).append( 1, 1 ) ); LongArrayBitVector plus1 = LongArrayBitVector.copy( bv ); long lastZero = plus1.lastZero(); if ( lastZero != -1 ) { plus1.length( lastZero + 1 ); plus1.set( lastZero ); rankers.add( plus1 ); } } intermediateTrie.internalNodeRepresentations.close(); intermediateTrie.internalNodeRepresentations = null; LongArrayBitVector[] rankerArray = rankers.toArray( new LongArrayBitVector[ rankers.size() ] ); rankers = null; Arrays.sort( rankerArray ); if ( DDEBUG ) { System.err.println( "Rankers: " ); for( BitVector bv: rankerArray ) System.err.println( bv ); System.err.println(); } LongArrayBitVector leavesBitVector = LongArrayBitVector.ofLength( rankerArray.length ); int q = 0; for( BitVector v : rankerArray ) { if ( intermediateTrie.delimiters.contains( v ) ) leavesBitVector.set( q ); q++; } intermediateTrie.delimiters = null; leaves = new Rank9( leavesBitVector ); if ( DDEBUG ) System.err.println( "Rank bit vector: " + leavesBitVector ); ranker = new TwoStepsLcpMonotoneMinimalPerfectHashFunction<BitVector>( Arrays.asList( rankerArray ), TransformationStrategies.prefixFree() ); rankerArray = null; // Compute errors to be corrected this.mistakeSignatures = new IntOpenHashSet(); final IntOpenHashSet mistakeSignatures = new IntOpenHashSet(); int c; Iterator<BitVector>iterator = TransformationStrategies.wrap( elements.iterator(), transformationStrategy ); c = 0; int mistakes = 0; while( iterator.hasNext() ) { BitVector curr = iterator.next(); if ( DEBUG ) System.err.println( "Checking element number " + c + ( ( c + 1 ) % ( 1L << log2BucketSize ) == 0 ? " (bucket)" : "" )); if ( getNodeStringLength( curr ) != intermediateTrie.externalParentRepresentations.getInt( c ) ){ if ( DEBUG ) System.err.println( "Error! " + getNodeStringLength( curr ) + " != " + intermediateTrie.externalParentRepresentations.getInt( c ) ); long h = Hashes.jenkins( curr, seed ); mistakeSignatures.add( (int)( h ^ h >>> 32 ) ); mistakes++; } c++; } LOGGER.info( "Errors: " + mistakes + " (" + ( 100.0 * mistakes / size ) + "%)" ); if ( ASSERTS ) assert (double)mistakes / size < .5 : 100.0 * mistakes / size + "% >= 50%"; ObjectArrayList<BitVector> positives = new ObjectArrayList<BitVector>(); LongArrayList results = new LongArrayList(); c = 0; for( BitVector curr: TransformationStrategies.wrap( elements, transformationStrategy ) ) { long h = Hashes.jenkins( curr, seed ); if ( mistakeSignatures.contains( (int)( h ^ h >>> 32 ) ) ) { positives.add( curr.copy() ); results.add( intermediateTrie.externalParentRepresentations.getInt( c ) ); } c++; } LOGGER.info( "False errors: " + ( positives.size() - mistakes ) + ( positives.size() != 0 ? " (" + 100 * ( positives.size() - mistakes ) / ( positives.size() ) + "%)" : "" ) ); this.mistakeSignatures = mistakeSignatures; corrections = new MWHCFunction<BitVector>( positives, TransformationStrategies.identity(), results, logW ); final int bucketSize = 1 << log2BucketSize; LOGGER.debug( "Forecast signature bits per element: " + ( 1.0 / bucketSize ) * ( GAMMA + log2( intermediateTrie.w ) + log2( bucketSize ) + log2( log2( intermediateTrie.w ) ) ) ); LOGGER.debug( "Actual signature bits per element: " + (double)signatures.numBits() / size ); LOGGER.debug( "Forecast ranker bits per element: " + ( 3.0 / bucketSize ) * ( HypergraphSorter.GAMMA + log2( Math.E ) - log2( log2( Math.E ) ) + log2( 1 + log2( 3.0 * size / bucketSize ) ) + log2( intermediateTrie.w - log2 ( log2( size ) ) ) ) ); LOGGER.debug( "Actual ranker bits per element: " + (double)ranker.numBits() / size ); LOGGER.debug( "Forecast leaves bits per element: " + ( 3.0 / bucketSize ) ); LOGGER.debug( "Actual leaves bits per element: " + (double)leaves.bitVector().length() / size ); LOGGER.debug( "Forecast mistake bits per element: " + ( log2( bucketSize ) / bucketSize + 2 * GAMMA / bucketSize ) ); LOGGER.debug( "Actual mistake bits per element: " + (double)numBitsForMistakes() / size ); LOGGER.debug( "Forecast behaviour bits per element: " + GAMMA ); LOGGER.debug( "Actual behaviour bits per element: " + (double)behaviour.numBits() / size ); } else { signatures = null; leaves = null; } if ( ASSERTS ) { final Iterator<BitVector> iterator = TransformationStrategies.wrap( elements.iterator(), transformationStrategy ); int c = 0; while( iterator.hasNext() ) { BitVector curr = iterator.next(); if ( DEBUG ) System.err.println( "Checking element number " + c + ( ( c + 1 ) >>> log2BucketSize == 0 ? " (bucket)" : "" )); long t = getLong( curr ); assert t == c >>> log2BucketSize : "At " + c + ": " + ( c >>> log2BucketSize ) + " != " + t; c++; } } } private long getNodeStringLength( BitVector v ) { if ( DEBUG ) System.err.println( "getNodeStringLength(" + v + ")..." ); long state[][] = Hashes.preprocessJenkins( v, seed ); final long[] a = state[ 0 ], b = state[ 1 ], c = state[ 2 ]; final long corr = Hashes.jenkins( v, v.length(), a, b, c ); if ( mistakeSignatures.contains( (int)( corr ^ corr >>> 32 ) ) ) { if ( DEBUG ) System.err.println( "Correcting..." ); return corrections.getLong( v ); } long r = v.length(); long l = 0; int i = Fast.mostSignificantBit( r ); long mask = 1L << i; while( r - l > 1 ) { if ( ASSERTS ) assert i > -1; if ( DDDEBUG ) System.err.println( "[" + l + ".." + r + "]; i = " + i ); if ( ( l & mask ) != ( r - 1 & mask ) ) { final long f = ( r - 1 ) & ( -1L << i ); long data = signatures.getLong( v.subVector( 0, f ) ); if ( data == -1 ) { if ( DDDEBUG ) System.err.println( "Missing " + v.subVector( 0, f ) ); r = f; } else { long g = data & logWMask; if ( g > v.length() ) { if ( DDDEBUG ) System.err.println( "Excessive length for " + v.subVector( 0, f ) ); r = f; } else { long h = Hashes.jenkins( v, g, a, b, c ); if ( ASSERTS ) assert h == Hashes.jenkins( v.subVector( 0, g ), seed ); if ( DDDEBUG ) System.err.println( "Testing signature " + ( h & signatureMask ) ); if ( ( data >>> logW ) == ( h & signatureMask ) && g >= f ) l = g; else r = f; } } } i mask >>= 1; } if ( DEBUG ) System.err.println( "getNodeStringLength(" + v + ") => " + l ); return l; } @SuppressWarnings("unchecked") public long getLong( final Object o ) { if ( noDelimiters ) return 0; final BitVector v = (BitVector)o; final int b = (int)behaviour.getLong( o ); if ( emptyTrie ) return b; final long length = getNodeStringLength( v ); if ( DDDEBUG ) System.err.println( "getNodeStringLength( v )=" + length ); final BitVector key = v.subVector( 0, length ).copy(); if ( length >= v.length() ) return -1; final boolean bit = v.getBoolean( length ); if ( b == LEFT ) { if ( DDDEBUG ) System.err.println( "LEFT: " + bit ); if ( bit ) key.add( true ); else key.length( key.lastOne() + 1 ); long pos = ranker.getLong( key ); if ( DDDEBUG ) System.err.println( key.length() + " " + pos + " " + leaves.bitVector() ); return leaves.rank( pos ); } else { if ( DDDEBUG ) System.err.println( "RIGHT: " + bit ); if ( bit ) { final long lastZero = key.lastZero(); //System.err.println( lastZero ); if ( lastZero == -1 ) return numDelimiters; // We are exiting at the right of 1^k (k>=0). key.length( lastZero + 1 ).set( lastZero ); long pos = ranker.getLong( key ); //System.err.println( "pos: " + pos + " rank: " + leaves.rank( pos ) ); return leaves.rank( pos ); } else { key.add( true ); long pos = ranker.getLong( key ); return leaves.rank( pos ); } } } private long numBitsForMistakes() { if ( emptyTrie ) return 0; return corrections.numBits() + mistakeSignatures.size() * Integer.SIZE; } public long numBits() { if ( emptyTrie ) return 0; return behaviour.numBits() + signatures.numBits() + ranker.numBits() + leaves.bitVector().length() + transformationStrategy.numBits() + numBitsForMistakes(); } public boolean containsKey( Object o ) { return true; } public int size() { return size; } }
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //You should have received a copy of the GNU Lesser General Public //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.parser; import java.util.ArrayList; import java.util.List; import java.util.Set; import opennlp.maxent.DataStream; import opennlp.maxent.Event; import opennlp.maxent.EventStream; import opennlp.tools.chunker.ChunkerContextGenerator; import opennlp.tools.ngram.Dictionary; import opennlp.tools.postag.DefaultPOSContextGenerator; import opennlp.tools.postag.POSContextGenerator; /** * Wrapper class for one of four parser event streams. The particular event stram is specified * at construction. * @author Tom Morton * */ public class ParserEventStream implements EventStream { private BuildContextGenerator bcg; private CheckContextGenerator kcg; private ChunkerContextGenerator ccg; private POSContextGenerator tcg; private DataStream data; private Event[] events; private int ei; private HeadRules rules; private Set punctSet; private EventTypeEnum etype; /** * Create an event stream based on the specified data stream of the specified type using the specified head rules. * @param d A 1-parse-per-line Penn Treebank Style parse. * @param rules The head rules. * @param etype The type of events desired (tag, chunk, build, or check). * @param dict A tri-gram dictionary to reduce feature generation. */ public ParserEventStream(DataStream d, HeadRules rules, EventTypeEnum etype, Dictionary dict) { if (etype == EventTypeEnum.BUILD) { this.bcg = new BuildContextGenerator(dict); } else if (etype == EventTypeEnum.CHECK) { this.kcg = new CheckContextGenerator(); } else if (etype == EventTypeEnum.CHUNK) { this.ccg = new ChunkContextGenerator(); } else if (etype == EventTypeEnum.TAG) { this.tcg = new DefaultPOSContextGenerator(dict); } this.rules = rules; punctSet = rules.getPunctuationTags(); this.etype = etype; data = d; ei = 0; if (d.hasNext()) { addNewEvents(); } else { events = new Event[0]; } } public ParserEventStream(DataStream d, HeadRules rules, EventTypeEnum etype) { this (d,rules,etype,null); } public boolean hasNext() { return (ei < events.length || data.hasNext()); } public Event nextEvent() { if (ei == events.length) { addNewEvents(); ei = 0; } return ((Event) events[ei++]); } private static void getInitialChunks(Parse p, List ichunks) { if (p.isPosTag()) { ichunks.add(p); } else { Parse[] kids = p.getChildren(); boolean allKidsAreTags = true; for (int ci = 0, cl = kids.length; ci < cl; ci++) { if (!kids[ci].isPosTag()) { allKidsAreTags = false; break; } } if (allKidsAreTags) { ichunks.add(p); } else { for (int ci = 0, cl = kids.length; ci < cl; ci++) { getInitialChunks(kids[ci], ichunks); } } } } public static Parse[] getInitialChunks(Parse p) { List chunks = new ArrayList(); getInitialChunks(p, chunks); return (Parse[]) chunks.toArray(new Parse[chunks.size()]); } /** * Returns true if the specified child is the first child of the specified parent. * @param child The child parse. * @param parent The parent parse. * @return true if the specified child is the first child of the specified parent; false otherwise. */ private boolean firstChild(Parse child, Parse parent) { return ParserME.collapsePunctuation(parent.getChildren(),punctSet)[0] == child; } /** * Returns true if the specified child is the last child of the specified parent. * @param child The child parse. * @param parent The parent parse. * @return true if the specified child is the last child of the specified parent; false otherwise. */ private boolean lastChild(Parse child, Parse parent) { Parse[] kids = ParserME.collapsePunctuation(parent.getChildren(),punctSet); return (kids[kids.length - 1] == child); } private void addNewEvents() { String parseStr = (String) data.nextToken(); //System.err.println("ParserEventStream.addNewEvents: "+parseStr); List events = new ArrayList(); Parse p = Parse.parseParse(parseStr); p.updateHeads(rules); Parse[] chunks = getInitialChunks(p); if (etype == EventTypeEnum.TAG) { addTagEvents(events, chunks); } else if (etype == EventTypeEnum.CHUNK) { addChunkEvents(events, chunks); } else { addParseEvents(events, ParserME.collapsePunctuation(chunks,punctSet)); } this.events = (Event[]) events.toArray(new Event[events.size()]); } public static Parse[] reduceChunks(Parse[] chunks, int ci, Parse parent) { String type = parent.getType(); // perform reduce int reduceStart = ci; int reduceEnd = ci; while (reduceStart >=0 && chunks[reduceStart].getParent() == parent) { reduceStart } reduceStart++; Parse[] reducedChunks; if (!type.equals(ParserME.TOP_NODE)) { reducedChunks = new Parse[chunks.length-(reduceEnd-reduceStart+1)+1]; //total - num_removed + 1 (for new node) //insert nodes before reduction for (int ri=0,rn=reduceStart;ri<rn;ri++) { reducedChunks[ri]=chunks[ri]; } //insert reduced node reducedChunks[reduceStart]=parent; //propagate punctuation sets parent.setPrevPunctuation(chunks[reduceStart].getPreviousPunctuationSet()); parent.setNextPunctuation(chunks[reduceEnd].getNextPunctuationSet()); //insert nodes after reduction int ri=reduceStart+1; for (int rci=reduceEnd+1;rci<chunks.length;rci++) { reducedChunks[ri]=chunks[rci]; ri++; } ci=reduceStart-1; //ci will be incremented at end of loop } else { reducedChunks = new Parse[0]; } return reducedChunks; } private void addParseEvents(List events, Parse[] chunks) { int ci = 0; while (ci < chunks.length) { //System.err.println("parserEventStream.addParseEvents: chunks="+Arrays.asList(chunks)); Parse c = chunks[ci]; Parse parent = c.getParent(); if (parent != null) { String type = parent.getType(); String outcome; if (firstChild(c, parent)) { outcome = ParserME.START + type; } else { outcome = ParserME.CONT + type; } //System.err.println("parserEventStream.addParseEvents: chunks["+ci+"]="+c+" label="+outcome); c.setLabel(outcome); if (etype == EventTypeEnum.BUILD) { events.add(new Event(outcome, bcg.getContext(chunks, ci))); } int start = ci - 1; while (start >= 0 && chunks[start].getParent() == parent) { start } if (lastChild(c, parent)) { if (etype == EventTypeEnum.CHECK) { events.add(new Event(ParserME.COMPLETE, kcg.getContext( chunks, type, start + 1, ci))); } //perform reduce int reduceStart = ci; int reduceEnd = ci; while (reduceStart >=0 && chunks[reduceStart].getParent() == parent) { reduceStart } reduceStart++; chunks = reduceChunks(chunks,ci,parent); ci=reduceStart-1; //ci will be incremented at end of loop } else { if (etype == EventTypeEnum.CHECK) { events.add(new Event(ParserME.INCOMPLETE, kcg.getContext(chunks, type, start + 1, ci))); } } } ci++; } } private void addChunkEvents(List events, Parse[] chunks) { List toks = new ArrayList(); List tags = new ArrayList(); List preds = new ArrayList(); for (int ci = 0, cl = chunks.length; ci < cl; ci++) { Parse c = chunks[ci]; if (c.isPosTag()) { toks.add(c.toString()); tags.add(c.getType()); preds.add(ParserME.OTHER); } else { boolean start = true; String ctype = c.getType(); Parse[] kids = c.getChildren(); for (int ti=0,tl=kids.length;ti<tl;ti++) { Parse tok = kids[ti]; toks.add(tok.toString()); tags.add(tok.getType()); if (start) { preds.add(ParserME.START + ctype); start = false; } else { preds.add(ParserME.CONT + ctype); } } } } for (int ti = 0, tl = toks.size(); ti < tl; ti++) { events.add(new Event((String) preds.get(ti), ccg.getContext(ti, toks.toArray(), (String[]) tags.toArray(new String[tags.size()]), (String[]) preds.toArray(new String[preds.size()])))); } } private void addTagEvents(List events, Parse[] chunks) { List toks = new ArrayList(); List preds = new ArrayList(); for (int ci = 0, cl = chunks.length; ci < cl; ci++) { Parse c = (Parse) chunks[ci]; if (c.isPosTag()) { toks.add(c.toString()); preds.add(c.getType()); } else { Parse[] kids = c.getChildren(); for (int ti=0,tl=kids.length;ti<tl;ti++) { Parse tok = kids[ti]; toks.add(tok.toString()); preds.add(tok.getType()); } } } for (int ti = 0, tl = toks.size(); ti < tl; ti++) { events.add(new Event((String) preds.get(ti), tcg.getContext(ti, toks.toArray(), (String[]) preds.toArray(new String[preds.size()]), null))); } } public static void main(String[] args) throws java.io.IOException { if (args.length == 0) { System.err.println("Usage ParserEventStream -[tag|chunk|build|check|fun] head_rules [dictionary] < parses"); System.exit(1); } EventTypeEnum etype = null; boolean fun = false; int ai = 0; while (ai < args.length && args[ai].startsWith("-")) { if (args[ai].equals("-build")) { etype = EventTypeEnum.BUILD; } else if (args[ai].equals("-check")) { etype = EventTypeEnum.CHECK; } else if (args[ai].equals("-chunk")) { etype = EventTypeEnum.CHUNK; } else if (args[ai].equals("-tag")) { etype = EventTypeEnum.TAG; } else if (args[ai].equals("-fun")) { fun = true; } else { System.err.println("Invalid option " + args[ai]); System.exit(1); } ai++; } HeadRules rules = new opennlp.tools.lang.english.HeadRules(args[ai++]); Dictionary dict = null; if (ai < args.length) { dict = new Dictionary(args[ai++]); } if (fun) { Parse.useFunctionTags(true); } opennlp.maxent.EventStream es = new ParserEventStream(new opennlp.maxent.PlainTextByLineDataStream(new java.io.InputStreamReader(System.in)), rules, etype, dict); while (es.hasNext()) { System.out.println(es.nextEvent()); } } } /** * Enumerated type of event types for the parser. * */ class EventTypeEnum { private String name; public static final EventTypeEnum BUILD = new EventTypeEnum("build"); public static final EventTypeEnum CHECK = new EventTypeEnum("check"); public static final EventTypeEnum CHUNK = new EventTypeEnum("chunk"); public static final EventTypeEnum TAG = new EventTypeEnum("tag"); private EventTypeEnum(String name) { this.name = name; } public String toString() { return name; } }
package de.lessvoid.nifty.html; import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.htmlparser.Tag; import org.htmlparser.Text; import org.htmlparser.visitors.NodeVisitor; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.builder.ElementBuilder; import de.lessvoid.nifty.builder.ImageBuilder; import de.lessvoid.nifty.builder.PanelBuilder; import de.lessvoid.nifty.spi.render.RenderFont; /** * A NodeVisitor for the HTML Parser project that will visit all HTML tags * and translate them into Nifty elements using the Nifty Builder pattern. * @author void */ public class NiftyVisitor extends NodeVisitor { // errors in processing are added to that list private List<String> errors = new ArrayList<String>(); // the PanelBuilder for the body tag private PanelBuilder bodyPanel; // helper class to create new builders private NiftyBuilderFactory niftyBuilderFactory; // to allow nested block level elements later we must stack them private Stack<PanelBuilder> blockElementStack = new Stack<PanelBuilder>(); // the current block level element private PanelBuilder currentBlockElement; // default font we use for generatin text elements private String defaultFontName; private String defaultFontBoldName; private RenderFont defaultFont; // current color private String currentColor; // this will be set to a different font name when a corresponding tag is being processed private String differentFont; // we collect all text nodes into this string buffer private StringBuffer currentText = new StringBuffer(); // table private PanelBuilder table; // table row private PanelBuilder tableRow; // table data private PanelBuilder tableData; /** * Create the NiftyVisitor. * @param nifty the Nifty instance * @param niftyBuilderFactory a helper class to create Nifty Builders */ public NiftyVisitor(final Nifty nifty, final NiftyBuilderFactory niftyBuilderFactory, final String defaultFontName, final String defaultFontBoldName) { this.niftyBuilderFactory = niftyBuilderFactory; this.defaultFontName = defaultFontName; this.defaultFontBoldName = defaultFontBoldName; if (defaultFontName != null) { this.defaultFont = nifty.createFont(defaultFontName); } } /* * (non-Javadoc) * @see org.htmlparser.visitors.NodeVisitor#beginParsing() */ @Override public void beginParsing () { errors.clear(); } /* * (non-Javadoc) * @see org.htmlparser.visitors.NodeVisitor#visitTag(org.htmlparser.Tag) */ @Override public void visitTag(final Tag tag) { try { if (isBody(tag)) { // we'll add a main panel for the body which will be the parent element for everything we generate // this way we can decide the childLayout and other properties of the body panel. bodyPanel = niftyBuilderFactory.createBodyPanelBuilder(); } else if (isParagraph(tag)) { assertBodyPanelNotNull(); currentBlockElement = niftyBuilderFactory.createParagraphPanelBuilder(); blockElementStack.push(currentBlockElement); } else if (isImageTag(tag)) { ImageBuilder image = niftyBuilderFactory.createImageBuilder( tag.getAttribute("src"), tag.getAttribute("align"), tag.getAttribute("width"), tag.getAttribute("height"), tag.getAttribute("bgcolor"), tag.getAttribute("vspace")); if (currentBlockElement != null) { currentBlockElement.image(image); } else { bodyPanel.image(image); } } else if (isBreak(tag)) { if (currentBlockElement != null) { currentText.append("\n"); } else { PanelBuilder breakPanelBuilder = niftyBuilderFactory.createBreakPanelBuilder(String.valueOf(defaultFont.getHeight())); bodyPanel.panel(breakPanelBuilder); } } else if (isTableTag(tag)) { assertBodyPanelNotNull(); table = niftyBuilderFactory.createTableTagPanelBuilder( tag.getAttribute("width"), tag.getAttribute("bgcolor"), tag.getAttribute("border"), tag.getAttribute("bordercolor")); } else if (isTableRowTag(tag)) { assertTableNotNull(); tableRow = niftyBuilderFactory.createTableRowPanelBuilder( tag.getAttribute("width"), tag.getAttribute("bgcolor"), tag.getAttribute("border"), tag.getAttribute("bordercolor")); } else if (isTableDataTag(tag)) { assertTableRowNotNull(); tableData = niftyBuilderFactory.createTableDataPanelBuilder( tag.getAttribute("width"), tag.getAttribute("bgcolor"), tag.getAttribute("border"), tag.getAttribute("bordercolor")); } else if (isFontTag(tag)) { String color = tag.getAttribute("color"); if (color != null) { currentColor = color; } } else if (isStrongTag(tag)) { differentFont = defaultFontBoldName; } } catch (Exception e) { addError(e); } } /* * (non-Javadoc) * @see org.htmlparser.visitors.NodeVisitor#visitEndTag(org.htmlparser.Tag) */ @Override public void visitEndTag(final Tag tag) { try { if (isBody(tag)) { // currently there is nothing to do when a body tag ends } else if (isParagraph(tag)) { assertBodyPanelNotNull(); assertCurrentBlockElementNotNull(); String textElement = currentText.toString(); if (textElement.length() > 0) { addTextElement(currentBlockElement, textElement); currentText.setLength(0); } if (currentBlockElement.getElementBuilders().isEmpty()) { currentBlockElement.height(String.valueOf(defaultFont.getHeight())); } bodyPanel.panel(currentBlockElement); blockElementStack.pop(); currentBlockElement = null; differentFont = null; } else if (isImageTag(tag)) { // nothing to do } else if (isBreak(tag)) { // nothing to do } else if (isTableTag(tag)) { assertBodyPanelNotNull(); bodyPanel.panel(table); table = null; } else if (isTableRowTag(tag)) { assertTableNotNull(); table.panel(tableRow); tableRow = null; } else if (isTableDataTag(tag)) { assertTableRowNotNull(); addTextElement(tableData, currentText.toString()); currentText.setLength(0); tableRow.panel(tableData); tableData = null; differentFont = null; } else if (isFontTag(tag)) { currentColor = null; } } catch (Exception e) { addError(e); } } /* * (non-Javadoc) * @see org.htmlparser.visitors.NodeVisitor#visitStringNode(org.htmlparser.Text) */ @Override public void visitStringNode(final Text textNode) { if (tableData != null) { appendText(textNode); } else if (currentBlockElement != null) { appendText(textNode); } } private void appendText(final Text textNode) { if (currentColor != null) { currentText.append("\\"); currentText.append(currentColor); currentText.append(" } currentText.append(removeNewLine(textNode.getText())); } public ElementBuilder builder() throws Exception { try { assertBodyPanelNotNull(); } catch (Exception e) { addAsFirstError(e); } assertNoErrors(); return bodyPanel; } // private stuff private void addError(final Exception e) { if (!errors.contains(e.getMessage())) { errors.add(e.getMessage()); } } private void addAsFirstError(final Exception e) { if (!errors.contains(e.getMessage())) { errors.add(0, e.getMessage()); } } private void assertBodyPanelNotNull() throws Exception { if (bodyPanel == null) { throw new Exception("This looks like HTML with a missing <body> tag"); } } private void assertTableNotNull() throws Exception { if (table == null) { throw new Exception("This looks like a <tr> element with a missing <table> tag"); } } private void assertTableRowNotNull() throws Exception { if (table == null) { throw new Exception("This looks like a <td> element with a missing <tr> tag"); } } private void assertCurrentBlockElementNotNull() throws Exception { if (currentBlockElement == null) { throw new Exception("This looks like broken HTML. currentBlockElement seems null. Maybe a duplicate close tag?"); } } private void addTextElement(final PanelBuilder panelBuilder, final String text) { String font = defaultFontName; if (differentFont != null) { font = differentFont; } panelBuilder.text(niftyBuilderFactory.createTextBuilder(text, font, currentColor)); } private void assertNoErrors() throws Exception { if (!errors.isEmpty()) { StringBuffer message = new StringBuffer(); for (int i=0; i<errors.size(); i++) { message.append(errors.get(i)); message.append("\n"); } throw new Exception(message.toString()); } } private boolean isBody(final Tag tag) { return "BODY".equals(tag.getTagName()); } private boolean isParagraph(final Tag tag) { return "P".equals(tag.getTagName()); } private boolean isBreak(final Tag tag) { return "BR".equals(tag.getTagName()); } private boolean isImageTag(final Tag tag) { return "IMG".equals(tag.getTagName()); } private boolean isTableTag(final Tag tag) { return "TABLE".equals(tag.getTagName()); } private boolean isTableRowTag(final Tag tag) { return "TR".equals(tag.getTagName()); } private boolean isTableDataTag(final Tag tag) { return "TD".equals(tag.getTagName()); } private boolean isFontTag(final Tag tag) { return "FONT".equals(tag.getTagName()); } private boolean isStrongTag(final Tag tag) { return "STRONG".equals(tag.getTagName()); } private String removeNewLine(final String text) { return text.replaceAll("\n", "").replaceAll("\t", ""); } }
package net.sourceforge.clonekeenplus; import android.app.Activity; import android.app.Service; import android.content.Context; import android.os.Bundle; import android.os.IBinder; import android.view.MotionEvent; import android.view.KeyEvent; import android.view.Window; import android.view.WindowManager; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.EditText; import android.text.Editable; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.FrameLayout; import android.graphics.drawable.Drawable; import android.graphics.Color; import android.content.res.Configuration; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.view.View.OnKeyListener; import android.view.MenuItem; import android.view.Menu; import android.view.Gravity; import android.text.method.TextKeyListener; import java.util.LinkedList; import java.io.SequenceInputStream; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.File; import java.io.FileInputStream; import java.util.zip.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.Set; import android.text.SpannedString; import java.io.BufferedReader; import java.io.BufferedInputStream; import java.io.InputStreamReader; import android.view.inputmethod.InputMethodManager; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import java.util.concurrent.Semaphore; import android.content.pm.ActivityInfo; import android.view.Display; import android.text.InputType; import android.util.Log; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2 ) setRequestedOrientation(Globals.HorizontalOrientation ? ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT); else if( android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD ) setRequestedOrientation(Globals.HorizontalOrientation ? ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); else setRequestedOrientation(Globals.HorizontalOrientation ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); instance = this; // fullscreen mode requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); if(Globals.InhibitSuspend) getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); Log.i("SDL", "libSDL: Creating startup screen"); _layout = new LinearLayout(this); _layout.setOrientation(LinearLayout.VERTICAL); _layout.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); _layout2 = new LinearLayout(this); _layout2.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); final Semaphore loadedLibraries = new Semaphore(0); if( Globals.StartupMenuButtonTimeout > 0 ) { _btn = new Button(this); _btn.setEnabled(false); _btn.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); _btn.setText(getResources().getString(R.string.device_change_cfg)); class onClickListener implements View.OnClickListener { public MainActivity p; onClickListener( MainActivity _p ) { p = _p; } public void onClick(View v) { setUpStatusLabel(); Log.i("SDL", "libSDL: User clicked change phone config button"); loadedLibraries.acquireUninterruptibly(); SettingsMenu.showConfig(p, false); } }; _btn.setOnClickListener(new onClickListener(this)); _layout2.addView(_btn); } _layout.addView(_layout2); ImageView img = new ImageView(this); img.setScaleType(ImageView.ScaleType.FIT_CENTER /* FIT_XY */ ); try { img.setImageDrawable(Drawable.createFromStream(getAssets().open("logo.png"), "logo.png")); } catch(Exception e) { img.setImageResource(R.drawable.publisherlogo); } img.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); _layout.addView(img); _videoLayout = new FrameLayout(this); _videoLayout.addView(_layout); _ad = new Advertisement(this); if( _ad.getView() != null ) { _videoLayout.addView(_ad.getView()); _ad.getView().setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.RIGHT)); } setContentView(_videoLayout); class Callback implements Runnable { MainActivity p; Callback( MainActivity _p ) { p = _p; } public void run() { try { Thread.sleep(200); } catch( InterruptedException e ) {}; if(p.mAudioThread == null) { Log.i("SDL", "libSDL: Loading libraries"); p.LoadLibraries(); p.mAudioThread = new AudioThread(p); Log.i("SDL", "libSDL: Loading settings"); final Semaphore loaded = new Semaphore(0); class Callback2 implements Runnable { public MainActivity Parent; public void run() { Settings.Load(Parent); loaded.release(); loadedLibraries.release(); if( _btn != null ) _btn.setEnabled(true); } } Callback2 cb = new Callback2(); cb.Parent = p; p.runOnUiThread(cb); loaded.acquireUninterruptibly(); if(!Globals.CompatibilityHacksStaticInit) p.LoadApplicationLibrary(p); } if( !Settings.settingsChanged ) { if( Globals.StartupMenuButtonTimeout > 0 ) { Log.i("SDL", "libSDL: " + String.valueOf(Globals.StartupMenuButtonTimeout) + "-msec timeout in startup screen"); try { Thread.sleep(Globals.StartupMenuButtonTimeout); } catch( InterruptedException e ) {}; } if( Settings.settingsChanged ) return; Log.i("SDL", "libSDL: Timeout reached in startup screen, process with downloader"); p.startDownloader(); } } }; (new Thread(new Callback(this))).start(); if( Globals.CreateService ) { Intent intent = new Intent(this, DummyService.class); startService(intent); } } public void setUpStatusLabel() { MainActivity Parent = this; // Too lazy to rename if( Parent._btn != null ) { Parent._layout2.removeView(Parent._btn); Parent._btn = null; } if( Parent._tv == null ) { //Get the display so we can know the screen size Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); Parent._tv = new TextView(Parent); Parent._tv.setMaxLines(2); // To show some long texts on smaller devices Parent._tv.setMinLines(2); // Otherwise the background picture is getting resized at random, which does not look good Parent._tv.setText(R.string.init); // Padding is a good idea because if the display device is a TV the edges might be cut off Parent._tv.setPadding((int)(width * 0.1), (int)(height * 0.1), (int)(width * 0.1), 0); Parent._layout2.addView(Parent._tv); } } public void startDownloader() { Log.i("SDL", "libSDL: Starting data downloader"); class Callback implements Runnable { public MainActivity Parent; public void run() { setUpStatusLabel(); Log.i("SDL", "libSDL: Starting downloader"); if( Parent.downloader == null ) Parent.downloader = new DataDownloader(Parent, Parent._tv); } } Callback cb = new Callback(); cb.Parent = this; this.runOnUiThread(cb); } public void initSDL() { (new Thread(new Runnable() { public void run() { //int tries = 30; while( isCurrentOrientationHorizontal() != Globals.HorizontalOrientation ) { Log.i("SDL", "libSDL: Waiting for screen orientation to change - the device is probably in the lockscreen mode"); try { Thread.sleep(500); } catch( Exception e ) {} /* tries--; if( tries <= 0 ) { Log.i("SDL", "libSDL: Giving up waiting for screen orientation change"); break; } */ if( _isPaused ) { Log.i("SDL", "libSDL: Application paused, cancelling SDL initialization until it will be brought to foreground"); return; } } runOnUiThread(new Runnable() { public void run() { initSDLInternal(); } }); } })).start(); } private void initSDLInternal() { if(sdlInited) return; Log.i("SDL", "libSDL: Initializing video and SDL application"); sdlInited = true; _videoLayout.removeView(_layout); if( _ad.getView() != null ) _videoLayout.removeView(_ad.getView()); _layout = null; _layout2 = null; _btn = null; _tv = null; _inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); _videoLayout = new FrameLayout(this); SetLayerType.get().setLayerType(_videoLayout); setContentView(_videoLayout); mGLView = new DemoGLSurfaceView(this); SetLayerType.get().setLayerType(mGLView); _videoLayout.addView(mGLView); mGLView.setFocusableInTouchMode(true); mGLView.setFocusable(true); mGLView.requestFocus(); if( _ad.getView() != null ) { _videoLayout.addView(_ad.getView()); _ad.getView().setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.RIGHT)); } // Receive keyboard events DimSystemStatusBar.get().dim(_videoLayout); DimSystemStatusBar.get().dim(mGLView); } @Override protected void onPause() { if( downloader != null ) { synchronized( downloader ) { downloader.setStatusField(null); } } _isPaused = true; if( mGLView != null ) mGLView.onPause(); //if( _ad.getView() != null ) // _ad.getView().onPause(); super.onPause(); } @Override protected void onResume() { super.onResume(); if( mGLView != null ) { mGLView.onResume(); DimSystemStatusBar.get().dim(_videoLayout); DimSystemStatusBar.get().dim(mGLView); } else if( downloader != null ) { synchronized( downloader ) { downloader.setStatusField(_tv); if( downloader.DownloadComplete ) { initSDL(); } } } //if( _ad.getView() != null ) // _ad.getView().onResume(); _isPaused = false; } @Override public void onWindowFocusChanged (boolean hasFocus) { super.onWindowFocusChanged(hasFocus); Log.i("SDL", "libSDL: onWindowFocusChanged: " + hasFocus + " - sending onPause/onResume"); if (hasFocus == false) onPause(); else onResume(); /* if (hasFocus == false) { synchronized(textInput) { // Send 'SDLK_PAUSE' (to enter pause mode) to native code: DemoRenderer.nativeTextInput( 19, 19 ); } } */ } public boolean isPaused() { return _isPaused; } @Override protected void onDestroy() { if( downloader != null ) { synchronized( downloader ) { downloader.setStatusField(null); } } if( mGLView != null ) mGLView.exitApp(); super.onDestroy(); try{ Thread.sleep(2000); // The event is sent asynchronously, allow app to save it's state, and call exit() itself. } catch (InterruptedException e) {} System.exit(0); } public void showScreenKeyboardWithoutTextInputField() { if( !keyboardWithoutTextInputShown ) { keyboardWithoutTextInputShown = true; _inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); _inputManager.showSoftInput(mGLView, InputMethodManager.SHOW_FORCED); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } else { keyboardWithoutTextInputShown = false; getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); _inputManager.hideSoftInputFromWindow(mGLView.getWindowToken(), 0); DimSystemStatusBar.get().dim(_videoLayout); DimSystemStatusBar.get().dim(mGLView); } } public void showScreenKeyboard(final String oldText, boolean sendBackspace) { if(Globals.CompatibilityHacksTextInputEmulatesHwKeyboard) { showScreenKeyboardWithoutTextInputField(); return; } if(_screenKeyboard != null) return; class simpleKeyListener implements OnKeyListener { MainActivity _parent; boolean sendBackspace; simpleKeyListener(MainActivity parent, boolean sendBackspace) { _parent = parent; this.sendBackspace = sendBackspace; }; public boolean onKey(View v, int keyCode, KeyEvent event) { if ((event.getAction() == KeyEvent.ACTION_UP) && ( keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU || keyCode == KeyEvent.KEYCODE_BUTTON_A || keyCode == KeyEvent.KEYCODE_BUTTON_B || keyCode == KeyEvent.KEYCODE_BUTTON_X || keyCode == KeyEvent.KEYCODE_BUTTON_Y || keyCode == KeyEvent.KEYCODE_BUTTON_1 || keyCode == KeyEvent.KEYCODE_BUTTON_2 || keyCode == KeyEvent.KEYCODE_BUTTON_3 || keyCode == KeyEvent.KEYCODE_BUTTON_4 )) { _parent.hideScreenKeyboard(); return true; } if (keyCode == KeyEvent.KEYCODE_DEL || keyCode == KeyEvent.KEYCODE_CLEAR) { if (sendBackspace && event.getAction() == KeyEvent.ACTION_UP) { synchronized(textInput) { DemoRenderer.nativeTextInput( 8, 0 ); // Send backspace to native code } } // EditText deletes two characters at a time, here's a hacky fix if (event.getAction() == KeyEvent.ACTION_DOWN && (event.getFlags() | KeyEvent.FLAG_SOFT_KEYBOARD) != 0) { EditText t = (EditText) v; int start = t.getSelectionStart(); //get cursor starting position int end = t.getSelectionEnd(); //get cursor ending position if ( start < 0 ) return true; if ( end < 0 || end == start ) { start if ( start < 0 ) return true; end = start + 1; } t.setText(t.getText().toString().substring(0, start) + t.getText().toString().substring(end)); t.setSelection(start); return true; } } //Log.i("SDL", "Key " + keyCode + " flags " + event.getFlags() + " action " + event.getAction()); return false; } }; _screenKeyboard = new EditText(this); // This code does not work /* _screenKeyboard.setMaxLines(100); ViewGroup.LayoutParams layout = _screenKeyboard.getLayoutParams(); if( layout != null ) { layout.width = ViewGroup.LayoutParams.FILL_PARENT; layout.height = ViewGroup.LayoutParams.FILL_PARENT; _screenKeyboard.setLayoutParams(layout); } _screenKeyboard.setGravity(android.view.Gravity.BOTTOM | android.view.Gravity.LEFT); */ String hint = _screenKeyboardHintMessage; _screenKeyboard.setHint(hint != null ? hint : getString(R.string.text_edit_click_here)); _screenKeyboard.setText(oldText); _screenKeyboard.setSelection(_screenKeyboard.getText().length()); _screenKeyboard.setOnKeyListener(new simpleKeyListener(this, sendBackspace)); _screenKeyboard.setBackgroundColor(Color.BLACK); // Full opaque - do not show semi-transparent edit box, it's confusing _screenKeyboard.setTextColor(Color.WHITE); // Just to be sure about gamma if( isRunningOnOUYA() ) _screenKeyboard.setPadding(100, 100, 100, 100); // Bad bad HDMI TVs all have cropped borders _videoLayout.addView(_screenKeyboard); //_screenKeyboard.setKeyListener(new TextKeyListener(TextKeyListener.Capitalize.NONE, false)); _screenKeyboard.setInputType(InputType.TYPE_CLASS_TEXT); _screenKeyboard.setFocusableInTouchMode(true); _screenKeyboard.setFocusable(true); _screenKeyboard.requestFocus(); _inputManager.showSoftInput(_screenKeyboard, InputMethodManager.SHOW_IMPLICIT); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); // Hack to try to force on-screen keyboard final EditText keyboard = _screenKeyboard; keyboard.postDelayed( new Runnable() { public void run() { keyboard.requestFocus(); //_inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); _inputManager.showSoftInput(keyboard, InputMethodManager.SHOW_FORCED); // Hack from Stackoverflow, to force text input on Ouya keyboard.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0)); keyboard.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0)); keyboard.postDelayed( new Runnable() { public void run() { keyboard.setSelection(keyboard.getText().length()); } }, 100 ); } }, 500 ); }; public void hideScreenKeyboard() { if( keyboardWithoutTextInputShown ) showScreenKeyboardWithoutTextInputField(); if(_screenKeyboard == null) return; synchronized(textInput) { String text = _screenKeyboard.getText().toString(); for(int i = 0; i < text.length(); i++) { DemoRenderer.nativeTextInput( (int)text.charAt(i), (int)text.codePointAt(i) ); } } DemoRenderer.nativeTextInputFinished(); _inputManager.hideSoftInputFromWindow(_screenKeyboard.getWindowToken(), 0); _videoLayout.removeView(_screenKeyboard); _screenKeyboard = null; mGLView.setFocusableInTouchMode(true); mGLView.setFocusable(true); mGLView.requestFocus(); DimSystemStatusBar.get().dim(_videoLayout); DimSystemStatusBar.get().dim(mGLView); _videoLayout.postDelayed( new Runnable() { public void run() { DimSystemStatusBar.get().dim(_videoLayout); DimSystemStatusBar.get().dim(mGLView); } }, 1000 ); }; public boolean isScreenKeyboardShown() { return _screenKeyboard != null; }; public void setScreenKeyboardHintMessage(String s) { _screenKeyboardHintMessage = s; //Log.i("SDL", "setScreenKeyboardHintMessage: " + (_screenKeyboardHintMessage != null ? _screenKeyboardHintMessage : getString(R.string.text_edit_click_here))); runOnUiThread(new Runnable() { public void run() { if( _screenKeyboard != null ) { String hint = _screenKeyboardHintMessage; _screenKeyboard.setHint(hint != null ? hint : getString(R.string.text_edit_click_here)); } } } ); } final static int ADVERTISEMENT_POSITION_RIGHT = -1; final static int ADVERTISEMENT_POSITION_BOTTOM = -1; final static int ADVERTISEMENT_POSITION_CENTER = -2; public void setAdvertisementPosition(int x, int y) { if( _ad.getView() != null ) { final FrameLayout.LayoutParams layout = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layout.gravity = 0; layout.leftMargin = 0; layout.topMargin = 0; if( x == ADVERTISEMENT_POSITION_RIGHT ) layout.gravity |= Gravity.RIGHT; else if ( x == ADVERTISEMENT_POSITION_CENTER ) layout.gravity |= Gravity.CENTER_HORIZONTAL; else { layout.gravity |= Gravity.LEFT; layout.leftMargin = x; } if( y == ADVERTISEMENT_POSITION_BOTTOM ) layout.gravity |= Gravity.BOTTOM; else if ( x == ADVERTISEMENT_POSITION_CENTER ) layout.gravity |= Gravity.CENTER_VERTICAL; else { layout.gravity |= Gravity.TOP; layout.topMargin = y; } class Callback implements Runnable { public void run() { _ad.getView().setLayoutParams(layout); } }; runOnUiThread(new Callback()); } } public void setAdvertisementVisible(final int visible) { if( _ad.getView() != null ) { class Callback implements Runnable { public void run() { if( visible == 0 ) _ad.getView().setVisibility(View.GONE); else _ad.getView().setVisibility(View.VISIBLE); } } runOnUiThread(new Callback()); } } public void getAdvertisementParams(int params[]) { for( int i = 0; i < 5; i++ ) params[i] = 0; if( _ad.getView() != null ) { params[0] = (_ad.getView().getVisibility() == View.VISIBLE) ? 1 : 0; FrameLayout.LayoutParams layout = (FrameLayout.LayoutParams) _ad.getView().getLayoutParams(); params[1] = layout.leftMargin; params[2] = layout.topMargin; params[3] = _ad.getView().getMeasuredWidth(); params[4] = _ad.getView().getMeasuredHeight(); } } public void requestNewAdvertisement() { if( _ad.getView() != null ) { class Callback implements Runnable { public void run() { _ad.requestNewAd(); } } runOnUiThread(new Callback()); } } /* @Override public boolean dispatchKeyEvent(final KeyEvent event) { //Log.i("SDL", "dispatchKeyEvent: action " + event.getAction() + " keycode " + event.getKeyCode() + " unicode " + event.getUnicodeChar() + " getCharacters() " + ((event.getCharacters() != null) ? event.getCharacters() : "none")); if( event.getAction() == KeyEvent.ACTION_DOWN ) return onKeyDown(event.getKeyCode(), event); if( event.getAction() == KeyEvent.ACTION_UP ) return onKeyUp(event.getKeyCode(), event); if( event.getAction() == KeyEvent.ACTION_MULTIPLE && event.getKeyCode() == KeyEvent.KEYCODE_UNKNOWN ) { // International text input if( mGLView != null && event.getCharacters() != null ) { for(int i = 0; i < event.getCharacters().length(); i++ ) { mGLView.nativeKey( event.getKeyCode(), 1, event.getCharacters().codePointAt(i) ); mGLView.nativeKey( event.getKeyCode(), 0, event.getCharacters().codePointAt(i) ); } return true; } } return true; //return super.dispatchKeyEvent(event); } */ @Override public boolean onKeyDown(int keyCode, final KeyEvent event) { if(_screenKeyboard != null) _screenKeyboard.onKeyDown(keyCode, event); else if( mGLView != null ) { if( mGLView.nativeKey( keyCode, 1, event.getUnicodeChar() ) == 0 ) return super.onKeyDown(keyCode, event); } else if( keyListener != null ) { keyListener.onKeyEvent(keyCode); } else if( _btn != null ) return _btn.onKeyDown(keyCode, event); return true; } @Override public boolean onKeyUp(int keyCode, final KeyEvent event) { if(_screenKeyboard != null) _screenKeyboard.onKeyUp(keyCode, event); else if( mGLView != null ) { if( mGLView.nativeKey( keyCode, 0, event.getUnicodeChar() ) == 0 ) return super.onKeyUp(keyCode, event); if( keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU ) { DimSystemStatusBar.get().dim(_videoLayout); DimSystemStatusBar.get().dim(mGLView); } } else if( _btn != null ) return _btn.onKeyUp(keyCode, event); return true; } @Override public boolean onKeyMultiple(int keyCode, int repeatCount, final KeyEvent event) { // International text input if( mGLView != null && event.getCharacters() != null ) { for(int i = 0; i < event.getCharacters().length(); i++ ) { mGLView.nativeKey( event.getKeyCode(), 1, event.getCharacters().codePointAt(i) ); mGLView.nativeKey( event.getKeyCode(), 0, event.getCharacters().codePointAt(i) ); } return true; } return false; } @Override public boolean dispatchTouchEvent(final MotionEvent ev) { //Log.i("SDL", "dispatchTouchEvent: " + ev.getAction() + " coords " + ev.getX() + ":" + ev.getY() ); if(_screenKeyboard != null) _screenKeyboard.dispatchTouchEvent(ev); else if( _ad.getView() != null && // User clicked the advertisement, ignore when user moved finger from game screen to advertisement or touches screen with several fingers ((ev.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN || (ev.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) && _ad.getView().getLeft() <= (int)ev.getX() && _ad.getView().getRight() > (int)ev.getX() && _ad.getView().getTop() <= (int)ev.getY() && _ad.getView().getBottom() > (int)ev.getY() ) return super.dispatchTouchEvent(ev); else if(mGLView != null) mGLView.onTouchEvent(ev); else if( _btn != null ) return _btn.dispatchTouchEvent(ev); else if( touchListener != null ) touchListener.onTouchEvent(ev); return true; } @Override public boolean dispatchGenericMotionEvent (MotionEvent ev) { //Log.i("SDL", "dispatchGenericMotionEvent: " + ev.getAction() + " coords " + ev.getX() + ":" + ev.getY() ); // This code fails to run for Android 1.6, so there will be no generic motion event for Andorid screen keyboard /* if(_screenKeyboard != null) _screenKeyboard.dispatchGenericMotionEvent(ev); else */ if(mGLView != null) mGLView.onGenericMotionEvent(ev); return true; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Do nothing here } public void setText(final String t) { class Callback implements Runnable { MainActivity Parent; public SpannedString text; public void run() { Parent.setUpStatusLabel(); if(Parent._tv != null) Parent._tv.setText(text); } } Callback cb = new Callback(); cb.text = new SpannedString(t); cb.Parent = this; this.runOnUiThread(cb); } public void showTaskbarNotification() { showTaskbarNotification("SDL application paused", "SDL application", "Application is paused, click to activate"); } // Stolen from SDL port by Mamaich public void showTaskbarNotification(String text0, String text1, String text2) { NotificationManager NotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Intent intent = new Intent(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_ACTIVITY_NEW_TASK); Notification n = new Notification(R.drawable.icon, text0, System.currentTimeMillis()); n.setLatestEventInfo(this, text1, text2, pendingIntent); NotificationManager.notify(NOTIFY_ID, n); } public void hideTaskbarNotification() { NotificationManager NotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); NotificationManager.cancel(NOTIFY_ID); } public void LoadLibraries() { try { if(Globals.NeedGles2) System.loadLibrary("GLESv2"); Log.i("SDL", "libSDL: loaded GLESv2 lib"); } catch ( UnsatisfiedLinkError e ) { Log.i("SDL", "libSDL: Cannot load GLESv2 lib"); } // Load all libraries try { for(String l : Globals.AppLibraries) { try { String libname = System.mapLibraryName(l); File libpath = new File(getFilesDir().getAbsolutePath() + "/../lib/" + libname); Log.i("SDL", "libSDL: loading lib " + libpath.getAbsolutePath()); System.load(libpath.getPath()); } catch( UnsatisfiedLinkError e ) { Log.i("SDL", "libSDL: error loading lib " + l + ": " + e.toString()); try { String libname = System.mapLibraryName(l); File libpath = new File(getFilesDir().getAbsolutePath() + "/" + libname); Log.i("SDL", "libSDL: loading lib " + libpath.getAbsolutePath()); System.load(libpath.getPath()); } catch( UnsatisfiedLinkError ee ) { Log.i("SDL", "libSDL: error loading lib " + l + ": " + ee.toString()); System.loadLibrary(l); } } } } catch ( UnsatisfiedLinkError e ) { try { Log.i("SDL", "libSDL: Extracting APP2SD-ed libs"); InputStream in = null; try { for( int i = 0; ; i++ ) { InputStream in2 = getAssets().open("bindata" + String.valueOf(i)); if( in == null ) in = in2; else in = new SequenceInputStream( in, in2 ); } } catch( IOException ee ) { } if( in == null ) throw new RuntimeException("libSDL: Extracting APP2SD-ed libs failed, the .apk file packaged incorrectly"); ZipInputStream zip = new ZipInputStream(in); File libDir = getFilesDir(); try { libDir.mkdirs(); } catch( SecurityException ee ) { }; byte[] buf = new byte[16384]; while(true) { ZipEntry entry = null; entry = zip.getNextEntry(); /* if( entry != null ) Log.i("SDL", "Extracting lib " + entry.getName()); */ if( entry == null ) { Log.i("SDL", "Extracting libs finished"); break; } if( entry.isDirectory() ) { File outDir = new File( libDir.getAbsolutePath() + "/" + entry.getName() ); if( !(outDir.exists() && outDir.isDirectory()) ) outDir.mkdirs(); continue; } OutputStream out = null; String path = libDir.getAbsolutePath() + "/" + entry.getName(); try { File outDir = new File( path.substring(0, path.lastIndexOf("/") )); if( !(outDir.exists() && outDir.isDirectory()) ) outDir.mkdirs(); } catch( SecurityException eeeee ) { }; Log.i("SDL", "Saving to file '" + path + "'"); out = new FileOutputStream( path ); int len = zip.read(buf); while (len >= 0) { if(len > 0) out.write(buf, 0, len); len = zip.read(buf); } out.flush(); out.close(); } for(String l : Globals.AppLibraries) { String libname = System.mapLibraryName(l); File libpath = new File(libDir, libname); Log.i("SDL", "libSDL: loading lib " + libpath.getPath()); System.load(libpath.getPath()); libpath.delete(); } } catch ( Exception ee ) { Log.i("SDL", "libSDL: Error: " + ee.toString()); } } String [] binaryZipNames = { "binaries-" + android.os.Build.CPU_ABI + ".zip", "binaries-" + android.os.Build.CPU_ABI2 + ".zip", "binaries.zip" }; for(String binaryZip: binaryZipNames) { try { Log.i("SDL", "libSDL: Trying to extract binaries from assets " + binaryZip); InputStream in = null; try { for( int i = 0; ; i++ ) { InputStream in2 = getAssets().open(binaryZip + String.format("%02d", i)); if( in == null ) in = in2; else in = new SequenceInputStream( in, in2 ); } } catch( IOException ee ) { try { if( in == null ) in = getAssets().open(binaryZip); } catch( IOException eee ) {} } if( in == null ) throw new RuntimeException("libSDL: Extracting binaries failed, the .apk file packaged incorrectly"); ZipInputStream zip = new ZipInputStream(in); File libDir = getFilesDir(); try { libDir.mkdirs(); } catch( SecurityException ee ) { }; byte[] buf = new byte[16384]; while(true) { ZipEntry entry = null; entry = zip.getNextEntry(); /* if( entry != null ) Log.i("SDL", "Extracting lib " + entry.getName()); */ if( entry == null ) { Log.i("SDL", "Extracting binaries finished"); break; } if( entry.isDirectory() ) { File outDir = new File( libDir.getAbsolutePath() + "/" + entry.getName() ); if( !(outDir.exists() && outDir.isDirectory()) ) outDir.mkdirs(); continue; } OutputStream out = null; String path = libDir.getAbsolutePath() + "/" + entry.getName(); try { File outDir = new File( path.substring(0, path.lastIndexOf("/") )); if( !(outDir.exists() && outDir.isDirectory()) ) outDir.mkdirs(); } catch( SecurityException eeeeeee ) { }; try { CheckedInputStream check = new CheckedInputStream( new FileInputStream(path), new CRC32() ); while( check.read(buf, 0, buf.length) > 0 ) {}; check.close(); if( check.getChecksum().getValue() != entry.getCrc() ) { File ff = new File(path); ff.delete(); throw new Exception(); } Log.i("SDL", "File '" + path + "' exists and passed CRC check - not overwriting it"); continue; } catch( Exception eeeeee ) { } Log.i("SDL", "Saving to file '" + path + "'"); out = new FileOutputStream( path ); int len = zip.read(buf); while (len >= 0) { if(len > 0) out.write(buf, 0, len); len = zip.read(buf); } out.flush(); out.close(); Settings.nativeChmod(path, 0755); //String chmod[] = { "/system/bin/chmod", "0755", path }; //Runtime.getRuntime().exec(chmod).waitFor(); } break; } catch ( Exception eee ) { //Log.i("SDL", "libSDL: Error: " + eee.toString()); } } }; public static void LoadApplicationLibrary(final Context context) { Settings.nativeChdir(Globals.DataDir); for(String l : Globals.AppMainLibraries) { try { String libname = System.mapLibraryName(l); File libpath = new File(context.getFilesDir().getAbsolutePath() + "/../lib/" + libname); Log.i("SDL", "libSDL: loading lib " + libpath.getAbsolutePath()); System.load(libpath.getPath()); } catch( UnsatisfiedLinkError e ) { Log.i("SDL", "libSDL: error loading lib " + l + ": " + e.toString()); try { String libname = System.mapLibraryName(l); File libpath = new File(context.getFilesDir().getAbsolutePath() + "/" + libname); Log.i("SDL", "libSDL: loading lib " + libpath.getAbsolutePath()); System.load(libpath.getPath()); } catch( UnsatisfiedLinkError ee ) { Log.i("SDL", "libSDL: error loading lib " + l + ": " + ee.toString()); System.loadLibrary(l); } } } } public int getApplicationVersion() { try { PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0); return packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { Log.i("SDL", "libSDL: Cannot get the version of our own package: " + e); } return 0; } public boolean isRunningOnOUYA() { try { PackageInfo packageInfo = getPackageManager().getPackageInfo("tv.ouya", 0); return true; } catch (PackageManager.NameNotFoundException e) { } return Globals.OuyaEmulation; } public boolean isCurrentOrientationHorizontal() { Display getOrient = getWindowManager().getDefaultDisplay(); return getOrient.getWidth() >= getOrient.getHeight(); } public FrameLayout getVideoLayout() { return _videoLayout; } static int NOTIFY_ID = 12367098; // Random ID private static DemoGLSurfaceView mGLView = null; private static AudioThread mAudioThread = null; private static DataDownloader downloader = null; private TextView _tv = null; private Button _btn = null; private LinearLayout _layout = null; private LinearLayout _layout2 = null; private Advertisement _ad = null; private FrameLayout _videoLayout = null; private EditText _screenKeyboard = null; private String _screenKeyboardHintMessage = null; static boolean keyboardWithoutTextInputShown = false; private boolean sdlInited = false; public interface TouchEventsListener { public void onTouchEvent(final MotionEvent ev); } public interface KeyEventsListener { public void onKeyEvent(final int keyCode); } public TouchEventsListener touchListener = null; public KeyEventsListener keyListener = null; boolean _isPaused = false; private InputMethodManager _inputManager = null; public LinkedList<Integer> textInput = new LinkedList<Integer> (); public static MainActivity instance = null; } abstract class DimSystemStatusBar { public static DimSystemStatusBar get() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) return DimSystemStatusBarHoneycomb.Holder.sInstance; else return DimSystemStatusBarDummy.Holder.sInstance; } public abstract void dim(final View view); private static class DimSystemStatusBarHoneycomb extends DimSystemStatusBar { private static class Holder { private static final DimSystemStatusBarHoneycomb sInstance = new DimSystemStatusBarHoneycomb(); } public void dim(final View view) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && Globals.ImmersiveMode) // Immersive mode, I already hear curses when system bar reappears mid-game from the slightest swipe at the bottom of the screen view.setSystemUiVisibility(android.view.View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | android.view.View.SYSTEM_UI_FLAG_FULLSCREEN); else view.setSystemUiVisibility(android.view.View.STATUS_BAR_HIDDEN); } } private static class DimSystemStatusBarDummy extends DimSystemStatusBar { private static class Holder { private static final DimSystemStatusBarDummy sInstance = new DimSystemStatusBarDummy(); } public void dim(final View view) { } } } abstract class SetLayerType { public static SetLayerType get() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) return SetLayerTypeHoneycomb.Holder.sInstance; else return SetLayerTypeDummy.Holder.sInstance; } public abstract void setLayerType(final View view); private static class SetLayerTypeHoneycomb extends SetLayerType { private static class Holder { private static final SetLayerTypeHoneycomb sInstance = new SetLayerTypeHoneycomb(); } public void setLayerType(final View view) { view.setLayerType(android.view.View.LAYER_TYPE_NONE, null); //view.setLayerType(android.view.View.LAYER_TYPE_HARDWARE, null); } } private static class SetLayerTypeDummy extends SetLayerType { private static class Holder { private static final SetLayerTypeDummy sInstance = new SetLayerTypeDummy(); } public void setLayerType(final View view) { } } } class DummyService extends Service { public DummyService() { super(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return Service.START_STICKY; } @Override public void onDestroy() { } @Override public IBinder onBind(Intent intent) { return null; } }
package com.rapid.server.filter; import java.io.IOException; import java.net.InetAddress; import java.security.GeneralSecurityException; import java.util.Enumeration; import java.util.List; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import com.rapid.core.Application; import com.rapid.core.Applications; import com.rapid.core.Email; import com.rapid.security.RapidSecurityAdapter; import com.rapid.security.SecurityAdapter; import com.rapid.security.SecurityAdapter.User; import com.rapid.server.RapidHttpServlet; import com.rapid.server.RapidRequest; public class FormAuthenticationAdapter extends RapidAuthenticationAdapter { public static final String SESSION_VARIABLE_LOGIN_PATH = "login"; public static final String SESSION_VARIABLE_PASSWORDRESET_PATH = "passwordreset"; public static final String SESSION_VARIABLE_PASSWORDUPDATE_PATH = "passwordupdate"; public static final String LOGIN_PATH = "login.jsp"; public static final String INDEX_PATH = "index.jsp"; public static final String RESET_PATH = "reset.jsp"; public static final String UPDATE_PATH = "update.jsp"; private static Logger _logger = LogManager.getLogger(RapidAuthenticationAdapter.class); private List<JSONObject> _jsonLogins = null; private String[] _ipChecks = null; public FormAuthenticationAdapter(FilterConfig filterConfig) { // call the super super(filterConfig); // look for ip check for sensitive pages String ipCheck = filterConfig.getInitParameter(INIT_PARAM_IP_CHECK); // if we got some, build the array now if (ipCheck != null) { // split them _ipChecks = ipCheck.split(","); // loop them for (int i = 0; i < _ipChecks.length; i++) { // trim them for good measure, and replace * _ipChecks[i] = _ipChecks[i].trim().replace("*",""); } // log _logger.info("IP addresses will be checked against " + ipCheck + " for access to sensitive resources."); } // log _logger.info("Form authentication filter initialised."); } @Override public ServletRequest process(ServletRequest req, ServletResponse res) throws IOException, ServletException { // cast the ServletRequest to a HttpServletRequest HttpServletRequest request = (HttpServletRequest) req; // log the full request if (_logger.isTraceEnabled()) { _logger.debug("FormAuthenticationAdapter request : " + request.getMethod() + " " + request.getRequestURL() + (request.getQueryString() == null ? "" : "?" + request.getQueryString())); Enumeration<String> headerNames = request.getHeaderNames(); String headers = ""; while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); headers += headerName + " = " + request.getHeader(headerName) + "; "; } _logger.debug("Headers : " + headers); } // now get just the resource path String requestPath = request.getServletPath(); // if null set to root if (requestPath == null) requestPath = "/"; if (requestPath.length() == 0) requestPath = "/"; // if ip checking is in place if (_ipChecks != null) { // get the query string String queryString = request.getQueryString(); // check we got one if (queryString == null) { // set to empty string queryString = ""; } else { // set to lower case queryString = queryString.toLowerCase(); } // if this is a sensitive resource if (requestPath.startsWith("/" + LOGIN_PATH) || requestPath.startsWith("/design.jsp") || requestPath.startsWith("/designpage.jsp") || requestPath.startsWith("/designer") || (requestPath.startsWith("/~") && queryString.contains("a=rapid"))) { // assume no pass boolean pass = false; // get the client IP String ip = request.getRemoteAddr(); // if this is for login.jsp if (requestPath.startsWith("/" + LOGIN_PATH)) { // get the user agent String agent = request.getHeader("User-Agent"); // if we got one if (agent != null) { // Rapid Mobile exempts just login.jsp from the IP checks if (agent.contains("RapidMobile")) pass = true; } } // if we haven't passed yet if (!pass) { // log _logger.debug("Checking IP " + ip + " for " + requestPath); // loop the ip checks for (String ipCheck : _ipChecks) { // check the ip starts with the filter, this allows full, or partial IPs (we remove the * for good measure) if (ip.startsWith(ipCheck)) { // we passed pass = true; // we're done break; } } } // if we failed if (!pass) { // log _logger.info("Access from " + ip + " for " + requestPath + " failed IP check"); // cast the ServletRequest to a HttpServletRequest HttpServletResponse response = (HttpServletResponse) res; // send a not found response.sendError(404); // no further processing return null; } } // sensitive resource } // ip checks // if we can return this resource without authentication if (requestPath.endsWith("favicon.ico") || requestPath.startsWith("/images/") || requestPath.startsWith("/scripts") || requestPath.startsWith("/styles")) { // proceed to the next step return req; } else { // if it's a resource that requires authentication _logger.trace("FormAuthenticationAdapter checking authorisation"); // cast response to http HttpServletResponse response = (HttpServletResponse) res; // assume default login page String loginPath = LOGIN_PATH; // assume default index page String indexPath = INDEX_PATH; // assume default password reset path String resetPath = RESET_PATH; // assume default password reset path String updatePath = UPDATE_PATH; // assume no userName String userName = null; // create a new session, if we need one HttpSession session = request.getSession(); // look in the session for username userName = (String) session.getAttribute(RapidFilter.SESSION_VARIABLE_USER_NAME); // look in the session for index path String sessionIndexPath = (String) session.getAttribute(RapidFilter.SESSION_VARIABLE_INDEX_PATH); // if we got one use it if (sessionIndexPath != null) indexPath = sessionIndexPath; // look in the session for the password reset path String sessionResetPath = (String) session.getAttribute(SESSION_VARIABLE_PASSWORDRESET_PATH); // if we got one use it if (sessionResetPath != null) resetPath = sessionResetPath; // look in the session for the password reset path String sessionUpdatePath = (String) session.getAttribute(SESSION_VARIABLE_PASSWORDUPDATE_PATH); // if we got one use it if (sessionUpdatePath != null) updatePath = sessionUpdatePath; // if email is enabled, reset is present, and we requested the password reset if ((Email.getEmailSettings() != null && requestPath.endsWith(resetPath))) { // look in the request for the email String email = request.getParameter("email"); // log that we are requesting a password update _logger.info("FormAuthenticationAdapter requesting password reset for " + email); // if password reset is present if (RapidSecurityAdapter.hasPasswordReset(getServletContext())) { // look in the request for the crsf token String crsfToken = request.getParameter("csrfToken"); // check we have what we need if (email == null || crsfToken == null) { // log the error _logger.error("FormAuthenticationAdapter error resetting password - required items not present"); } else { // check the token if (RapidRequest.getCSRFToken(session).equals(crsfToken)) { try { // get the applications collection Applications applications = (Applications) getServletContext().getAttribute("applications"); // if there are some applications if (applications != null) { // loop all applications for (Application application : applications.get()) { // get a Rapid request RapidRequest rapidRequest = new RapidRequest(request, application); // have the security reset this email and break once done if (application.getSecurityAdapter().resetUserPassword(rapidRequest, email)) break; } } } catch (Exception ex) { // log the error _logger.error("FormAuthenticationAdapter error resetting password for " + email, ex); } // Get the stored login path from session loginPath = (String) session.getAttribute(SESSION_VARIABLE_LOGIN_PATH); // if null set to default if (loginPath == null) loginPath = LOGIN_PATH; // send a message to display session.setAttribute("message", "A new password has been emailed - click <a href='" + loginPath + "'>here</a> to log in"); } else { // log the error _logger.error("FormAuthenticationAdapter error resetting password - csrf failed, email is " + email); } // csrf check } // items check } else { // log the error _logger.error("FormAuthenticationAdapter error resetting password - password reset is not supported, email is " + email); } // delay by 1sec to make brute force attacks a little harder try { Thread.sleep(1000); } catch (InterruptedException e) {} // proceed to the next step return req; } // password reset page request // check if we got a user name if (userName == null) { _logger.trace("No userName found in session"); // look for a sessionRequestPath attribute in the session String sessionRequestPath = (String) session.getAttribute("requestPath"); // look in the request for the username userName = request.getParameter("userName"); // if jsonLogins is null try and get some from the servlet context if (_jsonLogins == null) _jsonLogins = (List<JSONObject>) req.getServletContext().getAttribute("jsonLogins"); // if we have custom logins if (_jsonLogins != null) { // get the query string String queryString = request.getQueryString(); // loop the login pages for (JSONObject jsonLogin : _jsonLogins) { // get the custom login path String customLoginPath = jsonLogin.optString("path").trim(); // get the custom index String customIndexPath = jsonLogin.optString("index").trim(); // get any password reset String customPasswordReset = jsonLogin.optString("passwordreset",null); // assume the custom index is pretty url direct for app String customIndexApp = customIndexPath; // if the index path is non pretty if (customIndexPath.contains("a=")) { // find the start int startPos = customIndexPath.indexOf("a=") + 2; // find next & int endPos = customIndexPath.indexOf("&", startPos); // if there wasn't one, it's the end of the string if (endPos < startPos) endPos = customIndexPath.length() - 1; // get the app customIndexApp = customIndexPath.substring(startPos, endPos); } // if the request is for a custom login page, or the full request includes the custom index app if (requestPath.endsWith(customLoginPath) || (requestPath + queryString).contains(customIndexApp)) { // remember this custom login loginPath = customLoginPath; // put the login path in the session session.setAttribute(SESSION_VARIABLE_LOGIN_PATH, customLoginPath); // put the index path in the session session.setAttribute(RapidFilter.SESSION_VARIABLE_INDEX_PATH, customIndexPath); // put the password reset page in the session if there is one if (customPasswordReset != null) session.setAttribute(SESSION_VARIABLE_PASSWORDRESET_PATH, customPasswordReset.trim()); // add cache defeating to try and stop the 302 from custom login .jsp pages to index.jsp RapidFilter.noCache(response); // log _logger.trace("Custom login " + customLoginPath + " identified. Index set to " + customIndexPath); // we're done break; } // get the application parameter String appId = request.getParameter("a"); // check we got one if (appId != null) { // if custom index is the app which has just been requested if (customIndexPath.endsWith("a=" + appId) || customIndexPath.contains("a=" + appId + "&")) { // put the index path in the session session.setAttribute(RapidFilter.SESSION_VARIABLE_INDEX_PATH, customIndexPath); // send a redirect to load the custom login response.sendRedirect(customLoginPath); // return immediately return null; } } } } // check for a user in the request if (userName == null) { _logger.trace("No userName found in request"); // if we are attempting to authorise if (requestPath.endsWith(loginPath) && sessionRequestPath != null) { // check the url for a requestPath String urlRequestPath = request.getParameter("requestPath"); // overide the session one if so if (urlRequestPath != null) session.setAttribute("requestPath", urlRequestPath); // progress to the next step in the filter return req; } else { // if we're allowing public access, but not if this is the login page, nor RapidMobile if (_publicAccess && !requestPath.endsWith(loginPath) && request.getHeader("User-Agent") != null && !request.getHeader("User-Agent").contains("RapidMobile")) { // set the user name to public session.setAttribute(RapidFilter.SESSION_VARIABLE_USER_NAME, PUBLIC_ACCESS_USER); // set the password to none session.setAttribute(RapidFilter.SESSION_VARIABLE_USER_PASSWORD, ""); // progress to the next step in the filter return req; } } String acceptHeader = request.getHeader("Accept"); if (acceptHeader == null) acceptHeader = ""; // if this is json and not a login page just send a 401 if (acceptHeader.contains("application/json")) { // if this a request for a login page that came through an ajax json request if (requestPath.endsWith(loginPath)) { // send a 401 with the login path response.sendError(401, "location=" + loginPath); } else { // send a standard 401 - access denied response.sendError(401); } } else { // retain the request path less the leading / String authorisationRequestPath = requestPath.substring(1); // replace designpage.jsp with design.jsp to get us out of the parent authorisationRequestPath = authorisationRequestPath.replace("designpage.jsp", "design.jsp"); // append the query string if there was one if (request.getQueryString() != null) authorisationRequestPath += "?" + request.getQueryString(); // retain the request path in the session session.setAttribute("requestPath", authorisationRequestPath); // send a redirect to load the login page unless the login path (from the custom login) is the request path (this creates a redirect) if (authorisationRequestPath.equals(loginPath) && request.getHeader("User-Agent") != null && request.getHeader("User-Agent").contains("RapidMobile")) { // send a 401 with the login path to get RapidMobile to authenticate response.sendError(401, "location=" + loginPath); } else { // send a redirect with . in front to allow for Rapid instances below the root response.sendRedirect("./" + loginPath); } } // return immediately return null; } else { // log that we were provided with a user name _logger.trace("userName found in request"); // look in the request for the password String userPassword = request.getParameter("userPassword"); // look in the request for device details String deviceId = request.getParameter("deviceId"); // get the address from the request host InetAddress inetAddress = InetAddress.getByName(request.getRemoteHost()); // get the request device details String deviceDetails = "ip=" + inetAddress.getHostAddress() + ",name=" + inetAddress.getHostName() + ",agent=" + request.getHeader("User-Agent"); // if we were sent a device id add it to the device details if (deviceId != null) deviceDetails += "," + deviceId; // retain device id in the session so it's used when check app authorisation session.setAttribute(RapidFilter.SESSION_VARIABLE_USER_DEVICE, deviceDetails); // remember whether we are authorised for at least one application boolean authorised = RapidFilter.isAuthorised(req, userName, userPassword, indexPath); // we passed authorisation so redirect the client to the resource they wanted if (authorised) { // retain user name in the session session.setAttribute(RapidFilter.SESSION_VARIABLE_USER_NAME, userName); // retain encrypted user password in the session try { session.setAttribute(RapidFilter.SESSION_VARIABLE_USER_PASSWORD, RapidHttpServlet.getEncryptedXmlAdapter().marshal(userPassword)); } catch (GeneralSecurityException ex) { // log the error _logger.error("FormAuthenticationAdapter error storing encrypted password", ex); } // log that authentication was granted _logger.debug("FormAuthenticationAdapter authenticated " + userName + " from " + deviceDetails); // make the sessionRequest path the root just in case it was null (or login.jsp itself) if (sessionRequestPath == null || loginPath.equals(sessionRequestPath)) { // if index path is the default (usually index.jsp) if (INDEX_PATH.equals(indexPath)) { // convert to . to hide index.jsp from url sessionRequestPath = "."; } else { // request custom index path sessionRequestPath = indexPath; } // log _logger.trace("Session request path set to " + sessionRequestPath); } // if we had a requestApp in the sessionRequestPath, go straight to the app if (sessionRequestPath.indexOf("requestApp") > 0) { // split the parts String[] requestAppParts = sessionRequestPath.split("="); // if we have a second part with the appId in it if (requestAppParts.length > 1) { // set the sessionRequestPath to the appId sessionRequestPath = "~?a=" + requestAppParts[1]; } // log _logger.trace("Session request path set to " + sessionRequestPath); } // remove the authorisation session attribute session.setAttribute("requestPath", null); // send a redirect to reload what we wanted before response.sendRedirect(sessionRequestPath); // return to client immediately return null; } else { // log that authentication was unsuccessful _logger.debug("FormAuthenticationAdapter failed for " + userName + " from " + deviceDetails); // start the message String message = "Your user name or password has not been recognised"; // if email is configured if (Email.getEmailSettings() != null) { // if any app has password reset if (SecurityAdapter.hasPasswordReset(getServletContext())) message += " - click <a href='" + resetPath + "'>here</a> to reset your password"; } // retain the authorisation attempt in the session session.setAttribute("message", message); // delay by 1sec to make brute force attacks a little harder try { Thread.sleep(1000); } catch (InterruptedException e) {} // send a redirect to load the login page response.sendRedirect(loginPath); // return immediately return null; } // authorised } // check for a username parameter in request data } // authentication check (whether username is in session) // log the request path - see how it is cleaned up a bit at the top of this method _logger.trace("FormAuthenticationAdapter requestpath=" + requestPath + ", loginPath="); // if we are requesting the login.jsp or root but have authenticated, go to index instead if ((requestPath.contains(loginPath) || "/".equals(requestPath)) && "GET".equals(request.getMethod())) { _logger.trace("Redirecting to index: " + indexPath); // send a redirect to load the index response.sendRedirect(indexPath); // return immediately return null; } // if we are updating our password if (requestPath.endsWith(updatePath) && "POST".equals(request.getMethod())) { // log that we are requesting a password update _logger.info("FormAuthenticationAdapter requesting password update for " + userName); // if password reset is present if (RapidSecurityAdapter.hasPasswordUpdate(getServletContext())) { // default message String message = "Your current password is not correct"; // assume no updates performed boolean updatedPassword = false; // get csrf token String csrfToken = request.getParameter("csrfToken"); // check the token if (RapidRequest.getCSRFToken(session).equals(csrfToken)) { // get the old password String passwordOld = request.getParameter("password"); // get new password String passwordNew = request.getParameter("passwordNew"); // get new password check String passwordConfirm = request.getParameter("passwordConfirm"); // check nothing is missing if (csrfToken == null || passwordOld == null || passwordNew == null || passwordConfirm == null) { // log issue _logger.error("FormAuthenticationAdapter requesting password update failure, required items not present"); } else { // this is supposed to be caught by the front end but we'll do it here as well if (passwordNew.equals(passwordConfirm)) { try { // get the applications collection Applications applications = (Applications) getServletContext().getAttribute("applications"); // if there are some applications if (applications != null) { // remember if complexity is ok boolean complexityCheck = true; // loop all applications for (Application application : applications.get()) { // get a Rapid request for this application RapidRequest rapidRequest = new RapidRequest(request, application); // get the security adapter SecurityAdapter securityAdapter = application.getSecurityAdapter(); // check password complexity if (!securityAdapter.checkPasswordComplexity(rapidRequest, passwordNew)) { // retain failed complexity complexityCheck = false; // update the message message = securityAdapter.getPasswordComplexityDescription(rapidRequest, passwordNew); // log password not complex enough _logger.error("FormAuthenticationAdapter password not complex enough for " + application.getId() + "/" + application.getVersion()); // we're done break; } // password complexity check } // applications loop // if we password complexity check if (complexityCheck) { // loop all applications for (Application application : applications.get()) { // get a Rapid request for this application RapidRequest rapidRequest = new RapidRequest(request, application); // get the security adapter SecurityAdapter securityAdapter = application.getSecurityAdapter(); // if the old password passes if (securityAdapter.checkUserPassword(rapidRequest, userName, passwordOld)) { // get the user User user = securityAdapter.getUser(rapidRequest); // update the user password user.setPassword(passwordNew); // update the password securityAdapter.updateUser(rapidRequest, user); // update session password rapidRequest.setUserPassword(passwordNew); // set updated password updatedPassword = true; } // password check } // applications loop } // password complexity check } // applications check } catch (Exception ex) { // log the error _logger.error("FormAuthenticationAdapter error updating password for user " + userName, ex); } } else { _logger.error("FormAuthenticationAdapter requesting password update failure, new and confirm passwords do not match"); } // confirm password } // required items check if (updatedPassword) { // Get the stored login path from session indexPath = (String) session.getAttribute(RapidFilter.SESSION_VARIABLE_INDEX_PATH); // if null set to default if (indexPath == null) indexPath = INDEX_PATH; // send a message to display session.setAttribute("message", "Your password has been updated - click <a href='" + indexPath + "'>here</a> for your applications"); } else { // send a message to display session.setAttribute("message", message); } // updated password check } else { _logger.error("FormAuthenticationAdapter requesting password update failure, failed csrf"); } // csrf check } else { _logger.error("FormAuthenticationAdapter requesting password update failure, password update is not supported"); } } // update check // return the request which will process the chain // hold a reference to the original request HttpServletRequest filteredReq = request; // wrap the request if it is not a rapid request (with our username and principle) if(!(request instanceof RapidRequestWrapper)) filteredReq = new RapidRequestWrapper(request, userName); return filteredReq; } } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.madvoc; import jodd.http.HttpRequest; import jodd.http.HttpResponse; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertEquals; public class RawActionTest { @BeforeClass public static void beforeClass() { MadvocSuite.startTomcat(); } @AfterClass public static void afterClass() { MadvocSuite.stopTomcat(); } @Test public void testRawAction() { HttpResponse response = HttpRequest.get("localhost:8173/raw.html").send(); assertEquals("this is some raw direct result", response.bodyText().trim()); } @Test public void testRawTextAction() { HttpResponse response = HttpRequest.get("localhost:8173/raw.text.html").send(); assertEquals("some raw txt", response.bodyText().trim()); } @Test public void testRawDownloadAction() { HttpResponse response = HttpRequest.get("localhost:8173/raw.download").send(); assertEquals("attachment;filename=\"jodd-download.txt\";filename*=utf8''jodd-download.txt", response.header("content-disposition")); assertEquals("file from jodd.org!", response.bodyText().trim()); } }
package dr.evomodel.tree; import dr.evolution.tree.NodeRef; import dr.evolution.tree.Tree; import dr.evolution.util.Taxa; import dr.evolution.util.TaxonList; import dr.inference.model.Statistic; import dr.xml.*; import java.util.Set; /** * A statistic that tracks the time of MRCA of a set of taxa * * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: TMRCAStatistic.java,v 1.21 2005/07/11 14:06:25 rambaut Exp $ */ public class TMRCAStatistic extends Statistic.Abstract implements TreeStatistic { public static final String TMRCA_STATISTIC = "tmrcaStatistic"; public static final String MRCA = "mrca"; public TMRCAStatistic(String name, Tree tree, TaxonList taxa, boolean isRate) throws Tree.MissingTaxonException { super(name); this.tree = tree; this.leafSet = Tree.Utils.getLeavesForTaxa(tree, taxa); this.isRate = isRate; } public void setTree(Tree tree) { this.tree = tree; } public Tree getTree() { return tree; } public int getDimension() { return 1; } /** * @return the height of the MRCA node. */ public double getStatisticValue(int dim) { NodeRef node = Tree.Utils.getCommonAncestorNode(tree, leafSet); if (node == null) throw new RuntimeException("No node found that is MRCA of " + leafSet); if (isRate) { return tree.getNodeRate(node); } return tree.getNodeHeight(node); } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return TMRCA_STATISTIC; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { String name = xo.getAttribute(NAME, xo.getId()); Tree tree = (Tree) xo.getChild(Tree.class); TaxonList taxa = (TaxonList) xo.getElementFirstChild(MRCA); boolean isRate = xo.getAttribute("rate", false); try { return new TMRCAStatistic(name, tree, taxa, isRate); } catch (Tree.MissingTaxonException mte) { throw new XMLParseException( "Taxon, " + mte + ", in " + getParserName() + "was not found in the tree."); } }
package com.subgraph.orchid.circuits.hs; import com.subgraph.orchid.crypto.TorPublicKey; import com.subgraph.orchid.data.HexDigest; import com.subgraph.orchid.data.IPv4Address; public class IntroductionPoint { private HexDigest identity; private IPv4Address address; private int onionPort; private TorPublicKey onionKey; private TorPublicKey serviceKey; IntroductionPoint(HexDigest identity) { this.identity = identity; } void setAddress(IPv4Address address) { this.address = address; } void setOnionPort(int onionPort) { this.onionPort = onionPort; } void setOnionKey(TorPublicKey onionKey) { this.onionKey = onionKey; } void setServiceKey(TorPublicKey serviceKey) { this.serviceKey = serviceKey; } }
package com.intellij.jar; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.compiler.CompileContext; import com.intellij.openapi.compiler.CompileScope; import com.intellij.openapi.compiler.PackagingCompiler; import com.intellij.openapi.compiler.ValidityState; import com.intellij.openapi.compiler.make.BuildInstructionVisitor; import com.intellij.openapi.compiler.make.BuildRecipe; import com.intellij.openapi.compiler.make.FileCopyInstruction; import com.intellij.openapi.deployment.ModuleContainer; import com.intellij.openapi.deployment.ModuleLink; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ArrayUtil; import com.intellij.util.io.IOUtil; import gnu.trove.THashSet; import gnu.trove.TObjectLongHashMap; import gnu.trove.TObjectLongProcedure; import org.jetbrains.annotations.NotNull; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.util.Collection; public class JarCompiler implements PackagingCompiler { private static final Logger LOG = Logger.getInstance("#com.intellij.jar.JarCompiler"); private static final JarCompiler INSTANCE = new JarCompiler(); public static JarCompiler getInstance() { return INSTANCE; } public void processOutdatedItem(final CompileContext context, String url, final ValidityState state) { if (state != null) { ApplicationManager.getApplication().runReadAction(new Runnable() { public void run() { MyValState valState = (MyValState)state; String jarPath = valState.getOutputJarUrl(); if (jarPath != null) { FileUtil.delete(new File(VfsUtil.urlToPath(jarPath))); } } }); } } public ValidityState createValidityState(DataInputStream is) throws IOException { return new MyValState(is); } static class MyValState implements ValidityState { private final String myModuleName; private final String[] sourceUrls; private final long[] timestamps; private final String outputJarUrl; private final long outputJarTimestamp; public MyValState(final Module module) { myModuleName = module.getName(); final BuildJarSettings jarSettings = BuildJarSettings.getInstance(module); outputJarUrl = jarSettings.getJarUrl(); outputJarTimestamp = new File(VfsUtil.urlToPath(outputJarUrl)).lastModified(); final TObjectLongHashMap<String> url2Timestamps = new TObjectLongHashMap<String>(); ApplicationManager.getApplication().runReadAction(new Runnable(){ public void run() { BuildRecipe buildRecipe = BuildJarProjectSettings.getBuildRecipe(module, jarSettings); buildRecipe.visitInstructions(new BuildInstructionVisitor() { public boolean visitFileCopyInstruction(FileCopyInstruction instruction) throws Exception { File source = instruction.getFile(); VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(source.getPath())); if (virtualFile != null) { addFilesToMap(virtualFile, url2Timestamps); } return true; } }, false); } }); sourceUrls = new String[url2Timestamps.size()]; timestamps = new long[url2Timestamps.size()]; TObjectLongProcedure<String> iterator = new TObjectLongProcedure<String>() { int i = 0; public boolean execute(final String url, final long timestamp) { sourceUrls[i] = url; timestamps[i] = timestamp; i++; return true; } }; url2Timestamps.forEachEntry(iterator); } private static void addFilesToMap(final VirtualFile virtualFile, final TObjectLongHashMap<String> url2Timestamps) { if (virtualFile.isDirectory()) { VirtualFile[] children = virtualFile.getChildren(); for (VirtualFile child : children) { addFilesToMap(child, url2Timestamps); } } else { long timestamp = virtualFile.getModificationStamp(); url2Timestamps.put(virtualFile.getUrl(), timestamp); } } public MyValState(final DataInputStream is) throws IOException { myModuleName = IOUtil.readString(is); int size = is.readInt(); sourceUrls = new String[size]; timestamps = new long[size]; for (int i=0;i<size;i++) { String url = IOUtil.readString(is); long timestamp = is.readLong(); sourceUrls[i] = url; timestamps[i] = timestamp; } outputJarUrl = IOUtil.readString(is); outputJarTimestamp = is.readLong(); } public void save(DataOutputStream os) throws IOException { IOUtil.writeString(myModuleName,os); int size = sourceUrls.length; os.writeInt(size); for (int i=0;i<size;i++) { String url = sourceUrls[i]; long timestamp = timestamps[i]; IOUtil.writeString(url, os); os.writeLong(timestamp); } IOUtil.writeString(outputJarUrl, os); os.writeLong(outputJarTimestamp); } public String getOutputJarUrl() { return outputJarUrl; } public boolean equalsTo(ValidityState otherState) { if (!(otherState instanceof MyValState)) return false; final MyValState other = (MyValState)otherState; if (!myModuleName.equals(other.myModuleName)) return false; if (sourceUrls.length != other.sourceUrls.length) return false; for (int i = 0; i < sourceUrls.length; i++) { String url = sourceUrls[i]; long timestamp = timestamps[i]; if (!url.equals(other.sourceUrls[i]) || timestamp != other.timestamps[i]) return false; } if (!Comparing.strEqual(outputJarUrl,other.outputJarUrl)) return false; if (outputJarTimestamp != other.outputJarTimestamp) return false; return true; } } static class MyProcItem implements ProcessingItem { private final Module myModule; public MyProcItem(Module module) { myModule = module; } @NotNull public VirtualFile getFile() { // return (semifake) file url to store compiler cache entry under return myModule.getModuleFile(); } @NotNull public MyValState getValidityState() { return new MyValState(myModule); } public Module getModule() { return myModule; } } @NotNull public ProcessingItem[] getProcessingItems(final CompileContext context) { return ApplicationManager.getApplication().runReadAction(new Computable<ProcessingItem[]>(){ public ProcessingItem[] compute() { final CompileScope compileScope = context.getCompileScope(); final Module[] affectedModules = compileScope.getAffectedModules(); if (affectedModules.length == 0) return ProcessingItem.EMPTY_ARRAY; Project project = affectedModules[0].getProject(); Module[] modules = ModuleManager.getInstance(project).getModules(); Collection<Module> modulesToRebuild = new THashSet<Module>(); for (Module module : modules) { BuildJarSettings jarSettings = BuildJarSettings.getInstance(module); if (jarSettings == null || !jarSettings.isBuildJar()) continue; ModuleContainer moduleContainer = jarSettings.getModuleContainer(); ModuleLink[] containingModules = moduleContainer.getContainingModules(); for (ModuleLink moduleLink : containingModules) { Module containingModule = moduleLink.getModule(); if (ArrayUtil.find(affectedModules, containingModule) != -1) { modulesToRebuild.add(module); } } } ProcessingItem[] result = new ProcessingItem[modulesToRebuild.size()]; int i=0; for (Module moduleToBuild : modulesToRebuild) { if (moduleToBuild.getModuleFile() == null) continue; result[i++] = new MyProcItem(moduleToBuild); } return result; } }); } public ProcessingItem[] process(final CompileContext context, final ProcessingItem[] items) { try { for (ProcessingItem item : items) { MyProcItem procItem = (MyProcItem)item; Module module = procItem.getModule(); BuildJarSettings jarSettings = BuildJarSettings.getInstance(module); BuildJarProjectSettings.buildJar(module, jarSettings, context.getProgressIndicator()); } } catch (IOException e) { LOG.error(e); } return items; } @NotNull public String getDescription() { return "jar compile"; } public boolean validateConfiguration(CompileScope scope) { return true; } }
package org.jpos.iso.channel; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; import org.jpos.iso.*; import org.jpos.iso.header.BASE1Header; import org.jpos.util.LogEvent; import org.jpos.util.Logger; import java.io.IOException; import java.net.ServerSocket; /** * ISOChannel implementation - VISA's VAP framing * * @author [email protected] * @version $Id$ * @see ISOMsg * @see ISOException * @see ISOChannel */ @SuppressWarnings("unused") public class VAPChannel extends BaseChannel { String srcid = "000000"; String dstid = "000000"; /** * Public constructor (used by Class.forName("...").newInstance()) */ public VAPChannel () { super(); } /** * Construct client ISOChannel * @param host server TCP Address * @param port server port number * @param p an ISOPackager (should be ISO87BPackager) * @see org.jpos.iso.packager.ISO87BPackager */ public VAPChannel (String host, int port, ISOPackager p) { super(host, port, p); } /** * Construct server ISOChannel * @param p an ISOPackager (should be ISO87BPackager) * @exception IOException * @see org.jpos.iso.packager.ISO87BPackager */ public VAPChannel (ISOPackager p) throws IOException { super(p); } /** * constructs a server ISOChannel associated with a Server Socket * @param p an ISOPackager * @param serverSocket where to accept a connection * @exception IOException * @see ISOPackager */ public VAPChannel (ISOPackager p, ServerSocket serverSocket) throws IOException { super(p, serverSocket); } /** * The default header for VAPChannel is BASE1Header */ protected ISOHeader getDynamicHeader (byte[] image) { return new BASE1Header(image); } /** * This method reads in a Base 1 Header. * * @param hLen * @return * @throws IOException */ protected byte[] readHeader(int hLen) throws IOException { // Read the first byte of the header (header length) int b = serverIn.read(); int bytesRead = b; if (b != -1) { // Create am array to read the header into byte bytes[] = new byte[b]; // Stick the first byte in bytes[0] = (byte) b; // and read the rest of the header serverIn.readFully(bytes, 1, b - 1); // Is there another header following on if ((bytes[1] & 0x80) == 0x80) { b = serverIn.read(); bytesRead += b; // Create an array big enough for both headers byte tmp[] = new byte[bytesRead]; // Copy in the original System.arraycopy(bytes, 0, tmp, 0, bytes.length); // And this one tmp[bytes.length] = (byte) b; serverIn.readFully(tmp, bytes.length + 1, b - 1); bytes = tmp; } return bytes; } else { throw new IOException("Error reading header"); } } protected void sendMessageLength(int len) throws IOException { serverOut.write (len >> 8); serverOut.write (len); serverOut.write (0); serverOut.write (0); } /** * @param m the message * @param len already packed message len (to avoid re-pack) * @exception IOException */ protected void sendMessageHeader(ISOMsg m, int len) throws IOException { ISOHeader h = (m.getHeader() != null) ? m.getISOHeader() : new BASE1Header (srcid, dstid); if (h instanceof BASE1Header) ((BASE1Header)h).setLen(len); serverOut.write(h.pack()); } protected int getMessageLength() throws IOException, ISOException { int l = 0; byte[] b = new byte[4]; // ignore VAP polls (0 message length) while (l == 0) { serverIn.readFully(b,0,4); l = ((((int)b[0])&0xFF) << 8) | (((int)b[1])&0xFF); if (l == 0) { serverOut.write(b); serverOut.flush(); Logger.log (new LogEvent (this, "poll")); } } return l; } protected int getHeaderLength() { return BASE1Header.LENGTH; } protected boolean isRejected(byte[] b) { BASE1Header h = new BASE1Header(b); return h.isRejected() || (h.getHLen() != BASE1Header.LENGTH); } protected boolean shouldIgnore (byte[] b) { if (b != null) { BASE1Header h = new BASE1Header(b); return h.getFormat() > 2; } return false; } /** * sends an ISOMsg over the TCP/IP session. * * swap source/destination addresses in BASE1Header if * a reply message is detected.<br> * Sending an incoming message is seen as a reply. * * @param m the Message to be sent * @exception IOException * @exception ISOException * @see ISOChannel#send */ public void send (ISOMsg m) throws IOException, ISOException { if (m.isIncoming() && m.getHeader() != null) { BASE1Header h = new BASE1Header(m.getHeader()); h.swapDirection(); } super.send(m); } public void setConfiguration (Configuration cfg) throws ConfigurationException { srcid = cfg.get ("srcid", "000000"); dstid = cfg.get ("dstid", "000000"); super.setConfiguration (cfg); } }
package dr.inference.trace; import dr.evolution.io.Importer; import dr.evolution.io.NexusImporter; import dr.evolution.io.TreeImporter; import dr.evolution.tree.Tree; import dr.evomodel.coalescent.VDdemographicFunction; import dr.evomodel.coalescent.VariableDemographicModel; import dr.evomodelxml.LoggerParser; import dr.stats.DiscreteStatistics; import dr.util.HeapSort; import dr.util.TabularData; import dr.xml.*; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Arrays; /** * @author Joseph Heled */ public class EBSPAnalysis extends TabularData { private double[] xPoints; private double[] means; private double[] medians; private double[][] hpdLower; private double[][] hpdHigh; private double[] HPDLevels; // each bin covers xPoints[-1]/coalBins.length private int[] coalBins; private boolean quantiles; EBSPAnalysis(File log, File[] treeFiles, VariableDemographicModel.Type modelType, String firstColumnName, String firstIndicatorColumnName, String rootHeightColumnName, int coalPointBins, double burnIn, double[] inHPDLevels, boolean quantiles, boolean logSpace, boolean mid, int restrictToNchanges) throws IOException, Importer.ImportException, TraceException { LogFileTraces ltraces = new LogFileTraces(log.getCanonicalPath(), log); ltraces.loadTraces(); ltraces.setBurnIn(0); final int runLengthIncludingBurnin = ltraces.getStateCount(); int intBurnIn = (int) Math.floor(burnIn < 1 ? runLengthIncludingBurnin * burnIn : burnIn); final int nStates = runLengthIncludingBurnin - intBurnIn; //intBurnIn *= ltraces.getStepSize(); ltraces.setBurnIn(intBurnIn * ltraces.getStepSize()); assert ltraces.getStateCount() == nStates; this.quantiles = quantiles; HPDLevels = (inHPDLevels != null) ? inHPDLevels : new double[]{0.95}; int populationFirstColumn = -1; int indicatorsFirstColumn = -1; int rootHeightColumn = -1; for (int n = 0; n < ltraces.getTraceCount(); ++n) { final String traceName = ltraces.getTraceName(n); if (traceName.equals(firstColumnName)) { populationFirstColumn = n; } else if (traceName.equals(firstIndicatorColumnName)) { indicatorsFirstColumn = n; } else if (rootHeightColumnName != null && traceName.equals(rootHeightColumnName)) { rootHeightColumn = n; } } if (populationFirstColumn < 0 || indicatorsFirstColumn < 0) { throw new TraceException("incorrect trace column names: unable to find populations/indicators"); } double binSize = 0; if (coalPointBins > 0) { if (rootHeightColumn < 0) { throw new TraceException("incorrect tree height column"); } double hSum = -0; double[] h = new double[1]; for (int ns = 0; ns < nStates; ++ns) { ltraces.getStateValues(ns, h, rootHeightColumn); hSum += h[0]; } binSize = hSum / (nStates * coalPointBins); coalBins = new int[coalPointBins]; Arrays.fill(coalBins, 0); } TreeImporter[] treeImporters = new TreeImporter[treeFiles.length]; final boolean isStepWise = modelType == VariableDemographicModel.Type.STEPWISE; int nIndicators = 0; for (int k = 0; k < treeFiles.length; ++k) { // System.err.println("burnin " + treeFiles[k] + "(" + k + ")"); treeImporters[k] = new NexusImporter(new FileReader(treeFiles[k])); assert intBurnIn > 0; for (int z = 0; z < intBurnIn - 1; ++z) { treeImporters[k].importNextTree(); } nIndicators += treeImporters[k].importNextTree().getExternalNodeCount() - 1; } if (isStepWise) { nIndicators -= 1; } final int nXaxisPoints = nIndicators + (isStepWise ? 1 : 0) + 1; xPoints = new double[nXaxisPoints]; Arrays.fill(xPoints, 0.0); int nDataPoints = 0; VDdemographicFunction[] allDemog = new VDdemographicFunction[nStates]; { double[] indicators = new double[nIndicators]; double[] pop = new double[nIndicators + 1]; Tree[] tt = new Tree[treeFiles.length]; boolean match = true; for (int ns = 0; ns < nStates; ++ns) { ltraces.getStateValues(ns, indicators, indicatorsFirstColumn); ltraces.getStateValues(ns, pop, populationFirstColumn); if(match){ for (int nt = 0; nt < tt.length; ++nt) { tt[nt] = treeImporters[nt].importNextTree(); } } //Get tree state number String name1 = tt[0].getId(); int state1 = Integer.parseInt(name1.substring(name1.indexOf('_')+1, name1.length())); String name2 = tt[1].getId(); int state2 = Integer.parseInt(name1.substring(name2.indexOf('_')+1, name2.length())); if (state1 != state2){ //... can this happen at all? throw new TraceException("NEXUS tree files have different rates or corrupted!!!!"); //Not too sure what kind of message is appropriate here. }else if((ns+intBurnIn)*ltraces.getStepSize() == state1){ //Check if log state matches tree state match = true; final VDdemographicFunction demoFunction = new VDdemographicFunction(tt, modelType, indicators, pop, logSpace, mid); if (demoFunction.numberOfChanges() == restrictToNchanges) { continue; } double[] xs = demoFunction.allTimePoints(); for (int k = 0; k < xs.length; ++k) { xPoints[k + 1] += xs[k]; } if (coalPointBins > 0) { for (double x : xs) { coalBins[Math.min((int) (x / binSize), coalBins.length - 1)]++; } } allDemog[nDataPoints] = demoFunction; ++nDataPoints; demoFunction.freeze(); }else{ match = false; } } for (int k = 0; k < xPoints.length; ++k) { xPoints[k] /= nStates; } if(nStates != nDataPoints){ //Warning if log file ant tree files // have different rates System.err.println("Different Rates is \"main\" and \"tree\" log files"); } if(nDataPoints < 10){ //Warning if number of states is not sufficient // enough to do the analysis System.err.println("Warning!!! Not Sufficient number of data points"); } } double[] popValues = new double[nDataPoints]; means = new double[nXaxisPoints]; medians = new double[nXaxisPoints]; hpdLower = new double[HPDLevels.length][]; hpdHigh = new double[HPDLevels.length][]; for (int i = 0; i < HPDLevels.length; ++i) { hpdLower[i] = new double[nXaxisPoints]; hpdHigh[i] = new double[nXaxisPoints]; } for (int nx = 0; nx < xPoints.length; ++nx) { final double x = xPoints[nx]; for (int ns = 0; ns < nDataPoints; ++ns) { popValues[ns] = allDemog[ns].getDemographic(x); } int[] indices = new int[popValues.length]; HeapSort.sort(popValues, indices); means[nx] = DiscreteStatistics.mean(popValues); for (int i = 0; i < HPDLevels.length; ++i) { if (quantiles) { hpdLower[i][nx] = DiscreteStatistics.quantile((1 - HPDLevels[i]) / 2, popValues, indices); hpdHigh[i][nx] = DiscreteStatistics.quantile((1 + HPDLevels[i]) / 2, popValues, indices); } else { final double[] hpd = DiscreteStatistics.HPDInterval(HPDLevels[i], popValues, indices); hpdLower[i][nx] = hpd[0]; hpdHigh[i][nx] = hpd[1]; } } medians[nx] = DiscreteStatistics.median(popValues, indices); } } private final String[] columnNames = {"time", "mean", "median"}; public int nColumns() { return columnNames.length + 2 * HPDLevels.length + (coalBins != null ? 1 : 0); } public String columnName(int nColumn) { final int fixed = columnNames.length; if (nColumn < fixed) { return columnNames[nColumn]; } nColumn -= fixed; if (nColumn < 2 * HPDLevels.length) { final double p = HPDLevels[nColumn / 2]; final String s = (nColumn % 2 == 0) ? "lower" : "upper"; return (quantiles ? "cpd " : "hpd ") + s + " " + Math.round(p * 100); } assert (nColumn - 2 * HPDLevels.length) == 0; return "bins"; } public int nRows() { return Math.max(xPoints.length, (coalBins != null ? coalBins.length : 0)); } public Object data(int nRow, int nColumn) { switch (nColumn) { case 0: { if (nRow < xPoints.length) { return xPoints[nRow]; } break; } case 1: { if (nRow < means.length) { return means[nRow]; } break; } case 2: { if (nRow < medians.length) { return medians[nRow]; } break; } default: { final int j = nColumn - columnNames.length; if (j < 2 * HPDLevels.length) { if (nRow < xPoints.length) { final int k = j / 2; if (0 <= k && k < HPDLevels.length) { if (j % 2 == 0) { return hpdLower[k][nRow]; } else { return hpdHigh[k][nRow]; } } } } else { if (nRow < coalBins.length) { return coalBins[nRow]; } } break; } } return ""; } // should be local to PARSER, but this makes them non-accesible from the outside in Java. public static final String VD_ANALYSIS = "VDAnalysis"; public static final String FILE_NAME = "fileName"; public static final String BURN_IN = "burnIn"; public static final String HPD_LEVELS = "Confidencelevels"; public static final String QUANTILES = "useQuantiles"; public static final String LOG_SPACE = VariableDemographicModel.LOG_SPACE; public static final String USE_MIDDLE = VariableDemographicModel.USE_MIDPOINTS; public static final String N_CHANGES = "nChanges"; public static final String TREE_LOG = "treeOfLoci"; public static final String LOG_FILE_NAME = "logFileName"; public static final String TREE_FILE_NAMES = "treeFileNames"; public static final String MODEL_TYPE = "populationModelType"; public static final String POPULATION_FIRST_COLUMN = "populationFirstColumn"; public static final String INDICATORS_FIRST_COLUMN = "indicatorsFirstColumn"; public static final String ROOTHEIGHT_COLUMN = "rootheightColumn"; public static final String NBINS = "nBins"; public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() { private String getElementText(XMLObject xo, String childName) throws XMLParseException { return ((XMLObject) xo.getChild(childName)).getStringChild(0); } public String getParserName() { return VD_ANALYSIS; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { try { // 10% is brun-in default double burnin = xo.getAttribute(BURN_IN, 0.1); if (burnin < 0) throw new XMLParseException("burnIn should be either between 0 and 1 or a positive number"); final double[] hpdLevels = xo.hasAttribute(HPD_LEVELS) ? xo.getDoubleArrayAttribute(HPD_LEVELS) : null; final File log = LoggerParser.getFile(getElementText(xo, LOG_FILE_NAME)); final XMLObject treeFileNames = (XMLObject) xo.getChild(TREE_FILE_NAMES); final int nTrees = treeFileNames.getChildCount(); File[] treeFiles = new File[nTrees]; for (int k = 0; k < nTrees; ++k) { treeFiles[k] = LoggerParser.getFile(((XMLObject) treeFileNames.getChild(k)).getStringChild(0)); } String modelTypeName = getElementText(xo, MODEL_TYPE).trim().toUpperCase(); String populationFirstColumn = getElementText(xo, POPULATION_FIRST_COLUMN); String indicatorsFirstColumn = getElementText(xo, INDICATORS_FIRST_COLUMN); VariableDemographicModel.Type modelType = VariableDemographicModel.Type.valueOf(modelTypeName); String rootHeightColumn = null; int nBins = -1; if (xo.hasAttribute(NBINS)) { if (xo.getChild(ROOTHEIGHT_COLUMN) != null) { rootHeightColumn = getElementText(xo, ROOTHEIGHT_COLUMN); nBins = xo.getIntegerAttribute(NBINS); } } final boolean quantiles = xo.getAttribute(QUANTILES, false); final boolean logSpace = xo.getAttribute(LOG_SPACE, false); final boolean useMid = xo.getAttribute(USE_MIDDLE, false); final int onlyNchanges = xo.getAttribute(N_CHANGES, -1); return new EBSPAnalysis(log, treeFiles, modelType, populationFirstColumn, indicatorsFirstColumn, rootHeightColumn, nBins, burnin, hpdLevels, quantiles, logSpace, useMid, onlyNchanges); } catch (java.io.IOException ioe) { throw new XMLParseException(ioe.getMessage()); } catch (Importer.ImportException e) { throw new XMLParseException(e.toString()); } catch (TraceException e) { throw new XMLParseException(e.toString()); } }
package com.tactfactory.harmony.plateforme; import com.google.common.base.Strings; import com.tactfactory.harmony.plateforme.android.AndroidAdapter; import com.tactfactory.harmony.plateforme.ios.IosAdapter; import com.tactfactory.harmony.plateforme.rim.RimAdapter; import com.tactfactory.harmony.plateforme.winphone.WinphoneAdapter; /** * Target platform. * */ public enum TargetPlatform { /** All platforms. */ ALL (0, "all", null), /** Web. */ WEB (1005, "web", null), //TODO WebAdapter.class), /** Android. */ ANDROID (2004, "android", AndroidAdapter.class), /** iPhone. */ IPHONE (3005, "iphone", IosAdapter.class), /** iPad. */ IPAD (3105, "ipad", IosAdapter.class), /** RIM. */ RIM (4006, "rim", RimAdapter.class), /** WinPhone. */ WINPHONE(5007, "winphone", WinphoneAdapter.class); /** Value. */ private final int value; /** Platform name. */ private final String str; private final Class<?> adapterType; /** * Constructor. * @param v The value * @param s The platform name */ TargetPlatform(final int v, final String s, Class<?> adapterType) { this.value = v; this.str = s; this.adapterType = adapterType; } /** * Get the platform value. * @return the value */ public int getValue() { return this.value; } /** * Get the platform name. * @return the platform name */ public String toLowerString() { return this.str; } public Class<?> getAdapterType() { return this.adapterType; } /** * Parses a target to get the correct platform. * @param target The target to parse * @return The found platform. (All if nothing else found) */ public static TargetPlatform parse(final String target) { TargetPlatform result = TargetPlatform.ALL; if (!Strings.isNullOrEmpty(target)) { if (target.equalsIgnoreCase( TargetPlatform.ANDROID.toLowerString())) { result = TargetPlatform.ANDROID; } else if (target.equalsIgnoreCase( TargetPlatform.IPHONE.toLowerString())) { result = TargetPlatform.IPHONE; } else if (target.equalsIgnoreCase( TargetPlatform.RIM.toLowerString())) { result = TargetPlatform.RIM; } else // if (target.equalsIgnoreCase( // TargetPlatform.WINPHONE.toLowerString())) { // result = TargetPlatform.WINPHONE; // } else if (target.equalsIgnoreCase( TargetPlatform.WEB.toLowerString())) { result = TargetPlatform.WEB; } } return result; } /** * Parses a target to get the correct platform. * @param target The target to parse * @return The found platform. (All if nothing else found) */ public static TargetPlatform parse(final BaseAdapter adapter) { TargetPlatform result = TargetPlatform.ALL; if (adapter != null) { if (TargetPlatform.ANDROID .getAdapterType().getClass().equals(adapter.getClass())) { result = TargetPlatform.ANDROID; } else if (TargetPlatform.IPHONE .getAdapterType().getClass().equals(adapter.getClass())) { result = TargetPlatform.IPHONE; } else if (TargetPlatform.RIM .getAdapterType().getClass().equals(adapter.getClass())) { result = TargetPlatform.RIM; } else if (TargetPlatform.WINPHONE .getAdapterType().getClass().equals(adapter.getClass())) { result = TargetPlatform.WINPHONE; } //else // if (TargetPlatform.WEB // .getAdapterType().getClass().equals(adapter.getClass())) { // result = TargetPlatform.WEB; } return result; } }
package edu.oakland.OUSoft.items; /** * "The person class should include information such as id, first name, last name, etc." */ public class Person { private String ID; private String FirstName; private String LastName; private Date Birthday; /** * Create an empty person */ public Person() { } /** * Create a person with a first name and last name. * * @param firstName The first name of the Person * @param lastName The last name of the Person */ public Person(String firstName, String lastName) { this.FirstName = firstName; this.LastName = lastName; } /** * Create a person with an ID, first name, and last name. * * @param ID The ID of the Person * @param firstName The first name of the Person * @param lastName The last name of the Person */ public Person(String ID, String firstName, String lastName) { this.ID = ID; this.FirstName = firstName; this.LastName = lastName; } public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } public String getFirstName() { return FirstName; } public void setFirstName(String firstName) { FirstName = firstName; } public String getLastName() { return LastName; } public void setLastName(String lastName) { LastName = lastName; } public Date getBirthday() { return Birthday; } public void setBirthday(Date birthday) { Birthday = birthday; } }
package com.untamedears.ItemExchange.utility; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.BookMeta; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.FireworkEffectMeta; import org.bukkit.inventory.meta.FireworkMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.inventory.meta.MapMeta; import org.bukkit.inventory.meta.PotionMeta; import org.bukkit.inventory.meta.SkullMeta; import com.untamedears.ItemExchange.ItemExchangePlugin; import com.untamedears.ItemExchange.exceptions.ExchangeRuleCreateException; import com.untamedears.ItemExchange.exceptions.ExchangeRuleParseException; import com.untamedears.ItemExchange.metadata.AdditionalMetadata; import com.untamedears.ItemExchange.metadata.BookMetadata; import com.untamedears.ItemExchange.metadata.EnchantmentStorageMetadata; import com.untamedears.citadel.Citadel; import com.untamedears.citadel.entity.Faction; /* * Contains the rules pertaining to an item which can participate in the exchange */ /** * * @author Brian Landry */ public class ExchangeRule { private static final List<Material> NOT_SUPPORTED = Arrays.asList(Material.MAP, Material.WRITTEN_BOOK, Material.ENCHANTED_BOOK, Material.FIREWORK, Material.FIREWORK_CHARGE, Material.POTION); public static final String hiddenRuleSpacer = "§&§&§&§&§r"; public static final String hiddenCategorySpacer = "§&§&§&§r"; public static final String hiddenSecondarySpacer = "§&§&§r"; public static final String hiddenTertiarySpacer = "§&§r"; public static final String ruleSpacer = "&&&&r"; public static final String categorySpacer = "&&&r"; public static final String secondarySpacer = "&&r"; public static final String tertiarySpacer = "&r"; private Material material; private int amount; private short durability; private Map<Enchantment, Integer> requiredEnchantments; private List<Enchantment> excludedEnchantments; private boolean unlistedEnchantmentsAllowed; private String displayName; private String[] lore; private RuleType ruleType; private AdditionalMetadata additional = null; private Faction citadelGroup = null; /* * Describes whether the Exchange Rule functions as an input or an output */ public static enum RuleType { INPUT, OUTPUT } public ExchangeRule(Material material, int amount, short durability, RuleType ruleType) { this(material, amount, durability, new HashMap<Enchantment, Integer>(), new ArrayList<Enchantment>(), false, "", new String[0], ruleType); } public ExchangeRule(Material material, int amount, short durability, Map<Enchantment, Integer> requiredEnchantments, List<Enchantment> excludedEnchantments, boolean otherEnchantmentsAllowed, String displayName, String[] lore, RuleType ruleType) { this.material = material; this.amount = amount; this.durability = durability; this.requiredEnchantments = requiredEnchantments; this.excludedEnchantments = excludedEnchantments; this.unlistedEnchantmentsAllowed = otherEnchantmentsAllowed; this.displayName = displayName; this.lore = lore; this.ruleType = ruleType; } public void setAdditionalMetadata(AdditionalMetadata meta) { this.additional = meta; } /* * Parses an ItemStack into an ExchangeRule which represents that ItemStack */ public static ExchangeRule parseItemStack(ItemStack itemStack, RuleType ruleType) throws ExchangeRuleCreateException { Map<Enchantment, Integer> requiredEnchantments = new HashMap<Enchantment, Integer>(); for (Enchantment enchantment : itemStack.getEnchantments().keySet()) { requiredEnchantments.put(enchantment, itemStack.getEnchantments().get(enchantment)); } String displayName = ""; String[] lore = new String[0]; AdditionalMetadata additional = null; if (itemStack.hasItemMeta()) { ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta.hasDisplayName()) { displayName = itemMeta.getDisplayName(); } if (itemMeta.hasLore()) { lore = itemMeta.getLore().toArray(new String[itemMeta.getLore().size()]); } if(itemMeta instanceof BookMeta) { additional = new BookMetadata((BookMeta) itemMeta); } else if(itemMeta instanceof EnchantmentStorageMeta) { additional = new EnchantmentStorageMetadata((EnchantmentStorageMeta) itemMeta); } if(itemMeta instanceof FireworkEffectMeta || itemMeta instanceof FireworkMeta || itemMeta instanceof LeatherArmorMeta || itemMeta instanceof MapMeta || itemMeta instanceof PotionMeta || itemMeta instanceof SkullMeta) { throw new ExchangeRuleCreateException("This item is not yet supported by ItemExchange."); } } ExchangeRule exchangeRule = new ExchangeRule(itemStack.getType(), itemStack.getAmount(), itemStack.getDurability(), requiredEnchantments, new ArrayList<Enchantment>(), false, displayName, lore, ruleType); exchangeRule.setAdditionalMetadata(additional); return exchangeRule; } public static ExchangeRule[] parseBulkRuleBlock(ItemStack ruleBlock) throws ExchangeRuleParseException { try { String[] rules = ruleBlock.getItemMeta().getLore().get(1).split(hiddenRuleSpacer); List<ExchangeRule> ruleList = new ArrayList<ExchangeRule>(); for(String rule : rules) { ruleList.add(parseRuleString(rule)); } return ruleList.toArray(new ExchangeRule[0]); } catch(Exception e) { throw new ExchangeRuleParseException("Invalid Exchange Rule"); } } /* * Parses an RuleBlock into an ExchangeRule It uses the escape character to * hide the information being stored from being visible to the character. It * also includes an easily read but not parse version of the rule for the * player. Might fail if the display name contains an &. */ public static ExchangeRule parseRuleBlock(ItemStack ruleBlock) throws ExchangeRuleParseException { try { return parseRuleString(ruleBlock.getItemMeta().getLore().get(0)); } catch(Exception e) { throw new ExchangeRuleParseException("Invalid exchange rule"); } } public static ExchangeRule parseRuleString(String ruleString) throws ExchangeRuleParseException { try { // [Type,Material // ID,Durability,Amount,RequiredEnchantments[],ExcludedEnchantments[],UnlistedEnchantments[],DisplayName,Lore] String[] compiledRule = ruleString.split(hiddenCategorySpacer); // Check length is correct if (compiledRule.length < 12) { throw new ExchangeRuleParseException("Compiled rule too short: " + String.valueOf(compiledRule.length)); } // Get Rule Type RuleType ruleType; if (showString(compiledRule[0]).equals("i")) { ruleType = RuleType.INPUT; } else if (showString(compiledRule[0]).equals("o")) { ruleType = RuleType.OUTPUT; } else { throw new ExchangeRuleParseException("Invalid rule type"); } String transactionType = showString(compiledRule[1]); if(!transactionType.equals("item")) { throw new ExchangeRuleParseException("Invalid transaction type"); } // Get Material Material material = Material.getMaterial(Integer.valueOf(showString(compiledRule[2]))); // Get Durability short durability = Short.valueOf(showString(compiledRule[3])); // Get Amount int amount = Integer.parseInt(showString(compiledRule[4])); // Get Required Enchantments Map<Enchantment, Integer> requiredEnchantments = new HashMap<Enchantment, Integer>(); for (String compiledEnchant : compiledRule[5].split(hiddenSecondarySpacer)) { if (compiledEnchant.equals("")) { continue; } Enchantment enchantment = Enchantment.getById(Integer.valueOf(showString(compiledEnchant.split(hiddenTertiarySpacer)[0]))); Integer level = Integer.valueOf(showString(compiledEnchant.split(hiddenTertiarySpacer)[1])); requiredEnchantments.put(enchantment, level); } // Get Excluded Enchantments List<Enchantment> excludedEnchantments = new ArrayList<Enchantment>(); for (String compiledEnchant : compiledRule[6].split(hiddenSecondarySpacer)) { if (compiledEnchant.equals("")) { continue; } Enchantment enchantment = Enchantment.getById(Integer.valueOf(showString(compiledEnchant))); excludedEnchantments.add(enchantment); } // Get if unlisted enchantments are allowed boolean unlistedEnchantmentsAllowed; if (showString(compiledRule[7]).equals("0")) { unlistedEnchantmentsAllowed = false; } else if (showString(compiledRule[7]).equals("1")) { unlistedEnchantmentsAllowed = true; } else { throw new ExchangeRuleParseException("Invalid Rule Type"); } // Get DisplayName String displayName = ""; if (!compiledRule[8].equals("")) { displayName = unescapeString(showString(compiledRule[8])); } // Get Lore String[] lore = new String[0]; if (!compiledRule[9].equals("")) { lore = showString(compiledRule[9]).split(secondarySpacer); for(String line : lore) { line = unescapeString(line); } } AdditionalMetadata additional = null; if(material == Material.WRITTEN_BOOK) { additional = BookMetadata.deserialize(showString(compiledRule[10])); } else if(material == Material.ENCHANTED_BOOK) { additional = EnchantmentStorageMetadata.deserialize(showString(compiledRule[10])); } Faction group; if(!compiledRule[11].equals("")) { group = Citadel.getGroupManager().getGroup(unescapeString(showString(compiledRule[11]))); } else { group = null; } ExchangeRule exchangeRule = new ExchangeRule(material, amount, durability, requiredEnchantments, excludedEnchantments, unlistedEnchantmentsAllowed, displayName, lore, ruleType); exchangeRule.setAdditionalMetadata(additional); exchangeRule.setCitadelGroup(group); return exchangeRule; } catch (Exception e) { throw new ExchangeRuleParseException("Invalid Exchange Rule"); } } /* * Removes every other character from a string */ private static String showString(String string) { StringBuilder result = new StringBuilder(); char[] chars = string.toCharArray(); for(int i = 1; i < chars.length; i += 2) { result.append(chars[i]); } return result.toString(); } private static String hideString(String string) { String hiddenString = ""; for (char character : string.toCharArray()) { hiddenString += "§" + character; } return hiddenString; } /* * Escapes all 'r' and '\' characters in a string */ private static String escapeString(String string) { return string.replaceAll("([\\\\r])", "\\\\$1"); } /* * Un-escapes all 'r' and '\' characters in a string */ private static String unescapeString(String string) { return string.replaceAll("\\\\([\\\\r])", "$1"); } /* * Parse create command into an exchange rule */ public static ExchangeRule parseCreateCommand(String[] args) throws ExchangeRuleParseException { try { // Parse ruletype RuleType ruleType = null; if (args[0].equalsIgnoreCase("input")) { ruleType = ExchangeRule.RuleType.INPUT; } else if (args[0].equalsIgnoreCase("output")) { ruleType = ExchangeRule.RuleType.OUTPUT; } if (ruleType != null) { Material material = null; short durability = 0; int amount = 1; if (args.length >= 2) { if (ItemExchangePlugin.NAME_MATERIAL.containsKey(args[1].toLowerCase())) { ItemStack itemStack = ItemExchangePlugin.NAME_MATERIAL.get(args[1].toLowerCase()); material = itemStack.getType(); durability = itemStack.getDurability(); } else { String[] split = args[1].split(":"); material = Material.getMaterial(Integer.valueOf(split[0])); if (split.length > 1) { durability = Short.valueOf(split[1]); } } if (args.length == 3) { amount = Integer.valueOf(args[2]); } } if(NOT_SUPPORTED.contains(material)) { throw new ExchangeRuleParseException("This material is not supported."); } return new ExchangeRule(material, amount, durability, ruleType); } else { throw new ExchangeRuleParseException("Please specify an input or output."); } } catch (Exception e) { throw new ExchangeRuleParseException("Invalid exchange rule."); } } public static ItemStack toBulkItemStack(Collection<ExchangeRule> rules) { ItemStack itemStack = ItemExchangePlugin.ITEM_RULE_ITEMSTACK.clone(); String ruleSpacer = "§&§&§&§&§r"; ItemMeta itemMeta = itemStack.getItemMeta(); itemMeta.setDisplayName(ChatColor.DARK_RED + "Bulk Rule Block"); List<String> newLore = new ArrayList<String>(); StringBuilder compiledRules = new StringBuilder(); Iterator<ExchangeRule> iterator = rules.iterator(); while(iterator.hasNext()) { compiledRules.append(iterator.next().compileRule()); if(iterator.hasNext()) compiledRules.append(ruleSpacer); } newLore.add("This rule block holds " + rules.size() + (rules.size() > 1 ? " exchange rules." : " exchange rule.")); newLore.add(compiledRules.toString()); itemMeta.setLore(newLore); itemStack.setItemMeta(itemMeta); return itemStack; } /* * Stores the exchange rule as an item stack */ public ItemStack toItemStack() { ItemStack itemStack = ItemExchangePlugin.ITEM_RULE_ITEMSTACK.clone(); ItemMeta itemMeta = itemStack.getItemMeta(); itemMeta.setDisplayName(displayedItemStackInfo()); List<String> newLore = new ArrayList<String>(); if(ItemExchangePlugin.ENCHANTABLE_ITEMS.contains(material)) { newLore.add(displayedEnchantments()); } for (String line : displayedLore()) { newLore.add(line); } if(newLore.size() > 0) { newLore.set(0, compileRule() + newLore.get(0)); } else { newLore.add(compileRule()); } itemMeta.setLore(newLore); itemStack.setItemMeta(itemMeta); return itemStack; } /* * Saves the exchange rule to lore in a semi-readable fashion */ public String compileRule() { String compiledRule = ""; // RuleType compiledRule += ruleType.equals(RuleType.INPUT) ? hideString("i") : hideString("o"); // Transaction type compiledRule += hiddenCategorySpacer + hideString("item"); // Material ID compiledRule += hiddenCategorySpacer + hideString(String.valueOf(material.getId())); // Durability compiledRule += hiddenCategorySpacer + hideString(String.valueOf(durability)); // Amount compiledRule += hiddenCategorySpacer + hideString(String.valueOf(amount)); compiledRule += hiddenCategorySpacer; boolean enchantable = ItemExchangePlugin.ENCHANTABLE_ITEMS.contains(material); if(enchantable) { for (Entry<Enchantment, Integer> entry : requiredEnchantments.entrySet()) { compiledRule += hideString(String.valueOf(entry.getKey().getId())) + hiddenTertiarySpacer + hideString(entry.getValue().toString()) + hiddenSecondarySpacer; } } compiledRule += hiddenCategorySpacer; if(enchantable) { for (Enchantment enchantment : excludedEnchantments) { compiledRule += hideString(String.valueOf(enchantment.getId())) + hiddenSecondarySpacer; } } compiledRule += hiddenCategorySpacer + ((unlistedEnchantmentsAllowed && enchantable) ? hideString("1") : hideString("0")); compiledRule += hiddenCategorySpacer + hideString(escapeString(displayName)); compiledRule += hiddenCategorySpacer; for (int i = 0; i < lore.length; i++) { String line = lore[i]; if(i > 0) compiledRule += hiddenSecondarySpacer; compiledRule += hideString(escapeString(line)); } compiledRule += hiddenCategorySpacer; if(additional != null) { compiledRule += hideString(additional.serialize()); } compiledRule += hiddenCategorySpacer; if(citadelGroup != null) { compiledRule += hideString(escapeString(citadelGroup.getName())); } compiledRule += hiddenCategorySpacer + "§r"; return compiledRule; } public boolean followsRules(Player player) { if(this.ruleType == RuleType.INPUT) { if(citadelGroup != null) { String playerName = player.getName(); if(citadelGroup.isMember(playerName) || citadelGroup.isModerator(playerName) || citadelGroup.isFounder(playerName)) { return true; } else { return false; } } } return true; } /* * Checks if an inventory has enough items which follow the ItemRules */ public boolean followsRules(Inventory inventory) { int invAmount = 0; for (ItemStack itemStack : inventory.getContents()) { if (itemStack != null && followsRules(itemStack)) { invAmount += itemStack.getAmount(); } } return invAmount >= amount; } /* * Counts how many multiples of the specified item an inventory has. */ public int checkMultiples(Inventory inventory) { int invAmount = 0; for (ItemStack itemStack : inventory.getContents()) { if (itemStack != null && followsRules(itemStack)) { invAmount += itemStack.getAmount(); } } return invAmount / amount; } /* * Checks if the given ItemStack follows the ItemRules except for the amount */ public boolean followsRules(ItemStack itemStack) { // check material type and druability boolean followsRules = material.getId() == itemStack.getTypeId() && durability == itemStack.getDurability(); // Check enchantments if (itemStack.getEnchantments().size() > 0) { followsRules = followsRules && itemStack.getEnchantments().entrySet().containsAll(requiredEnchantments.entrySet()); for (Enchantment excludedEnchantment : excludedEnchantments) { followsRules = followsRules && !itemStack.getEnchantments().entrySet().contains(excludedEnchantment); } } else if (requiredEnchantments.size() > 0) { followsRules = false; } if(additional != null) followsRules = followsRules && additional.matches(itemStack); // Check displayName and Lore if (itemStack.hasItemMeta()) { ItemMeta itemMeta = itemStack.getItemMeta(); if (itemMeta.hasDisplayName()) { followsRules = followsRules && displayName.equals(itemMeta.getDisplayName()); } else { followsRules = followsRules && displayName.equals(""); } if (itemMeta.hasLore()) { for (int i = 0; i < itemMeta.getLore().size() && i < lore.length; i++) { followsRules = followsRules && lore[i].equals(itemMeta.getLore().get(i)); } followsRules = followsRules && itemMeta.getLore().size() == lore.length; } else { followsRules = followsRules && lore.length == 0; } } else { followsRules = followsRules && displayName.equals("") && lore.length == 0; } return followsRules; } public String[] display() { List<String> displayed = new ArrayList<>(); // Material type, durability and amount displayed.add(displayedItemStackInfo()); // Additional metadata (books, etc.) if(additional != null) { displayed.add(additional.getDisplayedInfo()); } // Enchantments if(ItemExchangePlugin.ENCHANTABLE_ITEMS.contains(material)) { displayed.add(displayedEnchantments()); } // Lore for(String line : displayedLore()) { displayed.add(line); } // Citadel group if(citadelGroup != null) { displayed.add(ChatColor.RED + "Restricted with Citadel."); } return displayed.toArray(new String[displayed.size()]); } private String displayedItemStackInfo() { StringBuilder stringBuilder = new StringBuilder().append(ChatColor.YELLOW).append((ruleType == RuleType.INPUT ? "Input" : "Output") + ": " + ChatColor.WHITE).append(amount); if (ItemExchangePlugin.MATERIAL_NAME.containsKey(new ItemStack(material, 1, durability))) { stringBuilder.append(" " + ItemExchangePlugin.MATERIAL_NAME.get(new ItemStack(material, 1, durability))); } else { stringBuilder.append(material.name() + ":").append(durability); } stringBuilder.append(displayName.equals("") ? "" : " \"" + displayName + "\""); return stringBuilder.toString(); } private String displayedEnchantments() { if (requiredEnchantments.size() > 0 || excludedEnchantments.size() > 0) { StringBuilder stringBuilder = new StringBuilder(); for (Entry<Enchantment, Integer> entry : requiredEnchantments.entrySet()) { stringBuilder.append(ChatColor.GREEN); stringBuilder.append(ItemExchangePlugin.ENCHANTMENT_ABBRV.get(entry.getKey().getName())); stringBuilder.append(entry.getValue()); stringBuilder.append(" "); } for (Enchantment enchantment : excludedEnchantments) { stringBuilder.append(ChatColor.RED); stringBuilder.append(ItemExchangePlugin.ENCHANTMENT_ABBRV.get(enchantment.getName())); stringBuilder.append(" "); } stringBuilder.append(unlistedEnchantmentsAllowed ? ChatColor.GREEN + "Other Enchantments Allowed." : ChatColor.RED + "Other Enchantments Disallowed"); return stringBuilder.toString(); } else { return unlistedEnchantmentsAllowed ? ChatColor.GREEN + "Any enchantments allowed" : ChatColor.RED + "No enchantments allowed"; } } private String[] displayedLore() { if (lore.length == 0) { return new String[0]; } else if (lore.length == 1) { return new String[] { ChatColor.DARK_PURPLE + lore[0] }; } else { return new String[] { ChatColor.DARK_PURPLE + lore[0], ChatColor.DARK_PURPLE + lore[1] + "..." }; } } public void setMaterial(Material material) { this.material = material; } public void setUnlistedEnchantmentsAllowed(boolean allowed) { this.unlistedEnchantmentsAllowed = allowed; } public boolean getUnlistedEnchantmentsAllowed() { return unlistedEnchantmentsAllowed; } public void requireEnchantment(Enchantment enchantment, Integer level) { requiredEnchantments.put(enchantment, level); } public void removeRequiredEnchantment(Enchantment enchantment) { requiredEnchantments.remove(enchantment); } public void excludeEnchantment(Enchantment enchantment) { if(!excludedEnchantments.contains(enchantment)) excludedEnchantments.add(enchantment); } public void removeExcludedEnchantment(Enchantment enchantment) { excludedEnchantments.remove(enchantment); } public void setAmount(int amount) { this.amount = amount; } public void setDurability(short durability) { this.durability = durability; } public void setDisplayName(String displayName) { this.displayName = displayName; } public void setLore(String[] lore) { this.lore = lore; } public void switchIO() { ruleType = ruleType == RuleType.INPUT ? RuleType.OUTPUT : RuleType.INPUT; } public int getAmount() { return amount; } public void setCitadelGroup(Faction group) { this.citadelGroup = group; } public Faction getCitadelGroup() { return citadelGroup; } public RuleType getType() { return ruleType; } public static boolean isRuleBlock(ItemStack item) { try { ExchangeRule.parseBulkRuleBlock(item); return true; } catch(ExchangeRuleParseException e) { try { ExchangeRule.parseRuleBlock(item); return true; } catch(ExchangeRuleParseException e2) { return false; } } } }
package org.apache.lenya.workflow.impl; import java.io.File; import javax.xml.transform.TransformerException; import org.apache.lenya.cms.workflow.CMSSituation; import org.apache.lenya.workflow.BooleanVariable; import org.apache.lenya.workflow.Event; import org.apache.lenya.workflow.Situation; import org.apache.lenya.workflow.State; import org.apache.lenya.workflow.WorkflowException; import org.apache.lenya.workflow.WorkflowInstance; import org.apache.lenya.workflow.WorkflowListener; import org.apache.lenya.xml.DocumentHelper; import org.apache.lenya.xml.NamespaceHelper; import org.apache.xpath.XPathAPI; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * @author andreas * * To change the template for this generated type comment go to * Window>Preferences>Java>Code Generation>Code and Comments */ public abstract class History implements WorkflowListener { public static final String WORKFLOW_ATTRIBUTE = "workflow"; public static final String HISTORY_ELEMENT = "history"; public static final String VERSION_ELEMENT = "version"; public static final String STATE_ATTRIBUTE = "state"; public static final String USER_ATTRIBUTE = "user"; public static final String EVENT_ATTRIBUTE = "event"; public static final String VARIABLE_ELEMENT = "variable"; public static final String NAME_ATTRIBUTE = "name"; public static final String VALUE_ATTRIBUTE = "value"; /** * Creates a new history object. A new history file is created and initialized. * @param file The history file. * @param workflowFileName The workflow reference. */ public void initialize(String workflowId) throws WorkflowException { try { File file = getHistoryFile(); file.getParentFile().mkdirs(); file.createNewFile(); NamespaceHelper helper = new NamespaceHelper( WorkflowBuilder.NAMESPACE, WorkflowBuilder.DEFAULT_PREFIX, HISTORY_ELEMENT); Element historyElement = helper.getDocument().getDocumentElement(); historyElement.setAttribute(WORKFLOW_ATTRIBUTE, workflowId); createVariableElements(helper); saveVariables(helper); DocumentHelper.writeDocument(helper.getDocument(), file); } catch (Exception e) { throw new WorkflowException(e); } } /** * Creates a new history object for a workflow instance. * @param instance * @param file * @param x * @throws WorkflowException */ protected History() { } private WorkflowInstanceImpl instance = null; /** * Restores the workflow, state and variables of a workflow instance from this history. * @param instance The workflow instance to restore. * @throws WorkflowException if something goes wrong. */ public WorkflowInstanceImpl getInstance() throws WorkflowException { if (this.instance == null) { if (!isInitialized()) { throw new WorkflowException( "The workflow history has not been initialized!"); } WorkflowInstanceImpl instance = createInstance(); NamespaceHelper helper; String workflowId; try { Document document = DocumentHelper.readDocument(getHistoryFile()); helper = new NamespaceHelper( WorkflowBuilder.NAMESPACE, WorkflowBuilder.DEFAULT_PREFIX, document); } catch (Exception e) { throw new WorkflowException(e); } workflowId = helper.getDocument().getDocumentElement().getAttribute(WORKFLOW_ATTRIBUTE); if (null == workflowId) { throw new WorkflowException("No workflow attribute set in history document!"); } instance.setWorkflow(workflowId); restoreState(instance, helper); restoreVariables(instance, helper); instance.addWorkflowListener(this); setInstance(instance); } return instance; } /** * Returns if the history has been initialized. * @return A boolean value. */ public boolean isInitialized() { return getHistoryFile().exists(); } /** * Factory method to obtain the history file. * @return A file. */ protected abstract File getHistoryFile(); /** * Factory method to create a workflow instance object. * @return A workflow instance object. */ protected abstract WorkflowInstanceImpl createInstance() throws WorkflowException; protected Element createVersionElement( NamespaceHelper helper, StateImpl state, Situation situation, Event event) { Element versionElement = helper.createElement(VERSION_ELEMENT); versionElement.setAttribute(STATE_ATTRIBUTE, state.getId()); versionElement.setAttribute(EVENT_ATTRIBUTE, event.getName()); return versionElement; } public void transitionFired(WorkflowInstance instance, Situation situation, Event event) throws WorkflowException { try { org.w3c.dom.Document xmlDocument = DocumentHelper.readDocument(getHistoryFile()); Element root = xmlDocument.getDocumentElement(); NamespaceHelper helper = new NamespaceHelper( WorkflowBuilder.NAMESPACE, WorkflowBuilder.DEFAULT_PREFIX, xmlDocument); CMSSituation cmsSituation = (CMSSituation) situation; Element versionElement = createVersionElement(helper, (StateImpl) instance.getCurrentState(), situation, event); root.appendChild(versionElement); saveVariables(helper); DocumentHelper.writeDocument(xmlDocument, getHistoryFile()); } catch (Exception e) { throw new WorkflowException(e); } } /** * @param impl */ public void setInstance(WorkflowInstanceImpl impl) { instance = impl; } /** * Saves the state variables as children of the document element. * @param helper The helper that holds the document. */ protected void saveVariables(NamespaceHelper helper) throws WorkflowException { Element parent = helper.getDocument().getDocumentElement(); BooleanVariable variables[] = getInstance().getWorkflowImpl().getVariables(); for (int i = 0; i < variables.length; i++) { String name = variables[i].getName(); boolean value = getInstance().getValue(name); try { Element element = (Element) XPathAPI.selectSingleNode(parent, "*[local-name() = '" + VARIABLE_ELEMENT + "']" + "[@" + NAME_ATTRIBUTE + " = '" + name + "']"); if (element == null) { throw new WorkflowException("Variable element for variable '" + name + "' not found!"); } element.setAttribute(VALUE_ATTRIBUTE, Boolean.toString(value)); } catch (TransformerException e) { throw new WorkflowException(e); } } } protected void createVariableElements(NamespaceHelper helper) throws WorkflowException { Element parent = helper.getDocument().getDocumentElement(); BooleanVariable variables[] = getInstance().getWorkflowImpl().getVariables(); for (int i = 0; i < variables.length; i++) { Element element = helper.createElement(VARIABLE_ELEMENT); element.setAttribute(NAME_ATTRIBUTE, variables[i].getName()); parent.appendChild(element); } } /** * Restores the state variables of a workflow instance. * @param instance The instance to restore. * @param helper The helper that wraps the history document. * @throws WorkflowException */ protected void restoreVariables(WorkflowInstanceImpl instance, NamespaceHelper helper) throws WorkflowException { Element parent = helper.getDocument().getDocumentElement(); Element variableElements[] = helper.getChildren(parent, VARIABLE_ELEMENT); for (int i = 0; i < variableElements.length; i++) { String name = variableElements[i].getAttribute(NAME_ATTRIBUTE); String value = variableElements[i].getAttribute(VALUE_ATTRIBUTE); instance.setValue(name, new Boolean(value).booleanValue()); } } /** * Restores the state of a workflow instance. * @param instance The instance to restore. * @param helper The helper that wraps the history document. * @throws WorkflowException */ protected void restoreState(WorkflowInstanceImpl instance, NamespaceHelper helper) throws WorkflowException { State state; Element versionElements[] = helper.getChildren(helper.getDocument().getDocumentElement(), VERSION_ELEMENT); if (versionElements.length > 0) { Element lastElement = versionElements[versionElements.length - 1]; String stateId = lastElement.getAttribute(STATE_ATTRIBUTE); state = instance.getWorkflowImpl().getState(stateId); } else { state = instance.getWorkflow().getInitialState(); } instance.setCurrentState(state); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.untamedears.JukeAlert.storage; import com.untamedears.JukeAlert.JukeAlert; import com.untamedears.JukeAlert.chat.ChatFiller; import com.untamedears.JukeAlert.group.GroupMediator; import com.untamedears.JukeAlert.manager.ConfigManager; import com.untamedears.JukeAlert.model.LoggedAction; import com.untamedears.JukeAlert.model.Snitch; import com.untamedears.JukeAlert.tasks.GetSnitchInfoTask; import com.untamedears.JukeAlert.util.SparseQuadTree; import com.untamedears.citadel.entity.Faction; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; /** * * @author Dylan Holmes */ public class JukeAlertLogger { private JukeAlert plugin; private ConfigManager configManager; private GroupMediator groupMediator; private Database db; private String snitchsTbl; private String snitchDetailsTbl; private PreparedStatement getSnitchIdFromLocationStmt; private PreparedStatement getAllSnitchesStmt; private PreparedStatement getAllSnitchesByWorldStmt; private PreparedStatement getLastSnitchID; private PreparedStatement getSnitchLogStmt; private PreparedStatement deleteSnitchLogStmt; private PreparedStatement insertSnitchLogStmt; private PreparedStatement insertNewSnitchStmt; private PreparedStatement deleteSnitchStmt; private PreparedStatement updateGroupStmt; private PreparedStatement updateCuboidVolumeStmt; private PreparedStatement updateSnitchNameStmt; private PreparedStatement updateSnitchGroupStmt; private int logsPerPage; private int lastSnitchID; public JukeAlertLogger() { plugin = JukeAlert.getInstance(); configManager = plugin.getConfigManager(); groupMediator = plugin.getGroupMediator(); String host = configManager.getHost(); int port = configManager.getPort(); String dbname = configManager.getDatabase(); String username = configManager.getUsername(); String password = configManager.getPassword(); String prefix = configManager.getPrefix(); snitchsTbl = prefix + "snitchs"; snitchDetailsTbl = prefix + "snitch_details"; db = new Database(host, port, dbname, username, password, prefix, this.plugin.getLogger()); boolean connected = db.connect(); if (connected) { genTables(); initializeStatements(); } else { this.plugin.getLogger().log(Level.SEVERE, "Could not connect to the database! Fill out your config.yml!"); } logsPerPage = configManager.getLogsPerPage(); } public Database getDb() { return db; } /** * Table generator */ private void genTables() { //Snitches db.execute("CREATE TABLE IF NOT EXISTS `" + snitchsTbl + "` (" + "`snitch_id` int(10) unsigned NOT NULL AUTO_INCREMENT," + "`snitch_world` varchar(40) NOT NULL," + "`snitch_name` varchar(40) NOT NULL," + "`snitch_x` int(10) NOT NULL," + "`snitch_y` int(10) NOT NULL," + "`snitch_z` int(10) NOT NULL," + "`snitch_group` varchar(40) NOT NULL," + "`snitch_cuboid_x` int(10) NOT NULL," + "`snitch_cuboid_y` int(10) NOT NULL," + "`snitch_cuboid_z` int(10) NOT NULL," + "`snitch_should_log` BOOL," + "PRIMARY KEY (`snitch_id`));"); //Snitch Details // need to know: // action: (killed, block break, block place, etc), can't be null // person who initiated the action (player name), can't be null // victim of action (player name, entity), can be null // x, (for things like block place, bucket empty, etc, NOT the snitch x,y,z) can be null // y, can be null // z, can be null // block_id, can be null (block id for block place, block use, block break, etc) db.execute("CREATE TABLE IF NOT EXISTS `" + snitchDetailsTbl + "` (" + "`snitch_details_id` int(10) unsigned NOT NULL AUTO_INCREMENT," + "`snitch_id` int(10) unsigned NOT NULL," // reference to the column in the main snitches table + "`snitch_log_time` datetime," + "`snitch_logged_action` tinyint unsigned NOT NULL," + "`snitch_logged_initiated_user` varchar(16) NOT NULL," + "`snitch_logged_victim_user` varchar(16), " + "`snitch_logged_x` int(10), " + "`snitch_logged_Y` int(10), " + "`snitch_logged_z` int(10), " + "`snitch_logged_materialid` smallint unsigned," // can be either a block, item, etc + "PRIMARY KEY (`snitch_details_id`));"); } private void initializeStatements() { getAllSnitchesStmt = db.prepareStatement(String.format( "SELECT * FROM %s", snitchsTbl)); getAllSnitchesByWorldStmt = db.prepareStatement(String.format( "SELECT * FROM %s WHERE snitch_world = ?", snitchsTbl)); getLastSnitchID = db.prepareStatement(String.format( "SHOW TABLE STATUS LIKE '%s'", snitchsTbl)); // statement to get LIMIT entries OFFSET from a number from the snitchesDetailsTbl based on a snitch_id from the main snitchesTbl // LIMIT ?,? means offset followed by max rows to return getSnitchLogStmt = db.prepareStatement(String.format( "SELECT * FROM %s" + " WHERE snitch_id=? ORDER BY snitch_log_time DESC LIMIT ?,?", snitchDetailsTbl)); // statement to get the ID of a snitch in the main snitchsTbl based on a Location (x,y,z, world) getSnitchIdFromLocationStmt = db.prepareStatement(String.format("SELECT snitch_id FROM %s" + " WHERE snitch_x=? AND snitch_y=? AND snitch_z=? AND snitch_world=?", snitchsTbl)); // statement to insert a log entry into the snitchesDetailsTable insertSnitchLogStmt = db.prepareStatement(String.format( "INSERT INTO %s (snitch_id, snitch_log_time, snitch_logged_action, snitch_logged_initiated_user," + " snitch_logged_victim_user, snitch_logged_x, snitch_logged_y, snitch_logged_z, snitch_logged_materialid) " + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", snitchDetailsTbl)); insertNewSnitchStmt = db.prepareStatement(String.format( "INSERT INTO %s (snitch_world, snitch_name, snitch_x, snitch_y, snitch_z, snitch_group, snitch_cuboid_x, snitch_cuboid_y, snitch_cuboid_z)" + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", snitchsTbl)); deleteSnitchLogStmt = db.prepareStatement(String.format( "DELETE FROM %s WHERE snitch_id=?", snitchDetailsTbl)); deleteSnitchStmt = db.prepareStatement(String.format( "DELETE FROM %s WHERE snitch_world=? AND snitch_x=? AND snitch_y=? AND snitch_z=?", snitchsTbl)); updateGroupStmt = db.prepareStatement(String.format( "UPDATE %s SET snitch_group=? WHERE snitch_world=? AND snitch_x=? AND snitch_y=? AND snitch_z=?", snitchsTbl)); updateCuboidVolumeStmt = db.prepareStatement(String.format( "UPDATE %s SET snitch_cuboid_x=?, snitch_cuboid_y=?, snitch_cuboid_z=?" + " WHERE snitch_world=? AND snitch_x=? AND snitch_y=? AND snitch_z=?", snitchsTbl)); updateSnitchNameStmt = db.prepareStatement(String.format( "UPDATE %s SET snitch_name=?" + " WHERE snitch_id=?", snitchsTbl)); updateSnitchGroupStmt = db.prepareStatement(String.format( "UPDATE %s SET snitch_group=?" + " WHERE snitch_id=?", snitchsTbl)); } public static String snitchKey(final Location loc) { return String.format( "World: %s X: %d Y: %d Z: %d", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()); } public Map<World, SparseQuadTree> getAllSnitches() { Map<World, SparseQuadTree> snitches = new HashMap<World, SparseQuadTree>(); List<World> worlds = this.plugin.getServer().getWorlds(); for (World world : worlds) { SparseQuadTree snitchesByWorld = getAllSnitchesByWorld(world); snitches.put(world, snitchesByWorld); } return snitches; } public SparseQuadTree getAllSnitchesByWorld(World world) { SparseQuadTree snitches = new SparseQuadTree(); try { Snitch snitch = null; getAllSnitchesByWorldStmt.setString(1, world.getName()); ResultSet rs = getAllSnitchesByWorldStmt.executeQuery(); while (rs.next()) { double x = rs.getInt("snitch_x"); double y = rs.getInt("snitch_y"); double z = rs.getInt("snitch_z"); String groupName = rs.getString("snitch_group"); Faction group = groupMediator.getGroupByName(groupName); Location location = new Location(world, x, y, z); snitch = new Snitch(location, group); snitch.setId(rs.getInt("snitch_id")); snitch.setName(rs.getString("snitch_name")); snitches.add(snitch); } ResultSet rsKey = getLastSnitchID.executeQuery(); if (rsKey.next()) { lastSnitchID = rsKey.getInt("Auto_increment"); } } catch (SQLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Could not get all Snitches from World " + world + "!"); } return snitches; } public void saveAllSnitches() { //TODO: Save snitches. } /** * Gets * * @limit events about that snitch. * @param loc - the location of the snitch * @param offset - the number of entries to start at (10 means you start at * the 10th entry and go to * @limit) * @param limit - the number of entries to limit * @return a Map of String/Date objects of the snitch entries, formatted * nicely */ public List<String> getSnitchInfo(Location loc, int offset) { List<String> info = new ArrayList<String>(); // get the snitch's ID based on the location, then use that to get the snitch details from the snitchesDetail table int interestedSnitchId = -1; try { // params are x(int), y(int), z(int), world(tinyint), column returned: snitch_id (int) getSnitchIdFromLocationStmt.setInt(1, loc.getBlockX()); getSnitchIdFromLocationStmt.setInt(2, loc.getBlockY()); getSnitchIdFromLocationStmt.setInt(3, loc.getBlockZ()); getSnitchIdFromLocationStmt.setString(4, loc.getWorld().getName()); ResultSet snitchIdSet = getSnitchIdFromLocationStmt.executeQuery(); // make sure we got a result boolean didFind = false; while (snitchIdSet.next()) { didFind = true; interestedSnitchId = snitchIdSet.getInt("snitch_id"); } // only continue if we actually got a result from the first query if (!didFind) { this.plugin.getLogger().log(Level.SEVERE, "Didn't get any results trying to find a snitch in the snitches table at location " + loc); } else { GetSnitchInfoTask task = new GetSnitchInfoTask(plugin, interestedSnitchId, offset); Bukkit.getScheduler().runTaskAsynchronously(plugin, task); return task.getInfo(); } } catch (SQLException ex1) { this.plugin.getLogger().log(Level.SEVERE, "Could not get Snitch Details! loc: " + loc, ex1); } return info; } public List<String> getSnitchInfo(int snitchId, int offset) { List<String> info = new ArrayList<String>(); try { getSnitchLogStmt.setInt(1, snitchId); getSnitchLogStmt.setInt(2, offset); getSnitchLogStmt.setInt(3, logsPerPage); ResultSet set = getSnitchLogStmt.executeQuery(); if (!set.isBeforeFirst()) { System.out.println("No data"); } else { while (set.next()) { // TODO: need a function to create a string based upon what things we have / don't have in this result set // so like if we have a block place action, then we include the x,y,z, but if its a KILL action, then we just say // x killed y, etc info.add(createInfoString(set)); } } } catch (SQLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Could not get Snitch Details from the snitchesDetail table using the snitch id " + snitchId, ex); } return info; } public Boolean deleteSnitchInfo(Location loc) { Boolean completed = false; // get the snitch's ID based on the location, then use that to get the snitch details from the snitchesDetail table int interestedSnitchId = -1; try { // params are x(int), y(int), z(int), world(tinyint), column returned: snitch_id (int) getSnitchIdFromLocationStmt.setInt(1, loc.getBlockX()); getSnitchIdFromLocationStmt.setInt(2, loc.getBlockY()); getSnitchIdFromLocationStmt.setInt(3, loc.getBlockZ()); getSnitchIdFromLocationStmt.setString(4, loc.getWorld().getName()); ResultSet snitchIdSet = getSnitchIdFromLocationStmt.executeQuery(); // make sure we got a result boolean didFind = false; while (snitchIdSet.next()) { didFind = true; interestedSnitchId = snitchIdSet.getInt("snitch_id"); } // only continue if we actually got a result from the first query if (!didFind) { this.plugin.getLogger().log(Level.SEVERE, "Didn't get any results trying to find a snitch in the snitches table at location " + loc); } else { deleteSnitchInfo(interestedSnitchId); } } catch (SQLException ex1) { completed = false; this.plugin.getLogger().log(Level.SEVERE, "Could not get Snitch Details! loc: " + loc, ex1); } return completed; } public Boolean deleteSnitchInfo(int snitchId) { try { deleteSnitchLogStmt.setInt(1, snitchId); deleteSnitchLogStmt.execute(); return true; } catch (SQLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Could not delete Snitch Details from the snitchesDetail table using the snitch id " + snitchId, ex); return false; } } public void logSnitchInfo(Snitch snitch, Material material, Location loc, Date date, LoggedAction action, String initiatedUser, String victimUser) { try { // snitchid insertSnitchLogStmt.setInt(1, snitch.getId()); // snitch log time insertSnitchLogStmt.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime())); // snitch logged action insertSnitchLogStmt.setByte(3, (byte) action.getLoggedActionId()); // initiated user insertSnitchLogStmt.setString(4, initiatedUser); // These columns, victimUser, location and materialid can all be null so check if it is an insert SQL null if it is // victim user if (victimUser != null) { insertSnitchLogStmt.setString(5, victimUser); } else { insertSnitchLogStmt.setNull(5, java.sql.Types.VARCHAR); } // location, x, y, z if (loc != null) { insertSnitchLogStmt.setInt(6, loc.getBlockX()); insertSnitchLogStmt.setInt(7, loc.getBlockY()); insertSnitchLogStmt.setInt(8, loc.getBlockZ()); } else { insertSnitchLogStmt.setNull(6, java.sql.Types.INTEGER); insertSnitchLogStmt.setNull(7, java.sql.Types.INTEGER); insertSnitchLogStmt.setNull(8, java.sql.Types.INTEGER); } // materialid if (material != null) { insertSnitchLogStmt.setShort(9, (short) material.getId()); } else { insertSnitchLogStmt.setNull(9, java.sql.Types.SMALLINT); } Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { try { insertSnitchLogStmt.execute(); } catch (SQLException ex) { Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex); } } }); //To change body of generated methods, choose Tools | Templates. } catch (SQLException ex) { this.plugin.getLogger().log(Level.SEVERE, String.format("Could not create snitch log entry! with snitch %s, " + "material %s, date %s, initiatedUser %s, victimUser %s", snitch, material, date, initiatedUser, victimUser), ex); } } /** * logs a message that someone killed an entity * * @param snitch - the snitch that recorded this event * @param player - the player that did the killing * @param entity - the entity that died */ public void logSnitchEntityKill(Snitch snitch, Player player, Entity entity) { // There is no material or location involved in this event this.logSnitchInfo(snitch, null, null, new Date(), LoggedAction.KILL, player.getPlayerListName(), entity.getType().toString()); } /** * Logs a message that someone killed another player * * @param snitch - the snitch that recorded this event * @param player - the player that did the killing * @param victim - the player that died */ public void logSnitchPlayerKill(Snitch snitch, Player player, Player victim) { // There is no material or location involved in this event this.logSnitchInfo(snitch, null, null, new Date(), LoggedAction.KILL, player.getPlayerListName(), victim.getPlayerListName()); } /** * Logs a message that someone ignited a block within the snitch's field * * @param snitch - the snitch that recorded this event * @param player - the player that did the ignition * @param block - the block that was ignited */ public void logSnitchIgnite(Snitch snitch, Player player, Block block) { // There is no material or location involved in this event this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.IGNITED, player.getPlayerListName(), null); } /** * Logs a message that someone entered the snitch's field * * @param snitch - the snitch that recorded this event * @param player - the player that entered the snitch's field * @param loc - the location of where the player entered */ public void logSnitchEntry(Snitch snitch, Location loc, Player player) { // no material or victimUser for this event this.logSnitchInfo(snitch, null, loc, new Date(), LoggedAction.ENTRY, player.getPlayerListName(), null); } /** * Logs a message that someone broke a block within the snitch's field * * @param snitch - the snitch that recorded this event * @param player - the player that broke the block * @param block - the block that was broken */ public void logSnitchBlockBreak(Snitch snitch, Player player, Block block) { // no victim user in this event this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.BLOCK_BREAK, player.getPlayerListName(), null); } /** * Logs a message that someone placed a block within the snitch's field * * @param snitch - the snitch that recorded this event * @param player - the player that placed the block * @param block - the block that was placed */ public void logSnitchBlockPlace(Snitch snitch, Player player, Block block) { // no victim user in this event this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.BLOCK_PLACE, player.getPlayerListName(), null); } /** * Logs a message that someone emptied a bucket within the snitch's field * * @param snitch - the snitch that recorded this event * @param player - the player that emptied the bucket * @param loc - the location of where the bucket empty occurred * @param item - the ItemStack representing the bucket that the player * emptied */ public void logSnitchBucketEmpty(Snitch snitch, Player player, Location loc, ItemStack item) { // no victim user in this event this.logSnitchInfo(snitch, item.getType(), loc, new Date(), LoggedAction.BUCKET_EMPTY, player.getPlayerListName(), null); } /** * Logs a message that someone filled a bucket within the snitch's field * * @param snitch - the snitch that recorded this event * @param player - the player that filled the bucket * @param block - the block that was 'put into' the bucket */ public void logSnitchBucketFill(Snitch snitch, Player player, Block block) { // TODO: should we take a block or a ItemStack as a parameter here? // JM: I think it'll be fine either way, most griefing is done with with block placement and this could be updated fairly easily // no victim user in this event this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.BUCKET_FILL, player.getPlayerListName(), null); } /** * Logs a message that someone used a block within the snitch's field * * @param snitch - the snitch that recorded this event * @param player - the player that used something * @param block - the block that was used */ public void logUsed(Snitch snitch, Player player, Block block) { // TODO: what should we use to identify what was used? Block? Material? //JM: Let's keep this consistent with block plament this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.BLOCK_USED, player.getPlayerListName(), null); } //Logs the snitch being placed at World, x, y, z in the database. public void logSnitchPlace(String world, String group, String name, int x, int y, int z) { try { insertNewSnitchStmt.setString(1, world); insertNewSnitchStmt.setString(2, name); insertNewSnitchStmt.setInt(3, x); insertNewSnitchStmt.setInt(4, y); insertNewSnitchStmt.setInt(5, z); insertNewSnitchStmt.setString(6, group); insertNewSnitchStmt.setInt(7, configManager.getDefaultCuboidSize()); insertNewSnitchStmt.setInt(8, configManager.getDefaultCuboidSize()); insertNewSnitchStmt.setInt(9, configManager.getDefaultCuboidSize()); Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { try { insertNewSnitchStmt.execute(); } catch (SQLException ex) { Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex); } } }); } catch (SQLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Could not create new snitch in DB!", ex); } } //Removes the snitch at the location of World, X, Y, Z from the database. public void logSnitchBreak(String world, int x, int y, int z) { try { deleteSnitchStmt.setString(1, world); deleteSnitchStmt.setInt(2, (int) Math.floor(x)); deleteSnitchStmt.setInt(3, (int) Math.floor(y)); deleteSnitchStmt.setInt(4, (int) Math.floor(z)); Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { try { deleteSnitchStmt.execute(); } catch (SQLException ex) { Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex); } } }); } catch (SQLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Could not log Snitch break!", ex); } } //Changes the group of which the snitch is registered to at the location of loc in the database. public void updateGroupSnitch(Location loc, String group) { try { updateGroupStmt.setString(1, group); updateGroupStmt.setString(2, loc.getWorld().getName()); updateGroupStmt.setInt(3, loc.getBlockX()); updateGroupStmt.setInt(4, loc.getBlockY()); updateGroupStmt.setInt(5, loc.getBlockZ()); Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { try { updateGroupStmt.execute(); } catch (SQLException ex) { Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex); } } }); } catch (SQLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Could not update Snitch group!", ex); } } //Updates the cuboid size of the snitch in the database. public void updateCubiodSize(Location loc, int x, int y, int z) { try { updateCuboidVolumeStmt.setInt(1, x); updateCuboidVolumeStmt.setInt(2, y); updateCuboidVolumeStmt.setInt(3, z); updateCuboidVolumeStmt.setString(4, loc.getWorld().getName()); updateCuboidVolumeStmt.setInt(5, loc.getBlockX()); updateCuboidVolumeStmt.setInt(6, loc.getBlockY()); updateCuboidVolumeStmt.setInt(7, loc.getBlockZ()); Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { try { updateCuboidVolumeStmt.execute(); } catch (SQLException ex) { Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex); } } }); } catch (SQLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Could not update Snitch cubiod size!", ex); } } //Updates the name of the snitch in the database. public void updateSnitchName(Snitch snitch, String name) { try { updateSnitchNameStmt.setString(1, name); updateSnitchNameStmt.setInt(2, snitch.getId()); Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { try { updateSnitchNameStmt.execute(); } catch (SQLException ex) { Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex); } } }); } catch (SQLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Could not update snitch name!", ex); } } //Updates the group of the snitch in the database. public void updateSnitchGroup(Snitch snitch, String group) { try { updateSnitchGroupStmt.setString(1, group); updateSnitchGroupStmt.setInt(2, snitch.getId()); Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() { @Override public void run() { try { updateSnitchGroupStmt.execute(); } catch (SQLException ex) { Logger.getLogger(JukeAlertLogger.class.getName()).log(Level.SEVERE, null, ex); } } }); } catch (SQLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Could not update snitch group!", ex); } } public Integer getLastSnitchID() { return lastSnitchID; } public void increaseLastSnitchID() { lastSnitchID++; } public void logSnitchBlockBurn(Snitch snitch, Block block) { this.logSnitchInfo(snitch, block.getType(), block.getLocation(), new Date(), LoggedAction.BLOCK_BURN, null, snitchDetailsTbl); } public String createInfoString(ResultSet set) { String resultString = ChatColor.RED + "Error!"; try { int id = set.getInt("snitch_details_id"); String initiator = set.getString("snitch_logged_initiated_user"); String victim = set.getString("snitch_logged_victim_user"); int action = (int) set.getByte("snitch_logged_action"); int material = set.getInt("snitch_logged_materialid"); int x = set.getInt("snitch_logged_X"); int y = set.getInt("snitch_logged_Y"); int z = set.getInt("snitch_logged_Z"); String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(set.getTimestamp("snitch_log_time")); if (action == LoggedAction.ENTRY.getLoggedActionId()) { resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.BLUE + ChatFiller.fillString("Entry", (double) 20), ChatColor.WHITE + ChatFiller.fillString(timestamp, (double) 30)); } else if (action == LoggedAction.BLOCK_BREAK.getLoggedActionId()) { resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.DARK_RED + ChatFiller.fillString("Block Break", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30)); } else if (action == LoggedAction.BLOCK_PLACE.getLoggedActionId()) { resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.DARK_RED + ChatFiller.fillString("Block Place", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30)); } else if (action == LoggedAction.BLOCK_BURN.getLoggedActionId()) { resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.DARK_RED + ChatFiller.fillString("Block Burn", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30)); } else if (action == LoggedAction.IGNITED.getLoggedActionId()) { resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.GOLD + ChatFiller.fillString("Ignited", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30)); } else if (action == LoggedAction.USED.getLoggedActionId()) { resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.GREEN + ChatFiller.fillString("Used", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30)); } else if (action == LoggedAction.BUCKET_EMPTY.getLoggedActionId()) { resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.DARK_RED + ChatFiller.fillString("Bucket Empty", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30)); } else if (action == LoggedAction.BUCKET_FILL.getLoggedActionId()) { resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.GREEN + ChatFiller.fillString("Bucket Fill", (double) 20), ChatColor.WHITE + ChatFiller.fillString(String.format("%d [%d %d %d]", material, x, y, z), (double) 30)); } else if (action == LoggedAction.KILL.getLoggedActionId()) { resultString = String.format(" %s %s %s", ChatColor.GOLD + ChatFiller.fillString(initiator, (double) 25), ChatColor.DARK_RED + ChatFiller.fillString("Killed", (double) 20), ChatColor.WHITE + ChatFiller.fillString(victim, (double) 30)); } else { resultString = ChatColor.RED + "Action not found. Please contact your administrator with log ID " + id; } } catch (SQLException ex) { this.plugin.getLogger().log(Level.SEVERE, "Could not get Snitch Details!"); } return resultString; } }
package eu.modernmt.model; import java.io.Serializable; import java.util.Arrays; import java.util.Iterator; public class Alignment implements Iterable<int[]>, Serializable { private final int[] sourceIndexes; private final int[] targetIndexes; private final float score; public static Alignment fromAlignmentPairs(int[][] pairs) { return fromAlignmentPairs(pairs, 0); } public static Alignment fromAlignmentPairs(int[][] pairs, float score) { int[] sourceIndexes = new int[pairs.length]; int[] targetIndexes = new int[pairs.length]; for (int i = 0; i < pairs.length; i++) { sourceIndexes[i] = pairs[i][0]; targetIndexes[i] = pairs[i][1]; } return new Alignment(sourceIndexes, targetIndexes, score); } public static Alignment fromAlignmentPairs(String string) { String[] pairsString = string.split(" "); int[][] pairs = new int[pairsString.length][]; for (int i = 0; i < pairsString.length; i++) { String[] point = pairsString[i].split("-"); pairs[i] = new int[]{Integer.parseInt(point[0]), Integer.parseInt(point[1])}; } return fromAlignmentPairs(pairs); } public Alignment(int[] sourceIndexes, int[] targetIndexes) { this(sourceIndexes, targetIndexes, 0); } public Alignment(int[] sourceIndexes, int[] targetIndexes, float score) { this.sourceIndexes = sourceIndexes; this.targetIndexes = targetIndexes; this.score = score; } public int[] getSourceIndexes() { return sourceIndexes; } public int[] getTargetIndexes() { return targetIndexes; } public int size() { return sourceIndexes.length; } public float getScore() { return score; } public Alignment getInverse() { return new Alignment(targetIndexes, sourceIndexes, score); } @Override public Iterator<int[]> iterator() { return new Iterator<int[]>() { private int index = 0; private final int[] container = new int[2]; @Override public boolean hasNext() { return index < sourceIndexes.length; } @Override public int[] next() { container[0] = sourceIndexes[index]; container[1] = targetIndexes[index]; index++; return container; } }; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Alignment alignment = (Alignment) o; if (Float.compare(alignment.score, score) != 0) return false; if (!Arrays.equals(sourceIndexes, alignment.sourceIndexes)) return false; return Arrays.equals(targetIndexes, alignment.targetIndexes); } @Override public int hashCode() { int result = Arrays.hashCode(sourceIndexes); result = 31 * result + Arrays.hashCode(targetIndexes); result = 31 * result + (score != +0.0f ? Float.floatToIntBits(score) : 0); return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < sourceIndexes.length; i++) { if (i > 0) builder.append(' '); builder.append(sourceIndexes[i]); builder.append('-'); builder.append(targetIndexes[i]); } return builder.toString(); } }
package org.jdesktop.swingx; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * An abstract implementation of Searchable supporting * incremental search. * * Keeps internal state to represent the previous search result. * For all methods taking a string as parameter: compiles the String * to a Pattern as-is and routes to the central method taking a Pattern. * * * @author Jeanette Winzenburg */ public abstract class AbstractSearchable implements Searchable { /** * a constant representing not-found state. */ public static final SearchResult NO_MATCH = new SearchResult(); /** * stores the result of the previous search. */ protected SearchResult lastSearchResult = new SearchResult(); /** key for client property to use SearchHighlighter as match marker. */ public static final String MATCH_HIGHLIGHTER = "match.highlighter"; /** * Performs a forward search starting at the beginning * across the Searchable using String that represents a * regex pattern; {@link java.util.regex.Pattern}. * @param searchString <code>String</code> that we will try to locate * @return the position of the match in appropriate coordinates or -1 if * no match found. */ public int search(String searchString) { return search(searchString, -1); } /** * Performs a forward search starting at the given startIndex * using String that represents a regex * pattern; {@link java.util.regex.Pattern}. * @param searchString <code>String</code> that we will try to locate * @param startIndex position in the document in the appropriate coordinates * from which we will start search or -1 to start from the beginning * @return the position of the match in appropriate coordinates or -1 if * no match found. */ public int search(String searchString, int startIndex) { return search(searchString, startIndex, false); } /** * Performs a search starting at the given startIndex * using String that represents a regex * pattern; {@link java.util.regex.Pattern}. The search direction * depends on the boolean parameter: forward/backward if false/true, respectively. * @param searchString <code>String</code> that we will try to locate * @param startIndex position in the document in the appropriate coordinates * from which we will start search or -1 to start from the beginning * @param backward <code>true</code> if we should perform search towards the beginning * @return the position of the match in appropriate coordinates or -1 if * no match found. */ public int search(String searchString, int startIndex, boolean backward) { Pattern pattern = null; if (!isEmpty(searchString)) { pattern = Pattern.compile(searchString, 0); } return search(pattern, startIndex, backward); } /** * Performs a forward search starting at the beginning * across the Searchable using the pattern; {@link java.util.regex.Pattern}. * @param pattern <code>Pattern</code> that we will try to locate * @return the position of the match in appropriate coordinates or -1 if * no match found. */ public int search(Pattern pattern) { return search(pattern, -1); } /** * Performs a forward search starting at the given startIndex * using the Pattern; {@link java.util.regex.Pattern}. * * @param pattern <code>Pattern</code> that we will try to locate * @param startIndex position in the document in the appropriate coordinates * from which we will start search or -1 to start from the beginning * @return the position of the match in appropriate coordinates or -1 if * no match found. */ public int search(Pattern pattern, int startIndex) { return search(pattern, startIndex, false); } /** * Performs a search starting at the given startIndex * using the pattern; {@link java.util.regex.Pattern}. * The search direction depends on the boolean parameter: * forward/backward if false/true, respectively. * * Updates visible and internal search state. * * @param pattern <code>Pattern</code> that we will try to locate * @param startIndex position in the document in the appropriate coordinates * from which we will start search or -1 to start from the beginning * @param backwards <code>true</code> if we should perform search towards the beginning * @return the position of the match in appropriate coordinates or -1 if * no match found. */ public int search(Pattern pattern, int startIndex, boolean backwards) { int matchingRow = doSearch(pattern, startIndex, backwards); moveMatchMarker(); return matchingRow; } /** * Performs a search starting at the given startIndex * using the pattern; {@link java.util.regex.Pattern}. * The search direction depends on the boolean parameter: * forward/backward if false/true, respectively. * * Updates internal search state. * * @param pattern <code>Pattern</code> that we will try to locate * @param startIndex position in the document in the appropriate coordinates * from which we will start search or -1 to start from the beginning * @param backwards <code>true</code> if we should perform search towards the beginning * @return the position of the match in appropriate coordinates or -1 if * no match found. */ protected int doSearch(Pattern pattern, final int startIndex, boolean backwards) { if (isTrivialNoMatch(pattern, startIndex)) { updateState(null); return lastSearchResult.foundRow; } int startRow; if (isEqualStartIndex(startIndex)) { // implies: the last found coordinates are valid if (!isEqualPattern(pattern)) { SearchResult searchResult = findExtendedMatch(pattern, startIndex); if (searchResult != null) { updateState(searchResult); return lastSearchResult.foundRow; } } // didn't find a match, make sure to move the startPosition // for looking for the next/previous match startRow = moveStartPosition(startIndex, backwards); } else { // startIndex is different from last search, reset the column to -1 // and make sure a -1 startIndex is mapped to first/last row, respectively. startRow = adjustStartPosition(startIndex, backwards); } findMatchAndUpdateState(pattern, startRow, backwards); return lastSearchResult.foundRow; } /** * Loops through the searchable until a match is found or the * end is reached. Updates internal search state. * * @param pattern <code>Pattern</code> that we will try to locate * @param startRow position in the document in the appropriate coordinates * from which we will start search or -1 to start from the beginning * @param backwards <code>true</code> if we should perform search towards the beginning */ protected abstract void findMatchAndUpdateState(Pattern pattern, int startRow, boolean backwards); /** * Checks and returns if it can be trivially decided to not match. * Here: pattern is null or startIndex exceeds the upper size limit. * * @param pattern <code>Pattern</code> that we will try to locate * @param startIndex position in the document in the appropriate coordinates * from which we will start search or -1 to start from the beginning * @return true if we can say ahead that no match will be found with given search criteria */ protected boolean isTrivialNoMatch(Pattern pattern, final int startIndex) { return (pattern == null) || (startIndex >= getSize()); } /** * Called if <code>startIndex</code> is different from last search * and make sure a backwards/forwards search starts at last/first row, * respectively. * @param startIndex position in the document in the appropriate coordinates * from which we will start search or -1 to start from the beginning * @param backwards <code>true</code> if we should perform search from towards the beginning * @return adjusted <code>startIndex</code> */ protected int adjustStartPosition(int startIndex, boolean backwards) { if (startIndex < 0) { if (backwards) { return getSize() - 1; } else { return 0; } } return startIndex; } /** * Moves the internal start position for matching as appropriate and returns * the new startIndex to use. * Called if search was messaged with the same startIndex as previously. * * @param startIndex position in the document in the appropriate coordinates * from which we will start search or -1 to start from the beginning * @param backwards <code>true</code> if we should perform search towards the beginning * @return adjusted <code>startIndex</code> */ protected int moveStartPosition(int startIndex, boolean backwards) { if (backwards) { startIndex } else { startIndex++; } return startIndex; } /** * Checks if the given Pattern should be considered as the same as * in a previous search. * * Here: compares the patterns' regex. * * @param pattern <code>Pattern</code> that we will compare with last request * @return if provided <code>Pattern</code> is the same as the stored from * the previous search attempt */ protected boolean isEqualPattern(Pattern pattern) { return pattern.pattern().equals(lastSearchResult.getRegEx()); } /** * Checks if the startIndex should be considered as the same as in * the previous search. * * @param startIndex <code>startIndex</code> that we will compare with the index * stored by the previous search request * @return true if the startIndex should be re-matched, false if not. */ protected boolean isEqualStartIndex(final int startIndex) { return isValidIndex(startIndex) && (startIndex == lastSearchResult.foundRow); } /** * checks if the searchString should be interpreted as empty. * here: returns true if string is null or has zero length. * * @param searchString <code>String</code> that we should evaluate * @return true if the provided <code>String</code> should be interpreted as empty */ protected boolean isEmpty(String searchString) { return (searchString == null) || searchString.length() == 0; } /** * called if sameRowIndex && !hasEqualRegEx. * Matches the cell at row/lastFoundColumn against the pattern. * PRE: lastFoundColumn valid. * * @param pattern <code>Pattern</code> that we will try to match * @param row position at which we will get the value to match with the provided <code>Pattern</code> * @return result of the match; {@link SearchResult} */ protected abstract SearchResult findExtendedMatch(Pattern pattern, int row); /** * Factory method to create a SearchResult from the given parameters. * * @param matcher the matcher after a successful find. Must not be null. * @param row the found index * @param column the found column * @return newly created <code>SearchResult</code> */ protected SearchResult createSearchResult(Matcher matcher, int row, int column) { return new SearchResult(matcher.pattern(), matcher.toMatchResult(), row, column); } /** * checks if index is in range: 0 <= index < getSize(). * @param index possible start position that we will check for validity * @return <code>true</code> if given parameter is valid index */ protected boolean isValidIndex(int index) { return index >= 0 && index < getSize(); } /** * returns the size of this searchable. * * @return size of this searchable */ protected abstract int getSize(); /** * Update inner searchable state based on provided search result * * @param searchResult <code>SearchResult</code> that represents the new state * of this <code>AbstractSearchable</code> */ protected void updateState(SearchResult searchResult) { lastSearchResult.updateFrom(searchResult); } /** * Moves the match marker according to current found state. */ protected abstract void moveMatchMarker(); /** * A convenience class to hold search state. * NOTE: this is still in-flow, probably will take more responsibility/ * or even change altogether on further factoring */ public static class SearchResult { int foundRow; int foundColumn; MatchResult matchResult; Pattern pattern; public SearchResult() { reset(); } public void updateFrom(SearchResult searchResult) { if (searchResult == null) { reset(); return; } foundRow = searchResult.foundRow; foundColumn = searchResult.foundColumn; matchResult = searchResult.matchResult; pattern = searchResult.pattern; } public String getRegEx() { return pattern != null ? pattern.pattern() : null; } public SearchResult(Pattern ex, MatchResult result, int row, int column) { pattern = ex; matchResult = result; foundRow = row; foundColumn = column; } public void reset() { foundRow= -1; foundColumn = -1; matchResult = null; pattern = null; } } }
package org.jivesoftware.spark.ui; import org.jivesoftware.resource.Res; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.spark.PresenceManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.component.VerticalFlowLayout; import org.jivesoftware.spark.component.panes.CollapsiblePane; import org.jivesoftware.spark.component.renderer.JPanelRenderer; import org.jivesoftware.spark.util.GraphicUtils; import org.jivesoftware.spark.util.ModelUtil; import org.jivesoftware.spark.util.log.Log; import org.jivesoftware.sparkimpl.settings.local.LocalPreferences; import org.jivesoftware.sparkimpl.settings.local.SettingsManager; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionAdapter; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.Timer; /** * Container representing a RosterGroup within the Contact List. */ public class ContactGroup extends CollapsiblePane implements MouseListener { private List<ContactItem> contactItems = new ArrayList<ContactItem>(); private List<ContactGroup> contactGroups = new ArrayList<ContactGroup>(); private List<ContactGroupListener> listeners = new ArrayList<ContactGroupListener>(); private List<ContactItem> offlineContacts = new ArrayList<ContactItem>(); private String groupName; private DefaultListModel model; private JList contactItemList; private boolean sharedGroup; private JPanel listPanel; // Used to display no contacts in list. private final ContactItem noContacts = new ContactItem("There are no online contacts in this group.", null); private final ListMotionListener motionListener = new ListMotionListener(); private boolean canShowPopup; private MouseEvent mouseEvent; private LocalPreferences preferences; /** * Create a new ContactGroup. * * @param groupName the name of the new ContactGroup. */ public ContactGroup(String groupName) { // Initialize Model and UI model = new DefaultListModel(); contactItemList = new JList(model); preferences = SettingsManager.getLocalPreferences(); setTitle(getGroupTitle(groupName)); // Use JPanel Renderer contactItemList.setCellRenderer(new JPanelRenderer()); this.groupName = groupName; listPanel = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, 0, true, false)); listPanel.add(contactItemList, listPanel); this.setContentPane(listPanel); if (!isOfflineGroup()) { contactItemList.setDragEnabled(true); contactItemList.setTransferHandler(new ContactGroupTransferHandler()); } // Allow for mouse events to take place on the title bar getTitlePane().addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { checkPopup(e); } public void mouseReleased(MouseEvent e) { checkPopup(e); } public void checkPopup(MouseEvent e) { if (e.isPopupTrigger()) { e.consume(); fireContactGroupPopupEvent(e); } } }); // Items should have selection listener contactItemList.addMouseListener(this); contactItemList.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent keyEvent) { } public void keyPressed(KeyEvent keyEvent) { if (keyEvent.getKeyChar() == KeyEvent.VK_ENTER) { ContactItem item = (ContactItem)contactItemList.getSelectedValue(); fireContactItemDoubleClicked(item); } ContactList.activeKeyEvent = keyEvent; } public void keyReleased(KeyEvent keyEvent) { ContactList.activeKeyEvent = null; } }); noContacts.getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11)); noContacts.getNicknameLabel().setForeground(Color.GRAY); model.addElement(noContacts); // Add Popup Window addPopupWindow(); } /** * Adds a new offline contact. * * @param nickname the nickname of the offline contact. * @param jid the jid of the offline contact. */ public void addOfflineContactItem(String nickname, String jid, String status) { // Build new ContactItem final ContactItem offlineItem = new ContactItem(nickname, jid); offlineItem.setGroupName(getGroupName()); final Presence offlinePresence = PresenceManager.getPresence(jid); offlineItem.setPresence(offlinePresence); // set offline icon offlineItem.setIcon(PresenceManager.getIconFromPresence(offlinePresence)); // Set status if applicable. if (ModelUtil.hasLength(status)) { offlineItem.setStatusText(status); } // Add to offlien contacts. offlineContacts.add(offlineItem); insertOfflineContactItem(offlineItem); } /** * Inserts a new offline <code>ContactItem</code> into the ui model. * * @param offlineItem the ContactItem to add. */ public void insertOfflineContactItem(ContactItem offlineItem) { if (model.contains(offlineItem)) { return; } if (!preferences.isOfflineGroupVisible()) { Collections.sort(offlineContacts, itemComparator); int index = offlineContacts.indexOf(offlineItem); int totalListSize = contactItems.size(); int newPos = totalListSize + index; if (newPos > model.size()) { newPos = model.size(); } model.insertElementAt(offlineItem, newPos); if (model.contains(noContacts)) { model.removeElement(noContacts); } } } /** * Removes an offline <code>ContactItem</code> from the Offline contact * model and ui. * * @param item the offline contact item to remove. */ public void removeOfflineContactItem(ContactItem item) { offlineContacts.remove(item); removeContactItem(item); } /** * Removes an offline <code>ContactItem</code> from the offline contact model and ui. * * @param jid the offline contact item to remove. */ public void removeOfflineContactItem(String jid) { final List<ContactItem> items = new ArrayList<ContactItem>(offlineContacts); for (ContactItem item : items) { if (item.getJID().equals(jid)) { removeOfflineContactItem(item); } } } /** * Toggles the visibility of Offline Contacts. * * @param show true if offline contacts should be shown, otherwise false. */ public void toggleOfflineVisibility(boolean show) { final List<ContactItem> items = new ArrayList<ContactItem>(offlineContacts); for (ContactItem item : items) { if (show) { insertOfflineContactItem(item); } else { model.removeElement(item); } } } /** * Adds a <code>ContactItem</code> to the ContactGroup. * * @param item the ContactItem. */ public void addContactItem(ContactItem item) { // Remove from offline group if it exists removeOfflineContactItem(item.getJID()); if (model.contains(noContacts)) { model.remove(0); } if ("Offline Group".equals(groupName)) { item.getNicknameLabel().setFont(new Font("Dialog", Font.PLAIN, 11)); item.getNicknameLabel().setForeground(Color.GRAY); } item.setGroupName(getGroupName()); contactItems.add(item); final List<ContactItem> sortedItemList = getContactItems(); final int index = sortedItemList.indexOf(item); Object[] objs = contactItemList.getSelectedValues(); model.insertElementAt(item, index); int[] intList = new int[objs.length]; for (int i = 0; i < objs.length; i++) { ContactItem contact = (ContactItem)objs[i]; intList[i] = model.indexOf(contact); } if (intList.length > 0) { contactItemList.setSelectedIndices(intList); } fireContactItemAdded(item); } /** * Call whenever the UI needs to be updated. */ public void fireContactGroupUpdated() { contactItemList.validate(); contactItemList.repaint(); updateTitle(); } public void addContactGroup(ContactGroup contactGroup) { final JPanel panel = new JPanel(new GridBagLayout()); panel.add(contactGroup, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 15, 0, 0), 0, 0)); panel.setBackground(Color.white); contactGroup.setSubPane(true); // contactGroup.setStyle(CollapsiblePane.TREE_STYLE); listPanel.add(panel); contactGroups.add(contactGroup); } /** * Removes a child ContactGroup. * * @param contactGroup the contact group to remove. */ public void removeContactGroup(ContactGroup contactGroup) { Component[] comps = listPanel.getComponents(); for (int i = 0; i < comps.length; i++) { Component comp = comps[i]; if (comp instanceof JPanel) { JPanel panel = (JPanel)comp; ContactGroup group = (ContactGroup)panel.getComponent(0); if (group == contactGroup) { listPanel.remove(panel); break; } } } contactGroups.remove(contactGroup); } public void setPanelBackground(Color color) { Component[] comps = listPanel.getComponents(); for (int i = 0; i < comps.length; i++) { Component comp = comps[i]; if (comp instanceof JPanel) { JPanel panel = (JPanel)comp; panel.setBackground(color); } } } /** * Returns a ContactGroup based on it's name. * * @param groupName the name of the group. * @return the ContactGroup. */ public ContactGroup getContactGroup(String groupName) { final Iterator groups = new ArrayList(contactGroups).iterator(); while (groups.hasNext()) { ContactGroup group = (ContactGroup)groups.next(); if (group.getGroupName().equals(groupName)) { return group; } } return null; } /** * Removes a <code>ContactItem</code>. * * @param item the ContactItem to remove. */ public void removeContactItem(ContactItem item) { contactItems.remove(item); model.removeElement(item); updateTitle(); fireContactItemRemoved(item); } /** * Returns a <code>ContactItem</code> by the nickname the user has been assigned. * * @param nickname the nickname of the user. * @return the ContactItem. */ public ContactItem getContactItemByNickname(String nickname) { final Iterator iter = new ArrayList(contactItems).iterator(); while (iter.hasNext()) { ContactItem item = (ContactItem)iter.next(); if (item.getNickname().equals(nickname)) { return item; } } return null; } /** * Returns a <code>ContactItem</code> by the users bare bareJID. * * @param bareJID the bareJID of the user. * @return the ContactItem. */ public ContactItem getContactItemByJID(String bareJID) { final Iterator iter = new ArrayList(contactItems).iterator(); while (iter.hasNext()) { ContactItem item = (ContactItem)iter.next(); if (item.getJID().equals(bareJID)) { return item; } } return null; } /** * Returns all <code>ContactItem</cod>s in the ContactGroup. * * @return all ContactItems. */ public List<ContactItem> getContactItems() { final List<ContactItem> list = new ArrayList<ContactItem>(contactItems); Collections.sort(list, itemComparator); return list; } /** * Returns the name of the ContactGroup. * * @return the name of the ContactGroup. */ public String getGroupName() { return groupName; } public void mouseClicked(MouseEvent e) { Object o = contactItemList.getSelectedValue(); if (!(o instanceof ContactItem)) { return; } // Iterator through rest ContactItem item = (ContactItem)o; if (e.getClickCount() == 2) { fireContactItemDoubleClicked(item); } else if (e.getClickCount() == 1) { fireContactItemClicked(item); } } public void mouseEntered(MouseEvent e) { int loc = contactItemList.locationToIndex(e.getPoint()); Object o = model.getElementAt(loc); if (!(o instanceof ContactItem)) { return; } ContactItem item = (ContactItem)o; if (item == null) { return; } contactItemList.setCursor(GraphicUtils.HAND_CURSOR); } public void mouseExited(MouseEvent e) { Object o = null; try { int loc = contactItemList.locationToIndex(e.getPoint()); if (loc == -1) { return; } o = model.getElementAt(loc); if (!(o instanceof ContactItem)) { ContactInfoWindow.getInstance().dispose(); return; } } catch (Exception e1) { Log.error(e1); return; } ContactItem item = (ContactItem)o; if (item == null) { return; } contactItemList.setCursor(GraphicUtils.DEFAULT_CURSOR); } public void mousePressed(MouseEvent e) { checkPopup(e); } public void mouseReleased(MouseEvent e) { checkPopup(e); } private void checkPopup(MouseEvent e) { if (e.isPopupTrigger()) { // Otherwise, handle single selection int index = contactItemList.locationToIndex(e.getPoint()); if (index != -1) { int[] indexes = contactItemList.getSelectedIndices(); boolean selected = false; for (int i = 0; i < indexes.length; i++) { int o = indexes[i]; if (index == o) { selected = true; } } if (!selected) { contactItemList.setSelectedIndex(index); fireContactItemClicked((ContactItem)contactItemList.getSelectedValue()); } } final Collection selectedItems = SparkManager.getChatManager().getSelectedContactItems(); if (selectedItems.size() > 1) { firePopupEvent(e, selectedItems); return; } else if (selectedItems.size() == 1) { final ContactItem contactItem = (ContactItem)selectedItems.iterator().next(); firePopupEvent(e, contactItem); } } } /** * Add a <code>ContactGroupListener</code>. * * @param listener the ContactGroupListener. */ public void addContactGroupListener(ContactGroupListener listener) { listeners.add(listener); } /** * Removes a <code>ContactGroupListener</code>. * * @param listener the ContactGroupListener. */ public void removeContactGroupListener(ContactGroupListener listener) { listeners.remove(listener); } private void fireContactItemClicked(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemClicked(item); } } private void fireContactItemDoubleClicked(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemDoubleClicked(item); } } private void firePopupEvent(MouseEvent e, ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).showPopup(e, item); } } private void firePopupEvent(MouseEvent e, Collection items) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).showPopup(e, items); } } private void fireContactGroupPopupEvent(MouseEvent e) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactGroupPopup(e, this); } } private void fireContactItemAdded(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemAdded(item); } } private void fireContactItemRemoved(ContactItem item) { final Iterator iter = new ArrayList(listeners).iterator(); while (iter.hasNext()) { ((ContactGroupListener)iter.next()).contactItemRemoved(item); } } private void updateTitle() { if ("Offline Group".equals(groupName)) { setTitle("Offline Group"); return; } int count = 0; List list = new ArrayList(getContactItems()); int size = list.size(); for (int i = 0; i < size; i++) { ContactItem it = (ContactItem)list.get(i); if (it.isAvailable()) { count++; } } setTitle(getGroupTitle(groupName) + " (" + count + " online)"); if (model.getSize() == 0) { model.addElement(noContacts); } } /** * Returns the containing <code>JList</code> of the ContactGroup. * * @return the JList. */ public JList getList() { return contactItemList; } /** * Clears all selections within this group. */ public void clearSelection() { contactItemList.clearSelection(); } public void removeAllContacts() { // Remove all users from online group. Iterator contactItems = new ArrayList(getContactItems()).iterator(); while (contactItems.hasNext()) { ContactItem item = (ContactItem)contactItems.next(); removeContactItem(item); } // Remove all users from offline group. for (ContactItem item : getOfflineContacts()) { removeOfflineContactItem(item); } } /** * Returns true if the ContactGroup contains available users. * * @return true if the ContactGroup contains available users. */ public boolean hasAvailableContacts() { final Iterator iter = contactGroups.iterator(); while (iter.hasNext()) { ContactGroup group = (ContactGroup)iter.next(); if (group.hasAvailableContacts()) { return true; } } Iterator contacts = getContactItems().iterator(); while (contacts.hasNext()) { ContactItem item = (ContactItem)contacts.next(); if (item.getPresence() != null) { return true; } } return false; } public Collection<ContactItem> getOfflineContacts() { return new ArrayList<ContactItem>(offlineContacts); } /** * Sorts ContactItems. */ final Comparator<ContactItem> itemComparator = new Comparator() { public int compare(Object contactItemOne, Object contactItemTwo) { final ContactItem item1 = (ContactItem)contactItemOne; final ContactItem item2 = (ContactItem)contactItemTwo; return item1.getNickname().toLowerCase().compareTo(item2.getNickname().toLowerCase()); } }; /** * Returns true if this ContactGroup is the Offline Group. * * @return true if OfflineGroup. */ public boolean isOfflineGroup() { return "Offline Group".equals(getGroupName()); } /** * Returns true if this ContactGroup is the Unfiled Group. * * @return true if UnfiledGroup. */ public boolean isUnfiledGroup() { return "Unfiled".equals(getGroupName()); } public String toString() { return getGroupName(); } /** * Returns true if ContactGroup is a Shared Group. * * @return true if Shared Group. */ public boolean isSharedGroup() { return sharedGroup; } /** * Set to true if this ContactGroup is a shared Group. * * @param sharedGroup true if shared group. */ protected void setSharedGroup(boolean sharedGroup) { this.sharedGroup = sharedGroup; if (sharedGroup) { setToolTipText(Res.getString("message.is.shared.group", getGroupName())); } } /** * Returns all Selected Contacts within the ContactGroup. * * @return all selected ContactItems. */ public List getSelectedContacts() { final List items = new ArrayList(); Object[] selections = contactItemList.getSelectedValues(); final int no = selections != null ? selections.length : 0; for (int i = 0; i < no; i++) { ContactItem item = (ContactItem)selections[i]; items.add(item); } return items; } public JPanel getContainerPanel() { return listPanel; } public Collection getContactGroups() { return contactGroups; } /** * Lets make sure that the panel doesn't stretch past the * scrollpane view pane. * * @return the preferred dimension */ public Dimension getPreferredSize() { final Dimension size = super.getPreferredSize(); size.width = 0; return size; } /** * Sets the name of group. * * @param groupName the contact group name. */ public void setGroupName(String groupName) { this.groupName = groupName; } /** * Returns the "pretty" title of the ContactGroup. * * @param title the title. * @return the new title. */ public String getGroupTitle(String title) { int lastIndex = title.lastIndexOf("::"); if (lastIndex != -1) { title = title.substring(lastIndex + 2); } return title; } /** * Returns true if the group is nested. * * @param groupName the name of the group. * @return true if the group is nested. */ public boolean isSubGroup(String groupName) { return groupName.indexOf("::") != -1; } /** * Returns true if this group is nested. * * @return true if nested. */ public boolean isSubGroup() { return isSubGroup(getGroupName()); } /** * Returns the underlying container for the JList. * * @return the underlying container of the JList. */ public JPanel getListPanel() { return listPanel; } /** * Adds an internal popup listesner. */ private void addPopupWindow() { final Timer timer = new Timer(500, new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { canShowPopup = true; } }); contactItemList.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent mouseEvent) { timer.start(); } public void mouseExited(MouseEvent mouseEvent) { timer.stop(); canShowPopup = false; ContactInfoWindow.getInstance().dispose(); } }); contactItemList.addMouseMotionListener(motionListener); } private class ListMotionListener extends MouseMotionAdapter { public void mouseMoved(MouseEvent e) { if (e != null) { mouseEvent = e; } if (!canShowPopup) { return; } if (e == null) { return; } displayWindow(e); } } /** * Displays the <code>ContactInfoWindow</code>. * * @param e the mouseEvent that triggered this event. */ private void displayWindow(MouseEvent e) { ContactInfoWindow.getInstance().display(this, e); } }
package org.kuali.rice.krms.api; import java.util.List; /** * The context represents the area(s) of an organization's activity where a * rule applies and where the terms used to create the rule are defined and relevant. * An equivalent phrase often used is business domain. Rules only make sense in a * particular context and because they must be evaluated against the information in * that domain or context. * * <p>For example, rules that are specifically authored and * that are meaningful in an application on a Research Proposal would be most * unlikely to make sense or be relevant in the context of a Student Record even * if the condition could be evaluated. * * @author Kuali Rice Team ([email protected]) * */ public interface Context { void execute(ExecutionEnvironment environment); List<AssetResolver<?>> getAssetResolvers(); boolean appliesTo(ExecutionEnvironment environment); }
package com.esotericsoftware.kryonet; import static com.esotericsoftware.minlog.Log.*; import java.io.IOException; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import com.esotericsoftware.kryo.Context; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.SerializationException; import com.esotericsoftware.kryo.serialize.IntSerializer; /** * @author Nathan Sweet <[email protected]> */ class TcpConnection { static private final int IPTOS_LOWDELAY = 0x10; SocketChannel socketChannel; int keepAliveTime = 59000; final ByteBuffer readBuffer, writeBuffer; private final Kryo kryo; private final ByteBuffer writeLengthBuffer = ByteBuffer.allocateDirect(4); private SelectionKey selectionKey; private final Object writeLock = new Object(); private int currentObjectLength; private long lastCommunicationTime; public TcpConnection (Kryo kryo, int writeBufferSize, int readBufferSize) { this.kryo = kryo; writeBuffer = ByteBuffer.allocateDirect(writeBufferSize); readBuffer = ByteBuffer.allocateDirect(readBufferSize); readBuffer.flip(); } public SelectionKey accept (Selector selector, SocketChannel socketChannel) throws IOException { try { this.socketChannel = socketChannel; socketChannel.configureBlocking(false); socketChannel.socket().setTcpNoDelay(true); selectionKey = socketChannel.register(selector, SelectionKey.OP_READ); if (DEBUG) { debug("kryonet", "Port " + socketChannel.socket().getLocalPort() + "/TCP connected to: " + socketChannel.socket().getRemoteSocketAddress()); } if (keepAliveTime > 0) lastCommunicationTime = System.currentTimeMillis(); return selectionKey; } catch (IOException ex) { close(); throw ex; } } public void connect (Selector selector, SocketAddress remoteAddress, int timeout) throws IOException { close(); writeBuffer.clear(); readBuffer.clear(); readBuffer.flip(); try { SocketChannel socketChannel = selector.provider().openSocketChannel(); Socket socket = socketChannel.socket(); socket.setTcpNoDelay(true); socket.setTrafficClass(IPTOS_LOWDELAY); socket.connect(remoteAddress, timeout); // Connect using blocking mode for simplicity. socketChannel.configureBlocking(false); this.socketChannel = socketChannel; selectionKey = socketChannel.register(selector, SelectionKey.OP_READ); selectionKey.attach(this); if (DEBUG) { debug("kryonet", "Port " + socketChannel.socket().getLocalPort() + "/TCP connected to: " + socketChannel.socket().getRemoteSocketAddress()); } if (keepAliveTime > 0) lastCommunicationTime = System.currentTimeMillis(); } catch (IOException ex) { close(); IOException ioEx = new IOException("Unable to connect to: " + remoteAddress); ioEx.initCause(ex); throw ioEx; } } public Object readObject (Connection connection) throws IOException { SocketChannel socketChannel = this.socketChannel; if (socketChannel == null) throw new SocketException("Connection is closed."); if (currentObjectLength == 0) { // Read the length of the next object from the socket. if (!IntSerializer.canRead(readBuffer, true)) { readBuffer.compact(); int bytesRead = socketChannel.read(readBuffer); readBuffer.flip(); if (bytesRead == -1) throw new SocketException("Connection is closed."); if (keepAliveTime > 0) lastCommunicationTime = System.currentTimeMillis(); if (!IntSerializer.canRead(readBuffer, true)) return null; } currentObjectLength = IntSerializer.get(readBuffer, true); if (currentObjectLength <= 0) throw new SerializationException("Invalid object length: " + currentObjectLength); if (currentObjectLength > readBuffer.capacity()) throw new SerializationException("Unable to read object larger than read buffer: " + currentObjectLength); } int length = currentObjectLength; if (readBuffer.remaining() < length) { // Read the bytes for the next object from the socket. readBuffer.compact(); int bytesRead = socketChannel.read(readBuffer); readBuffer.flip(); if (bytesRead == -1) throw new SocketException("Connection is closed."); if (keepAliveTime > 0) lastCommunicationTime = System.currentTimeMillis(); if (readBuffer.remaining() < length) return null; } currentObjectLength = 0; int startPosition = readBuffer.position(); int oldLimit = readBuffer.limit(); readBuffer.limit(startPosition + length); Context context = Kryo.getContext(); context.put("connection", connection); context.setRemoteEntityID(connection.id); Object object = kryo.readClassAndObject(readBuffer); readBuffer.limit(oldLimit); if (readBuffer.position() - startPosition != length) throw new SerializationException("Incorrect number of bytes (" + (startPosition + length - readBuffer.position()) + " remaining) used to deserialize object: " + object); return object; } public void writeOperation () throws IOException { synchronized (writeLock) { // If it was not a partial write, clear the OP_WRITE flag. Otherwise wait to be notified when more writing can occur. if (writeToSocket()) selectionKey.interestOps(SelectionKey.OP_READ); } } private boolean writeToSocket () throws IOException { SocketChannel socketChannel = this.socketChannel; if (socketChannel == null) throw new SocketException("Connection is closed."); writeBuffer.flip(); while (writeBuffer.hasRemaining()) if (socketChannel.write(writeBuffer) == 0) break; boolean wasFullWrite = !writeBuffer.hasRemaining(); writeBuffer.compact(); if (keepAliveTime > 0) lastCommunicationTime = System.currentTimeMillis(); return wasFullWrite; } /** * This method is thread safe. */ public int send (Connection connection, Object object) throws IOException { SocketChannel socketChannel = this.socketChannel; if (socketChannel == null) throw new SocketException("Connection is closed."); synchronized (writeLock) { int start = writeBuffer.position(); try { writeBuffer.position(start + 1); // Allow 1 byte for the data length (the ideal case). } catch (IllegalArgumentException ex) { throw new SerializationException("Buffer limit exceeded writing object of type: " + object.getClass().getName(), new BufferOverflowException()); } Context context = Kryo.getContext(); context.put("connection", connection); context.setRemoteEntityID(connection.id); try { kryo.writeClassAndObject(writeBuffer, object); } catch (SerializationException ex) { writeBuffer.position(start); throw new SerializationException("Unable to serialize object of type: " + object.getClass().getName(), ex); } // Write data length to socket. int dataLength = writeBuffer.position() - start - 1; int lengthLength; if (dataLength <= 127) { // Ideally it fits in one byte. lengthLength = 1; writeBuffer.put(start, (byte)dataLength); } else { // Write it to a temporary buffer. writeLengthBuffer.clear(); lengthLength = IntSerializer.put(writeLengthBuffer, dataLength, true); writeLengthBuffer.flip(); // Put last byte in writeBuffer. int lastIndex = writeLengthBuffer.limit() - 1; writeBuffer.put(start, writeLengthBuffer.get(lastIndex)); writeLengthBuffer.limit(lastIndex); // Write the rest to the socket. while (writeLengthBuffer.hasRemaining()) if (socketChannel.write(writeLengthBuffer) == 0) break; if (writeLengthBuffer.hasRemaining()) { // If writing the length failed (rare), shift the data over. byte[] temp = context.getByteArray(dataLength + 1); writeBuffer.position(start); writeBuffer.get(temp); writeBuffer.position(start); writeBuffer.put(writeLengthBuffer); writeBuffer.put(temp); } } if (DEBUG || TRACE) { float percentage = writeBuffer.position() / (float)writeBuffer.capacity(); if (TRACE) trace("kryonet", connection + " TCP write buffer utilization: " + percentage + "%"); if (DEBUG && percentage > 0.75f) debug("kryonet", connection + " TCP write buffer is approaching capacity: " + percentage + "%"); } // If it was a partial write, set the OP_WRITE flag to be notified when more writing can occur. if (!writeToSocket()) selectionKey.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE); return lengthLength + dataLength; } } public void close () { try { if (socketChannel != null) { socketChannel.close(); socketChannel = null; if (selectionKey != null) selectionKey.selector().wakeup(); } } catch (IOException ex) { if (DEBUG) debug("kryonet", "Unable to close TCP connection.", ex); } } public boolean needsKeepAlive (long time) { return socketChannel != null && keepAliveTime > 0 && time - lastCommunicationTime > keepAliveTime; } }
package foam.nanos.http; import foam.nanos.app.Mode; import foam.box.Box; import foam.box.SessionServerBox; import foam.core.FObject; import foam.core.ProxyX; import foam.core.X; import foam.lib.json.ExprParser; import foam.lib.json.JSONParser; import foam.lib.parse.*; import foam.nanos.app.AppConfig; import foam.nanos.jetty.HttpServer; import foam.nanos.jetty.HttpServer; import foam.nanos.logger.Logger; import foam.nanos.servlet.VirtualHostRoutingServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.PrintWriter; import java.net.URL; @SuppressWarnings("serial") public class ServiceWebAgent implements WebAgent { public static final int BUFFER_SIZE = 4096; protected static ThreadLocal<StringBuilder> sb = new ThreadLocal<StringBuilder>() { @Override protected StringBuilder initialValue() { return new StringBuilder(); } @Override public StringBuilder get() { StringBuilder b = super.get(); b.setLength(0); return b; } }; protected Box skeleton_; protected boolean authenticate_; public ServiceWebAgent(Box skeleton, boolean authenticate) { skeleton_ = skeleton; authenticate_ = authenticate; } public void execute(X x) { try { HttpServletRequest req = x.get(HttpServletRequest.class); HttpServletResponse resp = x.get(HttpServletResponse.class); PrintWriter out = x.get(PrintWriter.class); BufferedReader reader = req.getReader(); X requestContext = x.put("httpRequest", req).put("httpResponse", resp); Logger logger = (Logger) x.get("logger"); HttpServer http = (HttpServer) x.get("http"); if ( ((AppConfig) x.get("appConfig")).getMode() != Mode.PRODUCTION ) { resp.setHeader("Access-Control-Allow-Origin", "*"); } else if ( ! foam.util.SafetyUtil.isEmpty(req.getHeader("Origin")) && ! "null".equals(req.getHeader("Origin")) ) { URL url = new URL(req.getHeader("Origin")); if ( ((VirtualHostRoutingServlet) http.getServletMappings()[0].getServletObject()).getHostMapping().containsKey(url.getHost()) ) resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin")); } if ( req.getMethod() == "OPTIONS" ) { resp.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS, POST, PUT"); resp.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, Cache-Control, Origin, Pragma"); resp.setStatus(resp.SC_OK); out.flush(); return; } int read = 0; int count = 0; int length = req.getContentLength(); StringBuilder builder = sb.get(); char[] cbuffer = new char[BUFFER_SIZE]; while ( ( read = reader.read(cbuffer, 0, BUFFER_SIZE)) != -1 && count < length ) { builder.append(cbuffer, 0, read); count += read; } FObject result; try { result = requestContext.create(JSONParser.class).parseString(builder.toString()); } catch (Throwable t) { System.err.println("Unable to parse: " + builder.toString()); throw t; } if ( result == null ) { resp.setStatus(resp.SC_BAD_REQUEST); String message = getParsingError(x, builder.toString()); logger.error("JSON parse error: " + message + ", input: " + builder.toString()); out.flush(); return; } if ( ! ( result instanceof foam.box.Message ) ) { resp.setStatus(resp.SC_BAD_REQUEST); logger.error("Expected instance of foam.box.Message"); out.print("Expected instance of foam.box.Message"); out.flush(); return; } foam.box.Message msg = (foam.box.Message) result; new SessionServerBox(x, skeleton_, authenticate_).send(msg); } catch (Throwable t) { throw new RuntimeException(t); } } /** * Gets the result of a failing parsing of a buffer * @param buffer the buffer that failed to be parsed * @return the error message */ protected String getParsingError(X x, String buffer) { Parser parser = ExprParser.instance(); PStream ps = new StringPStream(); ParserContext psx = new ParserContextImpl(); ((StringPStream) ps).setString(buffer); psx.set("X", x == null ? new ProxyX() : x); ErrorReportingPStream eps = new ErrorReportingPStream(ps); ps = eps.apply(parser, psx); return eps.getMessage(); } }
package ljdp.minechem.common.recipe; import java.util.ArrayList; import java.util.Iterator; import ljdp.minechem.api.core.Chemical; import ljdp.minechem.api.core.Element; import ljdp.minechem.api.core.EnumElement; import ljdp.minechem.api.core.EnumMolecule; import ljdp.minechem.api.core.Molecule; import ljdp.minechem.api.recipe.DecomposerRecipe; import ljdp.minechem.api.recipe.DecomposerRecipeChance; import ljdp.minechem.api.recipe.DecomposerRecipeSelect; import ljdp.minechem.api.recipe.SynthesisRecipe; import ljdp.minechem.api.util.Util; import ljdp.minechem.common.MinechemBlocks; import ljdp.minechem.common.MinechemItems; import ljdp.minechem.common.blueprint.MinechemBlueprint; import ljdp.minechem.common.items.ItemBlueprint; import ljdp.minechem.common.items.ItemElement; import ljdp.minechem.common.recipe.handlers.AppliedEnergisticsOreDictionaryHandler; import ljdp.minechem.common.recipe.handlers.DefaultOreDictionaryHandler; import ljdp.minechem.common.recipe.handlers.GregTechOreDictionaryHandler; import ljdp.minechem.common.recipe.handlers.IC2OreDictionaryHandler; import ljdp.minechem.common.recipe.handlers.MekanismOreDictionaryHandler; import ljdp.minechem.common.recipe.handlers.UndergroundBiomesOreDictionaryHandler; import net.minecraft.block.Block; import net.minecraft.item.Item; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.event.ForgeSubscribe; import net.minecraftforge.oredict.OreDictionary; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.registry.GameRegistry; public class MinechemRecipes { private static final MinechemRecipes instance = new MinechemRecipes(); public ArrayList unbondingRecipes = new ArrayList(); public ArrayList synthesisRecipes = new ArrayList(); public static MinechemRecipes getInstance() { return instance; } public void registerVanillaChemicalRecipes() { // Molecules Molecule moleculeSiliconDioxide = this.molecule( EnumMolecule.siliconDioxide, 4); Molecule moleculeCellulose = this.molecule(EnumMolecule.cellulose, 1); Molecule moleculePolyvinylChloride = this .molecule(EnumMolecule.polyvinylChloride); // Elements Element elementHydrogen = this.element(EnumElement.H, 64); Element elementHelium = this.element(EnumElement.He, 64); Element elementCarbon = this.element(EnumElement.C, 64); // Section 1 - Blocks // Stone ItemStack blockStone = new ItemStack(Block.stone); DecomposerRecipe.add(new DecomposerRecipeSelect(blockStone, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.stone, 7), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, this.element(EnumElement.O, 2), null, null })); // Grass Block ItemStack blockGrass = new ItemStack(Block.grass); DecomposerRecipe.add(new DecomposerRecipeSelect(blockGrass, 0.07F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }), new DecomposerRecipe( new Chemical[] { moleculeCellulose }) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.grass, 16), true, 50, new Chemical[] { null, moleculeCellulose, null, null, this.element(EnumElement.O, 2), this.element(EnumElement.Si) })); // Dirt ItemStack blockDirt = new ItemStack(Block.dirt); DecomposerRecipe.add(new DecomposerRecipeSelect(blockDirt, 0.07F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Zn), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.dirt, 16), true, 50, new Chemical[] { null, null, null, null, this.element(EnumElement.O, 2), this.element(EnumElement.Si) })); // Cobblestone ItemStack blockCobblestone = new ItemStack(Block.cobblestone); DecomposerRecipe.add(new DecomposerRecipeSelect(blockCobblestone, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Fe), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Mg), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ti), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Na), this.element(EnumElement.Cl) }) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack( Block.cobblestone, 8), true, 50, new Chemical[] { this.element(EnumElement.Si), null, null, null, this.element(EnumElement.O, 2), null })); // Planks // TODO: Add synthesizer recipes? ItemStack blockOakWoodPlanks = new ItemStack(Block.planks, 1, 0); ItemStack blockSpruceWoodPlanks = new ItemStack(Block.planks, 1, 1); ItemStack blockBirchWoodPlanks = new ItemStack(Block.planks, 1, 2); ItemStack blockJungleWoodPlanks = new ItemStack(Block.planks, 1, 3); DecomposerRecipe.add(new DecomposerRecipeChance(blockOakWoodPlanks, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockSpruceWoodPlanks, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockBirchWoodPlanks, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockJungleWoodPlanks, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 2) })); // Saplings ItemStack blockOakSapling = new ItemStack(Block.sapling, 1, 0); ItemStack blockSpruceSapling = new ItemStack(Block.sapling, 1, 1); ItemStack blockBirchSapling = new ItemStack(Block.sapling, 1, 2); ItemStack blockJungleSapling = new ItemStack(Block.sapling, 1, 3); DecomposerRecipe.add(new DecomposerRecipeChance(blockOakSapling, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); DecomposerRecipe .add(new DecomposerRecipeChance( blockSpruceSapling, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); DecomposerRecipe .add(new DecomposerRecipeChance( blockBirchSapling, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); DecomposerRecipe .add(new DecomposerRecipeChance( blockJungleSapling, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); SynthesisRecipe.add(new SynthesisRecipe(blockOakSapling, true, 20, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose) })); SynthesisRecipe.add(new SynthesisRecipe(blockSpruceSapling, true, 20, new Chemical[] { null, null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null })); SynthesisRecipe.add(new SynthesisRecipe(blockBirchSapling, true, 20, new Chemical[] { null, null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null })); SynthesisRecipe .add(new SynthesisRecipe(blockJungleSapling, true, 20, new Chemical[] { null, null, null, null, null, this.molecule(EnumMolecule.cellulose), null, null, null })); // Water ItemStack blockWaterSource = new ItemStack(Block.waterMoving); ItemStack blockWaterStill = new ItemStack(Block.waterStill); DecomposerRecipe.add(new DecomposerRecipe(blockWaterSource, new Chemical[] { this.molecule(EnumMolecule.water, 16) })); DecomposerRecipe.add(new DecomposerRecipe(blockWaterStill, new Chemical[] { this.molecule(EnumMolecule.water, 16) })); SynthesisRecipe.add(new SynthesisRecipe(blockWaterSource, false, 20, new Chemical[] { this.molecule(EnumMolecule.water, 16) })); // Lava // TODO: Add support for lava // Sand ItemStack blockSand = new ItemStack(Block.sand); DecomposerRecipe .add(new DecomposerRecipe(blockSand, new Chemical[] { this .molecule(EnumMolecule.siliconDioxide, 16) })); SynthesisRecipe.add(new SynthesisRecipe(blockSand, true, 200, new Chemical[] { moleculeSiliconDioxide, moleculeSiliconDioxide, moleculeSiliconDioxide, moleculeSiliconDioxide })); // Gravel ItemStack blockGravel = new ItemStack(Block.gravel); DecomposerRecipe.add(new DecomposerRecipeChance(blockGravel, 0.35F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) })); SynthesisRecipe.add(new SynthesisRecipe(blockGravel, true, 30, new Chemical[] { null, null, null, null, null, null, null, null, this.molecule(EnumMolecule.siliconDioxide) })); // Gold Ore ItemStack oreGold = new ItemStack(Block.oreGold); DecomposerRecipe.add(new DecomposerRecipe(oreGold, new Chemical[] { this.element(EnumElement.Au, 32) })); // Iron Ore ItemStack oreIron = new ItemStack(Block.oreIron); DecomposerRecipe.add(new DecomposerRecipe(oreIron, new Chemical[] { this.element(EnumElement.Fe, 32) })); // Coal Ore ItemStack oreCoal = new ItemStack(Block.oreCoal); DecomposerRecipe.add(new DecomposerRecipe(oreCoal, new Chemical[] { this.element(EnumElement.C, 32) })); // Wood ItemStack blockOakWood = new ItemStack(Block.wood, 1, 0); ItemStack blockSpruceWood = new ItemStack(Block.wood, 1, 1); ItemStack blockBirchWood = new ItemStack(Block.wood, 1, 2); ItemStack blockJungleWood = new ItemStack(Block.wood, 1, 3); DecomposerRecipe.add(new DecomposerRecipeChance(blockOakWood, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockSpruceWood, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockBirchWood, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockJungleWood, 0.5F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 8) })); SynthesisRecipe.add(new SynthesisRecipe(blockOakWood, true, 100, new Chemical[] { moleculeCellulose, moleculeCellulose, moleculeCellulose, null, moleculeCellulose, null, null, null, null })); SynthesisRecipe.add(new SynthesisRecipe(blockSpruceWood, true, 100, new Chemical[] { null, null, null, null, moleculeCellulose, null, moleculeCellulose, moleculeCellulose, moleculeCellulose })); SynthesisRecipe.add(new SynthesisRecipe(blockBirchWood, true, 100, new Chemical[] { moleculeCellulose, null, moleculeCellulose, null, null, null, moleculeCellulose, null, moleculeCellulose })); SynthesisRecipe.add(new SynthesisRecipe(blockJungleWood, true, 100, new Chemical[] { moleculeCellulose, null, null, moleculeCellulose, moleculeCellulose, null, moleculeCellulose, null, null })); // Leaves // TODO: Add support for leaves // Glass ItemStack blockGlass = new ItemStack(Block.glass); DecomposerRecipe .add(new DecomposerRecipe(blockGlass, new Chemical[] { this .molecule(EnumMolecule.siliconDioxide, 16) })); SynthesisRecipe .add(new SynthesisRecipe(blockGlass, true, 500, new Chemical[] { moleculeSiliconDioxide, null, moleculeSiliconDioxide, null, null, null, moleculeSiliconDioxide, null, moleculeSiliconDioxide })); // Lapis Lazuli Ore ItemStack blockOreLapis = new ItemStack(Block.oreLapis); DecomposerRecipe.add(new DecomposerRecipe(blockOreLapis, new Chemical[] { this.molecule(EnumMolecule.lazurite, 4), this.molecule(EnumMolecule.sodalite), this.molecule(EnumMolecule.noselite), this.molecule(EnumMolecule.calcite), this.molecule(EnumMolecule.pyrite) })); // Lapis Lazuli Block // TODO: Add support for Lapis Lazuli Block? // Cobweb ItemStack blockCobweb = new ItemStack(Block.web); DecomposerRecipe.add(new DecomposerRecipe(blockCobweb, new Chemical[] { this.molecule(EnumMolecule.fibroin) })); // Tall Grass ItemStack blockTallGrass = new ItemStack(Block.tallGrass, 1, 1); DecomposerRecipe.add(new DecomposerRecipeChance(blockTallGrass, 0.1F, new Chemical[] { new Molecule(EnumMolecule.afroman, 2) })); // Sandstone ItemStack blockSandStone = new ItemStack(Block.sandStone, 1, 0); ItemStack blockChiseledSandStone = new ItemStack(Block.sandStone, 1, 1); ItemStack blockSmoothSandStone = new ItemStack(Block.sandStone, 1, 2); DecomposerRecipe .add(new DecomposerRecipe(blockSandStone, new Chemical[] { this .molecule(EnumMolecule.siliconDioxide, 16) })); DecomposerRecipe .add(new DecomposerRecipe(blockChiseledSandStone, new Chemical[] { this.molecule( EnumMolecule.siliconDioxide, 16) })); DecomposerRecipe .add(new DecomposerRecipe(blockSmoothSandStone, new Chemical[] { this.molecule( EnumMolecule.siliconDioxide, 16) })); SynthesisRecipe.add(new SynthesisRecipe(blockSandStone, true, 20, new Chemical[] { null, null, null, null, this.molecule(EnumMolecule.siliconDioxide, 16), null, null, null, null })); SynthesisRecipe .add(new SynthesisRecipe(blockChiseledSandStone, true, 20, new Chemical[] { null, null, null, null, null, null, null, this.molecule(EnumMolecule.siliconDioxide, 16), null })); SynthesisRecipe.add(new SynthesisRecipe(blockSmoothSandStone, true, 20, new Chemical[] { null, this.molecule(EnumMolecule.siliconDioxide, 16), null, null, null, null, null, null, null })); // Wool ItemStack blockWool = new ItemStack(Block.cloth, 1, 0); ItemStack blockOrangeWool = new ItemStack(Block.cloth, 1, 1); ItemStack blockMagentaWool = new ItemStack(Block.cloth, 1, 2); ItemStack blockLightBlueWool = new ItemStack(Block.cloth, 1, 3); ItemStack blockYellowWool = new ItemStack(Block.cloth, 1, 4); ItemStack blockLimeWool = new ItemStack(Block.cloth, 1, 5); ItemStack blockPinkWool = new ItemStack(Block.cloth, 1, 6); ItemStack blockGrayWool = new ItemStack(Block.cloth, 1, 7); ItemStack blockLightGrayWool = new ItemStack(Block.cloth, 1, 8); ItemStack blockCyanWool = new ItemStack(Block.cloth, 1, 9); ItemStack blockPurpleWool = new ItemStack(Block.cloth, 1, 10); ItemStack blockBlueWool = new ItemStack(Block.cloth, 1, 11); ItemStack blockBrownWool = new ItemStack(Block.cloth, 1, 12); ItemStack blockGreenWool = new ItemStack(Block.cloth, 1, 13); ItemStack blockRedWool = new ItemStack(Block.cloth, 1, 14); ItemStack blockBlackWool = new ItemStack(Block.cloth, 1, 15); DecomposerRecipe.add(new DecomposerRecipeChance(blockWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockOrangeWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockMagentaWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockLightBlueWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockYellowWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockLimeWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockPinkWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockGrayWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockLightGrayWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockCyanWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockPurpleWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockBlueWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockBrownWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.tannicacid) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockGreenWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockRedWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(blockBlackWool, 0.6F, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockOrangeWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.orangePigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockMagentaWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockLightBlueWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockYellowWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.yellowPigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockLimeWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.limePigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockPinkWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockGrayWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) })); SynthesisRecipe.add(new SynthesisRecipe(blockLightGrayWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockCyanWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockPurpleWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.purplePigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockBlueWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.lazurite) })); SynthesisRecipe.add(new SynthesisRecipe(blockGreenWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.greenPigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockRedWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.redPigment) })); SynthesisRecipe.add(new SynthesisRecipe(blockBlackWool, false, 50, new Chemical[] { this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.blackPigment) })); // Flowers // TODO: Add support for Rose ItemStack blockPlantYellow = new ItemStack(Block.plantYellow); DecomposerRecipe.add(new DecomposerRecipeChance(blockPlantYellow, 0.3F, new Chemical[] { new Molecule(EnumMolecule.shikimicAcid, 2) })); // Mushrooms ItemStack blockMushroomBrown = new ItemStack(Block.mushroomBrown); ItemStack blockMushroomRed = new ItemStack(Block.mushroomRed); DecomposerRecipe.add(new DecomposerRecipe(blockMushroomBrown, new Chemical[] { this.molecule(EnumMolecule.psilocybin), this.molecule(EnumMolecule.water, 2) })); DecomposerRecipe.add(new DecomposerRecipe(blockMushroomRed, new Chemical[] { this.molecule(EnumMolecule.pantherine), this.molecule(EnumMolecule.water, 2) })); // Block of Gold DecomposerRecipe.add(new DecomposerRecipe( new ItemStack(Block.blockGold), new Chemical[] { this.element( EnumElement.Au, 144) })); // Block of Iron DecomposerRecipe.add(new DecomposerRecipe( new ItemStack(Block.blockIron), new Chemical[] { this.element( EnumElement.Fe, 144) })); // Slabs // TODO: Add support for slabs? // TNT ItemStack blockTnt = new ItemStack(Block.tnt); DecomposerRecipe.add(new DecomposerRecipe(blockTnt, new Chemical[] { this.molecule(EnumMolecule.tnt) })); SynthesisRecipe.add(new SynthesisRecipe(blockTnt, false, 1000, new Chemical[] { this.molecule(EnumMolecule.tnt) })); // Obsidian ItemStack blockObsidian = new ItemStack(Block.obsidian); DecomposerRecipe.add(new DecomposerRecipe(blockObsidian, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 16), this.molecule(EnumMolecule.magnesiumOxide, 8) })); SynthesisRecipe.add(new SynthesisRecipe(blockObsidian, true, 1000, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), null, this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2), this.molecule(EnumMolecule.magnesiumOxide, 2) })); // Diamond Ore ItemStack blockOreDiamond = new ItemStack(Block.oreDiamond); DecomposerRecipe.add(new DecomposerRecipe(blockOreDiamond, new Chemical[] { this.molecule(EnumMolecule.fullrene, 6) })); // Block of Diamond ItemStack blockDiamond = new ItemStack(Block.blockDiamond); DecomposerRecipe.add(new DecomposerRecipe(blockDiamond, new Chemical[] { this.molecule(EnumMolecule.fullrene, 36) })); SynthesisRecipe.add(new SynthesisRecipe(blockDiamond, true, 120000, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4), this.molecule(EnumMolecule.fullrene, 4) })); // Pressure Plate ItemStack blockPressurePlatePlanks = new ItemStack( Block.pressurePlatePlanks); DecomposerRecipe.add(new DecomposerRecipeChance( blockPressurePlatePlanks, 0.4F, new Chemical[] { this.molecule( EnumMolecule.cellulose, 4) })); // Redston Ore ItemStack blockOreRedstone = new ItemStack(Block.oreRedstone); DecomposerRecipe.add(new DecomposerRecipeChance(blockOreRedstone, 0.8F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide, 6), this.element(EnumElement.Cu, 6) })); // Cactus ItemStack blockCactus = new ItemStack(Block.cactus); DecomposerRecipe.add(new DecomposerRecipe(blockCactus, new Chemical[] { this.molecule(EnumMolecule.mescaline), this.molecule(EnumMolecule.water, 20) })); SynthesisRecipe.add(new SynthesisRecipe(blockCactus, true, 200, new Chemical[] { this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.mescaline), null, this.molecule(EnumMolecule.water, 5), null, this.molecule(EnumMolecule.water, 5) })); // Pumpkin ItemStack blockPumpkin = new ItemStack(Block.pumpkin); DecomposerRecipe.add(new DecomposerRecipe(blockPumpkin, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) })); SynthesisRecipe.add(new SynthesisRecipe(blockPumpkin, false, 400, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin) })); // Netherrack ItemStack blockNetherrack = new ItemStack(Block.netherrack); DecomposerRecipe.add(new DecomposerRecipeSelect(blockNetherrack, 0.1F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.Ni), this.element(EnumElement.Tc) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 3), this.element(EnumElement.Ti), this.element(EnumElement.Fe) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 1), this.element(EnumElement.W, 4), this.element(EnumElement.Cr, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 10), this.element(EnumElement.W, 1), this.element(EnumElement.Zn, 8), this.element(EnumElement.Be, 4) }) })); // Water Bottle ItemStack itemPotion = new ItemStack(Item.potion, 1, 0); DecomposerRecipe.add(new DecomposerRecipe(itemPotion, new Chemical[] { this.molecule(EnumMolecule.water, 8) })); // Soul Sand ItemStack blockSlowSand = new ItemStack(Block.slowSand); DecomposerRecipe.add(new DecomposerRecipeSelect(blockSlowSand, 0.2F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 3), this.element(EnumElement.Be, 1), this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Pb, 1), this.element(EnumElement.Si, 5), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 6), this.element(EnumElement.O, 2) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Es, 1), this.element(EnumElement.O, 2) }) })); // Glowstone ItemStack blockGlowStone = new ItemStack(Block.glowStone); DecomposerRecipe.add(new DecomposerRecipe(blockGlowStone, new Chemical[] { this.element(EnumElement.P, 4) })); SynthesisRecipe.add(new SynthesisRecipe(blockGlowStone, true, 500, new Chemical[] { this.element(EnumElement.P), null, this.element(EnumElement.P), this.element(EnumElement.P), null, this.element(EnumElement.P), null, null, null })); // Glass Panes ItemStack blockThinGlass = new ItemStack(Block.thinGlass); DecomposerRecipe .add(new DecomposerRecipe(blockThinGlass, new Chemical[] { this .molecule(EnumMolecule.siliconDioxide, 1) })); SynthesisRecipe.add(new SynthesisRecipe(blockThinGlass, true, 50, new Chemical[] { null, null, null, this.molecule(EnumMolecule.siliconDioxide), null, null, null, null, null })); // Melon ItemStack blockMelon = new ItemStack(Block.melon); DecomposerRecipe.add(new DecomposerRecipe(blockMelon, new Chemical[] { this.molecule(EnumMolecule.cucurbitacin), this.molecule(EnumMolecule.asparticAcid), this.molecule(EnumMolecule.water, 16) })); // Mycelium ItemStack blockMycelium = new ItemStack(Block.mycelium); DecomposerRecipe.add(new DecomposerRecipeChance(blockMycelium, 0.09F, new Chemical[] { this.molecule(EnumMolecule.fingolimod) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Block.mycelium, 16), false, 300, new Chemical[] { this .molecule(EnumMolecule.fingolimod) })); // End Stone ItemStack blockWhiteStone = new ItemStack(Block.whiteStone); DecomposerRecipe.add(new DecomposerRecipeSelect(blockWhiteStone, 0.8F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O), this.element(EnumElement.H, 4), this.element(EnumElement.Li) }), new DecomposerRecipe(new Chemical[] { this .element(EnumElement.Es) }), new DecomposerRecipe(new Chemical[] { this .element(EnumElement.Pu) }), new DecomposerRecipe(new Chemical[] { this .element(EnumElement.Fr) }), new DecomposerRecipe(new Chemical[] { this .element(EnumElement.Nd) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Si, 2), this.element(EnumElement.O, 4) }), new DecomposerRecipe(new Chemical[] { this.element( EnumElement.H, 4) }), new DecomposerRecipe(new Chemical[] { this.element( EnumElement.Be, 8) }), new DecomposerRecipe(new Chemical[] { this.element( EnumElement.Li, 2) }), new DecomposerRecipe(new Chemical[] { this .element(EnumElement.Zr) }), new DecomposerRecipe(new Chemical[] { this .element(EnumElement.Na) }), new DecomposerRecipe(new Chemical[] { this .element(EnumElement.Rb) }), new DecomposerRecipe(new Chemical[] { this.element(EnumElement.Ga), this.element(EnumElement.As) }) })); // Emerald Ore ItemStack blockOreEmerald = new ItemStack(Block.oreEmerald); DecomposerRecipe.add(new DecomposerRecipe(blockOreEmerald, new Chemical[] { this.molecule(EnumMolecule.beryl, 4), this.element(EnumElement.Cr, 4), this.element(EnumElement.V, 4) })); // Emerald Block ItemStack blockEmerald = new ItemStack(Block.blockEmerald); SynthesisRecipe.add(new SynthesisRecipe(blockEmerald, true, 150000, new Chemical[] { this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.V, 9), this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.V, 9), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3), this.element(EnumElement.Cr, 3) })); DecomposerRecipe.add(new DecomposerRecipe(blockEmerald, new Chemical[] { this.molecule(EnumMolecule.beryl, 18), this.element(EnumElement.Cr, 18), this.element(EnumElement.V, 18) })); // Section 2 - Items // Apple ItemStack itemAppleRed = new ItemStack(Item.appleRed); DecomposerRecipe.add(new DecomposerRecipe(itemAppleRed, new Chemical[] { this.molecule(EnumMolecule.malicAcid) })); SynthesisRecipe.add(new SynthesisRecipe(itemAppleRed, false, 400, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.molecule(EnumMolecule.water, 2) })); // Arrow ItemStack itemArrow = new ItemStack(Item.arrow); DecomposerRecipe.add(new DecomposerRecipe(itemArrow, new Chemical[] { this.element(EnumElement.Si), this.element(EnumElement.O, 2), this.element(EnumElement.N, 6) })); // Coal ItemStack itemCoal = new ItemStack(Item.coal); DecomposerRecipe.add(new DecomposerRecipe(itemCoal, new Chemical[] { this.element(EnumElement.C, 16) })); // Charcoal // Does 16 charcoal to 1 coal seem balanced? ItemStack itemChar = new ItemStack(Item.charcoal); DecomposerRecipe.add(new DecomposerRecipe(itemChar, new Chemical[] { this.element(EnumElement.C, 1) })); // Diamond ItemStack itemDiamond = new ItemStack(Item.diamond); DecomposerRecipe.add(new DecomposerRecipe(itemDiamond, new Chemical[] { this.molecule(EnumMolecule.fullrene, 4) })); SynthesisRecipe.add(new SynthesisRecipe(itemDiamond, true, '\uea60', new Chemical[] { null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null, this.molecule(EnumMolecule.fullrene), null })); // Iron Ingot ItemStack itemIngotIron = new ItemStack(Item.ingotIron); DecomposerRecipe.add(new DecomposerRecipe(itemIngotIron, new Chemical[] { this.element(EnumElement.Fe, 16) })); SynthesisRecipe.add(new SynthesisRecipe(itemIngotIron, false, 1000, new Chemical[] { this.element(EnumElement.Fe, 16) })); // Gold Ingot ItemStack itemIngotGold = new ItemStack(Item.ingotGold); DecomposerRecipe.add(new DecomposerRecipe(itemIngotGold, new Chemical[] { this.element(EnumElement.Au, 16) })); SynthesisRecipe.add(new SynthesisRecipe(itemIngotGold, false, 1000, new Chemical[] { this.element(EnumElement.Au, 16) })); // Stick ItemStack itemStick = new ItemStack(Item.stick); DecomposerRecipe.add(new DecomposerRecipeChance(itemStick, 0.3F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); // String ItemStack itemSilk = new ItemStack(Item.silk); DecomposerRecipe.add(new DecomposerRecipeChance(itemSilk, 0.45F, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) })); SynthesisRecipe.add(new SynthesisRecipe(itemSilk, true, 150, new Chemical[] { this.molecule(EnumMolecule.serine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.alinine) })); // Feather ItemStack itemFeather = new ItemStack(Item.feather); DecomposerRecipe.add(new DecomposerRecipe(itemFeather, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.N, 6) })); SynthesisRecipe.add(new SynthesisRecipe(itemFeather, true, 800, new Chemical[] { this.element(EnumElement.N), this.molecule(EnumMolecule.water, 2), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 1), this.element(EnumElement.N), this.element(EnumElement.N), this.molecule(EnumMolecule.water, 5), this.element(EnumElement.N) })); // Gunpowder ItemStack itemGunpowder = new ItemStack(Item.gunpowder); DecomposerRecipe.add(new DecomposerRecipe(itemGunpowder, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.S, 2), this.element(EnumElement.C) })); SynthesisRecipe.add(new SynthesisRecipe(itemGunpowder, true, 600, new Chemical[] { this.molecule(EnumMolecule.potassiumNitrate), this.element(EnumElement.C), null, this.element(EnumElement.S, 2), null, null, null, null, null })); // Bread ItemStack itemBread = new ItemStack(Item.bread); DecomposerRecipe.add(new DecomposerRecipeChance(itemBread, 0.1F, new Chemical[] { this.molecule(EnumMolecule.starch), this.molecule(EnumMolecule.sucrose) })); // Flint ItemStack itemFlint = new ItemStack(Item.flint); DecomposerRecipe.add(new DecomposerRecipeChance(itemFlint, 0.5F, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide) })); SynthesisRecipe.add(new SynthesisRecipe(itemFlint, true, 100, new Chemical[] { null, moleculeSiliconDioxide, null, moleculeSiliconDioxide, moleculeSiliconDioxide, moleculeSiliconDioxide, null, null, null })); // Golden Apple ItemStack itemAppleGold = new ItemStack(Item.appleGold, 1, 0); DecomposerRecipe.add(new DecomposerRecipe(itemAppleGold, new Chemical[] { this.molecule(EnumMolecule.malicAcid), this.element(EnumElement.Au, 64) })); // Wooden Door ItemStack itemDoorWood = new ItemStack(Item.doorWood); DecomposerRecipe.add(new DecomposerRecipeChance(itemDoorWood, 0.4F, new Chemical[] { this.molecule(EnumMolecule.cellulose, 12) })); // Water Bucket ItemStack itemBucketWater = new ItemStack(Item.bucketWater); DecomposerRecipe.add(new DecomposerRecipe(itemBucketWater, new Chemical[] { this.molecule(EnumMolecule.water, 16) })); // Redstone ItemStack itemRedstone = new ItemStack(Item.redstone); DecomposerRecipe.add(new DecomposerRecipeChance(itemRedstone, 0.42F, new Chemical[] { this.molecule(EnumMolecule.iron3oxide), this.element(EnumElement.Cu) })); SynthesisRecipe .add(new SynthesisRecipe(itemRedstone, true, 100, new Chemical[] { null, null, this.molecule(EnumMolecule.iron3oxide), null, this.element(EnumElement.Cu), null, null, null, null })); // Snowball ItemStack itemSnowball = new ItemStack(Item.snowball); DecomposerRecipe.add(new DecomposerRecipe(itemSnowball, new Chemical[] { this.molecule(EnumMolecule.water) })); SynthesisRecipe.add(new SynthesisRecipe( new ItemStack(Item.snowball, 5), true, 20, new Chemical[] { this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water), null, this.molecule(EnumMolecule.water) })); // Leather ItemStack itemLeather = new ItemStack(Item.leather); DecomposerRecipe.add(new DecomposerRecipeChance(itemLeather, 0.5F, new Chemical[] { this.molecule(EnumMolecule.arginine), this.molecule(EnumMolecule.glycine), this.molecule(EnumMolecule.keratin) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.leather, 5), true, 700, new Chemical[] { this.molecule(EnumMolecule.arginine), null, null, null, this.molecule(EnumMolecule.keratin), null, null, null, this.molecule(EnumMolecule.glycine) })); // Brick ItemStack itemBrick = new ItemStack(Item.brick); DecomposerRecipe.add(new DecomposerRecipeChance(itemBrick, 0.5F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.brick, 8), true, 400, new Chemical[] { this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null, this.molecule(EnumMolecule.kaolinite), this.molecule(EnumMolecule.kaolinite), null })); // Clay ItemStack itemClay = new ItemStack(Item.clay); DecomposerRecipe.add(new DecomposerRecipeChance(itemClay, 0.3F, new Chemical[] { this.molecule(EnumMolecule.kaolinite) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.clay, 12), false, 100, new Chemical[] { this .molecule(EnumMolecule.kaolinite) })); // Reed ItemStack itemReed = new ItemStack(Item.reed); DecomposerRecipe.add(new DecomposerRecipeChance(itemReed, 0.65F, new Chemical[] { this.molecule(EnumMolecule.sucrose), this.element(EnumElement.H, 2), this.element(EnumElement.O) })); // Paper ItemStack itemPaper = new ItemStack(Item.paper); DecomposerRecipe.add(new DecomposerRecipeChance(itemPaper, 0.25F, new Chemical[] { this.molecule(EnumMolecule.cellulose) })); SynthesisRecipe.add(new SynthesisRecipe(new ItemStack(Item.paper, 16), true, 150, new Chemical[] { null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null, null, this.molecule(EnumMolecule.cellulose), null })); // Slimeball ItemStack itemSlimeBall = new ItemStack(Item.slimeBall); DecomposerRecipe.add(new DecomposerRecipeSelect(itemSlimeBall, 0.9F, new DecomposerRecipe[] { new DecomposerRecipe(new Chemical[] { this .molecule(EnumMolecule.polycyanoacrylate) }), new DecomposerRecipe(new Chemical[] { this .element(EnumElement.Hg) }), new DecomposerRecipe(new Chemical[] { this.molecule( EnumMolecule.water, 10) }) })); // Glowstone Dust ItemStack itemGlowstone = new ItemStack(Item.glowstone); DecomposerRecipe.add(new DecomposerRecipe(itemGlowstone, new Chemical[] { this.element(EnumElement.P) })); // Dyes ItemStack itemDyePowderBlack = new ItemStack(Item.dyePowder, 1, 0); ItemStack itemDyePowderRed = new ItemStack(Item.dyePowder, 1, 1); ItemStack itemDyePowderGreen = new ItemStack(Item.dyePowder, 1, 2); ItemStack itemDyePowderBrown = new ItemStack(Item.dyePowder, 1, 3); ItemStack itemDyePowderBlue = new ItemStack(Item.dyePowder, 1, 4); ItemStack itemDyePowderPurple = new ItemStack(Item.dyePowder, 1, 5); ItemStack itemDyePowderCyan = new ItemStack(Item.dyePowder, 1, 6); ItemStack itemDyePowderLightGray = new ItemStack(Item.dyePowder, 1, 7); ItemStack itemDyePowderGray = new ItemStack(Item.dyePowder, 1, 8); ItemStack itemDyePowderPink = new ItemStack(Item.dyePowder, 1, 9); ItemStack itemDyePowderLime = new ItemStack(Item.dyePowder, 1, 10); ItemStack itemDyePowderYellow = new ItemStack(Item.dyePowder, 1, 11); ItemStack itemDyePowderLightBlue = new ItemStack(Item.dyePowder, 1, 12); ItemStack itemDyePowderMagenta = new ItemStack(Item.dyePowder, 1, 13); ItemStack itemDyePowderOrange = new ItemStack(Item.dyePowder, 1, 14); ItemStack itemDyePowderWhite = new ItemStack(Item.dyePowder, 1, 15); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderBlack, new Chemical[] { this.molecule(EnumMolecule.blackPigment) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderRed, new Chemical[] { this.molecule(EnumMolecule.redPigment) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderGreen, new Chemical[] { this.molecule(EnumMolecule.greenPigment) })); DecomposerRecipe.add(new DecomposerRecipeChance(itemDyePowderBrown, 0.4F, new Chemical[] { this.molecule(EnumMolecule.theobromine), this.molecule(EnumMolecule.tannicacid) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderBlue, new Chemical[] { this.molecule(EnumMolecule.lazurite) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderPurple, new Chemical[] { this.molecule(EnumMolecule.purplePigment) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderCyan, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderLightGray, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderGray, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderPink, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderLime, new Chemical[] { this.molecule(EnumMolecule.limePigment) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderYellow, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) })); DecomposerRecipe .add(new DecomposerRecipe(itemDyePowderLightBlue, new Chemical[] { this .molecule(EnumMolecule.lightbluePigment) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderMagenta, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderOrange, new Chemical[] { this.molecule(EnumMolecule.orangePigment) })); DecomposerRecipe.add(new DecomposerRecipe(itemDyePowderWhite, new Chemical[] { this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBlack, false, 50, new Chemical[] { this.molecule(EnumMolecule.blackPigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderRed, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderGreen, false, 50, new Chemical[] { this.molecule(EnumMolecule.greenPigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBrown, false, 400, new Chemical[] { this.molecule(EnumMolecule.theobromine) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderBlue, false, 50, new Chemical[] { this.molecule(EnumMolecule.lazurite) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderPurple, false, 50, new Chemical[] { this.molecule(EnumMolecule.purplePigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderCyan, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLightGray, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderGray, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment), this.molecule(EnumMolecule.blackPigment, 2) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderPink, false, 50, new Chemical[] { this.molecule(EnumMolecule.redPigment), this.molecule(EnumMolecule.whitePigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLime, false, 50, new Chemical[] { this.molecule(EnumMolecule.limePigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderYellow, false, 50, new Chemical[] { this.molecule(EnumMolecule.yellowPigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderLightBlue, false, 50, new Chemical[] { this .molecule(EnumMolecule.lightbluePigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderMagenta, false, 50, new Chemical[] { this.molecule(EnumMolecule.lightbluePigment), this.molecule(EnumMolecule.redPigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderOrange, false, 50, new Chemical[] { this.molecule(EnumMolecule.orangePigment) })); SynthesisRecipe.add(new SynthesisRecipe(itemDyePowderWhite, false, 50, new Chemical[] { this.molecule(EnumMolecule.whitePigment) })); // Bone ItemStack itemBone = new ItemStack(Item.bone); DecomposerRecipe .add(new DecomposerRecipe(itemBone, new Chemical[] { this .molecule(EnumMolecule.hydroxylapatite) })); SynthesisRecipe .add(new SynthesisRecipe(itemBone, false, 100, new Chemical[] { this .molecule(EnumMolecule.hydroxylapatite) })); // Sugar ItemStack itemSugar = new ItemStack(Item.sugar); DecomposerRecipe.add(new DecomposerRecipeChance(itemSugar, 0.75F, new Chemical[] { this.molecule(EnumMolecule.sucrose) })); SynthesisRecipe.add(new SynthesisRecipe(itemSugar, false, 400, new Chemical[] { this.molecule(EnumMolecule.sucrose) })); // Melon ItemStack itemMelon = new ItemStack(Item.melon); DecomposerRecipe.add(new DecomposerRecipe(itemMelon, new Chemical[] { this.molecule(EnumMolecule.water) })); // Cooked Chicken ItemStack itemChickenCooked = new ItemStack(Item.chickenCooked); DecomposerRecipe.add(new DecomposerRecipe(itemChickenCooked, new Chemical[] { this.element(EnumElement.K), this.element(EnumElement.Na), this.element(EnumElement.C, 2) })); SynthesisRecipe.add(new SynthesisRecipe(itemChickenCooked, true, 5000, new Chemical[] { this.element(EnumElement.K, 16), this.element(EnumElement.Na, 16), this.element(EnumElement.C, 16) })); // Rotten Flesh ItemStack itemRottenFlesh = new ItemStack(Item.rottenFlesh); DecomposerRecipe.add(new DecomposerRecipeChance(itemRottenFlesh, 0.05F, new Chemical[] { new Molecule(EnumMolecule.nod, 1) })); // Enderpearl ItemStack itemEnderPearl = new ItemStack(Item.enderPearl); DecomposerRecipe.add(new DecomposerRecipe(itemEnderPearl, new Chemical[] { this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate, 8) })); SynthesisRecipe.add(new SynthesisRecipe(itemEnderPearl, true, 5000, new Chemical[] { this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.element(EnumElement.Es), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate), this.molecule(EnumMolecule.calciumCarbonate) })); // Blaze Rod ItemStack itemBlazeRod = new ItemStack(Item.blazeRod); DecomposerRecipe.add(new DecomposerRecipe(itemBlazeRod, new Chemical[] { this.element(EnumElement.Pu, 3) })); SynthesisRecipe.add(new SynthesisRecipe(itemBlazeRod, true, 15000, new Chemical[] { this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null, this.element(EnumElement.Pu), null, null })); // Ghast Tear ItemStack itemGhastTear = new ItemStack(Item.ghastTear); DecomposerRecipe.add(new DecomposerRecipe(itemGhastTear, new Chemical[] { this.element(EnumElement.Yb, 4), this.element(EnumElement.No, 4) })); SynthesisRecipe.add(new SynthesisRecipe(itemGhastTear, true, 15000, new Chemical[] { this.element(EnumElement.Yb), this.element(EnumElement.Yb), this.element(EnumElement.No), null, this.element(EnumElement.Yb, 2), this.element(EnumElement.No, 2), null, this.element(EnumElement.No), null })); // Nether Wart ItemStack itemNetherStalkSeeds = new ItemStack(Item.netherStalkSeeds); DecomposerRecipe.add(new DecomposerRecipeChance(itemNetherStalkSeeds, 0.5F, new Chemical[] { this.molecule(EnumMolecule.coke) })); // Spider Eye ItemStack itemSpiderEye = new ItemStack(Item.spiderEye); DecomposerRecipe.add(new DecomposerRecipeChance(itemSpiderEye, 0.2F, new Chemical[] { this.molecule(EnumMolecule.ttx) })); SynthesisRecipe.add(new SynthesisRecipe(itemSpiderEye, true, 2000, new Chemical[] { this.element(EnumElement.C), null, null, null, this.molecule(EnumMolecule.ttx), null, null, null, this.element(EnumElement.C) })); // Fermented Spider Eye ItemStack itemFermentedSpiderEye = new ItemStack( Item.fermentedSpiderEye); DecomposerRecipe.add(new DecomposerRecipe(itemFermentedSpiderEye, new Chemical[] { this.element(EnumElement.Po), this.molecule(EnumMolecule.ethanol) })); // Blaze Powder ItemStack itemBlazePowder = new ItemStack(Item.blazePowder); DecomposerRecipe.add(new DecomposerRecipe(itemBlazePowder, new Chemical[] { this.element(EnumElement.Pu) })); // Magma Cream ItemStack itemMagmaCream = new ItemStack(Item.magmaCream); DecomposerRecipe.add(new DecomposerRecipe(itemMagmaCream, new Chemical[] { this.element(EnumElement.Hg), this.element(EnumElement.Pu), this.molecule(EnumMolecule.polycyanoacrylate, 3) })); SynthesisRecipe.add(new SynthesisRecipe(itemMagmaCream, true, 5000, new Chemical[] { null, this.element(EnumElement.Pu), null, this.molecule(EnumMolecule.polycyanoacrylate), this.element(EnumElement.Hg), this.molecule(EnumMolecule.polycyanoacrylate), null, this.molecule(EnumMolecule.polycyanoacrylate), null })); // Glistering Melon ItemStack itemSpeckledMelon = new ItemStack(Item.speckledMelon); DecomposerRecipe.add(new DecomposerRecipe(itemSpeckledMelon, new Chemical[] { this.molecule(EnumMolecule.water, 4), this.molecule(EnumMolecule.whitePigment), this.element(EnumElement.Au, 1) })); // Emerald ItemStack itemEmerald = new ItemStack(Item.emerald); DecomposerRecipe.add(new DecomposerRecipe(itemEmerald, new Chemical[] { this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.Cr, 2), this.element(EnumElement.V, 2) })); SynthesisRecipe.add(new SynthesisRecipe(itemEmerald, true, 80000, new Chemical[] { null, this.element(EnumElement.Cr), null, this.element(EnumElement.V), this.molecule(EnumMolecule.beryl, 2), this.element(EnumElement.V), null, this.element(EnumElement.Cr), null })); // Carrot ItemStack itemCarrot = new ItemStack(Item.carrot); DecomposerRecipe.add(new DecomposerRecipe(itemCarrot, new Chemical[] { this.molecule(EnumMolecule.ret) })); // Potato ItemStack itemPotato = new ItemStack(Item.potato); DecomposerRecipe.add(new DecomposerRecipeChance(itemPotato, 0.4F, new Chemical[] { this.molecule(EnumMolecule.water, 8), this.element(EnumElement.K, 2), this.molecule(EnumMolecule.cellulose) })); // Golden Carrot ItemStack itemGoldenCarrot = new ItemStack(Item.goldenCarrot); DecomposerRecipe.add(new DecomposerRecipe(itemGoldenCarrot, new Chemical[] { this.molecule(EnumMolecule.ret), this.element(EnumElement.Au, 4) })); // Nether Star ItemStack itemNetherStar = new ItemStack(Item.netherStar); DecomposerRecipe.add(new DecomposerRecipe(itemNetherStar, new Chemical[] { this.element(EnumElement.Cn, 16), elementHydrogen, elementHydrogen, elementHydrogen, elementHelium, elementHelium, elementHelium, elementCarbon, elementCarbon })); SynthesisRecipe.add(new SynthesisRecipe(itemNetherStar, true, 500000, new Chemical[] { elementHelium, elementHelium, elementHelium, elementCarbon, this.element(EnumElement.Cn, 16), elementHelium, elementHydrogen, elementHydrogen, elementHydrogen })); // Nether Quartz ItemStack itemNetherQuartz = new ItemStack(Item.netherQuartz); DecomposerRecipe.add(new DecomposerRecipe(itemNetherQuartz, new Chemical[] { this.molecule(EnumMolecule.siliconDioxide, 4), this.molecule(EnumMolecule.galliumarsenide, 1) })); // Music Records ItemStack itemRecord13 = new ItemStack(Item.record13); ItemStack itemRecordCat = new ItemStack(Item.recordCat); ItemStack itemRecordFar = new ItemStack(Item.recordFar); ItemStack itemRecordMall = new ItemStack(Item.recordMall); ItemStack itemRecordMellohi = new ItemStack(Item.recordMellohi); ItemStack itemRecordStal = new ItemStack(Item.recordStal); ItemStack itemRecordStrad = new ItemStack(Item.recordStrad); ItemStack itemRecordWard = new ItemStack(Item.recordWard); ItemStack itemRecordChirp = new ItemStack(Item.recordChirp); DecomposerRecipe.add(new DecomposerRecipe(itemRecord13, new Chemical[] { moleculePolyvinylChloride })); DecomposerRecipe.add(new DecomposerRecipe(itemRecordCat, new Chemical[] { moleculePolyvinylChloride })); DecomposerRecipe.add(new DecomposerRecipe(itemRecordFar, new Chemical[] { moleculePolyvinylChloride })); DecomposerRecipe.add(new DecomposerRecipe(itemRecordMall, new Chemical[] { moleculePolyvinylChloride })); DecomposerRecipe.add(new DecomposerRecipe(itemRecordMellohi, new Chemical[] { moleculePolyvinylChloride })); DecomposerRecipe.add(new DecomposerRecipe(itemRecordStal, new Chemical[] { moleculePolyvinylChloride })); DecomposerRecipe.add(new DecomposerRecipe(itemRecordStrad, new Chemical[] { moleculePolyvinylChloride })); DecomposerRecipe.add(new DecomposerRecipe(itemRecordWard, new Chemical[] { moleculePolyvinylChloride })); DecomposerRecipe.add(new DecomposerRecipe(itemRecordChirp, new Chemical[] { moleculePolyvinylChloride })); SynthesisRecipe.add(new SynthesisRecipe(itemRecord13, true, 1000, new Chemical[] { moleculePolyvinylChloride, null, null, null, null, null, null, null, null })); SynthesisRecipe.add(new SynthesisRecipe(itemRecordCat, true, 1000, new Chemical[] { null, moleculePolyvinylChloride, null, null, null, null, null, null, null })); SynthesisRecipe.add(new SynthesisRecipe(itemRecordFar, true, 1000, new Chemical[] { null, null, moleculePolyvinylChloride, null, null, null, null, null, null })); SynthesisRecipe.add(new SynthesisRecipe(itemRecordMall, true, 1000, new Chemical[] { null, null, null, moleculePolyvinylChloride, null, null, null, null, null })); SynthesisRecipe.add(new SynthesisRecipe(itemRecordMellohi, true, 1000, new Chemical[] { null, null, null, null, moleculePolyvinylChloride, null, null, null, null })); SynthesisRecipe.add(new SynthesisRecipe(itemRecordStal, true, 1000, new Chemical[] { null, null, null, null, null, moleculePolyvinylChloride, null, null, null })); SynthesisRecipe.add(new SynthesisRecipe(itemRecordStrad, true, 1000, new Chemical[] { null, null, null, null, null, null, moleculePolyvinylChloride, null, null })); SynthesisRecipe.add(new SynthesisRecipe(itemRecordWard, true, 1000, new Chemical[] { null, null, null, null, null, null, null, moleculePolyvinylChloride, null })); SynthesisRecipe.add(new SynthesisRecipe(itemRecordChirp, true, 1000, new Chemical[] { null, null, null, null, null, null, null, null, moleculePolyvinylChloride })); } public void RegisterRecipes() { this.registerVanillaChemicalRecipes(); ItemStack blockGlass = new ItemStack(Block.glass); ItemStack blockThinGlass = new ItemStack(Block.thinGlass); ItemStack blockIron = new ItemStack(Block.blockIron); ItemStack itemIngotIron = new ItemStack(Item.ingotIron); ItemStack itemRedstone = new ItemStack(Item.redstone); ItemStack minechemItemsAtomicManipulator = new ItemStack(MinechemItems.atomicManipulator); ItemStack mineChemItemsTestTube = new ItemStack(MinechemItems.testTube, 16); ItemStack moleculePolyvinylChloride = new ItemStack(MinechemItems.molecule, 1, EnumMolecule.polyvinylChloride.ordinal()); GameRegistry.addRecipe(mineChemItemsTestTube, new Object[] { " G ", " G ", " G ", Character.valueOf('G'), blockGlass }); GameRegistry.addRecipe(MinechemItems.concaveLens, new Object[] { "G G", "GGG", "G G", Character.valueOf('G'), blockGlass }); GameRegistry.addRecipe(MinechemItems.convexLens, new Object[] { " G ", "GGG", " G ", Character.valueOf('G'), blockGlass }); GameRegistry.addRecipe(MinechemItems.microscopeLens, new Object[] { "A", "B", "A", Character.valueOf('A'), MinechemItems.convexLens, Character.valueOf('B'), MinechemItems.concaveLens }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.microscope), new Object[] { " LI", " PI", "III", Character.valueOf('L'), MinechemItems.microscopeLens, Character.valueOf('P'), blockThinGlass, Character.valueOf('I'), itemIngotIron }); GameRegistry.addRecipe(new ItemStack(MinechemItems.atomicManipulator), new Object[] { "PPP", "PIP", "PPP", Character.valueOf('P'), new ItemStack(Block.pistonBase), Character.valueOf('I'), blockIron }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.decomposer), new Object[] { "III", "IAI", "IRI", Character.valueOf('A'), minechemItemsAtomicManipulator, Character.valueOf('I'), itemIngotIron, Character.valueOf('R'), itemRedstone }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.synthesis), new Object[] { "IRI", "IAI", "IDI", Character.valueOf('A'), minechemItemsAtomicManipulator, Character.valueOf('I'), itemIngotIron, Character.valueOf('R'), itemRedstone, Character.valueOf('D'), new ItemStack(Item.diamond) }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 0), new Object[] { "ILI", "ILI", "ILI", Character.valueOf('I'), itemIngotIron, Character.valueOf('L'), ItemElement.createStackOf(EnumElement.Pb, 1) }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.fusion, 16, 1), new Object[] { "IWI", "IBI", "IWI", Character.valueOf('I'), itemIngotIron, Character.valueOf('W'), ItemElement.createStackOf(EnumElement.W, 1), Character.valueOf('B'), ItemElement.createStackOf(EnumElement.Be, 1) }); GameRegistry.addRecipe(MinechemItems.projectorLens, new Object[] { "ABA", Character.valueOf('A'), MinechemItems.concaveLens, Character.valueOf('B'), MinechemItems.convexLens }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.blueprintProjector), new Object[] { " I ", "GPL", " I ", Character.valueOf('I'), itemIngotIron, Character.valueOf('P'), blockThinGlass, Character.valueOf('L'), MinechemItems.projectorLens, Character.valueOf('G'), new ItemStack(Block.redstoneLampIdle) }); GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatFeet), new Object[] { " ", "P P", "P P", Character.valueOf('P'), moleculePolyvinylChloride }); GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatLegs), new Object[] { "PPP", "P P", "P P", Character.valueOf('P'), moleculePolyvinylChloride }); GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatTorso), new Object[] { " P ", "PPP", "PPP", Character.valueOf('P'), moleculePolyvinylChloride }); GameRegistry.addRecipe(new ItemStack(MinechemItems.hazmatHead), new Object[] { "PPP", "P P", " ", Character.valueOf('P'), moleculePolyvinylChloride }); GameRegistry.addRecipe(new ItemStack(MinechemBlocks.chemicalStorage), new Object[] { "LLL", "LCL", "LLL", Character.valueOf('L'), new ItemStack(MinechemItems.element, 1, EnumElement.Pb.ordinal()), Character.valueOf('C'), new ItemStack(Block.chest) }); GameRegistry.addRecipe(new ItemStack(MinechemItems.IAintAvinit), new Object[] { "ZZZ", "ZSZ", " S ", Character.valueOf('Z'), new ItemStack(Item.ingotIron), Character.valueOf('S'), new ItemStack(Item.stick) }); GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.journal), new Object[] { new ItemStack(Item.book), new ItemStack(MinechemItems.testTube) }); GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.EmptyPillz,4), new Object[] { new ItemStack(Item.sugar), new ItemStack(Item.slimeBall), new ItemStack(Item.slimeBall) }); //Fusion GameRegistry.addShapelessRecipe(ItemBlueprint.createItemStackFromBlueprint(MinechemBlueprint.fusion), new Object[] { new ItemStack(Item.paper), new ItemStack(Block.blockDiamond)}); //Fission GameRegistry.addShapelessRecipe(ItemBlueprint.createItemStackFromBlueprint(MinechemBlueprint.fission), new Object[] { new ItemStack(Item.paper), new ItemStack(Item.diamond)}); for (EnumElement element : EnumElement.values()) { GameRegistry.addShapelessRecipe(new ItemStack(MinechemItems.testTube), new Object[] { new ItemStack(MinechemItems.element, element.ordinal()) }); } GameRegistry.addRecipe(new RecipeJournalCloning()); DecomposerRecipe.add(new DecomposerRecipe(new ItemStack(MinechemBlocks.uranium), new Chemical[] { this.element(EnumElement.U, 32) })); this.addDecomposerRecipesFromMolecules(); this.addSynthesisRecipesFromMolecules(); this.addUnusedSynthesisRecipes(); this.registerPoisonRecipes(EnumMolecule.poison); this.registerPoisonRecipes(EnumMolecule.sucrose); this.registerPoisonRecipes(EnumMolecule.psilocybin); this.registerPoisonRecipes(EnumMolecule.methamphetamine); this.registerPoisonRecipes(EnumMolecule.amphetamine); this.registerPoisonRecipes(EnumMolecule.pantherine); this.registerPoisonRecipes(EnumMolecule.ethanol); this.registerPoisonRecipes(EnumMolecule.penicillin); this.registerPoisonRecipes(EnumMolecule.testosterone); this.registerPoisonRecipes(EnumMolecule.xanax); this.registerPoisonRecipes(EnumMolecule.mescaline); this.registerPoisonRecipes(EnumMolecule.asprin); this.registerPoisonRecipes(EnumMolecule.sulfuricAcid); this.registerPoisonRecipes(EnumMolecule.ttx); this.registerPoisonRecipes(EnumMolecule.pal2); this.registerPoisonRecipes(EnumMolecule.nod); this.registerPoisonRecipes(EnumMolecule.afroman); this.registerPoisonRecipes(EnumMolecule.radchlor); // Whoa, oh, oh, oh, I'm radioactive, radioactive this.registerPoisonRecipes(EnumMolecule.redrocks); this.registerPoisonRecipes(EnumMolecule.coke); this.registerPoisonRecipes(EnumMolecule.theobromine); } private void addDecomposerRecipesFromMolecules() { EnumMolecule[] var1 = EnumMolecule.molecules; int var2 = var1.length; for (int var3 = 0; var3 < var2; ++var3) { EnumMolecule var4 = var1[var3]; ArrayList var5 = var4.components(); Chemical[] var6 = (Chemical[]) var5.toArray(new Chemical[var5.size()]); ItemStack var7 = new ItemStack(MinechemItems.molecule, 1, var4.id()); DecomposerRecipe.add(new DecomposerRecipe(var7, var6)); } } private void addSynthesisRecipesFromMolecules() { EnumMolecule[] var1 = EnumMolecule.molecules; int var2 = var1.length; for (int var3 = 0; var3 < var2; ++var3) { EnumMolecule var4 = var1[var3]; ArrayList var5 = var4.components(); ItemStack var6 = new ItemStack(MinechemItems.molecule, 1, var4.id()); SynthesisRecipe.add(new SynthesisRecipe(var6, false, 50, var5)); } } private void addUnusedSynthesisRecipes() { Iterator var1 = DecomposerRecipe.recipes.iterator(); while (var1.hasNext()) { DecomposerRecipe var2 = (DecomposerRecipe) var1.next(); if (var2.getInput().getItemDamage() != -1) { boolean var3 = false; Iterator var4 = SynthesisRecipe.recipes.iterator(); //What kind of crappy code is this? //I've got to fix it.....If I can figure out what it does while (true) { if (var4.hasNext()) { SynthesisRecipe var5 = (SynthesisRecipe) var4.next(); if (!Util.stacksAreSameKind(var5.getOutput(), var2.getInput())) { continue; } var3 = true; } if (!var3) { ArrayList var6 = var2.getOutputRaw(); if (var6 != null) { SynthesisRecipe.add(new SynthesisRecipe(var2.getInput(), false, 100, var6)); } } break; } } } } private ItemStack createPoisonedItemStack(Item var1, int var2, EnumMolecule var3) { ItemStack var4 = new ItemStack(MinechemItems.molecule, 1, var3.id()); ItemStack var5 = new ItemStack(var1, 1, var2); ItemStack var6 = new ItemStack(var1, 1, var2); NBTTagCompound var7 = new NBTTagCompound(); var7.setBoolean("minechem.isPoisoned", true); var7.setInteger("minechem.effectType", var3.id()); var6.setTagCompound(var7); GameRegistry.addShapelessRecipe(var6, new Object[]{var4, var5}); return var6; } private void registerPoisonRecipes(EnumMolecule molecule) { for(Item i: Item.itemsList) { // Thanks Adrian! if(i != null && i instanceof ItemFood) { // Should allow for lacing of BOP and AquaCulture foodstuffs. this.createPoisonedItemStack(i, 0, molecule); } } } /* * This stuff is unused and is replaced by ljdp.minechem.common.recipe.handlers.DefaultOreDictionaryHandler String[] compounds = {"Aluminium","Titanium","Chrome", "Tungsten", "Lead", "Zinc", "Platinum", "Nickel", "Osmium", "Iron", "Gold", "Coal", "Copper", "Tin", "Silver", "RefinedIron", "Steel", "Bronze", "Brass", "Electrum", "Invar"};//,"Iridium"}; EnumElement[][] elements = {{EnumElement.Al}, {EnumElement.Ti}, {EnumElement.Cr}, {EnumElement.W}, {EnumElement.Pb}, {EnumElement.Zn}, {EnumElement.Pt}, {EnumElement.Ni}, {EnumElement.Os}, {EnumElement.Fe}, {EnumElement.Au}, {EnumElement.C}, {EnumElement.Cu}, {EnumElement.Sn}, {EnumElement.Ag}, {EnumElement.Fe}, {EnumElement.Fe, EnumElement.C}, //Steel {EnumElement.Sn, EnumElement.Cu}, {EnumElement.Cu},//Bronze {EnumElement.Zn, EnumElement.Cu}, //Brass {EnumElement.Ag, EnumElement.Au}, //Electrum {EnumElement.Fe, EnumElement.Ni} //Invar };//, EnumElement.Ir int[][] proportions = {{4},{4},{4}, {4},{4},{4}, {4},{4},{4}, {4},{4},{4}, {4},{4},{4}, {4}, {4,4}, {1,3},{1,3},{2,2},{2,1}}; String[] itemTypes = {"dustSmall", "dust", "ore" , "ingot", "block", "gear", "plate"}; //"nugget", "plate" boolean[] craftable = {true, true, false, false, false, false, false}; int[] sizeCoeff = {1, 4, 8, 4, 36, 16, 4}; */ private ArrayList<OreDictionaryHandler> oreDictionaryHandlers; @ForgeSubscribe public void oreEvent(OreDictionary.OreRegisterEvent var1) { if (var1.Name.contains("gemApatite")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Ca, 5), this.molecule(EnumMolecule.phosphate, 4), this.element(EnumElement.Cl) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.element(EnumElement.Ca, 5), this.molecule(EnumMolecule.phosphate, 4), this.element(EnumElement.Cl) })); } else if (var1.Name.contains("Ruby")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr) })); } else if (var1.Name.contains("Sapphire")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.molecule(EnumMolecule.aluminiumOxide, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.molecule(EnumMolecule.aluminiumOxide, 2) })); } else if (var1.Name.contains("ingotBronze")) { if (Loader.isModLoaded("Mekanism")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Cu, 16), this.element(EnumElement.Sn, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.element(EnumElement.Cu, 16), this.element(EnumElement.Sn, 2) })); } else { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Cu, 24), this.element(EnumElement.Sn, 8) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.element(EnumElement.Cu, 24), this.element(EnumElement.Sn, 8) })); } } else if (var1.Name.contains("plateSilicon")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Si, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.element(EnumElement.Si, 2) })); } else if (var1.Name.contains("xychoriumBlue")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Zr, 2), this.element(EnumElement.Cu, 1) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[] { this.element(EnumElement.Zr, 2), this.element(EnumElement.Cu, 1) })); } else if (var1.Name.contains("xychoriumRed")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Zr, 2), this.element(EnumElement.Fe, 1) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[] { this.element(EnumElement.Zr, 2), this.element(EnumElement.Fe, 1) })); } else if (var1.Name.contains("xychoriumGreen")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Zr, 2), this.element(EnumElement.V, 1) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[] { this.element(EnumElement.Zr, 2), this.element(EnumElement.V, 1) })); } else if (var1.Name.contains("xychoriumDark")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Zr, 2), this.element(EnumElement.Si, 1) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[] { this.element(EnumElement.Zr, 2), this.element(EnumElement.Si, 1) })); } else if (var1.Name.contains("xychoriumLight")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Zr, 2), this.element(EnumElement.Ti, 1) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 300, new Chemical[] { this.element(EnumElement.Zr, 2), this.element(EnumElement.Ti, 1) })); } else if (var1.Name.contains("ingotCobalt")) { // Tungsten - Cobalt // Alloy DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Co, 2), this.element(EnumElement.W, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[] { this.element(EnumElement.Co, 2), this.element(EnumElement.W, 2) })); } else if (var1.Name.contains("ingotArdite")) { // Tungsten - Iron - // Silicon Alloy DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 5000, new Chemical[] { this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2) })); } else if (var1.Name.contains("ingotManyullyn")) { // Tungsten - Iron - // Silicon - Cobalt // Alloy DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2), this.element(EnumElement.Co, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 7000, new Chemical[] { this.element(EnumElement.Fe, 2), this.element(EnumElement.W, 2), this.element(EnumElement.Si, 2), this.element(EnumElement.Co, 2) })); } else if (var1.Name.contains("gemRuby")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.molecule(EnumMolecule.aluminiumOxide), this.element(EnumElement.Cr) })); } else if (var1.Name.contains("gemSapphire")) { DecomposerRecipe .add(new DecomposerRecipe(var1.Ore, new Chemical[] { this .molecule(EnumMolecule.aluminiumOxide) })); SynthesisRecipe .add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this .molecule(EnumMolecule.aluminiumOxide) })); } else if (var1.Name.contains("gemPeridot")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.molecule(EnumMolecule.olivine) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.molecule(EnumMolecule.olivine) })); } else if (var1.Name.contains("cropMaloberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.molecule(EnumMolecule.stevenk), this.molecule(EnumMolecule.sucrose) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.molecule(EnumMolecule.stevenk), this.molecule(EnumMolecule.sucrose) })); } else if (var1.Name.contains("cropDuskberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.molecule(EnumMolecule.psilocybin), this.element(EnumElement.S, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.molecule(EnumMolecule.psilocybin), this.element(EnumElement.S, 2) })); } else if (var1.Name.contains("cropSkyberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.molecule(EnumMolecule.theobromine), this.element(EnumElement.S, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.molecule(EnumMolecule.theobromine), this.element(EnumElement.S, 2) })); } else if (var1.Name.contains("cropBlightberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.molecule(EnumMolecule.asprin), this.element(EnumElement.S, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.molecule(EnumMolecule.asprin), this.element(EnumElement.S, 2) })); } else if (var1.Name.contains("cropBlueberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.molecule(EnumMolecule.blueorgodye), this.molecule(EnumMolecule.sucrose, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.molecule(EnumMolecule.blueorgodye), this.molecule(EnumMolecule.sucrose, 2) })); } else if (var1.Name.contains("cropRaspberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.molecule(EnumMolecule.redorgodye), this.molecule(EnumMolecule.sucrose, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.molecule(EnumMolecule.redorgodye), this.molecule(EnumMolecule.sucrose, 2) })); } else if (var1.Name.contains("cropBlackberry")) { DecomposerRecipe.add(new DecomposerRecipe(var1.Ore, new Chemical[] { this.molecule(EnumMolecule.purpleorgodye), this.molecule(EnumMolecule.sucrose, 2) })); SynthesisRecipe.add(new SynthesisRecipe(var1.Ore, false, 1000, new Chemical[] { this.molecule(EnumMolecule.purpleorgodye), this.molecule(EnumMolecule.sucrose, 2) })); } else { for (OreDictionaryHandler handler : this.oreDictionaryHandlers) { if (handler.canHandle(var1)) { handler.handle(var1); return; } } } } // END // BEGIN MISC FUNCTIONS private Element element(EnumElement var1, int var2) { return new Element(var1, var2); } private Element element(EnumElement var1) { return new Element(var1, 1); } private Molecule molecule(EnumMolecule var1, int var2) { return new Molecule(var1, var2); } private Molecule molecule(EnumMolecule var1) { return new Molecule(var1, 1); } // END public void RegisterHandlers() { this.oreDictionaryHandlers = new ArrayList<OreDictionaryHandler>(); if (Loader.isModLoaded("Mekanism")) this.oreDictionaryHandlers.add(new MekanismOreDictionaryHandler()); if (Loader.isModLoaded("UndergroundBiomes")) this.oreDictionaryHandlers.add(new UndergroundBiomesOreDictionaryHandler()); if (Loader.isModLoaded("gregtech_addon")) this.oreDictionaryHandlers.add(new GregTechOreDictionaryHandler()); if (Loader.isModLoaded("IC2")) this.oreDictionaryHandlers.add(new IC2OreDictionaryHandler()); if (Loader.isModLoaded("AppliedEnergistics")) this.oreDictionaryHandlers.add(new AppliedEnergisticsOreDictionaryHandler()); this.oreDictionaryHandlers.add(new DefaultOreDictionaryHandler()); } } // EOF
package de.mrapp.android.adapter.list; import static de.mrapp.android.adapter.util.Condition.ensureAtLeast; import static de.mrapp.android.adapter.util.Condition.ensureAtMaximum; import static de.mrapp.android.adapter.util.Condition.ensureNotNull; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Set; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import de.mrapp.android.adapter.ListAdapter; import de.mrapp.android.adapter.datastructure.SerializableWrapper; import de.mrapp.android.adapter.datastructure.item.Item; import de.mrapp.android.adapter.datastructure.item.ItemIterator; import de.mrapp.android.adapter.datastructure.item.ItemListIterator; import de.mrapp.android.adapter.inflater.Inflater; import de.mrapp.android.adapter.logging.LogLevel; import de.mrapp.android.adapter.logging.Logger; import de.mrapp.android.adapter.util.VisibleForTesting; /** * An abstract base class for all adapters, whose underlying data is managed as * a list of arbitrary items. Such an adapter's purpose is to provide the * underlying data for visualization using a {@link ListView} widget. * * @param <DataType> * The type of the adapter's underlying data * @param <DecoratorType> * The type of the decorator, which allows to customize the * appearance of the views, which are used to visualize the items of * the adapter * * @author Michael Rapp * * @since 1.0.0 */ public abstract class AbstractListAdapter<DataType, DecoratorType> extends BaseAdapter implements ListAdapter<DataType> { /** * The constant serial version UID. */ private static final long serialVersionUID = 1L; /** * The key, which is used to store the adapter's underlying data within a * bundle. */ @VisibleForTesting protected static final String ITEMS_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::Items"; /** * The key, which is used to store, whether duplicate items should be * allowed, or not, within a bundle. */ @VisibleForTesting protected static final String ALLOW_DUPLICATES_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::AllowDuplicates"; /** * The key, which is used to store the log level, which is used for logging, * within a bundle. */ @VisibleForTesting protected static final String LOG_LEVEL_BUNDLE_KEY = AbstractListAdapter.class .getSimpleName() + "::LogLevel"; /** * The context, the adapter belongs to. */ private final transient Context context; /** * The inflater, which is used to inflate the views, which are used to * visualize the adapter's items. */ private final transient Inflater inflater; /** * The decorator, which allows to customize the appearance of the views, * which are used to visualize the items of the adapter. */ private final transient DecoratorType decorator; /** * The logger, which is used for logging. */ private final transient Logger logger; /** * A set, which contains the listeners, which should be notified, when the * adapter's underlying data has been modified. */ private transient Set<ListAdapterListener<DataType>> adapterListeners; /** * True, if duplicate items are allowed, false otherwise. */ private boolean allowDuplicates; /** * A list, which contains the the adapter's underlying data. */ private List<Item<DataType>> items; /** * Notifies all listeners, which have been registered to be notified, when * the adapter's underlying data has been modified, about an item, which has * been added to the adapter. * * @param item * The item, which has been added to the adapter, as an instance * of the generic type DataType. The item may not be null * @param index * The index of the item, which has been added to the adapter, as * an {@link Integer} value. The index must be between 0 and the * value of the method <code>getNumberOfItems():int</code> - 1 */ private void notifyOnItemAdded(final DataType item, final int index) { for (ListAdapterListener<DataType> listener : adapterListeners) { listener.onItemAdded(this, item, index); } } /** * Notifies all listeners, which have been registered to be notified, when * the adapter's underlying data has been modified, about an item, which has * been removed from the adapter. * * @param item * The item, which has been removed from the adapter, as an * instance of the generic type DataType. The item may not be * null * @param index * The index of the item, which has been removed from the * adapter, as an {@link Integer} value. The index must be * between 0 and the value of the method * <code>getNumberOfItems():int</code> */ private void notifyOnItemRemoved(final DataType item, final int index) { for (ListAdapterListener<DataType> listener : adapterListeners) { listener.onItemRemoved(this, item, index); } } /** * Creates and returns an {@link OnClickListener}, which is invoked, when a * specific item has been clicked. * * @param index * The index of the item, which should cause the listener to be * invoked, when clicked, as an {@link Integer} value * @return The listener, which has been created as an instance of the type * {@link OnClickListener} */ private OnClickListener createItemOnClickListener(final int index) { return new OnClickListener() { @Override public void onClick(final View v) { onItemClicked(index); } }; } /** * Returns, whether the adapter's underlying data implements the interface * {@link Serializable}, or not. * * @return True, if the adapter's underlying data implements the interface * {@link Serializable}, false otherwise */ private boolean isUnderlyingDataSerializable() { if (!isEmpty()) { if (!Serializable.class.isAssignableFrom(getItem(0).getClass())) { return false; } } return true; } /** * Returns, the context, the adapter belongs to. * * @return The context, the adapter belongs to, as an instance of the class * {@link Context}. The context may not be null */ protected final Context getContext() { return context; } /** * Returns the inflater, which is used to inflate the views, which are used * to visualize the adapter's items. * * @return The inflater, which is used to inflate views, which are used to * visualize the adapter's items, as an instance of the type * {@link Inflater}. The inflater may not be null */ protected final Inflater getInflater() { return inflater; } /** * Returns the decorator, which allows to customize the appearance of the * views, which are used to visualize the items of the adapter. * * @return The decorator, which allows to customize the appearance of the * views, which are used to visualize the items of the adapter, as * an instance of the generic type DecoratorType. The decorator may * not be null */ protected final DecoratorType getDecorator() { return decorator; } /** * Returns the logger, which is used for logging. * * @return The logger, which is used for logging, as an instance of the * class {@link Logger}. The logger may not be null */ protected final Logger getLogger() { return logger; } /** * Returns a list, which contains the adapter's underlying data. * * @return A list, which contains the adapters underlying data, as an * instance of the type {@link List} or an empty list, if the * adapter does not contain any data */ protected final List<Item<DataType>> getItems() { return items; } /** * Sets the list, which contains the adapter's underlying data. * * @param items * The list, which should be set, as an instance of the type * {@link List} or an empty list, if the adapter should not * contain any data */ protected final void setItems(final List<Item<DataType>> items) { ensureNotNull(items, "The items may not be null"); this.items = items; } /** * Creates and returns a deep copy of the list, which contains the adapter's * underlying data. * * @return A deep copy of the list, which contains the adapter's underlying * data, as an instance of the type {@link List}. The list may not * be null * @throws CloneNotSupportedException * The exception, which is thrown, if cloning is not supported * by the adapter's underlying data */ protected final List<Item<DataType>> cloneItems() throws CloneNotSupportedException { List<Item<DataType>> clonedItems = new ArrayList<Item<DataType>>(); for (Item<DataType> item : items) { clonedItems.add(item.clone()); } return clonedItems; } /** * Returns a set, which contains the listeners, which should be notified, * when the adapter's underlying data has been modified. * * @return A set, which contains the listeners, which should be notified, * when the adapter's underlying data has been modified, as an * instance of the type {@link Set} or an empty set, if no listeners * should be notified */ protected final Set<ListAdapterListener<DataType>> getAdapterListeners() { return adapterListeners; } /** * The method, which is invoked, when an item has been clicked. * * @param index * The index of the item, which has been clicked, as an * {@link Integer} value */ protected void onItemClicked(final int index) { return; } /** * This method is invoked to apply the decorator, which allows to customize * the view, which is used to visualize a specific item. * * @param context * The context, the adapter belongs to, as an instance of the * class {@link Context}. The context may not be null * @param view * The view, which is used to visualize the item, as an instance * of the class {@link View}. The view may not be null * @param index * The index of the item, which should be visualized, as an * {@link Integer} value */ protected abstract void applyDecorator(final Context context, final View view, final int index); /** * Creates a new adapter, whose underlying data is managed as a list of * arbitrary items. * * @param context * The context, the adapter belongs to, as an instance of the * class {@link Context}. The context may not be null * @param inflater * The inflater, which should be used to inflate the views, which * are used to visualize the adapter's items, as an instance of * the type {@link Inflater}. The inflater may not be null * @param decorator * The decorator, which should be used to customize the * appearance of the views, which are used to visualize the items * of the adapter, as an instance of the generic type * DecoratorType. The decorator may not be null * @param logLevel * The log level, which should be used for logging, as a value of * the enum {@link LogLevel}. The log level may not be null * @param items * A list, which contains the the adapter's underlying data, as * an instance of the type {@link List} or an empty list, if the * adapter should not contain any data * @param allowDuplicates * True, if duplicate items should be allowed, false otherwise * @param adapterListeners * A set, which contains the listeners, which should be notified, * when the adapter's underlying data has been modified, as an * instance of the type {@link Set} or an empty set, if no * listeners should be notified */ protected AbstractListAdapter(final Context context, final Inflater inflater, final DecoratorType decorator, final LogLevel logLevel, final List<Item<DataType>> items, final boolean allowDuplicates, final Set<ListAdapterListener<DataType>> adapterListeners) { ensureNotNull(context, "The context may not be null"); ensureNotNull(inflater, "The inflater may not be null"); ensureNotNull(decorator, "The decorator may not be null"); ensureNotNull(adapterListeners, "The adapter listeners may not be null"); setItems(items); this.context = context; this.inflater = inflater; this.decorator = decorator; this.logger = new Logger(logLevel); this.items = items; this.allowDuplicates = allowDuplicates; this.adapterListeners = adapterListeners; } @Override public final LogLevel getLogLevel() { return getLogger().getLogLevel(); } @Override public final void setLogLevel(final LogLevel logLevel) { getLogger().setLogLevel(logLevel); } @Override public final boolean areDuplicatesAllowed() { return allowDuplicates; } @Override public final void allowDuplicates(final boolean allowDuplicates) { this.allowDuplicates = allowDuplicates; String message = "Duplicate items are now " + (allowDuplicates ? "allowed" : "disallowed"); getLogger().logDebug(getClass(), message); } @Override public final void addAdapterListener( final ListAdapterListener<DataType> listener) { ensureNotNull(listener, "The listener may not be null"); adapterListeners.add(listener); String message = "Added adapter listener \"" + listener + "\""; getLogger().logDebug(getClass(), message); } @Override public final void removeAdapterListener( final ListAdapterListener<DataType> listener) { ensureNotNull(listener, "The listener may not be null"); adapterListeners.remove(listener); String message = "Removed adapter listener \"" + listener + "\""; getLogger().logDebug(getClass(), message); } @Override public final boolean addItem(final DataType item) { return addItem(getNumberOfItems(), item); } @Override public final boolean addItem(final int index, final DataType item) { ensureNotNull(item, "The item may not be null"); if (!areDuplicatesAllowed() && containsItem(item)) { String message = "Item \"" + item + "\" at index " + index + " not added, because adapter already contains item"; getLogger().logDebug(getClass(), message); return false; } items.add(index, new Item<DataType>(item)); notifyOnItemAdded(item, index); notifyDataSetChanged(); String message = "Item \"" + item + "\" added"; getLogger().logInfo(getClass(), message); return true; } @Override public final boolean addAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); return addAllItems(getNumberOfItems(), items); } @Override public final boolean addAllItems(final int index, final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); boolean result = true; int currentIndex = index; for (DataType item : items) { result &= addItem(currentIndex, item); currentIndex++; } return result; } @Override public final boolean addAllItems(final DataType... items) { return addAllItems(getNumberOfItems(), items); } @Override public final boolean addAllItems(final int index, final DataType... items) { ensureNotNull(items, "The array may not be null"); return addAllItems(index, Arrays.asList(items)); } @Override public final DataType replaceItem(final int index, final DataType item) { ensureNotNull(item, "The item may not be null"); DataType replacedItem = items.set(index, new Item<DataType>(item)) .getData(); notifyOnItemRemoved(replacedItem, index); notifyOnItemAdded(item, index); notifyDataSetChanged(); String message = "Replaced item \"" + replacedItem + "\" at index " + index + " with item \"" + item + "\""; getLogger().logInfo(getClass(), message); return replacedItem; } @Override public final DataType removeItem(final int index) { DataType removedItem = items.remove(index).getData(); notifyOnItemRemoved(removedItem, index); notifyDataSetChanged(); String message = "Removed item \"" + removedItem + "\" from index " + index; getLogger().logInfo(getClass(), message); return removedItem; } @Override public final boolean removeItem(final DataType item) { ensureNotNull(item, "The item may not be null"); int index = indexOf(item); if (index != -1) { items.remove(index); notifyOnItemRemoved(item, index); notifyDataSetChanged(); String message = "Removed item \"" + item + "\" from index " + index; getLogger().logInfo(getClass(), message); return true; } String message = "Item \"" + item + "\" not removed, because adapter does not contain item"; getLogger().logDebug(getClass(), message); return false; } @Override public final boolean removeAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); int numberOfRemovedItems = 0; for (int i = getNumberOfItems() - 1; i >= 0; i if (items.contains(getItem(i))) { removeItem(i); numberOfRemovedItems++; } } return numberOfRemovedItems == items.size(); } @Override public final boolean removeAllItems(final DataType... items) { ensureNotNull(items, "The array may not be null"); return removeAllItems(Arrays.asList(items)); } @Override public final void retainAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); for (int i = getNumberOfItems() - 1; i >= 0; i if (!items.contains(getItem(i))) { removeItem(i); } } } @Override public final void retainAllItems(final DataType... items) { ensureNotNull(items, "The array may not be null"); retainAllItems(Arrays.asList(items)); } @Override public final void clearItems() { for (int i = getNumberOfItems() - 1; i >= 0; i removeItem(i); } getLogger().logInfo(getClass(), "Cleared all items"); } @Override public final Iterator<DataType> iterator() { return new ItemIterator<DataType>(items, this); } @Override public final ListIterator<DataType> listIterator() { return new ItemListIterator<DataType>(items, this); } @Override public final ListIterator<DataType> listIterator(final int index) { return new ItemListIterator<DataType>(items, this, index); } @Override public final Collection<DataType> subList(final int start, final int end) { Collection<DataType> subList = new ArrayList<DataType>(); for (int i = start; i < end; i++) { subList.add(getItem(i)); } return subList; } @Override public final Object[] toArray() { return getAllItems().toArray(); } @Override public final <T> T[] toArray(final T[] array) { return getAllItems().toArray(array); } @Override public final int indexOf(final DataType item) { ensureNotNull(item, "The item may not be null"); return getAllItems().indexOf(item); } @Override public final int lastIndexOf(final DataType item) { ensureNotNull(item, "The item may not be null"); return getAllItems().lastIndexOf(item); } @Override public final boolean containsItem(final DataType item) { ensureNotNull(item, "The item may not be null"); return getAllItems().contains(item); } @Override public final boolean containsAllItems(final Collection<DataType> items) { ensureNotNull(items, "The collection may not be null"); return getAllItems().containsAll(items); } @Override public final boolean containsAllItems(final DataType... items) { ensureNotNull(items, "The array may not be null"); return containsAllItems(Arrays.asList(items)); } @Override public final int getNumberOfItems() { return items.size(); } @Override public final DataType getItem(final int index) { return items.get(index).getData(); } @Override public final List<DataType> getAllItems() { List<DataType> result = new ArrayList<DataType>(); for (Item<DataType> item : items) { result.add(item.getData()); } return result; } @Override public final boolean isEmpty() { return items.isEmpty(); } @Override public final int getCount() { return getNumberOfItems(); } @Override public final long getItemId(final int index) { ensureAtLeast(index, 0, "The index must be at least 0"); ensureAtMaximum(index, items.size() - 1, isEmpty() ? "The index must be at maximum " + (items.size() - 1) : "The adapter is empty"); return index; } @Override public final View getView(final int index, final View convertView, final ViewGroup parent) { View view = convertView; if (view == null) { view = getInflater().inflate(getContext(), parent, false); view.setOnClickListener(createItemOnClickListener(index)); String message = "Inflated view to visualize the item at index " + index; getLogger().logVerbose(getClass(), message); } applyDecorator(getContext(), view, index); return view; } @Override public void onSaveInstanceState(final Bundle outState) { if (isUnderlyingDataSerializable()) { SerializableWrapper<List<Item<DataType>>> wrappedItems = new SerializableWrapper<List<Item<DataType>>>( getItems()); outState.putSerializable(ITEMS_BUNDLE_KEY, wrappedItems); } else { String message = "The adapter's items can not be stored, because the " + "underlying data does not implement the interface \"" + Serializable.class.getName() + "\""; getLogger().logWarn(getClass(), message); } outState.putBoolean(ALLOW_DUPLICATES_BUNDLE_KEY, areDuplicatesAllowed()); outState.putInt(LOG_LEVEL_BUNDLE_KEY, getLogLevel().getRank()); getLogger().logDebug(getClass(), "Saved instance state"); } @SuppressWarnings("unchecked") @Override public void onRestoreInstanceState(final Bundle savedInstanceState) { if (savedInstanceState != null) { if (savedInstanceState.containsKey(ITEMS_BUNDLE_KEY)) { SerializableWrapper<List<Item<DataType>>> wrappedItems = (SerializableWrapper<List<Item<DataType>>>) savedInstanceState .getSerializable(ITEMS_BUNDLE_KEY); items = wrappedItems.getWrappedInstance(); } allowDuplicates(savedInstanceState .getBoolean(ALLOW_DUPLICATES_BUNDLE_KEY)); setLogLevel(LogLevel.fromRank(savedInstanceState .getInt(LOG_LEVEL_BUNDLE_KEY))); notifyDataSetChanged(); getLogger().logDebug(getClass(), "Restored instance state"); } } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (allowDuplicates ? 1231 : 1237); result = prime * result + items.hashCode(); result = prime * result + getLogLevel().getRank(); return result; } @Override public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; AbstractListAdapter<?, ?> other = (AbstractListAdapter<?, ?>) obj; if (allowDuplicates != other.allowDuplicates) return false; if (!items.equals(other.items)) return false; if (!getLogLevel().equals(other.getLogLevel())) return false; return true; } @Override public abstract AbstractListAdapter<DataType, DecoratorType> clone() throws CloneNotSupportedException; }
//#MIDP_EXCLUDE_FILE package jade.core.management; import jade.core.ServiceFinder; import jade.core.HorizontalCommand; import jade.core.VerticalCommand; import jade.core.GenericCommand; import jade.core.Service; import jade.core.BaseService; import jade.core.ServiceException; import jade.core.Sink; import jade.core.Filter; import jade.core.Node; import jade.core.Profile; import jade.core.Agent; import jade.core.AgentState; import jade.core.AID; import jade.core.ContainerID; import jade.core.AgentContainer; import jade.core.BackEndContainer; import jade.core.MainContainer; import jade.core.ProfileException; import jade.core.IMTPException; import jade.core.NameClashException; import jade.core.NotFoundException; import jade.core.UnreachableException; import jade.security.Authority; import jade.security.CertificateFolder; import jade.security.AgentPrincipal; import jade.security.IdentityCertificate; import jade.security.AuthException; import jade.util.leap.Map; import jade.util.leap.HashMap; import jade.util.leap.Iterator; /** The JADE service to manage the basic agent life cycle: creation, destruction, suspension and resumption, in the special case of a Back-End Container. @author Giovanni Rimassa - FRAMeTech s.r.l. */ public class BEAgentManagementService extends BaseService { static final String NAME = "jade.core.management.AgentManagement"; private static final String[] OWNED_COMMANDS = new String[] { AgentManagementSlice.REQUEST_CREATE, AgentManagementSlice.REQUEST_START, AgentManagementSlice.REQUEST_KILL, AgentManagementSlice.REQUEST_STATE_CHANGE, AgentManagementSlice.INFORM_CREATED, AgentManagementSlice.INFORM_KILLED, AgentManagementSlice.INFORM_STATE_CHANGED, AgentManagementSlice.KILL_CONTAINER }; public void init(AgentContainer ac, Profile p) throws ProfileException { super.init(ac, p); myContainer = (BackEndContainer)ac; } public String getName() { return AgentManagementSlice.NAME; } public Class getHorizontalInterface() { try { return Class.forName(AgentManagementSlice.NAME + "Slice"); } catch(ClassNotFoundException cnfe) { return null; } } public Service.Slice getLocalSlice() { return localSlice; } public Filter getCommandFilter(boolean direction) { return null; } public Sink getCommandSink(boolean side) { if(side == Sink.COMMAND_SOURCE) { return senderSink; } else { return receiverSink; } } public String[] getOwnedCommands() { return OWNED_COMMANDS; } // This inner class handles the messaging commands on the command // issuer side, turning them into horizontal commands and // forwarding them to remote slices when necessary. private class CommandSourceSink implements Sink { public void consume(VerticalCommand cmd) { try { String name = cmd.getName(); if(name.equals(AgentManagementSlice.INFORM_KILLED)) { handleInformKilled(cmd); } else if(name.equals(AgentManagementSlice.INFORM_STATE_CHANGED)) { handleInformStateChanged(cmd); } else if(name.equals(AgentManagementSlice.INFORM_CREATED)) { handleInformCreated(cmd); } } catch(IMTPException imtpe) { cmd.setReturnValue(new UnreachableException("Remote container is unreachable", imtpe)); } catch(NotFoundException nfe) { cmd.setReturnValue(nfe); } catch(NameClashException nce) { cmd.setReturnValue(nce); } catch(AuthException ae) { cmd.setReturnValue(ae); } catch(ServiceException se) { cmd.setReturnValue(new UnreachableException("A Service Exception occurred", se)); } } // Vertical command handler methods private void handleInformCreated(VerticalCommand cmd) throws IMTPException, NotFoundException, NameClashException, AuthException, ServiceException { Object[] params = cmd.getParams(); AID agentID = (AID)params[0]; // If an actual agent instance was passed as second // argument, then this agent has to be started within the // Back-End container. if((params.length > 2) && (params[1] instanceof Agent) && (params[2] instanceof Boolean)) { Agent instance = (Agent)params[1]; boolean startIt = ((Boolean)params[2]).booleanValue(); createAgentOnBE(agentID, instance, startIt); } else { BackEndContainer.AgentImage image = (BackEndContainer.AgentImage) pendingImages.remove(agentID); if (image == null) { // The agent spontaneously born on the FrontEnd --> its image still has to be created image = myContainer.createAgentImage(agentID); // Create and set security information try { CertificateFolder certs = myContainer.createCertificateFolder(agentID); image.setPrincipal(certs); image.setOwnership(((AgentPrincipal) certs.getIdentityCertificate().getSubject()).getOwnership()); } catch (AuthException ae) { // Should never happen ae.printStackTrace(); } } // Add the agent image to the table BackEndContainer.AgentImage previous = (BackEndContainer.AgentImage) myContainer.addAgentImage(agentID, image); try { ContainerID cid = myContainer.getID(); AgentManagementSlice mainSlice = (AgentManagementSlice)getSlice(MAIN_SLICE); try { mainSlice.bornAgent(agentID, cid, image.getCertificateFolder()); } catch(IMTPException imtpe) { mainSlice = (AgentManagementSlice)getFreshSlice(jade.core.ServiceFinder.MAIN_SLICE); mainSlice.bornAgent(agentID, cid, image.getCertificateFolder()); } } catch (Exception e) { e.printStackTrace(); // Roll back if necessary and throw an IMTPException myContainer.removeAgentImage(agentID); if (previous != null) { myContainer.addAgentImage(agentID, previous); } throw new IMTPException("Error creating agent " + agentID.getLocalName() + ". ", e); } } } private void handleInformKilled(VerticalCommand cmd) throws IMTPException, ServiceException, NotFoundException { Object[] params = cmd.getParams(); AID target = (AID)params[0]; // Remove the dead agent from the agent images BackEndContainer.AgentImage image = (BackEndContainer.AgentImage) myContainer.removeAgentImage(target); // Notify the main container through its slice AgentManagementSlice mainSlice = (AgentManagementSlice)getSlice(MAIN_SLICE); try { mainSlice.deadAgent(target); } catch(IMTPException imtpe) { // Try to get a newer slice and repeat... mainSlice = (AgentManagementSlice)getFreshSlice(MAIN_SLICE); mainSlice.deadAgent(target); } } private void handleInformStateChanged(VerticalCommand cmd) { Object[] params = cmd.getParams(); AID target = (AID)params[0]; AgentState from = (AgentState)params[1]; AgentState to = (AgentState)params[2]; if (to.equals(jade.domain.FIPAAgentManagement.AMSAgentDescription.SUSPENDED)) { try { // Notify the main container through its slice AgentManagementSlice mainSlice = (AgentManagementSlice)getSlice(MAIN_SLICE); try { mainSlice.suspendedAgent(target); } catch(IMTPException imtpe) { // Try to get a newer slice and repeat... mainSlice = (AgentManagementSlice)getFreshSlice(MAIN_SLICE); mainSlice.suspendedAgent(target); } } catch(IMTPException re) { re.printStackTrace(); } catch(NotFoundException nfe) { nfe.printStackTrace(); } catch(ServiceException se) { se.printStackTrace(); } } else if (from.equals(jade.domain.FIPAAgentManagement.AMSAgentDescription.SUSPENDED)) { try { // Notify the main container through its slice AgentManagementSlice mainSlice = (AgentManagementSlice)getSlice(MAIN_SLICE); try { mainSlice.resumedAgent(target); } catch(IMTPException imtpe) { // Try to get a newer slice and repeat... mainSlice = (AgentManagementSlice)getFreshSlice(MAIN_SLICE); mainSlice.resumedAgent(target); } } catch(IMTPException re) { re.printStackTrace(); } catch(NotFoundException nfe) { nfe.printStackTrace(); } catch(ServiceException se) { se.printStackTrace(); } } } private void createAgentOnBE(AID target, Agent instance, boolean startIt) throws IMTPException, AuthException, NameClashException, NotFoundException, ServiceException { // Connect the new instance to the local container Agent old = myContainer.addLocalAgent(target, instance); try { CertificateFolder agentCerts = instance.getCertificateFolder(); if(startIt) { // Notify the main container through its slice AgentManagementSlice mainSlice = (AgentManagementSlice)getSlice(MAIN_SLICE); try { mainSlice.bornAgent(target, myContainer.getID(), agentCerts); } catch(IMTPException imtpe) { // Try to get a newer slice and repeat... mainSlice = (AgentManagementSlice)getFreshSlice(MAIN_SLICE); mainSlice.bornAgent(target, myContainer.getID(), agentCerts); } // Actually start the agent thread myContainer.powerUpLocalAgent(target, instance); } } catch(NameClashException nce) { myContainer.removeLocalAgent(target); if(old != null) { myContainer.addLocalAgent(target, old); } throw nce; } catch(IMTPException imtpe) { myContainer.removeLocalAgent(target); throw imtpe; } catch(NotFoundException nfe) { myContainer.removeLocalAgent(target); throw nfe; } catch(AuthException ae) { myContainer.removeLocalAgent(target); throw ae; } } } // End of CommandSourceSink class private class CommandTargetSink implements Sink { public void consume(VerticalCommand cmd) { try { String name = cmd.getName(); if(name.equals(AgentManagementSlice.REQUEST_CREATE)) { handleRequestCreate(cmd); } else if(name.equals(AgentManagementSlice.REQUEST_KILL)) { handleRequestKill(cmd); } else if(name.equals(AgentManagementSlice.REQUEST_STATE_CHANGE)) { handleRequestStateChange(cmd); } else if(name.equals(AgentManagementSlice.INFORM_STATE_CHANGED)) { handleInformStateChanged(cmd); } else if(name.equals(AgentManagementSlice.KILL_CONTAINER)) { handleKillContainer(cmd); } } catch(IMTPException imtpe) { cmd.setReturnValue(new UnreachableException("Remote container is unreachable", imtpe)); } catch(NotFoundException nfe) { cmd.setReturnValue(nfe); } catch(NameClashException nce) { cmd.setReturnValue(nce); } catch(AuthException ae) { cmd.setReturnValue(ae); } catch(ServiceException se) { cmd.setReturnValue(new UnreachableException("A Service Exception occurred", se)); } } // Vertical command handler methods private void handleRequestCreate(VerticalCommand cmd) throws IMTPException, AuthException, NotFoundException, NameClashException, ServiceException { Object[] params = cmd.getParams(); AID agentID = (AID)params[0]; String className = (String)params[1]; Object[] arguments = (Object[])params[2]; String ownership = (String)params[3]; CertificateFolder certs = (CertificateFolder)params[4]; boolean startIt = ((Boolean)params[5]).booleanValue(); createAgent(agentID, className, arguments, ownership, certs, startIt); } private void handleRequestKill(VerticalCommand cmd) throws IMTPException, AuthException, NotFoundException, ServiceException { Object[] params = cmd.getParams(); AID agentID = (AID)params[0]; killAgent(agentID); } private void handleRequestStateChange(VerticalCommand cmd) throws IMTPException, AuthException, NotFoundException, ServiceException { Object[] params = cmd.getParams(); AID agentID = (AID)params[0]; int newState = ((Integer)params[1]).intValue(); changeAgentState(agentID, newState); } private void handleInformStateChanged(VerticalCommand cmd) throws NotFoundException { Object[] params = cmd.getParams(); AID agentID = (AID)params[0]; String newState = (String)params[1]; if (newState.equals(jade.domain.FIPAAgentManagement.AMSAgentDescription.SUSPENDED)) { suspendedAgent(agentID); } else if(newState.equals(jade.domain.FIPAAgentManagement.AMSAgentDescription.ACTIVE)) { resumedAgent(agentID); } } private void handleKillContainer(VerticalCommand cmd) { exitContainer(); } /** Force the creation of an agent on the FrontEnd. Note that the agent to create can have a different owner with respect to the owner of this "container" --> Its image holding the agent's ownership information must be created now and not in the bornAgent() method. This image is stored in the pendingImages map for later retrieval (see bornAgent()). */ private void createAgent(AID agentID, String className, Object[] args, String ownership, CertificateFolder certs, boolean startIt) throws IMTPException { BackEndContainer.AgentImage image = myContainer.createAgentImage(agentID); // Set security information if (certs != null) { image.setPrincipal(certs); } if(ownership != null) { image.setOwnership(ownership); } else if (certs.getIdentityCertificate() != null) { image.setOwnership(((AgentPrincipal) certs.getIdentityCertificate().getSubject()).getOwnership()); } // Store the image so that it can be retrieved when the new agent starts BackEndContainer.AgentImage previous = (BackEndContainer.AgentImage) pendingImages.put(agentID, image); try { // Arguments can only be Strings String[] sargs = null; if (args != null) { sargs = new String[args.length]; for (int i = 0; i < args.length; ++i) { sargs[i] = (String) args[i]; } } myContainer.createAgentOnFE(agentID.getLocalName(), className, sargs); } catch (IMTPException imtpe) { // Roll back if necessary and forward the exception pendingImages.remove(agentID); if (previous != null) { pendingImages.put(agentID, previous); } throw imtpe; } catch (ClassCastException cce) { // Roll back if necessary and forward the exception pendingImages.remove(agentID); if (previous != null) { pendingImages.put(agentID, previous); } throw new IMTPException("Non-String argument"); } } private void killAgent(AID agentID) throws IMTPException, NotFoundException { if (myContainer.getAgentImage(agentID) != null) { String name = agentID.getLocalName(); myContainer.killAgentOnFE(name); } else { throw new NotFoundException("KillAgent failed to find " + agentID); } } private void changeAgentState(AID agentID, int newState) throws IMTPException, NotFoundException { BackEndContainer.AgentImage a = myContainer.getAgentImage(agentID); if(a == null) throw new NotFoundException("Change-Agent-State failed to find " + agentID); if(newState == Agent.AP_SUSPENDED) { myContainer.suspendAgentOnFE(agentID.getLocalName()); } else if(newState == Agent.AP_ACTIVE) { myContainer.resumeAgentOnFE(agentID.getLocalName()); } } private void suspendedAgent(AID name) throws NotFoundException { } private void resumedAgent(AID name) throws NotFoundException { } private void exitContainer() { // "Kill" all agent images AID[] targets = myContainer.getAgentImages(); for(int i = 0; i < targets.length; i++) { AID target = targets[i]; try { // Remove the dead agent from the agent images BackEndContainer.AgentImage image = myContainer.removeAgentImage(target); // Notify the main container through its slice AgentManagementSlice mainSlice = (AgentManagementSlice)getSlice(MAIN_SLICE); try { mainSlice.deadAgent(target); } catch(IMTPException imtpe) { // Try to get a newer slice and repeat... mainSlice = (AgentManagementSlice)getFreshSlice(MAIN_SLICE); mainSlice.deadAgent(target); } } catch (Exception ex) { ex.printStackTrace(); } } myContainer.shutDown(); } } // End of CommandTargetSink class /** Inner mix-in class for this service: this class receives commands from the service <code>Sink</code> and serves them, coordinating with remote parts of this service through the <code>Service.Slice</code> interface. */ private class ServiceComponent implements Service.Slice { // Implementation of the Service.Slice interface public Service getService() { return BEAgentManagementService.this; } public Node getNode() throws ServiceException { try { return BEAgentManagementService.this.getLocalNode(); } catch(IMTPException imtpe) { throw new ServiceException("Problem in contacting the IMTP Manager", imtpe); } } public VerticalCommand serve(HorizontalCommand cmd) { VerticalCommand result = null; try { String cmdName = cmd.getName(); Object[] params = cmd.getParams(); if(cmdName.equals(AgentManagementSlice.H_CREATEAGENT)) { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.REQUEST_CREATE, AgentManagementSlice.NAME, null); AID agentID = (AID)params[0]; String className = (String)params[1]; Object[] arguments = (Object[])params[2]; String ownership = (String)params[3]; CertificateFolder certs = (CertificateFolder)params[4]; Boolean startIt = (Boolean)params[5]; gCmd.addParam(agentID); gCmd.addParam(className); gCmd.addParam(arguments); gCmd.addParam(ownership); gCmd.addParam(certs); gCmd.addParam(startIt); result = gCmd; } else if(cmdName.equals(AgentManagementSlice.H_KILLAGENT)) { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.REQUEST_KILL, AgentManagementSlice.NAME, null); AID agentID = (AID)params[0]; gCmd.addParam(agentID); result = gCmd; } else if(cmdName.equals(AgentManagementSlice.H_CHANGEAGENTSTATE)) { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.REQUEST_STATE_CHANGE, AgentManagementSlice.NAME, null); AID agentID = (AID)params[0]; Integer newState = (Integer)params[1]; gCmd.addParam(agentID); gCmd.addParam(newState); result = gCmd; } else if(cmdName.equals(AgentManagementSlice.H_BORNAGENT)) { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_CREATED, AgentManagementSlice.NAME, null); AID agentID = (AID)params[0]; ContainerID cid = (ContainerID)params[1]; CertificateFolder certs = (CertificateFolder)params[2]; gCmd.addParam(agentID); gCmd.addParam(cid); gCmd.addParam(certs); result = gCmd; } else if(cmdName.equals(AgentManagementSlice.H_DEADAGENT)) { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_KILLED, AgentManagementSlice.NAME, null); AID agentID = (AID)params[0]; gCmd.addParam(agentID); result = gCmd; } else if(cmdName.equals(AgentManagementSlice.H_SUSPENDEDAGENT)) { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_STATE_CHANGED, AgentManagementSlice.NAME, null); AID agentID = (AID)params[0]; gCmd.addParam(agentID); gCmd.addParam(jade.domain.FIPAAgentManagement.AMSAgentDescription.SUSPENDED); result = gCmd; } else if(cmdName.equals(AgentManagementSlice.H_RESUMEDAGENT)) { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.INFORM_STATE_CHANGED, AgentManagementSlice.NAME, null); AID agentID = (AID)params[0]; gCmd.addParam(agentID); gCmd.addParam(jade.domain.FIPAAgentManagement.AMSAgentDescription.ACTIVE); result = gCmd; } else if(cmdName.equals(AgentManagementSlice.H_EXITCONTAINER)) { GenericCommand gCmd = new GenericCommand(AgentManagementSlice.KILL_CONTAINER, AgentManagementSlice.NAME, null); result = gCmd; } } catch(Throwable t) { cmd.setReturnValue(t); } finally { return result; } } } // End of AgentManagementSlice class // The concrete agent container, providing access to LADT, etc. private BackEndContainer myContainer; // The local slice for this service private final ServiceComponent localSlice = new ServiceComponent(); // The command sink, source side private final CommandSourceSink senderSink = new CommandSourceSink(); // The command sink, target side private final CommandTargetSink receiverSink = new CommandTargetSink(); // Service specific data private Map pendingImages = new HashMap(); }
package eu.bryants.anthony.plinth.compiler; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; /** * @author Anthony Bryant */ public class ArgumentParser { private String mainTypeName; private String output; private String outputDir; private String[] sources; private String[] importFiles; private Set<String> linkSet = new HashSet<String>(); public ArgumentParser(String... arguments) { List<String> sourceList = new LinkedList<String>(); List<String> importList = new LinkedList<String>(); for (int i = 0; i < arguments.length; ++i) { if (arguments[i].equals("-m") || arguments[i].equals("--main-type")) { if (i >= arguments.length - 1 | mainTypeName != null) { usage(); System.exit(1); } ++i; mainTypeName = arguments[i]; continue; } if (arguments[i].equals("-o") || arguments[i].equals("--output")) { if (i >= arguments.length - 1 | output != null) { usage(); System.exit(1); } ++i; output = arguments[i]; continue; } if (arguments[i].equals("-d") || arguments[i].equals("--output-dir")) { if (i >= arguments.length - 1 | outputDir != null) { usage(); System.exit(1); } ++i; outputDir = arguments[i]; continue; } if (arguments[i].equals("-i") || arguments[i].equals("--import")) { if (i >= arguments.length - 1) { usage(); System.exit(1); } ++i; importList.add(arguments[i]); continue; } if (arguments[i].equals("-l") || arguments[i].equals("--link")) { if (i >= arguments.length - 1) { usage(); System.exit(1); } ++i; importList.add(arguments[i]); linkSet.add(arguments[i]); continue; } sourceList.add(arguments[i]); } sources = sourceList.toArray(new String[sourceList.size()]); importFiles = importList.toArray(new String[importList.size()]); } /** * @return the mainTypeName */ public String getMainTypeName() { return mainTypeName; } /** * @return the output */ public String getOutput() { return output; } /** * @return the outputDir */ public String getOutputDir() { return outputDir; } /** * @return the sources */ public String[] getSources() { return sources; } /** * @return the array of names of files which were specified with --import or --link, in the order they were specified */ public String[] getImportedFiles() { return importFiles; } /** * @return the set of names of files which were specified with --link. A file name in this set will always be in the array returned by getImportedFiles(). */ public Set<String> getLinkedFileSet() { return linkSet; } /** * Prints the usage information for the program. */ public static void usage() { System.out.println("Usage: java eu.bryants.anthony.plinth.compiler.Compiler [option]... [source-file]...\n" + "Options:\n" + " -m <main-type>, --main-type <main-type>\n" + " Generates a low-level main method which calls the main() method in the type with the specified fully qualified name.\n" + " The correct signature for a main method is:\n" + " static uint main([]string)\n" + " -o <binary>, --output <binary>\n" + " Specifies the name of the binary produced.\n" + " -d <output-dir>, --output-dir <output-dir>\n" + " Specifies the output directory for the generated bitcode files, which will be generated in a directory structure equivalent to the package structure.\n" + " If this is not specified, these files will not be generated.\n" + " -i <bitcode-file>, --import <bitcode-file>\n" + " Imports the type definition(s) defined in the specified file into the search when searching for types.\n" + " Note: This option can be specified multiple times.\n" + " -l <bitcode-file>, --link <bitcode-file>\n" + " Links the specified bitcode file into the output module.\n" + " Using this option also implicitly imports the specified bitcode file (i.e. it also acts as --import).\n" + " Note: This option can be specified multiple times."); } }
public class Solution { public int evalRPN(String[] tokens) { ArrayList<String> wordlist = new ArrayList<String>(Arrays.asList(tokens)); int loc = 0; int leftoperand; int rightoperand; int operandafter = 0; String symbol; if(wordlist.size()==1) operandafter = Integer.parseInt(wordlist.get(loc)); while(wordlist.size()!=1){ symbol = wordlist.get(loc); switch(symbol){ case "+": leftoperand = Integer.parseInt(wordlist.get(loc - 2)); rightoperand = Integer.parseInt(wordlist.get(loc - 1)); operandafter = leftoperand + rightoperand; wordlist.remove(loc - 2); wordlist.remove(loc - 2); wordlist.set(loc - 2, Integer.toString(operandafter)); loc break; case "-": leftoperand = Integer.parseInt(wordlist.get(loc - 2)); rightoperand = Integer.parseInt(wordlist.get(loc - 1)); operandafter = leftoperand - rightoperand; wordlist.remove(loc - 2); wordlist.remove(loc - 2); wordlist.set(loc - 2, Integer.toString(operandafter)); loc break; case "*": leftoperand = Integer.parseInt(wordlist.get(loc - 2)); rightoperand = Integer.parseInt(wordlist.get(loc - 1)); operandafter = leftoperand * rightoperand; wordlist.remove(loc - 2); wordlist.remove(loc - 2); wordlist.set(loc - 2, Integer.toString(operandafter)); loc break; case "/": leftoperand = Integer.parseInt(wordlist.get(loc - 2)); rightoperand = Integer.parseInt(wordlist.get(loc - 1)); operandafter = leftoperand / rightoperand; wordlist.remove(loc - 2); wordlist.remove(loc - 2); wordlist.set(loc - 2, Integer.toString(operandafter)); loc break; default: loc++; break; } } return operandafter; } }
package au.com.agic.apptesting; import au.com.agic.apptesting.constants.Constants; import au.com.agic.apptesting.exception.FileProfileAccessException; import au.com.agic.apptesting.exception.RunScriptsException; import au.com.agic.apptesting.utils.*; import au.com.agic.apptesting.utils.impl.*; import net.lightbody.bmp.BrowserMobProxy; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.TrueFileFilter; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.threadpool.DefaultThreadPool; import org.openqa.selenium.remote.DesiredCapabilities; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.validation.constraints.NotNull; import java.io.File; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import static au.com.agic.apptesting.constants.Constants.OPEN_REPORT_FILE_SYSTEM_PROPERTY; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; /** * Typically Cucumber tests are run as jUnit tests. However, in our configuration we run Cucumber as a standalone * application spawned in a thread, and let Cucumber itself save junit report files. <p> In this process, there is * little to be gained by running the tests within junit, so we create a standard java command line application. */ public class TestRunner { private static final Logger LOGGER = LoggerFactory.getLogger(TestRunner.class); private static final ExceptionWriter EXCEPTION_WRITER = new ExceptionWriterImpl(); private static final SystemPropertyUtils SYSTEM_PROPERTY_UTILS = new SystemPropertyUtilsImpl(); private static final ApplicationUrlLoader APPLICATION_URL_LOADER = new ApplicationUrlLoaderImpl(); private static final JUnitReportMerge J_UNIT_REPORT_MERGE = new JUnitReportMergeImpl(); private static final String MERGED_REPORT = "MergedReport.xml"; private static final ScreenCapture SCREEN_CAPTURE = new ScreenCaptureImpl(); private static final DesktopInteraction DESKTOP_INTERACTION = new DesktopInteractionImpl(); private static final FileSystemUtils FILE_SYSTEM_UTILS = new FileSystemUtilsImpl(); private static final LocalProxyUtils<?> ZAP_PROXY = new ZapProxyUtilsImpl(); private static final LocalProxyUtils<?> BROWSERMOB_PROXY = new BrowsermobProxyUtilsImpl(); private static final WebDriverHandler WEB_DRIVER_HANDLER = new WebDriverHandlerImpl(); private static final JarDownloader JAR_DOWNLOADER = new JarDownloaderImpl(); private static final String HTML_EXTENSION = ".html"; /** * Used to name threads that might be reused */ private static final AtomicInteger THREAD_COUNT = new AtomicInteger(0); private static final TagAnalyser TAG_ANALYSER = new TagAnalyserImpl(); /** * How long to offset the initial launch of the cucumber tests */ private static final long DELAY_CONCURRENT_START = 2000; private static final long THREAD_COMPLETE_SLEEP = 1000; private final DefaultThreadPool threadPool = new DefaultThreadPool(NumberUtils .toInt(SYSTEM_PROPERTY_UTILS.getProperty(Constants.NUMBER_THREADS_SYSTEM_PROPERTY), 2)); /** * Used to count the number of scripts that have completed */ private int completed = 0; /** * Used to count the number of scripts that completed with errors */ private int failure = 0; public TestRunner() { /* This is the directory that will hold our reports */ final String reportOutput = FILE_SYSTEM_UTILS.buildReportDirectoryName() + File.separator; /* A list of files to clean up one the test is complete */ final List<File> tempFiles = new ArrayList<>(); try { JAR_DOWNLOADER.downloadJar(tempFiles); copySystemProperties(); WEB_DRIVER_HANDLER.configureWebDriver(tempFiles); final List<ProxyDetails<?>> proxies = configureProxies(tempFiles); cleanupOldReports(); init(reportOutput, tempFiles, proxies); /* Now run the tests */ try { runScripts(reportOutput); mergeReports(reportOutput); } catch (final FileProfileAccessException ex) { LOGGER.error("WEBAPPTESTER-BUG-0003: There was an exception thrown while trying to run the test scripts." + " This is most likely because of an invalid URL or path to the feature scripts." + " The details of the error are shown below.", ex); } catch (final Exception ex) { LOGGER.error("WEBAPPTESTER-BUG-0004: There was an exception thrown while trying to run the test scripts." + " The details of the error are shown below.", ex); } threadPool.stop(); } catch (final Exception ex) { EXCEPTION_WRITER.saveException(reportOutput, ex); } finally { /* Clean up temp files */ tempFiles.stream().forEach(File::delete); } } /** * We always create the browsermod proxy, and we optionally create the ZAP proxy */ private List<ProxyDetails<?>> configureProxies(final List<File> tempFiles) { final Optional<ProxyDetails<?>> zapProxy = ZAP_PROXY.startProxy(tempFiles); final Optional<ProxyDetails<?>> browermobProxy = BROWSERMOB_PROXY.startProxy(tempFiles); final List<ProxyDetails<?>> proxies = new ArrayList<>(); proxies.add(browermobProxy.get()); /* Forward browsermod to ZAP */ if (zapProxy.isPresent()) { ((BrowserMobProxy) browermobProxy.get().getInterface().get()) .setChainedProxy(new InetSocketAddress("localhost", zapProxy.get().getPort())); proxies.add(zapProxy.get()); } return proxies; } /** * Copy out any system properties used by webdriver passed in via webstart */ private void copySystemProperties() { SYSTEM_PROPERTY_UTILS.copyVariableToDefaultLocation( Constants.CHROME_WEB_DRIVER_LOCATION_SYSTEM_PROPERTY); SYSTEM_PROPERTY_UTILS.copyVariableToDefaultLocation( Constants.OPERA_WEB_DRIVER_LOCATION_SYSTEM_PROPERTY); SYSTEM_PROPERTY_UTILS.copyVariableToDefaultLocation( Constants.PHANTOM_JS_BINARY_PATH_SYSTEM_PROPERTY); SYSTEM_PROPERTY_UTILS.copyVariableToDefaultLocation( Constants.IE_WEB_DRIVER_LOCATION_SYSTEM_PROPERTY); } /** * Cleans up any existing reports left over from an old run */ private void cleanupOldReports() { final Iterator<File> iterator = FileUtils.iterateFiles(new File("."), new String[]{"xml", "txt"}, false); while (iterator.hasNext()) { final File file = iterator.next(); file.delete(); } } /** * Initialise the global state of the application */ private void init( final String reportOutput, final List<File> tempFiles, final List<ProxyDetails<?>> proxies) { final String appName = SYSTEM_PROPERTY_UTILS.getProperty(Constants.FEATURE_GROUP_SYSTEM_PROPERTY); final List<DesiredCapabilities> desiredCapabilities = new DesiredCapabilitiesLoaderImpl().getCapabilities(); State.THREAD_DESIRED_CAPABILITY_MAP.initialise( desiredCapabilities, APPLICATION_URL_LOADER.getAppUrls(appName), APPLICATION_URL_LOADER.getDatasets(), reportOutput, tempFiles, proxies); } /** * Spawn threads to run Cucumber scripts, and wait until they are all finished */ @SuppressWarnings("BusyWait") private void runScripts(@NotNull final String reportDirectory) { checkArgument(StringUtils.isNotBlank(reportDirectory)); final String groupName = SYSTEM_PROPERTY_UTILS.getProperty( Constants.GROUP_NAME_SYSTEM_PROPERTY); final String appName = SYSTEM_PROPERTY_UTILS.getProperty( Constants.FEATURE_GROUP_SYSTEM_PROPERTY); final String destination = SYSTEM_PROPERTY_UTILS.getProperty( Constants.TEST_DESTINATION_SYSTEM_PROPERTY); final boolean videoCapture = Boolean.parseBoolean( SYSTEM_PROPERTY_UTILS.getProperty( Constants.VIDEO_CAPTURE_SYSTEM_PROPERTY)) && !Constants.REMOTE_TESTS.equalsIgnoreCase(destination) && !Constants.PHANTOMJS.equalsIgnoreCase(SYSTEM_PROPERTY_UTILS.getProperty( Constants.TEST_DESTINATION_SYSTEM_PROPERTY)); String testPath = null; try { /* Start the video capture */ if (videoCapture) { SCREEN_CAPTURE.start(reportDirectory); } /* Select a feature loader */ final FeatureLoader featureLoader = getFeatureLoader(); /* Get the file system path that holds the feature scripts */ testPath = featureLoader.loadFeatures("", appName, groupName); /* For each combination of browser and url run a test */ for (int i = 0; i < State.THREAD_DESIRED_CAPABILITY_MAP.getNumberCapabilities(); ++i) { /* For those first few threads that are execute immediately, add a small offset. Obviously this doesn't have any impact as the thread pool is used up, but that is fine because in theory new threads will start with some kind of offset anyway as the time it takes to process the preceeding ones is random enough. */ try { Thread.sleep(i * DELAY_CONCURRENT_START); } catch (final Exception ignored) { /* Ignore this */ } threadPool.invokeLater(new CucumberThread(reportDirectory, testPath)); } /* Wait for the thread to finish */ while (completed != State.THREAD_DESIRED_CAPABILITY_MAP.getNumberCapabilities()) { try { Thread.sleep(THREAD_COMPLETE_SLEEP); } catch (final Exception ignored) { /* ignored */ } } /* Doh! Some scripts failed, so print a warning */ if (failure != 0) { LOGGER.error("Some of the cucumber tests failed. Check the logs for more details"); } LOGGER.info("Report files can be found in {}", reportDirectory); } finally { State.THREAD_DESIRED_CAPABILITY_MAP.shutdown(); if (testPath != null) { new File(testPath).delete(); } SCREEN_CAPTURE.stop(); } } private void mergeReports(@NotNull final String reportDirectory) { checkArgument(StringUtils.isNotBlank(reportDirectory)); try { final List<String> reports = new ArrayList<>(); final Iterator<File> iterator = FileUtils.iterateFiles(new File(reportDirectory), new String[]{"xml"}, false); while (iterator.hasNext()) { final File file = iterator.next(); reports.add(file.getAbsolutePath()); } final Optional<String> mergedReport = J_UNIT_REPORT_MERGE.mergeReports(reports); if (mergedReport.isPresent()) { FileUtils.write(new File(reportDirectory + MERGED_REPORT), mergedReport.get()); } } catch (final Exception ex) { LOGGER.error("WEBAPPTESTER-BUG-0002: Could not save merged report", ex); } } /** * @return The feature loader that is to be used for the tests */ private FeatureLoader getFeatureLoader() { final String testSourceFilePath = SYSTEM_PROPERTY_UTILS.getProperty(Constants.TEST_SOURCE_SYSTEM_PROPERTY); if (StringUtils.isBlank(testSourceFilePath)) { throw new RunScriptsException("Test sources directory not specified"); } return new LocalPathFeatureLoaderImpl(); } /** * We run each Cucumber test in a new thread. This improves performance, but also allows us to use a different * configuration for each thread, which means we can connect to BrowserStack and test against a different * browser. */ private class CucumberThread implements Runnable { private final String featuresLocation; private final String reportDirectory; CucumberThread(@NotNull final String reportDirectory, final String featuresLocation) { checkArgument(StringUtils.isNotBlank(reportDirectory)); this.featuresLocation = featuresLocation; this.reportDirectory = reportDirectory; } @Override public void run() { LOGGER.info("CucumberThread.run()"); try { /* Threads might be reused, so the id is shared, but we can set the name to something new each time. */ Thread.currentThread().setName("CucumberThread" + THREAD_COUNT.incrementAndGet()); /* Get the details for this thread */ final ThreadDetails threadDetails = State.THREAD_DESIRED_CAPABILITY_MAP.getDesiredCapabilitiesForThread( Thread.currentThread().getName()); /* These are the arguments we'll pass to the cucumber runner */ final List<String> args = new ArrayList<>(); args.add("--monochrome"); args.add("--plugin"); args.add("json:" + reportDirectory + Thread.currentThread().getName() + ".json"); args.add("--plugin"); args.add("html:" + reportDirectory + Thread.currentThread().getName() + ".html"); args.add("--plugin"); args.add("pretty"); args.add("--plugin"); args.add("pretty:" + reportDirectory + Thread.currentThread().getName() + ".txt"); args.add("--plugin"); args.add("junit:" + reportDirectory + Thread.currentThread().getName() + ".xml"); args.add("--glue"); args.add("au.com.agic.apptesting"); addTags(args, threadDetails); args.add(featuresLocation); LOGGER.info("Executing Cucumber CLI with arguments {}", args); /* Specify the glue command line argument so the Cucumber application can find the steps definitions. */ final byte retValue = cucumber.api.cli.Main.run( args.toArray(new String[args.size()]), Thread.currentThread().getContextClassLoader()); if (retValue != 0) { ++failure; } /* Open the report files */ openReportFiles(reportDirectory); } catch (final Exception ex) { ++failure; LOGGER.error("Failed to run Cucumber test", ex); EXCEPTION_WRITER.saveException(reportDirectory, ex); } finally { ++completed; /* Clean up this web driver so we don't hold windows open */ State.THREAD_DESIRED_CAPABILITY_MAP.shutdown(Thread.currentThread().getName()); } } /** * Scans the supplied directory for html files, which are then opened */ private void openReportFiles(@NotNull final String reportDir) { if (Boolean.parseBoolean(SYSTEM_PROPERTY_UTILS.getProperty(OPEN_REPORT_FILE_SYSTEM_PROPERTY))) { final List<File> files = (List<File>) FileUtils.listFiles( new File(reportDir), TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); files.stream() .filter(e -> e.getName().endsWith(HTML_EXTENSION)) .forEach(e -> DESKTOP_INTERACTION.openWebpage(e.toURI())); } } /** * Tags can be defined against the URL, or overridden with a system property */ private void addTags(@NotNull final List<String> args, @NotNull final ThreadDetails threadDetails) { checkNotNull(args); checkNotNull(threadDetails); final String tagOverride = SYSTEM_PROPERTY_UTILS.getProperty(Constants.TAGS_OVERRIDE_SYSTEM_PROPERTY); final String tagSetToUse = StringUtils.isNotBlank(tagOverride) ? tagOverride : threadDetails.getUrlDetails().getTags(); final List<String> tags = TAG_ANALYSER.convertTagsToList(tagSetToUse); for (final String tag : tags) { args.add("--tags"); args.add(tag); } } } }
package eu.visualize.ini.convnet; import net.sf.jaer.util.TobiLogger; import java.awt.Color; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import com.jogamp.opengl.GL2; import com.jogamp.opengl.GLAutoDrawable; import java.io.IOException; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; import net.sf.jaer.chip.AEChip; import net.sf.jaer.event.EventPacket; import static net.sf.jaer.eventprocessing.EventFilter.log; import net.sf.jaer.eventprocessing.FilterChain; import net.sf.jaer.graphics.MultilineAnnotationTextRenderer; /** * Extends DavisDeepLearnCnnProcessor to add annotation graphics to show * steering decision. * * @author Tobi */ @Description("Displays Visualise steering ConvNet results; subclass of DavisDeepLearnCnnProcessor") @DevelopmentStatus(DevelopmentStatus.Status.Experimental) public class VisualiseSteeringConvNet extends DavisDeepLearnCnnProcessor implements PropertyChangeListener { private static final int LEFT = 0, CENTER = 1, RIGHT = 2, INVISIBLE = 3; // define output cell types volatile private boolean hideSteeringOutput = getBoolean("hideOutput", false); volatile private boolean showAnalogDecisionOutput = getBoolean("showAnalogDecisionOutput", false); volatile private boolean showStatistics = getBoolean("showStatistics", true); private TargetLabeler targetLabeler = null; private Error error = new Error(); // /** This object used to publish the results to ROS */ // public VisualiseSteeringNetRosNodePublisher visualiseSteeringNetRosNodePublisher=new VisualiseSteeringNetRosNodePublisher(); // UDP output to client, e.g. ROS volatile private boolean sendUDPSteeringMessages = getBoolean("sendUDPSteeringMessages", false); volatile private boolean sendOnlyNovelSteeringMessages = getBoolean("sendOnlyNovelSteeringMessages", true); volatile private byte lastUDPmessage = -1; volatile private boolean forceNetworkOutpout = getBoolean("forceNetworkOutpout", false); volatile private int forcedNetworkOutputValue = getInt("forcedNetworkOutputValue", 3); // default is prey invisible output private String host = getString("host", "localhost"); private int remotePort = getInt("remotePort", 13331); private int localPort = getInt("localPort", 15555); private DatagramSocket socket = null; private InetSocketAddress client = null; private DatagramChannel channel = null; private ByteBuffer udpBuf = ByteBuffer.allocate(2); private int seqNum = 0; private int[] decisionArray = new int[2]; private int[] decisionLowPassArray = new int[3]; private int savedDecision = -1; private int counterD = 0; private float[] LCRNstate = new float[]{0.5f, 0.5f, 0.5f, 0.5f}; volatile private boolean apply_LR_RL_constraint = getBoolean("apply_LR_RL_constraint", false); volatile private boolean apply_LNR_RNL_constraint = getBoolean("apply_LNR_RNL_constraint", false); volatile private boolean apply_CN_NC_constraint = getBoolean("apply_CN_NC_constraint", false); volatile private float LCRNstep = getFloat("LCRNstep", 1f); private final TobiLogger descisionLogger = new TobiLogger("Decisions", "Decisions of CNN sent to Predator robot Summit XL"); private final TobiLogger behaviorLogger = new TobiLogger("Behavior", "Behavior of robots as sent back by Predator robot Summit XL"); BehaviorLoggingThread behaviorLoggingThread = new BehaviorLoggingThread(); public VisualiseSteeringConvNet(AEChip chip) { super(chip); String deb = "3. Debug", disp = "1. Display", anal = "2. Analysis"; String udp = "UDP messages"; setPropertyTooltip(disp, "showAnalogDecisionOutput", "Shows output units as analog shading rather than binary. If LCRNstep=1, then the analog CNN output is shown. Otherwise, the lowpass filtered LCRN states are shown."); setPropertyTooltip(disp, "hideSteeringOutput", "hides steering output unit rendering as shading over sensor image. If the prey is invisible no rectangle is rendered when showAnalogDecisionOutput is deselected."); setPropertyTooltip(anal, "pixelErrorAllowedForSteering", "If ground truth location is within this many pixels of closest border then the descision is still counted as corret"); setPropertyTooltip(disp, "showStatistics", "shows statistics of DVS frame rate and error rate (when ground truth TargetLabeler file is loaded)"); setPropertyTooltip(udp, "sendUDPSteeringMessages", "sends UDP packets with steering network output to host:port in hostAndPort"); setPropertyTooltip(udp, "sendOnlyNovelSteeringMessages", "only sends UDP message if it contains a novel command; avoids too many datagrams"); setPropertyTooltip(udp, "host", "hostname or IP address to send UDP messages to, e.g. localhost"); setPropertyTooltip(udp, "remotePort", "destination UDP port address to send UDP messages to, e.g. 13331"); setPropertyTooltip(udp, "localPort", "our UDP port address to recieve UDP messages from robot, e.g. 15555"); setPropertyTooltip(udp, "forcedNetworkOutputValue", "forced value of network output sent to client (0=left, 1=middle, 2=right, 3=invisible)"); setPropertyTooltip(udp, "forceNetworkOutpout", "force (override) network output classification to forcedNetworkOutputValue"); setPropertyTooltip(udp, "apply_LR_RL_constraint", "force (override) network output classification to make sure there is no switching from L to R or viceversa directly"); setPropertyTooltip(udp, "apply_LNR_RNL_constraint", "force (override) network output classification to make sure there is no switching from L to N and to R or viceversa, since the predator will see the prey back from the same last seen steering output (it spins in the last seen direction)"); setPropertyTooltip(udp, "apply_CN_NC_constraint", "force (override) network output classification to make sure there is no switching from C to N or viceversa directly"); setPropertyTooltip(udp, "LCRNstep", "mixture of decisicion outputs over time (LCR or N) to another (if 1, no lowpass filtering, if lower, then slower transitions)"); setPropertyTooltip(udp, "startLoggingUDPMessages", "start logging UDP messages to a text log file"); setPropertyTooltip(udp, "stopLoggingUDPMessages", "stop logging UDP messages"); FilterChain chain = new FilterChain(chip); targetLabeler = new TargetLabeler(chip); // used to validate whether descisions are correct or not chain.add(targetLabeler); setEnclosedFilterChain(chain); apsDvsNet.getSupport().addPropertyChangeListener(DeepLearnCnnNetwork.EVENT_MADE_DECISION, this); descisionLogger.setAbsoluteTimeEnabled(true); descisionLogger.setNanotimeEnabled(false); behaviorLogger.setAbsoluteTimeEnabled(true); behaviorLogger.setNanotimeEnabled(false); // dvsNet.getSupport().addPropertyChangeListener(DeepLearnCnnNetwork.EVENT_MADE_DECISION, this); } @Override public synchronized EventPacket<?> filterPacket(EventPacket<?> in) { targetLabeler.filterPacket(in); EventPacket out = super.filterPacket(in); return out; } public int getPixelErrorAllowedForSteering() { return error.getPixelErrorAllowedForSteering(); } public void setPixelErrorAllowedForSteering(int pixelErrorAllowedForSteering) { error.setPixelErrorAllowedForSteering(pixelErrorAllowedForSteering); } // private Boolean correctDescisionFromTargetLabeler(TargetLabeler targetLabeler, DeepLearnCnnNetwork net) { // if (targetLabeler.getTargetLocation() == null) { // return null; // no location labeled for this time // Point p = targetLabeler.getTargetLocation().location; // if (p == null) { // if (net.outputLayer.maxActivatedUnit == 3) { // return true; // no target seen // } else { // int x = p.x; // int third = (x * 3) / chip.getSizeX(); // if (third == net.outputLayer.maxActivatedUnit) { // return true; // return false; @Override public void resetFilter() { super.resetFilter(); error.reset(); } @Override public synchronized void setFilterEnabled(boolean yes) { super.setFilterEnabled(yes); if (yes && !targetLabeler.hasLocations()) { Runnable r = new Runnable() { @Override public void run() { targetLabeler.loadLastLocations(); } }; SwingUtilities.invokeLater(r); } if (yes && sendUDPSteeringMessages) { try { openChannel(); } catch (IOException ex) { log.warning("Caught exception when trying to open datagram channel to host:port - " + ex); } } if (!yes) { closeChannel(); } } @Override public void annotate(GLAutoDrawable drawable) { super.annotate(drawable); targetLabeler.annotate(drawable); if (hideSteeringOutput) { return; } GL2 gl = drawable.getGL().getGL2(); checkBlend(gl); int third = chip.getSizeX() / 3; int sy = chip.getSizeY(); if (apsDvsNet != null && apsDvsNet.outputLayer != null && apsDvsNet.outputLayer.activations != null) { drawDecisionOutput(third, gl, sy, apsDvsNet, Color.RED); } // if (dvsNet != null && dvsNet.outputLayer != null && dvsNet.outputLayer.activations != null && isProcessDVSTimeSlices()) { // drawDecisionOutput(third, gl, sy, dvsNet, Color.YELLOW); MultilineAnnotationTextRenderer.resetToYPositionPixels(chip.getSizeY() * .5f); MultilineAnnotationTextRenderer.setScale(.3f); if (showStatistics) { MultilineAnnotationTextRenderer.renderMultilineString(String.format("LCRN states: [L=%6.1f] [C=%6.1f] [R%6.1f] [N=%6.1f]", LCRNstate[0], LCRNstate[1], LCRNstate[2], LCRNstate[3])); MultilineAnnotationTextRenderer.setScale(.3f); if (dvsSubsampler != null) { MultilineAnnotationTextRenderer.renderMultilineString(String.format("DVS subsampler, %d events, inst/avg interval %6.1f/%6.1f ms", getDvsMinEvents(), dvsSubsampler.getLastSubsamplerFrameIntervalUs() * 1e-3f, dvsSubsampler.getFilteredSubsamplerIntervalUs() * 1e-3f)); } if (error.totalCount > 0) { MultilineAnnotationTextRenderer.renderMultilineString(error.toString()); } } // if (totalDecisions > 0) { // float errorRate = (float) incorrect / totalDecisions; // String s = String.format("Error rate %.2f%% (total=%d correct=%d incorrect=%d)\n", errorRate * 100, totalDecisions, correct, incorrect); // MultilineAnnotationTextRenderer.renderMultilineString(s); } private void drawDecisionOutput(int third, GL2 gl, int sy, DeepLearnCnnNetwork net, Color color) { // 0=left, 1=center, 2=right, 3=no target int decision = net.outputLayer.maxActivatedUnit; float r = color.getRed() / 255f, g = color.getGreen() / 255f, b = color.getBlue() / 255f; float[] cv = color.getColorComponents(null); if (showAnalogDecisionOutput) { final float brightness = .3f; // brightness scale for (int i = 0; i < 3; i++) { int x0 = third * i; int x1 = x0 + third; float shade = brightness * chooseOutputToShow(net, i); gl.glColor3f((shade * r), (shade * g), (shade * b)); gl.glRecti(x0, 0, x1, sy); gl.glRecti(x0, 0, x1, sy); } float shade = brightness * chooseOutputToShow(net, 3); // no target gl.glColor3f((shade * r), (shade * g), (shade * b)); gl.glRecti(0, 0, chip.getSizeX(), sy / 8); } else if (decision != INVISIBLE) { int x0 = third * decision; int x1 = x0 + third; float shade = .5f; gl.glColor3f((shade * r), (shade * g), (shade * b)); gl.glRecti(x0, 0, x1, sy); } } // returns either network or lowpass filtered output private float chooseOutputToShow(DeepLearnCnnNetwork net, int i) { if (LCRNstep < 1) { return LCRNstate[i]; } else { return net.outputLayer.activations[i]; } } public void applyConstraints(DeepLearnCnnNetwork net) { int currentDecision = net.outputLayer.maxActivatedUnit; float maxLCRN = 0; int maxLCRNindex = -1; for (int i = 0; i < 4; i++) { if (i == currentDecision) { LCRNstate[i] = LCRNstate[i] + LCRNstep; if (LCRNstate[i] > 1) { LCRNstate[i] = 1; } if (LCRNstate[i] > maxLCRN) { maxLCRN = LCRNstate[i]; maxLCRNindex = i; } } else { LCRNstate[i] = LCRNstate[i] - LCRNstep; if (LCRNstate[i] < 0) { LCRNstate[i] = 0; } if (LCRNstate[i] > maxLCRN) { maxLCRN = LCRNstate[i]; maxLCRNindex = i; } } } net.outputLayer.maxActivatedUnit = maxLCRNindex; if (apply_CN_NC_constraint) {// Cannot switch from C to N and viceversa if (currentDecision == 1 && decisionArray[1] == 3) { net.outputLayer.maxActivatedUnit = 3; } else if (currentDecision == 3 && decisionArray[1] == 1) { net.outputLayer.maxActivatedUnit = 1; } } if (apply_LNR_RNL_constraint) { //Remember last position before going to N, the robot will reappear from there // Possible transition to N (RN or LN) if (currentDecision == 3 && decisionArray[1] == 0) { savedDecision = 0; } else if (currentDecision == 3 && decisionArray[1] == 2) { savedDecision = 2; } // Possible transition back from N (NR or LN) if (savedDecision >= 0) {//Real value saved if (currentDecision == 0 && decisionArray[1] == 3) { if (currentDecision != savedDecision) { net.outputLayer.maxActivatedUnit = 3; } else { savedDecision = -1; } } else if (currentDecision == 2 && decisionArray[1] == 3) { if (currentDecision != savedDecision) { net.outputLayer.maxActivatedUnit = 3; } else { savedDecision = -1; } } } } if (apply_LR_RL_constraint) {// Cannot switch from R to L and viceversa if (currentDecision == 0 && decisionArray[1] == 2) { net.outputLayer.maxActivatedUnit = 2; } else if (currentDecision == 2 && decisionArray[1] == 0) { net.outputLayer.maxActivatedUnit = 0; } } //Update decision decisionArray[0] = decisionArray[1]; decisionArray[1] = net.outputLayer.maxActivatedUnit; } /** * @return the hideSteeringOutput */ public boolean isHideSteeringOutput() { return hideSteeringOutput; } /** * @param hideSteeringOutput the hideSteeringOutput to set */ public void setHideSteeringOutput(boolean hideSteeringOutput) { this.hideSteeringOutput = hideSteeringOutput; putBoolean("hideSteeringOutput", hideSteeringOutput); } /** * @return the showAnalogDecisionOutput */ public boolean isShowAnalogDecisionOutput() { return showAnalogDecisionOutput; } /** * @param showAnalogDecisionOutput the showAnalogDecisionOutput to set */ public void setShowAnalogDecisionOutput(boolean showAnalogDecisionOutput) { this.showAnalogDecisionOutput = showAnalogDecisionOutput; putBoolean("showAnalogDecisionOutput", showAnalogDecisionOutput); } @Override synchronized public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName() != DeepLearnCnnNetwork.EVENT_MADE_DECISION) { super.propertyChange(evt); } else { DeepLearnCnnNetwork net = (DeepLearnCnnNetwork) evt.getNewValue(); if (targetLabeler.isLocationsLoadedFromFile()) { error.addSample(targetLabeler.getTargetLocation(), net.outputLayer.maxActivatedUnit, net.isLastInputTypeProcessedWasApsFrame()); } applyConstraints(net); if (sendUDPSteeringMessages) { if (checkClient()) { // if client not there, just continue - maybe it comes back byte msg = (byte) (forceNetworkOutpout ? forcedNetworkOutputValue : net.outputLayer.maxActivatedUnit); if (!sendOnlyNovelSteeringMessages || msg != lastUDPmessage) { lastUDPmessage=msg; udpBuf.clear(); udpBuf.put((byte) (seqNum & 0xFF)); // mask bits to cast to unsigned byte value 0-255 seqNum++; if (seqNum > 255) { seqNum = 0; } udpBuf.put(msg); String s = String.format("%d\t%d", lastProcessedEventTimestamp, net.outputLayer.maxActivatedUnit); descisionLogger.log(s); try { // log.info("sending buf="+buf+" to client="+client); // log.info("sending seqNum=" + seqNum + " with msg=" + msg); udpBuf.flip(); int numBytesSent = channel.send(udpBuf, client); if (numBytesSent != 2) { log.warning("only sent " + numBytesSent); } } catch (IOException e) { log.warning("Exception trying to send UDP datagram to ROS: " + e); } } } } } } /** * @return the sendUDPSteeringMessages */ public boolean isSendUDPSteeringMessages() { return sendUDPSteeringMessages; } /** * @param sendUDPSteeringMessages the sendUDPSteeringMessages to set */ synchronized public void setSendUDPSteeringMessages(boolean sendUDPSteeringMessages) { this.sendUDPSteeringMessages = sendUDPSteeringMessages; putBoolean("sendUDPSteeringMessages", sendUDPSteeringMessages); if (sendUDPSteeringMessages) { try { openChannel(); } catch (IOException ex) { log.warning("Caught exception when trying to open datagram channel to host:port - " + ex); } } else { closeChannel(); } } /** * @return the host */ public String getHost() { return host; } /** * @param host the host to set */ public void setHost(String host) { try { InetAddress udpAddress = InetAddress.getByName(host); } catch (UnknownHostException e) { log.warning("can't find " + host + ": caught " + e); JOptionPane.showMessageDialog(chip.getAeViewer().getFilterFrame(), e.toString(), "Bad host for UDP steering messages", JOptionPane.WARNING_MESSAGE); return; } this.host = host; putString("host", host); } /** * @return the remotePort */ public int getRemotePort() { return remotePort; } /** * @param remotePort the remotePort to set */ public void setRemotePort(int remotePort) { this.remotePort = remotePort; putInt("remotePort", remotePort); } private class Error { int totalCount, totalCorrect, totalIncorrect; int[] correct = new int[4], incorrect = new int[4], count = new int[4]; protected int pixelErrorAllowedForSteering = getInt("pixelErrorAllowedForSteering", 10); int dvsTotalCount, dvsCorrect, dvsIncorrect; int apsTotalCount, apsCorrect, apsIncorrect; char[] outputChars = {'L', 'M', 'R', 'I'}; public Error() { reset(); } void reset() { totalCount = 0; totalCorrect = 0; totalIncorrect = 0; Arrays.fill(correct, 0); Arrays.fill(incorrect, 0); Arrays.fill(count, 0); dvsTotalCount = 0; dvsCorrect = 0; dvsIncorrect = 0; apsTotalCount = 0; apsCorrect = 0; apsIncorrect = 0; } void addSample(TargetLabeler.TargetLocation gtTargetLocation, int descision, boolean apsType) { totalCount++; if (apsType) { apsTotalCount++; } else { dvsTotalCount++; } int third = chip.getSizeX() / 3; if (gtTargetLocation != null && gtTargetLocation.location != null) { // we have a location that is not null for the target int x = (int) Math.floor(gtTargetLocation.location.x); int gtDescision = x / third; if (gtDescision < 0 || gtDescision > 3) { return; // bad descision output, should not happen } count[gtDescision]++; if (gtDescision == descision) { correct[gtDescision]++; totalCorrect++; if (apsType) { apsCorrect++; } else { dvsCorrect++; } } else if (getPixelErrorAllowedForSteering() == 0) { incorrect[gtDescision]++; totalIncorrect++; if (apsType) { apsIncorrect++; } else { dvsIncorrect++; } } else { boolean wrong = true; // might be error but maybe not if the descision is e.g. to left and the target location is just over the border to middle float gtX = gtTargetLocation.location.x; if (descision == LEFT && gtX < third + pixelErrorAllowedForSteering) { wrong = false; } else if (descision == CENTER && gtX >= third - pixelErrorAllowedForSteering && gtX <= 2 * third + pixelErrorAllowedForSteering) { wrong = false; } else if (descision == RIGHT && gtX >= 2 * third - pixelErrorAllowedForSteering) { wrong = false; } if (wrong) { incorrect[gtDescision]++; totalIncorrect++; if (apsType) { apsIncorrect++; } else { dvsIncorrect++; } } } } else { // no target in ground truth (prey out of view) count[INVISIBLE]++; if (descision == INVISIBLE) { correct[INVISIBLE]++; totalCorrect++; if (apsType) { apsCorrect++; } else { dvsCorrect++; } } else { incorrect[INVISIBLE]++; totalIncorrect++; if (apsType) { apsIncorrect++; } else { dvsIncorrect++; } } } } @Override public String toString() { // if (targetLabeler.hasLocations() == false) { // return "Error: No ground truth target locations loaded"; if (totalCount == 0) { return "Error: no samples yet"; } StringBuilder sb = new StringBuilder("Error rates: "); sb.append(String.format(" Total=%.1f%% (%d/%d) \n(", (100f * totalIncorrect) / totalCount, totalIncorrect, totalCount)); for (int i = 0; i < 4; i++) { if (count[i] == 0) { sb.append(String.format("%c: 0/0 ", outputChars[i])); } else { sb.append(String.format("%c: %.1f%% (%d) ", outputChars[i], (100f * incorrect[i]) / count[i], count[i])); } } sb.append(String.format("\naps=%.1f%% (%d/%d) dvs=%.1f%% (%d/%d)", (100f * apsIncorrect) / apsTotalCount, apsIncorrect, apsTotalCount, (100f * dvsIncorrect) / dvsTotalCount, dvsIncorrect, dvsTotalCount)); sb.append(")"); return sb.toString(); } /** * @return the pixelErrorAllowedForSteering */ public int getPixelErrorAllowedForSteering() { return pixelErrorAllowedForSteering; } /** * @param pixelErrorAllowedForSteering the pixelErrorAllowedForSteering * to set */ public void setPixelErrorAllowedForSteering(int pixelErrorAllowedForSteering) { this.pixelErrorAllowedForSteering = pixelErrorAllowedForSteering; putInt("pixelErrorAllowedForSteering", pixelErrorAllowedForSteering); } } /** * returns true if socket exists and is bound */ private boolean checkClient() { if (socket == null) { return false; } try { if (socket.isBound()) { return true; } client = new InetSocketAddress(host, remotePort); // channel.connect(client); // connecting the channel causes some kind of portunavailable error on linux return true; } catch (Exception se) { log.warning("While checking client host=" + host + " port=" + remotePort + " caught " + se.toString()); return false; } } public void openChannel() throws IOException { closeChannel(); channel = DatagramChannel.open(); socket = channel.socket(); // bind to any available remotePort because we will be sending datagrams with included host:remotePort info socket.setTrafficClass(0x10 + 0x08); // low delay log.info("opened channel on local port to send UDP messages to ROS."); } public void closeChannel() { if (socket != null) { log.info("closing local socket " + socket + " to UDP client"); socket.close(); socket = null; } if (channel != null) { try { channel.close(); } catch (IOException ex) { Logger.getLogger(VisualiseSteeringConvNet.class.getName()).log(Level.SEVERE, null, ex); } channel = null; } } /** * @return the forceNetworkOutpout */ public boolean isForceNetworkOutpout() { return forceNetworkOutpout; } /** * @param forceNetworkOutpout the forceNetworkOutpout to set */ public void setForceNetworkOutpout(boolean forceNetworkOutpout) { this.forceNetworkOutpout = forceNetworkOutpout; putBoolean("forceNetworkOutpout", forceNetworkOutpout); } /** * @return the forcedNetworkOutputValue */ public int getForcedNetworkOutputValue() { return forcedNetworkOutputValue; } /** * @param forcedNetworkOutputValue the forcedNetworkOutputValue to set */ public void setForcedNetworkOutputValue(int forcedNetworkOutputValue) { if (forcedNetworkOutputValue < 0) { forcedNetworkOutputValue = 0; } else if (forcedNetworkOutputValue > 3) { forcedNetworkOutputValue = 3; } this.forcedNetworkOutputValue = forcedNetworkOutputValue; putInt("forcedNetworkOutputValue", forcedNetworkOutputValue); } /** * @return the showStatistics */ public boolean isShowStatistics() { return showStatistics; } /** * @param showStatistics the showStatistics to set */ public void setShowStatistics(boolean showStatistics) { this.showStatistics = showStatistics; putBoolean("showStatistics", showStatistics); } /** * @return the LCRNstep */ public float getLCRNstep() { return LCRNstep; } /** * @param LCRNstep the LCRNstep to set */ public void setLCRNstep(float LCRNstep) { if (LCRNstep > 1) { LCRNstep = 1; } else if (LCRNstep < .01) { LCRNstep = 0.01f; } this.LCRNstep = LCRNstep; putFloat("LCRNstep", LCRNstep); } /** * @return the apply_CN_NC_constraint */ public boolean isApply_CN_NC_constraint() { return apply_CN_NC_constraint; } /** * @param apply_CN_NC_constraint the apply_CN_NC_constraint to set */ public void setApply_CN_NC_constraint(boolean apply_CN_NC_constraint) { this.apply_CN_NC_constraint = apply_CN_NC_constraint; putBoolean("apply_CN_NC_constraint", apply_CN_NC_constraint); } /** * @return the apply_LNR_RNL_constraint */ public boolean isApply_LNR_RNL_constraint() { return apply_LNR_RNL_constraint; } /** * @param apply_LNR_RNL_constraint the apply_LNR_RNL_constraint to set */ public void setApply_LNR_RNL_constraint(boolean apply_LNR_RNL_constraint) { this.apply_LNR_RNL_constraint = apply_LNR_RNL_constraint; putBoolean("apply_LNR_RNL_constraint", apply_LNR_RNL_constraint); } /** * @return the apply_LR_RL_constraint */ public boolean isApply_LR_RL_constraint() { return apply_LR_RL_constraint; } /** * @param apply_LR_RL_constraint the apply_LR_RL_constraint to set */ public void setApply_LR_RL_constraint(boolean apply_LR_RL_constraint) { this.apply_LR_RL_constraint = apply_LR_RL_constraint; putBoolean("apply_LR_RL_constraint", apply_LR_RL_constraint); } public void doStartLoggingUDPMessages() { if (isSendUDPSteeringMessages() == false) { JOptionPane.showMessageDialog(chip.getAeViewer().getFilterFrame(), "UDP output is not enabled yet; logging will only occur if sendUDPSteeringMessages is selected"); } if (apsDvsNet != null) { if (!apsDvsNet.networkRanOnce) { JOptionPane.showMessageDialog(chip.getAeViewer().getFilterFrame(), "Network must run at least once to correctly plot kernels (internal variables for indexing are computed at runtime)"); return; } descisionLogger.setEnabled(true); descisionLogger.addComment("network is " + apsDvsNet.getXmlFilename()); descisionLogger.addComment("system.currentTimeMillis lastTimestampUs decisionLCRN"); behaviorLogger.setEnabled(true); behaviorLogger.addComment("network is " + apsDvsNet.getXmlFilename()); behaviorLogger.addComment("system.currentTimeMillis string_message_from_ROS"); if (behaviorLoggingThread != null) { behaviorLoggingThread.closeChannel(); } behaviorLoggingThread = new BehaviorLoggingThread(); behaviorLoggingThread.start(); } } public void doStopLoggingUDPMessages() { if (!descisionLogger.isEnabled()) { log.info("Logging not enabled, no effect"); return; } descisionLogger.setEnabled(false); behaviorLogger.setEnabled(false); behaviorLoggingThread.closeChannel(); behaviorLoggingThread = null; } /** * @return the localPort */ public int getLocalPort() { return localPort; } /** * @param localPort the localPort to set */ public void setLocalPort(int localPort) { this.localPort = localPort; putInt("localPort", localPort); } /** * @return the sendOnlyNovelSteeringMessages */ public boolean isSendOnlyNovelSteeringMessages() { return sendOnlyNovelSteeringMessages; } /** * @param sendOnlyNovelSteeringMessages the sendOnlyNovelSteeringMessages to * set */ public void setSendOnlyNovelSteeringMessages(boolean sendOnlyNovelSteeringMessages) { this.sendOnlyNovelSteeringMessages = sendOnlyNovelSteeringMessages; putBoolean("sendOnlyNovelSteeringMessages", sendOnlyNovelSteeringMessages); } private class BehaviorLoggingThread extends Thread { // private DatagramSocket socket = null; private InetSocketAddress localSocketAddress = null; private DatagramChannel channel = null; private ByteBuffer udpBuf = ByteBuffer.allocate(16); private int seqNum = 0; boolean keepRunning = true; int expectedSeqNum = 0; @Override public void run() { try { openChannel(); while (keepRunning) { udpBuf.clear(); SocketAddress address = channel.receive(udpBuf); if (udpBuf.limit() == 0) { continue; } seqNum = (int) (udpBuf.get(0)); if (seqNum != expectedSeqNum) { log.warning(String.format("dropped %d packets from %s", (seqNum - expectedSeqNum), address.toString())); } behaviorLogger.log(Byte.toString(udpBuf.get(1))); } closeChannel(); } catch (Exception ex) { log.warning(ex.toString()); } } private void openChannel() throws IOException { closeChannel(); keepRunning = true; channel = DatagramChannel.open(); localSocketAddress = new InetSocketAddress("192.168.1.161", localPort); channel.bind(localSocketAddress); log.info("opened channel on local port " + localSocketAddress + " to receive UDP messages from ROS."); } public void closeChannel() { keepRunning = false; if (channel != null) { log.info("closing local channel " + localSocketAddress + " from UDP client"); try { channel.close(); channel = null; } catch (IOException ex) { Logger.getLogger(VisualiseSteeringConvNet.class.getName()).log(Level.SEVERE, null, ex); } } } } }
package br.com.caelum.parsac.modelo; import java.util.ArrayList; import java.util.List; import br.com.caelum.parsac.util.SecaoConverter; import com.thoughtworks.xstream.annotations.XStreamAlias; import com.thoughtworks.xstream.annotations.XStreamConverter; @XStreamAlias("secao") @XStreamConverter(SecaoConverter.class) public class Secao { private int numero; private String titulo; private String explicacao; private List<Aberto> exerciciosAbertos = new ArrayList<Aberto>(); private List<MultiplaEscolha> exerciciosMultiplaEscolhas = new ArrayList<MultiplaEscolha>(); public Secao() { } public Secao(int numero, String titulo, String explicacao, List<Exercicio> exercicios) { this.numero = numero; this.titulo = titulo; this.explicacao = explicacao; } public int getNumero() { return numero; } public String getTitulo() { return titulo; } public String getExplicacao() { return explicacao; } public void setNumero(int numero) { this.numero = numero; } public void setTitulo(String titulo) { this.titulo = titulo; } public void setExplicacao(String explicacao) { this.explicacao = explicacao; } public List<Aberto> getExerciciosAbertos() { return exerciciosAbertos; } public void setExerciciosAbertos(List<Aberto> exerciciosAbertos) { this.exerciciosAbertos = exerciciosAbertos; } public List<MultiplaEscolha> getExerciciosMultiplaEscolhas() { return exerciciosMultiplaEscolhas; } public void setExerciciosMultiplaEscolhas(List<MultiplaEscolha> exerciciosMultiplaEscolhas) { this.exerciciosMultiplaEscolhas = exerciciosMultiplaEscolhas; } public String toString() { return "Seção " + this.numero + ": " + this.titulo + "\n" + this.explicacao + "\n\n" + this.exerciciosAbertos; } }
package eu.ydp.empiria.player.client.module; public enum ModuleTagName { DIV("div"), GROUP("group"), SPAN("span"), TEXT_INTERACTION("textInteraction"), IMG("img"), CHOICE_INTERACTION("choiceInteraction"), SELECTION_INTERACTION("selectionInteraction"), IDENTYFICATION_INTERACTION("identificationInteraction"), TEXT_ENTRY_INTERACTION("textEntryInteraction"), INLINE_CHOICE_INTERACTION("inlineChoiceInteraction"), SIMPLE_TEXT("simpleText"), AUDIO_PLAYER("audioPlayer"), MATH_TEXT("mathText"), MATH_INTERACTION("mathInteraction"), OBJECT("object"), SLIDESHOW_PLAYER("slideshowPlayer"), PROMPT("prompt"), TABLE("table"), PAGE_IN_PAGE("pageInPage"), SHAPE("shape"), INFO("info"), REPORT("report"), LINK("link"), NEXT_ITEM_NAVIGATION("nextItemNavigation"), PREV_ITEM_NAVIGATION("prevItemNavigation"), PAGES_SWITCH_BOX("pagesSwitchBox"), MARK_ALL_BUTTON("markAllButton"), SHOW_ANSWERS_BUTTON("showAnswersButton"), RESET_BUTTON("resetButton"), SUB("sub"), SUP("sup"), FLASH("flash"), AUDIO_MUTE_BUTTON("feedbackAudioMuteButton"),MEDIA_PLAY_PAUSE_BUTTON("mediaPlayPauseButton"),MEDIA_STOP_BUTTON("mediaStopButton"),MEDIA_MUTE_BUTTON("mediaMuteButton"), MEDIA_PROGRESS_BAR("mediaProgressBar"),MEDIA_VOLUME_BAR("mediaVolumeBar"),MEDIA_FULL_SCREEN_BUTTON("mediaFullScreenButton"), MEDIA_POSITION_IN_STREAM("mediaPositinInStream"),MEDIA_CURRENT_TIME("mediaCurrentTime"),MEDIA_TOTAL_TIME("mediaTotalTime"), MEDIA_TITLE("mediaTitle"), MEDIA_DESCRIPTION("mediaDescription"), MEDIA_SCREEN("mediaScreen"), SIMULATION_PLAYER("simulationPlayer"), MEDIA_TEXT_TRACK("mediaTextTrack"), MATCH_INTERACTION("matchInteraction"); String name = null; private ModuleTagName(String name){ this.name = name; } public String tagName(){ return name; } public static ModuleTagName getTag(String name){ for(ModuleTagName tag : ModuleTagName.values()){ if(tag.name.equals(name)){ return tag; } } return null; } @Override public String toString() { return name; } }
package br.fameg.edu.view; import br.fameg.edu.domain.model.*; import br.fameg.edu.domain.repositories.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(value = "/coordenadores", consumes = "application/json", produces = "application/json") public class CoordenadorView { private @Autowired DadosPessoaisRepository dadosPessoaisRepository; private @Autowired CoordenadorRepository coordenadorRepository; private @Autowired DisciplinaRepository disciplinaRepository; private @Autowired ProfessorRepository professorRepository; private @Autowired AlunoRepository alunoRepository; private @Autowired TurmaRepository turmaRepository; @PostMapping public @ResponseBody Coordenador addCoordenador(@RequestBody Coordenador payload) { return coordenadorRepository.save(payload); } @GetMapping public @ResponseBody Iterable<Coordenador> getAll() { return coordenadorRepository.findAll(); } @GetMapping(value = "/{id}") public @ResponseBody Coordenador getOne(@PathVariable("id") Long id) { return coordenadorRepository.findOne(id); } @PutMapping(value = "/{id}") public @ResponseBody Coordenador updateCoordenador(@PathVariable("id") Long id, @RequestBody Coordenador payload) { return coordenadorRepository.save(payload); } @DeleteMapping("/{id}") public void deleteCoordenador(@PathVariable("id") Long id) { coordenadorRepository.delete(id); } @PostMapping("/{id}/aluno") public @ResponseBody Aluno criarAluno(@RequestBody Aluno aluno) { if(dadosPessoaisRepository.findByCpf(aluno.getDadosPessoais().getCpf()) == null) dadosPessoaisRepository.save(aluno.getDadosPessoais()); return alunoRepository.save(aluno); } @DeleteMapping("/{id}/aluno/{alunoId}") public void removerAluno(@PathVariable("alunoId") Long alunoId) { alunoRepository.delete(alunoId); } @PostMapping("/{id}/professor") public @ResponseBody Professor addProfessor(@RequestBody Professor payload) { return professorRepository.save(payload); } @GetMapping("/{id}/professor") public @ResponseBody Iterable<Professor> getProfessores() { return professorRepository.findAll(); } @GetMapping("/{id}/professor/{professorId}") public @ResponseBody Professor getProfessor(@PathVariable("professorId") Long professorId) { return professorRepository.findOne(professorId); } @PutMapping("/{id}/professor/{professorId}") public @ResponseBody Professor updateProfessor(@RequestBody Professor payload) { return professorRepository.save(payload); } @DeleteMapping("/{id}/professor/{professorId}") public void deleteProfessor(@PathVariable("professorId") Long professorId) { professorRepository.delete(professorId); } @PostMapping("/{id}/turma") public @ResponseBody Turma criarTurma(@RequestBody Turma turma) { return turmaRepository.save(turma); } @GetMapping("/{id}/turma") public @ResponseBody Iterable<Turma> getTurmas() { return turmaRepository.findAll(); } @GetMapping("/{id}/turma/{turmaId}") public @ResponseBody Turma getTurma(@PathVariable("turmaId") Long turmaId) { return turmaRepository.findOne(turmaId); } @PutMapping("/{id}/turma/{turmaId}") public @ResponseBody Turma updateTurma(@RequestBody Turma payload) { return turmaRepository.save(payload); } @DeleteMapping("/{id}/turma/{turmaId}") public void deleteTurma(@PathVariable("id") Long id) { turmaRepository.delete(id); } @PostMapping("/{id}/disciplina") public @ResponseBody Disciplina addDisciplina(@RequestBody Disciplina payload) { return disciplinaRepository.save(payload); } @GetMapping("/{id}/disciplina") public @ResponseBody Iterable<Disciplina> getDisciplinas() { return disciplinaRepository.findAll(); } @GetMapping("/{id}/disciplina/{disciplinaId}") public @ResponseBody Disciplina getDisciplina(@PathVariable("disciplinaId") Long disciplinaId) { return disciplinaRepository.findOne(disciplinaId); } @PutMapping("/{id}/disciplina/{disciplinaId}") public @ResponseBody Disciplina updateDisciplina(@RequestBody Disciplina payload) { return disciplinaRepository.save(payload); } @DeleteMapping("/{id}/disciplina/{disciplinaId}") public void deleteDisciplina(@PathVariable("disciplinaId") Long disciplinaId) { disciplinaRepository.delete(disciplinaId); } }
package ch.ethz.globis.tinspin; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Random; import ch.ethz.globis.phtree.PhTreeHelper; import ch.ethz.globis.tinspin.TestStats.IDX; import ch.ethz.globis.tinspin.TestStats.TST; import ch.ethz.globis.tinspin.data.AbstractTest; import ch.ethz.globis.tinspin.data.TestPoint; import ch.ethz.globis.tinspin.data.TestRectangle; import ch.ethz.globis.tinspin.util.JmxTools; import ch.ethz.globis.tinspin.util.MemTools; import ch.ethz.globis.tinspin.util.TestPerf; import ch.ethz.globis.tinspin.wrappers.Candidate; import ch.ethz.globis.tinspin.wrappers.PointPHCCTree; /** * Main test runner class. * The test runner can be executed directly or remotely in a separate * process via the TestManager. * * @author Tilmann Zaeschke */ public class TestRunner { private static final SimpleDateFormat FT = new SimpleDateFormat ("yyyy-MM-dd' 'HH:mm:ss"); private static final boolean DEBUG = PhTreeHelper.DEBUG; public static boolean USE_NEW_QUERIES = true; public static long minimumMS = 2000; private final TestStats S; private Random R; private double[] data; private Candidate tree; private AbstractTest test = null; public static void main(String[] args) { //-Xmx28G -XX:+UseConcMarkSweepGC -Xprof -XX:MaxInlineSize=0 -XX:FreqInlineSize=0 -XX:+UnlockDiagnosticVMOptions -XX:+PrintInlining //-XX:+PrintHeapAtGC - Prints detailed GC info including heap occupancy before and after GC //-XX:+PrintTenuringDistribution - Prints object aging or tenuring information if (args.length > 0) { runWithArgs(args); return; } final int DIM = 3; final int N = 1*1000*1000; //TestStats s0 = new TestStats(TST.CLUSTER, IDX.QTZ, N, DIM, true, 5); //TestStats s0 = new TestStats(TST.CUBE, IDX.QTZ, N, DIM, true, 1.0); //TestStats s0 = new TestStats(TST.OSM, IDX.PHC, N, 2, true, 1.0); //TestStats s0 = new TestStats(TST.CUBE, IDX.PHC, N, DIM, true, 1.0E-5); TestStats s0 = new TestStats(TST.CLUSTER, IDX.QT2Z, N, DIM, false, 5.0); //TestStats s0 = new TestStats(TST.CUBE, IDX.PHC, N, DIM, false, 1.0); //TestStats s0 = new TestStats(TST.OSM, IDX.QT2Z, N, 2, false, 1.0); //s0.cfgWindowQueryRepeat = 1000; //s0.cfgPointQueryRepeat = 1000000; //s0.cfgUpdateSize = 1000; //s0.cfgWindowQuerySize = 1; //s0.cfgWindowQueryRepeat = 10_000; //s0.cfgWindowQuerySize = 1; //s0.cfgKnnQueryBaseRepeat = 1000_000; //s0.cfgWindowQuerySize = 10000; //s0.cfgWindowQueryRepeat = 10000; s0.setSeed(0); TestRunner test = new TestRunner(s0); TestStats s = test.run(); System.out.println(s); //System.out.println(BitsLong.POOL.print()); // System.out.println("AMM: " + PhIteratorNoGC.AMM1 + " / " + PhIteratorNoGC.AMM2 + " / " + PhIteratorNoGC.AMM3 + " / " + PhIteratorNoGC.AMM4 + " / " + PhIteratorNoGC.AMM5 + " / "); // System.out.println("VMM: " + PhIteratorNoGC.VMM1 + " / " + PhIteratorNoGC.VMM2 + " / " + PhIteratorNoGC.VMM3); // System.out.println("HCI-A/L/N: " + PhIteratorNoGC.HCIA + " / " + PhIteratorNoGC.HCIL + " / " + PhIteratorNoGC.HCIN); } private static void runWithArgs(String[] args) { if (args.length < 4) { System.out.println("ERROR: At least 4 arguments required, found: " + args.length); System.out.println("Example: TestRunner CUBE PHC 1000000 3 <true/false> " + "<1.0/3.4/3.5/...> <0/1/2/...>"); System.out.println("Example: TestRunner [TEST] [INDEX] [SIZE] [DIM] " + "[BOXES=false] [param=1.0] [random seed=0]"); return; } TST tst; try { tst = TST.valueOf(args[0]); } catch (IllegalArgumentException e) { System.out.println("Test not recognised: " + args[0]); System.out.print("Please choose one of: "); for (TST t: TST.values()) { System.out.print(t.name() + ", "); } return; } IDX idx; try { idx = IDX.valueOf(args[1]); } catch (IllegalArgumentException e) { System.out.println("Index not recognised: " + args[0]); System.out.print("Please choose one of: "); for (IDX t: IDX.values()) { System.out.print(t.name() + ", "); } return; } int n = Integer.parseInt(args[2]); int dim = Integer.parseInt(args[3]); boolean box = args.length > 4 ? Boolean.parseBoolean(args[4]) : false; double param0 = args.length > 5 ? Double.parseDouble(args[5]) : 1.0; int seed = args.length > 6 ? Integer.parseInt(args[6]) : 0; TestStats s0 = new TestStats(tst, idx, n, dim, box, param0); s0.setSeed(seed); TestRunner test = new TestRunner(s0); TestStats s = test.run(); System.out.println(s); return; } public TestRunner(TestStats S) { this.S = S; this.R = new Random(S.seed); } public TestStats run() { JmxTools.startUp(); //load resetR(); load(S); // if (!false) { // TestDraw.draw(data, 2); // return S; // int resolution = 10000; // for (int d = 0; d < S.cfgNDims; d++) { // int[] histo = new int[resolution]; // for (int i = d; i < S.cfgNEntries; i+=S.cfgNDims) { // double dat = data[i]; // histo[(int)(dat*resolution)]++; // System.out.println("histo(d=" + d + "): " + Arrays.toString(histo)); //window queries if (tree.supportsWindowQuery()) { resetR(); repeatQuery(S.cfgWindowQueryRepeat, 0); repeatQuery(S.cfgWindowQueryRepeat, 1); S.assortedInfo += " WINDOW_RESULTS=" + S.cfgWindowQuerySize; } else { System.err.println("WARNING: window queries disabled"); } //point queries. if (tree.supportsPointQuery()) { resetR(); repeatPointQuery(S.cfgPointQueryRepeat, 0); repeatPointQuery(S.cfgPointQueryRepeat, 1); } else { System.err.println("WARNING: point queries disabled"); } //kNN queries if (tree.supportsKNN()) { int repeat = getKnnRepeat(S.cfgNDims); S.assortedInfo += " KNN_REPEAT=" + repeat; resetR(12345); repeatKnnQuery(repeat, 0, 1); repeatKnnQuery(repeat, 1, 1); repeatKnnQuery(repeat, 0, 10); repeatKnnQuery(repeat, 1, 10); } else { System.err.println("WARNING: kNN queries disabled"); } //update if (tree.supportsUpdate()) { S.assortedInfo += " UPD_DIST=" + test.maxUpdateDistance(); resetR(); update(0); update(1); } else { System.err.println("WARNING: update() disabled"); } //unload if (tree.supportsUnload()) { unload(); } else { System.err.println("WARNING: unload() disabled"); } if (tree != null) { tree.release(); } return S; } /** * This method sets the random seed to the default seed plus a given delta. * This solves the problem that, for example, the kNN generator * would generate the same points as the data generator, which * resulted in 0.0 distance for all queried points. * @param delta */ private void resetR(int delta) { R.setSeed(S.seed + delta); } private void resetR() { R.setSeed(S.seed); } private int getKnnRepeat(int dims) { if (S.TEST == TestStats.TST.CLUSTER && S.cfgNDims > 5 ) { S.cfgKnnQueryBaseRepeat /= 10;//100; } if (dims <= 3) { return S.cfgKnnQueryBaseRepeat; } if (dims <= 6) { return S.cfgKnnQueryBaseRepeat/10; } if (dims <= 10) { return S.cfgKnnQueryBaseRepeat/10; } return S.cfgKnnQueryBaseRepeat/50; } private void load(TestStats ts) { log(time() + "generating data ..."); long t1g = System.currentTimeMillis(); if (ts.isRangeData) { test = TestRectangle.create(R, ts); } else { test = TestPoint.create(R, ts); } switch (ts.TEST) { case CUBE: case CLUSTER: case CSV: case OSM: case TIGER: case TOUCH: case VORTEX: { data = test.generate(); break; } //case ASPECT: case MBR_SIZE: { //IS_POINT_DATA = PR_TestSize.generate(R, cfgDataLen, N, DIM, 0.001f); //IS_POINT_DATA = PR_TestSize.generate(R, cfgDataLen, N, DIM, 0.02f); //data = PR_TestAspect.generate(R, cfgDataLen, N, DIM, 1e3f);//10.0f); data = test.generate(); if (!ts.isRangeData) throw new IllegalStateException(); break; } case CUSTOM: { if (S.testClass == null) throw new RuntimeException("No dataset class passed (null)"); try { // Note: a custom Test class MUST have an empty constructor test = S.testClass.getDeclaredConstructor().newInstance(); data = test.generate(); break; } catch (Exception e) { throw new RuntimeException("Failed to generate custom dataset.", e); } } default: throw new UnsupportedOperationException("No data for: " + ts.TEST.name()); } long t2g = System.currentTimeMillis(); log("data generation finished in: " + (t2g-t1g)); S.statTGen = t2g-t1g; int dims = S.cfgNDims; int N = S.cfgNEntries; long memTree = MemTools.getMemUsed(); if (ts.paramEnforceGC) { MemTools.cleanMem(N, memTree); } //load index log(time() + "loading index ..."); memTree = MemTools.getMemUsed(); JmxTools.reset(); long t1 = System.currentTimeMillis(); tree = ts.createTree(); tree.load(data, dims); long t2 = System.currentTimeMillis(); S.statGcDiffL = JmxTools.getDiff(); S.statGcTimeL = JmxTools.getTime(); log("loading finished in: " + (t2-t1)); if (ts.paramEnforceGC) { S.statSjvmF = MemTools.cleanMem(N, memTree); } S.statSjvmE = S.statSjvmF / N; S.statTLoad = t2-t1; S.statPSLoad = (long) (N*1000)/(t2-t1); if (ts.INDEX == IDX.PHCC) { // TODO: add pht-cpp statistics collection // memory usage S.statSjvmF = ((PointPHCCTree)tree).getMemoryUsage(); S.statSjvmE = S.statSjvmF / N; } tree.getStats(S); S.assortedInfo += tree.toString(); //This avoid premature garbage collection... log("loaded objects: " + N + " " + data[0]); } private void repeatQuery(int repeat, int round) { int dims = S.cfgNDims; log("N=" + S.cfgNEntries); log(time() + "querying index ... repeat = " + repeat); double[][] lower = new double[repeat][dims]; double[][] upper = new double[repeat][dims]; test.generateWindowQueries(lower, upper); long t00 = System.currentTimeMillis(); int n; long t1, t2; do { JmxTools.reset(); t1 = System.currentTimeMillis(); n = 0; if (tree.supportsWindowQuery()) { n = repeatQueries(lower, upper); } else { n = -1; } t2 = System.currentTimeMillis(); logNLF("*"); } while (System.currentTimeMillis() - t00 < minimumMS); log("Query time: " + (t2-t1) + " ms -> " + (t2-t1)/(double)repeat + " ms/q -> " + (t2-t1)*1000*1000/(double)n + " ns/q/r (n=" + n + ")"); if (round == 0) { S.statTq1 = (t2-t1); S.statTq1E = (long) ((t2-t1)*1000*1000/(double)n); S.statPSq1 = (long) (repeat*1000)/(t2-t1); S.statNq1 = n; } else { S.statTq2 = (t2-t1); S.statTq2E = (long) ((t2-t1)*1000*1000/(double)n); S.statPSq2 = (long) (repeat*1000)/(t2-t1); S.statNq2 = n; } S.statGcDiffWq = JmxTools.getDiff(); S.statGcTimeWq = JmxTools.getTime(); } private void repeatPointQuery(int repeat, int round) { log(time() + "point queries ..."); //prepare query //TODO return only double[], convert inside query function! double[][] qDA = preparePointQuery(repeat); Object q = tree.preparePointQuery(qDA); long t00 = System.currentTimeMillis(); int n; long t1, t2; do { JmxTools.reset(); //query t1 = System.currentTimeMillis(); n = tree.pointQuery(q); t2 = System.currentTimeMillis(); logNLF("*"); } while (System.currentTimeMillis() - t00 < minimumMS); log("Elements found: " + n + " -> " + n/(double)repeat); log("Query time: " + (t2-t1) + " ms -> " + (t2-t1)/(double)repeat + " ms/q -> " + (t2-t1)*1000*1000/(double)repeat + " ns/q"); if (round == 0) { S.statTqp1 = (t2-t1); S.statTqp1E = (long) ((t2-t1)*1000*1000/(double)repeat); S.statPSqp1 = (long) (repeat*1000)/(t2-t1); S.statNqp1 = n; } else { S.statTqp2 = (t2-t1); S.statTqp2E = (long) ((t2-t1)*1000*1000/(double)repeat); S.statPSqp2 = (long) (repeat*1000)/(t2-t1); S.statNqp2 = n; } S.statGcDiffPq = JmxTools.getDiff(); S.statGcTimePq = JmxTools.getTime(); } private double[][] preparePointQuery(int repeat) { int dims = S.cfgNDims; double[][] qA; if (!S.isRangeData) { qA = new double[repeat][]; for (int i = 0; i < repeat; i++) { qA[i] = generateQueryPointD(S.cfgNEntries, dims); } } else { qA = new double[repeat*2][]; for (int i = 0; i < repeat; i++) { double[] lo = new double[dims]; double[] hi = new double[dims]; generateQueryPointDRect(lo, hi, S.cfgNEntries, dims); qA[2*i] = lo; qA[2*i+1] = hi; } } return qA; } private void repeatKnnQuery(int repeat, int round, int k) { log(time() + "kNN queries ..."); //prepare query double[][] q = prepareKnnQuery(repeat); long t00 = System.currentTimeMillis(); long t1, t2; double dist; do { JmxTools.reset(); //query dist = 0; t1 = System.currentTimeMillis(); for (int i = 0; i < repeat; i++) { dist += tree.knnQuery(k, q[i]); } t2 = System.currentTimeMillis(); logNLF("*"); } while (System.currentTimeMillis() - t00 < minimumMS); double avgDist = dist/repeat/k; log("Element distance: " + dist + " -> " + avgDist); log("kNN query time (repeat=" + repeat + "): " + (t2-t1) + " ms -> " + (t2-t1)/(double)repeat + " ms/q -> " + (t2-t1)*1000*1000/(double)(k*repeat) + " ns/q/r"); if (k == 1) { if (round == 0) { S.statTqk1_1 = t2-t1; S.statTqk1_1E = (long) ((t2-t1)*1000*1000/(double)repeat); S.statPSqk1_1 = (long) (repeat*1000)/(t2-t1); S.statDqk1_1 = avgDist; } else { S.statTqk1_2 = t2-t1; S.statTqk1_2E = (long) ((t2-t1)*1000*1000/(double)repeat); S.statPSqk1_2 = (long) (repeat*1000)/(t2-t1); S.statDqk1_2 = avgDist; } S.statGcDiffK1 = JmxTools.getDiff(); S.statGcTimeK1 = JmxTools.getTime(); } else { if (round == 0) { S.statTqk10_1 = t2-t1; S.statTqk10_1E = (long) ((t2-t1)*1000*1000/(double)repeat); S.statPSqk10_1 = (long) (repeat*1000)/(t2-t1); S.statDqk10_1 = avgDist; } else { S.statTqk10_2 = t2-t1; S.statTqk10_2E = (long) ((t2-t1)*1000*1000/(double)repeat); S.statPSqk10_2 = (long) (repeat*1000)/(t2-t1); S.statDqk10_2 = avgDist; } S.statGcDiffK10 = JmxTools.getDiff(); S.statGcTimeK10 = JmxTools.getTime(); } } private double[][] prepareKnnQuery(int repeat) { int dims = S.cfgNDims; double[][] qA; if (!S.isRangeData) { qA = new double[repeat][]; for (int i = 0; i < repeat; i++) { qA[i] = generateKnnQueryPointD(dims); } } else { qA = new double[repeat*2][]; for (int i = 0; i < repeat; i++) { double[] lo = new double[dims]; double[] hi = new double[dims]; generateKnnQueryPointDRect(lo, hi, dims); qA[2*i] = lo; qA[2*i+1] = hi; } } return qA; } @SuppressWarnings("unused") private static class Hist implements Comparable<Hist> { long t1, t2, X1, X2, X2f, X3, X3f; long X4, X4pa, X4pb, X4pc, X4sa, X4sb, X4sc; long X0, X2f1, X2f2, X5, X5a, X5b, X5ab; public Hist() { TestPerf.resetStats(); t1 = System.currentTimeMillis(); } void close() { t2 = System.currentTimeMillis(); X0 += TestPerf.STAT_X0; X1 += TestPerf.STAT_X1; X2 += TestPerf.STAT_X2; X2f1 += TestPerf.STAT_X2f1; X2f2 += TestPerf.STAT_X2f2; X3 += TestPerf.STAT_X3; X3f += TestPerf.STAT_X3f; X4 += TestPerf.STAT_X4; X4pa += TestPerf.STAT_X4pa; X4pb += TestPerf.STAT_X4pb; X4pc += TestPerf.STAT_X4pc; X4sa += TestPerf.STAT_X4sa; X4sb += TestPerf.STAT_X4sb; X4sc += TestPerf.STAT_X4sc; X5 += TestPerf.STAT_X5; X5a += TestPerf.STAT_X5a; X5b += TestPerf.STAT_X5b; X5ab += TestPerf.STAT_X5ab; } @Override public int compareTo(Hist o) { return (int) ((t2-t1)-(o.t2-o.t1)); } @Override public String toString() { return "dT=" + (t2-t1) + " X1=" + X1 + " X2=" + X2 + " X2f=" + X2f + " X2f1/f2=" + X2f1 + "/" + X2f2 + " X3=" + X3 + " X3f=" + X3f + " X5=" + X5 + " X5a/b=" + X5a + "/" + X5b; } /** * @param histList histograms * @return summary in String form */ public static String summary(ArrayList<Hist> histList) { Hist sum = new Hist(); for (Hist h: histList) { sum.X0 += h.X0; sum.X1 += h.X1; sum.X2 += h.X2; sum.X2f1 += h.X2f1; sum.X2f2 += h.X2f2; sum.X3 += h.X3; sum.X3f += h.X3f; sum.X5 += h.X5; sum.X5a += h.X5a; sum.X5b += h.X5b; } return sum.toString(); } } private int repeatQueries(double[][] lower, double[][] upper) { int n=0; int mod = lower.length / 100; for (int i = 0; i < lower.length; i++) { n += tree.query(lower[i], upper[i]); if (i%mod == 0) System.out.print('.'); } //System.out.println(); TestRunner.log("n/q=" + n/(double)lower.length); if (DEBUG) { log(TestPerf.toStringOut()); TestPerf.resetStats(); } return n; } static void log(String string) { System.out.println(string); } static void logNLF(String string) { System.out.print(string); } /** * Generates a random cuboid with fixed size=0.1^DIM, for example 0.001 for DIM=2. * @param xyz lower left corner * @param len lengths of edges */ // private void generateQueryCorners(double[] min, double[] max) { // if (test.getTestType() == TST.CLUSTER) { // test.queryCuboid(S.cfgWindowQuerySize, min, max); // return; // } else if (test.getTestType() == TST.TIGER) { // if (test.getTestStats().isRangeData) { // test.queryCuboid(S.cfgWindowQuerySize, min, max); // return; // } else if (test.getTestType() == TST.CUSTOM) { // test.queryCuboid(S.cfgWindowQuerySize, min, max); // return; // if (USE_NEW_QUERIES) { // generateQueryCornersNew(min, max); // } else { // generateQueryCornersOld(min, max); // private void generateQueryCornersOld(double[] min, double[] max) { // int dims = min.length; // //Here is a fixed size version, returning 1% of the space. // //final double qVolume = 0.01 * Math.pow(cfgDataLen, DIM);//(float) Math.pow(0.1, DIM); //0.01 for DIM=2 // final double qVolume = S.cfgWindowQuerySize/(double)S.cfgNEntries * Math.pow(S.cfgDataLen, dims); // int dDrop = R.nextInt(dims); // //query create cube // double[] len = new double[min.length]; // double vol = 1; // for (int d = 0; d < dims; d++) { // if (d == dDrop) { // continue; // len[d] = R.nextDouble()*S.cfgDataLen; // vol *= len[d]; // //create cuboid/box of desired size by dropping random length // len[dDrop] = qVolume/vol; //now the new len creates a rectangle/box of SIZE. // } while (len[dDrop] >= S.cfgDataLen); //drop bad rectangles // //create location // for (int d = 0; d < dims; d++) { // min[d] = R.nextDouble()*(S.cfgDataLen-len[d]); // max[d] = min[d]+len[d]; // if (min[d]+len[d] >= S.cfgDataLen) { // //drop bad rectangles // throw new RuntimeException(); private double[] generateQueryPointD(final int N, final int dims) { double[] xyz = new double[dims]; int pos = R.nextInt(N*2); if (pos >= N) { //randomise for (int d = 0; d < dims; d++) { xyz[d] = test.min(d) + R.nextDouble()*test.len(d); } } else { //get existing element System.arraycopy(data, pos*dims, xyz, 0, dims); } return xyz; } private void generateQueryPointDRect(double[] lo, double[] hi, final int N, final int dims) { int pos = R.nextInt(N*2); if (pos >= N) { //randomise for (int d = 0; d < dims; d++) { lo[d] = test.min(d) + R.nextDouble()*test.len(d); hi[d] = lo[d] + R.nextDouble()*test.len(d)/1000.; } } else { //get existing element System.arraycopy(data, pos*dims*2, lo, 0, dims); System.arraycopy(data, pos*dims*2+dims, hi, 0, dims); } } private double[] generateKnnQueryPointD(final int dims) { double[] xyz = new double[dims]; //randomise for (int d = 0; d < dims; d++) { xyz[d] = test.min(d) + R.nextDouble()*test.len(d); } return xyz; } private void generateKnnQueryPointDRect(double[] lo, double[] hi, final int dims) { //randomise for (int d = 0; d < dims; d++) { lo[d] = test.min(d) + R.nextDouble()*test.len(d); hi[d] = lo[d] + R.nextDouble()*test.len(d)/1000.; } } private void update(int round) { log(time() + "updates ..."); // long t00 = System.currentTimeMillis(); int n; long t; n = 0; t = 0; double[][] u = null; //2 points, 2 versions int nUpdates = S.cfgUpdateSize > S.cfgNEntries/4 ? S.cfgNEntries/4 : S.cfgUpdateSize; for (int i = 0; i < S.cfgUpdateRepeat; i++) { //prepare query u = test.generateUpdates(nUpdates, data, u); JmxTools.reset(); //updates long t1 = System.currentTimeMillis(); n += tree.update(u); long t2 = System.currentTimeMillis(); t += t2-t1; S.statGcDiffUp += JmxTools.getDiff(); S.statGcTimeUp += JmxTools.getTime(); } // logNLF("*"); // } while (System.currentTimeMillis() - t00 < minimumMS); log("Elements updated: " + n + " -> " + n); log("Update time: " + t + " ms -> " + t*1000*1000/(double)n + " ns/update"); if (round == 0) { S.statTu1 = t; S.statTu1E = (long) (t*1000*1000/(double)n); S.statPSu1E = (long) (n*1000)/t; S.statNu1 = n; } else { S.statTu2 = t; S.statTu2E = (long) (t*1000*1000/(double)n); S.statPSu2E = (long) (n*1000)/t; S.statNu2 = n; } } private void unload() { log("Unloading..."); JmxTools.reset(); long t1 = System.currentTimeMillis(); int n = tree.unload(); long t2 = System.currentTimeMillis(); log("Deletion time: " + (t2-t1) + " ms -> " + (t2-t1)*1000*1000/(double)S.cfgNEntries + " ns/q/r"); S.statTUnload = t2-t1; S.statPSUnload = (long) (n*1000)/(t2-t1); S.statGcDiffUl = JmxTools.getDiff(); S.statGcTimeUl = JmxTools.getTime(); if (S.cfgNEntries != n) { System.err.println("Delete N/n: " + S.cfgNEntries + "/" + n); } } public TestStats getTestStats() { return S; } private String time() { return FT.format(new Date()) + " "; } public Candidate getCandidate() { return tree; } }
package cn.net.openid.web; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.openid4java.message.ParameterList; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; import cn.net.openid.Credential; import cn.net.openid.User; import cn.net.openid.dao.DaoFacade; /** * @author Sutra Zhou * */ public class LoginController extends SimpleFormController { private static final Log log = LogFactory.getLog(LoginController.class); private DaoFacade daoFacade; private User check(LoginForm lf) { User user = daoFacade.getUserByUsername(lf.getUsername()); if (user == null) { return null; } List<Credential> credentials = daoFacade.getCredentials(user.getId()); for (Credential c : credentials) { log.debug("Password: " + new String(c.getInfo())); if (new String(c.getInfo()).equals(new String(lf.getPassword() .getBytes()))) { return user; } } return null; } /* * (non-Javadoc) * * @see org.springframework.web.servlet.mvc.BaseCommandController#onBindAndValidate(javax.servlet.http.HttpServletRequest, * java.lang.Object, org.springframework.validation.BindException) */ @Override protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception { LoginForm lf = (LoginForm) command; User user = this.check(lf); if (user == null) { errors.rejectValue("username", "error.login.failed"); } else { HttpSession session = request.getSession(); UserSession userSession = new UserSession(user); userSession.setLoggedIn(true); userSession.setOpenidUrl(this.daoFacade.buildOpenidUrl(lf .getUsername())); session.setAttribute("userSession", userSession); session.setAttribute("cn.net.openid.username", lf.getUsername() .toLowerCase()); session.setAttribute("cn.net.openid.identity", this.daoFacade .buildOpenidUrl(lf.getUsername())); } super.onBindAndValidate(request, command, errors); } /* * (non-Javadoc) * * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.springframework.validation.BindException) */ @SuppressWarnings("unchecked") @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { HttpSession session = request.getSession(); ParameterList pl = (ParameterList) session .getAttribute("parameterlist"); if (pl == null) { return super.onSubmit(request, response, command, errors); } else { response.sendRedirect("provider-authorization"); return null; } } /* * (non-Javadoc) * * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest, * java.lang.Object, org.springframework.validation.Errors) */ @SuppressWarnings("unchecked") @Override protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception { LoginForm form = (LoginForm) command; if (StringUtils.isEmpty(form.getUsername())) { form.setUsername(request.getParameter("username")); } return super.referenceData(request, command, errors); } /** * @param daoFacade * the daoFacade to set */ public void setDaoFacade(DaoFacade daoFacade) { this.daoFacade = daoFacade; } }
package com.cx.client; import com.checkmarx.v7.*; import com.cx.client.dto.CreateScanResponse; import com.cx.client.dto.LocalScanConfiguration; import com.cx.client.dto.ReportType; import com.cx.client.dto.ScanResults; import com.cx.client.exception.CxClientException; import com.cx.client.rest.CxRestClient; import com.cx.client.rest.dto.*; import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.xml.namespace.QName; import javax.xml.ws.BindingProvider; import java.io.File; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; public class CxClientServiceImpl implements CxClientService { private static final Logger log = LoggerFactory.getLogger(CxClientServiceImpl.class); private String sessionId; private CxSDKWebServiceSoap client; private CxRestClient restClient; private String username; private String password; private URL url; private static final QName SERVICE_NAME = new QName("http://Checkmarx.com/v7", "CxSDKWebService"); private static URL WSDL_LOCATION = CxSDKWebService.class.getClassLoader().getResource("WEB-INF/CxSDKWebService.wsdl"); private static String CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADDRESS = "Checkmarx server was not found on the specified address"; private static String SDK_PATH = "/cxwebinterface/sdk/CxSDKWebService.asmx"; private static int generateReportTimeOutInSec = 500; private static int waitForScanToFinishRetry = 5; public CxClientServiceImpl(URL url, String username, String password) throws CxClientException { this.url = url; this.username = username; this.password = password; CxSDKWebService ss = new CxSDKWebService(WSDL_LOCATION, SERVICE_NAME); client = ss.getCxSDKWebServiceSoap(); BindingProvider bindingProvider = (BindingProvider) client; bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url + SDK_PATH); checkServerConnectivity(url); restClient = new CxRestClient(url.toString(), username, password); } private void checkServerConnectivity(URL url) throws CxClientException { try { HttpURLConnection urlConn; URL toCheck = new URL(url + SDK_PATH); urlConn = (HttpURLConnection) toCheck.openConnection(); urlConn.connect(); if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new CxClientException(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADDRESS + ": " + url); } } catch (IOException e) { log.debug(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADDRESS + ": " + url, e); throw new CxClientException(CHECKMARX_SERVER_WAS_NOT_FOUND_ON_THE_SPECIFIED_ADDRESS + ": " + url, e); } } public void loginToServer() throws CxClientException { Credentials credentials = new Credentials(); credentials.setUser(username); credentials.setPass(password); CxWSResponseLoginData res = client.login(credentials, 1099); sessionId = res.getSessionId(); if(sessionId == null) { throw new CxClientException("fail to perform login: " + res.getErrorMessage()); } } public CreateScanResponse createLocalScan(LocalScanConfiguration conf) throws CxClientException { CliScanArgs cliScanArgs = CxPluginHelper.genCliScanArgs(conf); //todo do this (handler) //SourceCodeSettings srcCodeSettings = blah(conf); SourceCodeSettings srcCodeSettings = new SourceCodeSettings(); srcCodeSettings.setSourceOrigin(SourceLocationType.LOCAL); LocalCodeContainer packageCode = new LocalCodeContainer(); packageCode.setFileName(conf.getFileName()); packageCode.setZippedFile(conf.getZippedSources()); srcCodeSettings.setPackagedCode(packageCode); cliScanArgs.setSrcCodeSettings(srcCodeSettings); //todo problem with that if(conf.getFolderExclusions() != null || conf.getFileExclusions() != null) { SourceFilterPatterns filter = new SourceFilterPatterns(); filter.setExcludeFilesPatterns(conf.getFileExclusions()); filter.setExcludeFoldersPatterns(conf.getFolderExclusions()); srcCodeSettings.setSourceFilterLists(filter); } log.info("Sending Scan Request"); CxWSResponseRunID scanResponse = client.scan(sessionId, cliScanArgs); if(!scanResponse.isIsSuccesfull()) { throw new CxClientException("fail to perform scan: " + scanResponse.getErrorMessage()); } log.debug("create scan returned with projectId: {}, runId: {}", scanResponse.getProjectID(), scanResponse.getRunId()); return new CreateScanResponse(scanResponse.getProjectID(), scanResponse.getRunId()); } //todo do this. local/shared scan handler by Class type (localConfig/tfsConfig...) //public abstract SourceCodeSettings blah(BaseScanConfiguration conf); public CreateScanResponse createLocalScanResolveFields(LocalScanConfiguration conf) throws CxClientException { //resolve preset if(conf.getPreset() != null) { long presetId = resolvePresetIdFromName(conf.getPreset()); conf.setPresetId(presetId); if(presetId == 0) { if(conf.isFailPresetNotFound()) { throw new CxClientException("preset: ["+conf.getPreset()+"], not found"); } else { log.warn("preset ["+conf.getPreset()+"] not found. preset set to default."); } } } //resolve preset if(conf.getFullTeamPath() != null) { String groupId = resolveGroupIdFromTeamPath(conf.getFullTeamPath()); conf.setGroupId(groupId); if(groupId == null){ if(conf.isFailTeamNotFound()) { throw new CxClientException("team: ["+conf.getFullTeamPath()+"], not found"); } else { log.warn("team ["+conf.getFullTeamPath()+"] not found. team set to default."); } } } return createLocalScan(conf); } public String resolveGroupIdFromTeamPath(String fullTeamPath) { fullTeamPath = StringUtils.defaultString(fullTeamPath).trim(); CxWSResponseGroupList associatedGroupsList = client.getAssociatedGroupsList(sessionId); if(!associatedGroupsList.isIsSuccesfull()) { log.warn("fail to retrieve group list: ", associatedGroupsList.getErrorMessage()); return null; } List<Group> group = associatedGroupsList.getGroupList().getGroup(); for (Group g: group) { if(fullTeamPath.equalsIgnoreCase(g.getGroupName())){ return g.getID(); } } return null; } public long resolvePresetIdFromName(String presetName) { presetName = StringUtils.defaultString(presetName).trim(); CxWSResponsePresetList presetList = client.getPresetList(sessionId); if(!presetList.isIsSuccesfull()) { log.warn("fail to retrieve preset list: ", presetList.getErrorMessage()); return 0; } List<Preset> preset = presetList.getPresetList().getPreset(); for (Preset p : preset) { if(presetName.equalsIgnoreCase(p.getPresetName())){ return p.getID(); } } return 0; } public void waitForScanToFinish(String runId, ScanWaitHandler<CxWSResponseScanStatus> waitHandler) throws CxClientException { waitForScanToFinish(runId, 0, waitHandler); } public void waitForScanToFinish(String runId, long scanTimeoutInMin, ScanWaitHandler<CxWSResponseScanStatus> waitHandler) throws CxClientException { long timeToStop = (System.currentTimeMillis() / 60000) + scanTimeoutInMin; CurrentStatusEnum currentStatus = null; CxWSResponseScanStatus scanStatus = null; long startTime = System.currentTimeMillis(); waitHandler.onStart(startTime, scanTimeoutInMin); int retry = waitForScanToFinishRetry; while (scanTimeoutInMin <= 0 || (System.currentTimeMillis() / 60000) <= timeToStop) { try { Thread.sleep(10000); //Get status every 10 sec } catch (InterruptedException e) { log.debug("caught exception during sleep", e); } try { scanStatus = client.getStatusOfSingleScan(sessionId, runId); } catch (Exception e) { retry = checkRetry(retry, e.getMessage()); continue; } if(!scanStatus.isIsSuccesfull()) { retry = checkRetry(retry, scanStatus.getErrorMessage()); continue; } retry = waitForScanToFinishRetry; currentStatus = scanStatus.getCurrentStatus(); if(CurrentStatusEnum.FAILED.equals(currentStatus) || CurrentStatusEnum.CANCELED.equals(currentStatus) || CurrentStatusEnum.DELETED.equals(currentStatus) || CurrentStatusEnum.UNKNOWN.equals(currentStatus)) { waitHandler.onFail(scanStatus); throw new CxClientException("scan cannot be completed. status ["+currentStatus.value()+"]."); } if(CurrentStatusEnum.FINISHED.equals(currentStatus)) { waitHandler.onSuccess(scanStatus); return; } waitHandler.onIdle(scanStatus); } if(!CurrentStatusEnum.FINISHED.equals(currentStatus)) { waitHandler.onTimeout(scanStatus); throw new CxClientException("scan has reached the time limit. ("+scanTimeoutInMin+" minutes)."); } } private int checkRetry(int retry, String errorMessage) throws CxClientException { log.debug("fail to get status from scan. retrying ("+ (retry-1) + " tries left). error message: " + errorMessage); retry if(retry <=0) { throw new CxClientException("fail to get status from scan. error message: " + errorMessage); } return retry; } public ScanResults retrieveScanResults(long projectID) throws CxClientException { CxWSResponseProjectScannedDisplayData scanDataResponse = client.getProjectScannedDisplayData(sessionId); if(!scanDataResponse.isIsSuccesfull()) { throw new CxClientException("fail to get scan data: " + scanDataResponse.getErrorMessage()); } List<ProjectScannedDisplayData> scanList = scanDataResponse.getProjectScannedList().getProjectScannedDisplayData(); for (ProjectScannedDisplayData scan : scanList) { if(projectID == scan.getProjectID()) { return CxPluginHelper.genScanResponse(scan); } } throw new CxClientException("no scan data found for projectID ["+projectID+"]"); } public byte[] getScanReport(long scanId, ReportType reportType) throws CxClientException { CxWSReportRequest cxWSReportRequest = new CxWSReportRequest(); cxWSReportRequest.setScanID(scanId); CxWSReportType cxWSReportType = CxWSReportType.valueOf(reportType.name()); cxWSReportRequest.setType(cxWSReportType); CxWSCreateReportResponse createScanReportResponse = client.createScanReport(sessionId, cxWSReportRequest); if(!createScanReportResponse.isIsSuccesfull()) { log.warn("fail to create scan report: " + createScanReportResponse.getErrorMessage()); throw new CxClientException("fail to create scan report: " + createScanReportResponse.getErrorMessage()); } long reportId = createScanReportResponse.getID(); waitForReport(reportId); CxWSResponseScanResults scanReport = client.getScanReport(sessionId, reportId); if(!scanReport.isIsSuccesfull()) { log.debug("fail to create scan report: " + createScanReportResponse.getErrorMessage()); throw new CxClientException("fail to retrieve scan report: " + createScanReportResponse.getErrorMessage()); } return scanReport.getScanResults(); } public void close() { //todo implement } private void waitForReport(long reportId) throws CxClientException { //todo: const+ research of the appropriate time long timeToStop = (System.currentTimeMillis() / 1000) + generateReportTimeOutInSec; CxWSReportStatusResponse scanReportStatus = null; while ((System.currentTimeMillis() / 1000) <= timeToStop) { log.debug("waiting for server to generate pdf report" + (timeToStop - (System.currentTimeMillis() / 1000)) + " sec left to timeout"); try { Thread.sleep(2000); //Get status every 2 sec } catch (InterruptedException e) { log.debug("caught exception during sleep", e); } scanReportStatus = client.getScanReportStatus(sessionId, reportId); if(!scanReportStatus.isIsSuccesfull()) { log.warn("fail to get status from scan report: " + scanReportStatus.getErrorMessage()); } if( scanReportStatus.isIsFailed()) { throw new CxClientException("generation of scan report [id="+reportId+"] failed"); } if(scanReportStatus.isIsReady()) { return; } } if(scanReportStatus == null || !scanReportStatus.isIsReady()) { throw new CxClientException("generation of scan report [id="+reportId+"] failed. timed out"); } } public CreateOSAScanResponse createOSAScan(long projectId, File zipFile) throws CxClientException { restClient.login(); return restClient.createOSAScan(projectId, zipFile); } public OSAScanStatus waitForOSAScanToFinish(String scanId, long scanTimeoutInMin, ScanWaitHandler<OSAScanStatus> waitHandler) throws CxClientException { //re login in case of session timed out restClient.login(); long timeToStop = (System.currentTimeMillis() / 60000) + scanTimeoutInMin; long startTime = System.currentTimeMillis(); OSAScanStatus scanStatus = null; OSAScanStatusEnum status = null; waitHandler.onStart(startTime, scanTimeoutInMin); int retry = waitForScanToFinishRetry; while (scanTimeoutInMin <= 0 || (System.currentTimeMillis() / 60000) <= timeToStop) { try { Thread.sleep(10000); //Get status every 10 sec } catch (InterruptedException e) { log.debug("caught exception during sleep", e); } try { scanStatus = restClient.getOSAScanStatus(scanId); } catch (Exception e) { retry = checkRetry(retry, e.getMessage()); continue; } retry = waitForScanToFinishRetry; status = scanStatus.getStatus(); if(OSAScanStatusEnum.FAILED.equals(status)) { waitHandler.onFail(scanStatus); throw new CxClientException("OSA scan cannot be completed. status ["+status.uiValue()+"]."); } if(OSAScanStatusEnum.FINISHED.equals(status)) { waitHandler.onSuccess(scanStatus); return scanStatus; } waitHandler.onIdle(scanStatus); } if(!OSAScanStatusEnum.FINISHED.equals(status)) { waitHandler.onTimeout(scanStatus); throw new CxClientException("OSA scan has reached the time limit. ("+scanTimeoutInMin+" minutes)."); } return scanStatus; } public OSASummaryResults retrieveOSAScanSummaryResults(long projectId) throws CxClientException { return restClient.getOSAScanSummaryResults(projectId); } public String retrieveOSAScanHtmlResults(long projectId) throws CxClientException { return restClient.getOSAScanHtmlResults(projectId); } public byte[] retrieveOSAScanPDFResults(long projectId) throws CxClientException { return restClient.getOSAScanPDFResults(projectId); } public static int getWaitForScanToFinishRetry() { return waitForScanToFinishRetry; } public static void setWaitForScanToFinishRetry(int waitForScanToFinishRetry) { CxClientServiceImpl.waitForScanToFinishRetry = waitForScanToFinishRetry; } public static int getGenerateReportTimeOutInSec() { return generateReportTimeOutInSec; } public static void setGenerateReportTimeOutInSec(int generateReportTimeOutInSec) { CxClientServiceImpl.generateReportTimeOutInSec = generateReportTimeOutInSec; } }
package com.diary.services; import com.diary.dao.StudentDAO; import com.diary.dto.GradeDTO; import com.diary.model.Grade; import com.diary.model.SchoolClass; import com.diary.model.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; @Service public class StudentService { @Autowired StudentDAO studentDAO; @Autowired SchoolClassService schoolClassService; @Autowired GradeService gradeService; @Transactional public void create(Student student) { studentDAO.create(student); } /* @Transactional public List<Student> findAll() { return studentDAO.findAll(Student.class); }*/ @Transactional public Student findStudentById(Long studentId) { return (Student) studentDAO.getById(Student.class, studentId); } @Transactional public void addStudentToClass(Long classID, Long studentID) { SchoolClass schoolClass = schoolClassService.getClassByID(classID); Student student = (Student) studentDAO.getById(Student.class, studentID); student.setSchoolClass(schoolClass); studentDAO.update(student); } @Transactional public void addGradeToStudent(Long studentID, Grade grade) { Student student = (Student) studentDAO.getById(Student.class, studentID); List<Grade> studentGrades = student.getGradeList(); studentGrades.add(grade); student.setGradeList(studentGrades); studentDAO.update(student); } @Transactional public List<Student> findStudentsByClassID(Long clasID) { return studentDAO.findStudentsByClassID(clasID); } @Transactional public List<GradeDTO> prepareCardWithGrades(Long studentID) { HashMap<String, String> cardWithGrades = new HashMap<>(); List<Grade> grades = gradeService.findGradesByStudent(studentID); grades.forEach(x -> cardWithGrades.put(x.getSubject().getName(), cardWithGrades.get(x.getSubject().getName()) == null ? cardWithGrades.get(x.getSubject().getName()) + x.getGradeValue() + "," : x.getGradeValue() + ",")); Set<String> keys = cardWithGrades.keySet(); List<GradeDTO> gradesAsLists = new ArrayList<>(); keys.forEach(x -> gradesAsLists.add(new GradeDTO(x, cardWithGrades.get(x)))); return gradesAsLists; } }
package com.dominikschreiber.underscore; import com.dominikschreiber.underscore.java.util.function.BiFunction; import com.dominikschreiber.underscore.java.util.function.BiPredicate; import com.dominikschreiber.underscore.java.util.function.Consumer; import com.dominikschreiber.underscore.java.util.function.Function; import com.dominikschreiber.underscore.java.util.function.Predicate; import com.dominikschreiber.underscore.java.util.function.Supplier; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * <p>implements basic functional programming methods known from underscore.js</p> * <p><b>WARNING:</b> does not make use of advanced functional programming technologies * (like <i>tail calls</i> or <i>map optimization</i>) so might be slow on large data sets</p> */ public final class _ <T> { private Iterable<T> mValues; /** * <p>wraps {@code values} to allow chained execution, e.g.</p> * <pre>{@code * // compute sum of even squares * new _<>(_.list(1, 2, 3, 4, 5)) * // square the input * .map(new Function<Integer, Integer>() { * public Integer apply(Integer in) { * return in * in; * } * }) * // pick only even squares * .filter(new Predicate<Integer>() { * public boolean test(Integer in) { * return in % 2 == 0; * } * }) * // sum the squares * .reduce(new BiFunction<Integer, Integer, Integer>() { * public Integer apply(Integer now, Integer accumulator) { * return now + accumulator; * } * }, 0); * }</pre> * <p>To get the the actual value of the computation, use {@link #value()}:</p> * <pre>{@code * new _<>(_.list(1, 2, 3, 4, 5)) * [...] * .value(); // => Iterable<> * }</pre> * @param values the values that should be wrapped */ public _(Iterable<T> values) { mValues = values; } public Iterable<T> value() { return mValues; } /** * <p>calls {@code function} on each value in {@code values}</p> * <p>i.e.</p> * <pre> * _.each(_.list(1, 2, 3, 4), new Consumer<Integer>() { * public Void apply(Integer in) { * System.out.print("." + in + " "); * } * }); * // => .1 .2 .3 .4 * </pre> * @param values the values the function is called on * @param function the function to call on every element of {@code values} * @param <In> type of the elements in {@code values} */ public static <In> void each(Iterable<In> values, Consumer<In> function) { if (values == null) return; for (In value : values) function.accept(value); } /** @see #each(Iterable, Consumer) */ public _<T> each(Consumer<T> function) { _.each(mValues, function); return this; } /** * <p>creates a {@link List} of the results of applying {@code function} to all {@code values}</p> * <p>i.e.</p> * <pre> * _.map(_.list(1, 2, 3, 4), new Function<Integer, Integer>() { * public Integer apply(Integer x) { * return x * x; * } * }); * // => a List containing [1, 4, 9, 16] * </pre> * @param values the values to be mapped with the call of {@code function} * @param function the function to call on every element of {@code values} * @param <In> type of the elements in {@code values} * @param <Out> type of the result of {@code function} * @return a List of values of type {@code <Out>}, where {@code function} is * applied to all elements of {@code values} */ public static <In, Out> List<Out> map(Iterable<In> values, Function<In, Out> function) { if (values == null) return Collections.emptyList(); List<Out> result = new ArrayList<Out>(); for (In value : values) result.add(function.apply(value)); return result; } /** @see #map(Iterable, Function) */ public <Out> _<Out> map(Function<T, Out> function) { return new _<>(_.map(mValues, function)); } /** * <p>creates a {@link List} of all {@code values} that match {@code predicate}</p> * <p>i.e.</p> * <pre> * _.filter(_.list(1, 2, 3, 4), new Predicate<Integer>() { * public boolean test(Integer x) { * return x % 2 == 0; * } * }); * // => a List containing [2, 4] * </pre> * @param values the values to be filtered * @param predicate the predicate that must be matched by {@code values} * @param <In> type of the {@code values} * @return a List of all {@code values} that match {@code predicate} */ public static <In> List<In> filter(Iterable<In> values, Predicate<In> predicate) { if (values == null) return Collections.emptyList(); List<In> result = new ArrayList<>(); for (In value : values) if (predicate.test(value)) result.add(value); return result; } /** @see #filter(Iterable, Predicate) */ public _<T> filter(Predicate<T> predicate) { return new _<>(_.filter(mValues, predicate)); } /** * <p>looks through the {@code values}, returns the first value that matches {@code predicate}. * Breaks once the first matching value is found (does not traverse the whole list then).</p> * <p>e.g.</p> * <pre>{@code * _.find(_.list(1,2,3,4,5), new Predicate<Integer>() { * public boolean test(Integer x) { * return x % 2 == 0; * } * }); * // => 2 * }</pre> * @param values * @param predicate * @param <In> * @return */ public static <In> In find(Iterable<In> values, Predicate<In> predicate) { if (values == null) return null; for (In value : values) if (predicate.test(value)) return value; return null; } /** @see #find(Iterable, Predicate) */ public T find(Predicate<T> predicate) { return _.find(mValues, predicate); } /** * <p>reduces the {@code values} to a single value of type {@code <Out>}</p> * <p>(this is also known as {@code foldl}, {@code reducel}, {@code foldLeft} or {@code reduceLeft}</p> * <p>i.e.</p> * <pre> * _.reduce(_.list(1, 2, 3, 4), new BiFunction<Integer, Integer, Integer>() { * public Integer apply(Integer now, Integer accumulator) { * return now + accumulator; * } * }, 0); * // => 10 * </pre> * <p>to make it clear that this is a {@code reduceLeft}, take this example:</p> * <pre> * _.reduce(_.list(1, 2, 3, 4), new BiFunction<Integer, Integer, Integer>() { * public Integer apply(Integer now, Integer accumulator) { * return now - accumulator; * } * }, 0); * // => -10 (as (0 - (1 - (2 - (3 - (4)))))) * // not -2 (foldr would create (4 - (3 - (2 - (1 - (0)))))) * </pre> * @param values the values to be reduced * @param combine the combination function * @param init the initial value (if values is empty, this is the result) * @param <In> the type of the values * @param <Out> the result type * @return a value of type {@code <Out>} obtained by reducing {@code values} using {@combine} to a single value */ public static <In, Out> Out reduce(Iterable<In> values, BiFunction<In, Out, Out> combine, Out init) { if (values == null) return init; Out result = init; for (In value : values) result = combine.apply(value, result); return result; } /** @see #reduce(Iterable, BiFunction, Object) */ public <Out> Out reduce(BiFunction<T, Out, Out> combine, Out init) { return _.reduce(mValues, combine, init); } /** * <p>Returns the {@code values} that <b>do not pass</b> the {@code predicate}.</p> * <p>This is the opposite of {@link #filter(Iterable, com.dominikschreiber.underscore.java.util.function.Predicate)}. E.g.:</p> * <pre>{@code * _.reject(_.list(1,2,3,4,5), new Predicate<Integer>() { * public boolean test(Integer i) { * return i % 2 == 0; * } * }); * // => [1,3,5] * }</pre> * @param values the values to be checked * @param predicate the predicate that indicates which values should be rejected * @param <In> the type of the values * @return a list of values that do not match {@code predicate} */ public static <In> List<In> reject(Iterable<In> values, Predicate<In> predicate) { if (values == null) return Collections.emptyList(); List<In> reject = new ArrayList<>(); for (In value : values) if (!predicate.test(value)) reject.add(value); return reject; } /** @see #reject(Iterable, com.dominikschreiber.underscore.java.util.function.Predicate) */ public _<T> reject(Predicate<T> predicate) { return new _<>(_.reject(mValues, predicate)); } /** * <p>Returns {@code true} if all of the {@code values} pass {@code predicate}.</p> * <p>Short-circuits if it finds a non-passing value.</p> * @param values the values to be tested against {@code predicate} * @param predicate the predicate all {@code values} must pass * @param <In> the type of the {@code values} * @return {@code true} if all {@code values} pass {@code predicate}, otherwise {@code false}. * {@code true} if {@code values == null}. */ public static <In> boolean every(Iterable<In> values, Predicate<In> predicate) { if (values == null) return true; for (In value : values) if (!predicate.test(value)) return false; return true; } /** @see #every(Iterable, com.dominikschreiber.underscore.java.util.function.Predicate) */ public boolean every(Predicate<T> predicate) { return _.every(mValues, predicate); } /** * <p>Returns {@code true} if any of the {@code values} pass {@code predicate}.</p> * <p>Short-circuits if it finds a passing value..</p> * @param values the values to be tested against {@code predicate} * @param predicate the predicate that must be passed by a value in {@code values} * @param <In> the type of the {@code values} * @return {@code true} if a value in {@code values} passes {@code predicate}, otherwise {@code false}. * {@code false} if {@code values == null}. */ public static <In> boolean some(Iterable<In> values, Predicate<In> predicate) { if (values == null) return false; for (In value : values) if (predicate.test(value)) return true; return false; } public boolean some(Predicate<T> predicate) { return _.some(mValues, predicate); } /** * <p>returns {@code true} if the {@code needle} is present in {@code haystack}.</p> * <p>Uses {@code Object.equals()} to determine equality.</p> * @param haystack the values that should contain {@code needle} * @param needle the value to be found in {@code haystack} * @param <In> the type of values in haystack/needle * @return {@code true} if {@code needle} is found in {@code haystack} */ public static <In> boolean contains(Iterable<In> haystack, In needle) { return _.contains(haystack, needle, new BiPredicate<In, In>() { @Override public boolean test(In a, In b) { return a.equals(b); } }); } /** @see #contains(Iterable, Object) */ public boolean contains(T needle) { return _.contains(mValues, needle); } /** * <p>returns {@code true} if the {@code needle} is present in {@code haystack}.</p> * <p>uses {@code equals} to determine equality.</p> * <p>e.g.</p> * <pre>{@code * _.contains(_.list("abcde", "fghij"), "c", new BiPredicate<String, String>() { * // tests if any value in the haystack contains the needle * public boolean test(String hay, String needle) { * return hay.contains(needle); * } * }); * // => true ("abcde" contains "c") * }</pre> * @param haystack the values that should contain {@code needle} * @param needle the value to be found in {@code haystack} * @param equals the operation that determines if a value equals {@code needle}. * First parameter is the value from {@code haystack}, second parameter * is the {@code needle}. * @param <In> the type of values in haystack/needle * @return {@code true} if {@code needle} is found in {@code haystack} */ public static <In> boolean contains(Iterable<In> haystack, In needle, BiPredicate<In, In> equals) { if (haystack == null) return false; for (In hay : haystack) { if (equals.test(hay, needle)) { return true; } } return false; } /** @see #contains(Iterable, Object, BiPredicate) */ public boolean contains(T needle, BiPredicate<T, T> equals) { return _.contains(mValues, needle, equals); } public static <In, Key> Map<Key, List<In>> groupBy(Iterable<In> values, Function<In, Key> group) { if (values == null) return Collections.emptyMap(); Map<Key, List<In>> result = new HashMap<>(); for (In value : values) { Key key = group.apply(value); if (result.containsKey(key)) { result.get(key).add(value); } else { result.put(key, _.list(value)); } } return result; } public <Key> Map<Key, List<T>> groupBy(Function<T, Key> group) { return _.groupBy(mValues, group); } /** * <p>returns the number of values in {@code values}</p> * @param values the values to be counted * @return the number of values */ public static <In> int size(Iterable<In> values) { if (values == null) return 0; int size = 0; for (In value : values) { size += 1; } return size; } /** @see #size(Iterable) */ public int size() { return _.size(mValues); } /** * <p>returns the first {@code n} elements of {@code values}</p> * <p>e.g.</p> * <pre>{@code * _.first(_.list(1, 2, 3, 4, 5), 2); * // => [1, 2] * }</pre> * @param values * @param n * @param <In> * @return */ public static <In> List<In> first(Iterable<In> values, int n) { if (values == null) return Collections.emptyList(); List<In> first = new ArrayList<In>(n); Iterator<In> iterator = values.iterator(); for (int i = 0; i < n && iterator.hasNext(); i++) { first.add(iterator.next()); } return first; } /** @see #first(Iterable, int) */ public static <In> List<In> first(Iterable<In> values) { return _.first(values, 1); } /** @see #first(Iterable, int) */ public _<T> first(int n) { return new _<>(_.first(mValues, n)); } /** @see #first(int) */ public _<T> first() { return first(1); } public static <In> List<In> initial(Iterable<In> values, int n) { if (values == null) return Collections.emptyList(); List<In> initial = new ArrayList<>(); Iterator<In> iterator = values.iterator(); int limit = _.size(values) - n; for (int i = 0; i < limit && iterator.hasNext(); i++) { initial.add(iterator.next()); } return initial; } public static <In> List<In> initial(Iterable<In> values) { return _.initial(values, 1); } public _<T> initial(int n) { return new _<>(_.initial(mValues, n)); } public _<T> initial() { return initial(1); } /** * <p>returns the last {@code n} elements of {@code values}</p> * <p>e.g.</p> * <pre>{@code * _.last(_.list("foo", "bar", "baz"), 2); * // => ["bar", "baz"] * }</pre> * @param values the values to take the last {@code n} from * @param n the number of values to take from {@code values}, defaults to 1 * @return the last {@code n} {@code values} */ public static <In> List<In> last(Iterable<In> values, int n) { if (values == null) return Collections.emptyList(); List<In> last = new ArrayList<>(); int limit = _.size(values) - n; int i = 0; for (In value : values) { if (i >= limit) { last.add(value); } i += 1; } return last; } /** @see #last(Iterable, int) */ public static <In> List<In> last(Iterable<In> values) { return _.last(values, 1); } /** @see #last(Iterable, int) */ public _<T> last(int n) { return new _<>(_.last(mValues, n)); } /** @see #last(int) */ public _<T> last() { return last(1); } public static <In> List<In> rest(Iterable<In> values, int startindex) { return _.last(values, _.size(values) - startindex); } public static <In> List<In> rest(Iterable<In> values) { return _.rest(values, 1); } public _<T> rest(int startindex) { return new _<>(_.rest(mValues, startindex)); } public _<T> rest() { return rest(1); } private static BiPredicate<Integer, Integer> greater = new BiPredicate<Integer, Integer>() { @Override public boolean test(Integer a, Integer b) { return a > b; } }; private static BiPredicate<Integer, Integer> smaller = new BiPredicate<Integer, Integer>() { @Override public boolean test(Integer a, Integer b) { return a < b; } }; public static List<Integer> range(int start, int stop, int step) { if (start == stop || step == 0 || start > stop && step > 0) return Collections.emptyList(); List<Integer> range = new ArrayList<>(); BiPredicate<Integer, Integer> compare = (start < stop) ? smaller : greater; for (int i = start; compare.test(i, stop); i += step) range.add(i); return range; } public static List<Integer> range(int start, int stop) { return _.range(start, stop, 1); } public static List<Integer> range(int stop) { return _.range(0, stop); } public static <In, Out> Function<In, Out> wrap(Function<In, Out> function, Function<Function<In, Out>, Function<In, Out>> wrapper) { return wrapper.apply(function); } public static <In> Predicate<In> negate(final Predicate<In> predicate) { return new Predicate<In>() { @Override public boolean test(In in) { return !predicate.test(in); } }; } public static <U, V> BiPredicate<U, V> negate(final BiPredicate<U, V> predicate) { return new BiPredicate<U, V>() { @Override public boolean test(U u, V v) { return !predicate.test(u,v); } }; } public static <Datastore> Datastore extend(Datastore defaults, Datastore options) throws IllegalAccessException, NoSuchFieldException { for (Field field : options.getClass().getFields()) { if (field.get(options) != null) { defaults.getClass().getField(field.getName()).set(defaults, field.get(options)); } } return defaults; } /** * <p>Creates a list of the values passed as arguments. E.g.</p> * <pre>{@code * _.list("foo", "bar", "baz") * // => ["foo", "bar", "baz"] * }</pre> * <p>Without this function one would have written something like</p> * <pre>{@code * Arrays.asList(new String[] {"foo", "bar", "baz"}) * // => ["foo", "baz", "baz"] * }</pre> * <p>what would not allow e.g. adding items to the list</p> * @param values the values to create a list from * @param <In> the type the items in the list will have * @return a list that contains exactly the values */ @SafeVarargs public static <In> List<In> list(In... values) { if (values == null) return Collections.emptyList(); List<In> iterable = new ArrayList<>(); for (In value : values) { iterable.add(value); } return iterable; } public static String join(Iterable<String> values, final String separator) { if (values == null) return ""; StringBuilder joined = new StringBuilder(); boolean isFirst = true; for (String value : values) { if (isFirst) { joined.append(value); isFirst = false; } else { joined.append(separator).append(value); } } return joined.toString(); } public static String join(Iterable<String> values) { return _.join(values, ","); } public String join(final String separator) { return _.join(_.map(mValues, new Function<T, String>() { @Override public String apply(T t) { return t.toString(); } }), separator); } public String join() { return join(","); } /** * <p>returns the identity function for {@code In} values. E.g.</p> * <pre>{@code * _.identity(String.class).apply("foo") // => "foo" * }</pre> * @param clazz * @param <In> * @return */ public static <In> Function<In, In> identity(Class<In> clazz) { return new Function<In, In>() { @Override public In apply(In in) { return in; } }; } /** * <p>returns a function that always returns {@code value}. E.g.:</p> * <pre>{@code * Supplier<Integer> five = _.constant(5); * five.get() // => 5 * }</pre> * @param value the value the constant function should return * @param <In> the type of the value returned by the function * @return a {@link Supplier} that returns {@code value} */ public static <In> Supplier<In> constant(final In value) { return new Supplier<In>() { @Override public In get() { return value; } }; } }
package com.flavio.controller; import java.io.Serializable; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.primefaces.model.LazyDataModel; import com.flavio.anotation.Email; import com.flavio.model.Produto; import com.flavio.service.ContextMensage; import com.flavio.service.Mensagem; import com.flavio.service.ProdutoService; import com.flavio.service.XmlService; import com.flavio.util.Paginacao; @Named @ViewScoped public class ProdutoBean implements Serializable { private static final long serialVersionUID = 1L; @Inject private ContextMensage contextMensage; @Inject @Email private Mensagem mensagem; @Inject private ProdutoService produtoService; @Inject private XmlService xmlService; public static Log log = LogFactory.getLog(ProdutoBean.class); private List<Produto> produtos; private String nomePesquisa; private Paginacao paginacao = new Paginacao(); private Produto produto = new Produto(); private LazyDataModel<Produto> model; public void limpar() { produto = new Produto(); log.info("passou pela limpeza..."); } @PostConstruct public void consultaProdutos() { this.model = produtoService.consultaPaginada(paginacao); } public void buscar() { paginacao.setDescricao(this.nomePesquisa); model = produtoService.consultaPaginada(paginacao); } public void edit() { System.out.println(produto.getNome() + " produto para editar"); // this.produto = produtoService.produtoByID(produto.getId()); } public void salvar() { try { if (produtoService.salvar(produto)) { this.contextMensage.addmsg("", FacesMessage.SEVERITY_INFO, "Dados salvos com sucesso!", "Dados salvos com sucesso!"); model = produtoService.consultaPaginada(paginacao); System.out.println(xmlService.objectTOxmlProduto(produto)); System.out.println(xmlService.xmlToObjectProduto("<produto><id>17</id><nome>monitor aoc</nome><sku>3463jd</sku><valorUnitario>23</valorUnitario><quantidadeEstoque>45</quantidadeEstoque><categoria><id>10</id><nome>Informatica</nome></categoria></produto>")); //mensagem.enviar(); limpar(); } } catch (Exception e) { this.contextMensage.addmsg("", FacesMessage.SEVERITY_WARN, "Erro ao salvar!", "Erro ao salvar!"); log.error("Erro ao Salvar Produto: " + e); e.printStackTrace(); } } public String list() { List<Produto> listRepository = produtoService.listRepository(); if (listRepository != null) { produtos = listRepository; } return "/produto/listagem?faces-redirect=true"; } public List<Produto> getProdutos() { return produtos; } public void setProdutos(List<Produto> produtos) { this.produtos = produtos; } public String getNomePesquisa() { return nomePesquisa; } public void setNomePesquisa(String nomePesquisa) { this.nomePesquisa = nomePesquisa; } public Produto getProduto() { return produto; } public void setProduto(Produto produto) { this.produto = produto; } public LazyDataModel<Produto> getModel() { return model; } public void setModel(LazyDataModel<Produto> model) { this.model = model; } public Paginacao getPaginacao() { return paginacao; } public void setPaginacao(Paginacao paginacao) { this.paginacao = paginacao; } }
package scal.io.liger.model; import android.content.Context; import android.graphics.Bitmap; import android.support.annotation.NonNull; import android.util.Log; import com.google.gson.Gson; import com.google.gson.annotations.Expose; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashMap; import scal.io.liger.JsonHelper; import scal.io.liger.MainActivity; public class StoryPathLibrary extends StoryPath { public final String TAG = this.getClass().getSimpleName(); @Expose private HashMap<String, String> storyPathTemplateFiles; @Expose private ArrayList<String> storyPathInstanceFiles; @Expose private String currentStoryPathFile; private StoryPath currentStoryPath; // not serialized @Expose private HashMap<String, MediaFile> mediaFiles; /** * User preferences set by MainActivity. Delivered to MainActivity via Intent extras * from liger library client. * * TODO : Should these be serialized in StoryPathLibrary? */ public int photoSlideDurationMs; public String language; StoryPathLibraryListener mListener; public static interface StoryPathLibraryListener { public void onCardAdded(Card newCard); public void onCardChanged(Card changedCard); public void onCardsSwapped(Card cardOne, Card cardTwo); public void onCardRemoved(Card removedCard); public void onStoryPathLoaded(); } @Override public void notifyCardChanged(@NonNull Card firstCard) { Log.i(TAG, "(LIBRARY) notifyCardChanged of update to card " + firstCard.getId()); if (mListener == null) { return; } String action = ((MainActivity)context).checkCard(firstCard); if (action.equals("ADD")) { mListener.onCardAdded(firstCard); } if (action.equals("UPDATE")) { mListener.onCardChanged(firstCard); } if (action.equals("DELETE")) { mListener.onCardRemoved(firstCard); } // SEEMS LIKE A REASONABLE TIME TO SAVE save(true); } public void setStoryPathLibraryListener(StoryPathLibraryListener listener) { mListener = listener; } public HashMap<String, String> getStoryPathTemplateFiles() { return storyPathTemplateFiles; } public void setStoryPathTemplateFiles(HashMap<String, String> storyPathTemplateFiles) { this.storyPathTemplateFiles = storyPathTemplateFiles; } public ArrayList<String> getStoryPathInstanceFiles() { return storyPathInstanceFiles; } public void setStoryPathInstanceFiles(ArrayList<String> storyPathInstanceFiles) { this.storyPathInstanceFiles = storyPathInstanceFiles; } public void addStoryPathInstanceFile(String file) { if (this.storyPathInstanceFiles == null) { this.storyPathInstanceFiles = new ArrayList<String>(); } this.storyPathInstanceFiles.add(file); } public String getCurrentStoryPathFile() { return currentStoryPathFile; } public void setCurrentStoryPathFile(String currentStoryPathFile) { this.currentStoryPathFile = currentStoryPathFile; } public StoryPath getCurrentStoryPath() { return currentStoryPath; } public void setCurrentStoryPath(StoryPath currentStoryPath) { this.currentStoryPath = currentStoryPath; } public HashMap<String, MediaFile> getMediaFiles() { return mediaFiles; } public void setMediaFiles(HashMap<String, MediaFile> mediaFiles) { this.mediaFiles = mediaFiles; } @Override public void saveMediaFile(String uuid, MediaFile file) { if (this.mediaFiles == null) { this.mediaFiles = new HashMap<String, MediaFile>(); } this.mediaFiles.put(uuid, file); } @Override public MediaFile loadMediaFile(String uuid) { return mediaFiles.get(uuid); } // need to determine whether users are allowed to delete files that are referenced by cards // need to determine whether to automatically delete files when they are no longer referenced public void deleteMediaFile(String uuid) { if ((mediaFiles == null) || (!mediaFiles.keySet().contains(uuid))) { Log.e(this.getClass().getName(), "key was not found, cannot delete file"); return; } mediaFiles.remove(uuid); // delete actual file? } // need to determine where to present path options and deserialize new path public void switchPaths(StoryPath newPath) { // export clip metadata // also may need to export stored values StoryPath oldPath = this.getCurrentStoryPath(); ArrayList<ClipMetadata> metadata = oldPath.exportMetadata(); // serialize current story path Gson gson = new Gson(); oldPath.setStoryPathLibrary(null); oldPath.clearObservers(); oldPath.clearCardReferences(); // FIXME move this stuff into the model itself so we dont have to worry about it Context oldContext = oldPath.getContext(); oldPath.setContext(null); String json = gson.toJson(oldPath); try { File oldPathFile = new File(oldPath.buildZipPath(oldPath.getId() + ".path")); PrintStream ps = new PrintStream(new FileOutputStream(oldPathFile.getPath())); ps.print(json); // store file path // NOT YET SURE HOW TO HANDLE VERSIONS OR DUPLICATES this.addStoryPathInstanceFile(oldPathFile.getPath()); } catch (FileNotFoundException fnfe) { Log.e(this.getClass().getName(), "could not file file: " + fnfe.getMessage()); } catch (Exception e) { Log.e(this.getClass().getName(), "other exception: " + e.getMessage()); } // import clip metadata newPath.importMetadata(metadata); // should this be done externally? newPath.setContext(oldContext); newPath.setCardReferences(); newPath.initializeObservers(); newPath.setStoryPathLibrary(this); // update current story path this.setCurrentStoryPath(newPath); // NOTIFY/REFRESH HERE OR LET THAT BE HANDLED BY WHATEVER CALLS THIS? } public void loadStoryPathTemplate(String storyPathTemplateKey) { String storyPathTemplateFile = null; if (storyPathTemplateKey.equals("CURRENT")) { // ADD TO CONSTANTS storyPathTemplateFile = getCurrentStoryPathFile(); Log.d(TAG, "Loading current StoryPath: " + storyPathTemplateFile); // FIXME at least toast the user } else { storyPathTemplateFile = storyPathTemplateFiles.get(storyPathTemplateKey); Log.d(TAG, "Loading template StoryPath: " + storyPathTemplateFile); // FIXME at least toast the user } if (storyPathTemplateFile == null) { Log.e(TAG, "Loading failed. Could not find file: " + storyPathTemplateKey); // FIXME at least toast the user return; } if (context != null) { //File jsonTemplateFile = new File(buildZipPath(storyPathTemplateFile)); //String jsonTemplate = JsonHelper.loadJSONFromPath(jsonTemplateFile.getPath()); MainActivity mainActivity = null; String lang = "en"; // FIXME defaulting to en if (context instanceof MainActivity) { mainActivity = (MainActivity) context; // FIXME this isn't a safe cast as context can sometimes not be an activity (getApplicationContext()) lang = mainActivity.getLanguage(); } // check for file // paths to actual files should fully qualified // paths within zip files should be relative // (or at least not resolve to actual files) String checkPath = buildZipPath(storyPathTemplateFile); File checkFile = new File(checkPath); ArrayList<String> referencedFiles = null; // should not need to insert dependencies into a saved instance file if (checkPath.contains("instance")) { Log.d(TAG, "Load from saved instance"); referencedFiles = new ArrayList<String>(); } else { Log.d(TAG, "Load from template"); referencedFiles = new ArrayList<String>(); // pass through files referenced by library (which were pulled from intent) // does there need to be a way to select references when loading a path? // referencedFiles = JsonHelper.getInstancePaths(); if ((dependencies != null) && (dependencies.size() > 0)) { // support multiple referenced files? Log.d(TAG, "Found " + dependencies.size() + " referenced files in library"); for (Dependency dependency : dependencies) { if(dependency.getDependencyFile().contains("-instance")) { referencedFiles.add(dependency.getDependencyFile()); } } } else { Log.d(TAG, "Found no referenced files in library"); } } StoryPath story = null; if (checkFile.exists()) { story = JsonHelper.loadStoryPath(checkPath, this, referencedFiles, context, lang); Log.d(TAG, "Loaded StoryPath from file: " + checkPath); } else { story = JsonHelper.loadStoryPathFromZip(checkPath, this, referencedFiles, context, lang); Log.d(TAG, "Loaded StoryPath from zip: " + checkPath); } setCurrentStoryPath(story); setCurrentStoryPathFile(storyPathTemplateFile); save(false); if (mListener != null) mListener.onStoryPathLoaded(); } else { Log.e(this.getClass().getName(), "app context reference not found, cannot initialize card list for " + storyPathTemplateFile); // FIXME at least toast the user } } @Override public Bitmap getCoverImageThumbnail() { if (getCurrentStoryPath() != null) { return getCurrentStoryPath().getCoverImageThumbnail(); } else { return null; } } /** * Serialize this object to disk. * * @param saveCurrentStoryPath whether to also save the StoryPath returned by * {@link #getCurrentStoryPath()} */ public void save(boolean saveCurrentStoryPath) { //Gson gson = new Gson(); String savedStoryPathLibraryFile = getSavedFileName(); if (savedStoryPathLibraryFile == null) { savedStoryPathLibraryFile = JsonHelper.getStoryPathLibrarySaveFileName(this); setSavedFileName(savedStoryPathLibraryFile); Log.d(TAG, "Saving to new file: " + savedStoryPathLibraryFile); } else { Log.d(TAG, "Saving to existing file: " + savedStoryPathLibraryFile); } if (saveCurrentStoryPath && (getCurrentStoryPath() != null)) { getCurrentStoryPath().setStoryPathLibraryFile(savedStoryPathLibraryFile); String savedStoryPathFile = getCurrentStoryPath().getSavedFileName(); if (savedStoryPathFile == null) { savedStoryPathFile = JsonHelper.getStoryPathSaveFileName(getCurrentStoryPath()); getCurrentStoryPath().setSavedFileName(savedStoryPathFile); Log.d(TAG, "Saving current StoryPath to new file: " + savedStoryPathFile); } else { Log.d(TAG, "Saving current StoryPath to existing file: " + savedStoryPathFile); } setCurrentStoryPathFile(savedStoryPathFile); JsonHelper.saveStoryPath(getCurrentStoryPath(), savedStoryPathFile); Log.d(TAG, "Current StoryPath with id " + getCurrentStoryPath().getId() + " was saved to file " + savedStoryPathFile); } else { Log.d(TAG, "Id " + getId() + " has no current StoryPath, but save was explicitly requested. Ignoring."); } JsonHelper.saveStoryPathLibrary(this, savedStoryPathLibraryFile); Log.d(TAG, "Id " + getId() + " was saved to file " + savedStoryPathLibraryFile); //String savedFilePath = JsonHelper.saveStoryPath(mStoryPathLibrary.getCurrentStoryPath()); //mStoryPathLibrary.setCurrentStoryPathFile(savedFilePath); //JsonHelper.saveStoryPathLibrary(mStoryPathLibrary); /* // prep and serialize story path library String json3 = gson.toJson(mStoryPathLibrary); // write to file, store path try { File storyPathLibraryFile = new File("/storage/emulated/0/Liger/default/TEST_LIB.json"); // need file naming plan FileOutputStream fos = new FileOutputStream(storyPathLibraryFile); if (!storyPathLibraryFile.exists()) { storyPathLibraryFile.createNewFile(); } byte data[] = json3.getBytes(); fos.write(data); fos.flush(); fos.close(); mStory.setStoryPathLibrary(null); mStory.setStoryPathLibraryFile(storyPathLibraryFile.getPath()); } catch (IOException ioe) { Log.e(TAG, ioe.getMessage()); } */ /* // prep and serialize current story path mStoryPathLibrary.getCurrentStoryPath().setStoryPathLibrary(null); mStoryPathLibrary.getCurrentStoryPath().clearObservers(); mStoryPathLibrary.getCurrentStoryPath().clearCardReferences(); // FIXME move this stuff into the model itself so we dont have to worry about it mStoryPathLibrary.getCurrentStoryPath().setContext(null); String json1 = gson.toJson(mStoryPathLibrary.getCurrentStoryPath()); StoryPath sp = mStoryPathLibrary.getCurrentStoryPath(); // write to file, store path try { File currentStoryPathFile = new File("/storage/emulated/0/Liger/default/TEST_PATH.json"); // need file naming plan FileOutputStream fos = new FileOutputStream(currentStoryPathFile); if (!currentStoryPathFile.exists()) { currentStoryPathFile.createNewFile(); } byte data[] = json1.getBytes(); fos.write(data); fos.flush(); fos.close(); mStoryPathLibrary.setCurrentStoryPath(null); mStoryPathLibrary.setCurrentStoryPathFile(currentStoryPathFile.getPath()); } catch (IOException ioe) { Log.e(TAG, ioe.getMessage()); } // prep and serialize top level story String json2 = gson.toJson(mStoryPathLibrary); // write to file try { File storyFile = new File("/storage/emulated/0/Liger/default/TEST_STORY.json"); // need file naming plan FileOutputStream fos = new FileOutputStream(storyFile); if (!storyFile.exists()) { storyFile.createNewFile(); } byte data[] = json2.getBytes(); fos.write(data); fos.flush(); fos.close(); } catch (IOException ioe) { Log.e(TAG, ioe.getMessage()); } // restore links and continue // mStory.setStoryPathLibrary(mStoryPathLibrary); mStoryPathLibrary.setCurrentStoryPath(sp); mStoryPathLibrary.getCurrentStoryPath().setContext(this); mStoryPathLibrary.getCurrentStoryPath().setCardReferences(); mStoryPathLibrary.getCurrentStoryPath().initializeObservers(); mStoryPathLibrary.getCurrentStoryPath().setStoryPathLibrary(mStoryPathLibrary); */ } }
package com.fundynamic.d2tm.game.map; import com.fundynamic.d2tm.game.terrain.Terrain; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; public class Cell { private Terrain terrain; public Cell(Terrain terrain) { if (terrain == null) throw new IllegalArgumentException("Terrain argument may not be null"); this.terrain = terrain; } public void changeTerrain(Terrain terrain) { this.terrain = terrain; } public Image getTileImage() throws SlickException { return terrain.getTileImage(); } public Terrain getTerrain() { return terrain; } public boolean isSameTerrain(Terrain terrain) { return this.terrain.isSame(terrain); } }
package com.github.davidmoten.rtree; import static com.google.common.base.Optional.of; import java.util.Comparator; import rx.Observable; import rx.functions.Func1; import com.github.davidmoten.rtree.geometry.Geometry; import com.github.davidmoten.rtree.geometry.Rectangle; import com.github.davidmoten.rx.operators.OperatorBoundedPriorityQueue; import com.github.davidmoten.util.ImmutableStack; import com.google.common.base.Optional; import com.google.common.collect.Lists; /** * Immutable in-memory R-Tree with configurable splitter heuristic. */ public class RTree { private static final int MAX_CHILDREN_DEFAULT = 32; private final Optional<Node> root; private final Context context; /** * Constructor. * * @param root * @param context */ private RTree(Optional<Node> root, Context context) { this.root = root; this.context = context; } /** * Constructor. * * @param root * @param context */ private RTree(Node root, Context context) { this(of(root), context); } /** * Constructor. Creates an empty R-tree with maxChildren at 32 and using a * {@link QuadraticSplitter}. */ public RTree() { this(Optional.<Node> absent(), new Context(MAX_CHILDREN_DEFAULT, new QuadraticSplitter())); } /** * Constructor. Creates an empty R-tree using specified maxChildren and a * {@link QuadraticSplitter}. * * @param maxChildren */ public RTree(int maxChildren) { this(Optional.<Node> absent(), new Context(maxChildren, new QuadraticSplitter())); } /** * Constructor. Creates an empty R-tree using specified maxChildren and * splitter. * * @param maxChildren * @param splitter * for example {@link QuadraticSplitter} */ public RTree(int maxChildren, Splitter splitter) { this(Optional.<Node> absent(), new Context(maxChildren, splitter)); } /** * Returns a new Builder instance for {@link RTree}. */ public static Builder builder() { return new Builder(); } /** * RTree Builder */ public static class Builder { private int maxChildren = 8; private Splitter splitter = new QuadraticSplitter(); private Builder() { } /** * Sets the max number of children in an R-tree node. * * @param maxChildren * @return */ public Builder maxChildren(int maxChildren) { this.maxChildren = maxChildren; return this; } /** * Sets the {@link Splitter} to use when maxChildren is reached. * * @param splitter * @return */ public Builder splitter(Splitter splitter) { this.splitter = splitter; return this; } /** * Builds the {@link RTree}. */ public RTree build() { return new RTree(maxChildren, splitter); } } /** * Adds an entry to the R-tree. * * @param entry * item to add to the R-tree. * @return a new immutable R-trees */ public RTree add(Entry entry) { if (root.isPresent()) return new RTree(root.get().add(entry, ImmutableStack.<NonLeaf> empty()), context); else return new RTree(new Leaf(Lists.newArrayList(entry), context), context); } public RTree add(Object object, Geometry mbr) { return add(new Entry(object, mbr)); } public Observable<Entry> search(Func1<? super Geometry, Boolean> criterion) { if (root.isPresent()) return Observable.create(new OnSubscribeSearch(root.get(), criterion)); else return Observable.empty(); } public static final Comparator<Entry> ascendingDistance(final Rectangle r) { return new Comparator<Entry>() { @Override public int compare(Entry e1, Entry e2) { return ((Double) e1.geometry().distance(r)).compareTo(e2 .geometry().distance(r)); } }; } public static Func1<Geometry, Boolean> intersects(final Rectangle r) { return new Func1<Geometry, Boolean>() { @Override public Boolean call(Geometry g) { return g.intersects(r); } }; } public static Func1<Geometry, Boolean> ALWAYS_TRUE = new Func1<Geometry, Boolean>() { @Override public Boolean call(Geometry rectangle) { return true; } }; public Observable<Entry> search(final Rectangle r) { return search(intersects(r)); } public Observable<Entry> search(final Rectangle r, final double maxDistance) { return search(new Func1<Geometry, Boolean>() { @Override public Boolean call(Geometry g) { return g.distance(r) < maxDistance; } }); } public Observable<Entry> nearest(final Rectangle r, final double maxDistance, int maxCount) { return search(r, maxDistance).lift( new OperatorBoundedPriorityQueue<Entry>(maxCount, ascendingDistance(r))); } public Observable<Entry> entries() { return search(ALWAYS_TRUE); } public Visualizer visualize(int width, int height, Rectangle view, int maxDepth) { return new Visualizer(this, width, height, view); } Optional<Node> root() { return root; } }
package com.github.lpandzic.junit.bdd; import java.util.Optional; public final class Bdd { /** * Used for specifying behavior that should throw an throwable. * * <p><strong>Note: Not defining then inside the test after calling this method will cause throwable to be * silently swallowed and can cause subsequent test to fail on {@link #requireThatNoUnexpectedExceptionWasThrown()}. * }</strong></p> * * @param throwableSupplier supplier or throwable * @param <T> the type of * * @return new {@link Then.Throws} */ public static <T extends Exception> Then.Throws<T> when(ThrowableSupplier<T> throwableSupplier) { requireThatNoUnexpectedExceptionWasThrown(); return new When().when(throwableSupplier); } /** * Used for specifying behavior that should return a value. * * @param value returned by the specified behavior * @param <T> type of {@code value} * * @return new {@link Then.Returns} */ public static <T> Then.Returns<T> when(T value) { requireThatNoUnexpectedExceptionWasThrown(); return new When().when(value); } /** * {@link ThreadLocal} exception thrown or {@link Optional#empty()}. */ private static ThreadLocal<Optional<Throwable>> thrownException = new ThreadLocal<>().withInitial(Optional::empty); /** * Inserts the {@code throwable} into {@link #thrownException}. * * @param throwable to add */ static void putThrownException(Throwable throwable) { requireThatNoUnexpectedExceptionWasThrown(); thrownException.set(Optional.of(throwable)); } /** * Retrieves and removes {@link #thrownException}. * * Used by {@link Then} for consuming {@link #thrownException} * * @return {@link #thrownException} */ static Optional<Throwable> takeThrownException() { Optional<Throwable> thrownException = Bdd.thrownException.get(); Bdd.thrownException.set(Optional.<Throwable>empty()); return thrownException; } @SuppressWarnings("unchecked") static <T extends Throwable> void throwUnexpectedException(Optional<Throwable> throwable) throws T { if (throwable.isPresent()) { throw (T) throwable.get(); } } static void requireThatNoUnexpectedExceptionWasThrown() { if (thrownException.get().isPresent()) { throwUnexpectedException(takeThrownException()); } } private Bdd() { } }
package com.greghaskins.spectrum; /** * This is a convenience class to make working with Java closures easier. Variables from outer * scopes must be {@code final} to be referenced inside lambda functions. Wrapping objects in a * {@link #Variable} instance allows you to get/set values from anywhere as long as the Variable * itself is {@code final}. */ public class Variable<T> { private T value; /** * Create a Variable with a {@code null} initial value. */ public Variable() {} /** * Create a Variable with the given initial value. * * @param value starting value */ public Variable(final T value) { this.value = value; } /** * Get the current value of this Variable. * * @return current value */ public T get() { return this.value; } /** * Change the value of this Variable. * * @param value new value */ public void set(final T value) { this.value = value; } }
package com.heroku; import com.atlassian.bamboo.build.logger.BuildLogger; import com.atlassian.bamboo.security.StringEncrypter; import com.atlassian.bamboo.task.*; import com.herokuapp.directto.client.DeployRequest; import com.herokuapp.directto.client.DirectToHerokuClient; import com.herokuapp.directto.client.EventSubscription; import com.herokuapp.directto.client.VerificationException; import org.jetbrains.annotations.NotNull; import java.io.File; import java.util.HashMap; import java.util.Map; import static com.herokuapp.directto.client.EventSubscription.Event; import static com.herokuapp.directto.client.EventSubscription.Event.POLL_START; import static com.herokuapp.directto.client.EventSubscription.Event.UPLOAD_START; import static com.herokuapp.directto.client.EventSubscription.Subscriber; /** * @author Ryan Brainard */ public abstract class AbstractDeploymentTask<P extends DeploymentPipeline> implements TaskType { /** * A sandbox for static methods that don't play well with jMock */ protected static interface StaticSandbox { TaskResult success(TaskContext taskContext); TaskResult failed(TaskContext taskContext); } private final P pipeline; private final StaticSandbox staticSandbox; public AbstractDeploymentTask(P pipeline) { this(pipeline, new StaticSandbox() { @Override public TaskResult success(TaskContext taskContext) { return TaskResultBuilder.create(taskContext).success().build(); } @Override public TaskResult failed(TaskContext taskContext) { return TaskResultBuilder.create(taskContext).failed().build(); } }); } public AbstractDeploymentTask(P pipeline, StaticSandbox staticSandbox) { this.pipeline = pipeline; this.staticSandbox = staticSandbox; } @NotNull @Override public TaskResult execute(@NotNull final TaskContext taskContext) throws TaskException { final BuildLogger buildLogger = taskContext.getBuildLogger(); final String apiKey = new StringEncrypter().decrypt(taskContext.getConfigurationMap().get(AbstractDeploymentTaskConfigurator.API_KEY)); final String appName = taskContext.getConfigurationMap().get("appName"); final String pipelineName = pipeline.getPipelineName(); final DirectToHerokuClient client = new DirectToHerokuClient.Builder() .setApiKey(apiKey) .setConsumersUserAgent(HerokuPluginProperties.getUserAgent()) .build(); buildLogger.addBuildLogEntry("Preparing to deploy to Heroku app [" + appName + "]"); final Map<String, File> files = new HashMap<String, File>(pipeline.getRequiredFiles().size()); final String workingDir = taskContext.getWorkingDirectory().getAbsolutePath() + "/"; for (String file : pipeline.getRequiredFiles()) { final String filepath = workingDir + taskContext.getConfigurationMap().get(file); buildLogger.addBuildLogEntry("Adding [" + file + "]: " + filepath); files.put(file, new File(filepath)); } final DeployRequest deployRequest = new DeployRequest(pipelineName, appName, files) .setEventSubscription(new EventSubscription() .subscribe(UPLOAD_START, new Subscriber() { public void handle(Event event) { buildLogger.addBuildLogEntry("Uploading..."); } }) .subscribe(POLL_START, new Subscriber() { public void handle(Event event) { buildLogger.addBuildLogEntry("Deploying..."); } }) ); try { client.verify(deployRequest); } catch (VerificationException e) { for (String msg : e.getMessages()) { buildLogger.addErrorLogEntry(msg); } return staticSandbox.failed(taskContext); } final Map<String, String> deployResults = client.deploy(deployRequest); buildLogger.addBuildLogEntry("Deploy results:"); for (Map.Entry<String, String> result : deployResults.entrySet()) { buildLogger.addBuildLogEntry(" - " + result.getKey() + ":" + result.getValue()); } return "success".equals(deployResults.get("status")) ? staticSandbox.success(taskContext) : staticSandbox.failed(taskContext); } }
package com.afollestad.silk.http; import ch.boye.httpclientandroidlib.HttpResponse; import ch.boye.httpclientandroidlib.StatusLine; /** * @author Aidan Follestad (afollestad) */ public class SilkHttpException extends Exception { SilkHttpException(Exception e) { super(e); } SilkHttpException(HttpResponse response) { mIsResponse = true; StatusLine stat = response.getStatusLine(); mStatus = stat.getStatusCode(); mReason = stat.getReasonPhrase(); } private int mStatus = -1; private String mReason; private boolean mIsResponse; /** * Gets the status code returned from the HTTP request, this will only be set if {@link #isServerResponse()} returns true. */ public int getStatusCode() { return mStatus; } /** * Gets the reason phrase for the value of {@link #getStatusCode()}. this will only be set if {@link #isServerResponse()} returns true. */ public String getReasonPhrase() { return mReason; } /** * Gets whether or not this exception was thrown for a non-200 HTTP response code, or if it was thrown for a code level Exception. */ public boolean isServerResponse() { return mIsResponse; } @Override public String getMessage() { if (isServerResponse()) { return getStatusCode() + " " + getReasonPhrase(); } return super.getMessage(); } }
package com.lothrazar.backport; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.block.BlockBreakable; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.stats.StatList; //import net.minecraft.util.EnumWorldBlockLayer; import net.minecraft.world.World; //import net.minecraftforge.fml.relauncher.Side; //import net.minecraftforge.fml.relauncher.SideOnly; public class BlockSlime extends BlockBreakable { private static final String __OBFID = "CL_00002063"; public BlockSlime() { super("slime", Material.clay, false); this.setCreativeTab(CreativeTabs.tabDecorations); this.slipperiness = 0.8F; this.setBlockName("slime");//.setStepSound(new Block.SoundType("mob.slime.big", 1.0F, 1.0F)); this.setBlockTextureName("samspowerups:" +"slime_block"); //mob.slime.big from sounds.json //water has opacity of 3 this.setLightOpacity(3); } /* //this is what gives it that outer transparency , but not the same in 1.7 @SideOnly(Side.CLIENT) public EnumWorldBlockLayer getBlockLayer() { return EnumWorldBlockLayer.TRANSLUCENT; } */ @Override @SideOnly(Side.CLIENT) public boolean isOpaqueCube() { return false; } @Override public boolean renderAsNormalBlock() { return false; } @Override public int getRenderBlockPass() { return 1; } @Override @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister ii) { //texture wasnt showing up bc this was missing this.blockIcon = ii.registerIcon(this.textureName); } @Override public void onFallenUpon(World worldObj, int x,int y, int z, Entity entityIn, float fallDistance) { //this fires twice. assuming its once for each client/server System.out.println("onFallenUpon :: fallDistance = "+fallDistance); System.out.println("motionY = "+entityIn.motionY); if (entityIn.isSneaking()) { super.onFallenUpon(worldObj, x, y, z, entityIn,fallDistance); // super.onFallenUpon(worldIn, pos, entityIn, fallDistance); } else { //entity does not have a 'fall' method in 1.7 // entityIn.fall(fallDistance, 0.0F); // float damageMultiplier = 0.0F; //in 1.8 it loosk like this, which does nothing unless a //specific entity has overridden it //public void fall(float distance, float damageMultiplier) /* if (entityIn.riddenByEntity != null) { entityIn.riddenByEntity.fall(fallDistance, damageMultiplier); } */ //and for a player, all it does is add to stats. only change is 1.8 added the multiplier, //which for us is zero anyway if(entityIn instanceof EntityPlayer && fallDistance >= 2.0F) { //p.fall(fallDistance);//its protected though in 1.7, and public in 1.8 //but all it does is add to fallen stats EntityPlayer p = (EntityPlayer)entityIn; p.addStat(StatList.distanceFallenStat, (int)Math.round((double)fallDistance * 100.0D)); } /* //copied this from entity collide, since that doest fire if (Math.abs(entityIn.motionY) < 0.1D && !entityIn.isSneaking()) { double d0 = 0.4D + Math.abs(entityIn.motionY) * 0.2D; entityIn.motionX *= d0; entityIn.motionZ *= d0; } */ } //copy from landed, which never fires if (entityIn.isSneaking()) { entityIn.motionY = 0.0D; } else if (entityIn.motionY < 0.0D) { //since its in a differetn event, motion is always close to zero. so mult by fall dist // entityIn.motionY = -entityIn.motionY; // entityIn.motionY = -entityIn.motionY*fallDistance; entityIn.moveEntity(0, -entityIn.motionY * fallDistance / 1.8, 0); System.out.println("bounce trying to reverse motion TO =? "+entityIn.motionY); } worldObj.playSoundAtEntity( entityIn, // the entity at which to play the sound "mob.slime.big", // sound file name from sounds.json 1.0F, // volume (randomize if you want) 0.5F * ((worldObj.rand.nextFloat() - worldObj.rand.nextFloat()) * 0.7F + 1.8F) // pitch that has lots some randomness ); } //@Override public void onLanded(World worldObj, Entity entityIn) { //this does not fire at all. probably because we cant override since //super doesnt exist System.out.println("onLanded :: entityIn.motionY = "+entityIn.motionY); if (entityIn.isSneaking()) { //super doesnt exist so we skip it. must have been added in 1.8 // super.onLanded(worldIn, entityIn); //the super just does this anyway /* public void onLanded(World worldIn, Entity entityIn) { entityIn.motionY = 0.0D; }*/ entityIn.motionY = 0.0D; } else if (entityIn.motionY < 0.0D) { entityIn.motionY = -entityIn.motionY; } } //where the bounce happens @Override public void onEntityCollidedWithBlock(World worldIn, int x,int y, int z, Entity entityIn) { //this has an override so it should be good, but it never fires System.out.println("onEntityCollidedWithBlock :: entityIn.motionY = "+entityIn.motionY); if (Math.abs(entityIn.motionY) < 0.1D && !entityIn.isSneaking()) { double d0 = 0.4D + Math.abs(entityIn.motionY) * 0.2D; entityIn.motionX *= d0; entityIn.motionZ *= d0; } super.onEntityCollidedWithBlock(worldIn, x,y,z, entityIn); } }
package com.rarchives.ripme.ui; import java.awt.*; import java.awt.TrayIcon.MessageType; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.List; import javax.imageio.ImageIO; import javax.swing.DefaultListModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import javax.swing.table.AbstractTableModel; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import org.apache.log4j.ConsoleAppender; import org.apache.log4j.FileAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import com.rarchives.ripme.ripper.AbstractRipper; import com.rarchives.ripme.utils.RipUtils; import com.rarchives.ripme.utils.Utils; import javax.swing.UnsupportedLookAndFeelException; /** * Everything UI-related starts and ends here. */ public final class MainWindow implements Runnable, RipStatusHandler { private static final Logger logger = Logger.getLogger(MainWindow.class); private boolean isRipping = false; // Flag to indicate if we're ripping something private static JFrame mainFrame; private static JTextField ripTextfield; private static JButton ripButton, stopButton; private static JLabel statusLabel; private static JButton openButton; private static JProgressBar statusProgress; // Put an empty JPanel on the bottom of the window to keep components // anchored to the top when there is no open lower panel private static JPanel emptyPanel; // Log private static JButton optionLog; private static JPanel logPanel; private static JTextPane logText; // History private static JButton optionHistory; private static final History HISTORY = new History(); private static JPanel historyPanel; private static JTable historyTable; private static AbstractTableModel historyTableModel; private static JButton historyButtonRemove, historyButtonClear, historyButtonRerip; // Queue public static JButton optionQueue; private static JPanel queuePanel; private static DefaultListModel queueListModel; // Configuration private static JButton optionConfiguration; private static JPanel configurationPanel; private static JButton configUpdateButton; private static JLabel configUpdateLabel; private static JTextField configTimeoutText; private static JTextField configThreadsText; private static JCheckBox configOverwriteCheckbox; private static JLabel configSaveDirLabel; private static JButton configSaveDirButton; private static JTextField configRetriesText; private static JCheckBox configAutoupdateCheckbox; private static JComboBox configLogLevelCombobox; private static JCheckBox configURLHistoryCheckbox; private static JCheckBox configPlaySound; private static JCheckBox configSaveOrderCheckbox; private static JCheckBox configShowPopup; private static JCheckBox configSaveLogs; private static JCheckBox configSaveURLsOnly; private static JCheckBox configSaveAlbumTitles; private static JCheckBox configClipboardAutorip; private static JCheckBox configSaveDescriptions; private static JCheckBox configPreferMp4; private static JCheckBox configWindowPosition; private static TrayIcon trayIcon; private static MenuItem trayMenuMain; private static CheckboxMenuItem trayMenuAutorip; private static Image mainIcon; private static AbstractRipper ripper; private ResourceBundle rb = Utils.getResourceBundle(); private void updateQueueLabel() { if (queueListModel.size() > 0) { optionQueue.setText( rb.getString("Queue") + " (" + queueListModel.size() + ")"); } else { optionQueue.setText(rb.getString("Queue")); } } private static void addCheckboxListener(JCheckBox checkBox, String configString) { checkBox.addActionListener(arg0 -> { Utils.setConfigBoolean(configString, checkBox.isSelected()); Utils.configureLogger(); }); } private static JCheckBox addNewCheckbox(String text, String configString, Boolean configBool) { JCheckBox checkbox = new JCheckBox(text, Utils.getConfigBoolean(configString, configBool)); checkbox.setHorizontalAlignment(JCheckBox.RIGHT); checkbox.setHorizontalTextPosition(JCheckBox.LEFT); return checkbox; } public static void addUrlToQueue(String url) { queueListModel.addElement(url); } public MainWindow() { mainFrame = new JFrame("RipMe v" + UpdateUtils.getThisJarVersion()); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setLayout(new GridBagLayout()); createUI(mainFrame.getContentPane()); pack(); loadHistory(); setupHandlers(); Thread shutdownThread = new Thread(this::shutdownCleanup); Runtime.getRuntime().addShutdownHook(shutdownThread); if (Utils.getConfigBoolean("auto.update", true)) { upgradeProgram(); } boolean autoripEnabled = Utils.getConfigBoolean("clipboard.autorip", false); ClipboardUtils.setClipboardAutoRip(autoripEnabled); trayMenuAutorip.setState(autoripEnabled); } private void upgradeProgram() { if (!configurationPanel.isVisible()) { optionConfiguration.doClick(); } Runnable r = () -> UpdateUtils.updateProgram(configUpdateLabel); new Thread(r).start(); } public void run() { pack(); restoreWindowPosition(mainFrame); mainFrame.setVisible(true); } private void shutdownCleanup() { Utils.setConfigBoolean("file.overwrite", configOverwriteCheckbox.isSelected()); Utils.setConfigInteger("threads.size", Integer.parseInt(configThreadsText.getText())); Utils.setConfigInteger("download.retries", Integer.parseInt(configRetriesText.getText())); Utils.setConfigInteger("download.timeout", Integer.parseInt(configTimeoutText.getText())); Utils.setConfigBoolean("clipboard.autorip", ClipboardUtils.getClipboardAutoRip()); Utils.setConfigBoolean("auto.update", configAutoupdateCheckbox.isSelected()); Utils.setConfigString("log.level", configLogLevelCombobox.getSelectedItem().toString()); Utils.setConfigBoolean("play.sound", configPlaySound.isSelected()); Utils.setConfigBoolean("download.save_order", configSaveOrderCheckbox.isSelected()); Utils.setConfigBoolean("download.show_popup", configShowPopup.isSelected()); Utils.setConfigBoolean("log.save", configSaveLogs.isSelected()); Utils.setConfigBoolean("urls_only.save", configSaveURLsOnly.isSelected()); Utils.setConfigBoolean("album_titles.save", configSaveAlbumTitles.isSelected()); Utils.setConfigBoolean("clipboard.autorip", configClipboardAutorip.isSelected()); Utils.setConfigBoolean("descriptions.save", configSaveDescriptions.isSelected()); Utils.setConfigBoolean("prefer.mp4", configPreferMp4.isSelected()); Utils.setConfigBoolean("remember.url_history", configURLHistoryCheckbox.isSelected()); saveWindowPosition(mainFrame); saveHistory(); Utils.saveConfig(); } private void status(String text) { statusWithColor(text, Color.BLACK); } private void error(String text) { statusWithColor(text, Color.RED); } private void statusWithColor(String text, Color color) { statusLabel.setForeground(color); statusLabel.setText(text); pack(); } private void pack() { SwingUtilities.invokeLater(() -> { Dimension preferredSize = mainFrame.getPreferredSize(); mainFrame.setMinimumSize(preferredSize); if (isCollapsed()) { mainFrame.setSize(preferredSize); } }); } private boolean isCollapsed() { return (!logPanel.isVisible() && !historyPanel.isVisible() && !queuePanel.isVisible() && !configurationPanel.isVisible() ); } private void createUI(Container pane) { //If creating the tray icon fails, ignore it. try { setupTrayIcon(); } catch (Exception e) { } EmptyBorder emptyBorder = new EmptyBorder(5, 5, 5, 5); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1; gbc.ipadx = 2; gbc.gridx = 0; gbc.weighty = 0; gbc.ipady = 2; gbc.gridy = 0; gbc.anchor = GridBagConstraints.PAGE_START; try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException e) { logger.error("[!] Exception setting system theme:", e); } ripTextfield = new JTextField("", 20); ripTextfield.addMouseListener(new ContextMenuMouseListener()); ImageIcon ripIcon = new ImageIcon(mainIcon); ripButton = new JButton("<html><font size=\"5\"><b>Rip</b></font></html>", ripIcon); stopButton = new JButton("<html><font size=\"5\"><b>Stop</b></font></html>"); stopButton.setEnabled(false); try { Image stopIcon = ImageIO.read(getClass().getClassLoader().getResource("stop.png")); stopButton.setIcon(new ImageIcon(stopIcon)); } catch (Exception ignored) { } JPanel ripPanel = new JPanel(new GridBagLayout()); ripPanel.setBorder(emptyBorder); gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 0; gbc.gridx = 0; ripPanel.add(new JLabel("URL:", JLabel.RIGHT), gbc); gbc.weightx = 1; gbc.weighty = 1; gbc.gridx = 1; ripPanel.add(ripTextfield, gbc); gbc.weighty = 0; gbc.weightx = 0; gbc.gridx = 2; ripPanel.add(ripButton, gbc); gbc.gridx = 3; ripPanel.add(stopButton, gbc); gbc.weightx = 1; statusLabel = new JLabel(rb.getString("inactive")); statusLabel.setHorizontalAlignment(JLabel.CENTER); openButton = new JButton(); openButton.setVisible(false); JPanel statusPanel = new JPanel(new GridBagLayout()); statusPanel.setBorder(emptyBorder); gbc.gridx = 0; statusPanel.add(statusLabel, gbc); gbc.gridy = 1; statusPanel.add(openButton, gbc); gbc.gridy = 0; JPanel progressPanel = new JPanel(new GridBagLayout()); progressPanel.setBorder(emptyBorder); statusProgress = new JProgressBar(0, 100); progressPanel.add(statusProgress, gbc); JPanel optionsPanel = new JPanel(new GridBagLayout()); optionsPanel.setBorder(emptyBorder); optionLog = new JButton(rb.getString("Log")); optionHistory = new JButton(rb.getString("History")); optionQueue = new JButton(rb.getString("Queue")); optionConfiguration = new JButton(rb.getString("Configuration")); optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); try { Image icon; icon = ImageIO.read(getClass().getClassLoader().getResource("comment.png")); optionLog.setIcon(new ImageIcon(icon)); icon = ImageIO.read(getClass().getClassLoader().getResource("time.png")); optionHistory.setIcon(new ImageIcon(icon)); icon = ImageIO.read(getClass().getClassLoader().getResource("list.png")); optionQueue.setIcon(new ImageIcon(icon)); icon = ImageIO.read(getClass().getClassLoader().getResource("gear.png")); optionConfiguration.setIcon(new ImageIcon(icon)); } catch (Exception e) { } gbc.gridx = 0; optionsPanel.add(optionLog, gbc); gbc.gridx = 1; optionsPanel.add(optionHistory, gbc); gbc.gridx = 2; optionsPanel.add(optionQueue, gbc); gbc.gridx = 3; optionsPanel.add(optionConfiguration, gbc); logPanel = new JPanel(new GridBagLayout()); logPanel.setBorder(emptyBorder); logText = new JTextPane(); logText.setEditable(false); JScrollPane logTextScroll = new JScrollPane(logText); logTextScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); logPanel.setVisible(false); logPanel.setPreferredSize(new Dimension(300, 250)); gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 1; logPanel.add(logTextScroll, gbc); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weighty = 0; historyPanel = new JPanel(new GridBagLayout()); historyPanel.setBorder(emptyBorder); historyPanel.setVisible(false); historyPanel.setPreferredSize(new Dimension(300, 250)); historyTableModel = new AbstractTableModel() { private static final long serialVersionUID = 1L; @Override public String getColumnName(int col) { return HISTORY.getColumnName(col); } @Override public Class<?> getColumnClass(int c) { return getValueAt(0, c).getClass(); } @Override public Object getValueAt(int row, int col) { return HISTORY.getValueAt(row, col); } @Override public int getRowCount() { return HISTORY.toList().size(); } @Override public int getColumnCount() { return HISTORY.getColumnCount(); } @Override public boolean isCellEditable(int row, int col) { return (col == 0 || col == 4); } @Override public void setValueAt(Object value, int row, int col) { if (col == 4) { HISTORY.get(row).selected = (Boolean) value; historyTableModel.fireTableDataChanged(); } } }; historyTable = new JTable(historyTableModel); historyTable.addMouseListener(new HistoryMenuMouseListener()); historyTable.setAutoCreateRowSorter(true); for (int i = 0; i < historyTable.getColumnModel().getColumnCount(); i++) { int width = 130; // Default switch (i) { case 0: // URL width = 270; break; case 3: width = 40; break; case 4: width = 15; break; } historyTable.getColumnModel().getColumn(i).setPreferredWidth(width); } JScrollPane historyTableScrollPane = new JScrollPane(historyTable); historyButtonRemove = new JButton(rb.getString("remove")); historyButtonClear = new JButton(rb.getString("clear")); historyButtonRerip = new JButton(rb.getString("re-rip.checked")); gbc.gridx = 0; // History List Panel JPanel historyTablePanel = new JPanel(new GridBagLayout()); gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 1; historyTablePanel.add(historyTableScrollPane, gbc); gbc.ipady = 180; gbc.gridy = 0; historyPanel.add(historyTablePanel, gbc); gbc.ipady = 0; JPanel historyButtonPanel = new JPanel(new GridBagLayout()); historyButtonPanel.setPreferredSize(new Dimension(300, 10)); historyButtonPanel.setBorder(emptyBorder); gbc.gridx = 0; historyButtonPanel.add(historyButtonRemove, gbc); gbc.gridx = 1; historyButtonPanel.add(historyButtonClear, gbc); gbc.gridx = 2; historyButtonPanel.add(historyButtonRerip, gbc); gbc.gridy = 1; gbc.gridx = 0; gbc.weighty = 0; gbc.fill = GridBagConstraints.HORIZONTAL; historyPanel.add(historyButtonPanel, gbc); queuePanel = new JPanel(new GridBagLayout()); queuePanel.setBorder(emptyBorder); queuePanel.setVisible(false); queuePanel.setPreferredSize(new Dimension(300, 250)); queueListModel = new DefaultListModel(); JList queueList = new JList(queueListModel); queueList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); queueList.addMouseListener(new QueueMenuMouseListener()); JScrollPane queueListScroll = new JScrollPane(queueList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); for (String item : Utils.getConfigList("queue")) { queueListModel.addElement(item); } updateQueueLabel(); gbc.gridx = 0; JPanel queueListPanel = new JPanel(new GridBagLayout()); gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 1; queueListPanel.add(queueListScroll, gbc); queuePanel.add(queueListPanel, gbc); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weighty = 0; gbc.ipady = 0; configurationPanel = new JPanel(new GridBagLayout()); configurationPanel.setBorder(emptyBorder); configurationPanel.setVisible(false); // TODO Configuration components configUpdateButton = new JButton(rb.getString("check.for.updates")); configUpdateLabel = new JLabel( rb.getString("current.version") + ": " + UpdateUtils.getThisJarVersion(), JLabel.RIGHT); JLabel configThreadsLabel = new JLabel(rb.getString("max.download.threads") + ":", JLabel.RIGHT); JLabel configTimeoutLabel = new JLabel(rb.getString("timeout.mill"), JLabel.RIGHT); JLabel configRetriesLabel = new JLabel(rb.getString("retry.download.count"), JLabel.RIGHT); configThreadsText = new JTextField(Integer.toString(Utils.getConfigInteger("threads.size", 3))); configTimeoutText = new JTextField(Integer.toString(Utils.getConfigInteger("download.timeout", 60000))); configRetriesText = new JTextField(Integer.toString(Utils.getConfigInteger("download.retries", 3))); configOverwriteCheckbox = addNewCheckbox(rb.getString("overwrite.existing.files"), "file.overwrite", false); configAutoupdateCheckbox = addNewCheckbox(rb.getString("auto.update"), "auto.update", true); configPlaySound = addNewCheckbox(rb.getString("sound.when.rip.completes"), "play.sound", false); configShowPopup = addNewCheckbox(rb.getString("notification.when.rip.starts"), "download.show_popup", false); configSaveOrderCheckbox = addNewCheckbox(rb.getString("preserve.order"), "download.save_order", true); configSaveLogs = addNewCheckbox(rb.getString("save.logs"), "log.save", false); configSaveURLsOnly = addNewCheckbox(rb.getString("save.urls.only"), "urls_only.save", false); configSaveAlbumTitles = addNewCheckbox(rb.getString("save.album.titles"), "album_titles.save", true); configClipboardAutorip = addNewCheckbox(rb.getString("autorip.from.clipboard"), "clipboard.autorip", false); configSaveDescriptions = addNewCheckbox(rb.getString("save.descriptions"), "descriptions.save", true); configPreferMp4 = addNewCheckbox(rb.getString("prefer.mp4.over.gif"),"prefer.mp4", false); configWindowPosition = addNewCheckbox(rb.getString("restore.window.position"), "window.position", true); configURLHistoryCheckbox = addNewCheckbox(rb.getString("remember.url.history"), "remember.url_history", true); configLogLevelCombobox = new JComboBox(new String[] {"Log level: Error", "Log level: Warn", "Log level: Info", "Log level: Debug"}); configLogLevelCombobox.setSelectedItem(Utils.getConfigString("log.level", "Log level: Debug")); setLogLevel(configLogLevelCombobox.getSelectedItem().toString()); configSaveDirLabel = new JLabel(); try { String workingDir = (Utils.shortenPath(Utils.getWorkingDirectory())); configSaveDirLabel.setText(workingDir); configSaveDirLabel.setForeground(Color.BLUE); configSaveDirLabel.setCursor(new Cursor(Cursor.HAND_CURSOR)); } catch (Exception e) { } configSaveDirLabel.setToolTipText(configSaveDirLabel.getText()); configSaveDirLabel.setHorizontalAlignment(JLabel.RIGHT); configSaveDirButton = new JButton("Select Save Directory..."); gbc.gridy = 0; gbc.gridx = 0; configurationPanel.add(configUpdateLabel, gbc); gbc.gridx = 1; configurationPanel.add(configUpdateButton, gbc); gbc.gridy = 1; gbc.gridx = 0; configurationPanel.add(configAutoupdateCheckbox, gbc); gbc.gridx = 1; configurationPanel.add(configLogLevelCombobox, gbc); gbc.gridy = 2; gbc.gridx = 0; configurationPanel.add(configThreadsLabel, gbc); gbc.gridx = 1; configurationPanel.add(configThreadsText, gbc); gbc.gridy = 3; gbc.gridx = 0; configurationPanel.add(configTimeoutLabel, gbc); gbc.gridx = 1; configurationPanel.add(configTimeoutText, gbc); gbc.gridy = 4; gbc.gridx = 0; configurationPanel.add(configRetriesLabel, gbc); gbc.gridx = 1; configurationPanel.add(configRetriesText, gbc); gbc.gridy = 5; gbc.gridx = 0; configurationPanel.add(configOverwriteCheckbox, gbc); gbc.gridx = 1; configurationPanel.add(configSaveOrderCheckbox, gbc); gbc.gridy = 6; gbc.gridx = 0; configurationPanel.add(configPlaySound, gbc); gbc.gridx = 1; configurationPanel.add(configSaveLogs, gbc); gbc.gridy = 7; gbc.gridx = 0; configurationPanel.add(configShowPopup, gbc); gbc.gridx = 1; configurationPanel.add(configSaveURLsOnly, gbc); gbc.gridy = 8; gbc.gridx = 0; configurationPanel.add(configClipboardAutorip, gbc); gbc.gridx = 1; configurationPanel.add(configSaveAlbumTitles, gbc); gbc.gridy = 9; gbc.gridx = 0; configurationPanel.add(configSaveDescriptions, gbc); gbc.gridx = 1; configurationPanel.add(configPreferMp4, gbc); gbc.gridy = 10; gbc.gridx = 0; configurationPanel.add(configWindowPosition, gbc); gbc.gridx = 1; configurationPanel.add(configURLHistoryCheckbox, gbc); gbc.gridy = 11; gbc.gridx = 0; configurationPanel.add(configSaveDirLabel, gbc); gbc.gridx = 1; configurationPanel.add(configSaveDirButton, gbc); emptyPanel = new JPanel(); emptyPanel.setPreferredSize(new Dimension(0, 0)); emptyPanel.setSize(0, 0); gbc.anchor = GridBagConstraints.PAGE_START; gbc.gridy = 0; pane.add(ripPanel, gbc); gbc.gridy = 1; pane.add(statusPanel, gbc); gbc.gridy = 2; pane.add(progressPanel, gbc); gbc.gridy = 3; pane.add(optionsPanel, gbc); gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH; gbc.gridy = 4; pane.add(logPanel, gbc); gbc.gridy = 5; pane.add(historyPanel, gbc); gbc.gridy = 5; pane.add(queuePanel, gbc); gbc.gridy = 5; pane.add(configurationPanel, gbc); gbc.gridy = 5; pane.add(emptyPanel, gbc); gbc.weighty = 0; gbc.fill = GridBagConstraints.HORIZONTAL; } private void setupHandlers() { ripButton.addActionListener(new RipButtonHandler()); ripTextfield.addActionListener(new RipButtonHandler()); ripTextfield.getDocument().addDocumentListener(new DocumentListener() { @Override public void removeUpdate(DocumentEvent e) { update(); } @Override public void insertUpdate(DocumentEvent e) { update(); } @Override public void changedUpdate(DocumentEvent e) { update(); } private void update() { try { String urlText = ripTextfield.getText().trim(); if (urlText.equals("")) { return; } if (!urlText.startsWith("http")) { urlText = "http://" + urlText; } URL url = new URL(urlText); AbstractRipper ripper = AbstractRipper.getRipper(url); statusWithColor(ripper.getHost() + " album detected", Color.GREEN); } catch (Exception e) { statusWithColor("Can't rip this URL: " + e.getMessage(), Color.RED); } } }); stopButton.addActionListener(event -> { if (ripper != null) { ripper.stop(); isRipping = false; stopButton.setEnabled(false); statusProgress.setValue(0); statusProgress.setVisible(false); pack(); statusProgress.setValue(0); status("Ripping interrupted"); appendLog("Ripper interrupted", Color.RED); } }); optionLog.addActionListener(event -> { logPanel.setVisible(!logPanel.isVisible()); emptyPanel.setVisible(!logPanel.isVisible()); historyPanel.setVisible(false); queuePanel.setVisible(false); configurationPanel.setVisible(false); if (logPanel.isVisible()) { optionLog.setFont(optionLog.getFont().deriveFont(Font.BOLD)); } else { optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); } optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); pack(); }); optionHistory.addActionListener(event -> { logPanel.setVisible(false); historyPanel.setVisible(!historyPanel.isVisible()); emptyPanel.setVisible(!historyPanel.isVisible()); queuePanel.setVisible(false); configurationPanel.setVisible(false); optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); if (historyPanel.isVisible()) { optionHistory.setFont(optionLog.getFont().deriveFont(Font.BOLD)); } else { optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); } optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); pack(); }); optionQueue.addActionListener(event -> { logPanel.setVisible(false); historyPanel.setVisible(false); queuePanel.setVisible(!queuePanel.isVisible()); emptyPanel.setVisible(!queuePanel.isVisible()); configurationPanel.setVisible(false); optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); if (queuePanel.isVisible()) { optionQueue.setFont(optionLog.getFont().deriveFont(Font.BOLD)); } else { optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); } optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); pack(); }); optionConfiguration.addActionListener(event -> { logPanel.setVisible(false); historyPanel.setVisible(false); queuePanel.setVisible(false); configurationPanel.setVisible(!configurationPanel.isVisible()); emptyPanel.setVisible(!configurationPanel.isVisible()); optionLog.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); optionHistory.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); optionQueue.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); if (configurationPanel.isVisible()) { optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.BOLD)); } else { optionConfiguration.setFont(optionLog.getFont().deriveFont(Font.PLAIN)); } pack(); }); historyButtonRemove.addActionListener(event -> { int[] indices = historyTable.getSelectedRows(); for (int i = indices.length - 1; i >= 0; i int modelIndex = historyTable.convertRowIndexToModel(indices[i]); HISTORY.remove(modelIndex); } try { historyTableModel.fireTableDataChanged(); } catch (Exception e) { } saveHistory(); }); historyButtonClear.addActionListener(event -> { if (Utils.getConfigBoolean("history.warn_before_delete", true)) { JPanel checkChoise = new JPanel(); checkChoise.setLayout(new FlowLayout()); JButton yesButton = new JButton("YES"); JButton noButton = new JButton("NO"); yesButton.setPreferredSize(new Dimension(70, 30)); noButton.setPreferredSize(new Dimension(70, 30)); checkChoise.add(yesButton); checkChoise.add(noButton); JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("Are you sure?"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(checkChoise); frame.setSize(405, 70); frame.setVisible(true); frame.setLocationRelativeTo(null); noButton.addActionListener(e -> { frame.setVisible(false); }); yesButton.addActionListener(ed -> { frame.setVisible(false); Utils.clearURLHistory(); HISTORY.clear(); try { historyTableModel.fireTableDataChanged(); } catch (Exception e) { } saveHistory(); }); } else { Utils.clearURLHistory(); HISTORY.clear(); try { historyTableModel.fireTableDataChanged(); } catch (Exception e) { } saveHistory(); } }); // Re-rip all history historyButtonRerip.addActionListener(event -> { if (HISTORY.isEmpty()) { JOptionPane.showMessageDialog(null, "There are no history entries to re-rip. Rip some albums first", "RipMe Error", JOptionPane.ERROR_MESSAGE); return; } int added = 0; for (HistoryEntry entry : HISTORY.toList()) { if (entry.selected) { added++; queueListModel.addElement(entry.url); } } if (added == 0) { JOptionPane.showMessageDialog(null, "No history entries have been 'Checked'\n" + "Check an entry by clicking the checkbox to the right of the URL or Right-click a URL to check/uncheck all items", "RipMe Error", JOptionPane.ERROR_MESSAGE); } }); configUpdateButton.addActionListener(arg0 -> { Thread t = new Thread(() -> UpdateUtils.updateProgram(configUpdateLabel)); t.start(); }); configLogLevelCombobox.addActionListener(arg0 -> { String level = ((JComboBox) arg0.getSource()).getSelectedItem().toString(); setLogLevel(level); }); configSaveDirLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { File file = new File(Utils.getWorkingDirectory().toString()); Desktop desktop = Desktop.getDesktop(); try { desktop.open(file); } catch (Exception e1) { } } }); configSaveDirButton.addActionListener(arg0 -> { UIManager.put("FileChooser.useSystemExtensionHiding", false); JFileChooser jfc = new JFileChooser(Utils.getWorkingDirectory()); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = jfc.showDialog(null, "select directory"); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } File chosenFile = jfc.getSelectedFile(); String chosenPath = null; try { chosenPath = chosenFile.getCanonicalPath(); } catch (Exception e) { logger.error("Error while getting selected path: ", e); return; } configSaveDirLabel.setText(Utils.shortenPath(chosenPath)); Utils.setConfigString("rips.directory", chosenPath); }); addCheckboxListener(configSaveOrderCheckbox, "download.save_order"); addCheckboxListener(configOverwriteCheckbox, "file.overwrite"); addCheckboxListener(configSaveLogs, "log.save"); addCheckboxListener(configSaveURLsOnly, "urls_only.save"); addCheckboxListener(configURLHistoryCheckbox, "remember.url_history"); addCheckboxListener(configSaveAlbumTitles, "album_titles.save"); addCheckboxListener(configSaveDescriptions, "descriptions.save"); addCheckboxListener(configPreferMp4, "prefer.mp4"); addCheckboxListener(configWindowPosition, "window.position"); configClipboardAutorip.addActionListener(arg0 -> { Utils.setConfigBoolean("clipboard.autorip", configClipboardAutorip.isSelected()); ClipboardUtils.setClipboardAutoRip(configClipboardAutorip.isSelected()); trayMenuAutorip.setState(configClipboardAutorip.isSelected()); Utils.configureLogger(); }); queueListModel.addListDataListener(new ListDataListener() { @Override public void intervalAdded(ListDataEvent arg0) { updateQueueLabel(); if (!isRipping) { ripNextAlbum(); } } @Override public void contentsChanged(ListDataEvent arg0) { } @Override public void intervalRemoved(ListDataEvent arg0) { } }); } private void setLogLevel(String level) { Level newLevel = Level.ERROR; level = level.substring(level.lastIndexOf(' ') + 1); switch (level) { case "Debug": newLevel = Level.DEBUG; break; case "Info": newLevel = Level.INFO; break; case "Warn": newLevel = Level.WARN; break; case "Error": newLevel = Level.ERROR; break; } Logger.getRootLogger().setLevel(newLevel); logger.setLevel(newLevel); ConsoleAppender ca = (ConsoleAppender)Logger.getRootLogger().getAppender("stdout"); if (ca != null) { ca.setThreshold(newLevel); } FileAppender fa = (FileAppender)Logger.getRootLogger().getAppender("FILE"); if (fa != null) { fa.setThreshold(newLevel); } } private void setupTrayIcon() { mainFrame.addWindowListener(new WindowAdapter() { @Override public void windowActivated(WindowEvent e) { trayMenuMain.setLabel("Hide"); } @Override public void windowDeactivated(WindowEvent e) { trayMenuMain.setLabel("Show"); } @Override public void windowDeiconified(WindowEvent e) { trayMenuMain.setLabel("Hide"); } @Override public void windowIconified(WindowEvent e) { trayMenuMain.setLabel("Show"); } }); PopupMenu trayMenu = new PopupMenu(); trayMenuMain = new MenuItem("Hide"); trayMenuMain.addActionListener(arg0 -> toggleTrayClick()); MenuItem trayMenuAbout = new MenuItem("About " + mainFrame.getTitle()); trayMenuAbout.addActionListener(arg0 -> { StringBuilder about = new StringBuilder(); about.append("<html><h1>") .append(mainFrame.getTitle()) .append("</h1>"); about.append("Download albums from various websites:"); try { List<String> rippers = Utils.getListOfAlbumRippers(); about.append("<ul>"); for (String ripper : rippers) { about.append("<li>"); ripper = ripper.substring(ripper.lastIndexOf('.') + 1); if (ripper.contains("Ripper")) { ripper = ripper.substring(0, ripper.indexOf("Ripper")); } about.append(ripper); about.append("</li>"); } about.append("</ul>"); } catch (Exception e) { } about.append("<br>And download videos from video sites:"); try { List<String> rippers = Utils.getListOfVideoRippers(); about.append("<ul>"); for (String ripper : rippers) { about.append("<li>"); ripper = ripper.substring(ripper.lastIndexOf('.') + 1); if (ripper.contains("Ripper")) { ripper = ripper.substring(0, ripper.indexOf("Ripper")); } about.append(ripper); about.append("</li>"); } about.append("</ul>"); } catch (Exception e) { } about.append("Do you want to visit the project homepage on Github?"); about.append("</html>"); int response = JOptionPane.showConfirmDialog(null, about.toString(), mainFrame.getTitle(), JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, new ImageIcon(mainIcon)); if (response == JOptionPane.YES_OPTION) { try { Desktop.getDesktop().browse(URI.create("http://github.com/4pr0n/ripme")); } catch (IOException e) { logger.error("Exception while opening project home page", e); } } }); MenuItem trayMenuExit = new MenuItem("Exit"); trayMenuExit.addActionListener(arg0 -> System.exit(0)); trayMenuAutorip = new CheckboxMenuItem("Clipboard Autorip"); trayMenuAutorip.addItemListener(arg0 -> { ClipboardUtils.setClipboardAutoRip(trayMenuAutorip.getState()); configClipboardAutorip.setSelected(trayMenuAutorip.getState()); }); trayMenu.add(trayMenuMain); trayMenu.add(trayMenuAbout); trayMenu.addSeparator(); trayMenu.add(trayMenuAutorip); trayMenu.addSeparator(); trayMenu.add(trayMenuExit); try { mainIcon = ImageIO.read(getClass().getClassLoader().getResource("icon.png")); trayIcon = new TrayIcon(mainIcon); trayIcon.setToolTip(mainFrame.getTitle()); trayIcon.setImageAutoSize(true); trayIcon.setPopupMenu(trayMenu); SystemTray.getSystemTray().add(trayIcon); trayIcon.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { toggleTrayClick(); if (mainFrame.getExtendedState() != JFrame.NORMAL) { mainFrame.setExtendedState(JFrame.NORMAL); } mainFrame.setAlwaysOnTop(true); mainFrame.setAlwaysOnTop(false); } }); } catch (IOException | AWTException e) { //TODO implement proper stack trace handling this is really just intented as a placeholder until you implement proper error handling e.printStackTrace(); } } private void toggleTrayClick() { if (mainFrame.getExtendedState() == JFrame.ICONIFIED || !mainFrame.isActive() || !mainFrame.isVisible()) { mainFrame.setVisible(true); mainFrame.setAlwaysOnTop(true); mainFrame.setAlwaysOnTop(false); trayMenuMain.setLabel("Hide"); } else { mainFrame.setVisible(false); trayMenuMain.setLabel("Show"); } } private void appendLog(final String text, final Color color) { SimpleAttributeSet sas = new SimpleAttributeSet(); StyleConstants.setForeground(sas, color); StyledDocument sd = logText.getStyledDocument(); try { synchronized (this) { sd.insertString(sd.getLength(), text + "\n", sas); } } catch (BadLocationException e) { } logText.setCaretPosition(sd.getLength()); } private void loadHistory() { File historyFile = new File(Utils.getConfigDir() + File.separator + "history.json"); HISTORY.clear(); if (historyFile.exists()) { try { logger.info(rb.getString("loading.history.from") + " " + historyFile.getCanonicalPath()); HISTORY.fromFile(historyFile.getCanonicalPath()); } catch (IOException e) { logger.error("Failed to load history from file " + historyFile, e); JOptionPane.showMessageDialog(null, "RipMe failed to load the history file at " + historyFile.getAbsolutePath() + "\n\n" + "Error: " + e.getMessage() + "\n\n" + "Closing RipMe will automatically overwrite the contents of this file,\n" + "so you may want to back the file up before closing RipMe!", "RipMe - history load failure", JOptionPane.ERROR_MESSAGE); } } else { logger.info(rb.getString("loading.history.from.configuration")); HISTORY.fromList(Utils.getConfigList("download.history")); if (HISTORY.toList().size() == 0) { // Loaded from config, still no entries. // Guess rip history based on rip folder String[] dirs = Utils.getWorkingDirectory().list((dir, file) -> new File(dir.getAbsolutePath() + File.separator + file).isDirectory()); for (String dir : dirs) { String url = RipUtils.urlFromDirectoryName(dir); if (url != null) { // We found one, add it to history HistoryEntry entry = new HistoryEntry(); entry.url = url; HISTORY.add(entry); } } } } } private void saveHistory() { Path historyFile = Paths.get(Utils.getConfigDir() + File.separator + "history.json"); try { if (!Files.exists(historyFile)) { Files.createDirectories(historyFile.getParent()); Files.createFile(historyFile); } HISTORY.toFile(historyFile.toString()); Utils.setConfigList("download.history", Collections.emptyList()); } catch (IOException e) { logger.error("Failed to save history to file " + historyFile, e); } } @SuppressWarnings("unchecked") private void ripNextAlbum() { isRipping = true; // Save current state of queue to configuration. Utils.setConfigList("queue", (Enumeration<Object>) queueListModel.elements()); if (queueListModel.isEmpty()) { // End of queue isRipping = false; return; } String nextAlbum = (String) queueListModel.remove(0); updateQueueLabel(); Thread t = ripAlbum(nextAlbum); if (t == null) { try { Thread.sleep(500); } catch (InterruptedException ie) { logger.error(rb.getString("interrupted.while.waiting.to.rip.next.album"), ie); } ripNextAlbum(); } else { t.start(); } } private Thread ripAlbum(String urlString) { //shutdownCleanup(); if (!logPanel.isVisible()) { optionLog.doClick(); } urlString = urlString.trim(); if (urlString.toLowerCase().startsWith("gonewild:")) { urlString = "http://gonewild.com/user/" + urlString.substring(urlString.indexOf(':') + 1); } if (!urlString.startsWith("http")) { urlString = "http://" + urlString; } URL url = null; try { url = new URL(urlString); } catch (MalformedURLException e) { logger.error("[!] Could not generate URL for '" + urlString + "'", e); error("Given URL is not valid, expecting http://website.com/page/..."); return null; } stopButton.setEnabled(true); statusProgress.setValue(100); openButton.setVisible(false); statusLabel.setVisible(true); pack(); boolean failed = false; try { ripper = AbstractRipper.getRipper(url); ripper.setup(); } catch (Exception e) { failed = true; logger.error("Could not find ripper for URL " + url, e); error(e.getMessage()); } if (!failed) { try { mainFrame.setTitle("Ripping - RipMe v" + UpdateUtils.getThisJarVersion()); status("Starting rip..."); ripper.setObserver(this); Thread t = new Thread(ripper); if (configShowPopup.isSelected() && (!mainFrame.isVisible() || !mainFrame.isActive())) { mainFrame.toFront(); mainFrame.setAlwaysOnTop(true); trayIcon.displayMessage(mainFrame.getTitle(), "Started ripping " + ripper.getURL().toExternalForm(), MessageType.INFO); mainFrame.setAlwaysOnTop(false); } return t; } catch (Exception e) { logger.error("[!] Error while ripping: " + e.getMessage(), e); error("Unable to rip this URL: " + e.getMessage()); } } stopButton.setEnabled(false); statusProgress.setValue(0); pack(); return null; } class RipButtonHandler implements ActionListener { public void actionPerformed(ActionEvent event) { if (!queueListModel.contains(ripTextfield.getText()) && !ripTextfield.getText().equals("")) { queueListModel.add(queueListModel.size(), ripTextfield.getText()); ripTextfield.setText(""); } else { if (!isRipping) { ripNextAlbum(); } } } } private class StatusEvent implements Runnable { private final AbstractRipper ripper; private final RipStatusMessage msg; StatusEvent(AbstractRipper ripper, RipStatusMessage msg) { this.ripper = ripper; this.msg = msg; } public void run() { handleEvent(this); } } private synchronized void handleEvent(StatusEvent evt) { if (ripper.isStopped()) { return; } RipStatusMessage msg = evt.msg; int completedPercent = evt.ripper.getCompletionPercentage(); statusProgress.setValue(completedPercent); statusProgress.setVisible(true); status( evt.ripper.getStatusText() ); switch(msg.getStatus()) { case LOADING_RESOURCE: case DOWNLOAD_STARTED: if (logger.isEnabledFor(Level.INFO)) { appendLog("Downloading " + msg.getObject(), Color.BLACK); } break; case DOWNLOAD_COMPLETE: if (logger.isEnabledFor(Level.INFO)) { appendLog("Downloaded " + msg.getObject(), Color.GREEN); } break; case DOWNLOAD_ERRORED: if (logger.isEnabledFor(Level.ERROR)) { appendLog((String) msg.getObject(), Color.RED); } break; case DOWNLOAD_WARN: if (logger.isEnabledFor(Level.WARN)) { appendLog((String) msg.getObject(), Color.ORANGE); } break; case RIP_ERRORED: if (logger.isEnabledFor(Level.ERROR)) { appendLog((String) msg.getObject(), Color.RED); } stopButton.setEnabled(false); statusProgress.setValue(0); statusProgress.setVisible(false); openButton.setVisible(false); pack(); statusWithColor("Error: " + msg.getObject(), Color.RED); break; case RIP_COMPLETE: RipStatusComplete rsc = (RipStatusComplete) msg.getObject(); String url = ripper.getURL().toExternalForm(); if (HISTORY.containsURL(url)) { // TODO update "modifiedDate" of entry in HISTORY HistoryEntry entry = HISTORY.getEntryByURL(url); entry.count = rsc.count; entry.modifiedDate = new Date(); } else { HistoryEntry entry = new HistoryEntry(); entry.url = url; entry.dir = rsc.getDir(); entry.count = rsc.count; try { entry.title = ripper.getAlbumTitle(ripper.getURL()); } catch (MalformedURLException e) { } HISTORY.add(entry); historyTableModel.fireTableDataChanged(); } if (configPlaySound.isSelected()) { Utils.playSound("camera.wav"); } saveHistory(); stopButton.setEnabled(false); statusProgress.setValue(0); statusProgress.setVisible(false); openButton.setVisible(true); File f = rsc.dir; String prettyFile = Utils.shortenPath(f); openButton.setText("Open " + prettyFile); mainFrame.setTitle("RipMe v" + UpdateUtils.getThisJarVersion()); try { Image folderIcon = ImageIO.read(getClass().getClassLoader().getResource("folder.png")); openButton.setIcon(new ImageIcon(folderIcon)); } catch (Exception e) { } appendLog("Rip complete, saved to " + f.getAbsolutePath(), Color.GREEN); openButton.setActionCommand(f.toString()); openButton.addActionListener(event -> { try { Desktop.getDesktop().open(new File(event.getActionCommand())); } catch (Exception e) { logger.error(e); } }); pack(); ripNextAlbum(); break; case COMPLETED_BYTES: // Update completed bytes break; case TOTAL_BYTES: // Update total bytes break; } } public void update(AbstractRipper ripper, RipStatusMessage message) { StatusEvent event = new StatusEvent(ripper, message); SwingUtilities.invokeLater(event); } public static void ripAlbumStatic(String url) { ripTextfield.setText(url.trim()); ripButton.doClick(); } public static void enableWindowPositioning() { Utils.setConfigBoolean("window.position", true); } public static void disableWindowPositioning() { Utils.setConfigBoolean("window.position", false); } private static boolean hasWindowPositionBug() { String osName = System.getProperty("os.name"); // Java on Windows has a bug where if we try to manually set the position of the Window, // javaw.exe will not close itself down when the application is closed. // Therefore, even if isWindowPositioningEnabled, if we are on Windows, we ignore it. return osName == null || osName.startsWith("Windows"); } private static boolean isWindowPositioningEnabled() { boolean isEnabled = Utils.getConfigBoolean("window.position", true); return isEnabled && !hasWindowPositionBug(); } private static void saveWindowPosition(Frame frame) { if (!isWindowPositioningEnabled()) { return; } Point point; try { point = frame.getLocationOnScreen(); } catch (Exception e) { e.printStackTrace(); try { point = frame.getLocation(); } catch (Exception e2) { e2.printStackTrace(); return; } } int x = (int)point.getX(); int y = (int)point.getY(); int w = frame.getWidth(); int h = frame.getHeight(); Utils.setConfigInteger("window.x", x); Utils.setConfigInteger("window.y", y); Utils.setConfigInteger("window.w", w); Utils.setConfigInteger("window.h", h); logger.debug("Saved window position (x=" + x + ", y=" + y + ", w=" + w + ", h=" + h + ")"); } private static void restoreWindowPosition(Frame frame) { if (!isWindowPositioningEnabled()) { mainFrame.setLocationRelativeTo(null); // default to middle of screen return; } try { int x = Utils.getConfigInteger("window.x", -1); int y = Utils.getConfigInteger("window.y", -1); int w = Utils.getConfigInteger("window.w", -1); int h = Utils.getConfigInteger("window.h", -1); if (x < 0 || y < 0 || w <= 0 || h <= 0) { logger.debug("UNUSUAL: One or more of: x, y, w, or h was still less than 0 after reading config"); mainFrame.setLocationRelativeTo(null); // default to middle of screen return; } frame.setBounds(x, y, w, h); } catch (Exception e) { e.printStackTrace(); } } }
package com.s24.redjob.worker; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.util.AnnotatedTypeScanner; import org.springframework.util.Assert; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.ObjectMapper; /** * Scans the classpath and registers JSON subtypes ({@link JsonTypeName}) at a {@link ObjectMapper}. */ public class TypeScanner extends AnnotatedTypeScanner { /** * Redis serializer for job executions. */ @Autowired private ExecutionRedisSerializer executions; /** * Base packages to scan. */ private String[] basePackages; @PostConstruct public void afterPropertiesSet() { Assert.notNull(executions, "Precondition violated: json != null."); Assert.notNull(basePackages, "Precondition violated: basePackages != null."); ObjectMapper objectMapper = executions.getObjectMapper(); findTypes(basePackages).forEach(objectMapper::registerSubtypes); } /** * Constructor. */ public TypeScanner() { super(JsonTypeName.class); } /** * Redis serializer for job executions. */ public ExecutionRedisSerializer getExecutions() { return executions; } /** * Redis serializer for job executions. */ public void setExecutions(ExecutionRedisSerializer executions) { this.executions = executions; } /** * Base packages to scan. */ public String[] getBasePackages() { return basePackages; } /** * Base packages to scan. */ public void setBasePackages(String... basePackages) { this.basePackages = basePackages; } }
package com.sdl.bootstrap.form; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class DatePicker extends WebLocator { private static final Logger LOGGER = LoggerFactory.getLogger(DatePicker.class); private WebLocator input = new WebLocator(this).setClasses("icon-calendar").setInfoMessage("Open Calendar"); private WebLocator dataPicker = new WebLocator().setClasses("datepicker-dropdown dropdown-menu").setStyle("display: block;"); private WebLocator dataPickerDays = new WebLocator(dataPicker).setClasses("datepicker-days").setStyle("display: block;"); private WebLocator dataPickerMonths = new WebLocator(dataPicker).setClasses("datepicker-months").setStyle("display: block;"); private WebLocator dataPickerYear = new WebLocator(dataPicker).setClasses("datepicker-years").setStyle("display: block;"); private WebLocator switchDay = new WebLocator(dataPickerDays).setClasses("switch").setInfoMessage("switchMonth"); private WebLocator switchMonth = new WebLocator(dataPickerMonths).setClasses("switch").setInfoMessage("switchYear"); private WebLocator monthSelect = new WebLocator(dataPickerMonths).setClasses("month"); private WebLocator yearSelect = new WebLocator(dataPickerYear).setClasses("year"); private WebLocator daySelect = new WebLocator(dataPickerDays).setClasses("day"); public WebLocator getInput() { return input; } public WebLocator getMonthSelect() { return monthSelect; } public WebLocator getYearSelect() { return yearSelect; } public WebLocator getDaySelect() { return daySelect; } public DatePicker() { setClassName("DatePicker"); setClasses("date"); } public DatePicker(WebLocator container) { this(); setContainer(container); } public DatePicker(WebLocator container, String id) { this(container); setId(id); } /** * example new DatePicker().select("19/05/2013") * * @param date accept only this format: 'dd/MM/yyyy' * @return true if is selected date, false when DatePicker doesn't exist */ public boolean select(String date) { return select(date, "dd/MM/yyyy", Locale.ENGLISH); } public boolean select(String date, String format, Locale locale) { SimpleDateFormat inDateFormat = new SimpleDateFormat(format, locale); SimpleDateFormat outDateForm = new SimpleDateFormat("dd/MMM/yyyy"); try { Date fromDate = inDateFormat.parse(date); date = outDateForm.format(fromDate); } catch (ParseException e) { LOGGER.error("ParseException: {}", e); } String[] dates = date.split("/"); return setDate(Integer.parseInt(dates[0]) + "", dates[1], dates[2]); } public boolean setDate(String day, String month, String year) { if (getInput().click()) { boolean ok = true; getMonthSelect().setText(month); String fullDate = switchDay.getHtmlText(); if (!fullDate.contains(year)) { switchDay.click(); switchMonth.click(); getYearSelect().setText(year, SearchType.EQUALS); ok = getYearSelect().click() && getMonthSelect().click(); } else if (!fullDate.contains(month)) { switchDay.click(); ok = getMonthSelect().click(); } getDaySelect().setText(day, SearchType.EQUALS); return ok && getDaySelect().click(); } return false; } public String getDate() { WebLocator webLocator = new WebLocator(this, "//input"); return webLocator.getAttribute("value"); } }
package lucee.commons.io.log; import java.io.PrintStream; import lucee.commons.io.log.log4j.LogAdapter; import lucee.commons.lang.ExceptionUtil; /** * Helper class for the logs */ public final class LogUtil { public static final int LEVEL_TRACE=5; // FUTURE add to Log interface, if log interface not get removed public static void log(Log log, int level, String logName, Throwable t) { log(log,level,logName,"",t); } public static void log(Log log, int level, String logName,String msg, Throwable t) { if(log instanceof LogAdapter) { ((LogAdapter)log).log(level, logName, msg,t); } else { String em = ExceptionUtil.getMessage(t); String est = ExceptionUtil.getStacktrace(t, false); if(msg.equals(em)) msg=em+";"+est; else msg+=";"+em+";"+est; if(log!=null) { log.log(level, logName,msg); } else { PrintStream ps=(level>=Log.LEVEL_WARN)?System.err:System.out; ps.println(logName+";"+msg); } } } public static void log(Log log, int level, String logName, String msg, StackTraceElement[] stackTrace) { Throwable t = new Throwable(); t.setStackTrace(stackTrace); log(log,level,logName,msg,t); } }
package com.sdl.selenium.extjs6.grid; import com.sdl.selenium.web.SearchType; import com.sdl.selenium.web.WebLocator; import com.sdl.selenium.web.table.Table; import com.sdl.selenium.web.utils.RetryUtils; import com.sdl.selenium.web.utils.Utils; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.Collections; import java.util.List; @Slf4j public class Grid extends Table implements Scrollable { public Grid() { setClassName("Grid"); setBaseCls("x-grid"); setTag("*"); WebLocator header = new WebLocator().setClasses("x-title").setRoot(" setTemplateTitle(new WebLocator(header)); } public Grid(WebLocator container) { this(); setContainer(container); } /** * <pre>{@code * Grid grid = new Grid().setHeaders("Company", "Price", "Change"); * }</pre> * * @param headers grid's headers in order * @param <T> element which extended the Grid * @return this Grid */ public <T extends Table> T setHeaders(final String... headers) { List<WebLocator> list = new ArrayList<>(); for (int i = 0; i < headers.length; i++) { WebLocator headerEL = new WebLocator(this).setTag("*[" + (i + 1) + "]").setClasses("x-column-header"). setText(headers[i], SearchType.DEEP_CHILD_NODE_OR_SELF, SearchType.EQUALS); list.add(headerEL); } setChildNodes(list.stream().toArray(WebLocator[]::new)); return (T) this; } @Override public Row getRow(int rowIndex) { return new Row(this, rowIndex).setInfoMessage("-Row"); } public Group getGroup(String groupName) { return new Group(this, groupName).setInfoMessage("-Group"); } public Group getGroup(int rowIndex) { return new Group(this, rowIndex).setInfoMessage("-Group"); } @Override public Row getRow(String searchElement) { return new Row(this, searchElement, SearchType.EQUALS).setInfoMessage("-Row"); } @Override public Row getRow(String searchElement, SearchType... searchTypes) { return new Row(this, searchElement, searchTypes).setInfoMessage("-Row"); } public Row getRow(Cell... byCells) { return new Row(this, byCells).setInfoMessage("-Row"); } public Row getRow(int indexRow, Cell... byCells) { return new Row(this, indexRow, byCells).setInfoMessage("-Row"); } @Override public Cell getCell(int rowIndex, int columnIndex) { Row row = getRow(rowIndex); return new Cell(row, columnIndex).setInfoMessage("cell - Table"); } @Override public Cell getCell(String searchElement, SearchType... searchTypes) { Row row = new Row(this); return new Cell(row).setText(searchElement, searchTypes); } public Cell getCell(int rowIndex, int columnIndex, String text) { Row row = getRow(rowIndex); return new Cell(row, columnIndex, text, SearchType.EQUALS); } public Cell getCell(String searchElement, String columnText, SearchType... searchTypes) { Row row = getRow(searchElement, SearchType.CONTAINS); return new Cell(row).setText(columnText, searchTypes); } @Override public Cell getCell(String searchElement, int columnIndex, SearchType... searchTypes) { return new Cell(new Row(this, searchElement, searchTypes), columnIndex); } public Cell getCell(int columnIndex, Cell... byCells) { return new Cell(getRow(byCells), columnIndex); } public Cell getCell(int columnIndex, String text, Cell... byCells) { return new Cell(getRow(byCells), columnIndex, text, SearchType.EQUALS); } public boolean waitToActivate(int seconds) { String info = toString(); int count = 0; boolean hasMask; while ((hasMask = hasMask()) && (count < seconds)) { count++; log.info("waitToActivate:" + (seconds - count) + " seconds; " + info); Utils.sleep(900); } return !hasMask; } private boolean hasMask() { WebLocator mask = new WebLocator(this).setClasses("x-mask").setElPathSuffix("style", "not(contains(@style, 'display: none'))").setAttribute("aria-hidden", "false").setInfoMessage("Mask"); return mask.waitToRender(500L, false); } @Override public boolean waitToPopulate(int seconds) { Row row = getRow(1).setVisibility(true).setRoot("//..//").setInfoMessage("first Row"); WebLocator body = new WebLocator(this).setClasses("x-grid-header-ct"); // TODO see if must add for all rows row.setContainer(body); return row.waitToRender(seconds * 1000L); } public List<String> getHeaders() { List<String> headers = new ArrayList<>(); WebLocator header = new WebLocator(this).setClasses("x-grid-header-ct"); String headerText = RetryUtils.retrySafe(4, header::getText); Collections.addAll(headers, headerText.trim().split("\n")); return headers; } @Override public List<List<String>> getCellsText(int... excludedColumns) { Row rowsEl = new Row(this); Row rowEl = new Row(this, 1); Cell columnsEl = new Cell(rowEl); int rows = rowsEl.size(); int columns = columnsEl.size(); List<Integer> columnsList = getColumns(columns, excludedColumns); if (rows <= 0) { return null; } else { List<List<String>> listOfList = new ArrayList<>(); boolean canRead = true; String id = ""; int timeout = 0; do { for (int i = 1; i <= rows; ++i) { if (canRead) { List<String> list = new ArrayList<>(); for (int j : columnsList) { list.add(this.getCell(i, j).getText(true).trim()); } listOfList.add(list); } else { String currentId = new Row(this, i).getAttributeId(); if (!"".equals(id) && id.equals(currentId)) { canRead = true; } } } if (isScrollBottom()) { break; } id = new Row(this, rows).getAttributeId(); scrollPageDownInTree(); canRead = false; timeout++; } while (timeout < 30); return listOfList; } } public List<List<String>> getCellsText(String group, int... excludedColumns) { Group groupEl = getGroup(group); groupEl.expand(); List<Row> groupElRows = groupEl.getRows(); Cell columnsEl = new Cell(groupElRows.get(1)); int rows = groupElRows.size(); int columns = columnsEl.size(); List<Integer> columnsList = getColumns(columns, excludedColumns); if (rows <= 0) { return null; } else { List<List<String>> listOfList = new ArrayList<>(); boolean canRead = true; String id = ""; int timeout = 0; do { for (int i = 0; i < rows; ++i) { if (canRead) { List<String> list = new ArrayList<>(); for (int j : columnsList) { list.add(groupElRows.get(i).getCell(j).getText(true).trim()); } listOfList.add(list); } else { String currentId = new Row(this, i + 1).getAttributeId(); if (!"".equals(id) && id.equals(currentId)) { canRead = true; } } } if (isScrollBottom() || listOfList.size() >= rows) { break; } id = new Row(this, rows).getAttributeId(); scrollPageDownInTree(); canRead = false; timeout++; } while (listOfList.size() < rows && timeout < 30); return listOfList; } } @Override public int getCount() { if (ready(true)) { return new Row(this).size(); } else { return -1; } } public List<String> getGroupsName() { Group group = new Group(this); int size = group.size(); List<String> list = new ArrayList<>(); for (int i = 1; i <= size; i++) { group.setResultIdx(i); list.add(group.getNameGroup()); } return list; } public String getNextGroupName(String groupName) { Group group = new Group(this); int size = group.size(); for (int i = 1; i <= size; i++) { group.setResultIdx(i); String g = group.getNameGroup().toLowerCase(); if (g.contains(groupName.toLowerCase())) { group.setResultIdx(i + 1); String nameGroup = group.getNameGroup(); return nameGroup.substring(0, 1).toUpperCase() + nameGroup.substring(1).toLowerCase(); } } return null; } }
package acx.lam; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; public class HashMaglev16Balancer<T extends Cell> { private static final Logger logger = LoggerFactory.getLogger(HashMaglev16Balancer.class); private static final Charset KEY_ENCODING = StandardCharsets.US_ASCII; private static final Charset INPUT_ENCODING = StandardCharsets.UTF_8; private static final int MAX_LOOKUP = 65521; public static final int SPARE = 20; private int nServers; private int mSizeLookup; private Comparator<T> comparator; private ArrayList<T> cells; private ArrayList<CellState<T>> cellStates; private volatile char[] lookup; private static final HashFunction HASH_INPUT = Hashing.murmur3_32(0xaceaceac); private static final HashFunction HASH_OFFSET = Hashing.murmur3_32(0xdeadbabe); private static final HashFunction HASH_SKIP = Hashing.murmur3_32(0xdeadbeaf); private ArrayList<Cell> cellsBackup; //for add/remove stats only private int lastDelta; //for add/remove stats only private static class CellState<T> { //will not change private int offset; private int skip; private char[] row; //will change private int nextPos; private int last; private void reset() { this.nextPos = 0; this.last = offset; } } public HashMaglev16Balancer(List<T> inputCells, Integer mSizeLookup, Comparator<T> comparator) throws Exception { if (inputCells == null || inputCells.size() == 0) { throw new Exception("Empty cells"); } if (mSizeLookup == null) { mSizeLookup = MAX_LOOKUP; } this.comparator = comparator; if (mSizeLookup > MAX_LOOKUP || inputCells.size() > MAX_LOOKUP) { throw new IllegalArgumentException("This implementation allows a max of 65521 servers or lookups"); } this.nServers = inputCells.size(); logger.debug("number of cells {}", nServers); int initialCapacity = nServers + SPARE; this.cells = new ArrayList<>(initialCapacity); cells.addAll(inputCells); this.mSizeLookup = mSizeLookup; long start = System.currentTimeMillis(); Collections.sort(cells, comparator); //isPrime(mSizeLookup); //not yet implemented generateServerStates(initialCapacity); generateLookupLazily(); printStats(start); } public int addCells(List<T> newCells) { if (newCells == null || newCells.size() == 0) { logger.debug("addCells: nothing to add"); return 0; } long start = System.currentTimeMillis(); int added = 0; logger.debug("start adding cells"); if(logger.isDebugEnabled()){ cellsBackup = (ArrayList<Cell>) cells.clone(); } synchronized (this) { for (T newCell : newCells) { int pos = Collections.binarySearch(cells, newCell, this.comparator); if (pos >= 0) { logger.debug("cell already exists"); continue; } int insertPoint = -(pos + 1); CellState state = this.createState(newCell.getUniqueKey()); cells.add(insertPoint, newCell); cellStates.add(insertPoint, state); initSomeColumns(state); added++; nServers++; } logger.debug("time used moving arrays: {}ms ", (System.currentTimeMillis() - start)); if(added > 0 ) { resetCellState(); this.lastDelta = added; this.generateLookupLazily(); } } logger.debug("{} cells appended to the cell list", added); logger.debug("lookup regen completed, total time used: {}ms ", (System.currentTimeMillis() - start)); return added; } private void initSomeColumns(CellState state) { for(int i = 1 ; i < mSizeLookup / nServers; ++i){ state.last = (state.last + state.skip)% mSizeLookup; state.row[i] = (char)(state.last+1); } } private void resetCellState() { for(CellState<T> state: cellStates){ state.reset(); } } public int removeCells(List<T> removeCells) { long start = System.currentTimeMillis(); if (removeCells == null || removeCells.size() == 0) { logger.debug("remove cells: nothing to remove"); return 0; } if (cells.size() == 0){ logger.debug("already empty"); return 0; } int removed = 0; logger.debug("start removing cells"); if(logger.isDebugEnabled()){ cellsBackup = (ArrayList<Cell>) cells.clone(); } synchronized (this) { for (T removeCell : removeCells) { int pos = Collections.binarySearch(cells, removeCell, this.comparator); if (pos < 0) { logger.debug("cell not exists"); continue; } cells.remove(pos); cellStates.remove(pos); nServers removed++; } logger.debug("time used moving arrays: {}ms ", (System.currentTimeMillis() - start)); if(removed > 0) { resetCellState(); this.lastDelta = -removed; this.generateLookupLazily(); } } logger.debug("{} cells removed from the cell list", removed); logger.debug("lookup regen done, total time used removing cells: {}ms ", (System.currentTimeMillis() - start)); return removed; } private void generateServerStates(int initialCapacity) { cellStates = new ArrayList<>(initialCapacity); for (int i = 0; i < nServers; ++i) { String key = cells.get(i).getUniqueKey(); CellState state = createState(key); cellStates.add(state); } } private CellState createState(String key) { CellState state = new CellState(); state.offset = (int) (HASH_OFFSET.hashString(key, KEY_ENCODING).padToLong() % mSizeLookup); state.skip = (int) (HASH_SKIP.hashString(key, KEY_ENCODING).padToLong() % (mSizeLookup - 1) + 1); state.last = state.offset; char[] row = new char[mSizeLookup]; row[0] = (char) (++state.offset); // initialized first column ,store as +1 state.row = row; return state; } private void generateLookupLazily() { char[] tmpLookup = new char[mSizeLookup]; int filled = 0; fillLookup(tmpLookup, filled); if(logger.isDebugEnabled()) { if (lookup != null){ int changed = 0; logger.debug("lookup changed:"); for (int i = 0; i < mSizeLookup; i++) { if(cellsBackup.get(lookup[i]-1) != cells.get(tmpLookup[i]-1)){ changed++; // uncomment to show disruptions // logger.debug("{}:{}->{}", i, cellsBackup.get(lookup[i]-1).getUniqueKey(), cells.get(tmpLookup[i]-1).getUniqueKey()); } } cellsBackup = null; float permChanged = ((float)changed * 100)/(float)mSizeLookup; float best; if (lastDelta > 0) { best =((float) (this.lastDelta * 100)) / (float) (nServers ); } else { best = ((float) ((-this.lastDelta) * 100)) / (float) (nServers - lastDelta ); } logger.debug("total num of changes: {}, permchanged {}%, best {}% ,disruption (delta - best) {}%" , changed, permChanged, best, (permChanged - best) ); lastDelta = 0; } } this.lookup = tmpLookup; // swap; } private void fillLookup(char[] tmpLookup, int filled) { outer: while(true) { for (int i = 0; i < nServers; ++i) { CellState state = cellStates.get(i); while(state.nextPos < mSizeLookup) { int c = getPermutation(state); state.nextPos++; if (tmpLookup[c] == 0) { //found tmpLookup[c] = (char) (i + 1); //Store i + 1 to avoid initialization filled++; if(filled == mSizeLookup){ return; //break outer } else{ break; // next server } } } } } } public T getInstance(String key) { if (key == null || nServers == 0) { return null; } if (nServers == 1) { return cells.get(0); } int index = (int) ((HASH_INPUT.hashString(key, INPUT_ENCODING).padToLong()) % mSizeLookup); return cells.get(lookup[index] - 1); } private int getPermutation(CellState state) { char c = state.row[state.nextPos]; if (c == 0) { if (state.nextPos == 0){ return state.offset; } int perm = (state.last + state.skip) % mSizeLookup; state.last = perm; state.row[state.nextPos] = (char) (perm + 1); //store to perm as i+1 return perm; } return --c; } private void printStats(long start) { logger.debug("time used {}ms", (System.currentTimeMillis() - start)); // printPermutationAndLookup(); //uncomment to see all the permutations and lookup int totalUsed = 0; for (CellState state : cellStates) { totalUsed += state.nextPos; } float occupation = (float) totalUsed * 100 / (float) MAX_LOOKUP / (float) nServers; logger.debug("total steps {}, percentage to all permutations {}%", totalUsed, occupation); logger.debug(" } private void printPermutationAndLookup() { StringBuilder sb = new StringBuilder(mSizeLookup * 2 + 10); for(int i = 0 ; i < nServers ; ++i){ for(int j = 0; j < mSizeLookup; ++j){ sb.append(cellStates.get(i).row[j] -1); sb.append(','); } sb.append("\r\n"); } logger.debug(sb.toString()); sb.setLength(0); sb.append('['); for (char entry : lookup) { sb.append((int) entry); sb.append(','); } sb.append(']'); logger.debug("lookup table:" + sb.toString()); } }
package com.sourcegraph.javagraph; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.util.JavacTask; import com.sun.source.util.TreePath; import com.sun.source.util.Trees; import com.sun.tools.javac.tree.JCTree; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.tools.*; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; import static com.sun.tools.javac.util.Position.NOPOS; public class Grapher { private static final Logger LOGGER = LoggerFactory.getLogger(Grapher.class); private final JavaCompiler compiler; private final DiagnosticCollector<JavaFileObject> diags; private final StandardJavaFileManager fileManager; private final GraphWriter emit; private final List<String> javacOpts; private final SourceUnit unit; /** * Constructs new grapher object * @param unit source unit * @param emit target responsible for emitting definitions and references * @throws Exception */ public Grapher(SourceUnit unit, GraphWriter emit) throws Exception { this.unit = unit; this.emit = emit; compiler = ToolProvider.getSystemJavaCompiler(); diags = new DiagnosticCollector<>(); fileManager = compiler.getStandardFileManager(diags, null, null); javacOpts = new ArrayList<>(); Collection<String> bootClassPath = unit.getProject().getBootClassPath(); if (bootClassPath == null) { String envBootClasspath = System.getProperty("sun.boot.class.path"); if (StringUtils.isEmpty(envBootClasspath)) { LOGGER.error("System property sun.boot.class.path is not set. It is required to load rt.jar."); System.exit(1); } bootClassPath = Arrays.asList(envBootClasspath.split(SystemUtils.PATH_SEPARATOR)); } Collection<File> bootClassPathFiles = new ArrayList<>(); Collection<String> resolvedBootClassPath = new ArrayList<>(); for (String path : bootClassPath) { Path resolvedPath = PathUtil.CWD.resolve(path).toAbsolutePath(); bootClassPathFiles.add(resolvedPath.toFile()); resolvedBootClassPath.add(resolvedPath.toString()); } fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, bootClassPathFiles); javacOpts.add("-Xbootclasspath:" + StringUtils.join(resolvedBootClassPath, SystemUtils.PATH_SEPARATOR)); Collection<String> classPath = unit.getProject().getClassPath(); if (classPath == null) { classPath = Collections.emptyList(); } Collection<File> classPathFiles = new ArrayList<>(); Collection<String> resolvedClassPath = new ArrayList<>(); for (String path : classPath) { Path resolvedPath = PathUtil.CWD.resolve(path).toAbsolutePath(); classPathFiles.add(resolvedPath.toFile()); resolvedClassPath.add(resolvedPath.toString()); } fileManager.setLocation(StandardLocation.CLASS_PATH, classPathFiles); javacOpts.add("-classpath"); javacOpts.add(StringUtils.join(resolvedClassPath, SystemUtils.PATH_SEPARATOR)); Collection<String> sourcePath = unit.getProject().getSourcePath(); if (sourcePath != null && !sourcePath.isEmpty()) { javacOpts.add("-sourcepath"); Collection<String> resolvedSourcePath = new ArrayList<>(); Collection<File> sourcePathFiles = new ArrayList<>(); for (String path : sourcePath) { Path resolvedPath = PathUtil.CWD.resolve(path).toAbsolutePath(); resolvedSourcePath.add(resolvedPath.toString()); sourcePathFiles.add(resolvedPath.toFile()); } javacOpts.add(StringUtils.join(resolvedSourcePath, SystemUtils.PATH_SEPARATOR)); fileManager.setLocation(StandardLocation.SOURCE_PATH, sourcePathFiles); } // Speed up compilation by not doing dataflow, code gen, etc. javacOpts.add("-XDcompilePolicy=attr"); javacOpts.add("-XDshouldStopPolicyIfError=ATTR"); javacOpts.add("-XDshouldStopPolicyIfNoError=ATTR"); String sourceVersion = unit.getProject().getSourceCodeVersion(); if (!StringUtils.isEmpty(sourceVersion)) { javacOpts.add("-source"); javacOpts.add(sourceVersion); } javacOpts.add("-implicit:none"); // turn off warnings javacOpts.add("-Xlint:none"); String sourceEncoding = unit.getProject().getSourceCodeEncoding(); if (!StringUtils.isEmpty(sourceEncoding)) { javacOpts.add("-encoding"); javacOpts.add(sourceEncoding); } // This is necessary to produce Elements (and therefore defs and refs) when compilation errors occur. It will still probably fail on syntax errors, but typechecking errors are survivable. javacOpts.add("-proc:none"); } /** * Builds a graph of given files and directories. * @param filePaths collection of file path elements to graph sources of. If element is a file it will be scheduled * for graphing, otherwise, if element is a directory, we'll schedule for graphing all java files located in the * given directory recursively. Each element should point to existing file/directory * @throws IOException */ public void graphFilesAndDirs(Collection<String> filePaths) throws IOException { LOGGER.debug("Collecting source files to graph"); File root = PathUtil.CWD.toFile(); final List<String> files = new ArrayList<>(); for (String filePath : filePaths) { File file = PathUtil.concat(root, filePath); if (!file.exists()) { LOGGER.error("No such file {}", file.getAbsolutePath()); System.exit(1); } if (file.isFile()) { files.add(file.toPath().normalize().toString()); } else if (file.isDirectory()) { Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (attrs.isRegularFile() && file.toString().endsWith(".java")) { files.add(file.normalize().toString()); } return FileVisitResult.CONTINUE; } }); } } LOGGER.debug("Collected source files to graph"); graphFiles(files); } /** * Builds a graph of given files * @param files collection of file path elements to graph sources of. Each element should point to existing file * @throws IOException */ public void graphFiles(Collection<String> files) throws IOException { if (LOGGER.isDebugEnabled()) { LOGGER.debug("javac {} {}", StringUtils.join(javacOpts, ' '), StringUtils.join(files, ' ')); } graphJavaFiles(fileManager.getJavaFileObjectsFromStrings(files)); } /** * Builds a graph of given file objects * * @param files list of file objects to build graphs for * @throws IOException */ public void graphJavaFiles(Iterable<? extends JavaFileObject> files) throws IOException { final JavacTask task = (JavacTask) compiler.getTask(null, fileManager, diagnostic -> { LOGGER.warn("{} javac: {}", unit.Name, diagnostic); }, javacOpts, null, files); final Trees trees = Trees.instance(task); final Set<String> seenPackages = new HashSet<>(); try { Iterable<? extends CompilationUnitTree> units = task.parse(); task.analyze(); for (final CompilationUnitTree unit : units) { try { ExpressionTree pkgName = unit.getPackageName(); if (pkgName != null && !seenPackages.contains(pkgName.toString()) && (isPackageInfo(unit) || !hasPackageInfo(pkgName.toString(), files))) { seenPackages.add(pkgName.toString()); writePackageSymbol(pkgName, unit, trees); } TreePath root = new TreePath(unit); new TreeScanner(emit, trees, this.unit).scan(root, null); } catch (Exception e) { LOGGER.warn("Skipping compilation unit {} ({})", unit.getPackageName(), unit.getSourceFile(), e); } } } catch (Exception e) { LOGGER.warn("Compilation failed", e); for (Diagnostic<?> diagnostic : diags.getDiagnostics()) { LOGGER.warn("Error on line {} in {}", diagnostic.getLineNumber(), diagnostic.getSource()); } LOGGER.warn("If the stack trace contains \"task.analyze();\", there's a reasonable chance you're using a buggy compiler.\n" + "As of Nov 7, 2014, the Oracle 8 JDK is one of those compilers.\n" + "See https://bugs.openjdk.java.net/browse/JDK-8062359?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel\n" + "and compile OpenJDK 8 with that workaround. OpenJDK 8 build instructions: http://openjdk.java.net/projects/build-infra/guide.html\nWe can remove this once jdk 8u26+ is released. NOTE that you need to install from the jdk8u hg repo, not jdk8 (as that is frozen when the first version of jdk8 was released)."); System.exit(1); } } /** * @param packageName package name to check * @param files list of source unit files * @return true if there is explicit package info file (package-info.java) for the given package in the * given files list */ private boolean hasPackageInfo(String packageName, Iterable<? extends JavaFileObject> files) { Path p = Paths.get(packageName.replace('.', File.separatorChar)).resolve("package-info.java"); for (JavaFileObject file : files) { Path candidate = Paths.get(file.getName()); if (candidate.endsWith(p)) { return true; } } return false; } /** * @param unit compilation unit * @return true if given compilation unit matches .../package-info.java */ private boolean isPackageInfo(CompilationUnitTree unit) { return unit.getSourceFile().getName().endsWith("package-info.java"); } /** * Emits package object definition to graph * @param packageTree package AST node * @param compilationUnit current compilation unit * @param trees trees object * @throws IOException */ private void writePackageSymbol(ExpressionTree packageTree, CompilationUnitTree compilationUnit, Trees trees) throws IOException { Def s = new Def(unit.Name, unit.Type); String packageName = packageTree.toString(); // TODO(sqs): set origin to the JAR this likely came from (it's hard because it could be from multiple JARs) s.defKey = new DefKey(null, packageName); s.name = packageName.substring(packageName.lastIndexOf('.') + 1); s.kind = "PACKAGE"; s.pkg = packageName; if (isPackageInfo(compilationUnit)) { if (packageTree instanceof JCTree.JCFieldAccess) { JCTree.JCFieldAccess fieldAccessTree = (JCTree.JCFieldAccess) packageTree; int start = (int) trees.getSourcePositions().getStartPosition(compilationUnit, fieldAccessTree.selected); int end = (int) trees.getSourcePositions().getEndPosition(compilationUnit, fieldAccessTree.selected); if (start != NOPOS && end != NOPOS) { s.defStart = start; s.defEnd = end; } } else if (packageTree instanceof JCTree.JCIdent) { int start = (int) trees.getSourcePositions().getStartPosition(compilationUnit, packageTree); int end = (int) trees.getSourcePositions().getEndPosition(compilationUnit, packageTree); if (start != NOPOS && end != NOPOS) { s.defStart = start; s.defEnd = end; } } s.file = compilationUnit.getSourceFile().getName(); s.doc = trees.getDocComment(getRootPath(trees.getPath(compilationUnit, packageTree))); } emit.writeDef(s); } /** * Closes grapher and releases underlying resources * @throws IOException */ public void close() throws IOException { emit.flush(); fileManager.close(); } /** * @param path tree path, e.g. foo/bar/baz * @return root path (foo) that has no parent tree path */ private TreePath getRootPath(TreePath path) { TreePath parent = path == null ? null : path.getParentPath(); while (parent != null) { path = parent; parent = path.getParentPath(); } return path; } }
package com.toomasr.sgf4j.parser; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; import com.toomasr.sgf4j.board.StoneState; public class GameNode implements Comparable<GameNode>, Cloneable { private final Set<GameNode> children = new TreeSet<>(); private final Map<String, String> properties = new HashMap<>(); private int moveNo = -1; private int nodeNo = -1; private int visualDepth = -1; private GameNode parentNode; private GameNode nextNode = null; private GameNode prevNode = null; private int id; /** * Constructs a new node with the argument as the parent. * * @param parentNode node to be the parent of the just created node. */ public GameNode(GameNode parentNode) { this.parentNode = parentNode; } public void addProperty(String key, String value) { properties.put(key, value); } public String getProperty(String key) { return properties.get(key); } public String getProperty(String key, String defaultValue) { if (properties.get(key) == null) return defaultValue; else return properties.get(key); } public Map<String, String> getProperties() { return properties; } public boolean isMove() { return properties.get("W") != null || properties.get("B") != null; } public String getMoveString() { if (properties.get("W") != null) { return properties.get("W"); } else if (properties.get("B") != null) { return properties.get("B"); } else { //throw new RuntimeException("Unable to extract move from " + properties.toString()); return null; } } public int[] getCoords() { String moveStr = getMoveString(); int[] moveCoords = Util.alphaToCoords(moveStr); return moveCoords; } public boolean isWhite() { return properties.get("W") != null; } public boolean isBlack() { return properties.get("B") != null; } public String getColor() { if (properties.get("W") != null) return "W"; return "B"; } public StoneState getColorAsEnum() { if (properties.get("W") != null) return StoneState.WHITE; return StoneState.BLACK; } public void addChild(GameNode node) { if (nextNode == null) { nextNode = node; nextNode.setVisualDepth(0); node.setPrevNode(this); return; } if (children.contains(node)) { throw new RuntimeException("Node '" + node + "' already exists for " + this); } children.add(node); } public boolean hasChildren() { return children.size() > 0; } public Set<GameNode> getChildren() { return children; } public GameNode getParentNode() { return parentNode; } public void setParentNode(GameNode node) { parentNode = node; } public String toString() { return "Props: keys=" + properties.keySet().toString() + " all=" + properties.toString() + " moveNo: " + moveNo + " children: " + children.size() + " vdepth: " + visualDepth+ " parentNode: "+getParentNode(); } public void setMoveNo(int i) { this.moveNo = i; } public int getMoveNo() { return moveNo; } public boolean isEmpty() { if (properties.isEmpty() && children.size() == 0) return true; return false; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } /* * Don't add id to the list. The id is generated during parsing * is more like transient. * */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((children == null) ? 0 : children.hashCode()); result = prime * result + moveNo; result = prime * result + ((parentNode == null) ? 0 : parentNode.properties.hashCode()); result = prime * result + ((properties == null) ? 0 : properties.hashCode()); result = prime * result + visualDepth; return result; } /* * Don't add id to the list. The id is generated during parsing * is more like transient. * */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GameNode other = (GameNode) obj; if (children == null) { if (other.children != null) return false; } else if (!children.equals(other.children)) return false; if (moveNo != other.moveNo) return false; if (parentNode == null) { if (other.parentNode != null) return false; } else if (!parentNode.equals(other.parentNode)) return false; if (properties == null) { if (other.properties != null) return false; } else if (!properties.equals(other.properties)) return false; if (visualDepth != other.visualDepth) return false; return true; } @Override public int compareTo(GameNode o) { if (this.visualDepth < o.visualDepth) return -1; if (this.visualDepth > o.visualDepth) return 1; if (this.moveNo < o.moveNo) return -1; if (this.moveNo > o.moveNo) return 1; // so the move no is the same and the depth is the same if (this.hashCode() < o.hashCode()) return -1; else if (this.hashCode() > o.hashCode()) return 1; return 0; } public void setVisualDepth(int visualDepth) { this.visualDepth = visualDepth; } public int getVisualDepth() { return visualDepth; } public GameNode getNextNode() { return nextNode; } public void setNextNode(GameNode nextNode) { this.nextNode = nextNode; } public GameNode getPrevNode() { return prevNode; } public void setPrevNode(GameNode node) { this.prevNode = node; } public boolean isPass() { // tt means a pass and actually an empty [] also // but right now not handling that because I don't know // how exactly it looks like in a SGF if (!isPlacementMove() && "tt".equals(getMoveString())) { return true; } return false; } /** * There are moves that actually don't place a stone of a * move but rather a new added position. I call this a placementMove * * @return true if this is a placement move and not a game move */ public boolean isPlacementMove() { return properties.get("W") == null && properties.get("B") == null && (properties.get("AB") != null || properties.get("AW") != null); } public void setNodeNo(int nodeNo) { this.nodeNo = nodeNo; } public int getNodeNo() { return this.nodeNo; } public String getSgfComment() { return properties.getOrDefault("C", ""); } public void setId(int id) { this.id = id; } public int getId() { return this.id; } }
package com.ueffort.study.base; public class IndexMinPQ<Key extends Comparable<Key>> { private Node[] pq; private int N = 0; // pq[1..N]pq[0] private Node[] iq; private class Node{ private int index; private Key key; private int priority; public Node(int index, Key key, int priority){ this.index = index; this.key = key; this.priority = priority; } } public IndexMinPQ(int maxN){ pq = (Node[]) new Object[maxN + 1]; iq = (Node[]) new Object[maxN + 1]; } public boolean isEmpty(){ return N == 0; } public int size(){ return N; } public void insert(int index, Key v){ N++; Node n = new Node(index, v, N); pq[N] = n; iq[index] = n; swim(N); } public void change(int index, Key k){ iq[index].key = k; swim(iq[index].priority); } public Key delMin(){ Node min = pq[0]; exch(1, N--); pq[N + 1] = null; iq[min.index] = null; sink(1); return min.key; } public boolean contains(int index){ return iq[index] != null; } private boolean more(int i, int j){ return pq[i].key.compareTo(pq[j].key) > 0; } private void exch(int i, int j){ Node t = pq[i]; pq[i] = pq[j]; pq[j] = t; pq[i].priority = i; pq[j].priority = j; } /** * * * @param k */ private void swim(int k){ while(k > 1 && more(k / 2, k)){ exch(k / 2, k); k = k / 2; } } /** * * * @param k */ private void sink(int k){ while(2 * k <= N){ int j = 2 * k; if (j < N && more(j, j+1)) j++; if (!more(k, j))break; exch(k, j); k = j; } } }
package coyote.commons.network.http; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.security.KeyStore; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import java.util.regex.Pattern; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.TrustManagerFactory; import coyote.loader.log.Log; /** * This is the core of the HTTP Server. * * <p>This class should be subclassed and the {@link #serve(IHTTPSession)} * method overridden to serve the request.</p> */ public abstract class HTTPD { public static final String CLASS = "HTTPD"; public static final long EVENT = Log.getCode( CLASS ); private static final String CONTENT_DISPOSITION_REGEX = "([ |\t]*Content-Disposition[ |\t]*:)(.*)"; static final Pattern CONTENT_DISPOSITION_PATTERN = Pattern.compile( CONTENT_DISPOSITION_REGEX, Pattern.CASE_INSENSITIVE ); private static final String CONTENT_TYPE_REGEX = "([ |\t]*content-type[ |\t]*:)(.*)"; static final Pattern CONTENT_TYPE_PATTERN = Pattern.compile( CONTENT_TYPE_REGEX, Pattern.CASE_INSENSITIVE ); private static final String CONTENT_DISPOSITION_ATTRIBUTE_REGEX = "[ |\t]*([a-zA-Z]*)[ |\t]*=[ |\t]*['|\"]([^\"^']*)['|\"]"; static final Pattern CONTENT_DISPOSITION_ATTRIBUTE_PATTERN = Pattern.compile( CONTENT_DISPOSITION_ATTRIBUTE_REGEX ); /** * Maximum time to wait on Socket.getInputStream().read() (in milliseconds) * This is required as the Keep-Alive HTTP connections would otherwise block * the socket reading thread forever (or as long the browser is open). */ public static final int SOCKET_READ_TIMEOUT = 5000; /** Common MIME type for dynamic content: plain text */ public static final String MIME_PLAINTEXT = "text/plain"; /** Common MIME type for dynamic content: html */ public static final String MIME_HTML = "text/html"; /** * Pseudo-Parameter to use to store the actual query string in the * parameters map for later re-processing. */ private static final String QUERY_STRING_PARAMETER = "Httpd.QUERY_STRING"; /** Hashtable mapping file extension to mime type */ protected static Map<String, String> MIME_TYPES; final String hostname; final int myPort; volatile ServerSocket myServerSocket; private ServerSocketFactory serverSocketFactory = new DefaultServerSocketFactory(); private Thread myThread; /** Pluggable strategy for asynchronously executing requests. */ protected AsyncRunner asyncRunner; /** Pluggable strategy for creating and cleaning up temporary files. */ TempFileManagerFactory tempFileManagerFactory; /** * Decode parameters from a URL, handing the case where a single parameter * name might have been supplied several times, by return lists of values. * * <p>In general these lists will contain a single element.</p> * * @param parms original HTTPD parameters values, as passed to the * {@code serve()} method. * @return a map of {@code String} (parameter name) to * {@code List<String>} - a list of the values supplied. */ protected static Map<String, List<String>> decodeParameters( final Map<String, String> parms ) { return decodeParameters( parms.get( HTTPD.QUERY_STRING_PARAMETER ) ); } /** * Decode parameters from a URL, handing the case where a single parameter * name might have been supplied several times, by return lists of values. * * <p>In general these lists will contain a single element.</p> * * @param queryString a query string pulled from the URL. * @return a map of {@code String} (parameter name) to * {@code List<String>} (a list of the values supplied). */ protected static Map<String, List<String>> decodeParameters( final String queryString ) { final Map<String, List<String>> parms = new HashMap<String, List<String>>(); if ( queryString != null ) { final StringTokenizer st = new StringTokenizer( queryString, "&" ); while ( st.hasMoreTokens() ) { final String e = st.nextToken(); final int sep = e.indexOf( '=' ); final String propertyName = sep >= 0 ? decodePercent( e.substring( 0, sep ) ).trim() : decodePercent( e ).trim(); if ( !parms.containsKey( propertyName ) ) { parms.put( propertyName, new ArrayList<String>() ); } final String propertyValue = sep >= 0 ? decodePercent( e.substring( sep + 1 ) ) : null; if ( propertyValue != null ) { parms.get( propertyName ).add( propertyValue ); } } } return parms; }; /** * Decode percent encoded {@code String} values. * * @param str the percent encoded {@code String} * * @return expanded form of the input, for example "foo%20bar" becomes * "foo bar" */ protected static String decodePercent( final String str ) { String decoded = null; try { decoded = URLDecoder.decode( str, "UTF8" ); } catch ( final UnsupportedEncodingException ignored ) { Log.append( EVENT, "Encoding not supported, ignored", ignored ); } return decoded; } /** * Get MIME type from file name extension, if possible * * @param uri the string representing a file * * @return the connected mime/type */ public static String getMimeTypeForFile( final String uri ) { final int dot = uri.lastIndexOf( '.' ); String mime = null; if ( dot >= 0 ) { mime = mimeTypes().get( uri.substring( dot + 1 ).toLowerCase() ); } return mime == null ? "application/octet-stream" : mime; } @SuppressWarnings({ "unchecked", "rawtypes" }) private static void loadMimeTypes( final Map<String, String> result, final String resourceName ) { try { final Enumeration<URL> resources = HTTPD.class.getClassLoader().getResources( resourceName ); while ( resources.hasMoreElements() ) { final URL url = resources.nextElement(); final Properties properties = new Properties(); InputStream stream = null; try { stream = url.openStream(); properties.load( url.openStream() ); } catch ( final IOException e ) { Log.append( EVENT, "could not load mimetypes from " + url, e ); } finally { safeClose( stream ); } result.putAll( (Map)properties ); } } catch ( final IOException e ) { Log.append( EVENT, "no mime types available at " + resourceName ); } } /** * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an * array of loaded KeyManagers. These objects must properly * loaded/initialized by the caller. */ public static SSLServerSocketFactory makeSSLSocketFactory( final KeyStore loadedKeyStore, final KeyManager[] keyManagers ) throws IOException { SSLServerSocketFactory res = null; try { final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm() ); trustManagerFactory.init( loadedKeyStore ); final SSLContext ctx = SSLContext.getInstance( "TLS" ); ctx.init( keyManagers, trustManagerFactory.getTrustManagers(), null ); res = ctx.getServerSocketFactory(); } catch ( final Exception e ) { throw new IOException( e.getMessage() ); } return res; } /** * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a * loaded KeyManagerFactory. These objects must properly loaded/initialized * by the caller. */ public static SSLServerSocketFactory makeSSLSocketFactory( final KeyStore loadedKeyStore, final KeyManagerFactory loadedKeyFactory ) throws IOException { try { return makeSSLSocketFactory( loadedKeyStore, loadedKeyFactory.getKeyManagers() ); } catch ( final Exception e ) { throw new IOException( e.getMessage() ); } } /** * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your * certificate and passphrase */ public static SSLServerSocketFactory makeSSLSocketFactory( final String keyAndTrustStoreClasspathPath, final char[] passphrase ) throws IOException { try { final KeyStore keystore = KeyStore.getInstance( KeyStore.getDefaultType() ); final InputStream keystoreStream = HTTPD.class.getResourceAsStream( keyAndTrustStoreClasspathPath ); if ( keystoreStream == null ) { throw new IOException( "Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath ); } keystore.load( keystoreStream, passphrase ); final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() ); keyManagerFactory.init( keystore, passphrase ); return makeSSLSocketFactory( keystore, keyManagerFactory ); } catch ( final Exception e ) { throw new IOException( e.getMessage() ); } } public static Map<String, String> mimeTypes() { if ( MIME_TYPES == null ) { MIME_TYPES = new HashMap<String, String>(); loadMimeTypes( MIME_TYPES, "httpd/default-mimetypes.properties" ); loadMimeTypes( MIME_TYPES, "httpd/mimetypes.properties" ); if ( MIME_TYPES.isEmpty() ) { Log.append( EVENT, "no mime types found in the classpath! please provide mimetypes.properties" ); } } return MIME_TYPES; } /** * Create a response with unknown length (using HTTP 1.1 chunking). */ public static Response newChunkedResponse( final IStatus status, final String mimeType, final InputStream data ) { return new Response( status, mimeType, data, -1 ); } /** * Create a response with known length. */ public static Response newFixedLengthResponse( final IStatus status, final String mimeType, final InputStream data, final long totalBytes ) { return new Response( status, mimeType, data, totalBytes ); } /** * Create a text response with known length. */ public static Response newFixedLengthResponse( final IStatus status, final String mimeType, final String txt ) { ContentType contentType = new ContentType( mimeType ); if ( txt == null ) { return newFixedLengthResponse( status, mimeType, new ByteArrayInputStream( new byte[0] ), 0 ); } else { byte[] bytes; try { final CharsetEncoder newEncoder = Charset.forName( contentType.getEncoding() ).newEncoder(); if ( !newEncoder.canEncode( txt ) ) { contentType = contentType.tryUTF8(); } bytes = txt.getBytes( contentType.getEncoding() ); } catch ( final UnsupportedEncodingException e ) { Log.append( EVENT, "encoding problem", e ); bytes = new byte[0]; } return newFixedLengthResponse( status, contentType.getContentTypeHeader(), new ByteArrayInputStream( bytes ), bytes.length ); } } /** * Create a text response with known length. */ public static Response newFixedLengthResponse( final String msg ) { return newFixedLengthResponse( Status.OK, HTTPD.MIME_HTML, msg ); } static final void safeClose( final Object closeable ) { try { if ( closeable != null ) { if ( closeable instanceof Closeable ) { ( (Closeable)closeable ).close(); } else if ( closeable instanceof Socket ) { ( (Socket)closeable ).close(); } else if ( closeable instanceof ServerSocket ) { ( (ServerSocket)closeable ).close(); } else { throw new IllegalArgumentException( "Unknown object to close" ); } } } catch ( final IOException e ) { Log.append( EVENT, "Could not close", e ); } } /** * Constructs an HTTP server on given port. */ public HTTPD( final int port ) { this( null, port ); } /** * Constructs an HTTP server on given hostname and port. */ public HTTPD( final String hostname, final int port ) { this.hostname = hostname; myPort = port; setTempFileManagerFactory( new DefaultTempFileManagerFactory() ); setAsyncRunner( new DefaultAsyncRunner() ); Log.append( EVENT, "Server initialized on port "+myPort ); } /** * @return the port on which this server was requested to run. * * @see #getListeningPort() */ public int getPort() { return myPort; } /** * Forcibly closes all connections that are open. */ public synchronized void closeAllConnections() { stop(); } /** * Create a instance of the client handler, subclasses can return a subclass * of the ClientHandler. * * @param finalAccept the socket the cleint is connected to * @param inputStream the input stream * * @return the client handler */ protected ClientHandler createClientHandler( final Socket finalAccept, final InputStream inputStream ) { return new ClientHandler( this, inputStream, finalAccept ); } /** * Instantiate the server runnable, can be overwritten by subclasses to * provide a subclass of the ServerRunnable. * * @param timeout the socet timeout to use. * * @return the server runnable. */ protected ServerRunnable createServerRunnable( final int timeout ) { return new ServerRunnable( this, timeout ); } public String getHostname() { return hostname; } /** * @return return the port on which this server is <i>actually</i> listening. May be -1 for an inactive socket. * * @see #getPort() */ public final int getListeningPort() { return myServerSocket == null ? -1 : myServerSocket.getLocalPort(); } public ServerSocketFactory getServerSocketFactory() { return serverSocketFactory; } public TempFileManagerFactory getTempFileManagerFactory() { return tempFileManagerFactory; } public final boolean isAlive() { return wasStarted() && !myServerSocket.isClosed() && myThread.isAlive(); } /** * Call before {@code start()} to serve over HTTPS instead of HTTP */ public void makeSecure( final SSLServerSocketFactory sslServerSocketFactory, final String[] sslProtocols ) { serverSocketFactory = new SecureServerSocketFactory( sslServerSocketFactory, sslProtocols ); } /** * Override this to customize the server. * * <p>This returns a 404 "Not Found" plain text error response.</p> * * @param session The HTTP session * * @return HTTP response, see class Response for details */ public Response serve( final IHTTPSession session ) { final Map<String, String> files = new HashMap<String, String>(); final Method method = session.getMethod(); if ( Method.PUT.equals( method ) || Method.POST.equals( method ) ) { try { session.parseBody( files ); } catch ( final IOException ioe ) { return newFixedLengthResponse( Status.INTERNAL_ERROR, HTTPD.MIME_PLAINTEXT, "SERVER INTERNAL ERROR: IOException: " + ioe.getMessage() ); } catch ( final ResponseException re ) { return newFixedLengthResponse( re.getStatus(), HTTPD.MIME_PLAINTEXT, re.getMessage() ); } } final Map<String, String> parms = session.getParms(); parms.put( HTTPD.QUERY_STRING_PARAMETER, session.getQueryParameterString() ); return newFixedLengthResponse( Status.NOT_FOUND, HTTPD.MIME_PLAINTEXT, "Not Found" ); } /** * Pluggable strategy for asynchronously executing requests. * * @param asyncRunner strategy for handling threads. */ public void setAsyncRunner( final AsyncRunner asyncRunner ) { this.asyncRunner = asyncRunner; } public void setServerSocketFactory( final ServerSocketFactory serverSocketFactory ) { this.serverSocketFactory = serverSocketFactory; } /** * Pluggable strategy for creating and cleaning up temporary files. * * @param factory new strategy for handling temp files. */ public void setTempFileManagerFactory( final TempFileManagerFactory factory ) { tempFileManagerFactory = factory; } /** * Start the server. * * @throws IOException if the socket is in use. */ public void start() throws IOException { start( HTTPD.SOCKET_READ_TIMEOUT ); } /** * Starts the server (in setDaemon(true) mode). */ public void start( final int timeout ) throws IOException { start( timeout, true ); } /** * Start the server. * * @param timeout timeout to use for socket connections. * @param daemon start the thread daemon or not. * * @throws IOException if the socket is in use. */ public void start( final int timeout, final boolean daemon ) throws IOException { myServerSocket = getServerSocketFactory().create(); myServerSocket.setReuseAddress( true ); final ServerRunnable serverRunnable = createServerRunnable( timeout ); myThread = new Thread( serverRunnable ); myThread.setDaemon( daemon ); myThread.setName( "HTTPD Listener" ); myThread.start(); while ( !serverRunnable.hasBinded && ( serverRunnable.bindException == null ) ) { try { Thread.sleep( 10L ); } catch ( final Throwable e ) { // on some platforms (e.g. mobile devices) this may not be allowed, // that is why we catch throwable. THis should happen right away // because we are just waiting for the socket to bind. } } if ( serverRunnable.bindException != null ) { throw serverRunnable.bindException; } } /** * Stop the server. */ public void stop() { Log.append( EVENT, "Server terminating" ); try { safeClose( myServerSocket ); asyncRunner.closeAll(); if ( myThread != null ) { myThread.join(); } } catch ( final Exception e ) { Log.append( EVENT, "WARN: Could not stop all connections", e ); } Log.append( EVENT, "Server termination complete" ); } /** * @return true if the gzip compression should be used if the client accespts * it. Default this option is on for text content and off for * everything. Override this for custom semantics. */ @SuppressWarnings("static-method") protected boolean useGzipWhenAccepted( final Response r ) { return ( r.getMimeType() != null ) && r.getMimeType().toLowerCase().contains( "text/" ); } public final boolean wasStarted() { return ( myServerSocket != null ) && ( myThread != null ); } }
package de.prob2.ui.internal; import java.io.CharArrayWriter; import java.io.IOException; import java.io.PrintWriter; import java.lang.ref.WeakReference; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.WeakHashMap; import javax.annotation.Nullable; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Singleton; import de.codecentric.centerdevice.MenuToolkit; import de.prob.exception.ProBError; import de.prob2.ui.layout.FontSize; import de.prob2.ui.persistence.UIState; import javafx.beans.binding.Bindings; import javafx.beans.property.ObjectProperty; import javafx.beans.property.ReadOnlyObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.fxml.FXMLLoader; import javafx.geometry.BoundingBox; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.TextArea; import javafx.scene.image.Image; import javafx.scene.layout.Pane; import javafx.scene.layout.Region; import javafx.scene.layout.VBox; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Tracks registered stages to implement UI persistence and the Mac Cmd+W shortcut. Also provides some convenience methods for creating {@link Stage}s and {@link Alert}s and loading FXML files. */ @Singleton public final class StageManager { private enum PropertiesKey { PERSISTENCE_ID, USE_GLOBAL_MAC_MENU_BAR } private static final Logger LOGGER = LoggerFactory.getLogger(StageManager.class); private static final String STYLESHEET = "prob.css"; private static final Image ICON = new Image("prob_128.png"); private final Injector injector; private final MenuToolkit menuToolkit; private final UIState uiState; private final ObjectProperty<Stage> current; private final Map<Stage, Void> registered; private MenuBar globalMacMenuBar; private Stage mainStage; @Inject private StageManager(final Injector injector, @Nullable final MenuToolkit menuToolkit, final UIState uiState) { this.injector = injector; this.menuToolkit = menuToolkit; this.uiState = uiState; this.current = new SimpleObjectProperty<>(this, "current"); this.registered = new WeakHashMap<>(); this.globalMacMenuBar = null; } /** * Get a new FXMLLoader from the manager's injector. * * @return a new FXMLLoader */ public FXMLLoader makeFXMLLoader() { return injector.getInstance(FXMLLoader.class); } /** * Load a FXML file with {@code controller} as the root and controller. {@code filename} may be absolute, or relative to {@code controller}'s package. * * @param controller the root and controller to use * @param filename the FXML file to load */ public void loadFXML(final Object controller, final String filename) { final FXMLLoader loader = this.makeFXMLLoader(); if (!filename.startsWith("custom")) { loader.setLocation(controller.getClass().getResource(filename)); } else { try { loader.setLocation(new URL(filename.replace("custom ", ""))); } catch (MalformedURLException e) { LOGGER.error("Loading fxml failed", e); } } loader.setRoot(controller); loader.setController(controller); try { loader.load(); } catch (IOException e) { LOGGER.error("Loading fxml failed", e); } String fontSizeCssString = "-fx-font-size: %dpx;"; if (controller instanceof Node) { Node controllerNode = (Node) controller; FontSize fontSize = injector.getInstance(FontSize.class); controllerNode.styleProperty().bind(Bindings.format(fontSizeCssString, fontSize)); } else if (controller instanceof Stage) { Stage controllerStage = (Stage) controller; FontSize fontSize = injector.getInstance(FontSize.class); controllerStage.getScene().getRoot().styleProperty().bind(Bindings.format(fontSizeCssString, fontSize)); } else if (controller instanceof Dialog<?>) { Dialog<?> controllerDialog = (Dialog<?>) controller; FontSize fontSize = injector.getInstance(FontSize.class); controllerDialog.getDialogPane().styleProperty().bind(Bindings.format(fontSizeCssString, fontSize)); } } /** * Load a FXML file using {@link #loadFXML(Object, String)} and register its root/controller using {@link #register(Stage, String)}. * * @param controller the root and controller to use * @param filename the FXML file to load * @param id a string identifying the stage for UI persistence, or null if the stage should not be persisted */ public void loadFXML(final Stage controller, final String filename, final String id) { this.loadFXML((Object)controller, filename); this.register(controller, id); } /** * Load a FXML file using {@link #loadFXML(Stage, String, String)} with a {@code null} ID (persistence disabled). * * @param controller the root and controller to use * @param filename the FXML file to load */ public void loadFXML(final Stage controller, final String filename) { this.loadFXML(controller, filename, null); } /** * Register the given stage with the manager. The stage must already have its scene {@link Stage#setScene(Scene) set}. This method applies the {@link #STYLESHEET} to the stage's scene, sets the stage icon, and adds some internal listeners for implementing UI persistence and the Mac Cmd+W shortcut. * * @param stage the stage to register * @param id a string identifying the stage for UI persistence, or null if the stage should not be persisted */ public void register(final Stage stage, final String id) { this.registered.put(stage, null); setPersistenceID(stage, id); stage.getProperties().putIfAbsent(PropertiesKey.USE_GLOBAL_MAC_MENU_BAR, true); stage.getScene().getStylesheets().add(STYLESHEET); stage.getIcons().add(ICON); stage.focusedProperty().addListener(e -> { final String stageId = getPersistenceID(stage); if (stageId != null) { injector.getInstance(UIState.class).moveStageToEnd(stageId); } }); stage.showingProperty().addListener((observable, from, to) -> { final String stageId = getPersistenceID(stage); if (to) { if (stageId != null) { final BoundingBox box = uiState.getSavedStageBoxes().get(stageId); if (box != null) { stage.setX(box.getMinX()); stage.setY(box.getMinY()); stage.setWidth(box.getWidth()); stage.setHeight(box.getHeight()); } uiState.getStages().put(stageId, new WeakReference<>(stage)); uiState.getSavedVisibleStages().add(stageId); } } else { if (stageId != null) { uiState.getSavedVisibleStages().remove(stageId); uiState.getSavedStageBoxes().put( stageId, new BoundingBox(stage.getX(), stage.getY(), stage.getWidth(), stage.getHeight()) ); } } }); stage.focusedProperty().addListener((observable, from, to) -> { if (to) { this.current.set(stage); } else if (stage.equals(this.current.get())) { this.current.set(null); } }); if (this.menuToolkit != null && this.globalMacMenuBar != null && isUseGlobalMacMenuBar(stage)) { this.menuToolkit.setMenuBar(stage, this.globalMacMenuBar); } } public void registerMainStage(Stage primaryStage, String name) { this.mainStage = primaryStage; this.register(primaryStage, name); } /** * Create with the given {@link Scene} as its scene, and register it automatically. * * @param scene the new scene's stage * @param id a string identifying the stage for UI persistence, or null if the stage should not be persisted * @return a new stage with the given scene */ public Stage makeStage(final Scene scene, final String id) { final Stage stage = new Stage(); stage.setScene(scene); this.register(stage, id); return stage; } /** * Register the given dialog with the manager. Currently this only applies the {@link #STYLESHEET} to the dialog's dialog pane. * * @param dialog the dialog to register */ public void register(final Dialog<?> dialog) { dialog.getDialogPane().getStylesheets().add(STYLESHEET); } /** * Create and register a new alert. The arguments are the same as with {@link Alert#Alert(Alert.AlertType, String, ButtonType...)}. * * @return a new alert */ @SuppressWarnings("OverloadedVarargsMethod") // OK here, because the overload is shorter than the vararg version public Alert makeAlert(final Alert.AlertType alertType, final String contentText, final ButtonType... buttons) { final Alert alert = new Alert(alertType, contentText, buttons); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); this.register(alert); return alert; } /** * Create and register a new alert. * * @param alertType the alert type * @return a new alert */ public Alert makeAlert(final Alert.AlertType alertType) { final Alert alert = new Alert(alertType); alert.getDialogPane().setMinHeight(Region.USE_PREF_SIZE); this.register(alert); return alert; } public Alert makeExceptionAlert(final Alert.AlertType alertType, final String contentText, final Throwable exc) { final String message = exc instanceof ProBError ? ((ProBError)exc).getOriginalMessage() : exc.getMessage(); final Alert alert = this.makeAlert(alertType, contentText + '\n' + message); if (exc instanceof ProBError && ((ProBError)exc).getErrors() != null) { final ListView<String> errorsListView = new ListView<>(); errorsListView.getItems().setAll(((ProBError)exc).getErrors()); errorsListView.setPrefSize(480, 160); alert.getDialogPane().setContent(new VBox(new Label(alert.getContentText()), errorsListView)); } final TextArea textArea = new TextArea(); try (final CharArrayWriter caw = new CharArrayWriter(); final PrintWriter pw = new PrintWriter(caw)) { exc.printStackTrace(pw); textArea.setText(caw.toString()); } alert.getDialogPane().setExpandableContent(textArea); return alert; } /** * A read-only property containing the currently focused stage. If a non-JavaFX window or an unregistered stage is in focus, the property's value is {@code null}. * * @return a property containing the currently focused stage */ public ReadOnlyObjectProperty<Stage> currentProperty() { return this.current; } /** * Get the currently focused stage. If a non-JavaFX window or an unregistered stage is in focus, this method returns {@code null}. * * @return the currently focused stage */ public Stage getCurrent() { return this.currentProperty().get(); } /** * Get the main stage. * * @return the main stage */ public Stage getMainStage() { return this.mainStage; } /** * Get a read-only set containing all registered stages. The returned set should not be permanently stored or copied elsewhere, as this would prevent all registered stages from being garbage-collected. * * @return a read-only set containing all registered stages */ public Set<Stage> getRegistered() { return Collections.unmodifiableSet(this.registered.keySet()); } /** * Get the persistence ID of the given stage. * * @param stage the stage for which to get the persistence ID * @return the stage's persistence ID, or {@code null} if none */ public static String getPersistenceID(final Stage stage) { Objects.requireNonNull(stage); return (String)stage.getProperties().get(PropertiesKey.PERSISTENCE_ID); } /** * Set the given stage's persistence ID. * * @param stage the stage for which to set the persistence ID * @param id the persistence ID to set, or {@code null} to remove it */ public static void setPersistenceID(final Stage stage, final String id) { Objects.requireNonNull(stage); if (id == null) { stage.getProperties().remove(PropertiesKey.PERSISTENCE_ID); } else { stage.getProperties().put(PropertiesKey.PERSISTENCE_ID, id); } } /** * Get whether the given stage uses the global Mac menu bar. On non-Mac systems this setting should not be used. * * @param stage the stage for which to get this setting * @return whether the given stage uses the global Mac menu bar, or {@code false} if not set */ public static boolean isUseGlobalMacMenuBar(final Stage stage) { return (boolean)stage.getProperties().getOrDefault(PropertiesKey.USE_GLOBAL_MAC_MENU_BAR, false); } /** * On Mac, set the given stage's menu bar. On other systems this method does nothing. * * @param menuBar the menu bar to use, or {@code null} to use the global menu bar */ public void setMacMenuBar(final Stage stage, final MenuBar menuBar) { Objects.requireNonNull(stage); if (this.menuToolkit == null) { return; } stage.getProperties().put(PropertiesKey.USE_GLOBAL_MAC_MENU_BAR, menuBar == null); final Scene scene = stage.getScene(); if (scene != null) { final Parent root = scene.getRoot(); if (root instanceof Pane) { if (menuBar != null) { // Temporary placeholder for the application menu, is later replaced with the global application menu menuBar.getMenus().add(0, new Menu("Invisible Application Menu")); } this.menuToolkit.setMenuBar((Pane)root, menuBar == null ? this.globalMacMenuBar : menuBar); // Put the application menu from the global menu bar back menuToolkit.setApplicationMenu(this.globalMacMenuBar.getMenus().get(0)); } } } /** * <p>On Mac, set the given menu bar as the menu bar for all registered stages and any stages registered in the future. On other systems this method does nothing.</p> * <p>This method is similar to {@link MenuToolkit#setGlobalMenuBar(MenuBar)}, except that it only affects registered stages and handles stages with a null scene correctly.</p> * * @param menuBar the menu bar to set */ public void setGlobalMacMenuBar(final MenuBar menuBar) { if (this.menuToolkit == null) { return; } this.globalMacMenuBar = menuBar; this.getRegistered().stream().filter(StageManager::isUseGlobalMacMenuBar).forEach(stage -> this.setMacMenuBar(stage, null)); } }
package gov.nih.nci.calab.service.util; import gov.nih.nci.calab.domain.nano.characterization.Characterization; import java.util.HashMap; import java.util.Map; public class CaNanoLabConstants { public static final String DOMAIN_MODEL_NAME = "caNanoLab"; public static final String CSM_APP_NAME = "caNanoLab"; public static final String DATE_FORMAT = "MM/dd/yyyy"; public static final String ACCEPT_DATE_FORMAT = "MM/dd/yy"; // Storage element public static final String STORAGE_BOX = "Box"; public static final String STORAGE_SHELF = "Shelf"; public static final String STORAGE_RACK = "Rack"; public static final String STORAGE_FREEZER = "Freezer"; public static final String STORAGE_ROOM = "Room"; public static final String STORAGE_LAB = "Lab"; // DataStatus public static final String MASK_STATUS = "Masked"; public static final String ACTIVE_STATUS = "Active"; // for Container type public static final String OTHER = "Other"; public static final String[] DEFAULT_CONTAINER_TYPES = new String[] { "Tube", "Vial" }; // Sample Container type public static final String ALIQUOT = "Aliquot"; public static final String SAMPLE_CONTAINER = "Sample_container"; // Run Name public static final String RUN = "Run"; // File upload public static final String FILEUPLOAD_PROPERTY = "caNanoLab.properties"; public static final String UNCOMPRESSED_FILE_DIRECTORY = "decompressedFiles"; public static final String EMPTY = "N/A"; // File input/output type public static final String INPUT = "Input"; public static final String OUTPUT = "Output"; // zip file name public static final String ALL_FILES = "ALL_FILES"; public static final String URI_SEPERATOR = "/"; // caNanoLab property file public static final String CANANOLAB_PROPERTY = "caNanoLab.properties"; // caLAB Submission property file public static final String SUBMISSION_PROPERTY = "exception.properties"; public static final String BOOLEAN_YES = "Yes"; public static final String BOOLEAN_NO = "No"; public static final String[] BOOLEAN_CHOICES = new String[] { BOOLEAN_YES, BOOLEAN_NO }; public static final String DEFAULT_SAMPLE_PREFIX = "NANO-"; public static final String DEFAULT_APP_OWNER = "NCICB"; public static final String APP_OWNER; static { String appOwner = PropertyReader.getProperty(CANANOLAB_PROPERTY, "applicationOwner"); if (appOwner == null || appOwner.length() == 0) appOwner = DEFAULT_APP_OWNER; APP_OWNER = appOwner; } public static final String SAMPLE_PREFIX; static { String samplePrefix = PropertyReader.getProperty(CANANOLAB_PROPERTY, "samplePrefix"); if (samplePrefix == null || samplePrefix.length() == 0) samplePrefix = DEFAULT_SAMPLE_PREFIX; SAMPLE_PREFIX = samplePrefix; } public static final String GRID_INDEX_SERVICE_URL; static { String gridIndexServiceURL = PropertyReader.getProperty( CANANOLAB_PROPERTY, "gridIndexServiceURL"); GRID_INDEX_SERVICE_URL = gridIndexServiceURL; } /* * The following Strings are nano specific * */ public static final String[] DEFAULT_CHARACTERIZATION_SOURCES = new String[] { APP_OWNER }; public static final String[] CARBON_NANOTUBE_WALLTYPES = new String[] { "Single (SWNT)", "Double (DWNT)", "Multiple (MWNT)" }; public static final String REPORT = "Report"; public static final String ASSOCIATED_FILE = "Other Associated File"; public static final String PROTOCOL_FILE = "Protocol File"; public static final String FOLDER_WORKFLOW_DATA = "workflow_data"; public static final String FOLDER_PARTICLE = "particles"; public static final String FOLDER_REPORT = "reports"; public static final String FOLDER_PROTOCOL = "protocols"; public static final String[] DEFAULT_POLYMER_INITIATORS = new String[] { "Free Radicals", "Peroxide" }; public static final String[] DEFAULT_DENDRIMER_BRANCHES = new String[] { "1-2", "1-3" }; public static final String[] DEFAULT_DENDRIMER_GENERATIONS = new String[] { "0", "0.5", "1.0", "1.5", "2.0", "2.5", "3.0", "3.5", "4.0", "4.5", "5.0", "5.5", "6.0", "6.5", "7.0", "7.5", "8.0", "8.5", "9.0", "9.5", "10.0" }; public static final String CHARACTERIZATION_FILE = "characterizationFile"; public static final String DNA = "DNA"; public static final String PEPTIDE = "Peptide"; public static final String SMALL_MOLECULE = "Small Molecule"; public static final String PROBE = "Probe"; public static final String ANTIBODY = "Antibody"; public static final String IMAGE_CONTRAST_AGENT = "Image Contrast Agent"; public static final String ATTACHMENT = "Attachment"; public static final String ENCAPSULATION = "Encapsulation"; public static final String[] FUNCTION_AGENT_TYPES = new String[] { DNA, PEPTIDE, SMALL_MOLECULE, PROBE, ANTIBODY, IMAGE_CONTRAST_AGENT }; public static final String[] FUNCTION_LINKAGE_TYPES = new String[] { ATTACHMENT, ENCAPSULATION }; public static final String RECEPTOR = "Receptor"; public static final String ANTIGEN = "Antigen"; public static final int MAX_VIEW_TITLE_LENGTH = 23; public static final String[] SPECIES_SCIENTIFIC = { "Mus musculus", "Homo sapiens", "Rattus rattus", "Sus scrofa", "Meriones unguiculatus", "Mesocricetus auratus", "Cavia porcellus", "Bos taurus", "Canis familiaris", "Capra hircus", "Equus Caballus", "Ovis aries", "Felis catus", "Saccharomyces cerevisiae", "Danio rerio" }; public static final String[] SPECIES_COMMON = { "Mouse", "Human", "Rat", "Pig", "Mongolian Gerbil", "Hamster", "Guinea pig", "Cattle", "Dog", "Goat", "Horse", "Sheep", "Cat", "Yeast", "Zebrafish" }; public static final String UNIT_PERCENT = "%"; public static final String UNIT_CFU = "CFU"; public static final String UNIT_RFU = "RFU"; public static final String UNIT_SECOND = "SECOND"; public static final String UNIT_MG_ML = "mg/ml"; public static final String UNIT_FOLD = "Fold"; public static final String ORGANIC_HYDROCARBON = "organic:hydrocarbon"; public static final String ORGANIC_CARBON = "organic:carbon"; public static final String ORGANIC = "organic"; public static final String INORGANIC = "inorganic"; public static final String COMPLEX = "complex"; public static final Map<String, String> PARTICLE_CLASSIFICATION_MAP; static { PARTICLE_CLASSIFICATION_MAP = new HashMap<String, String>(); PARTICLE_CLASSIFICATION_MAP.put(Characterization.DENDRIMER_TYPE, ORGANIC_HYDROCARBON); PARTICLE_CLASSIFICATION_MAP.put(Characterization.POLYMER_TYPE, ORGANIC_HYDROCARBON); PARTICLE_CLASSIFICATION_MAP.put(Characterization.FULLERENE_TYPE, ORGANIC_CARBON); PARTICLE_CLASSIFICATION_MAP.put(Characterization.CARBON_NANOTUBE_TYPE, ORGANIC_CARBON); PARTICLE_CLASSIFICATION_MAP .put(Characterization.LIPOSOME_TYPE, ORGANIC); PARTICLE_CLASSIFICATION_MAP .put(Characterization.EMULSION_TYPE, ORGANIC); PARTICLE_CLASSIFICATION_MAP.put(Characterization.METAL_PARTICLE_TYPE, INORGANIC); PARTICLE_CLASSIFICATION_MAP.put(Characterization.QUANTUM_DOT_TYPE, INORGANIC); PARTICLE_CLASSIFICATION_MAP.put(Characterization.COMPLEX_PARTICLE_TYPE, COMPLEX); } public static final String CSM_PI = APP_OWNER + "_PI"; public static final String CSM_RESEARCHER = APP_OWNER + "_Researcher"; public static final String CSM_ADMIN = APP_OWNER + "_Administrator"; public static final String CSM_PUBLIC_GROUP = "Public"; public static final String[] VISIBLE_GROUPS = new String[] { CSM_PI, CSM_RESEARCHER }; public static final String AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX = "copy_"; public static final String AUTO_COPY_CHARACTERIZATION_VIEW_COLOR = "red"; public static final String UNIT_TYPE_CONCENTRATION = "Concentration"; public static final String UNIT_TYPE_CHARGE = "Charge"; public static final String UNIT_TYPE_QUANTITY = "Quantity"; public static final String UNIT_TYPE_AREA = "Area"; public static final String UNIT_TYPE_SIZE = "Size"; public static final String UNIT_TYPE_VOLUME = "Volume"; public static final String UNIT_TYPE_MOLECULAR_WEIGHT = "Molecular Weight"; public static final String UNIT_TYPE_ZETA_POTENTIAL = "Zeta Potential"; public static final String CSM_READ_ROLE = "R"; public static final String CSM_DELETE_ROLE = "D"; public static final String CSM_EXECUTE_ROLE = "E"; public static final String CSM_CURD_ROLE = "CURD"; public static final String CSM_CUR_ROLE = "CUR"; public static final String CSM_READ_PRIVILEGE = "READ"; public static final String CSM_EXECUTE_PRIVILEGE = "EXECUTE"; public static final String CSM_DELETE_PRIVILEGE = "DELETE"; public static final String CSM_CREATE_PRIVILEGE = "CREATE"; public static final String CSM_PG_SAMPLE = "sample"; public static final String CSM_PG_PROTOCOL = "protocol"; public static final String CSM_PG_PARTICLE = "nanoparticle"; public static final String CSM_PG_REPORT = "report"; public static final String PHYSICAL_ASSAY_PROTOCOL = "Physical Assay"; public static final String INVITRO_ASSAY_PROTOCOL = "In Vitro Assay"; /* image file name extension */ public static final String[] IMAGE_FILE_EXTENSIONS = { "AVS", "BMP", "CIN", "DCX", "DIB", "DPX", "FITS", "GIF", "ICO", "JFIF", "JIF", "JPE", "JPEG", "JPG", "MIFF", "OTB", "P7", "PALM", "PAM", "PBM", "PCD", "PCDS", "PCL", "PCX", "PGM", "PICT", "PNG", "PNM", "PPM", "PSD", "RAS", "SGI", "SUN", "TGA", "TIF", "TIFF", "WMF", "XBM", "XPM", "YUV", "CGM", "DXF", "EMF", "EPS", "MET", "MVG", "ODG", "OTG", "STD", "SVG", "SXD", "WMF" }; public static final String[] PUBLIC_DISPATCHES = {"view", "search", "setupView", "summaryView", "detailView", "printDetailView", "exportDetail", "printSummaryView", "printFullSummaryView", "exportSummary", "exportFullSummary", "download", "loadFile" }; }
/** * * $Id: PublicationAction.java,v 1.6 2005-10-26 20:12:43 pandyas Exp $ * * $Log: not supported by cvs2svn $ * */ package gov.nih.nci.camod.webapp.action; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import gov.nih.nci.camod.Constants; import gov.nih.nci.camod.domain.AnimalModel; import gov.nih.nci.camod.domain.Publication; import gov.nih.nci.camod.domain.PublicationStatus; import gov.nih.nci.camod.service.AnimalModelManager; import gov.nih.nci.camod.service.PublicationManager; import gov.nih.nci.camod.webapp.form.PublicationForm; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; /** * PublicationAction Class */ public final class PublicationAction extends BaseAction { /** * Delete * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (log.isDebugEnabled()) { log.debug("Entering 'delete' method"); } return mapping.findForward(""); } /** * Cancel * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward duplicate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward(""); } /** * Edit * @param mapping * @param form * @param request * @param response * @return * @throws Exception */ public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (log.isDebugEnabled()) { log.debug("Entering 'edit' method"); } // Create a form to edit PublicationForm pubForm = ( PublicationForm ) form; System.out.println( "<PublicationAction save> following Characteristics:" + "\n\t name: " + pubForm.getName() + "\n\t Aurthur: " + pubForm.getAuthors() + "\n\t Year: " + pubForm.getYear() + "\n\t Volume: " + pubForm.getVolume() + "\n\t PMID: " + pubForm.getPmid() + "\n\t Start Page: " + pubForm.getStartPage() + "\n\t End Page: " + pubForm.getEndPage() + "\n\t Title: " + pubForm.getTitle() + "\n\t journal: " + pubForm.getJournal() + "\n\t FirstTimeReported: " + pubForm.getFirstTimeReported() + "\n\t user: " + (String) request.getSession().getAttribute( "camod.loggedon.username" ) ); // Grab the current Therapy we are working with related to this animalModel String aPubID = request.getParameter( "aPubID" ); /* Grab the current modelID from the session */ String modelID = "" + request.getSession().getAttribute( Constants.MODELID ); // Use the current animalModel based on the ID stored in the session AnimalModelManager animalModelManager = (AnimalModelManager) getBean( "animalModelManager" ); PublicationManager publicationManager = (PublicationManager) getBean( "publicationManager" ); AnimalModel am = animalModelManager.get( modelID ); // TODO: Verify that the Long values are longs or else there will be exceptions, do this in the validation! //retrieve the list of all therapies from the current animalModel List pubList = am.getPublicationCollection(); Publication pub = new Publication(); //find the specific one we need for ( int i=0; i<pubList.size(); i++ ) { pub = (Publication)pubList.get(i); if ( pub.getId().toString().equals( aPubID ) ) break; } /* 1. Create the Publication Object */ pub.setAuthors( pubForm.getAuthors() ); pub.setTitle( pubForm.getTitle() ); pub.setJournal( pubForm.getJournal() ); pub.setVolume( pubForm.getVolume() ); // pub.setYear( Long.valueOf( pubForm.getYear().trim() ) ); // pub.setStartPage( Long.valueOf( pubForm.getStartPage().trim() ) ); // pub.setEndPage( Long.valueOf( pubForm.getEndPage().trim() ) ); // pub.setPmid( Long.valueOf( pubForm.getPmid().trim() ) ); String strPub = pubForm.getPmid().trim(); Pattern p = Pattern.compile("[0-9]{" + strPub.length() + "}"); Matcher m = p.matcher( strPub ); if (m.matches() && strPub != null && ! strPub.equals("") ) { pub.setPmid( Long.valueOf( strPub ) ); } strPub = pubForm.getStartPage().trim(); p = Pattern.compile("[0-9]{" + strPub.length() + "}"); m = p.matcher( strPub ); if (m.matches() && strPub != null && ! strPub.equals("") ) { pub.setStartPage( Long.valueOf( strPub ) ); } strPub = pubForm.getEndPage().trim(); p = Pattern.compile("[0-9]{" + strPub.length() + "}"); m = p.matcher( strPub ); if (m.matches() && strPub != null && ! strPub.equals("") ) { pub.setEndPage( Long.valueOf( strPub ) ); } strPub = pubForm.getYear().trim(); p = Pattern.compile("[0-9]{" + strPub.length() + "}"); m = p.matcher( strPub ); if (m.matches() && strPub != null && ! strPub.equals("") ) { pub.setYear( Long.valueOf( strPub ) ); } if ( pubForm.getFirstTimeReported() != null && pubForm.getFirstTimeReported().equals( "yes" ) ) pub.setFirstTimeReported( new Boolean(true) ); else pub.setFirstTimeReported( new Boolean(false) ); PublicationStatus pubStatus = new PublicationStatus(); pubStatus.setName( pubForm.getName() ); publicationManager.save( pub, pubStatus ); //Add a message to be displayed in submitOverview.jsp saying you've created a new model successfully ActionMessages msg = new ActionMessages(); msg.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "publication.edit.successful" ) ); saveErrors( request, msg ); return mapping.findForward("AnimalModelTreePopulateAction"); } /** Called from submitEnvironmentalFactors.jsp * */ public ActionForward save( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (log.isDebugEnabled()) { log.debug("Entering 'save' method"); } PublicationForm pubForm = ( PublicationForm ) form; System.out.println( "<PublicationAction save> following Characteristics:" + "\n\t name: " + pubForm.getName() + "\n\t Aurthur: " + pubForm.getAuthors() + "\n\t Year: " + pubForm.getYear() + "\n\t Volume: " + pubForm.getVolume() + "\n\t PMID: " + pubForm.getPmid() + "\n\t Start Page: " + pubForm.getStartPage() + "\n\t End Page: " + pubForm.getEndPage() + "\n\t Title: " + pubForm.getTitle() + "\n\t journal: " + pubForm.getJournal() + "\n\t FirstTimeReported: " + pubForm.getFirstTimeReported() + "\n\t user: " + (String) request.getSession().getAttribute( "camod.loggedon.username" ) ); /* Grab the current modelID from the session */ String modelID = (String) request.getSession().getAttribute( Constants.MODELID ); /* Create all the manager objects needed for Screen */ AnimalModelManager animalModelManager = (AnimalModelManager) getBean( "animalModelManager" ); PublicationManager publicationManager = (PublicationManager) getBean( "publicationManager" ); /* Set modelID in AnimalModel object */ AnimalModel animalModel = animalModelManager.get( modelID ); //TODO: Verify that the Long values are longs or else there will be exceptions, do this in the validation! /* 1. Create the Publication Object */ Publication pub = new Publication(); pub.setAuthors( pubForm.getAuthors() ); pub.setTitle( pubForm.getTitle() ); pub.setJournal( pubForm.getJournal() ); pub.setVolume( pubForm.getVolume() ); String strPub = pubForm.getPmid().trim(); Pattern p = Pattern.compile("[0-9]{" + strPub.length() + "}"); Matcher m = p.matcher( strPub ); if (m.matches() && strPub != null && ! strPub.equals("") ) { pub.setPmid( Long.valueOf( strPub ) ); } strPub = pubForm.getStartPage().trim(); p = Pattern.compile("[0-9]{" + strPub.length() + "}"); m = p.matcher( strPub ); if (m.matches() && strPub != null && ! strPub.equals("") ) { pub.setStartPage( Long.valueOf( strPub ) ); } strPub = pubForm.getEndPage().trim(); p = Pattern.compile("[0-9]{" + strPub.length() + "}"); m = p.matcher( strPub ); if (m.matches() && strPub != null && ! strPub.equals("") ) { pub.setEndPage( Long.valueOf( strPub ) ); } strPub = pubForm.getYear().trim(); p = Pattern.compile("[0-9]{" + strPub.length() + "}"); m = p.matcher( strPub ); if (m.matches() && strPub != null && ! strPub.equals("") ) { pub.setYear( Long.valueOf( strPub ) ); } // pub.setPmid( Long.valueOf( strPub ) ); // pub.setStartPage( Long.valueOf( pubForm.getStartPage().trim() ) ); // pub.setEndPage( Long.valueOf( pubForm.getEndPage().trim() ) ); // pub.setYear( Long.valueOf( pubForm.getYear().trim() ) ); if ( pubForm.getFirstTimeReported() != null && pubForm.getFirstTimeReported().equals( "yes" ) ) pub.setFirstTimeReported( new Boolean(true) ); else pub.setFirstTimeReported( new Boolean(false) ); PublicationStatus pubStatus = new PublicationStatus(); pubStatus.setName( pubForm.getName() ); //publicationManager.savePublicationStats( pubStatus ); //pub.setPublicationStatus( pubStatus ); publicationManager.save( pub, pubStatus ); animalModel.addPublication( pub ); /* save the animalModel = saves Therapy (Hibernate saves child in 1...1 relationships) */ animalModelManager.save( animalModel ); System.out.println( "<PublicationAction save> saved the animalModel" ); //Add a message to be displayed in submitOverview.jsp saying you've created a new model successfully ActionMessages msg = new ActionMessages(); msg.add( ActionMessages.GLOBAL_MESSAGE, new ActionMessage( "publication.creation.successful" ) ); saveErrors( request, msg ); return mapping.findForward("AnimalModelTreePopulateAction"); } }
package gov.nih.nci.cananolab.ui.sample; import gov.nih.nci.cananolab.dto.common.FileBean; import gov.nih.nci.cananolab.dto.common.UserBean; import gov.nih.nci.cananolab.dto.particle.SampleBean; import gov.nih.nci.cananolab.dto.particle.characterization.CharacterizationSummaryViewBean; import gov.nih.nci.cananolab.dto.particle.composition.ChemicalAssociationBean; import gov.nih.nci.cananolab.dto.particle.composition.CompositionBean; import gov.nih.nci.cananolab.dto.particle.composition.FunctionalizingEntityBean; import gov.nih.nci.cananolab.dto.particle.composition.NanomaterialEntityBean; import gov.nih.nci.cananolab.service.sample.CompositionService; import gov.nih.nci.cananolab.service.sample.helper.CompositionServiceHelper; import gov.nih.nci.cananolab.service.sample.impl.CompositionServiceLocalImpl; import gov.nih.nci.cananolab.service.sample.impl.CompositionServiceRemoteImpl; import gov.nih.nci.cananolab.ui.core.BaseAnnotationAction; import gov.nih.nci.cananolab.ui.core.InitSetup; import gov.nih.nci.cananolab.util.Constants; import gov.nih.nci.cananolab.util.ExportUtils; import gov.nih.nci.cananolab.util.SampleConstants; import gov.nih.nci.cananolab.util.StringUtils; import java.util.Collections; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessages; import org.apache.struts.validator.DynaValidatorForm; public class CompositionAction extends BaseAnnotationAction { /** * Handle Composition Summary Edit request. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward summaryEdit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Call shared function to prepare CompositionBean for editing. this.prepareSummary(mapping, form, request, response); // forward to appropriate tab String tab = (String) getValueFromRequest(request, "tab"); if (tab == null) { tab = "ALL"; // default tab to all; } if (tab.equals("ALL")) { request.getSession().removeAttribute("onloadJavascript"); request.getSession().removeAttribute("tab"); } else { request.getSession().setAttribute( "onloadJavascript", "showSummary('" + tab + "', " + CompositionBean.ALL_COMPOSITION_SECTIONS.length + ")"); } return mapping.findForward("summaryEdit"); } /** * Handle Composition Summary View request. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward summaryView(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Call shared function to prepare CompositionBean for viewing. this.prepareSummary(mapping, form, request, response); CompositionBean compBean = (CompositionBean) request.getSession() .getAttribute("compBean"); // forward to appropriate tab String tab = (String) getValueFromRequest(request, "tab"); if (tab == null) { tab = "ALL"; // default tab to all; } if (tab.equals("ALL")) { request.getSession().removeAttribute("onloadJavascript"); request.getSession().removeAttribute("tab"); } else { request.getSession().setAttribute( "onloadJavascript", "showSummary('" + tab + "', " + compBean.getCompositionSections().size() + ")"); } return mapping.findForward("summaryView"); } /** * Handle Composition Summary Print request. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward summaryPrint(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Retrieve compBean from session to avoid re-querying. CompositionBean compBean = (CompositionBean) request.getSession() .getAttribute("compBean"); SampleBean sampleBean = (SampleBean) request.getSession().getAttribute( "theSample"); if (compBean == null || sampleBean == null) { // Call shared function to prepare CompositionBean for viewing. this.prepareSummary(mapping, form, request, response); compBean = (CompositionBean) request.getSession().getAttribute( "compBean"); sampleBean = (SampleBean) request.getSession().getAttribute( "theSample"); } // Marker that indicates page is for printing (hide tabs, links, etc). request.setAttribute("printView", Boolean.TRUE); // Show only the selected type. this.filterType(request, compBean); return mapping.findForward("summaryPrint"); } /** * Handle Composition Summary Export request. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward summaryExport(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Retrieve compBean from session to avoid re-querying. CompositionBean compBean = (CompositionBean) request.getSession() .getAttribute("compBean"); SampleBean sampleBean = (SampleBean) request.getSession().getAttribute( "theSample"); if (compBean == null || sampleBean == null) { // Call shared function to prepare CompositionBean for viewing. this.prepareSummary(mapping, form, request, response); compBean = (CompositionBean) request.getSession().getAttribute( "compBean"); sampleBean = (SampleBean) request.getSession().getAttribute( "theSample"); } // Export only the selected type. this.filterType(request, compBean); // Get sample name for constructing file name. String type = request.getParameter("type"); String location = request.getParameter(Constants.LOCATION); String fileName = ExportUtils.getExportFileName(sampleBean.getDomain() .getName(), "CompositionSummaryView", type); ExportUtils.prepareReponseForExcel(response, fileName); String serviceUrl = null; if (!Constants.LOCAL_SITE.equals(location)) { serviceUrl = InitSetup.getInstance().getGridServiceUrl(request, location); } StringBuilder sb = getDownloadUrl(request, serviceUrl, location); CompositionServiceHelper.exportSummary(compBean, sb.toString(), response.getOutputStream()); return null; } /** * Shared function for summaryView() and summaryPrint(). Prepare * CompositionBean for displaying based on SampleId and location. * * @param mapping * @param form * @param request * @param response * @return ActionForward * @throws Exception */ private void prepareSummary(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Remove previous result from session. HttpSession session = request.getSession(); session.removeAttribute(CompositionBean.CHEMICAL_SELECTION); session.removeAttribute(CompositionBean.FILE_SELECTION); session.removeAttribute(CompositionBean.FUNCTIONALIZING_SELECTION); session.removeAttribute(CompositionBean.NANOMATERIAL_SELECTION); session.removeAttribute("theSample"); DynaValidatorForm theForm = (DynaValidatorForm) form; UserBean user = (UserBean) request.getSession().getAttribute("user"); String sampleId = theForm.getString(SampleConstants.SAMPLE_ID); String location = theForm.getString(Constants.LOCATION); SampleBean sampleBean = setupSample(theForm, request, location); CompositionService compService = null; if (Constants.LOCAL_SITE.equals(location)) { compService = new CompositionServiceLocalImpl(); } else { String serviceUrl = InitSetup.getInstance().getGridServiceUrl( request, location); compService = new CompositionServiceRemoteImpl(serviceUrl); } CompositionBean compBean = compService.findCompositionBySampleId( sampleId, user); theForm.set("comp", compBean); // Save result bean in session for later use - export/print. session.setAttribute("compBean", compBean); session.setAttribute("theSample", sampleBean); // for showing title. if (compBean != null) { session.setAttribute(CompositionBean.CHEMICAL_SELECTION, compBean .getChemicalAssociations()); session.setAttribute(CompositionBean.FILE_SELECTION, compBean .getFiles()); session.setAttribute(CompositionBean.FUNCTIONALIZING_SELECTION, compBean.getFunctionalizingEntities()); session.setAttribute(CompositionBean.NANOMATERIAL_SELECTION, compBean.getNanomaterialEntities()); } // retain action messages from send redirects ActionMessages msgs = (ActionMessages) session .getAttribute(ActionMessages.GLOBAL_MESSAGE); saveMessages(request, msgs); session.removeAttribute(ActionMessages.GLOBAL_MESSAGE); } /** * Shared function for summaryExport() and summaryPrint(). Filter out * unselected types when user selected one type for print/export. * * @param request * @param compBean */ private void filterType(HttpServletRequest request, CompositionBean compBean) { // 1. Restore all data first. HttpSession session = request.getSession(); List<ChemicalAssociationBean> chemBeans = (List<ChemicalAssociationBean>) session .getAttribute(CompositionBean.CHEMICAL_SELECTION); compBean.setChemicalAssociations(chemBeans); List<FileBean> fileBeans = (List<FileBean>) session .getAttribute(CompositionBean.FILE_SELECTION); compBean.setFiles(fileBeans); List<FunctionalizingEntityBean> funcBeans = (List<FunctionalizingEntityBean>) session .getAttribute(CompositionBean.FUNCTIONALIZING_SELECTION); compBean.setFunctionalizingEntities(funcBeans); List<NanomaterialEntityBean> nanoBeans = (List<NanomaterialEntityBean>) session .getAttribute(CompositionBean.NANOMATERIAL_SELECTION); compBean.setNanomaterialEntities(nanoBeans); // 2. Filter out unselected type. String type = request.getParameter("type"); if (!StringUtils.isEmpty(type)) { if (!type.equals(CompositionBean.CHEMICAL_SELECTION)) { compBean.setChemicalAssociations(Collections.EMPTY_LIST); } if (!type.equals(CompositionBean.FILE_SELECTION)) { compBean.setFiles(Collections.EMPTY_LIST); } if (!type.equals(CompositionBean.FUNCTIONALIZING_SELECTION)) { compBean.setFunctionalizingEntities(Collections.EMPTY_LIST); } if (!type.equals(CompositionBean.NANOMATERIAL_SELECTION)) { compBean.setNanomaterialEntities(Collections.EMPTY_LIST); } } } }
package fi.tekislauta.webserver; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import fi.tekislauta.db.Database; import fi.tekislauta.db.objects.BoardDao; import fi.tekislauta.db.objects.ModelValidationException; import fi.tekislauta.db.objects.PostDao; import fi.tekislauta.models.Board; import fi.tekislauta.models.Post; import fi.tekislauta.models.Result; import spark.Request; import static spark.Spark.*; import java.io.PrintStream; import java.util.Map; import java.util.Base64; public class Webserver { private final int port; private final Gson gson; //private final Database db; private final BoardDao boardDao; private final PostDao postDao; private final String USER = System.getenv("USER"); private final String PW = System.getenv("PW"); public Webserver(int port) { this.port = port; this.gson = new Gson(); Database db = new Database(); this.boardDao = new BoardDao(db); this.postDao = new PostDao(db); } public void listen() { port(this.port); // spark starts listening when first method listener is added, I think ~cx get("/api/boards/", (req, res) -> { Result r = new Result(); try { res.header("Content-Type", "application/json; charset=utf-8"); res.header("Access-Control-Allow-Origin", "*"); r.setData(boardDao.findAll("")); } catch (Exception e) { r.setStatus("Server error: " + e.getMessage()); } return gson.toJson(r); }); get("/api/boards/:abbreviation", (req, res) -> { Result r = new Result(); try { res.header("Content-Type", "application/json; charset=utf-8"); res.header("Access-Control-Allow-Origin", "*"); r.setData(boardDao.find(req.params("abbreviation"))); } catch (Exception e) { r.setStatus("Server error: " + e.getMessage()); } return gson.toJson(r); }); get("/api/boards/:board/posts/", (req, res) -> { Result r = new Result(); try { res.header("Content-Type", "application/json; charset=utf-8"); res.header("Access-Control-Allow-Origin", "*"); r.setData(postDao.findAll(req.params("board"))); } catch (Exception e) { r.setStatus("Server error: " + e.getMessage()); } return gson.toJson(r); }); get("/api/boards/:board/posts/:page", (req, res) -> { Result r = new Result(); try { res.header("Content-Type", "application/json; charset=utf-8"); res.header("Access-Control-Allow-Origin", "*"); r.setData(postDao.findPageTopics(req.params("board"), req.params("page"))); } catch (Exception e) { r.setStatus("Server error: " + e.getMessage()); } return gson.toJson(r); }); get("/api/jerry", (req, res) -> { res.header("Access-Control-Allow-Origin", "*"); return "\uD83D\uDC4C\uD83D\uDC40\uD83D\uDC4C\uD83D\uDC40\uD83D\uDC4C\uD83D\uDC40\uD83D\uDC4C\uD83D\uDC40\uD83D\uDC4C\uD83D\uDC40 good shit go౦ԁ sHit\uD83D\uDC4C thats some good\uD83D\uDC4C\uD83D\uDC4Cshit right\uD83D\uDC4C\uD83D\uDC4Cthere\uD83D\uDC4C\uD83D\uDC4C\uD83D\uDC4C rightthere if i do ƽaү so my self \uD83D\uDCAF i say so \uD83D\uDCAF thats what im talking about right there right there (chorus: ʳᶦᵍʰᵗ ᵗʰᵉʳᵉ) mMMMMᎷМ\uD83D\uDCAF \uD83D\uDC4C\uD83D\uDC4C \uD83D\uDC4CНO0ОଠOOOOOОଠଠOoooᵒᵒᵒᵒᵒᵒᵒᵒᵒ\uD83D\uDC4C \uD83D\uDC4C\uD83D\uDC4C \uD83D\uDC4C \uD83D\uDCAF \uD83D\uDC4C \uD83D\uDC40 \uD83D\uDC40 \uD83D\uDC40 \uD83D\uDC4C\uD83D\uDC4CGood shit"; }); get("/api/boards/:board/posts/topics/:topic", (req, res) -> { Result r = new Result(); try { res.header("Access-Control-Allow-Origin", "*"); res.header("Content-Type", "application/json; charset=utf-8"); r.setData(postDao.findByTopic(req.params("board"), req.params("topic"))); } catch (Exception e) { r.setStatus("Server error: " + e.getMessage()); } return gson.toJson(r); }); get("/api/posts/:id", (req, res) -> { Result r = new Result(); try { res.header("Access-Control-Allow-Origin", "*"); res.header("Content-Type", "application/json; charset=utf-8"); r.setData(postDao.find(req.params("id"))); } catch (Exception e) { r.setStatus("Server error: " + e.getMessage()); } return gson.toJson(r); }); post("api/boards/:board/posts/", (req, res) -> { // This endpoint creates new topics. Responses go to POST api/boards/:board/posts/topics/:topic Result r = new Result(); try { res.header("Access-Control-Allow-Origin", "*"); res.header("Content-Type", "application/json; charset=utf-8"); Map json = gson.fromJson(req.body(), Map.class); if (json.get("topic_id") != null) { // This endpoint only creates new topics. No replies. Nada. noty. res.status(400); r.setStatus("Error"); r.setData("This endpoint creates new topics. Topic replies go to POST api/boards/:board/posts/topics/:topic"); return r; } Post p = new Post(); p.setBoard_abbrevition(req.params("board")); p.setIp(req.ip()); p.setSubject(((String) json.get("subject")).trim()); p.setMessage(((String) json.get("message")).trim()); p.setPost_time(getUnixTimestamp()); r.setData(postDao.post(p)); } catch (JsonSyntaxException | ModelValidationException e) { res.status(400); r.setStatus("Error"); r.setData("Malformed request or missing data!"); } catch (Exception e) { res.status(500); r.setStatus("Error"); r.setStatus("Server error: " + e.getMessage()); dumpRequestException(req, e); } return r; }, gson::toJson); post("api/boards/:board/posts/topics/:topic", (req, res) -> { Result r = new Result(); try { res.header("Access-Control-Allow-Origin", "*"); res.header("Content-Type", "application/json; charset=utf-8"); Map json = gson.fromJson(req.body(), Map.class); Post p = new Post(); p.setBoard_abbrevition(req.params("board")); p.setTopic_id(Integer.parseInt(req.params("topic"))); p.setIp(req.ip()); p.setSubject((String) json.get("subject")); p.setMessage((String) json.get("message")); p.setPost_time(getUnixTimestamp()); r.setData(postDao.post(p)); } catch (Exception e) { r.setStatus("Server error: " + e.getMessage()); } return gson.toJson(r); }); post("/api/boards/", (req, res) -> { Result r = new Result(); try { res.header("Access-Control-Allow-Origin", "*"); res.header("Content-Type", "application/json; charset=utf-8"); Map json = gson.fromJson(req.body(), Map.class); Board b = new Board(); b.setName((String) json.get("name")); b.setAbbreviation((String) json.get("abbreviation")); b.setDescription((String) json.get("description")); r.setData(boardDao.post(b)); } catch (Exception e) { r.setStatus("Server error: " + e.getMessage()); } return gson.toJson(r); }); delete("api/posts/:id", (req, res) -> { Result r = new Result(); try { if (!isAuthrorized(req.headers("Authorization"))) throw new Exception("Unauthorized"); res.header("Access-Control-Allow-Origin", "*"); res.header("Content-Type", "application/json; charset=utf-8"); postDao.delete(req.params("id")); } catch (Exception e) { r.setStatus("Server error: " + e.getMessage()); } return gson.toJson(r); }); delete("api/boards/:id", (req, res) -> { Result r = new Result(); try { if (!isAuthrorized(req.headers("Authorization"))) throw new Exception("Unauthorized"); res.header("Access-Control-Allow-Origin", "*"); res.header("Content-Type", "application/json; charset=utf-8"); boardDao.delete(req.params("id")); } catch (Exception e) { r.setStatus("Server error: " + e.getMessage()); } return gson.toJson(r); }); } boolean isAuthrorized(String hdr) { byte[] decryptedHeader = Base64.getDecoder().decode(hdr.split(" ")[1]); String[] credentials = new String(decryptedHeader).split(":"); return (credentials[0].equals(USER) && credentials[1].equals(PW)); } private int getUnixTimestamp() { return (int)(System.currentTimeMillis() / 1000); // we deal with seconds around here } private void dumpRequestException(Request request, Exception e) { System.err.println("Error!"); System.err.printf("Request body:%n%s%n", request.body()); System.err.print("Exception: "); e.printStackTrace(new PrintStream(System.err)); } }
package gov.nasa.jpl.mbee.model; import gov.nasa.jpl.mbee.DocGen3Profile; import gov.nasa.jpl.mbee.generator.DocumentValidator; import gov.nasa.jpl.mbee.generator.GenerationContext; import gov.nasa.jpl.mbee.lib.Debug; import gov.nasa.jpl.mbee.lib.GeneratorUtils; import gov.nasa.jpl.mbee.lib.MoreToString; import gov.nasa.jpl.mbee.lib.Utils; import gov.nasa.jpl.mbee.lib.Utils.AvailableAttribute; import gov.nasa.jpl.mbee.lib.Utils2; import gov.nasa.jpl.mgss.mbee.docgen.docbook.DBParagraph; import gov.nasa.jpl.mgss.mbee.docgen.docbook.DocumentElement; import gov.nasa.jpl.mgss.mbee.docgen.docbook.From; import gov.nasa.jpl.ocl.OclEvaluator; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Stack; import com.nomagic.magicdraw.core.Application; import com.nomagic.magicdraw.uml.BaseElement; import com.nomagic.uml2.ext.jmi.helpers.ModelHelper; import com.nomagic.uml2.ext.jmi.helpers.StereotypesHelper; import com.nomagic.uml2.ext.magicdraw.activities.mdbasicactivities.InitialNode; import com.nomagic.uml2.ext.magicdraw.activities.mdfundamentalactivities.ActivityNode; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Element; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.EnumerationLiteral; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Property; import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Slot; import com.nomagic.uml2.ext.magicdraw.mdprofiles.Stereotype; public class Paragraph extends Query { private String text; private List<Property> stereotypeProperties; private From fromProperty; private DocumentValidator validator = null; private boolean tryOcl = false; private boolean iterate = true; private AvailableAttribute attribute = null; // this is redundant with fromProperty public InitialNode bnode; public ActivityNode activityNode; public GenerationContext context = null; public GenerationContext makeContext() { ActivityNode n = null; if (bnode != null && bnode.getOutgoing().iterator().hasNext()) { // should // check // next // node // collect/filter // node n = bnode.getOutgoing().iterator().next().getTarget(); } Stack<List<Object>> in = new Stack<List<Object>>(); // in.add( targets ); context = new GenerationContext(in, n, getValidator(), Application.getInstance().getGUILog()); return context; } public Paragraph(String t) { text = t; } public Paragraph() { } public Paragraph(DocumentValidator dv) { this.validator = dv; } public void setText(String t) { text = t; } public String getText() { return text; } public void setStereotypeProperties(List<Property> p) { stereotypeProperties = p; } public List<Property> getStereotypeProperties() { return stereotypeProperties; } public void setFrom(From f) { fromProperty = f; } public From getFrom() { return fromProperty; } public DocumentValidator getValidator() { return validator; } // /* (non-Javadoc) // * @see gov.nasa.jpl.mbee.model.Query#parse() // */ // @Override // public void parse() { // super.parse(); protected void addOclParagraph(List<DocumentElement> res, Object oclExpression, Object context) { Debug.outln( "addOclParagraph(" + res + ", \"" + oclExpression + "\", " + context + ")" ); Object result = DocumentValidator.evaluate( oclExpression, context, getValidator(), true ); Debug.outln("ocl result = " + result); if ( result instanceof Collection && ((Collection<?>)result).size() == 1 ) { result = ( (Collection< ? >)result ).iterator().next(); } if (OclEvaluator.instance.isValid() || result != null) { if ( result instanceof Element && getFrom() != null ) { Element e = (Element)result; res.add( new DBParagraph( Utils.getElementAttribute( e, attribute ), e, getFrom() ) ); } else { res.add( new DBParagraph( result ) ); } } else { // REVIEW -- TableStructure adds nothing in this case; is that right? } } /** * Create DocBook paragraph(s) for this Paragraph. * * @param forViewEditor * @param outputDir * @return Return one or more DBParagraphs for docgen or the view editor * based on properties of the Paragraph UML stereotype. * <p> * <code> * O=tryOcl && T=gotText && R=gotTargets && S=gotStereotypeProperties && D=don't care <br><br> * * 1 &nbsp;D && !T && !R && D: return nothing <br> * 2 !O && !T && R && !S: return a paragraph of documentation for each target <br> * 3 !O && !T && R && S: return a paragraph for each target-property pair <br> * 4 !O && T && D && D: return a paragraph of the text, tied to the "body" slot of dgElement <br> * <br> * 5 &nbsp;O && !T && R && !S: return a paragraph of the evaluation of the documentation of each target as OCL on dgElement <br> * 6 &nbsp;O && !T && R && S: return a paragraph of the evaluation of each target-property as OCL on dgElement <br> * 7 &nbsp;O && T && !R && D: return a paragraph of the evaluation of the text as OCL on dgElement <br> * 8 &nbsp;O && T && R && !S: return a paragraph of the evaluation of the text as OCL on each target <br> * 9 &nbsp;O && T && R && S: return a paragraph of the evaluation of the text as OCL on each target-property pair <br> * </code> * <p> * @see gov.nasa.jpl.mbee.model.Query#visit(boolean, java.lang.String) */ @Override public List<DocumentElement> visit(boolean forViewEditor, String outputDir) { Debug.outln( "visit(" + forViewEditor + ", " + outputDir + ")" ); List<DocumentElement> res = new ArrayList<DocumentElement>(); List< Reference > refs = new ArrayList< Reference >(); if (getIgnore()) return res; boolean gotText = getText() != null && !getText().equals(""); boolean gotTargets = getTargets() != null && !getTargets().isEmpty(); boolean gotStereotypeProperties = !Utils2.isNullOrEmpty( getStereotypeProperties() ); Debug.outln("gotText = " + gotText + ", " + getText()); Debug.outln("gotTargets = " + gotTargets + ", " + MoreToString.Helper.toLongString( getTargets()) ); Debug.outln("gotStereotypeProperties = " + gotStereotypeProperties + ", " + getStereotypeProperties()); Debug.outln("desiredAttribute = " + attribute); if (gotText && !tryOcl) { // ignoring targets -- should be none -- REVIEW Debug.outln( "case 4" ); // case 4: return a paragraph of the text, tied to an attribute (the // Documentation attribute as set from parseView) of dgElement if (forViewEditor || !getText().trim().equals("")) { //GeneratorUtils.getObjectProperty( getDgElement(), DocGen3Profile.paragraphStereotype, "body", null ); Stereotype paragraphStereotype = Utils.getStereotype( DocGen3Profile.paragraphStereotype ); Slot s = Utils.getSlot( getDgElement(), Utils.getStereotypePropertyByName( paragraphStereotype, "body" ) ); //StereotypesHelper.getSlot( getDgElement(), , arg2, arg3 ) res.add(new DBParagraph(getText(), s, From.DVALUE)); } //else { //res.add(new DBParagraph(getText())); } else if (gotText && !gotTargets) { // tryOcl must be true Debug.outln( "case 7" ); // case 7: return a paragraph of the evaluation of the text as OCL on dgElement addOclParagraph( res, getText(), dgElement ); } else if ( gotTargets ) { // build up a list of References before generating DBParagraphs for (Object o: targets) { Element e = null; if ( o instanceof Element ) { e = (Element)o; } else if ( !tryOcl ) continue; Reference ref = null; if ( gotStereotypeProperties ) { // for cases 3, 6, and 9 Debug.outln( "case 3, 6, or 9, target=" + o ); for (Property p: getStereotypeProperties()) { ref = Reference.getPropertyReference(e, p); refs.add( ref ); } } else { if ( tryOcl && gotText) { Debug.outln( "case 8, target=" + Utils.getName( o ) ); // for case 8 ref = new Reference( o ); } else { Debug.outln( "case 2 or 5" ); // for cases 2 and 5 ref = new Reference(e, From.DOCUMENTATION, ModelHelper.getComment(e)); } refs.add( ref ); } } if ( tryOcl && !iterate && gotText ) { Debug.outln( "case 8 or 9 a" ); // for cases 8 & 9 when !iterate // apply text as OCL to the collection as a whole ArrayList<Object> results = new ArrayList< Object >(); for ( Reference r : refs ) { results.add( r.getResult() ); } addOclParagraph( res, getText(), results ); } else { if ( !iterate ) { Debug.error( false, "The iterate property should be true when not using OCL or when the OCL is in the targets instead of the body: " + dgElement ); // REVIEW -- create a validation violation instead? // getValidator().addViolationIfUnique( rule, element, comment, reported ); // no public rule to reference! } // creating paragraph for each reference for ( Reference r : refs ) { if ( !tryOcl ) { // gotText is false Debug.outln( "case 2 or 3, ref=" + r ); // cases 2 & 3: return a paragraph for each // target-property pair (3) or for each target's // documentation (2) res.addAll( Common.getReferenceAsDocumentElements( r ) ); // res.add( new DBParagraph( r.getResult(), // r.getElement(), r.getFrom() ) ); } else { if ( gotText ) { Debug.outln( "case 8 or 9, ref=" + r ); // cases 8 & 9: return a paragraph of the evaluation // of the text as OCL on each target-property pair (9) // or on each target (8) addOclParagraph( res, getText(), r.getResult() ); } else { Debug.outln( "case 5 or 6, ref=" + r ); // cases 5 & 6: add a paragraph of the evaluation of // the value of each target-property (6) or of each target's // documentation (5) as OCL on dgElement addOclParagraph( res, r.getResult(), dgElement ); } } } } } // else case 1: gotText and gotTarget are both false, so return nothing Debug.outln( "visit(" + forViewEditor + ", \"" + outputDir + ") returning " + res ); return res; } @SuppressWarnings("unchecked") @Override public void initialize() { String body = (String)GeneratorUtils.getObjectProperty(dgElement, DocGen3Profile.paragraphStereotype, "body", null); setText(body); Object doOcl = GeneratorUtils.getObjectProperty(dgElement, DocGen3Profile.paragraphStereotype, "evaluateOcl", null); if ( doOcl != null ) { tryOcl = Utils.isTrue( doOcl, true ); } Object iter = GeneratorUtils.getObjectProperty(dgElement, DocGen3Profile.paragraphStereotype, "iterate", null); if ( iter != null ) { iterate = Utils.isTrue( iter, false ); // TODO -- use this! } Object attr = GeneratorUtils.getObjectProperty(dgElement, DocGen3Profile.attributeChoosable, "desiredAttribute", null); if ( attr instanceof EnumerationLiteral ) { attribute = Utils.AvailableAttribute.valueOf(((EnumerationLiteral)attr).getName()); if ( attribute != null ) setFrom( Utils.getFromAttribute( attribute ) ); } setStereotypeProperties((List<Property>)GeneratorUtils .getListProperty(dgElement, DocGen3Profile.stereotypePropertyChoosable, "stereotypeProperties", new ArrayList<Property>())); } }
package main.java.gui.application; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Point; import java.rmi.RemoteException; import javax.swing.border.LineBorder; import main.java.data.Data; import main.java.game.ExceptionForbiddenAction; import main.java.game.ExceptionGameHasNotStarted; import main.java.game.ExceptionNoPreviousGameToReach; import main.java.game.ExceptionNotEnoughTilesInDeck; import main.java.game.ExceptionNotYourTurn; import main.java.game.ExceptionTwoManyTilesToDraw; import main.java.gui.components.Button; import main.java.gui.components.Label; import main.java.gui.components.Panel; import main.java.player.PlayerIHM; @SuppressWarnings("serial") public class BottomPlayerPanel extends Panel { // Properties BottomPlayerCardsPanel cardsPanel; Panel buttonsPanel; boolean canBeginTrip = false; String playerName; int numberOfCardPlayed; PlayerIHM player; Label canBeginText; Button validateButton; //Button beginTripButton; Button resetButton; // Constructors public BottomPlayerPanel() { setupBottomPanel(); setupBottomPlayerCardsPanel(); setupBottomPlayerButtonsPanel(); } protected void setupBottomPanel() { this.setLayout(new BorderLayout()); this.setPreferredSize(new Dimension(0, 150)); //this.setBackground(Color.WHITE); } protected void setupBottomPlayerCardsPanel() { this.cardsPanel = new BottomPlayerCardsPanel(); this.add(cardsPanel, BorderLayout.CENTER); } protected void setupBottomPlayerButtonsPanel() { this.buttonsPanel = new Panel(); this.buttonsPanel.setLayout(null); this.buttonsPanel.setBackground(Color.WHITE); this.buttonsPanel.setPreferredSize(new Dimension(205, 150)); validateButton = new Button("Valider", null); resetButton = new Button("Annuler le dernier coup", null); resetButton.setEnabled(false); validateButton.addAction(this, "validateAction"); resetButton.addAction(this, "resetAction"); //beginTripButton.setBounds(0, 15, 200, 35); validateButton.setBounds(0, 55, 200, 35); resetButton.setBounds(0, 95, 200, 35); buttonsPanel.add(validateButton); buttonsPanel.add(resetButton); // TODO display canBeginText //canBeginText = new Label("Vous ne pouvez pas commencer votre voyage"); //canBeginText.setBorder(new LineBorder(Color.BLACK)); //canBeginText.setBounds(0, 15, 200, 35); //canBeginText.setFont(new Font("Serif", Font.PLAIN, 10)); //canBeginText.setFont(getFont()); this.add(buttonsPanel, BorderLayout.EAST); } public void validateAction() { try { int nbTiles = StreetCar.player.getGameData().getPlayerRemainingTilesToDraw(playerName); if (nbTiles > 0) StreetCar.player.drawTile(nbTiles); } catch (RemoteException e1) { e1.printStackTrace(); } catch (ExceptionGameHasNotStarted e1) { e1.printStackTrace(); } catch (ExceptionNotYourTurn e1) { e1.printStackTrace(); } catch (ExceptionNotEnoughTilesInDeck e1) { e1.printStackTrace(); } catch (ExceptionTwoManyTilesToDraw e1) { e1.printStackTrace(); } catch (ExceptionForbiddenAction e1) { e1.printStackTrace(); } try { StreetCar.player.validate(); } catch (RemoteException e) { e.printStackTrace(); } catch (ExceptionGameHasNotStarted e) { e.printStackTrace(); } catch (ExceptionNotYourTurn e) { e.printStackTrace(); } catch (ExceptionForbiddenAction e) { e.printStackTrace(); } } public void resetAction() { try { player.rollBack(); } catch (RemoteException e) { e.printStackTrace(); } catch (ExceptionForbiddenAction e) { e.printStackTrace(); } catch (ExceptionNotYourTurn e) { e.printStackTrace(); } catch (ExceptionNoPreviousGameToReach e) { e.printStackTrace(); } } // TODO delete this? public void beginTrip() { if(canBeginTrip) { Point p = player.getGameData().getPlayerTerminusPosition(playerName)[0]; } } protected void checkIfCanBeginTrip() { if (!canBeginTrip) { return; } Data data = StreetCar.player.getGameData(); if (data.getTramPosition(playerName) == null) { canBeginText = new Label("Vous pouvez commencer votre voyage !"); canBeginText.setFont(new Font("Serif", Font.PLAIN, 10)); canBeginText.setBorder(new LineBorder(Color.BLACK)); canBeginText.setBounds(0, 15, 200, 35); buttonsPanel.add(canBeginText); } else { canBeginText = new Label("Vitesse max = " + data.getMaximumSpeed()); } } protected void checkValidateButton(Data data) { Boolean enabled; try { enabled = !data.hasRemainingAction(this.playerName); } catch (Exception e) { enabled = false; } validateButton.setEnabled(enabled); } protected void checkResetButton(Data data) { /*numberOfCardPlayed = 5 - data.getHandSize(playerName); if (numberOfCardPlayed != 0) { resetButton.setEnabled(true); } else { resetButton.setEnabled(false); }*/ resetButton.setEnabled(!data.isStartOfTurn(playerName)); } protected void paintComponent(Graphics g) { super.paintComponent(g); } private int refreshCount = 0; public void refreshGame(PlayerIHM player, Data data) { this.refreshCount ++; this.player = player; player = StreetCar.player; try { playerName = player.getPlayerName(); canBeginTrip = data.isTrackCompleted(playerName); if (refreshCount > 1) { checkIfCanBeginTrip(); checkValidateButton(data); checkResetButton(data); cardsPanel.refreshGame(player, data); } if (data.isPlayerTurn(playerName)) { cardsPanel.setBackground(new Color(0xC9ECEE)); buttonsPanel.setBackground(new Color(0xC9ECEE)); } else { cardsPanel.setBackground(new Color(0xFFEDDE)); buttonsPanel.setBackground(new Color(0xFFEDDE)); } //beginTripButton.setEnabled(data.isTrackCompleted(playerName)); } catch (RemoteException e) { e.printStackTrace(); } } }
package info.faceland.strife; import com.comphenix.xp.lookup.LevelingRate; import info.faceland.api.FacePlugin; import info.faceland.facecore.shade.command.CommandHandler; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryConfiguration; import info.faceland.facecore.shade.nun.ivory.config.VersionedIvoryYamlConfiguration; import info.faceland.facecore.shade.nun.ivory.config.settings.IvorySettings; import info.faceland.strife.attributes.StrifeAttribute; import info.faceland.strife.commands.AttributesCommand; import info.faceland.strife.commands.StatsCommand; import info.faceland.strife.data.Champion; import info.faceland.strife.listeners.ExperienceListener; import info.faceland.strife.listeners.HealthListener; import info.faceland.strife.managers.ChampionManager; import info.faceland.strife.managers.StrifeStatManager; import info.faceland.strife.stats.StrifeStat; import info.faceland.strife.storage.JsonDataStorage; import info.faceland.strife.tasks.AttackSpeedTask; import info.faceland.strife.tasks.SaveTask; import net.nunnerycode.java.libraries.cannonball.DebugPrinter; import org.bukkit.Bukkit; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.event.HandlerList; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; public class StrifePlugin extends FacePlugin { private DebugPrinter debugPrinter; private VersionedIvoryYamlConfiguration configYAML; private VersionedIvoryYamlConfiguration statsYAML; private StrifeStatManager statManager; private JsonDataStorage storage; private ChampionManager championManager; private SaveTask saveTask; private AttackSpeedTask attackSpeedTask; private CommandHandler commandHandler; private IvorySettings settings; private LevelingRate levelingRate; @Override public void preEnable() { debugPrinter = new DebugPrinter(getDataFolder().getPath(), "debug.log"); statsYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "stats.yml"), getResource("stats.yml"), VersionedIvoryConfiguration.VersionUpdateType.BACKUP_AND_UPDATE); configYAML = new VersionedIvoryYamlConfiguration(new File(getDataFolder(), "config.yml"), getResource("config.yml"), VersionedIvoryConfiguration.VersionUpdateType.BACKUP_AND_UPDATE); statManager = new StrifeStatManager(); storage = new JsonDataStorage(this); championManager = new ChampionManager(); commandHandler = new CommandHandler(this); } public LevelingRate getLevelingRate() { return levelingRate; } @Override public void enable() { if (statsYAML.update()) { getLogger().info("Updating stats.yml"); } if (configYAML.update()) { getLogger().info("Updating config.yml"); } settings = IvorySettings.loadFromFiles(configYAML); List<StrifeStat> stats = new ArrayList<>(); List<String> loadedStats = new ArrayList<>(); for (String key : statsYAML.getKeys(false)) { if (!statsYAML.isConfigurationSection(key)) { continue; } ConfigurationSection cs = statsYAML.getConfigurationSection(key); StrifeStat stat = new StrifeStat(key); stat.setName(cs.getString("name")); stat.setDescription(cs.getString("description")); Map<StrifeAttribute, Double> attributeMap = new HashMap<>(); if (cs.isConfigurationSection("attributes")) { ConfigurationSection attrCS = cs.getConfigurationSection("attributes"); for (String k : attrCS.getKeys(false)) { StrifeAttribute attr = StrifeAttribute.fromName(k); if (attr == null) { continue; } attributeMap.put(attr, attrCS.getDouble(k)); } } stat.setAttributeMap(attributeMap); stats.add(stat); loadedStats.add(stat.getKey()); } for (StrifeStat stat : stats) { getStatManager().addStat(stat); } debug(Level.INFO, "Loaded stats: " + loadedStats.toString()); for (Champion champ : storage.load()) { championManager.addChampion(champ); } saveTask = new SaveTask(this); attackSpeedTask = new AttackSpeedTask(); commandHandler.registerCommands(new AttributesCommand(this)); commandHandler.registerCommands(new StatsCommand(this)); levelingRate = new LevelingRate(); for (int i = 0; i < 100; i++) { levelingRate.put(i, i, (int) (5 + (2 * i) + (Math.pow(i, 1.2))) * i); } } public JsonDataStorage getStorage() { return storage; } @Override public void postEnable() { saveTask.runTaskTimer(this, 20L * 600, 20L * 600); attackSpeedTask.runTaskTimer(this, 5L, 5L); Bukkit.getPluginManager().registerEvents(new ExperienceListener(this), this); Bukkit.getPluginManager().registerEvents(new HealthListener(this), this); debug(Level.INFO, "v" + getDescription().getVersion() + " enabled"); } @Override public void preDisable() { debug(Level.INFO, "v" + getDescription().getVersion() + " disabled"); saveTask.cancel(); HandlerList.unregisterAll(this); } @Override public void disable() { storage.save(championManager.getChampions()); } @Override public void postDisable() { configYAML = null; statsYAML = null; statManager = null; storage = null; championManager = null; saveTask = null; commandHandler = null; settings = null; } public StrifeStatManager getStatManager() { return statManager; } public void debug(Level level, String... messages) { if (debugPrinter != null) { debugPrinter.debug(level, messages); } } public ChampionManager getChampionManager() { return championManager; } public IvorySettings getSettings() { return settings; } }
package info.faceland.strife.effects; import info.faceland.strife.data.StrifeMob; import info.faceland.strife.data.WorldSpaceEffectEntity; import org.bukkit.entity.Entity; import org.bukkit.util.Vector; public class Push extends Effect { private double power; private double height; private boolean cancelFall; private PushType pushType; private Vector tempVector; @Override public void apply(StrifeMob caster, StrifeMob target) { Vector direction; switch (pushType) { case AWAY_FROM_CASTER: direction = getEffectVelocity(caster.getEntity(), target.getEntity()); break; case CASTER_DIRECTION: direction = caster.getEntity().getEyeLocation().getDirection().setY(0).normalize() .multiply(power / 10); break; case WSE_LOCATION: direction = target.getEntity().getVelocity(); direction.add(target.getEntity().getLocation().toVector().subtract(tempVector).setY(0) .normalize().multiply(power / 10)); break; case WSE_DIRECTION: direction = tempVector.clone().setY(0).normalize().multiply(power / 10); break; default: return; } if (cancelFall) { if (target.getEntity().getVelocity().getY() < 0) { target.getEntity().getVelocity().setY(0); } target.getEntity().setFallDistance(0); } direction.add(new Vector(0, height / 10, 0)); target.getEntity().setVelocity(direction); } public void setTempVectorFromWSE(WorldSpaceEffectEntity entity) { if (pushType == PushType.WSE_DIRECTION) { tempVector = entity.getVelocity().normalize(); return; } if (pushType == PushType.WSE_LOCATION) { tempVector = entity.getLocation().toVector(); return; } throw new IllegalArgumentException("Can only set temp vector with a WSE knockback type"); } private Vector getEffectVelocity(Entity from, Entity to) { return to.getLocation().toVector().subtract(from.getLocation().toVector()).setY(0) .normalize().multiply(power / 10); } public void setPower(double power) { this.power = power; } public void setHeight(double height) { this.height = height; } public void setCancelFall(boolean cancelFall) { this.cancelFall = cancelFall; } public void setPushType(PushType pushType) { this.pushType = pushType; } public enum PushType { AWAY_FROM_CASTER, CASTER_DIRECTION, WSE_LOCATION, WSE_DIRECTION } }
package joshie.maritech.items; import java.util.List; import joshie.lib.util.Text; import joshie.mariculture.api.core.MaricultureTab; import joshie.mariculture.api.fishery.fish.FishDNABase; import joshie.mariculture.api.fishery.fish.FishSpecies; import joshie.mariculture.core.items.ItemMCDamageable; import joshie.mariculture.core.util.MCTranslate; import joshie.mariculture.fishery.Fish; import joshie.mariculture.fishery.FishyHelper; import joshie.maritech.extensions.modules.ExtensionFishery; import joshie.maritech.lib.MTModInfo; import joshie.maritech.util.MTTranslate; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; public class ItemFishDNA extends ItemMCDamageable { public ItemFishDNA() { super(MTModInfo.MODPATH, MaricultureTab.tabFishery, 32); } @Override public String getItemStackDisplayName(ItemStack stack) { if(stack.hasTagCompound()) { for(FishDNABase dna: FishDNABase.DNAParts) { if(dna.getHigherString().equals(stack.stackTagCompound.getString("DNAType"))) { String format = MTTranslate.translate("dna.format"); format = format.replace("%D", MTTranslate.translate("dna")); return format.replace("%N", dna.getScannedDisplay(stack)[0]); } } } return MTTranslate.translate("dna.corrupt"); } @Override public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean bool) { if(stack.hasTagCompound()) { for(FishDNABase dna: FishDNABase.DNAParts) { if(dna.getHigherString().equals(stack.stackTagCompound.getString("DNAType"))) { int value = stack.stackTagCompound.getInteger("DNAValue"); if(dna == Fish.species) { FishSpecies species = FishSpecies.species.get(value); if(species.isDominant()) { list.add(MTTranslate.translate("dna.name") + ": " + Text.ORANGE + "(" + species.getName() + ")"); } else { list.add(MTTranslate.translate("dna.name") + ": " + Text.INDIGO + "(" + species.getName() + ")"); } } else if (dna == Fish.gender) { if(value == 0) { list.add(MTTranslate.translate("dna.name") + ": " + Text.DARK_AQUA + "(" + MCTranslate.translate("fish.data.gender.male") + ")"); } else { list.add(MTTranslate.translate("dna.name") + ": " + Text.PINK + "(" + MCTranslate.translate("fish.data.gender.female") + ")"); } } else { list.add(MTTranslate.translate("dna.name") + ": " + dna.getScannedDisplay(stack, false)[1]); } list.add(MTTranslate.translate("dna.value") + ": " + value); } } } } public static ItemStack create(FishDNABase dna, int value) { ItemStack stack = new ItemStack(ExtensionFishery.dna); stack.setTagCompound(new NBTTagCompound()); stack.stackTagCompound.setString("DNAType", dna.getHigherString()); stack.stackTagCompound.setInteger("DNAValue", value); return stack; } public static ItemStack add(ItemStack dnaStack, ItemStack fish) { ItemStack ret = fish.copy(); String type = dnaStack.stackTagCompound.getString("DNAType"); for (FishDNABase dna : FishDNABase.DNAParts) { if (type.equals(dna.getHigherString())) { //Found the matching dna dna.addDNA(ret, dnaStack.stackTagCompound.getInteger("DNAValue")); dna.addLowerDNA(ret, dnaStack.stackTagCompound.getInteger("DNAValue")); return ret; } } return ret; } }
package no.priv.garshol.duke; import java.io.IOException; import java.io.FileOutputStream; import org.xml.sax.helpers.AttributeListImpl; import no.priv.garshol.duke.datasources.Column; import no.priv.garshol.duke.datasources.CSVDataSource; import no.priv.garshol.duke.datasources.JDBCDataSource; import no.priv.garshol.duke.datasources.MongoDBDataSource; import no.priv.garshol.duke.datasources.JNDIDataSource; import no.priv.garshol.duke.datasources.SparqlDataSource; import no.priv.garshol.duke.datasources.ColumnarDataSource; import no.priv.garshol.duke.utils.XMLPrettyPrinter; /** * Can write XML configuration files. <b>WARNING</b>: It does not * completely preserve all aspects of configurations, so be careful. * @since 1.1 */ public class ConfigWriter { /** * Writes the given configuration to the given file. */ public static void write(Configuration config, String file) throws IOException { FileOutputStream fos = new FileOutputStream(file); XMLPrettyPrinter pp = new XMLPrettyPrinter(fos); pp.startDocument(); pp.startElement("duke", null); // FIXME: here we should write the objects, but that's not // possible with the current API. we don't need that for the // genetic algorithm at the moment, but it would be useful. pp.startElement("schema", null); writeElement(pp, "threshold", "" + config.getThreshold()); if (config.getMaybeThreshold() != 0.0) writeElement(pp, "maybe-threshold", "" + config.getMaybeThreshold()); for (Property p : config.getProperties()) writeProperty(pp, p); pp.endElement("schema"); String dbclass = config.getDatabase(false).getClass().getName(); AttributeListImpl atts = new AttributeListImpl(); atts.addAttribute("class", "CDATA", dbclass); pp.startElement("database", atts); pp.endElement("database"); if (config.isDeduplicationMode()) for (DataSource src : config.getDataSources()) writeDataSource(pp, src); else { pp.startElement("group", null); for (DataSource src : config.getDataSources(1)) writeDataSource(pp, src); pp.endElement("group"); pp.startElement("group", null); for (DataSource src : config.getDataSources(2)) writeDataSource(pp, src); pp.endElement("group"); } pp.endElement("duke"); pp.endDocument(); fos.close(); } private static void writeParam(XMLPrettyPrinter pp, String name, String value) { if (value == null) return; AttributeListImpl atts = new AttributeListImpl(); atts.addAttribute("name", "CDATA", name); atts.addAttribute("value", "CDATA", value); pp.startElement("param", atts); pp.endElement("param"); } private static void writeParam(XMLPrettyPrinter pp, String name, int value) { writeParam(pp, name, "" + value); } private static void writeParam(XMLPrettyPrinter pp, String name, char value) { writeParam(pp, name, "" + value); } private static void writeParam(XMLPrettyPrinter pp, String name, boolean value) { writeParam(pp, name, "" + value); } private static void writeElement(XMLPrettyPrinter pp, String name, String value) { if (value == null) return; // saves us having to repeat these tests everywhere pp.startElement(name, null); pp.text(value); pp.endElement(name); } private static void writeProperty(XMLPrettyPrinter pp, Property prop) { AttributeListImpl atts = new AttributeListImpl(); if (prop.isIdProperty()) atts.addAttribute("type", "CDATA", "id"); else if (prop.isIgnoreProperty()) atts.addAttribute("type", "CDATA", "ignore"); if (!prop.isIdProperty() && prop.getLookupBehaviour() != Property.Lookup.DEFAULT) { String value = prop.getLookupBehaviour().toString().toLowerCase(); atts.addAttribute("lookup", "CDATA", value); } pp.startElement("property", atts); writeElement(pp, "name", prop.getName()); if (prop.getComparator() != null) writeElement(pp, "comparator", prop.getComparator().getClass().getName()); if (prop.getLowProbability() != 0.0) writeElement(pp, "low", "" + prop.getLowProbability()); if (prop.getHighProbability() != 0.0) writeElement(pp, "high", "" + prop.getHighProbability()); pp.endElement("property"); } private static void writeDataSource(XMLPrettyPrinter pp, DataSource src) { String name = null; if (src instanceof JNDIDataSource) { name = "jndi"; JNDIDataSource jndi = (JNDIDataSource) src; pp.startElement(name, null); writeParam(pp, "jndi-path", jndi.getJndiPath()); writeParam(pp, "query", jndi.getQuery()); } else if (src instanceof JDBCDataSource) { name = "jdbc"; JDBCDataSource jdbc = (JDBCDataSource) src; pp.startElement(name, null); writeParam(pp, "driver-class", jdbc.getDriverClass()); writeParam(pp, "connection-string", jdbc.getConnectionString()); writeParam(pp, "user-name", jdbc.getUserName()); writeParam(pp, "password", jdbc.getPassword()); writeParam(pp, "query", jdbc.getQuery()); // **Fixup to correctly parse the MongoDBDataSource parameters } else if (src instanceof MongoDBDataSource) { name = "data-source"; MongoDBDataSource mongodb = (MongoDBDataSource) src; String mongoDatasource_classname = (""+mongodb.getClass()).substring(6); AttributeListImpl attribs = new AttributeListImpl(); attribs.addAttribute("class", "CDATA", mongoDatasource_classname); pp.startElement(name, attribs); writeParam(pp, "server-address", mongodb.getServerAddress()); writeParam(pp, "port-number", mongodb.getPortNumber()); writeParam(pp, "user-name", mongodb.getUserName()); writeParam(pp, "password", mongodb.getPassword()); writeParam(pp, "db-auth", mongodb.getDbAuth()); writeParam(pp, "database", mongodb.getDatabase()); writeParam(pp, "cursor-notimeout", mongodb.getCursorNotimeout()); writeParam(pp, "collection", mongodb.getCollection()); writeParam(pp, "query", mongodb.getQuery()); writeParam(pp, "projection", mongodb.getProjection()); } else if (src instanceof CSVDataSource) { name = "csv"; CSVDataSource csv = (CSVDataSource) src; pp.startElement(name, null); writeParam(pp, "input-file", csv.getInputFile()); writeParam(pp, "encoding", csv.getEncoding()); writeParam(pp, "skip-lines", csv.getSkipLines()); writeParam(pp, "header-line", csv.getHeaderLine()); if (csv.getSeparator() != 0) writeParam(pp, "separator", csv.getSeparator()); } else if (src instanceof SparqlDataSource) { name = "sparql"; SparqlDataSource sparql = (SparqlDataSource) src; pp.startElement(name, null); writeParam(pp, "endpoint", sparql.getEndpoint()); writeParam(pp, "query", sparql.getQuery()); writeParam(pp, "page-size", sparql.getPageSize()); writeParam(pp, "triple-mode", sparql.getTripleMode()); } if (src instanceof ColumnarDataSource) { // FIXME: this breaks the order... for (Column col : ((ColumnarDataSource) src).getColumns()) { AttributeListImpl atts = new AttributeListImpl(); atts.addAttribute("name", "CDATA", col.getName()); atts.addAttribute("property", "CDATA", col.getProperty()); if (col.getPrefix() != null) atts.addAttribute("prefix", "CDATA", col.getPrefix()); // FIXME: cleaner really requires object support ... :-( if (col.getCleaner() != null) atts.addAttribute("cleaner", "CDATA", col.getCleaner().getClass().getName()); pp.startElement("column", atts); pp.endElement("column"); } } pp.endElement(name); } }
package org.adrenalinee.stomp; import java.net.URI; import java.nio.channels.NotYetConnectedException; import java.util.LinkedHashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.adrenalinee.stomp.listener.ConnectedListnener; import org.adrenalinee.stomp.listener.DisconnectListener; import org.adrenalinee.stomp.listener.ErrorListener; import org.adrenalinee.stomp.listener.ReceiptListener; import org.adrenalinee.stomp.listener.SubscribeListener; import org.adrenalinee.stomp.listener.WebScoketErrorListener; import org.adrenalinee.stomp.listener.WebSocketCloseListener; import org.java_websocket.client.DefaultSSLWebSocketClientFactory; import org.java_websocket.client.WebSocketClient; import org.java_websocket.drafts.Draft_17; import org.java_websocket.handshake.ServerHandshake; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author shindongseong * @since 2015. 11. 6. */ public class StompClient { private Logger logger = LoggerFactory.getLogger(getClass()); private WebSocketClient webSocketClient; /** * default = 16KB */ private int maxWebSocketFrameSize = 16 * 1024; private Map<String, Subscription> subscriptions = new LinkedHashMap<String, Subscription>(); private Map<String, Receipt> receipts = new LinkedHashMap<String, Receipt>(); private int subscriptionCount; private int transactionCount; private int receiptCount; private Connection connection; private boolean connected; private Heartbeat heartbeat = new Heartbeat(); private Timer pinger; private Timer ponger; private long serverActivity; private DisconnectListener disconnectListener; private ErrorListener errorListener; private ReceiptListener globalReceiptListener; private WebScoketErrorListener webScoketErrorListener; private WebSocketCloseListener webSocketCloseListener; /** * StompClient instance create by clientOverWebsocket() */ private StompClient() { } public static StompClient clientOverWebsocket(String url) { return clientOverWebsocket(url, null); } public static StompClient clientOverWebsocket(String url, HttpHeaders httpHeaders) { if (httpHeaders == null) { httpHeaders = new HttpHeaders(); } StompClient stompClient = new StompClient(); stompClient.connection = new Connection(url, httpHeaders.getHeaders()); return stompClient; } private void transmit(Command command, Map<String, String> headers, String body) { if (!connected) { if (!Command.CONNECT.equals(command)) { logger.warn("not connected yet... command: {}", command); return; } } String out = Frame.marshall(command, headers, body); logger.debug(">>> {}", out); while (true) { if (out.length() > maxWebSocketFrameSize) { webSocketClient.send(out.substring(0, maxWebSocketFrameSize)); out = out.substring(maxWebSocketFrameSize); } else { webSocketClient.send(out); break; } } } private void setupHeartbeat(StompHeaders headers) { String heartbeatValue = headers.getHeartBeat(); if (heartbeatValue == null || "".equals(heartbeatValue)) { return; } String[] heartbeats = heartbeatValue.split(","); int serverOutgoing = Integer.parseInt(heartbeats[0]); int serverIncoming = Integer.parseInt(heartbeats[1]); if (!(heartbeat.getOutgoing() == 0 || serverIncoming == 0)) { int ttl = Math.max(heartbeat.getOutgoing(), serverIncoming); logger.debug("send PING every {}ms", ttl); //pinger pinger = new Timer(); pinger.scheduleAtFixedRate(new TimerTask() { // Logger logger = LoggerFactory.getLogger(getClass()); @Override public void run() { try { webSocketClient.send(Frame.LF); logger.debug(">>> PING"); } catch (NotYetConnectedException e) { logger.error("ping send fail. not yet connected."); } } }, ttl, ttl); } if (!(heartbeat.getIncoming() == 0 || serverOutgoing == 0)) { final int ttl = Math.max(heartbeat.getIncoming(), serverOutgoing); logger.debug("check PONG every {}ms", ttl); //ponger ponger = new Timer(); ponger.scheduleAtFixedRate(new TimerTask() { // Logger logger = LoggerFactory.getLogger(getClass()); @Override public void run() { long delta = System.currentTimeMillis() - serverActivity; if (delta > ttl * 2) { logger.warn("did not receive server activity for the last {}ms", delta); webSocketClient.close(); } } }, ttl, ttl); } } public void connect(final ConnectedListnener connectedLintener) { final String url = connection.getUrl(); final Map<String, String> headers = connection.getHeaders(); final int connecttimeout = connection.getConnecttimeout(); // WebSocketImpl.DEBUG = true; webSocketClient = new WebSocketClient(URI.create(url), new Draft_17(), headers, connecttimeout) { @Override public void onOpen(ServerHandshake handshakedata) { logger.debug("Web Socket Openned..."); Map<String, String> messageHeader = new TreeMap<String, String>(); messageHeader.put("accept-version", "1.1,1.0"); messageHeader.put("heart-beat", heartbeat.getOutgoing() + "," + heartbeat.getIncoming()); transmit(Command.CONNECT, messageHeader, null); } @Override public void onMessage(String message) { serverActivity = System.currentTimeMillis(); if (Frame.LF.equals(message)) { logger.debug("<<< PONG"); return; } logger.debug("<<< {}", message); Frame frame = Frame.unmarshall(message); if (Command.CONNECTED.equals(frame.getCommand())) { connected = true; setupHeartbeat(frame.getHeaders()); if (connectedLintener != null) { try { connectedLintener.onConnected(frame); } catch (Exception e) { logger.error("onConnected error url: " + url, e); } } else { logger.warn("Unhandled received CONNECTED: {}", frame); } } else if (Command.MESSAGE.equals(frame.getCommand())) { // serverActivity = System.currentTimeMillis(); // if (Frame.LF.equals(message)) { // logger.debug("<<< PONG"); // return; String subscription = frame.getHeaders().getSubscription(); frame.setStompClient(StompClient.this); SubscribeListener subscriptionListener = subscriptions.get(subscription).getListener(); if (connectedLintener != null) { try { subscriptionListener.onReceived(frame); } catch (Exception e) { logger.error("onMessage error subscrition id: " + subscription, e); } } else { logger.warn("Unhandled received MESSAGE: {}", frame); } } else if (Command.RECEIPT.equals(frame.getCommand())) { String receiptId = frame.getHeaders().getReceiptId(); Receipt receipt = receipts.remove(receiptId); if (receipt != null) { ReceiptListener receiptListener = receipt.getReceiptListener(); if (receiptListener != null) { try { receiptListener.onReceived(frame); } catch (Exception e) { logger.error("receiptListener.onReceipt error. receipt id: " + receiptId, e); } } else { logger.warn("Unhandled received RECEIPT: " + frame); } } else { //global receipt listener if (globalReceiptListener != null) { try { globalReceiptListener.onReceived(frame); } catch (Exception e) { logger.error("globalReceiptListener.onReceipt error. receipt id: " + receiptId, e); } } else { logger.warn("Unhandled received RECEIPT: {}", frame); } } } else if (Command.ERROR.equals(frame.getCommand())) { if (errorListener != null) { try { errorListener.onError(frame); } catch(Exception e) { logger.error("onErrorCallback error. frame: " + frame, e); } } else { logger.warn("Unhandled received ERROR: {}", frame); } } else { logger.warn("Unhandled frame: {}", frame); } } @Override public void onClose(int code, String reason, boolean remote) { logger.warn("Whoops! Lost connection to {}", connection.getUrl()); if (webSocketCloseListener != null) { try { webSocketCloseListener.onClose(code, reason, remote); } catch (Exception e) { logger.error("webSocketCloseListener.onClose() error. code: " + code + ", reason: " + reason + ", remote: " + remote, e); } } else { logger.warn("Unhandled onClose event. code: {}, reason: {}, remote: {}", code, reason, remote); } cleanUp(); if (disconnectListener != null) { try { disconnectListener.onDisconnect(); } catch (Exception e) { logger.error("disconnectListener.onDisconnect() error.", e); } } } @Override public void onError(Exception ex) { logger.error("websocket error", ex); if (webScoketErrorListener != null) { try { webScoketErrorListener.onError(ex); } catch (Exception e) { logger.error("webScoketErrorListener.onError() error.", e); } } else { logger.warn("Unhandled onError event.", ex); } } }; if (url != null) { if (url.startsWith("wss")) { //TODO SSL . .. webSocketClient.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(createSSLContext())); } } logger.debug("Opening Web Socket... url: {}", url); webSocketClient.connect(); } public void disconnect(final DisconnectListener disconnectListener) { transmit(Command.DISCONNECT, null, null); webSocketClient.close(); cleanUp(); if (disconnectListener != null) { try { disconnectListener.onDisconnect(); } catch (Exception e) { logger.error("disconnectListener.onDisconnect() error.", e); } } } private SSLContext createSSLContext() { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); return sc; } catch (Exception e) { logger.error(" ", e); } return null; } // public void disconnect(final DisconnectListener disconnectListener) { // this.disconnectListener = disconnectListener; // Receipt receipt = new Receipt(); // receipt.setReceiptId("receipt-" + receiptCount++); // receipt.setReceiptListener(new ReceiptListener() { // @Override // public void onReceived(Frame frame) { // webSocketClient.close(); //// cleanUp(); //// if (disconnectListener != null) { //// try { //// disconnectListener.onDisconnect(); //// } catch (Exception e) { //// logger.error("disconnectListener.onDisconnect() error.", e); // receipts.put(receipt.getReceiptId(), receipt); // disconnect(receipt); // private void disconnect(Receipt receipt) { // Map<String, String> headers = new TreeMap<String, String>(); // headers.put("receipt", receipt.getReceiptId()); // transmit(Command.DISCONNECT, headers, null); private void cleanUp() { if (pinger != null) { pinger.cancel(); } if (ponger != null) { ponger.cancel(); } disconnectListener = null; errorListener = null; webScoketErrorListener = null; webSocketCloseListener = null; subscriptions.clear(); receipts.clear(); serverActivity = 0; subscriptionCount = 0; receiptCount = 0; transactionCount = 0; connected = false; } public void send(String destination, String body) { send(destination, null, body); } public void send(String destination, StompHeaders stompHeaders, String body) { Map<String, String> headers = new TreeMap<String, String>(); headers.put("destination", destination); if (stompHeaders != null) { headers.putAll(stompHeaders.getHeaders()); } transmit(Command.SEND, headers, body); } public void subscribe(String destination, SubscribeListener listener) { Subscription subscription = new Subscription(); subscription.setDestination(destination); subscription.setId("sub-" + subscriptionCount++); subscription.setListener(listener); subscriptions.put(subscription.getId(), subscription); subscribe(subscription); } private void subscribe(Subscription subscription) { Map<String, String> headers = new TreeMap<String, String>(); headers.put("destination", subscription.getDestination()); headers.put("id", subscription.getId()); transmit(Command.SUBSCRIBE, headers, null); } public void unsubscribe(String id) { Subscription subscription = subscriptions.get(id); if (subscription == null) { logger.warn("not exist subscription id. id: {}", id); //TODO return; } unsubscribe(subscription); subscriptions.remove(id); } private void unsubscribe(Subscription subscription) { Map<String, String> headers = new TreeMap<String, String>(); headers.put("id", subscription.getId()); transmit(Command.UNSUBSCRIBE, headers, null); } public Transaction bigen() { Map<String, String> headers = new TreeMap<String, String>(); headers.put("transaction", "tx-" + transactionCount++); transmit(Command.BEGIN, headers, null); return new Transaction(this); } public void commit(String transaction) { Map<String, String> headers = new TreeMap<String, String>(); headers.put("transaction", transaction); transmit(Command.COMMIT, headers, null); } public void abort(String transaction) { Map<String, String> headers = new TreeMap<String, String>(); headers.put("transaction", transaction); transmit(Command.ABORT, headers, null); } public void ack(String messageID, String subscription, StompHeaders stompHeaders) { Map<String, String> headers = stompHeaders.getHeaders(); headers.put("message-id", messageID); headers.put("subscription", subscription); transmit(Command.ACK, headers, null); } public void nack(String messageID, String subscription, StompHeaders stompHeaders) { Map<String, String> headers = stompHeaders.getHeaders(); headers.put("message-id", messageID); headers.put("subscription", subscription); transmit(Command.NACK, headers, null); } public boolean isConnected() { return connected; } public void setWebScoketErrorListener(WebScoketErrorListener webScoketErrorListener) { this.webScoketErrorListener = webScoketErrorListener; } public WebScoketErrorListener getWebScoketErrorListener() { return webScoketErrorListener; } public void setWebSocketCloseListener(WebSocketCloseListener webSocketCloseListener) { this.webSocketCloseListener = webSocketCloseListener; } public WebSocketCloseListener getWebSocketCloseListener() { return webSocketCloseListener; } public void setGlobalReceiptListener(ReceiptListener receiptListener) { this.globalReceiptListener = receiptListener; } public ReceiptListener getGlobalReceiptListener() { return globalReceiptListener; } public ErrorListener getErrorListener() { return errorListener; } public void setErrorListener(ErrorListener errorListener) { this.errorListener = errorListener; } } /** * * @author shindongseong * @since 2015. 11. 7. */ class Heartbeat { int outgoing = 10000; int incoming = 10000; public int getOutgoing() { return outgoing; } public void setOutgoing(int outgoing) { this.outgoing = outgoing; } public int getIncoming() { return incoming; } public void setIncoming(int incoming) { this.incoming = incoming; } }
package io.mangoo.email; import java.util.Objects; import java.util.Properties; import com.google.inject.Inject; import com.google.inject.Singleton; import io.mangoo.core.Config; import io.mangoo.enums.Required; import jakarta.mail.Authenticator; import jakarta.mail.MessagingException; import jakarta.mail.PasswordAuthentication; import jakarta.mail.Session; import jakarta.mail.Transport; import jakarta.mail.internet.MimeMessage; @Singleton public class MailCenter { private Session session; @Inject public MailCenter(Config config) { Objects.requireNonNull(config, Required.CONFIG.toString()); var properties = new Properties(); properties.put("mail.smtp.host", config.getSmtpHost()); properties.put("mail.smtp.port", String.valueOf(config.getSmtpPort())); properties.put("mail.smtp.auth", config.isSmtpAuthentication()); properties.put("mail.from", config.getSmtpFrom()); properties.put("mail.debug", config.isSmtpDebug() ? Boolean.TRUE.toString() : Boolean.FALSE.toString()); if (("smtps").equalsIgnoreCase(config.getSmtpProtocol())) { properties.put("mail.smtp.ssl.enable", Boolean.TRUE.toString()); } else if (("smtptls").equalsIgnoreCase(config.getSmtpProtocol())) { properties.put("mail.smtp.starttls.enable", Boolean.TRUE.toString()); } Authenticator authenticator = null; if (config.isSmtpAuthentication()) { authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getSmtpUsername(), config.getSmtpPassword()); } }; } this.session = Session.getInstance(properties, authenticator); } /** * Processes the given mail message and passes it to the underlying SMTP handling * * @param mimeMessage The mimeMessage to send * @throws MessagingException */ public void process(MimeMessage mimeMessage) throws MessagingException { Transport.send(mimeMessage); } public Session getSession() { return session; } }
package org.animotron.graph; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; import java.util.UUID; import org.animotron.MessageDigester; import org.neo4j.graphdb.Relationship; /** * @author <a href="mailto:[email protected]">Dmitriy Shabanov</a> * @author <a href="mailto:[email protected]">Evgeny Gazdovsky</a> * */ public class BinanyBuilder extends GraphBuilder { private final static File STORAGE = new File(AnimoGraph.STORAGE, "binany"); private final static File TMP = new File(STORAGE, "tmp"); static { STORAGE.mkdir(); TMP.mkdirs(); } private InputStream stream; private String path; public BinanyBuilder(InputStream stream, String path) { this.stream = stream; this.path = path; } public Relationship build() { String txID = UUID.randomUUID().toString(); try { File tmp = new File(TMP, txID); tmp.createNewFile(); OutputStream out = new FileOutputStream(tmp); byte buf[] = new byte[1024 * 4]; int len; MessageDigest md = md(); while((len=stream.read(buf))>0) { out.write(buf,0,len); md.update(buf,0,len); } out.close(); stream.close(); String hash = MessageDigester.byteArrayToHex(md.digest()); File l1 = new File(STORAGE, hash.substring(0, 2)); File l2 = new File(l1, hash.substring(0, 4)); File bin = new File(l2, hash); if (bin.exists()) { tmp.delete(); System.out.println("File \"" + bin.getPath() + "\" already stored"); } else { l2.mkdirs(); tmp.renameTo(bin); System.out.println("Store the file \"" + bin.getPath() + "\""); } } catch (IOException e) { e.printStackTrace(); } //TODO: Store binary and build graph for one return getRelationship(); } }
package org.broad.igv.ui.panel; import com.jidesoft.swing.JidePopupMenu; import org.broad.igv.charts.ScatterPlotUtils; import org.broad.igv.feature.RegionOfInterest; import org.broad.igv.track.RegionScoreType; import org.broad.igv.track.TrackType; import org.broad.igv.ui.IGV; import org.broad.igv.ui.action.MenuAction; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Set; /** * @author jrobinso * @date Sep 18, 2010 */ public class RegionMenu extends JPopupMenu { RegionOfInterest roi; ReferenceFrame frame; public RegionMenu(final RegionOfInterest roi, final ReferenceFrame frame) { this(roi, frame, null); } public RegionMenu(final RegionOfInterest roi, final ReferenceFrame frame, String title) { this.roi = roi; this.frame = frame; if (title != null) { JLabel heading = new JLabel("<html>&nbsp;<b>" + title); //heading.setFont(UIConstants.boldFont); add(heading); addSeparator(); } Set<TrackType> loadedTypes = IGV.getInstance().getLoadedTypes(); if (loadedTypes.contains(TrackType.COPY_NUMBER) || loadedTypes.contains(TrackType.ALLELE_SPECIFIC_COPY_NUMBER) || loadedTypes.contains(TrackType.CNV)) { JMenuItem item = new JMenuItem("Sort by amplification"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { IGV.getInstance().sortByRegionScore(roi, RegionScoreType.AMPLIFICATION, frame); } }); add(item); item = new JMenuItem("Sort by deletion"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { IGV.getInstance().sortByRegionScore(roi, RegionScoreType.DELETION, frame); IGV.getInstance().getContentPane().repaint(); } }); add(item); item = new JMenuItem("Sort by breakpoint amplitudes"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { IGV.getInstance().sortByRegionScore(roi, RegionScoreType.FLUX, frame); IGV.getInstance().getContentPane().repaint(); } }); add(item); } if (loadedTypes.contains(TrackType.GENE_EXPRESSION)) { JMenuItem item = new JMenuItem("Sort by expression"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { IGV.getInstance().sortByRegionScore(roi, RegionScoreType.EXPRESSION, frame); IGV.getInstance().getContentPane().repaint(); } }); add(item); } if (loadedTypes.contains(TrackType.MUTATION)) { JMenuItem item = new JMenuItem("Sort by mutation count"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { IGV.getInstance().sortByRegionScore(roi, RegionScoreType.MUTATION_COUNT, frame); IGV.getInstance().getContentPane().repaint(); } }); add(item); } JMenuItem item = new JMenuItem("Sort by value"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { IGV.getInstance().sortByRegionScore(roi, RegionScoreType.SCORE, frame); IGV.getInstance().getContentPane().repaint(); } }); add(item); if (ScatterPlotUtils.hasPlottableTracks()) { addSeparator(); item = new JMenuItem("Scatter Plot ..."); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String chr = roi.getChr(); int start = roi.getStart(); int end = roi.getEnd(); int zoom = frame.getZoom(); ScatterPlotUtils.openPlot(chr, start, end, zoom); } }); add(item); } } }
package org.cs4j.core.domains; import com.sun.istack.internal.NotNull; import org.cs4j.core.SearchDomain; import org.cs4j.core.collections.PackedElement; import org.cs4j.core.collections.PairInt; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Vector; public class VacuumRobot implements SearchDomain { public static final char ROBOT_START_MARKER = 'V'; public static final char ROBOT_END_MARKER = 'E'; // The start location of the robot private int startX = -1; private int startY = -1; // 8 is the maximum count of Vacuum Robot operators // (4 for regular moves and more 4 for diagonals) private VacuumRobotOperator[] reverseOperators = new VacuumRobotOperator[8]; private Vector<PairInt> dirtyLocations = new Vector<>(); // Will be size of dirtyLocations (dirtyLocations.size()) private int maximumDirtyLocationsCount; // Mapping between locations and indexes in the dirtyLocations vector private int[] dirt; private static final int NUM_MOVES = 4; private GridMap map; private boolean heavy = false; private int robotLocationBits; private long robotLocationBitMask; private long singleBitMask; public enum COST_FUNCTION {HEAVY, LITE, UNIT}; // An array of pre-computed {h, d} pairs, each one based on some combination of dirty // locations (any combination is defined by a binary vector) // NOTE: The location of the robot is not considered while building the array double [][] lookupMST_heavy; /** * Whether the i'th location (among all the dirty initials) is dirty * * @param dirt A bit vector of locations * @param i The index of the location to check * * @return True if the location is dirty and False otherwise */ private boolean dirt(long dirt, int i) { return (dirt & (1<<i)) != 0; } /** * Init the possible operators for the given state * * @param state The state whose operators should be initialized */ private void initOps(VacuumRobotState state) { // An empty vector of operators Vector<VacuumRobotOperator> possibleOperators = new Vector<>(); // Get the dirty status on the location of the robot // (in case it is dirty - the value will be the index in the dirtLocations array) int dirt = this.dirt[state.robotLocation]; // Add a SUCK operator if the current location of the robot is dirty // TODO: dirt can't be lower than 0 - it is an index of an array! if (dirt >= 0 && state.isDirty(dirt)) { possibleOperators.add(new VacuumRobotOperator(VacuumRobotOperator.SUCK)); // Otherwise, let's add all the possible moves that the robot can perform } else { // Go ovr all the possible moves for (int i = 0; i < VacuumRobot.NUM_MOVES; ++i) { if (this._isValidMove(state.robotLocation, this.map.possibleMoves[i])) { possibleOperators.add(new VacuumRobotOperator(i)); } } } // Finally, create the possible operators array state.ops = possibleOperators.toArray(new VacuumRobotOperator[possibleOperators.size()]); } /** * Initializes the reverse operators array: For each operator, set its reverse operator * * NOTE: This function is called only once (by the constructor) */ private void _initializeReverseOperatorsArray() { int reversedMovesCount = 0; // Go over all the possible moves for (int i = 0; i < this.map.possibleMovesCount; i++) { // Go over all the possible moves for (int j = 0; j < this.map.possibleMovesCount; j++) { // In case the two operators are not reverse - ignore them if ((this.map.possibleMoves[i].dx != -this.map.possibleMoves[j].dx) || (this.map.possibleMoves[i].dy != -this.map.possibleMoves[j].dy)) { continue; } // Define operator j to be reverse of operator i this.reverseOperators[i] = new VacuumRobotOperator(j); // Count the number of found 'reverse pairs' ++reversedMovesCount; break; } } // The number of reverse pairs must be equal to the total number of operators assert (reversedMovesCount == map.possibleMovesCount); // Finally, add a reverse operator for SUCK: NOP this.reverseOperators[VacuumRobotOperator.SUCK] = new VacuumRobotOperator(VacuumRobotOperator.NOP); } /** * The function calculates h and d values for every possible combination of the dirty * vectors which allows to quickly calculate the actual h and d values for heavy Vacuum * Robot problems */ private void _preComputeMSTHeavy() { // The number of all possible permutations of dirty locations: // This can be easily calculated - since the dirty locations is a binary vector we can // just pre-compute the values for every possible binary vector of the specified length // e.g. Assume that we have 15 dirty locations - then, we have 2^15=32768 possible options // of dirty combinations // For each of the combinations we can compute an MST and calculate h and d values // Then, during the search we can just get the h and d values from the table int perm = (int)Math.pow(2, this.maximumDirtyLocationsCount); // The data structure for saving all the h and d values is a 2-dimensional array of // size perm * 2 (for h and d) this.lookupMST_heavy = new double[perm][2]; // The first value (all the locations are clean) is 0 and 0 => means we reached a goal! this.lookupMST_heavy[0] = new double[] {0, 0}; // Go over all the possible binary vectors of dirt and compute h and d values for (int i = 1; i < perm; ++i) { double[] hd = computeHD_MST(i); this.lookupMST_heavy[i] = hd; } } /** * The constructor of the general VacuumRobot World domain * * @param stream The input stream for parsing the instance * @param costFunction The type of the cost function */ public VacuumRobot(InputStream stream, COST_FUNCTION costFunction) { this.heavy = (costFunction == COST_FUNCTION.HEAVY); // Initialize the input-reader to allow parsing the state BufferedReader in = new BufferedReader(new InputStreamReader(stream)); try { // First, read the size of the grid String sz[] = in.readLine().trim().split(" "); int w = Integer.parseInt(sz[0]); int h = Integer.parseInt(sz[1]); // Now, let's read the board in.readLine(); // Create the map this.map = new GridMap(w, h); // Initialize the dirty locations vector this.dirt = new int[this.map.mapSize]; // Initially, all the locations are clean for (int i = 0; i < this.dirt.length; ++i) { this.dirt[i] = -1; } // Now, read all the locations for (int y = 0; y < h; ++y) { String line = in.readLine(); char[] chars = line.toCharArray(); int ci = 0; // Horizontal for (int x = 0; x < w; ++x) { char c = chars[ci++]; switch (c) { // An obstacle case ' this.map.setBlocked(this.map.index(x, y)); break; // Dirty location } case '*': { // Map between the dirty locations vector and the dirty locations index this.dirt[map.index(x, y)] = this.dirtyLocations.size(); this.dirtyLocations.add(new PairInt(x, y)); break; } // The start location of the robot case '@': case 'V': { this.startX = x; this.startY = y; break; // End of line } case '.': case '_': case ' ': { break; // Net line } case '\n': { assert x == chars.length; break; // Something strange } default: { Utils.fatal("Unknown character" + c); } } } } // Assure there is a start location if (this.startX < 0 || this.startY < 0) { Utils.fatal("No start location"); } } catch(IOException e) { e.printStackTrace(); Utils.fatal("Error reading input file"); } // Set the number of the dirty locations (according to the read value) this.maximumDirtyLocationsCount = this.dirtyLocations.size(); // Compute bit masks for bit twiddling states in pack/unpack // The number of bits required in order to store all the locations of the grid map this.robotLocationBits = (int) Math.ceil(Utils.log2(map.mapSize)); // The bit-mask required in order to access the locations bit-vector this.robotLocationBitMask = Utils.mask(this.robotLocationBits); // The bit-mask required in order to access the dirty state of a single location this.singleBitMask = Utils.mask(1); // All the required bits : locations and the dirty locations (a single bit for each one) int totalRequiredBits = this.robotLocationBits + this.maximumDirtyLocationsCount; // Assure there is no overflow : at most 64 bits can be used in order to store the state if (totalRequiredBits > 64) { System.err.println("Too many bits required: " + totalRequiredBits); System.exit(1); } System.out.println("[Init] Initializes reverse operators"); // Initialize the array of reverse operators this._initializeReverseOperatorsArray(); System.out.println("[Done] (Initializes reverse operators)"); System.out.println("[Init] Initializes MST for heavy calculation"); // Pre-compute the {h, d} pairs for all the possible combinations of dirty vectors this._preComputeMSTHeavy(); System.out.println("[Done] (Initializes MST for heavy calculation)"); } /** * The constructor of the general VacuumRobot World domain * * @param stream The input stream for parsing the instance */ public VacuumRobot(InputStream stream) { this(stream, COST_FUNCTION.UNIT); } /** * A node in a Minimum-Spanning-Tree (MST) */ private class MSTNode { // The parent node private MSTNode p; private int id; private int rank; /** * A constructor of the class * * @param id An identifier of the node */ private MSTNode(int id) { this.id = id; this.p = this; this.rank = 0; } /** * Initializes the state - no parent states and rank is 0 */ void reset() { this.p = this; this.rank = 0; } /** * Connects two nodes - x and y * * @param x The first node * @param y The second node */ private void link(MSTNode x, MSTNode y) { // Connect the states according to their rank if (x.rank > y.rank) { y.p = x; } else { x.p = y; // Increase the second rank if they are equal if (x.rank == y.rank) { ++y.rank; } } } /** * A recursive function that returns a ROOT state that actually represents a set of states * (The returned state must not have a parent - should be a parent of itself) * * NOTE: Actually, this function could be defined as static * * @param x The state whose representative state should be found * * @return The found state */ private MSTNode findSet(MSTNode x) { if (x != x.p) { return this.findSet(x.p); } return x.p; } /** * Connects the set of state in which this state recedes, to the set of states in which * state y recedes * * @param y The state which should be connected to this state */ private void union(MSTNode y) { this.link( this.findSet(this), this.findSet(y) ); } } /** * An Edge that connects two MST nodes */ private class MSTEdge implements Comparable<MSTEdge> { private MSTNode u; private MSTNode v; private int weight; /** * A constructor of the class : constructs an edge that connects two given nodes * @param u The first node * @param v The second node * @param weight The weight of the edge */ private MSTEdge(MSTNode u, MSTNode v, int weight) { this.u = u; this.v = v; this.weight = weight; } /** * Compares the edge to other one - the one with the smallest weight is the 'winner' * * @param other The edge to which this edge is compared * * @return A negative number if the weight of the current edge is smaller, * a positive number if the weight of the current edge is higher * and 0 if the weights are equal */ @Override public int compareTo(@NotNull MSTEdge other) { return this.weight - other.weight; } } /** * This class represents a grid on which the robot is moving and sucking garbage */ private class GridMap { private int mapWidth; private int mapHeight; private int mapSize; private char map[]; private Move possibleMoves[]; private int possibleMovesCount; /** * The constructor of the class - constructs a Map with a pre-defined width and height * * @param mapWidth The width of the map * @param mapHeight The height of the map */ private GridMap(int mapWidth, int mapHeight) { this.mapWidth = mapWidth; this.mapHeight = mapHeight; // The total size of the map this.mapSize = this.mapWidth * this.mapHeight; // The locations of the map : (mapWidth * mapHeight) this.map = new char[mapSize]; // All the possible moves (can't move diagonally) this.possibleMoves = new Move[4]; this.possibleMovesCount = possibleMoves.length; // Initialize all the moves according to the real directions to perform this.possibleMoves[0] = new Move(this, 'S', 0, 1); this.possibleMoves[1] = new Move(this, 'N', 0, -1); this.possibleMoves[2] = new Move(this, 'W', -1, 0); this.possibleMoves[3] = new Move(this, 'E', 1, 0); } /** * Make some location to tbe 'blocked': The robot can't be at this location * * @param loc The location to block */ void setBlocked(int loc) { this.map[loc] = ' } /** * Whether the queried location is blocked * * @param loc The location to check * * @return True if the location is blocked and False otherwise */ boolean isBlocked(int loc) { return map[loc] == ' } /** * Calculate the index of the location in a one-dimensional array * * @param x The horizontal location * @param y The vertical location * * @return The calculated index */ int index(int x, int y) { return y * this.mapWidth + x; } /** * Creates a Pair object with the dimensions of the given location * * @param loc The location of the object * @return The calculated Pair */ PairInt getPosition(int loc) { return new PairInt(loc % mapWidth, loc / mapWidth); } } /** * A specific Move performed on the grid */ private class Move { // An identification of the move private char id; // The x and y deltas between this move and the previous move private int dx; private int dy; private int delta; /** * The constructor of the class * * @param map The grid on which the move is performed * @param id The identification of the move * @param dx The x delta of the move * @param dy The y delta of the move */ private Move(GridMap map, char id, int dx, int dy) { this.id = id; this.dx = dx; this.dy = dy; this.delta = dx + map.mapWidth * dy; } } /** * This function creates a single MSTEdge which connects a state u and a state v * The function (is auxiliary) is called by the following functions: * 1. {@see _computeMSTForSingleState} * 2. {@see _computeMSTForSingleStateOnlyDirty} * * @param u The index of the node in the nodes array * @param xy A pair of doubles, which contains the location of the node u * @param v An index in the nodes array, from which we start to build the edges * @param nodes An array which contains all the MST nodes * * @return The calculated edge */ private MSTEdge __computeMSTForSingleState(int u, PairInt xy, int v, MSTNode[] nodes) { // Add the computed edge to the list of edges return new MSTEdge( nodes[u], nodes[v], // The weight of the edge is the Manhattan distance between the locations Utils.calcManhattanDistance( xy, this.dirtyLocations.get(v) ) ); } /** * An auxiliary function for computing all the edges of the MST whose first side is equal to * some specific state, starting from a pre-given index in the states array * * NOTE: Only states that ARE ACTUALLY DIRTY are considered in this function * NOTE: The function assumes that the location at index u, located at (x, y) is DIRTY * * @param u The index of the node in the nodes array * @param xy A pair of doubles, which contains the location of the node u * @param v An index in the nodes array, from which we start to build the edges * @param nodes An array which contains all the MST nodes * @param edges The edges list into which the calculated edges are added */ private void _computeMSTForSingleStateOnlyDirty(int dirtyVector, int u, PairInt xy, int v, MSTNode[] nodes, List<MSTEdge> edges) { // Go over all the NEXT dirty locations for (; v < this.dirtyLocations.size(); ++v) { // Again, treat only dirty locations if (!this.dirt(dirtyVector, v)) { continue; } edges.add(this.__computeMSTForSingleState(u, xy, v, nodes)); } } /** * Initializes an array of MSTNodes of a given count * * @param count The number of nodes to create * * @return The created array of nodes */ private MSTNode[] _initializeNodesArray(int count) { // All the dirty locations + location for the robot? MSTNode mstNodes[] = new MSTNode[count]; // An initialization step for (int i = 0; i < mstNodes.length; ++i) { mstNodes[i] = new MSTNode(i); } return mstNodes; } /** * Used for DEBUG issues: * verifies a given MST by checking that all the states have the same root * * @param mstEdges An array of all the edges of the MST */ // public void verifyMST(MSTEdge[] mstEdges) { // int setId = -1; // for (MSTEdge e : mstEdges) { // if (setId == -1) { // setId = e.u.findSet(e.u).id; // assert e.u.findSet(e.u).id == setId; // assert e.v.findSet(e.v).id == setId; /** * Given a state, computes a minimum spanning tree whose nodes are formed all the dirty * locations WHICH ARE ACTUALLY MARKED AS DIRTY * * @return The computed MST (set of edges) */ private List<MSTEdge> computeMSTOnlyDirty(int dirt) { // Initialize a MSTNodes array of size dirtyLocations MSTNode mstNodes[] = this._initializeNodesArray(this.dirtyLocations.size()); // Compute an MST of only the dirty locations (which are marked as actually dirty) List<MSTEdge> mstEdges = new ArrayList<>(); for (int u = 0; u < this.dirtyLocations.size(); ++u) { // Treat only dirty locations if (!this.dirt(dirt, u)) { continue; } // Find all the edges which start from the node with index u, // and start the computation at index v (treat only actually dirty locations) this._computeMSTForSingleStateOnlyDirty( dirt, u, this.dirtyLocations.get(u), u + 1, mstNodes, mstEdges); } Collections.sort(mstEdges); return mstEdges; } /** * Computes the heuristic values (h and d) of the CURRENT state, * based on an MST that are built from the ACTUALLY DIRTY locations * * @param dirt The binary vector which states for each location of the grid, whether it is dirty * * @return An array of the form {h, d} */ private double[] computeHD_MST(int dirt) { int remainingDirt = 0; // Count the dirty locations for (int u = 0; u < this.dirtyLocations.size(); ++u) { if (this.dirt(dirt, u)) { ++remainingDirt; } } // At least two remaining dirty locations should exist, otherwise, the heuristic value is 0 // TODO: Why??? if (remainingDirt <= 1) { return new double[] {0, 0}; } // Compute an MST of only the dirty locations (which are marked as actually dirty) List<MSTEdge> mstEdges = this.computeMSTOnlyDirty(dirt); // Since currently the tree is rooted at a 'random' state - let's make it be rooted at a // state whose rank is the highest // (remember that the edges are sorted by weight - the edge with the lowest weight is first) // Also, define the <i>p</i> and <i>rank</i> values for each state MSTEdge mst[] = new MSTEdge[remainingDirt - 1]; int j = mst.length - 1; // Go over all the built edges for (MSTEdge e : mstEdges) { // Bypass that pair of edges {e, v} if they have the same root state if (e.u.findSet(e.u) == e.v.findSet(e.v)) { continue; } // Add the edge to the list of edges // (the array will be sorted from highest to lowest weight values) // (don't forget to decrease the value of j after adding the edge to the array) mst[j e.u.union(e.v); } // DEBUG: verify the tree: All the MST states must have the same root! // verifyMST(mst); return this._computeHDAccordingToDirtyLocationsMST(mst, remainingDirt); } /** * The function calculates the distance between a given location and the closest dirty location * * @param xy The location whose distance (to the closest dirty location) should be calculated * @param ignoreIndexes An array of location indexes that should be ignored while traversing all * the locations (optional) * NOTE: The size of ignoreIndexes (ignoreIndexes.length) must be equal to the total number of * the possible dirty locations (dirtLocations.size()) * @param s The state in which the dirty locations recede * * @return A pair of : * { * DIRT: index of the dirty location closest to the robot, * DISTANCE: the calculated closest (minimum) distance, * } */ private int[] __getMinimumDirtAndDistanceToDirty(PairInt xy, boolean[] ignoreIndexes, VacuumRobotState s) { // The index of the dirty location, closest to the robot int minDirtyIndex = -1; // Initially, the minimum distance is the lowest possible value int minDirtyDist = Integer.MAX_VALUE; // Go over all the (possible) dirty locations for (int n = 0; n < this.maximumDirtyLocationsCount; ++n) { // If the location should be ignored or was already cleaned - bypass it if ((ignoreIndexes != null && ignoreIndexes[n]) || (!s.isDirty(n))) { continue; } // Get the distance between the robot location and the current dirty location int currentDist = Utils.calcManhattanDistance(xy, this.dirtyLocations.get(n)); // Update the minimum distance if required if (currentDist < minDirtyDist) { minDirtyIndex = n; minDirtyDist = currentDist; } } return new int[]{minDirtyIndex, minDirtyDist}; } /** * The function calculates the distance between a given location and the closest dirty location * * @param xy The location whose distance (to the closest dirty location) should be calculated * @param s The state in which the dirty locations recede * * {@see __getMinimumDirtAndDistanceToDirty} * * @return A pair of : * { * DIRT: index of the dirty location closest to the robot, * DISTANCE: the calculated closest (minimum) distance, * } */ /* private int[] _getMinimumDirtAndDistanceToDirty(PairInt xy, VacuumRobotState s) { // We don't have locations to ignore - so pass null as a parameter return this.__getMinimumDirtAndDistanceToDirty(xy, null, s); } */ /** * The function calculates the distance between a given location and the closest dirty location * * @param xy The location whose distance (to the closest dirty location) should be calculated * @param s The state in which the dirty locations recede * * @return The calculated minimum distance */ /* private int _getMinimumDistanceToDirty(PairInt xy, VacuumRobotState s) { return this._getMinimumDirtAndDistanceToDirty(xy, s)[1]; } */ /** * The function calculates h and d values given a pre-computed MST of all the remaining * dirty locations * * @param mstEdgesDirty An MST of all the locations that are dirty * @param remainingDirt The number of remaining dirty locations * * @return A pair of calculated h and d values {h, d} */ private double[] _computeHDAccordingToDirtyLocationsMST(MSTEdge mstEdgesDirty[], int remainingDirt) { // Initial values double h = 0.0d; double d = 0.0d; // Calculate the number of locations that are CLEAN // This value is used for the heavy operation - it is calculated by applying some function // on the number of the locations cleaned by the robot // The idea behind that calculation is that the robot is consuming fuel during the clean // operations, so each operation must cost more than the previous // TODO: +1? Why? int robotHeavyAddend = (this.maximumDirtyLocationsCount - (remainingDirt)) + 1; // Here we define the cost of a single operation that the robot should perform // (either MOVE or VACUUM) which normally costs 1.0 // In case heavy mode is applied, the operation will cost 1 + some function applied on the // number of required operations double robotOperationCost = (heavy) ? (this.heavy(robotHeavyAddend) + 1.0d) : 1.0d; // Now, let's calculate the h and d values for (MSTEdge edge : mstEdgesDirty) { // The cost of the operations to perform: MOVing and VACUUM h += (edge.weight * robotOperationCost + robotOperationCost); // Number of operations to perform: MOVing and VACUUM d += (edge.weight + 1); // Increase the number of locations passed by robot and update the cost of its single // operation ++robotHeavyAddend; robotOperationCost = (heavy) ? heavy(robotHeavyAddend) + 1.0d : 1.0d; } // Finally, we got the h and d values, so, let's return them return new double[]{h, d}; } private double[] __getHDAddendToClosestDirtyLocation(VacuumRobotState s, boolean[] ignoreIndexes, int[] closestLocationIndex){ int[] closestDirtAndDistance = this.__getMinimumDirtAndDistanceToDirty( // Location of the robot this.map.getPosition(s.robotLocation), ignoreIndexes, s ); // Fill the output parameter with the index of the location closest to the robot // (if the output parameter is not null) if (closestLocationIndex != null) { closestLocationIndex[0] = closestDirtAndDistance[0]; } int shortestDistance = closestDirtAndDistance[1]; // In case of heavy calculation - the cost of robot operation is // 1 + number of edges already considered (number of cleaned states) double robotOperationCost = (this.heavy) ? (heavy(s) + 1.0d) : 1.0d; // Cost of operations: MOVE * FUEL + SUCK double hAddend = (shortestDistance * robotOperationCost + robotOperationCost); // Number of operations: MOVE + SUCK double dAddend = (shortestDistance + 1.0d); return new double[]{hAddend, dAddend}; } private double[] _getHDAddendToClosestDirtyLocation(VacuumRobotState s) { // No locations to ignore and not output index of the closest distance to the robot location return this.__getHDAddendToClosestDirtyLocation(s, null, null); } /** * An auxiliary function for computing all the edges of the MST whose first side is equal to * some specific state, starting from a pre-given index in the states array * * @param u The index of the node in the nodes array * @param xy A pair of doubles, which contains the location of the node u * @param v An index in the nodes array, from which we start to build the edges * @param nodes An array which contains all the MST nodes * @param edges The edges list into which the calculated edges are added */ /* private void _computeMSTForSingleState(int u, PairInt xy, int v, MSTNode[] nodes, List<MSTEdge> edges) { // Go over all the NEXT dirty locations for (; v < this.dirtyLocations.size(); ++v) { edges.add(this.__computeMSTForSingleState(u, xy, v, nodes)); } } */ /** * Given a state, computes a minimum spanning tree whose nodes are formed all the dirty * locations * * NOTE: The locations from which the MST is formed ARE NOT CHECKED OF BEING DIRTY * * @return The computed MST (set of edges) */ /* private List<MSTEdge> _computeMST() { // Create an array of nodes (without the location of the robot) // All the dirty locations + location for the robot? MSTNode mstNodes[] = this._initializeNodesArray(this.dirtyLocations.size()); // Initial set of mstEdges (initially empty) List<MSTEdge> mstEdges = new ArrayList<>(); // Go over all the dirty locations for (int u = 0; u < this.dirtyLocations.size(); ++u) { // Find all the edges which start from the node with index u, // and start the computation at index v this._computeMSTForSingleState( u, this.dirtyLocations.get(u), u + 1, mstNodes, mstEdges); } // Sort the collection of edges by weight Collections.sort(mstEdges); return mstEdges; } */ /** * Given a state, computes a minimum spanning tree whose nodes are formed all the dirty * locations AND THE LOCATION OF THE ROBOT OF THAT STATE * * NOTE: The locations from which the MST is formed ARE NOT CHECKED OF BEING DIRTY * * @param state The state from which the minimum spanning tree should be computed * * @return The computed MST (set of edges) */ /* private List<MSTEdge> _computeMST(VacuumRobotState state) { // All the dirty locations + location for the robot? MSTNode mstNodes[] = this._initializeNodesArray(this.dirtyLocations.size() + 1); // Initial set of mstEdges (initially empty) List<MSTEdge> mstEdges = new ArrayList<>(); for (int u = 0; u < this.dirtyLocations.size() + 1; ++u) { // Get the location (one from the dirty locations or the location of the robot) PairInt xy = (u < this.dirtyLocations.size()) ? this.dirtyLocations.get(u) : this.map.getPosition(state.robotLocation); // Next dirty location int v = (u < this.dirtyLocations.size()) ? u + 1 : 0; // Find all the edges which start from the node with index u, and start the computation // at index v this._computeMSTForSingleState(u, xy, v, mstNodes, mstEdges); } // Sort the collection of edges by weight Collections.sort(mstEdges); return mstEdges; } */ /** * Calculate the h and d values for heavy vacuum problems: * 1. Compute the minimum spanning tree (MST) of the isDirty piles * 2. Order the edges by greatest length first * 3. Multiply the edge weights by the current weight of the robot plus the number of edges * already considered * (Add same calculation for the robot: * Reaching the closest dirty position from the current location of the robot) * * @param s The state whose heuristic values should be calculated * * @return An array of the form {h, d} */ /* private double[] computeHD_chris(VacuumRobotState s) { // Initial values double h; double d; // In case we are at goal - return 0 values if (s.remainingDirtyLocationsCount == 0) { return new double[]{0.0d, 0.0d}; } // Build mst of all the POTENTIALLY DIRTY locations List<MSTEdge> mstEdges = this._computeMST(); // Compute an MST of only the dirty locations (which are marked as actually dirty) // Number of edges of the MST (also mstEdges.size()) MSTEdge mst[] = new MSTEdge[s.remainingDirtyLocationsCount - 1]; // The last index in the array int j = mst.length - 1; for (MSTEdge e : mstEdges) { // If one of the nodes that form the edge is clean - bypass it if ((e.u.id < this.maximumDirtyLocationsCount && !s.isDirty(e.u.id)) || (e.v.id < this.maximumDirtyLocationsCount && !s.isDirty(e.v.id))) { continue; } // Nodes at both sides of the edge are dirty - let's define their parent // (if not identical) if (e.u.findSet(e.u) == e.v.findSet(e.v)) { continue; } // Add the edge to the final list of edges mst[j] = e; e.u.union(e.v); j--; } // DEBUG: verify the tree: All the MST states must have the same root! // verifyMST(); double[] hd = this._computeHDAccordingToDirtyLocationsMST(mst, s.remainingDirtyLocationsCount); // Extract the h and d values h = hd[0]; d = hd[1]; // now include edge for shortest isDirty to the current location of the robot double[] hdAddend = _getHDAddendToClosestDirtyLocation(s); // Finally, return the final h and d values return new double[]{h + hdAddend[0], d + hdAddend[1]}; } */ /** * This function is equivalent to the {@see computeHD_chris} function. * However, it uses pre-computed values of h and d which are calculated based on the * dirty locations binary vector - of the current state * * @param s The state whose heuristic values should be calculated * * @return An array of the form {h, d} */ private double[] computeHD_chris_fast(VacuumRobotState s) { // In case we are at goal - return 0 immediately if (s.remainingDirtyLocationsCount == 0) { return new double[]{0.0d, 0.0d}; } // Get the {h, d} pair for the current dirty locations binary vector double[] hd = this.lookupMST_heavy[s.dirt]; double h = hd[0]; double d = hd[1]; // Now, include edge for shortest dirt to the current location of the robot double[] hdAddend = _getHDAddendToClosestDirtyLocation(s); // Finally, return the final h and d values return new double[]{h + hdAddend[0], d + hdAddend[1]}; } /** * The function computes the h and d values in a greedy manner, which means that the * cost of moving the robot to the closest dirty location is calculated, then, moving it to the * next closest location etc. * * For heavy Vacuum Robot problems, the weight of each edge is multiplied by the current weight * of the robot plus the number of edges already considered * * @param s The state whose heuristic values should be calculated * * @return An array of the form {h, d} */ private double[] computeHD_greedy(VacuumRobotState s) { double h = 0.0d; double d = 0.0d; // In case we are at goal - return 0 immediately if (s.remainingDirtyLocationsCount == 0) { return new double[]{0.0d, 0.0d}; } int[] minDistDirtyIndexArray = new int[1]; double[] hdAddend = this.__getHDAddendToClosestDirtyLocation( // The state s, // No locations to ignore null, // OUTPUT parameter: The index of the location closest to the robot minDistDirtyIndexArray ); // Increase h and d values by moving the robot to the closest dirty location h += hdAddend[0]; d += hdAddend[1]; // Extract the output values: the index of the dirty location, closest to the robot int minDirtyIndex = minDistDirtyIndexArray[0]; // Number of cleaned locations // The last +1 is because the robot has been already moved to the closest location int numberOfCleanLocations = (this.maximumDirtyLocationsCount - s.remainingDirtyLocationsCount) + 1; // Sum the greedy traversal of remaining dirty locations boolean used[] = new boolean[this.maximumDirtyLocationsCount]; for (int rem = s.remainingDirtyLocationsCount - 1; rem > 0; --rem) { assert (s.isDirty(minDirtyIndex)); used[minDirtyIndex] = true; // Calculate the distance to the next closest location // (starting from the dirty location the robot is currently on) int[] minDirtyDirtAndDistance = this.__getMinimumDirtAndDistanceToDirty( // Current dirty location this.dirtyLocations.get(minDirtyIndex), // Indexes of locations to ignore used, s ); minDirtyIndex = minDirtyDirtAndDistance[0]; int minDirtyDistance = minDirtyDirtAndDistance[1]; double robotOperationCost = this.heavy(numberOfCleanLocations) + 1.0d; // Cost of current operation: MOVE * FUEL + SUCK h += (minDirtyDistance * robotOperationCost + robotOperationCost); // Number of operations: MOVE + SUCK d += (minDirtyDistance + 1); // One more location has been cleaned ++numberOfCleanLocations; } // For h on the heavy vacuum problems, multiply the edge weights by the current // weight of the robot plus the number of edges already considered if (this.heavy) { return new double[]{h, d}; } else { // Estimate the cost of a greedy traversal of the dirt piles: Calculate the number of // actions required to send the robot to the nearest pile of dirt, then the nearest after // that, and so on return new double[]{d, d}; } } /** * Compute the h and d values of a given state of the Vacuum Robot on the HEAVY Vacuum * Robot problems * * @param state The state whose heuristic values should be computed * * @return The pair of the form {h, d} */ private double[] computeHD_jordan(VacuumRobotState state) { // In case we are at goal - return 0 immediately if (state.remainingDirtyLocationsCount == 0) { return new double[]{0.0d, 0.0d}; } // For h, use the function based on fast calculation because of PRE-COMPUTED MSTs double h = computeHD_chris_fast(state)[0]; // This is an alternative (no fast calculation) // double h = computeHD_chris(s)[0]; // For d, use the standard function for the unit cost domain (which estimates the cost of a // greedy traversal of the the dirt piles) double d = computeHD_greedy(state)[1]; return new double[]{h, d}; } /** * Compute the heuristic value of a given state * * @param s The state whose heuristic value should be computed * @return The computed value */ private double[] computeHD(VacuumRobotState s) { /* if (this.heavy) { return computeHD_jordan(s); } else { return computeHD_greedy(s); }*/ return computeHD_jordan(s); } /** * The heavy function for Explicit Estimation Search * * @param ndirt The number of dirty location that were ALREADY CLEAN BY THE ROBOT * * @return The value of the function (currently is linear in number of the locations that were * already cleaned) */ private double heavy(int ndirt) { return ((double)ndirt); } /** * The heavy function for Explicit Estimation Search * * @param state The state for which the function should be calculated * * @return The value of the function (currently is linear in the number of locations that were * already cleaned) */ private double heavy(VacuumRobotState state) { // Number of cleaned locations: # of all possible dirty - # of still dirty return heavy(this.maximumDirtyLocationsCount - state.remainingDirtyLocationsCount); } /** * The function calculates the pair {h, d} by summing the Manhattan distance between the * farthest points of the surrounding rectangle of all the dirty locations * (+ the number of locations that the robot should clean) * * @param s The state whose heuristic values should be computed * * @return The pair of the form {h, d} */ /* private double[] computeHD_ethan(VacuumRobotState s) { // In case we are at goal - return 0 immediately if (s.remainingDirtyLocationsCount == 0) { return new double[]{0.0d, 0.0d}; } int i = 0; // Find the first dirty location in the vector (such one must exist) while (i < this.maximumDirtyLocationsCount && !s.isDirty(i)) { ++i; } PairInt dirtyLocation = this.dirtyLocations.get(i); // The minimum and maximum found X values are equal to the firstly taken location int minX = dirtyLocation.first; int maxX = minX; // The minimum and maximum found Y values are equal to the firstly taken location int minY = dirtyLocation.second; int maxY = minY; // Continue looking in the dirty locations array (increase i index) for (i++; i < maximumDirtyLocationsCount; i++) { // Bypass locations that has been already cleaned if (!s.isDirty(i)) { continue; } // Get the current dirty location and its X and Y values dirtyLocation = this.dirtyLocations.get(i); int currentX = dirtyLocation.first; int currentY = dirtyLocation.second; // Update minX, maxX, minY and maxY values (if required) if (currentX < minX) { minX = currentX; } if (currentX > maxX) { maxX = currentX; } if (currentY < minY) { minY = currentY; } if (currentY > maxY) { maxY = currentY; } } // Now, calculate the Manhattan distance between the farthest locations of the surrounding // square of all the possible dirty locations (+ number of dirty locations to clean) double sum = s.remainingDirtyLocationsCount + (maxX - minX) + (maxY - minY); return new double[]{sum, sum}; } */ /** * Checks whether the given move is valid for the given location * * @param location The location on the map, on which the move is applied * @param move The move to apply * * @return True if the move is valid and false otherwise */ private boolean _isValidMove(int location, Move move) { // Add the delta of the move and get the next location int next = location + move.delta; // Assure the move doesn't cause the state to exceed the grid and also that the move // doesn't cause the state to reach a blocked location // (Moving West/East && y changed) => invalid! if (move.dx != 0 && (next / this.map.mapWidth != location / this.map.mapWidth)) { return false; // Moving (South/North && x changed) => invalid } else if (move.dy != 0 && (next % this.map.mapWidth != location % this.map.mapWidth)) { return false; } return (next > 0 && next < this.map.mapSize && !this.map.isBlocked(next)); } @Override public VacuumRobotState initialState() { VacuumRobotState vrs = new VacuumRobotState(); vrs.robotLocation = this.map.index(this.startX, this.startY); vrs.remainingDirtyLocationsCount = this.maximumDirtyLocationsCount; // Initially, all the dirty locations should be marked as dirty (will be cleaned later) for (int i = 0; i < this.maximumDirtyLocationsCount; i++) { vrs.setDirty(i, true); } // Compute the initial h and d values and fill the state with that values double hd[] = this.computeHD(vrs); // Initially, g value equals to -1 vrs.h = hd[0]; vrs.d = hd[1]; // System.out.println(this.dumpState(vrs)); // System.out.println(this.dumpState(vrs)); // Return the created state return vrs; } @Override public boolean isGoal(State state) { VacuumRobotState drs = (VacuumRobotState)state; return drs.remainingDirtyLocationsCount == 0; } @Override public int getNumOperators(State state) { VacuumRobotState vrs = (VacuumRobotState) state; if (vrs.ops == null) { this.initOps(vrs); // TODO: Is required? assert vrs.ops.length < 6; } return vrs.ops.length; } @Override public Operator getOperator(State state, int index) { VacuumRobotState vrs = (VacuumRobotState)state; if (vrs.ops == null) { this.initOps(vrs); } return vrs.ops[index]; } @Override public State copy(State state) { return new VacuumRobotState((VacuumRobotState)state); } /** * Pack a state into a long number * * The packed state is a 64 bit (long) number which stores the following data: * * First part stores the location of the robot * The next part stores a bit vector which indicated for each possible location, whether it is dirty */ @Override public PackedElement pack(State s) { VacuumRobotState state = (VacuumRobotState)s; long packed = 0L; // pack the location of the robot packed |= (state.robotLocation & this.robotLocationBitMask); // pack 1 bit for each remaining dirt for (int i = 0; i < this.maximumDirtyLocationsCount; ++i) { packed <<= 1; if (state.isDirty(i)) { packed |= 1 & this.singleBitMask; } } PackedElement toReturn = new PackedElement(packed); /** * Debug: perform unpack after packing and assure results are ok */ if ((((VacuumRobotState)this.unpack(toReturn)).robotLocation != state.robotLocation) || (((VacuumRobotState)this.unpack(toReturn)).dirt != state.dirt)) { assert false; } /* * VacuumRobotState test = unpack(packed); * assert(test.equals(state)); */ return toReturn; } /** * An auxiliary function for unpacking Vacuum Robot state from a long number. * This function performs the actual unpacking * * @param packed The packed state * @param dst The destination state which is filled from the unpacked value */ private void _unpackLite(long packed, VacuumRobotState dst) { // unpack the dirty locations dst.ops = null; // Initially, there are no dirty locations dst.remainingDirtyLocationsCount = 0; dst.dirt = 0; // For each possible dirty location, check if it is actually dirty for (int i = this.maximumDirtyLocationsCount - 1; i >= 0; --i) { long d = packed & singleBitMask; if (d == 1) { // Make the location dirty dst.setDirty(i, true); // Increase the counter ++dst.remainingDirtyLocationsCount; } else { // Clear the dirty value from the location dst.setDirty(i, false); } packed >>= 1; } // Finally, unpack the location of the robot dst.robotLocation = (int) (packed & this.robotLocationBitMask); } /** * An auxiliary function for unpacking Vacuum Robot state from a long number * * @param packed The packed state * @param dst The destination state which is filled from the unpacked value */ private void unpack(long packed, VacuumRobotState dst) { this._unpackLite(packed, dst); // Compute the heuristic values double hd[] = this.computeHD(dst); dst.h = hd[0]; dst.d = hd[1]; } /** * Unpacks the Vacuum Robot state from a long number */ @Override public State unpack(PackedElement packed) { assert packed.getLongsCount() == 1; VacuumRobotState dst = new VacuumRobotState(); this.unpack(packed.getFirst(), dst); return dst; } /** * Apply the given operator on the given state and generate a new state * * @param state The state to apply the operator on * @param op The operator to apply the state on * * @return The new generated state */ @Override public State applyOperator(State state, Operator op) { VacuumRobotState s = (VacuumRobotState)state; VacuumRobotState vrs = (VacuumRobotState)copy(s); VacuumRobotOperator o = (VacuumRobotOperator)op; vrs.ops = null; // reset ops switch (o.type) { case VacuumRobotOperator.SUCK: { // Get the dirty location in the dirty locations vector int dirt = this.dirt[s.robotLocation]; assert (dirt >= 0); assert (dirt < this.maximumDirtyLocationsCount); // Assure the location is actually dirty assert (s.isDirty(dirt)); // Clean the location vrs.setDirty(dirt, false); // Decrease the count of dirty locations --vrs.remainingDirtyLocationsCount; break; } // All other operators are MOVE default: { // Assure the type of the operator is actually a move if (o.type < 0 || o.type > 3) { System.err.println("Unknown operator type " + o.type); System.exit(1); } // Update the location of the robot vrs.robotLocation += this.map.possibleMoves[o.type].delta; } } vrs.depth++; //dumpState(s); //dumpState(vrs); double p[] = this.computeHD(vrs); vrs.h = p[0]; vrs.d = p[1]; vrs.parent = s; //dumpState(vrs); return vrs; } /** * A VacuumRobot Cleaner World state */ private final class VacuumRobotState implements State { private double h; private double d; //private double hHat; //private double dHat; //private double sseD; //private double sseH; // The location of the robot private int robotLocation; // The depth of the search private int depth; // All the dirty locations private int dirt; // The number of remaining dirty locations private int remainingDirtyLocationsCount; // All the possible operators private VacuumRobotOperator[] ops; private VacuumRobotState parent; /** * A default constructor of the class */ private VacuumRobotState() { this.h = -1; this.d = -1; this.ops = null; this.parent = null; this.remainingDirtyLocationsCount = -1; this.dirt = 0; } /** * A copy constructor * * @param state The state to copy */ private VacuumRobotState(VacuumRobotState state) { this.h = state.h; this.d = state.d; this.depth = state.depth; // Copy the location of the robot this.robotLocation = state.robotLocation; // Copy dirty locations this.dirt = state.dirt; this.remainingDirtyLocationsCount = state.remainingDirtyLocationsCount; // Copy the parent state this.parent = state.parent; } @Override public boolean equals(Object obj) { try { VacuumRobotState otherState = (VacuumRobotState)obj; // First, compare the basic data : The current location and the number of // dirty locations if (this.robotLocation != otherState.robotLocation || this.remainingDirtyLocationsCount != otherState.remainingDirtyLocationsCount) { return false; } // Compare all the dirty locations return this.dirt == otherState.dirt; } catch (ClassCastException e) { return false; } } /** * Whether the i'th location is dirty - perform a bitwise AND with the bit at this location * @param i The index of the location to test * @return True if the location is dirty and False otherwise */ private boolean isDirty(int i) { // TODO: test! return (this.dirt & (1<<i)) != 0; } /** * Set the 'DIRTY' value of the i'th location * @param i The index of the location to set * @param b The value to set: True for 'DIRTY' and False for 'CLEAN' */ private void setDirty(int i, boolean b) { // TODO: test! if (b) { this.dirt |= (1 << i); } else { this.dirt &= ~(1 << i); } } @Override public State getParent() { return this.parent; } /** * An auxiliary function for calculating the h and d values of the current state */ private void computeHD() { double[] p = VacuumRobot.this.computeHD(this); this.h = p[0]; this.d = p[1]; } @Override public double getH() { if (this.h < 0) { this.computeHD(); } return this.h; } @Override public double getD() { if (this.d < 0) { this.computeHD(); } return this.d; } @Override public String dumpState() { return VacuumRobot.this.dumpState(this); } @Override public String dumpStateShort() { return VacuumRobot.this.dumpStateShort(this); } } private final class VacuumRobotOperator implements Operator { // UP = 0, DOWN = 1, LEFT = 2, RIGHT = 3 public static final int SUCK = 4; public static final int NOP = -1; // Initially, the type of the operator is NOP private int type = VacuumRobotOperator.NOP; /** * The constructor of the class: initializes an operator with the given type * * @param type The type of the operator */ private VacuumRobotOperator(int type) { this.type = type; } @Override public boolean equals(Object obj) { try { if (obj == null) { return false; } VacuumRobotOperator o = (VacuumRobotOperator) obj; return type == o.type; } catch (ClassCastException e) { return false; } } @Override public double getCost(State s, State parent) { VacuumRobotState vrs = (VacuumRobotState) s; double cost = 1.0d; if (VacuumRobot.this.heavy) { cost += VacuumRobot.this.heavy(vrs); } return cost; } /** * Finds the reverse operator that applying it will reverse the state caused by this * operator */ @Override public Operator reverse(State state) { return VacuumRobot.this.reverseOperators[this.type]; } } /** * The function performs a dump of the grid map used in the search and puts the positions of the robot on each * of the given states on the map * * @param states The states array (can be null) * @param markAllDirty Whether to mark all the dirty locations (as given in the initial state) or only the actual * dirty * @param obstaclesAndDirtyCountArray The obstacles counter and dirty locations counters (an OUTPUT parameter) * * @return A string representation of the map (with all agents located on it) */ private String _dumpMap(State states[], boolean markAllDirty, int[] obstaclesAndDirtyCountArray) { assert obstaclesAndDirtyCountArray == null || obstaclesAndDirtyCountArray.length == 2; StringBuilder sb = new StringBuilder(); int obstaclesCount = 0; int dirtyCount = 0; // Now, dump the Map with the location of the agent and the goals for (int y = 0; y < this.map.mapHeight; ++y, sb.append('\n')) { // Horizontal for (int x = 0; x < this.map.mapWidth; ++x) { // Get the index of the current location int locationIndex = this.map.index(x, y); PairInt locationPair = this.map.getPosition(locationIndex); // Check for obstacle if (this.map.isBlocked(locationIndex)) { sb.append(' ++obstaclesCount; // Check if the location is dirty } else { boolean dirtyLocation = false; if (this.dirtyLocations.contains(locationPair)) { if (markAllDirty) { sb.append('*'); dirtyLocation = true; } else if (states != null) { int dirtyIndex = this.dirt[locationIndex]; for (State state : states) { if (((VacuumRobotState)state).isDirty(dirtyIndex)) { // Check not last state and robot there if (states != null && ((VacuumRobotState)states[states.length - 1]).robotLocation == locationIndex) { sb.append(VacuumRobot.ROBOT_END_MARKER); } else { sb.append('*'); } dirtyLocation = true; break; } } } } if (dirtyLocation) { ++dirtyCount; } else if (states != null) { boolean robotLocation = false; // Check if the robot is at this location for (int k = 0; k < states.length; ++k) { if (((VacuumRobotState)states[k]).robotLocation == locationIndex) { if (k == 0) { sb.append(VacuumRobot.ROBOT_START_MARKER); } else if (k == states.length - 1) { sb.append(VacuumRobot.ROBOT_END_MARKER); } else { sb.append('X'); } robotLocation = true; break; } } if (!robotLocation) { sb.append("."); } } } } } // Set the output parameter if (obstaclesAndDirtyCountArray != null) { obstaclesAndDirtyCountArray[0] = obstaclesCount; obstaclesAndDirtyCountArray[1] = dirtyCount; } return sb.toString(); } /** * Print the a short representation of the state for debugging reasons * * @param state The state to print */ private String dumpStateShort(VacuumRobotState state) { StringBuilder sb = new StringBuilder(); PairInt robotLocation = this.map.getPosition(state.robotLocation); sb.append("robot location: "); sb.append(robotLocation.toString()); sb.append(", dirty vector: "); sb.append(state.dirt); return sb.toString(); } /** * Print the state for debugging reasons * * @param state The state to print */ private String dumpState(VacuumRobotState state) { StringBuilder sb = new StringBuilder(); int obstaclesCount; sb.append("********************************\n"); sb.append("h: "); sb.append(state.h); sb.append("\n"); sb.append("d: "); sb.append(state.d); sb.append("\n"); int obstaclesAndDirtyCountArray[] = new int[2]; sb.append(this._dumpMap(new State[]{state}, false, obstaclesAndDirtyCountArray)); obstaclesCount = obstaclesAndDirtyCountArray[0]; sb.append("\n"); sb.append(this.dumpStateShort(state)); sb.append("\n"); sb.append("obstacles count: "); sb.append(obstaclesCount); sb.append("\n"); sb.append("dirty locations count: "); sb.append(state.remainingDirtyLocationsCount); sb.append("\n"); sb.append("********************************\n\n"); return sb.toString(); } public String dumpStatesCollection(State[] states) { StringBuilder sb = new StringBuilder(); // All the data regarding a single state refers to the last state of the collection VacuumRobotState lastState = (VacuumRobotState)states[states.length - 1]; sb.append(this._dumpMap(states, true, null)); // Additional newline sb.append('\n'); PairInt agentLocation = this.map.getPosition(lastState.robotLocation); sb.append("Agent location: "); sb.append(agentLocation.toString()); sb.append("\n"); return sb.toString(); } }
package org.duyi.airVis; import com.mongodb.*; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.Point; import com.vividsolutions.jts.operation.valid.IsValidOp; import org.apache.commons.math3.stat.inference.TTest; import org.bson.Document; import org.geotools.feature.FeatureCollection; import org.geotools.feature.FeatureIterator; import org.geotools.geojson.feature.FeatureJSON; import org.geotools.geojson.geom.GeometryJSON; import org.geotools.geometry.jts.JTS; import org.geotools.geometry.jts.JTSFactoryFinder; import org.geotools.referencing.GeodeticCalculator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.opengis.feature.Feature; import org.pujun.correl.Correlation; import org.pujun.interp.InterpMeteo; import org.pujun.interp.InterpPm; import org.springframework.cglib.core.Local; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.PostConstruct; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @Controller @Scope("singleton") public class ClusterController { private static final String NEW_DB_NAME = "airdb"; // private static final String CITY_PATH = "/Users/yidu/dev/airvis/src/main/webapp/maps/china_cities.json"; private static final String CITY_PATH_RELATIVE = "/../../maps/china_cities.json"; private static ArrayList<Geometry> cityArea; private static String[] metoStations; @PostConstruct public void init(){ if(metoStations != null) { return; } FeatureJSON fj = new FeatureJSON(); cityArea = new ArrayList<Geometry>(); FeatureCollection fc = null; try{ fc = fj.readFeatureCollection(this.getClass().getResourceAsStream(CITY_PATH_RELATIVE));//new FileInputStream(new File(CITY_PATH))); }catch(Exception e){ e.printStackTrace(); } FeatureIterator iterator = fc.features(); while( iterator.hasNext() ){ Feature feature = iterator.next(); Geometry value = (Geometry)feature.getDefaultGeometryProperty().getValue(); cityArea.add(value); } metoStations = getNearestStation(cityArea); System.out.println("init complete"); } /** * String[] codes = {"1001A", "1002A"}; * double maxDistance = 200000;// * @return , * * : * [{"cluster":[{"code":"2630A","city":"","latitude":32.5,"station":"","point":"POINT (80.1161 32.5)","longitude":80.1161},{"code":"2631A","city":"","latitude":32.5039,"station":"","point":"POINT (80.0895 32.5039)","longitude":80.0895}],"centerY":33.03017272539136,"centerX":82.55745541810138,"angle":3},{"cluster":[{"code":"1954A","city":"","latitude":44.3336,"station":"","point":"POINT (84.8983 44.3336)","longitude":84.8983}],"centerY":45.446010320866435,"centerX":85.1694460113506,"angle":1},{"cluster":[{"code":"2693A","city":"","latitude":44.9079,"station":"","point":"POINT (82.0485 44.9079)","longitude":82.0485},{"code":"2694A","city":"","latitude":44.8969,"station":"","point":"POINT (82.0806 44.8969)","longitude":82.0806}],"centerY":44.73734089035971,"centerX":82.12236781021181,"angle":1},{"cluster":[{"code":"1956A","city":"","latitude":41.7511,"station":"","point":"POINT (86.1461 41.7511)","longitude":86.1461},{"code":"1957A","city":"","latitude":41.7192,"station":"","point":"POINT (86.2022 41.7192)","longitude":86.2022},{"code":"1958A","city":"","latitude":41.7128,"station":"","point":"POINT (86.2381 41.7128)","longitude":86.2381}],"centerY":39.49807254093696,"centerX":87.47418447395657,"angle":2},{"cluster":[{"code":"2695A","city":"","latitude":41.1636,"station":"","point":"POINT (80.2828 41.1636)","longitude":80.2828},{"code":"2696A","city":"","latitude":41.1933,"station":"","point":"POINT (80.2956 41.1933)","longitude":80.2956}],"centerY":40.961583439271244,"centerX":81.55654857903464,"angle":1},{"cluster":[{"code":"2701A","city":"","latitude":37.1152,"station":"","point":"POINT (79.9485 37.1152)","longitude":79.9485},{"code":"2702A","city":"","latitude":37.1013,"station":"","point":"POINT (79.9117 37.1013)","longitude":79.9117}],"centerY":37.07636221473472,"centerX":80.92700299425222,"angle":3}, { "cluster":[{"code":"2703A","city":"","latitude":43.9404,"station":"","point":"POINT (81.2815 43.9404)","longitude":81.2815},{"code":"2704A","city":"","latitude":43.895,"station":"","point":"POINT (81.2867 43.895)","longitude":81.2867},{"code":"2705A","city":"","latitude":43.941,"station":"","point":"POINT (81.3364 43.941)","longitude":81.3364}],"centerY":43.46412943531677,"centerX":82.11668673611187,"angle":1 } ] .... */ @RequestMapping(value = "cluster.do", method = RequestMethod.POST) public @ResponseBody String makeCluster(String[] codes, double maxDistance, double centerLon, double centerLat) { //input : codeList distance //output : cluster //codeList, //feature,feature,,, MongoClient client = new MongoClient("127.0.0.1"); MongoDatabase db = client.getDatabase(NEW_DB_NAME); MongoCollection coll = db.getCollection("pm_stations"); MongoCursor cur = coll.find().iterator(); JSONObject oneStation; ArrayList<JSONObject> filtered = new ArrayList<JSONObject>(); try { Document d; while(cur.hasNext()){ d = (Document)cur.next(); double lon = d.getDouble("lon"); double lat = d.getDouble("lat"); GeodeticCalculator calc = new GeodeticCalculator(); // mind, this is lon/lat calc.setStartingGeographicPoint(lon, lat); calc.setDestinationGeographicPoint(centerLon, centerLat);//116.4, 40); double distance = calc.getOrthodromicDistance(); if(distance > maxDistance) continue; boolean self = false; for(int i = 0; i < codes.length; i ++) { if (d.get("code").equals(codes[i])) self = true; } if(self) continue; oneStation = new JSONObject(); GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); oneStation.put("city", d.getString("city")); oneStation.put("station", d.getString("name")); oneStation.put("longitude", d.getDouble("lon")); oneStation.put("latitude", d.getDouble("lat")); oneStation.put("code", d.getString("code")); Coordinate coord = new Coordinate(d.getDouble("lon"), d.getDouble("lat"), 0); Point point = geometryFactory.createPoint(coord); oneStation.put("point", point); filtered.add(oneStation); } JSONObject cluster ; JSONArray result = new JSONArray(); for(int i = 0; i < cityArea.size(); i ++){ IsValidOp isValidOp = new IsValidOp(cityArea.get(i)); if(!isValidOp.isValid()) continue; cluster = new JSONObject(); JSONArray oneCluster = new JSONArray(); for(int j = 0; j < filtered.size(); j ++){ if(cityArea.get(i).contains((Geometry)filtered.get(j).get("point"))){ oneCluster.put(filtered.get(j)); } } if(oneCluster.length() != 0) { cluster.put("centerX", cityArea.get(i).getCentroid().getX()); cluster.put("centerY", cityArea.get(i).getCentroid().getY()); cluster.put("id", "cluster"+i); //,22.50, 451 GeodeticCalculator calc = new GeodeticCalculator(); calc.setStartingGeographicPoint(cityArea.get(i).getCentroid().getX(), cityArea.get(i).getCentroid().getY()); calc.setDestinationGeographicPoint(centerLon, cityArea.get(i).getCentroid().getY()); double deltaX = calc.getOrthodromicDistance(); if(cityArea.get(i).getCentroid().getX() < centerLon) deltaX = - deltaX; calc.setStartingGeographicPoint(centerLon, cityArea.get(i).getCentroid().getY()); calc.setDestinationGeographicPoint(centerLon, centerLat); double deltaY = calc.getOrthodromicDistance(); if(cityArea.get(i).getCentroid().getY() < centerLat) deltaY = - deltaY; double angle = Math.toDegrees(Math.atan2(deltaX, deltaY)); if(angle < 0 ) angle += 360; if((angle >= 0 && angle < 22.5) || (angle >= 337.5 && angle <= 360)){ cluster.put("angle", 0); }else if(angle >= 22.5 && angle < 67.5){ cluster.put("angle", 1); }else if(angle >= 67.5 && angle < 112.5){ cluster.put("angle", 2); }else if(angle >= 112.5 && angle < 157.5){ cluster.put("angle", 3); }else if(angle >= 157.5 && angle < 202.5){ cluster.put("angle", 4); }else if(angle >= 202.5 && angle < 247.5){ cluster.put("angle", 5); }else if(angle >= 247.5 && angle < 292.5) { cluster.put("angle", 6); }else if(angle >= 292.5 && angle < 337.5) { cluster.put("angle", 7); } cluster.put("cluster", oneCluster); result.put(cluster); } } client.close(); return result.toString(); }catch(Exception e){ e.printStackTrace(); } return "nothing1"; } @RequestMapping(value = "clusterWithWind.do", method = RequestMethod.POST) public @ResponseBody String clusterWithWind(String[] codes, double maxDistance, double centerLon, double centerLat, String startTime, String endTime) { //input : codeList distance //output : cluster //codeList, //feature,feature,,, MongoClient client = new MongoClient("127.0.0.1"); MongoDatabase db = client.getDatabase(NEW_DB_NAME); MongoCollection coll = db.getCollection("pm_stations"); MongoCursor cur = coll.find().iterator(); JSONObject oneStation; ArrayList<JSONObject> filtered = new ArrayList<JSONObject>(); Calendar cal = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.US); try { Document d; while(cur.hasNext()){ d = (Document)cur.next(); double lon = d.getDouble("lon"); double lat = d.getDouble("lat"); GeodeticCalculator calc = new GeodeticCalculator(); // mind, this is lon/lat calc.setStartingGeographicPoint(lon, lat); calc.setDestinationGeographicPoint(centerLon, centerLat);//116.4, 40); double distance = calc.getOrthodromicDistance(); if(distance > maxDistance) continue; boolean self = false; for(int i = 0; i < codes.length; i ++) { if (d.get("code").equals(codes[i])) self = true; } if(self) continue; oneStation = new JSONObject(); GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); oneStation.put("city", d.getString("city")); oneStation.put("station", d.getString("name")); oneStation.put("longitude", d.getDouble("lon")); oneStation.put("latitude", d.getDouble("lat")); oneStation.put("code", d.getString("code")); Coordinate coord = new Coordinate(d.getDouble("lon"), d.getDouble("lat"), 0); Point point = geometryFactory.createPoint(coord); oneStation.put("point", point); filtered.add(oneStation); } JSONObject cluster ; JSONArray result = new JSONArray(); if(metoStations == null) metoStations = getNearestStation(cityArea); MongoCollection colMeteo = db.getCollection("meteodata_day"); for(int i = 0; i < cityArea.size(); i ++){ IsValidOp isValidOp = new IsValidOp(cityArea.get(i)); if(!isValidOp.isValid()) continue; cluster = new JSONObject(); JSONArray oneCluster = new JSONArray(); for(int j = 0; j < filtered.size(); j ++){ if(cityArea.get(i).contains((Geometry)filtered.get(j).get("point"))){ oneCluster.put(filtered.get(j)); } } if(oneCluster.length() != 0) { cluster.put("centerX", cityArea.get(i).getCentroid().getX()); cluster.put("centerY", cityArea.get(i).getCentroid().getY()); cluster.put("id", "cluster"+i); if(metoStations[i] != null) { List<Document> query = new ArrayList<Document>(); Document match; Document sort = new Document("$sort", new Document("time", 1)); Document group = new Document().append("$group", new Document().append("_id", "$usaf") .append("dir", new Document("$avg", "$dir")) .append("spd", new Document("$avg", "$spd"))); match = new Document("$match", new Document("time", new Document("$gt", df.parse(startTime)).append("$lt", df.parse(endTime))) .append("usaf", new Document("$in", Arrays.asList(Integer.parseInt(metoStations[i]))))); query.add(match); query.add(group); MongoCursor curMeteo = colMeteo.aggregate(query).iterator(); if (curMeteo.hasNext()) { Document dd = (Document) curMeteo.next(); cluster.put("spd", dd.getDouble("spd")); cluster.put("dir", dd.getDouble("dir")); cluster.put("metostation", metoStations[i]); } } //,22.50, 451 GeodeticCalculator calc = new GeodeticCalculator(); calc.setStartingGeographicPoint(cityArea.get(i).getCentroid().getX(), cityArea.get(i).getCentroid().getY()); calc.setDestinationGeographicPoint(centerLon, cityArea.get(i).getCentroid().getY()); double deltaX = calc.getOrthodromicDistance(); if(cityArea.get(i).getCentroid().getX() < centerLon) deltaX = - deltaX; calc.setStartingGeographicPoint(centerLon, cityArea.get(i).getCentroid().getY()); calc.setDestinationGeographicPoint(centerLon, centerLat); double deltaY = calc.getOrthodromicDistance(); if(cityArea.get(i).getCentroid().getY() < centerLat) deltaY = - deltaY; double angle = Math.toDegrees(Math.atan2(deltaX, deltaY)); if(angle < 0 ) angle += 360; // cluster.append("angle", (angle)); // System.out.println((angle)+":"+deltaY+":"+deltaX); if((angle >= 0 && angle < 22.5) || (angle >= 337.5 && angle <= 360)){ cluster.put("angle", 0); }else if(angle >= 22.5 && angle < 67.5){ cluster.put("angle", 1); }else if(angle >= 67.5 && angle < 112.5){ cluster.put("angle", 2); }else if(angle >= 112.5 && angle < 157.5){ cluster.put("angle", 3); }else if(angle >= 157.5 && angle < 202.5){ cluster.put("angle", 4); }else if(angle >= 202.5 && angle < 247.5){ cluster.put("angle", 5); }else if(angle >= 247.5 && angle < 292.5) { cluster.put("angle", 6); }else if(angle >= 292.5 && angle < 337.5) { cluster.put("angle", 7); } cluster.put("cluster", oneCluster); result.put(cluster); } } client.close(); return result.toString(); }catch(Exception e){ e.printStackTrace(); } return "nothing1"; } @RequestMapping(value = "newclusterWithWind.do", method = RequestMethod.POST) public @ResponseBody String clusterWithWind2(String[] codes, double maxDistance, double centerLon, double centerLat, String startTime, String endTime) { //input : codeList distance //output : cluster //codeList, //feature,feature,,, MongoClient client = new MongoClient("127.0.0.1"); MongoDatabase db = client.getDatabase(NEW_DB_NAME); MongoCollection coll = db.getCollection("pm_stations"); MongoCollection collCluster = db.getCollection("cluster"); MongoCursor cur = coll.find().iterator(); JSONObject oneStation; // ArrayList<JSONObject> filtered = new ArrayList<JSONObject>(); Calendar cal = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.US); try { Document d; HashMap<String, JSONObject> clusterResult = new HashMap<String, JSONObject>(); while(cur.hasNext()){ d = (Document)cur.next(); double lon = d.getDouble("lon"); double lat = d.getDouble("lat"); GeodeticCalculator calc = new GeodeticCalculator(); // mind, this is lon/lat calc.setStartingGeographicPoint(lon, lat); calc.setDestinationGeographicPoint(centerLon, centerLat);//116.4, 40); double distance = calc.getOrthodromicDistance(); if(distance > maxDistance) continue; boolean self = false; for(int i = 0; i < codes.length; i ++) { if (d.get("code").equals(codes[i])) self = true; } if(self) continue; oneStation = new JSONObject(); GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); oneStation.put("city", d.getString("city")); oneStation.put("station", d.getString("name")); oneStation.put("longitude", d.getDouble("lon")); oneStation.put("latitude", d.getDouble("lat")); oneStation.put("code", d.getString("code")); Coordinate coord = new Coordinate(d.getDouble("lon"), d.getDouble("lat"), 0); Point point = geometryFactory.createPoint(coord); oneStation.put("point", point); //add clusterid MongoCursor curCluster = collCluster.find(new Document("code",d.getString("code"))).iterator(); // System.out.println(new Document("code",d.getString("code"))); if(!curCluster.hasNext())//TODO continue; String id = ((Document) curCluster.next()).getString("clusterid"); oneStation.put("clusterid", id); if(clusterResult.containsKey(id)){ JSONObject temp = clusterResult.get(id); temp.getJSONArray("cluster").put(oneStation); }else{ JSONObject temp = new JSONObject(); JSONArray tempArray = new JSONArray(); tempArray.put(oneStation); temp.put("cluster", tempArray); clusterResult.put(id, temp); } // filtered.add(oneStation); } JSONObject cluster ; JSONArray result = new JSONArray(); if(metoStations == null) metoStations = getNearestStation(cityArea); MongoCollection colMeteo = db.getCollection("meteodata_day"); MongoCollection clusterMeteo = db.getCollection("clusterMeteo"); Iterator<String> clusterIds = clusterResult.keySet().iterator(); while(clusterIds.hasNext()){ String id = clusterIds.next(); cluster = clusterResult.get(id); JSONArray oneCluster = cluster.getJSONArray("cluster"); double sumX = 0, sumY = 0; for(int j = 0; j < oneCluster.length(); j ++){ JSONObject station = oneCluster.getJSONObject(j); Point p = (Point)station.get("point"); sumX += p.getX(); sumY += p.getY(); } cluster.put("centerX", sumX/oneCluster.length()); cluster.put("centerY", sumY/oneCluster.length()); cluster.put("id", id); String meteoStation = ((Document)clusterMeteo.find(new Document("clusterid", id)).iterator().next()).getInteger("usaf").toString(); // System.out.println("station:"+meteoStation); List<Document> query = new ArrayList<Document>(); Document match; Document sort = new Document("$sort", new Document("time", 1)); Document group = new Document().append("$group", new Document().append("_id", "$usaf") .append("dir", new Document("$avg", "$dir")) .append("spd", new Document("$avg", "$spd"))); match = new Document("$match", new Document("time", new Document("$gt", df.parse(startTime)).append("$lt", df.parse(endTime))) .append("usaf", new Document("$in", Arrays.asList(Integer.parseInt(meteoStation))))); query.add(match); query.add(group); MongoCursor curMeteo = colMeteo.aggregate(query).iterator(); if (curMeteo.hasNext()) { Document dd = (Document) curMeteo.next(); cluster.put("spd", dd.getDouble("spd")); cluster.put("dir", dd.getDouble("dir")); cluster.put("metostation", meteoStation); } //,22.50, 451 GeodeticCalculator calc = new GeodeticCalculator(); calc.setStartingGeographicPoint(oneCluster.getJSONObject(0).getDouble("longitude"), oneCluster.getJSONObject(0).getDouble("latitude")); calc.setDestinationGeographicPoint(centerLon, oneCluster.getJSONObject(0).getDouble("latitude")); double deltaX = calc.getOrthodromicDistance(); if(oneCluster.getJSONObject(0).getDouble("longitude") < centerLon) deltaX = - deltaX; calc.setStartingGeographicPoint(centerLon, oneCluster.getJSONObject(0).getDouble("latitude")); calc.setDestinationGeographicPoint(centerLon, centerLat); double deltaY = calc.getOrthodromicDistance(); if(oneCluster.getJSONObject(0).getDouble("latitude") < centerLat) deltaY = - deltaY; double angle = Math.toDegrees(Math.atan2(deltaX, deltaY)); if(angle < 0 ) angle += 360; // cluster.append("angle", (angle)); // System.out.println((angle)+":"+deltaY+":"+deltaX); if((angle >= 0 && angle < 22.5) || (angle >= 337.5 && angle <= 360)){ cluster.put("angle", 0); }else if(angle >= 22.5 && angle < 67.5){ cluster.put("angle", 1); }else if(angle >= 67.5 && angle < 112.5){ cluster.put("angle", 2); }else if(angle >= 112.5 && angle < 157.5){ cluster.put("angle", 3); }else if(angle >= 157.5 && angle < 202.5){ cluster.put("angle", 4); }else if(angle >= 202.5 && angle < 247.5){ cluster.put("angle", 5); }else if(angle >= 247.5 && angle < 292.5) { cluster.put("angle", 6); }else if(angle >= 292.5 && angle < 337.5) { cluster.put("angle", 7); } result.put(cluster); } client.close(); return result.toString(); }catch(Exception e){ e.printStackTrace(); } return "nothing1"; } /** * ,,city * @param g * @return */ static String[] getNearestStation(ArrayList<Geometry> g){ MongoClient client = new MongoClient(); MongoDatabase db = client.getDatabase(NEW_DB_NAME); MongoCollection coll = db.getCollection("meteo_stations"); MongoCursor cur = coll.find().iterator(); String[] ids = new String[g.size()]; GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); while(cur.hasNext()){ Document d = (Document)cur.next(); for(int i = 0; i < g.size(); i ++){ Coordinate coord = new Coordinate(d.getDouble("lon"), d.getDouble("lat"), 0); Point point = geometryFactory.createPoint(coord); IsValidOp isValidOp = new IsValidOp(g.get(i)); if(!isValidOp.isValid()) continue; if(g.get(i).contains(point)) { ids[i] = d.getInteger("usaf").toString(); break; } } } client.close(); return ids; } /** * * @param wind * @return */ //TODO double calOverAllWindSpeedByTime(double[] wind){ double sum = 0; for(int i = 0; i < wind.length; i ++){ sum += wind[i]; } return sum/ wind.length; } /** * * @param wind * @return */ //TODO double calOverAllWindDirByTime(double[] wind){ double sum = 0; for(int i = 0; i < wind.length; i ++){ sum += wind[i]; } return sum/ wind.length; } /** * codescodesthemeriver * @param codes * @param startTime * @param endTime * @param index index * @return */ @RequestMapping(value = "themeriverdata.do", method = RequestMethod.POST) public @ResponseBody //TODO String themeriverdata(String[] codes, String startTime, String endTime, int index, String cluster) { if(codes == null || codes.length == 0) return ""; JSONArray jsonCluster = null; try{ jsonCluster = new JSONArray(cluster); }catch(JSONException e){ e.printStackTrace(); } MongoClient client = new MongoClient(); MongoDatabase db = client.getDatabase(NEW_DB_NAME); MongoCollection coll = db.getCollection("pmdata_day"); MongoCollection collStation = db.getCollection("pm_stations"); Calendar cal = Calendar.getInstance(); //TODO time zone problem SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.US); Document filter = new Document(); ArrayList<String> codeFilter = new ArrayList<String>(); for(int i = 0; i < codes.length; i ++){ codeFilter.add(codes[i]); } try { filter.append("time", new Document("$gt", df.parse(startTime)).append("$lt", df.parse(endTime))); filter.append("code", new Document().append("$in", codeFilter)); }catch(ParseException pe){ pe.printStackTrace(); } //filter HashMap<String, Double> latMap = new HashMap<String, Double>(); HashMap<String, Double> lonMap = new HashMap<String, Double>(); Document llFilter = new Document(); llFilter.append("code", new Document().append("$in", codeFilter)); MongoCursor curLL = collStation.find(llFilter).iterator(); while(curLL.hasNext()){ Document d = (Document)curLL.next(); latMap.put(d.getString("code"), d.getDouble("lat")); lonMap.put(d.getString("code"), d.getDouble("lon")); } MongoCursor cur = coll.find(filter).sort(new BasicDBObject("code", 1)).sort(new BasicDBObject("time", 1)).iterator(); JSONObject result = new JSONObject(); JSONArray res = new JSONArray(); Document pre = null; while(cur.hasNext()){ Document d = (Document)cur.next(); Document nd = new Document(); if(pre == null) { nd.put("time", d.get("time")); nd.put("pm25", d.get("pm25")); nd.put("code", d.get("code")); nd.put("city", d.get("city")); nd.put("lat", latMap.get(d.get("code"))); nd.put("lon", lonMap.get(d.get("code"))); res.put(nd); pre = d; }else { if (d.get("code") == pre.get("code")) { int interval = (int) (d.getDate("time").getTime() - pre.getDate("time").getTime() / (1000 * 60 * 60)); if (interval == 1) { } else { for (int i = 0; i < interval; i++) { Document nd2 = new Document(); long newDateSeconds = d.getDate("time").getTime() - (interval - i) * 1000 * 60 * 60; Date newDate = new Date(newDateSeconds); nd2.put("time", newDate); nd2.put("pm25", d.get("pm25")); nd2.put("code", d.get("code")); nd2.put("city", d.get("city")); nd2.put("lat", latMap.get(d.get("code"))); nd2.put("lon", lonMap.get(d.get("code"))); res.put(nd2); } } } nd.put("time", d.get("time")); nd.put("pm25", d.get("pm25")); nd.put("code", d.get("code")); nd.put("city", d.get("city")); nd.put("lat", latMap.get(d.get("code"))); nd.put("lon", lonMap.get(d.get("code"))); res.put(nd); pre = d; } } try { result.put("result", res); result.put("index", index); }catch(Exception e){ e.printStackTrace(); } JSONObject oneLagCor; JSONArray lagCor = new JSONArray(); //code,lagcor,result try { for (int i = 0; i < jsonCluster.length(); i++) { JSONObject oneCluster = jsonCluster.getJSONObject(i); JSONArray codeCluster = oneCluster.getJSONArray("cluster"); for(int j = 0; j < codeCluster.length(); j ++){ for(int k = 0; k < codes.length; k ++){ if(!codeCluster.getJSONObject(j).getString("code").equals(codes[k])){ continue; } oneLagCor = new JSONObject(); oneLagCor.put("code", codes[k]); oneLagCor.put("cor", oneCluster.getDouble("correlation")); oneLagCor.put("lag", oneCluster.getInt("lag")); lagCor.put(oneLagCor); } } } result.put("lag", lagCor); }catch(Exception ee){ ee.printStackTrace(); } client.close(); return result.toString(); } /** * ,\ * @param cluster * @param startTime * @param endTime * @return */ private String updateWind(String cluster, String startTime, String endTime){ JSONArray jsonCluster = null; try { SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.US); jsonCluster = new JSONArray(cluster); MongoClient client = new MongoClient("127.0.0.1", 27017); MongoDatabase db = client.getDatabase(NEW_DB_NAME); MongoCollection colMeteo = db.getCollection("meteodata_day"); for(int i = 0; i < jsonCluster.length(); i ++){ JSONObject oneCluster = jsonCluster.getJSONObject(i); if(!oneCluster.has("metostation")) continue; if(oneCluster.get("metostation") != null) { List<Document> query = new ArrayList<Document>(); Document match; Document sort = new Document("$sort", new Document("time", 1)); Document group = new Document().append("$group", new Document().append("_id", "$usaf") .append("dir", new Document("$avg", "$dir")) .append("spd", new Document("$avg", "$spd"))); match = new Document("$match", new Document("time", new Document("$gt", df.parse(startTime)).append("$lt", df.parse(endTime))) .append("usaf", new Document("$in", Arrays.asList(Integer.parseInt(oneCluster.getString("metostation")))))); query.add(match); query.add(group); MongoCursor curMeteo = colMeteo.aggregate(query).iterator(); if (curMeteo.hasNext()) { Document dd = (Document) curMeteo.next(); oneCluster.remove("spd"); oneCluster.remove("dir"); oneCluster.put("spd", dd.getDouble("spd")); oneCluster.put("dir", dd.getDouble("dir")); } } } client.close(); return jsonCluster.toString(); }catch(Exception e){ e.printStackTrace(); return "exception"; } } /** * cluster * cluster(),,() * @param cluster * @param startTime detailBrush * @param endTime detailBrush * @param codes * @return */ @RequestMapping(value = "correlation.do", method = RequestMethod.POST) public @ResponseBody //TODO String correlation(String cluster, String startTime, String endTime, String[] codes) { String clusterAfterUpdateWind = updateWind(cluster, startTime, endTime); try { //clustercode JSONArray jsonCluster = new JSONArray(clusterAfterUpdateWind); MongoClient client = new MongoClient("127.0.0.1", 27017); DB db = client.getDB(NEW_DB_NAME); DBCollection pmCollection = db.getCollection("pm_data"); DBCollection pmStationCollection = db.getCollection("pm_stations"); DBCollection clusterCollection = db.getCollection("cluster"); DBCollection clusterMeteoCollection = db.getCollection("clusterMeteo"); DBCollection meteoStationCollection = db.getCollection("meteo_stations"); DBCollection meteoCollection = db.getCollection("meteo_data"); DBCollection meteoCollectionDaily = db.getCollection("meteodata_day"); //TODO time zone problem SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.US); // df.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT"))); Calendar cal = Calendar.getInstance(); Date thisDate; Date endDate = df.parse(endTime); ArrayList<Double> codeTimeSeries = new ArrayList<Double>(); //code[0] thisDate = df.parse(startTime); cal.setTime(thisDate); BasicDBObject queryCode = new BasicDBObject(); double thisCodePM25, lastCodePM25=0; while(thisDate.before(endDate)) { queryCode.append("time", new Document("$gte", thisDate).append("$lt", new Date(thisDate.getTime()+24*60*60*1000))); queryCode.append("code", codes[0]); DBCursor cur = pmCollection.find(queryCode); if (cur.hasNext()) { //list thisCodePM25 = Double.parseDouble(cur.next().get("pm25").toString()); codeTimeSeries.add(thisCodePM25); lastCodePM25 = thisCodePM25; } else { codeTimeSeries.add(lastCodePM25); } cal.add(Calendar.HOUR, 1); thisDate = cal.getTime(); } double[] codeTimeSeriesDouble = new double[codeTimeSeries.size()]; for (int n = 0; n < codeTimeSeries.size(); n++) { codeTimeSeriesDouble[n] = codeTimeSeries.get(n); } BasicDBObject queryCenterMeteoStation = new BasicDBObject(); queryCenterMeteoStation.append("code", codes[0]);//TODO DBCursor curCenterMeteoStation = pmStationCollection.find(queryCenterMeteoStation); DBObject thisCenterMeteoStation = curCenterMeteoStation.next();//TODO double centerLat = Double.parseDouble(thisCenterMeteoStation.get("lat").toString()); double centerLon = Double.parseDouble(thisCenterMeteoStation.get("lon").toString()); for(int i = 0; i < jsonCluster.length(); i ++){ double clusterDistance, clusterSpd; int addition = 0; String oneCluster = jsonCluster.getJSONObject(i).getJSONArray("cluster").getJSONObject(0).getString("code"); BasicDBObject queryClusterID = new BasicDBObject(); //clusterclusterid queryClusterID.append("code", oneCluster); DBCursor curCluesterID = clusterCollection.find(queryClusterID); String clusterID = curCluesterID.next().get("clusterid").toString(); BasicDBObject queryClusterMeteo = new BasicDBObject(); //clustermeteousaf queryClusterMeteo.append("clusterid",clusterID); DBCursor curClusterMeteo = clusterMeteoCollection.find(queryClusterMeteo); int clusterMeteo = Integer.parseInt(curClusterMeteo.next().get("usaf").toString()); //TODO BasicDBObject queryClusterMeteoData = new BasicDBObject(); //meteospd queryClusterMeteoData.append("usaf",clusterMeteo); queryClusterMeteoData.append("time",new Document("$gt", df.parse(startTime)).append("$lt", df.parse(endTime))); DBCursor curClusterMeteoData = meteoCollectionDaily.find(queryClusterMeteoData); clusterSpd = Double.parseDouble(curClusterMeteoData.next().get("spd").toString()); BasicDBObject queryClusterMeteoStation = new BasicDBObject(); //meteo queryClusterMeteoStation.append("code",oneCluster); DBCursor curClusterMeteoStation = pmStationCollection.find(queryClusterMeteoStation); DBObject thisClusterMeteoStation = curClusterMeteoStation.next(); double clusterLat = Double.parseDouble(thisClusterMeteoStation.get("lat").toString()); double clusterLon = Double.parseDouble(thisClusterMeteoStation.get("lon").toString()); GeodeticCalculator calc = new GeodeticCalculator(); calc.setStartingGeographicPoint(clusterLon, clusterLat); calc.setDestinationGeographicPoint(centerLon, centerLat); clusterDistance = calc.getOrthodromicDistance() / 1609.344; if(clusterSpd != 0 && clusterSpd != -1) { addition = (int) (clusterDistance / clusterSpd); }else{ addition = 24; } ArrayList<Double> clusterTimeSeries = new ArrayList<Double>(); //cluster[0] thisDate = df.parse(startTime); cal.setTime(thisDate); cal.add(Calendar.HOUR, -addition); //clusteraddition thisDate = cal.getTime(); BasicDBObject queryCluster = new BasicDBObject(); double thisClusterPM25, lastClusterPM25 = 0; while(thisDate.before(endDate)) { queryCluster.append("time", new Document("$gte", thisDate).append("$lt", new Date(thisDate.getTime()+24*60*60*1000))); queryCluster.append("code", oneCluster); DBCursor cur = pmCollection.find(queryCluster); if (cur.hasNext()) { //list thisClusterPM25 = Double.parseDouble(cur.next().get("pm25").toString()); clusterTimeSeries.add(thisClusterPM25); lastClusterPM25 = thisClusterPM25; } else { //lastClusterPM25 clusterTimeSeries.add(lastClusterPM25); } cal.add(Calendar.HOUR, 1); thisDate = cal.getTime(); } //ArrayListdouble double[] clusterTimeSeriesDouble = new double[clusterTimeSeries.size()]; for (int m = 0; m < clusterTimeSeries.size(); m++) { clusterTimeSeriesDouble[m] = clusterTimeSeries.get(m); } //[0]lag[1][2]tp Correlation correlation = new Correlation(); double[] lagCorrelation = correlation.getLagResultEarlier(codeTimeSeriesDouble, clusterTimeSeriesDouble); //TODO correlation ((JSONObject) jsonCluster.get(i)).put("lag", addition - lagCorrelation[0]); ((JSONObject) jsonCluster.get(i)).put("correlation", lagCorrelation[1]); ((JSONObject) jsonCluster.get(i)).put("pvalue", lagCorrelation[2]); } client.close(); return jsonCluster.toString(); }catch(JSONException je){ je.printStackTrace(); }catch(ParseException pe){ pe.printStackTrace(); } return "exception"; } /** * cluster ,correlation.do * cluster(),,() * @param cluster * @param startTime detailBrush * @param endTime detailBrush * @param codes * @return */ @RequestMapping(value = "correlation2.do", method = RequestMethod.POST) public @ResponseBody //TODO String correlation2(String cluster, String startTime, String endTime, String[] codes) { String clusterAfterUpdateWind = updateWind(cluster, startTime, endTime); try { //clustercode JSONArray jsonCluster = new JSONArray(clusterAfterUpdateWind); MongoClient client = new MongoClient("127.0.0.1", 27017); DB db = client.getDB(NEW_DB_NAME); DBCollection pmCollection = db.getCollection("pm_data"); DBCollection pmStationCollection = db.getCollection("pm_stations"); DBCollection clusterCollection = db.getCollection("cluster"); DBCollection clusterMeteoCollection = db.getCollection("clusterMeteo"); DBCollection meteoStationCollection = db.getCollection("meteo_stations"); DBCollection meteoCollection = db.getCollection("meteo_data"); DBCollection meteoCollectionDaily = db.getCollection("meteodata_day"); //TODO time zone problem SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.US); // df.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT"))); Calendar cal = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); Date thisDate, endDate; ArrayList<Double> codeTimeSeries = new ArrayList<Double>(); //code[0] thisDate = df.parse(startTime); cal.setTime(thisDate); endDate= df.parse(endTime); BasicDBObject queryCode = new BasicDBObject(); double thisCodePM25, lastCodePM25=0; while(thisDate.before(endDate)) { queryCode.append("time", new Document("$gte", thisDate).append("$lt", new Date(thisDate.getTime()+24*60*60*1000))); queryCode.append("code", codes[0]); DBCursor cur = pmCollection.find(queryCode); if (cur.hasNext()) { //list thisCodePM25 = Double.parseDouble(cur.next().get("pm25").toString()); codeTimeSeries.add(thisCodePM25); lastCodePM25 = thisCodePM25; } else { codeTimeSeries.add(lastCodePM25); } cal.add(Calendar.HOUR, 1); thisDate = cal.getTime(); } double[] codeTimeSeriesDouble = new double[codeTimeSeries.size()]; for (int n = 0; n < codeTimeSeries.size(); n++) { codeTimeSeriesDouble[n] = codeTimeSeries.get(n); } //centerspd BasicDBObject queryCenterPMStation = new BasicDBObject(); queryCenterPMStation.append("code", codes[0]);//TODO DBCursor curCenterPMStation = pmStationCollection.find(queryCenterPMStation); DBObject thisCenterPMStation = curCenterPMStation.next();//TODO double centerLat = Double.parseDouble(thisCenterPMStation.get("lat").toString()); double centerLon = Double.parseDouble(thisCenterPMStation.get("lon").toString()); //clusterclusterid DBCursor curCenterCluesterID = clusterCollection.find(queryCenterPMStation); String centerClusterID = curCenterCluesterID.next().get("clusterid").toString(); //clustermeteousaf BasicDBObject queryCenterClusterMeteo = new BasicDBObject(); queryCenterClusterMeteo.append("clusterid",centerClusterID); DBCursor curCenterClusterMeteo = clusterMeteoCollection.find(queryCenterClusterMeteo); int centerClusterMeteo = Integer.parseInt(curCenterClusterMeteo.next().get("usaf").toString()); //meteospd BasicDBObject queryCenterClusterMeteoData = new BasicDBObject(); queryCenterClusterMeteoData.append("usaf",centerClusterMeteo); queryCenterClusterMeteoData.append("time",new Document("$gt", df.parse(startTime)).append("$lt", df.parse(endTime))); DBCursor curCenterClusterMeteoData = meteoCollectionDaily.find(queryCenterClusterMeteoData); double centerSpd = Double.parseDouble(curCenterClusterMeteoData.next().get("spd").toString()); for(int i = 0; i < jsonCluster.length(); i ++){ double clusterDistance, clusterSpd; int addition = 0; int additionLater = 0; String oneCluster = jsonCluster.getJSONObject(i).getJSONArray("cluster").getJSONObject(0).getString("code"); BasicDBObject queryClusterID = new BasicDBObject(); //clusterclusterid queryClusterID.append("code", oneCluster); DBCursor curCluesterID = clusterCollection.find(queryClusterID); String clusterID = curCluesterID.next().get("clusterid").toString(); BasicDBObject queryClusterMeteo = new BasicDBObject(); //clustermeteousaf queryClusterMeteo.append("clusterid",clusterID); DBCursor curClusterMeteo = clusterMeteoCollection.find(queryClusterMeteo); int clusterMeteo = Integer.parseInt(curClusterMeteo.next().get("usaf").toString()); //TODO BasicDBObject queryClusterMeteoData = new BasicDBObject(); //meteospd queryClusterMeteoData.append("usaf",clusterMeteo); queryClusterMeteoData.append("time",new Document("$gt", df.parse(startTime)).append("$lt", df.parse(endTime))); DBCursor curClusterMeteoData = meteoCollectionDaily.find(queryClusterMeteoData); clusterSpd = Double.parseDouble(curClusterMeteoData.next().get("spd").toString()); BasicDBObject queryClusterMeteoStation = new BasicDBObject(); //meteo queryClusterMeteoStation.append("code",oneCluster); DBCursor curClusterMeteoStation = pmStationCollection.find(queryClusterMeteoStation); DBObject thisClusterMeteoStation = curClusterMeteoStation.next(); double clusterLat = Double.parseDouble(thisClusterMeteoStation.get("lat").toString()); double clusterLon = Double.parseDouble(thisClusterMeteoStation.get("lon").toString()); GeodeticCalculator calc = new GeodeticCalculator(); calc.setStartingGeographicPoint(clusterLon, clusterLat); calc.setDestinationGeographicPoint(centerLon, centerLat); clusterDistance = calc.getOrthodromicDistance() / 1609.344; if(clusterSpd != 0 && clusterSpd != -1) { addition = (int) (clusterDistance / clusterSpd); }else{ addition = 24; } if(centerSpd != 0 && centerSpd != -1) { additionLater = (int) (clusterDistance / centerSpd); }else{ additionLater = 24; } ArrayList<Double> clusterTimeSeries = new ArrayList<Double>(); //cluster[0] cal.setTime(df.parse(startTime)); cal.add(Calendar.HOUR, -addition); //clusteraddition thisDate = cal.getTime(); cal2.setTime(df.parse(endTime)); cal2.add(Calendar.HOUR, additionLater); //cluster48 endDate = cal2.getTime(); BasicDBObject queryCluster = new BasicDBObject(); double thisClusterPM25, lastClusterPM25 = 0; while(thisDate.before(endDate)) { queryCluster.append("time", new Document("$gte", thisDate).append("$lt", new Date(thisDate.getTime()+24*60*60*1000))); queryCluster.append("code", oneCluster); DBCursor cur = pmCollection.find(queryCluster); if (cur.hasNext()) { //list thisClusterPM25 = Double.parseDouble(cur.next().get("pm25").toString()); clusterTimeSeries.add(thisClusterPM25); lastClusterPM25 = thisClusterPM25; } else { //lastClusterPM25 clusterTimeSeries.add(lastClusterPM25); } cal.add(Calendar.HOUR, 1); thisDate = cal.getTime(); } //ArrayListdouble double[] clusterTimeSeriesDouble = new double[clusterTimeSeries.size()]; for (int m = 0; m < clusterTimeSeries.size(); m++) { clusterTimeSeriesDouble[m] = clusterTimeSeries.get(m); } //[0]lag[1][2]tp Correlation correlation = new Correlation(); double[] lagCorrelation = correlation.getLagResultEarlier(codeTimeSeriesDouble, clusterTimeSeriesDouble); //TODO correlation ((JSONObject) jsonCluster.get(i)).put("lag", addition - lagCorrelation[0]); ((JSONObject) jsonCluster.get(i)).put("correlation", lagCorrelation[1]); ((JSONObject) jsonCluster.get(i)).put("pvalue", lagCorrelation[2]); } client.close(); return jsonCluster.toString(); }catch(JSONException je){ je.printStackTrace(); }catch(ParseException pe){ pe.printStackTrace(); } return "exception"; } }
package org.geoserver.shell; import it.geosolutions.geoserver.rest.HTTPUtils; import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder; import org.jdom.Element; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.shell.core.CommandMarker; import org.springframework.shell.core.annotation.CliCommand; import org.springframework.shell.core.annotation.CliOption; import org.springframework.shell.support.util.OsUtils; import org.springframework.stereotype.Component; import java.util.List; @Component public class AboutCommands implements CommandMarker { @Autowired private Geoserver geoserver; @CliCommand(value = "version list", help = "Get versions.") public String versionList() throws Exception { String TAB = " "; String xml = HTTPUtils.get(geoserver.getUrl() + "/rest/about/versions.xml", geoserver.getUser(), geoserver.getPassword()); StringBuilder builder = new StringBuilder(); Element root = JDOMBuilder.buildElement(xml); List<Element> resources = root.getChildren("resource"); for(Element resource : resources) { String name = resource.getAttributeValue("name"); String buildTime = resource.getChildText("Build-Timestamp"); String gitRevision = resource.getChildText("Git-Revision"); String version = resource.getChildText("Version"); builder.append(name).append(OsUtils.LINE_SEPARATOR); builder.append(TAB).append("Version: ").append(version).append(OsUtils.LINE_SEPARATOR); builder.append(TAB).append("Build Time: ").append(buildTime).append(OsUtils.LINE_SEPARATOR); builder.append(TAB).append("Git Revision: ").append(gitRevision).append(OsUtils.LINE_SEPARATOR); builder.append(OsUtils.LINE_SEPARATOR); } return builder.toString(); } @CliCommand(value = "manifest list", help = "List manifest.") public String manifestList() throws Exception { String xml = HTTPUtils.get(geoserver.getUrl() + "/rest/about/manifests.xml", geoserver.getUser(), geoserver.getPassword()); StringBuilder builder = new StringBuilder(); Element root = JDOMBuilder.buildElement(xml); List<Element> resources = root.getChildren("resource"); for(Element resource : resources) { String name = resource.getAttributeValue("name"); builder.append(name).append(OsUtils.LINE_SEPARATOR); } return builder.toString(); } @CliCommand(value = "manifest get", help = "Get a manifest.") public String manifestGet( @CliOption(key = "name", mandatory = true, help = "The name") String name ) throws Exception { String TAB = " "; String xml = HTTPUtils.get(geoserver.getUrl() + "/rest/about/manifests.xml", geoserver.getUser(), geoserver.getPassword()); StringBuilder builder = new StringBuilder(); Element root = JDOMBuilder.buildElement(xml); List<Element> resources = root.getChildren("resource"); for(Element resource : resources) { String n = resource.getAttributeValue("name"); if (name.equalsIgnoreCase(n)) { builder.append(name).append(OsUtils.LINE_SEPARATOR); List<Element> children = resource.getChildren(); for(Element child : children) { builder.append(TAB).append(child.getName()).append(": ").append(child.getTextTrim()).append(OsUtils.LINE_SEPARATOR); } } } return builder.toString(); } }
package org.iq80.leveldb.impl; import com.google.common.base.Function; import com.google.common.base.Preconditions; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import static com.google.common.base.Charsets.UTF_8; import static org.iq80.leveldb.util.SizeOf.SIZE_OF_LONG; public class InternalKey { private final ChannelBuffer userKey; private final long sequenceNumber; private final ValueType valueType; public InternalKey(ChannelBuffer userKey, long sequenceNumber, ValueType valueType) { Preconditions.checkNotNull(userKey, "userKey is null"); Preconditions.checkArgument(sequenceNumber >= 0, "sequenceNumber is negative"); Preconditions.checkNotNull(valueType, "valueType is null"); this.userKey = userKey.duplicate(); this.sequenceNumber = sequenceNumber; this.valueType = valueType; } public InternalKey(ChannelBuffer data) { Preconditions.checkNotNull(data, "data is null"); if (data.readableBytes() < SIZE_OF_LONG) { Preconditions.checkArgument(data.readableBytes() >= SIZE_OF_LONG, "data must be at least %s bytes", SIZE_OF_LONG); } this.userKey = getUserKey(data); this.sequenceNumber = getSequenceNumber(data); this.valueType = getValueType(data); } public ChannelBuffer getUserKey() { return userKey.duplicate(); } public long getSequenceNumber() { return sequenceNumber; } public ValueType getValueType() { return valueType; } public ChannelBuffer encode() { ChannelBuffer buffer = ChannelBuffers.buffer(userKey.readableBytes() + SIZE_OF_LONG); buffer.writeBytes(userKey.slice()); buffer.writeLong(SequenceNumber.packSequenceAndValueType(sequenceNumber, valueType)); return buffer; } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("InternalKey"); sb.append("{key=").append(getUserKey().toString(UTF_8)); // todo don't print the real value sb.append(", sequenceNumber=").append(getSequenceNumber()); sb.append(", valueType=").append(getValueType()); sb.append('}'); return sb.toString(); } // todo find new home for these public static final Function<InternalKey, ChannelBuffer> INTERNAL_KEY_TO_CHANNEL_BUFFER = new InternalKeyToChannelBufferFunction(); public static final Function<ChannelBuffer, InternalKey> CHANNEL_BUFFER_TO_INTERNAL_KEY = new ChannelBufferToInternalKeyFunction(); public static final Function<InternalKey, ChannelBuffer> INTERNAL_KEY_TO_USER_KEY = new InternalKeyToUserKeyFunction(); public static Function<ChannelBuffer, InternalKey> createUserKeyToInternalKeyFunction(final long sequenceNumber) { return new UserKeyInternalKeyFunction(sequenceNumber); } private static class InternalKeyToChannelBufferFunction implements Function<InternalKey, ChannelBuffer> { @Override public ChannelBuffer apply(InternalKey internalKey) { return internalKey.encode(); } } private static class InternalKeyToUserKeyFunction implements Function<InternalKey, ChannelBuffer> { @Override public ChannelBuffer apply(InternalKey internalKey) { return internalKey.getUserKey(); } } private static class ChannelBufferToInternalKeyFunction implements Function<ChannelBuffer, InternalKey> { @Override public InternalKey apply(ChannelBuffer channelBuffer) { return new InternalKey(channelBuffer); } } private static class UserKeyInternalKeyFunction implements Function<ChannelBuffer, InternalKey> { private final long sequenceNumber; public UserKeyInternalKeyFunction(long sequenceNumber) { this.sequenceNumber = sequenceNumber; } @Override public InternalKey apply(ChannelBuffer channelBuffer) { return new InternalKey(channelBuffer, sequenceNumber, ValueType.VALUE); } } private static ChannelBuffer getUserKey(ChannelBuffer data) { ChannelBuffer buffer = data.duplicate(); buffer.writerIndex(data.readableBytes() - SIZE_OF_LONG); return buffer; } private static long getSequenceNumber(ChannelBuffer data) { return SequenceNumber.unpackSequenceNumber(data.getLong(data.readableBytes() - SIZE_OF_LONG)); } private static ValueType getValueType(ChannelBuffer data) { return SequenceNumber.unpackValueType(data.getLong(data.readableBytes() - SIZE_OF_LONG)); } }
package org.jfree.chart.plot; import java.awt.AlphaComposite; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Composite; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeMap; import org.jfree.chart.LegendItemCollection; import org.jfree.chart.annotations.Annotation; import org.jfree.chart.annotations.CategoryAnnotation; import org.jfree.chart.axis.Axis; import org.jfree.chart.axis.AxisCollection; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.AxisSpace; import org.jfree.chart.axis.AxisState; import org.jfree.chart.axis.CategoryAnchor; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.TickType; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.axis.ValueTick; import org.jfree.chart.ui.Layer; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.RectangleInsets; import org.jfree.chart.util.ObjectList; import org.jfree.chart.util.ObjectUtilities; import org.jfree.chart.util.PaintUtilities; import org.jfree.chart.util.PublicCloneable; import org.jfree.chart.util.ShapeUtilities; import org.jfree.chart.util.SortOrder; import org.jfree.chart.event.AnnotationChangeEvent; import org.jfree.chart.event.AnnotationChangeListener; import org.jfree.chart.event.ChartChangeEventType; import org.jfree.chart.event.PlotChangeEvent; import org.jfree.chart.event.RendererChangeEvent; import org.jfree.chart.event.RendererChangeListener; import org.jfree.chart.renderer.category.AbstractCategoryItemRenderer; import org.jfree.chart.renderer.category.CategoryItemRenderer; import org.jfree.chart.renderer.category.CategoryItemRendererState; import org.jfree.chart.util.ResourceBundleWrapper; import org.jfree.chart.util.SerialUtilities; import org.jfree.chart.util.ShadowGenerator; import org.jfree.data.Range; import org.jfree.data.category.CategoryDataset; import org.jfree.data.general.Dataset; import org.jfree.data.general.DatasetChangeEvent; import org.jfree.data.general.DatasetUtilities; /** * A general plotting class that uses data from a {@link CategoryDataset} and * renders each data item using a {@link CategoryItemRenderer}. */ public class CategoryPlot extends Plot implements ValueAxisPlot, Pannable, Zoomable, AnnotationChangeListener, RendererChangeListener, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -3537691700434728188L; /** * The default visibility of the grid lines plotted against the domain * axis. */ public static final boolean DEFAULT_DOMAIN_GRIDLINES_VISIBLE = false; /** * The default visibility of the grid lines plotted against the range * axis. */ public static final boolean DEFAULT_RANGE_GRIDLINES_VISIBLE = true; /** The default grid line stroke. */ public static final Stroke DEFAULT_GRIDLINE_STROKE = new BasicStroke(0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0.0f, new float[] {2.0f, 2.0f}, 0.0f); /** The default grid line paint. */ public static final Paint DEFAULT_GRIDLINE_PAINT = Color.LIGHT_GRAY; /** The default value label font. */ public static final Font DEFAULT_VALUE_LABEL_FONT = new Font("SansSerif", Font.PLAIN, 10); /** * The default crosshair visibility. * * @since 1.0.5 */ public static final boolean DEFAULT_CROSSHAIR_VISIBLE = false; /** * The default crosshair stroke. * * @since 1.0.5 */ public static final Stroke DEFAULT_CROSSHAIR_STROKE = DEFAULT_GRIDLINE_STROKE; /** * The default crosshair paint. * * @since 1.0.5 */ public static final Paint DEFAULT_CROSSHAIR_PAINT = Color.BLUE; /** The resourceBundle for the localization. */ protected static ResourceBundle localizationResources = ResourceBundleWrapper.getBundle( "org.jfree.chart.plot.LocalizationBundle"); /** The plot orientation. */ private PlotOrientation orientation; /** The offset between the data area and the axes. */ private RectangleInsets axisOffset; /** Storage for the domain axes. */ private ObjectList<CategoryAxis> domainAxes; /** Storage for the domain axis locations. */ private ObjectList<AxisLocation> domainAxisLocations; /** * A flag that controls whether or not the shared domain axis is drawn * (only relevant when the plot is being used as a subplot). */ private boolean drawSharedDomainAxis; /** Storage for the range axes. */ private ObjectList<ValueAxis> rangeAxes; /** Storage for the range axis locations. */ private ObjectList<AxisLocation> rangeAxisLocations; /** Storage for the datasets. */ private ObjectList<CategoryDataset> datasets; /** Storage for keys that map datasets to domain axes. */ private TreeMap<Integer, List<Integer>> datasetToDomainAxesMap; /** Storage for keys that map datasets to range axes. */ private TreeMap<Integer, List<Integer>> datasetToRangeAxesMap; /** Storage for the renderers. */ private ObjectList<CategoryItemRenderer> renderers; /** The dataset rendering order. */ private DatasetRenderingOrder renderingOrder = DatasetRenderingOrder.REVERSE; /** * Controls the order in which the columns are traversed when rendering the * data items. */ private SortOrder columnRenderingOrder = SortOrder.ASCENDING; /** * Controls the order in which the rows are traversed when rendering the * data items. */ private SortOrder rowRenderingOrder = SortOrder.ASCENDING; /** * A flag that controls whether the grid-lines for the domain axis are * visible. */ private boolean domainGridlinesVisible; /** The position of the domain gridlines relative to the category. */ private CategoryAnchor domainGridlinePosition; /** The stroke used to draw the domain grid-lines. */ private transient Stroke domainGridlineStroke; /** The paint used to draw the domain grid-lines. */ private transient Paint domainGridlinePaint; /** * A flag that controls whether or not the zero baseline against the range * axis is visible. * * @since 1.0.13 */ private boolean rangeZeroBaselineVisible; /** * The stroke used for the zero baseline against the range axis. * * @since 1.0.13 */ private transient Stroke rangeZeroBaselineStroke; /** * The paint used for the zero baseline against the range axis. * * @since 1.0.13 */ private transient Paint rangeZeroBaselinePaint; /** * A flag that controls whether the grid-lines for the range axis are * visible. */ private boolean rangeGridlinesVisible; /** The stroke used to draw the range axis grid-lines. */ private transient Stroke rangeGridlineStroke; /** The paint used to draw the range axis grid-lines. */ private transient Paint rangeGridlinePaint; /** * A flag that controls whether or not gridlines are shown for the minor * tick values on the primary range axis. * * @since 1.0.13 */ private boolean rangeMinorGridlinesVisible; /** * The stroke used to draw the range minor grid-lines. * * @since 1.0.13 */ private transient Stroke rangeMinorGridlineStroke; /** * The paint used to draw the range minor grid-lines. * * @since 1.0.13 */ private transient Paint rangeMinorGridlinePaint; /** The anchor value. */ private double anchorValue; /** * The index for the dataset that the crosshairs are linked to (this * determines which axes the crosshairs are plotted against). * * @since 1.0.11 */ private int crosshairDatasetIndex; /** * A flag that controls the visibility of the domain crosshair. * * @since 1.0.11 */ private boolean domainCrosshairVisible; /** * The row key for the crosshair point. * * @since 1.0.11 */ private Comparable domainCrosshairRowKey; /** * The column key for the crosshair point. * * @since 1.0.11 */ private Comparable domainCrosshairColumnKey; /** * The stroke used to draw the domain crosshair if it is visible. * * @since 1.0.11 */ private transient Stroke domainCrosshairStroke; /** * The paint used to draw the domain crosshair if it is visible. * * @since 1.0.11 */ private transient Paint domainCrosshairPaint; /** A flag that controls whether or not a range crosshair is drawn. */ private boolean rangeCrosshairVisible; /** The range crosshair value. */ private double rangeCrosshairValue; /** The pen/brush used to draw the crosshair (if any). */ private transient Stroke rangeCrosshairStroke; /** The color used to draw the crosshair (if any). */ private transient Paint rangeCrosshairPaint; /** * A flag that controls whether or not the crosshair locks onto actual * data points. */ private boolean rangeCrosshairLockedOnData = true; /** A map containing lists of markers for the domain axes. */ private Map<Integer, Collection<Marker>> foregroundDomainMarkers; /** A map containing lists of markers for the domain axes. */ private Map<Integer, Collection<Marker>> backgroundDomainMarkers; /** A map containing lists of markers for the range axes. */ private Map<Integer, Collection<Marker>> foregroundRangeMarkers; /** A map containing lists of markers for the range axes. */ private Map<Integer, Collection<Marker>> backgroundRangeMarkers; /** * A (possibly empty) list of annotations for the plot. The list should * be initialised in the constructor and never allowed to be * <code>null</code>. */ private List<CategoryAnnotation> annotations; /** * The weight for the plot (only relevant when the plot is used as a subplot * within a combined plot). */ private int weight; /** The fixed space for the domain axis. */ private AxisSpace fixedDomainAxisSpace; /** The fixed space for the range axis. */ private AxisSpace fixedRangeAxisSpace; /** * An optional collection of legend items that can be returned by the * getLegendItems() method. */ private LegendItemCollection fixedLegendItems; /** * A flag that controls whether or not panning is enabled for the * range axis/axes. * * @since 1.0.13 */ private boolean rangePannable; /** * The shadow generator for the plot (<code>null</code> permitted). * * @since 1.0.14 */ private ShadowGenerator shadowGenerator; /** * Default constructor. */ public CategoryPlot() { this(null, null, null, null); } /** * Creates a new plot. * * @param dataset the dataset (<code>null</code> permitted). * @param domainAxis the domain axis (<code>null</code> permitted). * @param rangeAxis the range axis (<code>null</code> permitted). * @param renderer the item renderer (<code>null</code> permitted). * */ public CategoryPlot(CategoryDataset dataset, CategoryAxis domainAxis, ValueAxis rangeAxis, CategoryItemRenderer renderer) { super(); this.orientation = PlotOrientation.VERTICAL; // allocate storage for dataset, axes and renderers this.domainAxes = new ObjectList<CategoryAxis>(); this.domainAxisLocations = new ObjectList<AxisLocation>(); this.rangeAxes = new ObjectList<ValueAxis>(); this.rangeAxisLocations = new ObjectList<AxisLocation>(); this.datasetToDomainAxesMap = new TreeMap<Integer, List<Integer>>(); this.datasetToRangeAxesMap = new TreeMap<Integer, List<Integer>>(); this.renderers = new ObjectList<CategoryItemRenderer>(); this.datasets = new ObjectList<CategoryDataset>(); this.datasets.set(0, dataset); if (dataset != null) { dataset.addChangeListener(this); } this.axisOffset = RectangleInsets.ZERO_INSETS; setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT, false); setRangeAxisLocation(AxisLocation.TOP_OR_LEFT, false); this.renderers.set(0, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } this.domainAxes.set(0, domainAxis); this.mapDatasetToDomainAxis(0, 0); if (domainAxis != null) { domainAxis.setPlot(this); domainAxis.addChangeListener(this); } this.drawSharedDomainAxis = false; this.rangeAxes.set(0, rangeAxis); this.mapDatasetToRangeAxis(0, 0); if (rangeAxis != null) { rangeAxis.setPlot(this); rangeAxis.addChangeListener(this); } configureDomainAxes(); configureRangeAxes(); this.domainGridlinesVisible = DEFAULT_DOMAIN_GRIDLINES_VISIBLE; this.domainGridlinePosition = CategoryAnchor.MIDDLE; this.domainGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.domainGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.rangeZeroBaselineVisible = false; this.rangeZeroBaselinePaint = Color.BLACK; this.rangeZeroBaselineStroke = new BasicStroke(0.5f); this.rangeGridlinesVisible = DEFAULT_RANGE_GRIDLINES_VISIBLE; this.rangeGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.rangeGridlinePaint = DEFAULT_GRIDLINE_PAINT; this.rangeMinorGridlinesVisible = false; this.rangeMinorGridlineStroke = DEFAULT_GRIDLINE_STROKE; this.rangeMinorGridlinePaint = Color.WHITE; this.foregroundDomainMarkers = new HashMap<Integer, Collection<Marker>>(); this.backgroundDomainMarkers = new HashMap<Integer, Collection<Marker>>(); this.foregroundRangeMarkers = new HashMap<Integer, Collection<Marker>>(); this.backgroundRangeMarkers = new HashMap<Integer, Collection<Marker>>(); this.anchorValue = 0.0; this.domainCrosshairVisible = false; this.domainCrosshairStroke = DEFAULT_CROSSHAIR_STROKE; this.domainCrosshairPaint = DEFAULT_CROSSHAIR_PAINT; this.rangeCrosshairVisible = DEFAULT_CROSSHAIR_VISIBLE; this.rangeCrosshairValue = 0.0; this.rangeCrosshairStroke = DEFAULT_CROSSHAIR_STROKE; this.rangeCrosshairPaint = DEFAULT_CROSSHAIR_PAINT; this.annotations = new java.util.ArrayList<CategoryAnnotation>(); this.rangePannable = false; this.shadowGenerator = null; } /** * Returns a string describing the type of plot. * * @return The type. */ @Override public String getPlotType() { return localizationResources.getString("Category_Plot"); } /** * Returns the orientation of the plot. * * @return The orientation of the plot (never <code>null</code>). * * @see #setOrientation(PlotOrientation) */ @Override public PlotOrientation getOrientation() { return this.orientation; } /** * Sets the orientation for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param orientation the orientation (<code>null</code> not permitted). * * @see #getOrientation() */ public void setOrientation(PlotOrientation orientation) { if (orientation == null) { throw new IllegalArgumentException("Null 'orientation' argument."); } this.orientation = orientation; fireChangeEvent(); } /** * Returns the axis offset. * * @return The axis offset (never <code>null</code>). * * @see #setAxisOffset(RectangleInsets) */ public RectangleInsets getAxisOffset() { return this.axisOffset; } /** * Sets the axis offsets (gap between the data area and the axes) and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param offset the offset (<code>null</code> not permitted). * * @see #getAxisOffset() */ public void setAxisOffset(RectangleInsets offset) { if (offset == null) { throw new IllegalArgumentException("Null 'offset' argument."); } this.axisOffset = offset; fireChangeEvent(); } /** * Returns the domain axis for the plot. If the domain axis for this plot * is <code>null</code>, then the method will return the parent plot's * domain axis (if there is a parent plot). * * @return The domain axis (<code>null</code> permitted). * * @see #setDomainAxis(CategoryAxis) */ public CategoryAxis getDomainAxis() { return getDomainAxis(0); } /** * Returns a domain axis. * * @param index the axis index. * * @return The axis (<code>null</code> possible). * * @see #setDomainAxis(int, CategoryAxis) */ public CategoryAxis getDomainAxis(int index) { CategoryAxis result = null; if (index < this.domainAxes.size()) { result = this.domainAxes.get(index); } if (result == null) { Plot parent = getParent(); if (parent instanceof CategoryPlot) { CategoryPlot cp = (CategoryPlot) parent; result = cp.getDomainAxis(index); } } return result; } /** * Sets the domain axis for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param axis the axis (<code>null</code> permitted). * * @see #getDomainAxis() */ public void setDomainAxis(CategoryAxis axis) { setDomainAxis(0, axis); } /** * Sets a domain axis and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param index the axis index. * @param axis the axis (<code>null</code> permitted). * * @see #getDomainAxis(int) */ public void setDomainAxis(int index, CategoryAxis axis) { setDomainAxis(index, axis, true); } /** * Sets a domain axis and, if requested, sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the axis index. * @param axis the axis (<code>null</code> permitted). * @param notify notify listeners? */ public void setDomainAxis(int index, CategoryAxis axis, boolean notify) { CategoryAxis existing = this.domainAxes.get(index); if (existing != null) { existing.removeChangeListener(this); } if (axis != null) { axis.setPlot(this); } this.domainAxes.set(index, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Sets the domain axes for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axes the axes (<code>null</code> not permitted). * * @see #setRangeAxes(ValueAxis[]) */ public void setDomainAxes(CategoryAxis[] axes) { for (int i = 0; i < axes.length; i++) { setDomainAxis(i, axes[i], false); } fireChangeEvent(); } /** * Returns the index of the specified axis, or <code>-1</code> if the axis * is not assigned to the plot. * * @param axis the axis (<code>null</code> not permitted). * * @return The axis index. * * @see #getDomainAxis(int) * @see #getRangeAxisIndex(ValueAxis) * * @since 1.0.3 */ public int getDomainAxisIndex(CategoryAxis axis) { if (axis == null) { throw new IllegalArgumentException("Null 'axis' argument."); } return this.domainAxes.indexOf(axis); } /** * Returns the domain axis location for the primary domain axis. * * @return The location (never <code>null</code>). * * @see #getRangeAxisLocation() */ public AxisLocation getDomainAxisLocation() { return getDomainAxisLocation(0); } /** * Returns the location for a domain axis. * * @param index the axis index. * * @return The location. * * @see #setDomainAxisLocation(int, AxisLocation) */ public AxisLocation getDomainAxisLocation(int index) { AxisLocation result = null; if (index < this.domainAxisLocations.size()) { result = this.domainAxisLocations.get(index); } if (result == null) { result = AxisLocation.getOpposite(getDomainAxisLocation(0)); } return result; } /** * Sets the location of the domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param location the axis location (<code>null</code> not permitted). * * @see #getDomainAxisLocation() * @see #setDomainAxisLocation(int, AxisLocation) */ public void setDomainAxisLocation(AxisLocation location) { // delegate... setDomainAxisLocation(0, location, true); } /** * Sets the location of the domain axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the axis location (<code>null</code> not permitted). * @param notify a flag that controls whether listeners are notified. */ public void setDomainAxisLocation(AxisLocation location, boolean notify) { // delegate... setDomainAxisLocation(0, location, notify); } /** * Sets the location for a domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location. * * @see #getDomainAxisLocation(int) * @see #setRangeAxisLocation(int, AxisLocation) */ public void setDomainAxisLocation(int index, AxisLocation location) { // delegate... setDomainAxisLocation(index, location, true); } /** * Sets the location for a domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location. * @param notify notify listeners? * * @since 1.0.5 * * @see #getDomainAxisLocation(int) * @see #setRangeAxisLocation(int, AxisLocation, boolean) */ public void setDomainAxisLocation(int index, AxisLocation location, boolean notify) { if (index == 0 && location == null) { throw new IllegalArgumentException( "Null 'location' for index 0 not permitted."); } this.domainAxisLocations.set(index, location); if (notify) { fireChangeEvent(); } } /** * Returns the domain axis edge. This is derived from the axis location * and the plot orientation. * * @return The edge (never <code>null</code>). */ public RectangleEdge getDomainAxisEdge() { return getDomainAxisEdge(0); } /** * Returns the edge for a domain axis. * * @param index the axis index. * * @return The edge (never <code>null</code>). */ public RectangleEdge getDomainAxisEdge(int index) { RectangleEdge result; AxisLocation location = getDomainAxisLocation(index); if (location != null) { result = Plot.resolveDomainAxisLocation(location, this.orientation); } else { result = RectangleEdge.opposite(getDomainAxisEdge(0)); } return result; } /** * Returns the number of domain axes. * * @return The axis count. */ public int getDomainAxisCount() { return this.domainAxes.size(); } /** * Clears the domain axes from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. */ public void clearDomainAxes() { for (int i = 0; i < this.domainAxes.size(); i++) { CategoryAxis axis = this.domainAxes.get(i); if (axis != null) { axis.removeChangeListener(this); } } this.domainAxes.clear(); fireChangeEvent(); } /** * Configures the domain axes. */ public void configureDomainAxes() { for (int i = 0; i < this.domainAxes.size(); i++) { CategoryAxis axis = this.domainAxes.get(i); if (axis != null) { axis.configure(); } } } /** * Returns the range axis for the plot. If the range axis for this plot is * null, then the method will return the parent plot's range axis (if there * is a parent plot). * * @return The range axis (possibly <code>null</code>). */ public ValueAxis getRangeAxis() { return getRangeAxis(0); } /** * Returns a range axis. * * @param index the axis index. * * @return The axis (<code>null</code> possible). */ public ValueAxis getRangeAxis(int index) { ValueAxis result = null; if (index < this.rangeAxes.size()) { result = this.rangeAxes.get(index); } if (result == null) { Plot parent = getParent(); if (parent instanceof CategoryPlot) { CategoryPlot cp = (CategoryPlot) parent; result = cp.getRangeAxis(index); } } return result; } /** * Sets the range axis for the plot and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param axis the axis (<code>null</code> permitted). */ public void setRangeAxis(ValueAxis axis) { setRangeAxis(0, axis); } /** * Sets a range axis and sends a {@link PlotChangeEvent} to all registered * listeners. * * @param index the axis index. * @param axis the axis. */ public void setRangeAxis(int index, ValueAxis axis) { setRangeAxis(index, axis, true); } /** * Sets a range axis and, if requested, sends a {@link PlotChangeEvent} to * all registered listeners. * * @param index the axis index. * @param axis the axis. * @param notify notify listeners? */ public void setRangeAxis(int index, ValueAxis axis, boolean notify) { ValueAxis existing = this.rangeAxes.get(index); if (existing != null) { existing.removeChangeListener(this); } if (axis != null) { axis.setPlot(this); } this.rangeAxes.set(index, axis); if (axis != null) { axis.configure(); axis.addChangeListener(this); } if (notify) { fireChangeEvent(); } } /** * Sets the range axes for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param axes the axes (<code>null</code> not permitted). * * @see #setDomainAxes(CategoryAxis[]) */ public void setRangeAxes(ValueAxis[] axes) { for (int i = 0; i < axes.length; i++) { setRangeAxis(i, axes[i], false); } fireChangeEvent(); } /** * Returns the index of the specified axis, or <code>-1</code> if the axis * is not assigned to the plot. * * @param axis the axis (<code>null</code> not permitted). * * @return The axis index. * * @see #getRangeAxis(int) * @see #getDomainAxisIndex(CategoryAxis) * * @since 1.0.7 */ public int getRangeAxisIndex(ValueAxis axis) { if (axis == null) { throw new IllegalArgumentException("Null 'axis' argument."); } int result = this.rangeAxes.indexOf(axis); if (result < 0) { // try the parent plot Plot parent = getParent(); if (parent instanceof CategoryPlot) { CategoryPlot p = (CategoryPlot) parent; result = p.getRangeAxisIndex(axis); } } return result; } /** * Returns the range axis location. * * @return The location (never <code>null</code>). */ public AxisLocation getRangeAxisLocation() { return getRangeAxisLocation(0); } /** * Returns the location for a range axis. * * @param index the axis index. * * @return The location. * * @see #setRangeAxisLocation(int, AxisLocation) */ public AxisLocation getRangeAxisLocation(int index) { AxisLocation result = null; if (index < this.rangeAxisLocations.size()) { result = this.rangeAxisLocations.get(index); } if (result == null) { result = AxisLocation.getOpposite(getRangeAxisLocation(0)); } return result; } /** * Sets the location of the range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param location the location (<code>null</code> not permitted). * * @see #setRangeAxisLocation(AxisLocation, boolean) * @see #setDomainAxisLocation(AxisLocation) */ public void setRangeAxisLocation(AxisLocation location) { // defer argument checking... setRangeAxisLocation(location, true); } /** * Sets the location of the range axis and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param location the location (<code>null</code> not permitted). * @param notify notify listeners? * * @see #setDomainAxisLocation(AxisLocation, boolean) */ public void setRangeAxisLocation(AxisLocation location, boolean notify) { setRangeAxisLocation(0, location, notify); } /** * Sets the location for a range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location. * * @see #getRangeAxisLocation(int) * @see #setRangeAxisLocation(int, AxisLocation, boolean) */ public void setRangeAxisLocation(int index, AxisLocation location) { setRangeAxisLocation(index, location, true); } /** * Sets the location for a range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param index the axis index. * @param location the location. * @param notify notify listeners? * * @see #getRangeAxisLocation(int) * @see #setDomainAxisLocation(int, AxisLocation, boolean) */ public void setRangeAxisLocation(int index, AxisLocation location, boolean notify) { if (index == 0 && location == null) { throw new IllegalArgumentException( "Null 'location' for index 0 not permitted."); } this.rangeAxisLocations.set(index, location); if (notify) { fireChangeEvent(); } } /** * Returns the edge where the primary range axis is located. * * @return The edge (never <code>null</code>). */ public RectangleEdge getRangeAxisEdge() { return getRangeAxisEdge(0); } /** * Returns the edge for a range axis. * * @param index the axis index. * * @return The edge. */ public RectangleEdge getRangeAxisEdge(int index) { AxisLocation location = getRangeAxisLocation(index); return Plot.resolveRangeAxisLocation(location, this.orientation); } /** * Returns the number of range axes. * * @return The axis count. */ public int getRangeAxisCount() { return this.rangeAxes.size(); } /** * Clears the range axes from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. */ public void clearRangeAxes() { for (int i = 0; i < this.rangeAxes.size(); i++) { ValueAxis axis = this.rangeAxes.get(i); if (axis != null) { axis.removeChangeListener(this); } } this.rangeAxes.clear(); fireChangeEvent(); } /** * Configures the range axes. */ public void configureRangeAxes() { for (int i = 0; i < this.rangeAxes.size(); i++) { ValueAxis axis = this.rangeAxes.get(i); if (axis != null) { axis.configure(); } } } /** * Returns the primary dataset for the plot. * * @return The primary dataset (possibly <code>null</code>). * * @see #setDataset(CategoryDataset) */ public CategoryDataset getDataset() { return getDataset(0); } /** * Returns the dataset at the given index. * * @param index the dataset index. * * @return The dataset (possibly <code>null</code>). * * @see #setDataset(int, CategoryDataset) */ public CategoryDataset getDataset(int index) { CategoryDataset result = null; if (this.datasets.size() > index) { result = this.datasets.get(index); } return result; } /** * Sets the dataset for the plot, replacing the existing dataset, if there * is one. This method also calls the * {@link #datasetChanged(DatasetChangeEvent)} method, which adjusts the * axis ranges if necessary and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param dataset the dataset (<code>null</code> permitted). * * @see #getDataset() */ public void setDataset(CategoryDataset dataset) { setDataset(0, dataset); } /** * Sets a dataset for the plot. * * @param index the dataset index. * @param dataset the dataset (<code>null</code> permitted). * * @see #getDataset(int) */ public void setDataset(int index, CategoryDataset dataset) { CategoryDataset existing = this.datasets.get(index); if (existing != null) { existing.removeChangeListener(this); } this.datasets.set(index, dataset); if (dataset != null) { dataset.addChangeListener(this); } // send a dataset change event to self... DatasetChangeEvent event = new DatasetChangeEvent(this, dataset); datasetChanged(event); } /** * Returns the number of datasets. * * @return The number of datasets. * * @since 1.0.2 */ public int getDatasetCount() { return this.datasets.size(); } /** * Returns the index of the specified dataset, or <code>-1</code> if the * dataset does not belong to the plot. * * @param dataset the dataset (<code>null</code> not permitted). * * @return The index. * * @since 1.0.11 */ public int indexOf(CategoryDataset dataset) { int result = -1; for (int i = 0; i < this.datasets.size(); i++) { if (dataset == this.datasets.get(i)) { result = i; break; } } return result; } /** * Maps a dataset to a particular domain axis. * * @param index the dataset index (zero-based). * @param axisIndex the axis index (zero-based). * * @see #getDomainAxisForDataset(int) */ public void mapDatasetToDomainAxis(int index, int axisIndex) { List<Integer> axisIndices = new java.util.ArrayList<Integer>(1); axisIndices.add(axisIndex); mapDatasetToDomainAxes(index, axisIndices); } /** * Maps the specified dataset to the axes in the list. Note that the * conversion of data values into Java2D space is always performed using * the first axis in the list. * * @param index the dataset index (zero-based). * @param axisIndices the axis indices (<code>null</code> permitted). * * @since 1.0.12 */ public void mapDatasetToDomainAxes(int index, List<Integer> axisIndices) { if (index < 0) { throw new IllegalArgumentException("Requires 'index' >= 0."); } checkAxisIndices(axisIndices); this.datasetToDomainAxesMap.put(index, new ArrayList<Integer>(axisIndices)); // fake a dataset change event to update axes... datasetChanged(new DatasetChangeEvent(this, getDataset(index))); } /** * This method is used to perform argument checking on the list of * axis indices passed to mapDatasetToDomainAxes() and * mapDatasetToRangeAxes(). * * @param indices the list of indices (<code>null</code> permitted). */ private void checkAxisIndices(List<Integer> indices) { // axisIndices can be: // 1. null; // 2. non-empty, containing only Integer objects that are unique. if (indices == null) { return; } int count = indices.size(); if (count == 0) { throw new IllegalArgumentException("Empty list not permitted."); } HashSet<Integer> set = new HashSet<Integer>(); for (Integer item : indices) { if (set.contains(item)) { throw new IllegalArgumentException("Indices must be unique."); } set.add(item); } } /** * Returns the domain axis for a dataset. You can change the axis for a * dataset using the {@link #mapDatasetToDomainAxis(int, int)} method. * * @param index the dataset index. * * @return The domain axis. * * @see #mapDatasetToDomainAxis(int, int) */ public CategoryAxis getDomainAxisForDataset(int index) { if (index < 0) { throw new IllegalArgumentException("Negative 'index'."); } CategoryAxis axis; List<Integer> axisIndices = this.datasetToDomainAxesMap.get( Integer.valueOf(index)); if (axisIndices != null) { // the first axis in the list is used for data <--> Java2D Integer axisIndex = axisIndices.get(0); axis = getDomainAxis(axisIndex); } else { axis = getDomainAxis(0); } return axis; } /** * Maps a dataset to a particular range axis. * * @param index the dataset index (zero-based). * @param axisIndex the axis index (zero-based). * * @see #getRangeAxisForDataset(int) */ public void mapDatasetToRangeAxis(int index, int axisIndex) { List<Integer> axisIndices = new java.util.ArrayList<Integer>(1); axisIndices.add(axisIndex); mapDatasetToRangeAxes(index, axisIndices); } /** * Maps the specified dataset to the axes in the list. Note that the * conversion of data values into Java2D space is always performed using * the first axis in the list. * * @param index the dataset index (zero-based). * @param axisIndices the axis indices (<code>null</code> permitted). * * @since 1.0.12 */ public void mapDatasetToRangeAxes(int index, List<Integer> axisIndices) { if (index < 0) { throw new IllegalArgumentException("Requires 'index' >= 0."); } checkAxisIndices(axisIndices); Integer key = index; this.datasetToRangeAxesMap.put(key, new ArrayList<Integer>(axisIndices)); // fake a dataset change event to update axes... datasetChanged(new DatasetChangeEvent(this, getDataset(index))); } /** * Returns the range axis for a dataset. You can change the axis for a * dataset using the {@link #mapDatasetToRangeAxis(int, int)} method. * * @param index the dataset index. * * @return The range axis. * * @see #mapDatasetToRangeAxis(int, int) */ public ValueAxis getRangeAxisForDataset(int index) { if (index < 0) { throw new IllegalArgumentException("Negative 'index'."); } ValueAxis axis; List<Integer> axisIndices = this.datasetToRangeAxesMap.get( Integer.valueOf(index)); if (axisIndices != null) { // the first axis in the list is used for data <--> Java2D Integer axisIndex = axisIndices.get(0); axis = getRangeAxis(axisIndex); } else { axis = getRangeAxis(0); } return axis; } /** * Returns the number of renderer slots for this plot. * * @return The number of renderer slots. * * @since 1.0.11 */ public int getRendererCount() { return this.renderers.size(); } /** * Returns a reference to the renderer for the plot. * * @return The renderer. * * @see #setRenderer(CategoryItemRenderer) */ public CategoryItemRenderer getRenderer() { return getRenderer(0); } /** * Returns the renderer at the given index. * * @param index the renderer index. * * @return The renderer (possibly <code>null</code>). * * @see #setRenderer(int, CategoryItemRenderer) */ public CategoryItemRenderer getRenderer(int index) { CategoryItemRenderer result = null; if (this.renderers.size() > index) { result = this.renderers.get(index); } return result; } /** * Sets the renderer at index 0 (sometimes referred to as the "primary" * renderer) and sends a {@link PlotChangeEvent} to all registered * listeners. * * @param renderer the renderer (<code>null</code> permitted. * * @see #getRenderer() */ public void setRenderer(CategoryItemRenderer renderer) { setRenderer(0, renderer, true); } /** * Sets the renderer at index 0 (sometimes referred to as the "primary" * renderer) and, if requested, sends a {@link PlotChangeEvent} to all * registered listeners. * <p> * You can set the renderer to <code>null</code>, but this is not * recommended because: * <ul> * <li>no data will be displayed;</li> * <li>the plot background will not be painted;</li> * </ul> * * @param renderer the renderer (<code>null</code> permitted). * @param notify notify listeners? * * @see #getRenderer() */ public void setRenderer(CategoryItemRenderer renderer, boolean notify) { setRenderer(0, renderer, notify); } /** * Sets the renderer at the specified index and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the index. * @param renderer the renderer (<code>null</code> permitted). * * @see #getRenderer(int) * @see #setRenderer(int, CategoryItemRenderer, boolean) */ public void setRenderer(int index, CategoryItemRenderer renderer) { setRenderer(index, renderer, true); } /** * Sets a renderer. A {@link PlotChangeEvent} is sent to all registered * listeners. * * @param index the index. * @param renderer the renderer (<code>null</code> permitted). * @param notify notify listeners? * * @see #getRenderer(int) */ public void setRenderer(int index, CategoryItemRenderer renderer, boolean notify) { // stop listening to the existing renderer... CategoryItemRenderer existing = this.renderers.get(index); if (existing != null) { existing.removeChangeListener(this); } // register the new renderer... this.renderers.set(index, renderer); if (renderer != null) { renderer.setPlot(this); renderer.addChangeListener(this); } configureDomainAxes(); configureRangeAxes(); if (notify) { fireChangeEvent(); } } /** * Sets the renderers for this plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param renderers the renderers. */ public void setRenderers(CategoryItemRenderer[] renderers) { for (int i = 0; i < renderers.length; i++) { setRenderer(i, renderers[i], false); } fireChangeEvent(); } /** * Returns the renderer for the specified dataset. If the dataset doesn't * belong to the plot, this method will return <code>null</code>. * * @param dataset the dataset (<code>null</code> permitted). * * @return The renderer (possibly <code>null</code>). */ public CategoryItemRenderer getRendererForDataset(CategoryDataset dataset) { CategoryItemRenderer result = null; for (int i = 0; i < this.datasets.size(); i++) { if (this.datasets.get(i) == dataset) { result = this.renderers.get(i); break; } } return result; } /** * Returns the index of the specified renderer, or <code>-1</code> if the * renderer is not assigned to this plot. * * @param renderer the renderer (<code>null</code> permitted). * * @return The renderer index. */ public int getIndexOf(CategoryItemRenderer renderer) { return this.renderers.indexOf(renderer); } /** * Returns the dataset rendering order. * * @return The order (never <code>null</code>). * * @see #setDatasetRenderingOrder(DatasetRenderingOrder) */ public DatasetRenderingOrder getDatasetRenderingOrder() { return this.renderingOrder; } /** * Sets the rendering order and sends a {@link PlotChangeEvent} to all * registered listeners. By default, the plot renders the primary dataset * last (so that the primary dataset overlays the secondary datasets). You * can reverse this if you want to. * * @param order the rendering order (<code>null</code> not permitted). * * @see #getDatasetRenderingOrder() */ public void setDatasetRenderingOrder(DatasetRenderingOrder order) { if (order == null) { throw new IllegalArgumentException("Null 'order' argument."); } this.renderingOrder = order; fireChangeEvent(); } /** * Returns the order in which the columns are rendered. The default value * is <code>SortOrder.ASCENDING</code>. * * @return The column rendering order (never <code>null</code). * * @see #setColumnRenderingOrder(SortOrder) */ public SortOrder getColumnRenderingOrder() { return this.columnRenderingOrder; } /** * Sets the column order in which the items in each dataset should be * rendered and sends a {@link PlotChangeEvent} to all registered * listeners. Note that this affects the order in which items are drawn, * NOT their position in the chart. * * @param order the order (<code>null</code> not permitted). * * @see #getColumnRenderingOrder() * @see #setRowRenderingOrder(SortOrder) */ public void setColumnRenderingOrder(SortOrder order) { if (order == null) { throw new IllegalArgumentException("Null 'order' argument."); } this.columnRenderingOrder = order; fireChangeEvent(); } /** * Returns the order in which the rows should be rendered. The default * value is <code>SortOrder.ASCENDING</code>. * * @return The order (never <code>null</code>). * * @see #setRowRenderingOrder(SortOrder) */ public SortOrder getRowRenderingOrder() { return this.rowRenderingOrder; } /** * Sets the row order in which the items in each dataset should be * rendered and sends a {@link PlotChangeEvent} to all registered * listeners. Note that this affects the order in which items are drawn, * NOT their position in the chart. * * @param order the order (<code>null</code> not permitted). * * @see #getRowRenderingOrder() * @see #setColumnRenderingOrder(SortOrder) */ public void setRowRenderingOrder(SortOrder order) { if (order == null) { throw new IllegalArgumentException("Null 'order' argument."); } this.rowRenderingOrder = order; fireChangeEvent(); } /** * Returns the flag that controls whether the domain grid-lines are visible. * * @return The <code>true</code> or <code>false</code>. * * @see #setDomainGridlinesVisible(boolean) */ public boolean isDomainGridlinesVisible() { return this.domainGridlinesVisible; } /** * Sets the flag that controls whether or not grid-lines are drawn against * the domain axis. * <p> * If the flag value changes, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isDomainGridlinesVisible() */ public void setDomainGridlinesVisible(boolean visible) { if (this.domainGridlinesVisible != visible) { this.domainGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the position used for the domain gridlines. * * @return The gridline position (never <code>null</code>). * * @see #setDomainGridlinePosition(CategoryAnchor) */ public CategoryAnchor getDomainGridlinePosition() { return this.domainGridlinePosition; } /** * Sets the position used for the domain gridlines and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param position the position (<code>null</code> not permitted). * * @see #getDomainGridlinePosition() */ public void setDomainGridlinePosition(CategoryAnchor position) { if (position == null) { throw new IllegalArgumentException("Null 'position' argument."); } this.domainGridlinePosition = position; fireChangeEvent(); } /** * Returns the stroke used to draw grid-lines against the domain axis. * * @return The stroke (never <code>null</code>). * * @see #setDomainGridlineStroke(Stroke) */ public Stroke getDomainGridlineStroke() { return this.domainGridlineStroke; } /** * Sets the stroke used to draw grid-lines against the domain axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getDomainGridlineStroke() */ public void setDomainGridlineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' not permitted."); } this.domainGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint used to draw grid-lines against the domain axis. * * @return The paint (never <code>null</code>). * * @see #setDomainGridlinePaint(Paint) */ public Paint getDomainGridlinePaint() { return this.domainGridlinePaint; } /** * Sets the paint used to draw the grid-lines (if any) against the domain * axis and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getDomainGridlinePaint() */ public void setDomainGridlinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.domainGridlinePaint = paint; fireChangeEvent(); } /** * Returns a flag that controls whether or not a zero baseline is * displayed for the range axis. * * @return A boolean. * * @see #setRangeZeroBaselineVisible(boolean) * * @since 1.0.13 */ public boolean isRangeZeroBaselineVisible() { return this.rangeZeroBaselineVisible; } /** * Sets the flag that controls whether or not the zero baseline is * displayed for the range axis, and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param visible the flag. * * @see #isRangeZeroBaselineVisible() * * @since 1.0.13 */ public void setRangeZeroBaselineVisible(boolean visible) { this.rangeZeroBaselineVisible = visible; fireChangeEvent(); } /** * Returns the stroke used for the zero baseline against the range axis. * * @return The stroke (never <code>null</code>). * * @see #setRangeZeroBaselineStroke(Stroke) * * @since 1.0.13 */ public Stroke getRangeZeroBaselineStroke() { return this.rangeZeroBaselineStroke; } /** * Sets the stroke for the zero baseline for the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getRangeZeroBaselineStroke() * * @since 1.0.13 */ public void setRangeZeroBaselineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.rangeZeroBaselineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the zero baseline (if any) plotted against the * range axis. * * @return The paint (never <code>null</code>). * * @see #setRangeZeroBaselinePaint(Paint) * * @since 1.0.13 */ public Paint getRangeZeroBaselinePaint() { return this.rangeZeroBaselinePaint; } /** * Sets the paint for the zero baseline plotted against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRangeZeroBaselinePaint() * * @since 1.0.13 */ public void setRangeZeroBaselinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.rangeZeroBaselinePaint = paint; fireChangeEvent(); } /** * Returns the flag that controls whether the range grid-lines are visible. * * @return The flag. * * @see #setRangeGridlinesVisible(boolean) */ public boolean isRangeGridlinesVisible() { return this.rangeGridlinesVisible; } /** * Sets the flag that controls whether or not grid-lines are drawn against * the range axis. If the flag changes value, a {@link PlotChangeEvent} is * sent to all registered listeners. * * @param visible the new value of the flag. * * @see #isRangeGridlinesVisible() */ public void setRangeGridlinesVisible(boolean visible) { if (this.rangeGridlinesVisible != visible) { this.rangeGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke used to draw the grid-lines against the range axis. * * @return The stroke (never <code>null</code>). * * @see #setRangeGridlineStroke(Stroke) */ public Stroke getRangeGridlineStroke() { return this.rangeGridlineStroke; } /** * Sets the stroke used to draw the grid-lines against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getRangeGridlineStroke() */ public void setRangeGridlineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.rangeGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint used to draw the grid-lines against the range axis. * * @return The paint (never <code>null</code>). * * @see #setRangeGridlinePaint(Paint) */ public Paint getRangeGridlinePaint() { return this.rangeGridlinePaint; } /** * Sets the paint used to draw the grid lines against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRangeGridlinePaint() */ public void setRangeGridlinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.rangeGridlinePaint = paint; fireChangeEvent(); } /** * Returns <code>true</code> if the range axis minor grid is visible, and * <code>false</code> otherwise. * * @return A boolean. * * @see #setRangeMinorGridlinesVisible(boolean) * * @since 1.0.13 */ public boolean isRangeMinorGridlinesVisible() { return this.rangeMinorGridlinesVisible; } /** * Sets the flag that controls whether or not the range axis minor grid * lines are visible. * <p> * If the flag value is changed, a {@link PlotChangeEvent} is sent to all * registered listeners. * * @param visible the new value of the flag. * * @see #isRangeMinorGridlinesVisible() * * @since 1.0.13 */ public void setRangeMinorGridlinesVisible(boolean visible) { if (this.rangeMinorGridlinesVisible != visible) { this.rangeMinorGridlinesVisible = visible; fireChangeEvent(); } } /** * Returns the stroke for the minor grid lines (if any) plotted against the * range axis. * * @return The stroke (never <code>null</code>). * * @see #setRangeMinorGridlineStroke(Stroke) * * @since 1.0.13 */ public Stroke getRangeMinorGridlineStroke() { return this.rangeMinorGridlineStroke; } /** * Sets the stroke for the minor grid lines plotted against the range axis, * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @see #getRangeMinorGridlineStroke() * * @since 1.0.13 */ public void setRangeMinorGridlineStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.rangeMinorGridlineStroke = stroke; fireChangeEvent(); } /** * Returns the paint for the minor grid lines (if any) plotted against the * range axis. * * @return The paint (never <code>null</code>). * * @see #setRangeMinorGridlinePaint(Paint) * * @since 1.0.13 */ public Paint getRangeMinorGridlinePaint() { return this.rangeMinorGridlinePaint; } /** * Sets the paint for the minor grid lines plotted against the range axis * and sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRangeMinorGridlinePaint() * * @since 1.0.13 */ public void setRangeMinorGridlinePaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.rangeMinorGridlinePaint = paint; fireChangeEvent(); } /** * Returns the fixed legend items, if any. * * @return The legend items (possibly <code>null</code>). * * @see #setFixedLegendItems(LegendItemCollection) */ public LegendItemCollection getFixedLegendItems() { return this.fixedLegendItems; } /** * Sets the fixed legend items for the plot. Leave this set to * <code>null</code> if you prefer the legend items to be created * automatically. * * @param items the legend items (<code>null</code> permitted). * * @see #getFixedLegendItems() */ public void setFixedLegendItems(LegendItemCollection items) { this.fixedLegendItems = items; fireChangeEvent(); } /** * Returns the legend items for the plot. By default, this method creates * a legend item for each series in each of the datasets. You can change * this behaviour by overriding this method. * * @return The legend items. */ @Override public LegendItemCollection getLegendItems() { if (this.fixedLegendItems != null) { return this.fixedLegendItems; } LegendItemCollection result = new LegendItemCollection(); // get the legend items for the datasets... int count = this.datasets.size(); for (int datasetIndex = 0; datasetIndex < count; datasetIndex++) { CategoryDataset dataset = getDataset(datasetIndex); if (dataset != null) { CategoryItemRenderer renderer = getRenderer(datasetIndex); if (renderer != null) { result.addAll(renderer.getLegendItems()); } } } return result; } /** * Handles a 'click' on the plot by updating the anchor value. * * @param x x-coordinate of the click (in Java2D space). * @param y y-coordinate of the click (in Java2D space). * @param info information about the plot's dimensions. * */ @Override public void handleClick(int x, int y, PlotRenderingInfo info) { Rectangle2D dataArea = info.getDataArea(); if (dataArea.contains(x, y)) { // set the anchor value for the range axis... double java2D = 0.0; if (this.orientation == PlotOrientation.HORIZONTAL) { java2D = x; } else if (this.orientation == PlotOrientation.VERTICAL) { java2D = y; } RectangleEdge edge = Plot.resolveRangeAxisLocation( getRangeAxisLocation(), this.orientation); double value = getRangeAxis().java2DToValue( java2D, info.getDataArea(), edge); setAnchorValue(value); setRangeCrosshairValue(value); } } /** * Zooms (in or out) on the plot's value axis. * <p> * If the value 0.0 is passed in as the zoom percent, the auto-range * calculation for the axis is restored (which sets the range to include * the minimum and maximum data values, thus displaying all the data). * * @param percent the zoom amount. */ @Override public void zoom(double percent) { if (percent > 0.0) { double range = getRangeAxis().getRange().getLength(); double scaledRange = range * percent; getRangeAxis().setRange(this.anchorValue - scaledRange / 2.0, this.anchorValue + scaledRange / 2.0); } else { getRangeAxis().setAutoRange(true); } } /** * Receives notification of a change to an {@link Annotation} added to * this plot. * * @param event information about the event (not used here). * * @since 1.0.14 */ @Override public void annotationChanged(AnnotationChangeEvent event) { if (getParent() != null) { getParent().annotationChanged(event); } else { PlotChangeEvent e = new PlotChangeEvent(this); notifyListeners(e); } } /** * Receives notification of a change to the plot's dataset. * <P> * The range axis bounds will be recalculated if necessary. * * @param event information about the event (not used here). */ @Override public void datasetChanged(DatasetChangeEvent event) { int count = this.rangeAxes.size(); for (int axisIndex = 0; axisIndex < count; axisIndex++) { ValueAxis yAxis = getRangeAxis(axisIndex); if (yAxis != null) { yAxis.configure(); } } if (getParent() != null) { getParent().datasetChanged(event); } else { PlotChangeEvent e = new PlotChangeEvent(this); e.setType(ChartChangeEventType.DATASET_UPDATED); notifyListeners(e); } } /** * Receives notification of a renderer change event. * * @param event the event. */ @Override public void rendererChanged(RendererChangeEvent event) { Plot parent = getParent(); if (parent != null) { if (parent instanceof RendererChangeListener) { RendererChangeListener rcl = (RendererChangeListener) parent; rcl.rendererChanged(event); } else { // this should never happen with the existing code, but throw // an exception in case future changes make it possible... throw new RuntimeException( "The renderer has changed and I don't know what to do!"); } } else { configureRangeAxes(); PlotChangeEvent e = new PlotChangeEvent(this); notifyListeners(e); } } /** * Adds a marker for display (in the foreground) against the domain axis and * sends a {@link PlotChangeEvent} to all registered listeners. Typically a * marker will be drawn by the renderer as a line perpendicular to the * domain axis, however this is entirely up to the renderer. * * @param marker the marker (<code>null</code> not permitted). * * @see #removeDomainMarker(Marker) */ public void addDomainMarker(CategoryMarker marker) { addDomainMarker(marker, Layer.FOREGROUND); } /** * Adds a marker for display against the domain axis and sends a * {@link PlotChangeEvent} to all registered listeners. Typically a marker * will be drawn by the renderer as a line perpendicular to the domain * axis, however this is entirely up to the renderer. * * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (foreground or background) (<code>null</code> * not permitted). * * @see #removeDomainMarker(Marker, Layer) */ public void addDomainMarker(CategoryMarker marker, Layer layer) { addDomainMarker(0, marker, layer); } /** * Adds a marker for display by a particular renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to a domain axis, however this is entirely up to the renderer. * * @param index the renderer index. * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (<code>null</code> not permitted). * * @see #removeDomainMarker(int, Marker, Layer) */ public void addDomainMarker(int index, CategoryMarker marker, Layer layer) { addDomainMarker(index, marker, layer, true); } /** * Adds a marker for display by a particular renderer and, if requested, * sends a {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to a domain axis, however this is entirely up to the renderer. * * @param index the renderer index. * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (<code>null</code> not permitted). * @param notify notify listeners? * * @since 1.0.10 * * @see #removeDomainMarker(int, Marker, Layer, boolean) */ public void addDomainMarker(int index, CategoryMarker marker, Layer layer, boolean notify) { if (marker == null) { throw new IllegalArgumentException("Null 'marker' not permitted."); } if (layer == null) { throw new IllegalArgumentException("Null 'layer' not permitted."); } Collection<Marker> markers; if (layer == Layer.FOREGROUND) { markers = this.foregroundDomainMarkers.get( index); if (markers == null) { markers = new java.util.ArrayList<Marker>(); this.foregroundDomainMarkers.put(index, markers); } markers.add(marker); } else if (layer == Layer.BACKGROUND) { markers = this.backgroundDomainMarkers.get( index); if (markers == null) { markers = new java.util.ArrayList<Marker>(); this.backgroundDomainMarkers.put(index, markers); } markers.add(marker); } marker.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Clears all the domain markers for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @see #clearRangeMarkers() */ public void clearDomainMarkers() { if (this.backgroundDomainMarkers != null) { Set<Integer> keys = this.backgroundDomainMarkers.keySet(); for (Integer key : keys) { clearDomainMarkers(key); } this.backgroundDomainMarkers.clear(); } if (this.foregroundDomainMarkers != null) { Set<Integer> keys = this.foregroundDomainMarkers.keySet(); for (Integer key : keys) { clearDomainMarkers(key); } this.foregroundDomainMarkers.clear(); } fireChangeEvent(); } /** * Returns the list of domain markers (read only) for the specified layer. * * @param layer the layer (foreground or background). * * @return The list of domain markers. */ public Collection<Marker> getDomainMarkers(Layer layer) { return getDomainMarkers(0, layer); } /** * Returns a collection of domain markers for a particular renderer and * layer. * * @param index the renderer index. * @param layer the layer. * * @return A collection of markers (possibly <code>null</code>). */ public Collection<Marker> getDomainMarkers(int index, Layer layer) { Collection<Marker> result = null; if (layer == Layer.FOREGROUND) { result = this.foregroundDomainMarkers.get(index); } else if (layer == Layer.BACKGROUND) { result = this.backgroundDomainMarkers.get(index); } if (result != null) { result = Collections.unmodifiableCollection(result); } return result; } /** * Clears all the domain markers for the specified renderer. * * @param index the renderer index. * * @see #clearRangeMarkers(int) */ public void clearDomainMarkers(int index) { if (this.backgroundDomainMarkers != null) { Collection<Marker> markers = this.backgroundDomainMarkers.get(index); if (markers != null) { for (Marker m : markers) { m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundDomainMarkers != null) { Collection<Marker> markers = this.foregroundDomainMarkers.get(index); if (markers != null) { for (Marker m : markers) { m.removeChangeListener(this); } markers.clear(); } } fireChangeEvent(); } /** * Removes a marker for the domain axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param marker the marker. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(Marker marker) { return removeDomainMarker(marker, Layer.FOREGROUND); } /** * Removes a marker for the domain axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(Marker marker, Layer layer) { return removeDomainMarker(0, marker, layer); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 */ public boolean removeDomainMarker(int index, Marker marker, Layer layer) { return removeDomainMarker(index, marker, layer, true); } /** * Removes a marker for a specific dataset/renderer and, if requested, * sends a {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners? * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.10 */ public boolean removeDomainMarker(int index, Marker marker, Layer layer, boolean notify) { Collection<Marker> markers; if (layer == Layer.FOREGROUND) { markers = this.foregroundDomainMarkers.get(index); } else { markers = this.backgroundDomainMarkers.get(index); } if (markers == null) { return false; } boolean removed = markers.remove(marker); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Adds a marker for display (in the foreground) against the range axis and * sends a {@link PlotChangeEvent} to all registered listeners. Typically a * marker will be drawn by the renderer as a line perpendicular to the * range axis, however this is entirely up to the renderer. * * @param marker the marker (<code>null</code> not permitted). * * @see #removeRangeMarker(Marker) */ public void addRangeMarker(Marker marker) { addRangeMarker(marker, Layer.FOREGROUND); } /** * Adds a marker for display against the range axis and sends a * {@link PlotChangeEvent} to all registered listeners. Typically a marker * will be drawn by the renderer as a line perpendicular to the range axis, * however this is entirely up to the renderer. * * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (foreground or background) (<code>null</code> * not permitted). * * @see #removeRangeMarker(Marker, Layer) */ public void addRangeMarker(Marker marker, Layer layer) { addRangeMarker(0, marker, layer); } /** * Adds a marker for display by a particular renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to a range axis, however this is entirely up to the renderer. * * @param index the renderer index. * @param marker the marker. * @param layer the layer. * * @see #removeRangeMarker(int, Marker, Layer) */ public void addRangeMarker(int index, Marker marker, Layer layer) { addRangeMarker(index, marker, layer, true); } /** * Adds a marker for display by a particular renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * <P> * Typically a marker will be drawn by the renderer as a line perpendicular * to a range axis, however this is entirely up to the renderer. * * @param index the renderer index. * @param marker the marker. * @param layer the layer. * @param notify notify listeners? * * @since 1.0.10 * * @see #removeRangeMarker(int, Marker, Layer, boolean) */ public void addRangeMarker(int index, Marker marker, Layer layer, boolean notify) { Collection<Marker> markers; if (layer == Layer.FOREGROUND) { markers = this.foregroundRangeMarkers.get( index); if (markers == null) { markers = new java.util.ArrayList<Marker>(); this.foregroundRangeMarkers.put(index, markers); } markers.add(marker); } else if (layer == Layer.BACKGROUND) { markers = this.backgroundRangeMarkers.get( index); if (markers == null) { markers = new java.util.ArrayList<Marker>(); this.backgroundRangeMarkers.put(index, markers); } markers.add(marker); } marker.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Clears all the range markers for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @see #clearDomainMarkers() */ public void clearRangeMarkers() { if (this.backgroundRangeMarkers != null) { Set<Integer> keys = this.backgroundRangeMarkers.keySet(); for (Integer key : keys) { clearRangeMarkers(key); } this.backgroundRangeMarkers.clear(); } if (this.foregroundRangeMarkers != null) { Set<Integer> keys = this.foregroundRangeMarkers.keySet(); for (Integer key : keys) { clearRangeMarkers(key); } this.foregroundRangeMarkers.clear(); } fireChangeEvent(); } /** * Returns the list of range markers (read only) for the specified layer. * * @param layer the layer (foreground or background). * * @return The list of range markers. * * @see #getRangeMarkers(int, Layer) */ public Collection<Marker> getRangeMarkers(Layer layer) { return getRangeMarkers(0, layer); } /** * Returns a collection of range markers for a particular renderer and * layer. * * @param index the renderer index. * @param layer the layer. * * @return A collection of markers (possibly <code>null</code>). */ public Collection<Marker> getRangeMarkers(int index, Layer layer) { Collection<Marker> result = null; Integer key = index; if (layer == Layer.FOREGROUND) { result = this.foregroundRangeMarkers.get(key); } else if (layer == Layer.BACKGROUND) { result = this.backgroundRangeMarkers.get(key); } if (result != null) { result = Collections.unmodifiableCollection(result); } return result; } /** * Clears all the range markers for the specified renderer. * * @param index the renderer index. * * @see #clearDomainMarkers(int) */ public void clearRangeMarkers(int index) { Integer key = index; if (this.backgroundRangeMarkers != null) { Collection<Marker> markers = this.backgroundRangeMarkers.get(key); if (markers != null) { for (Marker m : markers) { m.removeChangeListener(this); } markers.clear(); } } if (this.foregroundRangeMarkers != null) { Collection<Marker> markers = this.foregroundRangeMarkers.get(key); if (markers != null) { for (Marker m : markers) { m.removeChangeListener(this); } markers.clear(); } } fireChangeEvent(); } /** * Removes a marker for the range axis and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param marker the marker. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 * * @see #addRangeMarker(Marker) */ public boolean removeRangeMarker(Marker marker) { return removeRangeMarker(marker, Layer.FOREGROUND); } /** * Removes a marker for the range axis in the specified layer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param marker the marker (<code>null</code> not permitted). * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 * * @see #addRangeMarker(Marker, Layer) */ public boolean removeRangeMarker(Marker marker, Layer layer) { return removeRangeMarker(0, marker, layer); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.7 * * @see #addRangeMarker(int, Marker, Layer) */ public boolean removeRangeMarker(int index, Marker marker, Layer layer) { return removeRangeMarker(index, marker, layer, true); } /** * Removes a marker for a specific dataset/renderer and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the dataset/renderer index. * @param marker the marker. * @param layer the layer (foreground or background). * @param notify notify listeners. * * @return A boolean indicating whether or not the marker was actually * removed. * * @since 1.0.10 * * @see #addRangeMarker(int, Marker, Layer, boolean) */ public boolean removeRangeMarker(int index, Marker marker, Layer layer, boolean notify) { if (marker == null) { throw new IllegalArgumentException("Null 'marker' argument."); } Collection<Marker> markers; if (layer == Layer.FOREGROUND) { markers = this.foregroundRangeMarkers.get(index); } else { markers = this.backgroundRangeMarkers.get(index); } if (markers == null) { return false; } boolean removed = markers.remove(marker); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Returns the flag that controls whether or not the domain crosshair is * displayed by the plot. * * @return A boolean. * * @since 1.0.11 * * @see #setDomainCrosshairVisible(boolean) */ public boolean isDomainCrosshairVisible() { return this.domainCrosshairVisible; } /** * Sets the flag that controls whether or not the domain crosshair is * displayed by the plot, and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param flag the new flag value. * * @since 1.0.11 * * @see #isDomainCrosshairVisible() * @see #setRangeCrosshairVisible(boolean) */ public void setDomainCrosshairVisible(boolean flag) { if (this.domainCrosshairVisible != flag) { this.domainCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns the row key for the domain crosshair. * * @return The row key. * * @since 1.0.11 */ public Comparable getDomainCrosshairRowKey() { return this.domainCrosshairRowKey; } /** * Sets the row key for the domain crosshair and sends a * {PlotChangeEvent} to all registered listeners. * * @param key the key. * * @since 1.0.11 */ public void setDomainCrosshairRowKey(Comparable key) { setDomainCrosshairRowKey(key, true); } /** * Sets the row key for the domain crosshair and, if requested, sends a * {PlotChangeEvent} to all registered listeners. * * @param key the key. * @param notify notify listeners? * * @since 1.0.11 */ public void setDomainCrosshairRowKey(Comparable key, boolean notify) { this.domainCrosshairRowKey = key; if (notify) { fireChangeEvent(); } } /** * Returns the column key for the domain crosshair. * * @return The column key. * * @since 1.0.11 */ public Comparable getDomainCrosshairColumnKey() { return this.domainCrosshairColumnKey; } /** * Sets the column key for the domain crosshair and sends * a {@link PlotChangeEvent} to all registered listeners. * * @param key the key. * * @since 1.0.11 */ public void setDomainCrosshairColumnKey(Comparable key) { setDomainCrosshairColumnKey(key, true); } /** * Sets the column key for the domain crosshair and, if requested, sends * a {@link PlotChangeEvent} to all registered listeners. * * @param key the key. * @param notify notify listeners? * * @since 1.0.11 */ public void setDomainCrosshairColumnKey(Comparable key, boolean notify) { this.domainCrosshairColumnKey = key; if (notify) { fireChangeEvent(); } } /** * Returns the dataset index for the crosshair. * * @return The dataset index. * * @since 1.0.11 */ public int getCrosshairDatasetIndex() { return this.crosshairDatasetIndex; } /** * Sets the dataset index for the crosshair and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the index. * * @since 1.0.11 */ public void setCrosshairDatasetIndex(int index) { setCrosshairDatasetIndex(index, true); } /** * Sets the dataset index for the crosshair and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param index the index. * @param notify notify listeners? * * @since 1.0.11 */ public void setCrosshairDatasetIndex(int index, boolean notify) { this.crosshairDatasetIndex = index; if (notify) { fireChangeEvent(); } } /** * Returns the paint used to draw the domain crosshair. * * @return The paint (never <code>null</code>). * * @since 1.0.11 * * @see #setDomainCrosshairPaint(Paint) * @see #getDomainCrosshairStroke() */ public Paint getDomainCrosshairPaint() { return this.domainCrosshairPaint; } /** * Sets the paint used to draw the domain crosshair. * * @param paint the paint (<code>null</code> not permitted). * * @since 1.0.11 * * @see #getDomainCrosshairPaint() */ public void setDomainCrosshairPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.domainCrosshairPaint = paint; fireChangeEvent(); } /** * Returns the stroke used to draw the domain crosshair. * * @return The stroke (never <code>null</code>). * * @since 1.0.11 * * @see #setDomainCrosshairStroke(Stroke) * @see #getDomainCrosshairPaint() */ public Stroke getDomainCrosshairStroke() { return this.domainCrosshairStroke; } /** * Sets the stroke used to draw the domain crosshair, and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param stroke the stroke (<code>null</code> not permitted). * * @since 1.0.11 * * @see #getDomainCrosshairStroke() */ public void setDomainCrosshairStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.domainCrosshairStroke = stroke; } /** * Returns a flag indicating whether or not the range crosshair is visible. * * @return The flag. * * @see #setRangeCrosshairVisible(boolean) */ public boolean isRangeCrosshairVisible() { return this.rangeCrosshairVisible; } /** * Sets the flag indicating whether or not the range crosshair is visible. * * @param flag the new value of the flag. * * @see #isRangeCrosshairVisible() */ public void setRangeCrosshairVisible(boolean flag) { if (this.rangeCrosshairVisible != flag) { this.rangeCrosshairVisible = flag; fireChangeEvent(); } } /** * Returns a flag indicating whether or not the crosshair should "lock-on" * to actual data values. * * @return The flag. * * @see #setRangeCrosshairLockedOnData(boolean) */ public boolean isRangeCrosshairLockedOnData() { return this.rangeCrosshairLockedOnData; } /** * Sets the flag indicating whether or not the range crosshair should * "lock-on" to actual data values, and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param flag the flag. * * @see #isRangeCrosshairLockedOnData() */ public void setRangeCrosshairLockedOnData(boolean flag) { if (this.rangeCrosshairLockedOnData != flag) { this.rangeCrosshairLockedOnData = flag; fireChangeEvent(); } } /** * Returns the range crosshair value. * * @return The value. * * @see #setRangeCrosshairValue(double) */ public double getRangeCrosshairValue() { return this.rangeCrosshairValue; } /** * Sets the range crosshair value and, if the crosshair is visible, sends * a {@link PlotChangeEvent} to all registered listeners. * * @param value the new value. * * @see #getRangeCrosshairValue() */ public void setRangeCrosshairValue(double value) { setRangeCrosshairValue(value, true); } /** * Sets the range crosshair value and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners (but only if the * crosshair is visible). * * @param value the new value. * @param notify a flag that controls whether or not listeners are * notified. * * @see #getRangeCrosshairValue() */ public void setRangeCrosshairValue(double value, boolean notify) { this.rangeCrosshairValue = value; if (isRangeCrosshairVisible() && notify) { fireChangeEvent(); } } /** * Returns the pen-style (<code>Stroke</code>) used to draw the crosshair * (if visible). * * @return The crosshair stroke (never <code>null</code>). * * @see #setRangeCrosshairStroke(Stroke) * @see #isRangeCrosshairVisible() * @see #getRangeCrosshairPaint() */ public Stroke getRangeCrosshairStroke() { return this.rangeCrosshairStroke; } /** * Sets the pen-style (<code>Stroke</code>) used to draw the range * crosshair (if visible), and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param stroke the new crosshair stroke (<code>null</code> not * permitted). * * @see #getRangeCrosshairStroke() */ public void setRangeCrosshairStroke(Stroke stroke) { if (stroke == null) { throw new IllegalArgumentException("Null 'stroke' argument."); } this.rangeCrosshairStroke = stroke; fireChangeEvent(); } /** * Returns the paint used to draw the range crosshair. * * @return The paint (never <code>null</code>). * * @see #setRangeCrosshairPaint(Paint) * @see #isRangeCrosshairVisible() * @see #getRangeCrosshairStroke() */ public Paint getRangeCrosshairPaint() { return this.rangeCrosshairPaint; } /** * Sets the paint used to draw the range crosshair (if visible) and * sends a {@link PlotChangeEvent} to all registered listeners. * * @param paint the paint (<code>null</code> not permitted). * * @see #getRangeCrosshairPaint() */ public void setRangeCrosshairPaint(Paint paint) { if (paint == null) { throw new IllegalArgumentException("Null 'paint' argument."); } this.rangeCrosshairPaint = paint; fireChangeEvent(); } /** * Returns the list of annotations. * * @return The list of annotations (never <code>null</code>). * * @see #addAnnotation(CategoryAnnotation) * @see #clearAnnotations() */ public List<CategoryAnnotation> getAnnotations() { return this.annotations; } /** * Adds an annotation to the plot and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param annotation the annotation (<code>null</code> not permitted). * * @see #removeAnnotation(CategoryAnnotation) */ public void addAnnotation(CategoryAnnotation annotation) { addAnnotation(annotation, true); } /** * Adds an annotation to the plot and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param annotation the annotation (<code>null</code> not permitted). * @param notify notify listeners? * * @since 1.0.10 */ public void addAnnotation(CategoryAnnotation annotation, boolean notify) { if (annotation == null) { throw new IllegalArgumentException("Null 'annotation' argument."); } this.annotations.add(annotation); annotation.addChangeListener(this); if (notify) { fireChangeEvent(); } } /** * Removes an annotation from the plot and sends a {@link PlotChangeEvent} * to all registered listeners. * * @param annotation the annotation (<code>null</code> not permitted). * * @return A boolean (indicates whether or not the annotation was removed). * * @see #addAnnotation(CategoryAnnotation) */ public boolean removeAnnotation(CategoryAnnotation annotation) { return removeAnnotation(annotation, true); } /** * Removes an annotation from the plot and, if requested, sends a * {@link PlotChangeEvent} to all registered listeners. * * @param annotation the annotation (<code>null</code> not permitted). * @param notify notify listeners? * * @return A boolean (indicates whether or not the annotation was removed). * * @since 1.0.10 */ public boolean removeAnnotation(CategoryAnnotation annotation, boolean notify) { if (annotation == null) { throw new IllegalArgumentException("Null 'annotation' argument."); } boolean removed = this.annotations.remove(annotation); annotation.removeChangeListener(this); if (removed && notify) { fireChangeEvent(); } return removed; } /** * Clears all the annotations and sends a {@link PlotChangeEvent} to all * registered listeners. */ public void clearAnnotations() { for (CategoryAnnotation annotation : this.annotations) { annotation.removeChangeListener(this); } this.annotations.clear(); fireChangeEvent(); } /** * Returns the shadow generator for the plot, if any. * * @return The shadow generator (possibly <code>null</code>). * * @since 1.0.14 */ public ShadowGenerator getShadowGenerator() { return this.shadowGenerator; } /** * Sets the shadow generator for the plot and sends a * {@link PlotChangeEvent} to all registered listeners. * * @param generator the generator (<code>null</code> permitted). * * @since 1.0.14 */ public void setShadowGenerator(ShadowGenerator generator) { this.shadowGenerator = generator; fireChangeEvent(); } /** * Calculates the space required for the domain axis/axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param space a carrier for the result (<code>null</code> permitted). * * @return The required space. */ protected AxisSpace calculateDomainAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space) { if (space == null) { space = new AxisSpace(); } // reserve some space for the domain axis... if (this.fixedDomainAxisSpace != null) { if (this.orientation == PlotOrientation.HORIZONTAL) { space.ensureAtLeast( this.fixedDomainAxisSpace.getLeft(), RectangleEdge.LEFT); space.ensureAtLeast(this.fixedDomainAxisSpace.getRight(), RectangleEdge.RIGHT); } else if (this.orientation == PlotOrientation.VERTICAL) { space.ensureAtLeast(this.fixedDomainAxisSpace.getTop(), RectangleEdge.TOP); space.ensureAtLeast(this.fixedDomainAxisSpace.getBottom(), RectangleEdge.BOTTOM); } } else { // reserve space for the primary domain axis... RectangleEdge domainEdge = Plot.resolveDomainAxisLocation( getDomainAxisLocation(), this.orientation); if (this.drawSharedDomainAxis) { space = getDomainAxis().reserveSpace(g2, this, plotArea, domainEdge, space); } // reserve space for any domain axes... for (int i = 0; i < this.domainAxes.size(); i++) { Axis xAxis = this.domainAxes.get(i); if (xAxis != null) { RectangleEdge edge = getDomainAxisEdge(i); space = xAxis.reserveSpace(g2, this, plotArea, edge, space); } } } return space; } /** * Calculates the space required for the range axis/axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param space a carrier for the result (<code>null</code> permitted). * * @return The required space. */ protected AxisSpace calculateRangeAxisSpace(Graphics2D g2, Rectangle2D plotArea, AxisSpace space) { if (space == null) { space = new AxisSpace(); } // reserve some space for the range axis... if (this.fixedRangeAxisSpace != null) { if (this.orientation == PlotOrientation.HORIZONTAL) { space.ensureAtLeast(this.fixedRangeAxisSpace.getTop(), RectangleEdge.TOP); space.ensureAtLeast(this.fixedRangeAxisSpace.getBottom(), RectangleEdge.BOTTOM); } else if (this.orientation == PlotOrientation.VERTICAL) { space.ensureAtLeast(this.fixedRangeAxisSpace.getLeft(), RectangleEdge.LEFT); space.ensureAtLeast(this.fixedRangeAxisSpace.getRight(), RectangleEdge.RIGHT); } } else { // reserve space for the range axes (if any)... for (int i = 0; i < this.rangeAxes.size(); i++) { Axis yAxis = this.rangeAxes.get(i); if (yAxis != null) { RectangleEdge edge = getRangeAxisEdge(i); space = yAxis.reserveSpace(g2, this, plotArea, edge, space); } } } return space; } /** * Trims a rectangle to integer coordinates. * * @param rect the incoming rectangle. * * @return A rectangle with integer coordinates. */ private Rectangle integerise(Rectangle2D rect) { int x0 = (int) Math.ceil(rect.getMinX()); int y0 = (int) Math.ceil(rect.getMinY()); int x1 = (int) Math.floor(rect.getMaxX()); int y1 = (int) Math.floor(rect.getMaxY()); return new Rectangle(x0, y0, (x1 - x0), (y1 - y0)); } /** * Calculates the space required for the axes. * * @param g2 the graphics device. * @param plotArea the plot area. * * @return The space required for the axes. */ protected AxisSpace calculateAxisSpace(Graphics2D g2, Rectangle2D plotArea) { AxisSpace space = new AxisSpace(); space = calculateRangeAxisSpace(g2, plotArea, space); space = calculateDomainAxisSpace(g2, plotArea, space); return space; } /** * Draws the plot on a Java 2D graphics device (such as the screen or a * printer). * <P> * At your option, you may supply an instance of {@link PlotRenderingInfo}. * If you do, it will be populated with information about the drawing, * including various plot dimensions and tooltip info. * * @param g2 the graphics device. * @param area the area within which the plot (including axes) should * be drawn. * @param anchor the anchor point (<code>null</code> permitted). * @param parentState the state from the parent plot, if there is one. * @param state collects info as the chart is drawn (possibly * <code>null</code>). */ @Override public void draw(Graphics2D g2, Rectangle2D area, Point2D anchor, PlotState parentState, PlotRenderingInfo state) { // if the plot area is too small, just return... boolean b1 = (area.getWidth() <= MINIMUM_WIDTH_TO_DRAW); boolean b2 = (area.getHeight() <= MINIMUM_HEIGHT_TO_DRAW); if (b1 || b2) { return; } // record the plot area... if (state == null) { // if the incoming state is null, no information will be passed // back to the caller - but we create a temporary state to record // the plot area, since that is used later by the axes state = new PlotRenderingInfo(null); } state.setPlotArea(area); // adjust the drawing area for the plot insets (if any)... RectangleInsets insets = getInsets(); insets.trim(area); // calculate the data area... AxisSpace space = calculateAxisSpace(g2, area); Rectangle2D dataArea = space.shrink(area, null); this.axisOffset.trim(dataArea); dataArea = integerise(dataArea); if (dataArea.isEmpty()) { return; } state.setDataArea(dataArea); createAndAddEntity((Rectangle2D) dataArea.clone(), state, null, null); // if there is a renderer, it draws the background, otherwise use the // default background... if (getRenderer() != null) { getRenderer().drawBackground(g2, this, dataArea); } else { drawBackground(g2, dataArea); } Map<Axis, AxisState> axisStateMap = drawAxes(g2, area, dataArea, state); // the anchor point is typically the point where the mouse last // clicked - the crosshairs will be driven off this point... if (anchor != null && !dataArea.contains(anchor)) { anchor = ShapeUtilities.getPointInRectangle(anchor.getX(), anchor.getY(), dataArea); } CategoryCrosshairState crosshairState = new CategoryCrosshairState(); crosshairState.setCrosshairDistance(Double.POSITIVE_INFINITY); crosshairState.setAnchor(anchor); // specify the anchor X and Y coordinates in Java2D space, for the // cases where these are not updated during rendering (i.e. no lock // on data) crosshairState.setAnchorX(Double.NaN); crosshairState.setAnchorY(Double.NaN); if (anchor != null) { ValueAxis rangeAxis = getRangeAxis(); if (rangeAxis != null) { double y; if (getOrientation() == PlotOrientation.VERTICAL) { y = rangeAxis.java2DToValue(anchor.getY(), dataArea, getRangeAxisEdge()); } else { y = rangeAxis.java2DToValue(anchor.getX(), dataArea, getRangeAxisEdge()); } crosshairState.setAnchorY(y); } } crosshairState.setRowKey(getDomainCrosshairRowKey()); crosshairState.setColumnKey(getDomainCrosshairColumnKey()); crosshairState.setCrosshairY(getRangeCrosshairValue()); // don't let anyone draw outside the data area Shape savedClip = g2.getClip(); g2.clip(dataArea); drawDomainGridlines(g2, dataArea); AxisState rangeAxisState = axisStateMap.get(getRangeAxis()); if (rangeAxisState == null) { if (parentState != null) { rangeAxisState = parentState.getSharedAxisStates() .get(getRangeAxis()); } } if (rangeAxisState != null) { drawRangeGridlines(g2, dataArea, rangeAxisState.getTicks()); drawZeroRangeBaseline(g2, dataArea); } Graphics2D savedG2 = g2; BufferedImage dataImage = null; if (this.shadowGenerator != null) { dataImage = new BufferedImage((int) dataArea.getWidth(), (int)dataArea.getHeight(), BufferedImage.TYPE_INT_ARGB); g2 = dataImage.createGraphics(); g2.translate(-dataArea.getX(), -dataArea.getY()); g2.setRenderingHints(savedG2.getRenderingHints()); } // draw the markers... for (int i = 0; i < this.renderers.size(); i++) { drawDomainMarkers(g2, dataArea, i, Layer.BACKGROUND); } for (int i = 0; i < this.renderers.size(); i++) { drawRangeMarkers(g2, dataArea, i, Layer.BACKGROUND); } // now render data items... boolean foundData = false; // set up the alpha-transparency... Composite originalComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, getForegroundAlpha())); DatasetRenderingOrder order = getDatasetRenderingOrder(); if (order == DatasetRenderingOrder.FORWARD) { for (int i = 0; i < this.datasets.size(); i++) { foundData = render(g2, dataArea, i, state, crosshairState) || foundData; } } else { // DatasetRenderingOrder.REVERSE for (int i = this.datasets.size() - 1; i >= 0; i foundData = render(g2, dataArea, i, state, crosshairState) || foundData; } } // draw the foreground markers... for (int i = 0; i < this.renderers.size(); i++) { drawDomainMarkers(g2, dataArea, i, Layer.FOREGROUND); } for (int i = 0; i < this.renderers.size(); i++) { drawRangeMarkers(g2, dataArea, i, Layer.FOREGROUND); } // draw the annotations (if any)... drawAnnotations(g2, dataArea); if (this.shadowGenerator != null) { BufferedImage shadowImage = this.shadowGenerator.createDropShadow( dataImage); g2 = savedG2; g2.drawImage(shadowImage, (int) dataArea.getX() + this.shadowGenerator.calculateOffsetX(), (int) dataArea.getY() + this.shadowGenerator.calculateOffsetY(), null); g2.drawImage(dataImage, (int) dataArea.getX(), (int) dataArea.getY(), null); } g2.setClip(savedClip); g2.setComposite(originalComposite); if (!foundData) { drawNoDataMessage(g2, dataArea); } int datasetIndex = crosshairState.getDatasetIndex(); setCrosshairDatasetIndex(datasetIndex, false); // draw domain crosshair if required... Comparable rowKey = crosshairState.getRowKey(); Comparable columnKey = crosshairState.getColumnKey(); setDomainCrosshairRowKey(rowKey, false); setDomainCrosshairColumnKey(columnKey, false); if (isDomainCrosshairVisible() && columnKey != null) { Paint paint = getDomainCrosshairPaint(); Stroke stroke = getDomainCrosshairStroke(); drawDomainCrosshair(g2, dataArea, this.orientation, datasetIndex, rowKey, columnKey, stroke, paint); } // draw range crosshair if required... ValueAxis yAxis = getRangeAxisForDataset(datasetIndex); RectangleEdge yAxisEdge = getRangeAxisEdge(); if (!this.rangeCrosshairLockedOnData && anchor != null) { double yy; if (getOrientation() == PlotOrientation.VERTICAL) { yy = yAxis.java2DToValue(anchor.getY(), dataArea, yAxisEdge); } else { yy = yAxis.java2DToValue(anchor.getX(), dataArea, yAxisEdge); } crosshairState.setCrosshairY(yy); } setRangeCrosshairValue(crosshairState.getCrosshairY(), false); if (isRangeCrosshairVisible()) { double y = getRangeCrosshairValue(); Paint paint = getRangeCrosshairPaint(); Stroke stroke = getRangeCrosshairStroke(); drawRangeCrosshair(g2, dataArea, getOrientation(), y, yAxis, stroke, paint); } // draw an outline around the plot area... if (isOutlineVisible()) { if (getRenderer() != null) { getRenderer().drawOutline(g2, this, dataArea); } else { drawOutline(g2, dataArea); } } } /** * Draws the plot background (the background color and/or image). * <P> * This method will be called during the chart drawing process and is * declared public so that it can be accessed by the renderers used by * certain subclasses. You shouldn't need to call this method directly. * * @param g2 the graphics device. * @param area the area within which the plot should be drawn. */ @Override public void drawBackground(Graphics2D g2, Rectangle2D area) { fillBackground(g2, area, this.orientation); drawBackgroundImage(g2, area); } /** * A utility method for drawing the plot's axes. * * @param g2 the graphics device. * @param plotArea the plot area. * @param dataArea the data area. * @param plotState collects information about the plot (<code>null</code> * permitted). * * @return A map containing the axis states. */ protected Map<Axis, AxisState> drawAxes(Graphics2D g2, Rectangle2D plotArea, Rectangle2D dataArea, PlotRenderingInfo plotState) { AxisCollection axisCollection = new AxisCollection(); // add domain axes to lists... for (int index = 0; index < this.domainAxes.size(); index++) { CategoryAxis xAxis = this.domainAxes.get(index); if (xAxis != null) { axisCollection.add(xAxis, getDomainAxisEdge(index)); } } // add range axes to lists... for (int index = 0; index < this.rangeAxes.size(); index++) { ValueAxis yAxis = this.rangeAxes.get(index); if (yAxis != null) { axisCollection.add(yAxis, getRangeAxisEdge(index)); } } Map<Axis, AxisState> axisStateMap = new HashMap<Axis, AxisState>(); // draw the top axes double cursor = dataArea.getMinY() - this.axisOffset.calculateTopOutset( dataArea.getHeight()); for (Axis axis : axisCollection.getAxesAtTop()) { if (axis != null) { AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.TOP, plotState); cursor = axisState.getCursor(); axisStateMap.put(axis, axisState); } } // draw the bottom axes cursor = dataArea.getMaxY() + this.axisOffset.calculateBottomOutset(dataArea.getHeight()); for (Axis axis : axisCollection.getAxesAtBottom()) { if (axis != null) { AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.BOTTOM, plotState); cursor = axisState.getCursor(); axisStateMap.put(axis, axisState); } } // draw the left axes cursor = dataArea.getMinX() - this.axisOffset.calculateLeftOutset(dataArea.getWidth()); for (Axis axis : axisCollection.getAxesAtLeft()) { if (axis != null) { AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.LEFT, plotState); cursor = axisState.getCursor(); axisStateMap.put(axis, axisState); } } // draw the right axes cursor = dataArea.getMaxX() + this.axisOffset.calculateRightOutset(dataArea.getWidth()); for (Axis axis : axisCollection.getAxesAtRight()) { if (axis != null) { AxisState axisState = axis.draw(g2, cursor, plotArea, dataArea, RectangleEdge.RIGHT, plotState); cursor = axisState.getCursor(); axisStateMap.put(axis, axisState); } } return axisStateMap; } /** * Draws a representation of a dataset within the dataArea region using the * appropriate renderer. * * @param g2 the graphics device. * @param dataArea the region in which the data is to be drawn. * @param index the dataset and renderer index. * @param info an optional object for collection dimension information. * @param crosshairState a state object for tracking crosshair info * (<code>null</code> permitted). * * @return A boolean that indicates whether or not real data was found. * * @since 1.0.11 */ public boolean render(Graphics2D g2, Rectangle2D dataArea, int index, PlotRenderingInfo info, CategoryCrosshairState crosshairState) { boolean foundData = false; CategoryDataset currentDataset = getDataset(index); CategoryItemRenderer renderer = getRenderer(index); CategoryAxis domainAxis = getDomainAxisForDataset(index); ValueAxis rangeAxis = getRangeAxisForDataset(index); boolean hasData = !DatasetUtilities.isEmptyOrNull(currentDataset); if (hasData && renderer != null) { foundData = true; CategoryItemRendererState state = renderer.initialise(g2, dataArea, this, index, info); state.setCrosshairState(crosshairState); int columnCount = currentDataset.getColumnCount(); int rowCount = currentDataset.getRowCount(); int passCount = renderer.getPassCount(); for (int pass = 0; pass < passCount; pass++) { if (this.columnRenderingOrder == SortOrder.ASCENDING) { for (int column = 0; column < columnCount; column++) { if (this.rowRenderingOrder == SortOrder.ASCENDING) { for (int row = 0; row < rowCount; row++) { renderer.drawItem(g2, state, dataArea, this, domainAxis, rangeAxis, currentDataset, row, column, pass); } } else { for (int row = rowCount - 1; row >= 0; row renderer.drawItem(g2, state, dataArea, this, domainAxis, rangeAxis, currentDataset, row, column, pass); } } } } else { for (int column = columnCount - 1; column >= 0; column if (this.rowRenderingOrder == SortOrder.ASCENDING) { for (int row = 0; row < rowCount; row++) { renderer.drawItem(g2, state, dataArea, this, domainAxis, rangeAxis, currentDataset, row, column, pass); } } else { for (int row = rowCount - 1; row >= 0; row renderer.drawItem(g2, state, dataArea, this, domainAxis, rangeAxis, currentDataset, row, column, pass); } } } } } } return foundData; } /** * Draws the domain gridlines for the plot, if they are visible. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * * @see #drawRangeGridlines(Graphics2D, Rectangle2D, List) */ protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea) { if (!isDomainGridlinesVisible()) { return; } CategoryAnchor anchor = getDomainGridlinePosition(); RectangleEdge domainAxisEdge = getDomainAxisEdge(); CategoryDataset dataset = getDataset(); if (dataset == null) { return; } CategoryAxis axis = getDomainAxis(); if (axis != null) { int columnCount = dataset.getColumnCount(); for (int c = 0; c < columnCount; c++) { double xx = axis.getCategoryJava2DCoordinate(anchor, c, columnCount, dataArea, domainAxisEdge); CategoryItemRenderer renderer1 = getRenderer(); if (renderer1 != null) { renderer1.drawDomainGridline(g2, this, dataArea, xx); } } } } /** * Draws the range gridlines for the plot, if they are visible. * * @param g2 the graphics device. * @param dataArea the area inside the axes. * @param ticks the ticks. * * @see #drawDomainGridlines(Graphics2D, Rectangle2D) */ protected void drawRangeGridlines(Graphics2D g2, Rectangle2D dataArea, List<ValueTick> ticks) { // draw the range grid lines, if any... if (!isRangeGridlinesVisible() && !isRangeMinorGridlinesVisible()) { return; } // no axis, no gridlines... ValueAxis axis = getRangeAxis(); if (axis == null) { return; } // no renderer, no gridlines... CategoryItemRenderer r = getRenderer(); if (r == null) { return; } Stroke gridStroke = null; Paint gridPaint = null; boolean paintLine; for (ValueTick tick : ticks) { paintLine = false; if ((tick.getTickType() == TickType.MINOR) && isRangeMinorGridlinesVisible()) { gridStroke = getRangeMinorGridlineStroke(); gridPaint = getRangeMinorGridlinePaint(); paintLine = true; } else if ((tick.getTickType() == TickType.MAJOR) && isRangeGridlinesVisible()) { gridStroke = getRangeGridlineStroke(); gridPaint = getRangeGridlinePaint(); paintLine = true; } if (((tick.getValue() != 0.0) || !isRangeZeroBaselineVisible()) && paintLine) { // the method we want isn't in the CategoryItemRenderer // interface... if (r instanceof AbstractCategoryItemRenderer) { AbstractCategoryItemRenderer aci = (AbstractCategoryItemRenderer) r; aci.drawRangeGridline(g2, this, axis, dataArea, tick.getValue(), gridPaint, gridStroke); } else { // we'll have to use the method in the interface, but // this doesn't have the paint and stroke settings... r.drawRangeGridline(g2, this, axis, dataArea, tick.getValue()); } } } } /** * Draws a base line across the chart at value zero on the range axis. * * @param g2 the graphics device. * @param area the data area. * * @see #setRangeZeroBaselineVisible(boolean) * * @since 1.0.13 */ protected void drawZeroRangeBaseline(Graphics2D g2, Rectangle2D area) { if (!isRangeZeroBaselineVisible()) { return; } CategoryItemRenderer r = getRenderer(); if (r instanceof AbstractCategoryItemRenderer) { AbstractCategoryItemRenderer aci = (AbstractCategoryItemRenderer) r; aci.drawRangeGridline(g2, this, getRangeAxis(), area, 0.0, this.rangeZeroBaselinePaint, this.rangeZeroBaselineStroke); } else { r.drawRangeGridline(g2, this, getRangeAxis(), area, 0.0); } } /** * Draws the annotations. * * @param g2 the graphics device. * @param dataArea the data area. */ protected void drawAnnotations(Graphics2D g2, Rectangle2D dataArea) { if (getAnnotations() != null) { for (CategoryAnnotation annotation : getAnnotations()) { annotation.draw(g2, this, dataArea, getDomainAxis(), getRangeAxis()); } } } /** * Draws the domain markers (if any) for an axis and layer. This method is * typically called from within the draw() method. * * @param g2 the graphics device. * @param dataArea the data area. * @param index the renderer index. * @param layer the layer (foreground or background). * * @see #drawRangeMarkers(Graphics2D, Rectangle2D, int, Layer) */ protected void drawDomainMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer) { CategoryItemRenderer r = getRenderer(index); if (r == null) { return; } Collection<Marker> markers = getDomainMarkers(index, layer); CategoryAxis axis = getDomainAxisForDataset(index); if (markers != null && axis != null) { for (Marker marker1 : markers) { CategoryMarker marker = (CategoryMarker) marker1; r.drawDomainMarker(g2, this, axis, marker, dataArea); } } } /** * Draws the range markers (if any) for an axis and layer. This method is * typically called from within the draw() method. * * @param g2 the graphics device. * @param dataArea the data area. * @param index the renderer index. * @param layer the layer (foreground or background). * * @see #drawDomainMarkers(Graphics2D, Rectangle2D, int, Layer) */ protected void drawRangeMarkers(Graphics2D g2, Rectangle2D dataArea, int index, Layer layer) { CategoryItemRenderer r = getRenderer(index); if (r == null) { return; } Collection<Marker> markers = getRangeMarkers(index, layer); ValueAxis axis = getRangeAxisForDataset(index); if (markers != null && axis != null) { for (Marker marker : markers) { r.drawRangeMarker(g2, this, axis, marker, dataArea); } } } /** * Utility method for drawing a line perpendicular to the range axis (used * for crosshairs). * * @param g2 the graphics device. * @param dataArea the area defined by the axes. * @param value the data value. * @param stroke the line stroke (<code>null</code> not permitted). * @param paint the line paint (<code>null</code> not permitted). */ protected void drawRangeLine(Graphics2D g2, Rectangle2D dataArea, double value, Stroke stroke, Paint paint) { double java2D = getRangeAxis().valueToJava2D(value, dataArea, getRangeAxisEdge()); Line2D line = null; if (this.orientation == PlotOrientation.HORIZONTAL) { line = new Line2D.Double(java2D, dataArea.getMinY(), java2D, dataArea.getMaxY()); } else if (this.orientation == PlotOrientation.VERTICAL) { line = new Line2D.Double(dataArea.getMinX(), java2D, dataArea.getMaxX(), java2D); } g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } /** * Draws a domain crosshair. * * @param g2 the graphics target. * @param dataArea the data area. * @param orientation the plot orientation. * @param datasetIndex the dataset index. * @param rowKey the row key. * @param columnKey the column key. * @param stroke the stroke used to draw the crosshair line. * @param paint the paint used to draw the crosshair line. * * @see #drawRangeCrosshair(Graphics2D, Rectangle2D, PlotOrientation, * double, ValueAxis, Stroke, Paint) * * @since 1.0.11 */ protected void drawDomainCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, int datasetIndex, Comparable rowKey, Comparable columnKey, Stroke stroke, Paint paint) { CategoryDataset dataset = getDataset(datasetIndex); CategoryAxis axis = getDomainAxisForDataset(datasetIndex); CategoryItemRenderer renderer = getRenderer(datasetIndex); Line2D line; if (orientation == PlotOrientation.VERTICAL) { double xx = renderer.getItemMiddle(rowKey, columnKey, dataset, axis, dataArea, RectangleEdge.BOTTOM); line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); } else { double yy = renderer.getItemMiddle(rowKey, columnKey, dataset, axis, dataArea, RectangleEdge.LEFT); line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); } g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } /** * Draws a range crosshair. * * @param g2 the graphics target. * @param dataArea the data area. * @param orientation the plot orientation. * @param value the crosshair value. * @param axis the axis against which the value is measured. * @param stroke the stroke used to draw the crosshair line. * @param paint the paint used to draw the crosshair line. * * @see #drawDomainCrosshair(Graphics2D, Rectangle2D, PlotOrientation, int, * Comparable, Comparable, Stroke, Paint) * * @since 1.0.5 */ protected void drawRangeCrosshair(Graphics2D g2, Rectangle2D dataArea, PlotOrientation orientation, double value, ValueAxis axis, Stroke stroke, Paint paint) { if (!axis.getRange().contains(value)) { return; } Line2D line; if (orientation == PlotOrientation.HORIZONTAL) { double xx = axis.valueToJava2D(value, dataArea, RectangleEdge.BOTTOM); line = new Line2D.Double(xx, dataArea.getMinY(), xx, dataArea.getMaxY()); } else { double yy = axis.valueToJava2D(value, dataArea, RectangleEdge.LEFT); line = new Line2D.Double(dataArea.getMinX(), yy, dataArea.getMaxX(), yy); } g2.setStroke(stroke); g2.setPaint(paint); g2.draw(line); } /** * Returns the range of data values that will be plotted against the range * axis. If the dataset is <code>null</code>, this method returns * <code>null</code>. * * @param axis the axis. * * @return The data range. */ @Override public Range getDataRange(ValueAxis axis) { Range result = null; List<CategoryDataset> mappedDatasets = new ArrayList<CategoryDataset>(); int rangeIndex = this.rangeAxes.indexOf(axis); if (rangeIndex >= 0) { mappedDatasets.addAll(datasetsMappedToRangeAxis(rangeIndex)); } else if (axis == getRangeAxis()) { mappedDatasets.addAll(datasetsMappedToRangeAxis(0)); } // iterate through the datasets that map to the axis and get the union // of the ranges. for (CategoryDataset d : mappedDatasets) { CategoryItemRenderer r = getRendererForDataset(d); if (r != null) { result = Range.combine(result, r.findRangeBounds(d)); } } return result; } /** * Returns a list of the datasets that are mapped to the axis with the * specified index. * * @param axisIndex the axis index. * * @return The list (possibly empty, but never <code>null</code>). * * @since 1.0.3 */ private List<CategoryDataset> datasetsMappedToDomainAxis(int axisIndex) { Integer key = axisIndex; List<CategoryDataset> result = new ArrayList<CategoryDataset>(); for (int i = 0; i < this.datasets.size(); i++) { List<Integer> mappedAxes = this.datasetToDomainAxesMap.get( Integer.valueOf(i)); CategoryDataset dataset = this.datasets.get(i); if (mappedAxes == null) { if (key.equals(ZERO)) { if (dataset != null) { result.add(dataset); } } } else { if (mappedAxes.contains(key)) { if (dataset != null) { result.add(dataset); } } } } return result; } /** * A utility method that returns a list of datasets that are mapped to a * given range axis. * * @param index the axis index. * * @return A list of datasets. */ private List<CategoryDataset> datasetsMappedToRangeAxis(int index) { Integer key = index; List<CategoryDataset> result = new ArrayList<CategoryDataset>(); for (int i = 0; i < this.datasets.size(); i++) { List<Integer> mappedAxes = this.datasetToRangeAxesMap.get( Integer.valueOf(i)); if (mappedAxes == null) { if (key.equals(ZERO)) { result.add(this.datasets.get(i)); } } else { if (mappedAxes.contains(key)) { result.add(this.datasets.get(i)); } } } return result; } /** * Returns the weight for this plot when it is used as a subplot within a * combined plot. * * @return The weight. * * @see #setWeight(int) */ public int getWeight() { return this.weight; } /** * Sets the weight for the plot and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param weight the weight. * * @see #getWeight() */ public void setWeight(int weight) { this.weight = weight; fireChangeEvent(); } /** * Returns the fixed domain axis space. * * @return The fixed domain axis space (possibly <code>null</code>). * * @see #setFixedDomainAxisSpace(AxisSpace) */ public AxisSpace getFixedDomainAxisSpace() { return this.fixedDomainAxisSpace; } /** * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space (<code>null</code> permitted). * * @see #getFixedDomainAxisSpace() */ public void setFixedDomainAxisSpace(AxisSpace space) { setFixedDomainAxisSpace(space, true); } /** * Sets the fixed domain axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space (<code>null</code> permitted). * @param notify notify listeners? * * @see #getFixedDomainAxisSpace() * * @since 1.0.7 */ public void setFixedDomainAxisSpace(AxisSpace space, boolean notify) { this.fixedDomainAxisSpace = space; if (notify) { fireChangeEvent(); } } /** * Returns the fixed range axis space. * * @return The fixed range axis space (possibly <code>null</code>). * * @see #setFixedRangeAxisSpace(AxisSpace) */ public AxisSpace getFixedRangeAxisSpace() { return this.fixedRangeAxisSpace; } /** * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space (<code>null</code> permitted). * * @see #getFixedRangeAxisSpace() */ public void setFixedRangeAxisSpace(AxisSpace space) { setFixedRangeAxisSpace(space, true); } /** * Sets the fixed range axis space and sends a {@link PlotChangeEvent} to * all registered listeners. * * @param space the space (<code>null</code> permitted). * @param notify notify listeners? * * @see #getFixedRangeAxisSpace() * * @since 1.0.7 */ public void setFixedRangeAxisSpace(AxisSpace space, boolean notify) { this.fixedRangeAxisSpace = space; if (notify) { fireChangeEvent(); } } /** * Returns a list of the categories in the plot's primary dataset. * * @return A list of the categories in the plot's primary dataset. * * @see #getCategoriesForAxis(CategoryAxis) */ public List<Comparable> getCategories() { List<Comparable> result = null; if (getDataset() != null) { result = Collections.unmodifiableList(getDataset().getColumnKeys()); } return result; } /** * Returns a list of the categories that should be displayed for the * specified axis. * * @param axis the axis (<code>null</code> not permitted) * * @return The categories. * * @since 1.0.3 */ public List<Comparable> getCategoriesForAxis(CategoryAxis axis) { List<Comparable> result = new ArrayList<Comparable>(); int axisIndex = this.domainAxes.indexOf(axis); List<CategoryDataset> datasets = datasetsMappedToDomainAxis(axisIndex); for (CategoryDataset dataset : datasets) { // add the unique categories from this dataset for (int i = 0; i < dataset.getColumnCount(); i++) { Comparable category = dataset.getColumnKey(i); if (!result.contains(category)) { result.add(category); } } } return result; } /** * Returns the flag that controls whether or not the shared domain axis is * drawn for each subplot. * * @return A boolean. * * @see #setDrawSharedDomainAxis(boolean) */ public boolean getDrawSharedDomainAxis() { return this.drawSharedDomainAxis; } /** * Sets the flag that controls whether the shared domain axis is drawn when * this plot is being used as a subplot. * * @param draw a boolean. * * @see #getDrawSharedDomainAxis() */ public void setDrawSharedDomainAxis(boolean draw) { this.drawSharedDomainAxis = draw; fireChangeEvent(); } /** * Returns <code>false</code> always, because the plot cannot be panned * along the domain axis/axes. * * @return A boolean. * * @see #isRangePannable() * * @since 1.0.13 */ @Override public boolean isDomainPannable() { return false; } /** * Returns <code>true</code> if panning is enabled for the range axes, * and <code>false</code> otherwise. * * @return A boolean. * * @see #setRangePannable(boolean) * @see #isDomainPannable() * * @since 1.0.13 */ @Override public boolean isRangePannable() { return this.rangePannable; } /** * Sets the flag that enables or disables panning of the plot along * the range axes. * * @param pannable the new flag value. * * @see #isRangePannable() * * @since 1.0.13 */ public void setRangePannable(boolean pannable) { this.rangePannable = pannable; } /** * Pans the domain axes by the specified percentage. * * @param percent the distance to pan (as a percentage of the axis length). * @param info the plot info * @param source the source point where the pan action started. * * @since 1.0.13 */ @Override public void panDomainAxes(double percent, PlotRenderingInfo info, Point2D source) { // do nothing, because the plot is not pannable along the domain axes } /** * Pans the range axes by the specified percentage. * * @param percent the distance to pan (as a percentage of the axis length). * @param info the plot info * @param source the source point where the pan action started. * * @since 1.0.13 */ @Override public void panRangeAxes(double percent, PlotRenderingInfo info, Point2D source) { if (!isRangePannable()) { return; } int rangeAxisCount = getRangeAxisCount(); for (int i = 0; i < rangeAxisCount; i++) { ValueAxis axis = getRangeAxis(i); if (axis == null) { continue; } double length = axis.getRange().getLength(); double adj = percent * length; if (axis.isInverted()) { adj = -adj; } axis.setRange(axis.getLowerBound() + adj, axis.getUpperBound() + adj); } } /** * Returns <code>false</code> to indicate that the domain axes are not * zoomable. * * @return A boolean. * * @see #isRangeZoomable() */ @Override public boolean isDomainZoomable() { return false; } /** * Returns <code>true</code> to indicate that the range axes are zoomable. * * @return A boolean. * * @see #isDomainZoomable() */ @Override public boolean isRangeZoomable() { return true; } /** * This method does nothing, because <code>CategoryPlot</code> doesn't * support zooming on the domain. * * @param factor the zoom factor. * @param state the plot state. * @param source the source point (in Java2D space) for the zoom. */ @Override public void zoomDomainAxes(double factor, PlotRenderingInfo state, Point2D source) { // can't zoom domain axis } /** * This method does nothing, because <code>CategoryPlot</code> doesn't * support zooming on the domain. * * @param lowerPercent the lower bound. * @param upperPercent the upper bound. * @param state the plot state. * @param source the source point (in Java2D space) for the zoom. */ @Override public void zoomDomainAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source) { // can't zoom domain axis } /** * This method does nothing, because <code>CategoryPlot</code> doesn't * support zooming on the domain. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point (in Java2D space). * @param useAnchor use source point as zoom anchor? * * @see #zoomRangeAxes(double, PlotRenderingInfo, Point2D, boolean) * * @since 1.0.7 */ @Override public void zoomDomainAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor) { // can't zoom domain axis } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param factor the zoom factor. * @param state the plot state. * @param source the source point (in Java2D space) for the zoom. */ @Override public void zoomRangeAxes(double factor, PlotRenderingInfo state, Point2D source) { // delegate to other method zoomRangeAxes(factor, state, source, false); } /** * Multiplies the range on the range axis/axes by the specified factor. * * @param factor the zoom factor. * @param info the plot rendering info. * @param source the source point. * @param useAnchor a flag that controls whether or not the source point * is used for the zoom anchor. * * @see #zoomDomainAxes(double, PlotRenderingInfo, Point2D, boolean) * * @since 1.0.7 */ @Override public void zoomRangeAxes(double factor, PlotRenderingInfo info, Point2D source, boolean useAnchor) { // perform the zoom on each range axis for (int i = 0; i < this.rangeAxes.size(); i++) { ValueAxis rangeAxis = this.rangeAxes.get(i); if (rangeAxis != null) { if (useAnchor) { // get the relevant source coordinate given the plot // orientation double sourceY = source.getY(); if (this.orientation == PlotOrientation.HORIZONTAL) { sourceY = source.getX(); } double anchorY = rangeAxis.java2DToValue(sourceY, info.getDataArea(), getRangeAxisEdge()); rangeAxis.resizeRange2(factor, anchorY); } else { rangeAxis.resizeRange(factor); } } } } /** * Zooms in on the range axes. * * @param lowerPercent the lower bound. * @param upperPercent the upper bound. * @param state the plot state. * @param source the source point (in Java2D space) for the zoom. */ @Override public void zoomRangeAxes(double lowerPercent, double upperPercent, PlotRenderingInfo state, Point2D source) { for (int i = 0; i < this.rangeAxes.size(); i++) { ValueAxis rangeAxis = this.rangeAxes.get(i); if (rangeAxis != null) { rangeAxis.zoomRange(lowerPercent, upperPercent); } } } /** * Returns the anchor value. * * @return The anchor value. * * @see #setAnchorValue(double) */ public double getAnchorValue() { return this.anchorValue; } /** * Sets the anchor value and sends a {@link PlotChangeEvent} to all * registered listeners. * * @param value the anchor value. * * @see #getAnchorValue() */ public void setAnchorValue(double value) { setAnchorValue(value, true); } /** * Sets the anchor value and, if requested, sends a {@link PlotChangeEvent} * to all registered listeners. * * @param value the value. * @param notify notify listeners? * * @see #getAnchorValue() */ public void setAnchorValue(double value, boolean notify) { this.anchorValue = value; if (notify) { fireChangeEvent(); } } /** * Tests the plot for equality with an arbitrary object. * * @param obj the object to test against (<code>null</code> permitted). * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof CategoryPlot)) { return false; } CategoryPlot that = (CategoryPlot) obj; if (this.orientation != that.orientation) { return false; } if (!ObjectUtilities.equal(this.axisOffset, that.axisOffset)) { return false; } if (!this.domainAxes.equals(that.domainAxes)) { return false; } if (!this.domainAxisLocations.equals(that.domainAxisLocations)) { return false; } if (this.drawSharedDomainAxis != that.drawSharedDomainAxis) { return false; } if (!this.rangeAxes.equals(that.rangeAxes)) { return false; } if (!this.rangeAxisLocations.equals(that.rangeAxisLocations)) { return false; } if (!ObjectUtilities.equal(this.datasetToDomainAxesMap, that.datasetToDomainAxesMap)) { return false; } if (!ObjectUtilities.equal(this.datasetToRangeAxesMap, that.datasetToRangeAxesMap)) { return false; } if (!ObjectUtilities.equal(this.renderers, that.renderers)) { return false; } if (this.renderingOrder != that.renderingOrder) { return false; } if (this.columnRenderingOrder != that.columnRenderingOrder) { return false; } if (this.rowRenderingOrder != that.rowRenderingOrder) { return false; } if (this.domainGridlinesVisible != that.domainGridlinesVisible) { return false; } if (this.domainGridlinePosition != that.domainGridlinePosition) { return false; } if (!ObjectUtilities.equal(this.domainGridlineStroke, that.domainGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.domainGridlinePaint, that.domainGridlinePaint)) { return false; } if (this.rangeGridlinesVisible != that.rangeGridlinesVisible) { return false; } if (!ObjectUtilities.equal(this.rangeGridlineStroke, that.rangeGridlineStroke)) { return false; } if (!PaintUtilities.equal(this.rangeGridlinePaint, that.rangeGridlinePaint)) { return false; } if (this.anchorValue != that.anchorValue) { return false; } if (this.rangeCrosshairVisible != that.rangeCrosshairVisible) { return false; } if (this.rangeCrosshairValue != that.rangeCrosshairValue) { return false; } if (!ObjectUtilities.equal(this.rangeCrosshairStroke, that.rangeCrosshairStroke)) { return false; } if (!PaintUtilities.equal(this.rangeCrosshairPaint, that.rangeCrosshairPaint)) { return false; } if (this.rangeCrosshairLockedOnData != that.rangeCrosshairLockedOnData) { return false; } if (!ObjectUtilities.equal(this.foregroundDomainMarkers, that.foregroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundDomainMarkers, that.backgroundDomainMarkers)) { return false; } if (!ObjectUtilities.equal(this.foregroundRangeMarkers, that.foregroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.backgroundRangeMarkers, that.backgroundRangeMarkers)) { return false; } if (!ObjectUtilities.equal(this.annotations, that.annotations)) { return false; } if (this.weight != that.weight) { return false; } if (!ObjectUtilities.equal(this.fixedDomainAxisSpace, that.fixedDomainAxisSpace)) { return false; } if (!ObjectUtilities.equal(this.fixedRangeAxisSpace, that.fixedRangeAxisSpace)) { return false; } if (!ObjectUtilities.equal(this.fixedLegendItems, that.fixedLegendItems)) { return false; } if (this.domainCrosshairVisible != that.domainCrosshairVisible) { return false; } if (this.crosshairDatasetIndex != that.crosshairDatasetIndex) { return false; } if (!ObjectUtilities.equal(this.domainCrosshairColumnKey, that.domainCrosshairColumnKey)) { return false; } if (!ObjectUtilities.equal(this.domainCrosshairRowKey, that.domainCrosshairRowKey)) { return false; } if (!PaintUtilities.equal(this.domainCrosshairPaint, that.domainCrosshairPaint)) { return false; } if (!ObjectUtilities.equal(this.domainCrosshairStroke, that.domainCrosshairStroke)) { return false; } if (this.rangeMinorGridlinesVisible != that.rangeMinorGridlinesVisible) { return false; } if (!PaintUtilities.equal(this.rangeMinorGridlinePaint, that.rangeMinorGridlinePaint)) { return false; } if (!ObjectUtilities.equal(this.rangeMinorGridlineStroke, that.rangeMinorGridlineStroke)) { return false; } if (this.rangeZeroBaselineVisible != that.rangeZeroBaselineVisible) { return false; } if (!PaintUtilities.equal(this.rangeZeroBaselinePaint, that.rangeZeroBaselinePaint)) { return false; } if (!ObjectUtilities.equal(this.rangeZeroBaselineStroke, that.rangeZeroBaselineStroke)) { return false; } if (!ObjectUtilities.equal(this.shadowGenerator, that.shadowGenerator)) { return false; } return super.equals(obj); } /** * Returns a clone of the plot. * * @return A clone. * * @throws CloneNotSupportedException if the cloning is not supported. */ @Override public Object clone() throws CloneNotSupportedException { CategoryPlot clone = (CategoryPlot) super.clone(); clone.domainAxes = new ObjectList<CategoryAxis>(); for (int i = 0; i < this.domainAxes.size(); i++) { CategoryAxis xAxis = this.domainAxes.get(i); if (xAxis != null) { CategoryAxis clonedAxis = (CategoryAxis) xAxis.clone(); clone.setDomainAxis(i, clonedAxis); } } clone.domainAxisLocations = (ObjectList<AxisLocation>) this.domainAxisLocations.clone(); clone.rangeAxes = new ObjectList<ValueAxis>(); for (int i = 0; i < this.rangeAxes.size(); i++) { ValueAxis yAxis = this.rangeAxes.get(i); if (yAxis != null) { ValueAxis clonedAxis = (ValueAxis) yAxis.clone(); clone.setRangeAxis(i, clonedAxis); } } clone.rangeAxisLocations = (ObjectList<AxisLocation>) this.rangeAxisLocations.clone(); clone.datasets = (ObjectList<CategoryDataset>) this.datasets.clone(); for (int i = 0; i < clone.datasets.size(); i++) { CategoryDataset dataset = clone.getDataset(i); if (dataset != null) { dataset.addChangeListener(clone); } } clone.datasetToDomainAxesMap = new TreeMap<Integer, List<Integer>>(); clone.datasetToDomainAxesMap.putAll(this.datasetToDomainAxesMap); clone.datasetToRangeAxesMap = new TreeMap<Integer, List<Integer>>(); clone.datasetToRangeAxesMap.putAll(this.datasetToRangeAxesMap); clone.renderers = (ObjectList<CategoryItemRenderer>) this.renderers.clone(); for (int i = 0; i < this.renderers.size(); i++) { CategoryItemRenderer renderer2 = this.renderers.get(i); if (renderer2 instanceof PublicCloneable) { PublicCloneable pc = (PublicCloneable) renderer2; CategoryItemRenderer rc = (CategoryItemRenderer) pc.clone(); clone.renderers.set(i, rc); rc.setPlot(clone); rc.addChangeListener(clone); } } if (this.fixedDomainAxisSpace != null) { clone.fixedDomainAxisSpace = ObjectUtilities.clone( this.fixedDomainAxisSpace); } if (this.fixedRangeAxisSpace != null) { clone.fixedRangeAxisSpace = ObjectUtilities.clone( this.fixedRangeAxisSpace); } clone.annotations = ObjectUtilities.deepClone(this.annotations); clone.foregroundDomainMarkers = cloneMarkerMap( this.foregroundDomainMarkers); clone.backgroundDomainMarkers = cloneMarkerMap( this.backgroundDomainMarkers); clone.foregroundRangeMarkers = cloneMarkerMap( this.foregroundRangeMarkers); clone.backgroundRangeMarkers = cloneMarkerMap( this.backgroundRangeMarkers); if (this.fixedLegendItems != null) { clone.fixedLegendItems = (LegendItemCollection) this.fixedLegendItems.clone(); } return clone; } /** * A utility method to clone the marker maps. * * @param map the map to clone. * * @return A clone of the map. * * @throws CloneNotSupportedException if there is some problem cloning the * map. */ private Map<Integer, Collection<Marker>> cloneMarkerMap(Map<Integer, Collection<Marker>> map) throws CloneNotSupportedException { Map<Integer, Collection<Marker>> clone = new HashMap<Integer, Collection<Marker>>(); Set<Integer> keys = map.keySet(); for (Integer key : keys) { Collection<Marker> entry = map.get(key); Collection<Marker> toAdd = ObjectUtilities.<Marker, Collection<Marker>>deepClone(entry); clone.put(key, toAdd); } return clone; } /** * Provides serialization support. * * @param stream the output stream. * * @throws IOException if there is an I/O error. */ private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); SerialUtilities.writeStroke(this.domainGridlineStroke, stream); SerialUtilities.writePaint(this.domainGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeGridlineStroke, stream); SerialUtilities.writePaint(this.rangeGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeCrosshairStroke, stream); SerialUtilities.writePaint(this.rangeCrosshairPaint, stream); SerialUtilities.writeStroke(this.domainCrosshairStroke, stream); SerialUtilities.writePaint(this.domainCrosshairPaint, stream); SerialUtilities.writeStroke(this.rangeMinorGridlineStroke, stream); SerialUtilities.writePaint(this.rangeMinorGridlinePaint, stream); SerialUtilities.writeStroke(this.rangeZeroBaselineStroke, stream); SerialUtilities.writePaint(this.rangeZeroBaselinePaint, stream); } /** * Provides serialization support. * * @param stream the input stream. * * @throws IOException if there is an I/O error. * @throws ClassNotFoundException if there is a classpath problem. */ private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.domainGridlineStroke = SerialUtilities.readStroke(stream); this.domainGridlinePaint = SerialUtilities.readPaint(stream); this.rangeGridlineStroke = SerialUtilities.readStroke(stream); this.rangeGridlinePaint = SerialUtilities.readPaint(stream); this.rangeCrosshairStroke = SerialUtilities.readStroke(stream); this.rangeCrosshairPaint = SerialUtilities.readPaint(stream); this.domainCrosshairStroke = SerialUtilities.readStroke(stream); this.domainCrosshairPaint = SerialUtilities.readPaint(stream); this.rangeMinorGridlineStroke = SerialUtilities.readStroke(stream); this.rangeMinorGridlinePaint = SerialUtilities.readPaint(stream); this.rangeZeroBaselineStroke = SerialUtilities.readStroke(stream); this.rangeZeroBaselinePaint = SerialUtilities.readPaint(stream); for (int i = 0; i < this.domainAxes.size(); i++) { CategoryAxis xAxis = this.domainAxes.get(i); if (xAxis != null) { xAxis.setPlot(this); xAxis.addChangeListener(this); } } for (int i = 0; i < this.rangeAxes.size(); i++) { ValueAxis yAxis = this.rangeAxes.get(i); if (yAxis != null) { yAxis.setPlot(this); yAxis.addChangeListener(this); } } int datasetCount = this.datasets.size(); for (int i = 0; i < datasetCount; i++) { Dataset dataset = this.datasets.get(i); if (dataset != null) { dataset.addChangeListener(this); } } int rendererCount = this.renderers.size(); for (int i = 0; i < rendererCount; i++) { CategoryItemRenderer renderer = this.renderers.get(i); if (renderer != null) { renderer.addChangeListener(this); } } } }
package org.lightmare.cache; import static org.lightmare.jpa.JPAManager.closeEntityManagerFactories; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.persistence.EntityManagerFactory; import javax.transaction.UserTransaction; import org.apache.log4j.Logger; import org.glassfish.jersey.server.model.Resource; import org.lightmare.config.Configuration; import org.lightmare.deploy.MetaCreator; import org.lightmare.ejb.exceptions.BeanInUseException; import org.lightmare.jpa.JPAManager; import org.lightmare.libraries.LibraryLoader; import org.lightmare.rest.utils.RestUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.WatchUtils; /** * Container class to save {@link MetaData} for bean interface {@link Class} and * connections {@link EntityManagerFactory}es for unit names * * @author Levan * */ public class MetaContainer { // Cached instance of MetaCreator private static MetaCreator creator; /** * {@link Configuration} container class for server */ public static final Map<String, Configuration> CONFIGS = new ConcurrentHashMap<String, Configuration>(); // Cached bean meta data private static final ConcurrentMap<String, MetaData> EJBS = new ConcurrentHashMap<String, MetaData>(); // Cached bean class name by its URL for undeploy processing private static final ConcurrentMap<URL, Collection<String>> EJB_URLS = new ConcurrentHashMap<URL, Collection<String>>(); // Cached REST resource classes private static final ConcurrentMap<Class<?>, Resource> REST_RESOURCES = new ConcurrentHashMap<Class<?>, Resource>(); // Caches UserTransaction object per thread private static final ThreadLocal<UserTransaction> TRANSACTION_HOLDER = new ThreadLocal<UserTransaction>(); private static final Logger LOG = Logger.getLogger(MetaContainer.class); /** * Gets cached {@link MetaCreator} object * * @return */ public static MetaCreator getCreator() { synchronized (MetaContainer.class) { return creator; } } /** * Caches {@link MetaCreator} object * * @param metaCreator */ public static void setCreator(MetaCreator metaCreator) { synchronized (MetaContainer.class) { creator = metaCreator; } } /** * Removes all cached resources */ public static void clear() { if (ObjectUtils.notNull(creator)) { synchronized (MetaContainer.class) { creator.clear(); creator = null; } } } /** * Caches {@link Configuration} for specific {@link URL} array * * @param archives * @param config */ public static void putConfig(URL[] archives, Configuration config) { if (ObjectUtils.available(archives)) { for (URL archive : archives) { String path = WatchUtils.clearPath(archive.getFile()); if (CONFIGS.containsKey(path)) { continue; } CONFIGS.put(path, config); } } } /** * Gets {@link Configuration} from cache for specific {@link URL} array * * @param archives * @param config */ public static Configuration getConfig(URL[] archives) { Configuration config; URL archive = ObjectUtils.getFirst(archives); if (ObjectUtils.notNull(archive)) { String path = WatchUtils.clearPath(archive.getFile()); config = CONFIGS.get(path); } else { config = null; } return config; } /** * Adds {@link MetaData} to cache on specified bean name if absent and * returns previous value on this name or null if such value does not exists * * @param beanName * @param metaData * @return */ public static MetaData addMetaData(String beanName, MetaData metaData) { return EJBS.putIfAbsent(beanName, metaData); } /** * Check if {@link MetaData} is ceched for specified bean name if true * throws {@link BeanInUseException} * * @param beanName * @param metaData * @throws BeanInUseException */ public static void checkAndAddMetaData(String beanName, MetaData metaData) throws BeanInUseException { MetaData tmpMeta = addMetaData(beanName, metaData); if (ObjectUtils.notNull(tmpMeta)) { throw new BeanInUseException(String.format( "bean %s is alredy in use", beanName)); } } /** * Checks if bean with associated name deployed and if yes if is deployment * in progress * * @param beanName * @return boolean */ public static boolean checkMetaData(String beanName) { boolean check; MetaData metaData = EJBS.get(beanName); check = metaData == null; if (!check) { check = metaData.isInProgress(); } return check; } /** * Checks if bean with associated name deployed * * @param beanName * @return boolean */ public boolean checkBean(String beanName) { return EJBS.containsKey(beanName); } /** * Waits while {@link MetaData#isInProgress()} is true * * @param metaData * @throws IOException */ public static void awaitMetaData(MetaData metaData) throws IOException { boolean inProgress = metaData.isInProgress(); if (inProgress) { synchronized (metaData) { while (inProgress) { try { metaData.wait(); inProgress = metaData.isInProgress(); } catch (InterruptedException ex) { throw new IOException(ex); } } } } } /** * Gets deployed bean {@link MetaData} by name without checking deployment * progress * * @param beanName * @return {@link MetaData} */ public static MetaData getMetaData(String beanName) { return EJBS.get(beanName); } /** * Check if {@link MetaData} with associated name deployed and if it is * waits while {@link MetaData#isInProgress()} true before return it * * @param beanName * @return {@link MetaData} * @throws IOException */ public static MetaData getSyncMetaData(String beanName) throws IOException { MetaData metaData = getMetaData(beanName); if (metaData == null) { throw new IOException(String.format("Bean %s is not deployed", beanName)); } awaitMetaData(metaData); return metaData; } /** * Gets bean name by containing archive {@link URL} address * * @param url * @return */ public static Collection<String> getBeanNames(URL url) { synchronized (MetaContainer.class) { return EJB_URLS.get(url); } } /** * checks containing archive {@link URL} address * * @param url * @return */ public static boolean chackDeployment(URL url) { synchronized (MetaContainer.class) { return EJB_URLS.containsKey(url); } } /** * Removes cached bean names {@link Collection} by containing file * {@link URL} as key * * @param url */ public static void removeBeanNames(URL url) { synchronized (MetaContainer.class) { EJB_URLS.remove(url); } } /** * Caches bean name by {@link URL} of jar ear or any file * * @param beanName */ public static void addBeanName(URL url, String beanName) { synchronized (MetaContainer.class) { Collection<String> beanNames = EJB_URLS.get(url); if (ObjectUtils.notAvailable(beanNames)) { beanNames = new HashSet<String>(); EJB_URLS.put(url, beanNames); } beanNames.add(beanName); } } /** * Lists set for deployed application {@link URL}'s * * @return {@link Set}<URL> */ public static Set<URL> listApplications() { Set<URL> apps = EJB_URLS.keySet(); return apps; } /** * Clears connection from cache * * @param metaData * @throws IOException */ private static void clearConnection(MetaData metaData) throws IOException { Collection<ConnectionData> connections = metaData.getConnections(); if (ObjectUtils.available(connections)) { for (ConnectionData connection : connections) { // Gets connection to clear String unitName = connection.getUnitName(); ConnectionSemaphore semaphore = connection.getConnection(); if (semaphore == null) { semaphore = JPAManager.getConnection(unitName); } if (ObjectUtils.notNull(semaphore) && semaphore.decrementUser() <= 1) { JPAManager.removeConnection(unitName); } } } } /** * Removes bean (removes it's {@link MetaData} from cache) by bean class * name * * @param beanName * @throws IOException */ public static void undeployBean(String beanName) throws IOException { MetaData metaData = null; try { metaData = getSyncMetaData(beanName); } catch (IOException ex) { LOG.error(String.format("Could not get bean resources %s cause %s", beanName, ex.getMessage()), ex); } // Removes MetaData from cache removeMeta(beanName); if (ObjectUtils.notNull(metaData)) { // Removes appropriated resource class from REST service RestUtils.remove(metaData.getBeanClass()); clearConnection(metaData); ClassLoader loader = metaData.getLoader(); LibraryLoader.closeClassLoader(loader); metaData = null; } } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link URL} of * archive file * * @param url * @throws IOException */ public static void undeploy(URL url) throws IOException { synchronized (MetaContainer.class) { Collection<String> beanNames = getBeanNames(url); if (ObjectUtils.available(beanNames)) { for (String beanName : beanNames) { undeployBean(beanName); } } removeBeanNames(url); } } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link File} * of archive file * * @param file * @throws IOException */ public static void undeploy(File file) throws IOException { URL url = file.toURI().toURL(); undeploy(url); } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link File} * path of archive file * * @param path * @throws IOException */ public static void undeploy(String path) throws IOException { File file = new File(path); undeploy(file); } /** * Removed {@link MetaData} from cache * * @param beanName */ public static void removeMeta(String beanName) { EJBS.remove(beanName); } /** * Gets {@link javax.persistence.EntityManagerFactory} from cache for * associated unit name * * @param unitName * @return {@link javax.persistence.EntityManagerFactory} * @throws IOException */ public static EntityManagerFactory getConnection(String unitName) throws IOException { return JPAManager.getEntityManagerFactory(unitName); } /** * Gets {@link UserTransaction} object from {@link ThreadLocal} per thread * * @return {@link UserTransaction} */ public static UserTransaction getTransaction() { UserTransaction transaction = TRANSACTION_HOLDER.get(); return transaction; } /** * Caches {@link UserTransaction} object in {@link ThreadLocal} per thread * * @param transaction */ public static void setTransaction(UserTransaction transaction) { TRANSACTION_HOLDER.set(transaction); } /** * Removes {@link UserTransaction} object from {@link ThreadLocal} per * thread */ public static void removeTransaction() { TRANSACTION_HOLDER.remove(); } /** * Closes all {@link javax.persistence.EntityManagerFactory} cached * instances */ public static void closeConnections() { closeEntityManagerFactories(); } /** * Gets {@link java.util.Iterator}<MetaData> over all cached * {@link org.lightmare.cache.MetaData} * * @return {@link java.util.Iterator}<MetaData> */ public static Iterator<MetaData> getBeanClasses() { return EJBS.values().iterator(); } public static void putResource(Class<?> resourceClass, Resource resource) { REST_RESOURCES.putIfAbsent(resourceClass, resource); } public static Resource getResource(Class<?> resourceClass) { Resource resource = REST_RESOURCES.get(resourceClass); return resource; } public static void removeResource(Class<?> resourceClass) { REST_RESOURCES.remove(resourceClass); } public static boolean hasRest() { return ObjectUtils.available(REST_RESOURCES); } }
package org.lightmare.cache; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.persistence.EntityManagerFactory; import org.apache.log4j.Logger; import org.lightmare.config.Configuration; import org.lightmare.deploy.MetaCreator; import org.lightmare.ejb.exceptions.BeanInUseException; import org.lightmare.libraries.LibraryLoader; import org.lightmare.rest.providers.RestProvider; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.LogUtils; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.fs.WatchUtils; /** * Container class to save {@link MetaData} for bean interface {@link Class} and * connections ({@link EntityManagerFactory}) for unit names * * @author Levan * */ public class MetaContainer { // Cached instance of MetaCreator private static MetaCreator creator; /** * {@link Configuration} container class for server */ public static final Map<String, Configuration> CONFIGS = new ConcurrentHashMap<String, Configuration>(); // Cached bean meta data private static final ConcurrentMap<String, MetaData> EJBS = new ConcurrentHashMap<String, MetaData>(); // Cached bean class name by its URL for undeploy processing private static final ConcurrentMap<URL, Collection<String>> EJB_URLS = new ConcurrentHashMap<URL, Collection<String>>(); private static final Logger LOG = Logger.getLogger(MetaContainer.class); /** * Gets cached {@link MetaCreator} object * * @return */ public static MetaCreator getCreator() { synchronized (MetaContainer.class) { return creator; } } /** * Caches {@link MetaCreator} object * * @param metaCreator */ public static void setCreator(MetaCreator metaCreator) { synchronized (MetaContainer.class) { creator = metaCreator; } } /** * Caches {@link Configuration} for specific {@link URL} array * * @param archives * @param config */ public static void putConfig(URL[] archives, Configuration config) { if (CollectionUtils.valid(archives)) { boolean containsPath; for (URL archive : archives) { String path = WatchUtils.clearPath(archive.getFile()); containsPath = CONFIGS.containsKey(path); if (ObjectUtils.notTrue(containsPath)) { CONFIGS.put(path, config); } } } } /** * Gets {@link Configuration} from cache for specific {@link URL} array * * @param archives * @param config */ public static Configuration getConfig(URL[] archives) { Configuration config; URL archive = CollectionUtils.getFirst(archives); if (ObjectUtils.notNull(archive)) { String path = WatchUtils.clearPath(archive.getFile()); config = CONFIGS.get(path); } else { config = null; } return config; } /** * Adds {@link MetaData} to cache on specified bean name if absent and * returns previous value on this name or null if such value does not exists * * @param beanName * @param metaData * @return */ public static MetaData addMetaData(String beanName, MetaData metaData) { return EJBS.putIfAbsent(beanName, metaData); } /** * Check if {@link MetaData} is ceched for specified bean name if true * throws {@link BeanInUseException} * * @param beanName * @param metaData * @throws BeanInUseException */ public static void checkAndAddMetaData(String beanName, MetaData metaData) throws BeanInUseException { MetaData tmpMeta = addMetaData(beanName, metaData); if (ObjectUtils.notNull(tmpMeta)) { throw BeanInUseException.get("bean %s is alredy in use", beanName); } } /** * Checks if bean with associated name deployed and if yes if is deployment * in progress * * @param beanName * @return boolean */ public static boolean checkMetaData(String beanName) { boolean check; MetaData metaData = EJBS.get(beanName); check = metaData == null; if (ObjectUtils.notTrue(check)) { check = metaData.isInProgress(); } return check; } /** * Checks if bean with associated name deployed * * @param beanName * @return boolean */ public boolean checkBean(String beanName) { return EJBS.containsKey(beanName); } /** * Waits while passed {@link MetaData} instance is in progress * * @param inProgress * @param metaData * @throws IOException */ private static void awaitProgress(boolean inProgress, MetaData metaData) throws IOException { while (inProgress) { try { metaData.wait(); inProgress = metaData.isInProgress(); } catch (InterruptedException ex) { throw new IOException(ex); } } } /** * Waits while {@link MetaData#isInProgress()} is true * * @param metaData * @throws IOException */ public static void awaitMetaData(MetaData metaData) throws IOException { boolean inProgress = metaData.isInProgress(); if (inProgress) { synchronized (metaData) { awaitProgress(inProgress, metaData); } } } /** * Gets deployed bean {@link MetaData} by name without checking deployment * progress * * @param beanName * @return {@link MetaData} */ public static MetaData getMetaData(String beanName) { return EJBS.get(beanName); } /** * Check if {@link MetaData} with associated name deployed and if it is * waits while {@link MetaData#isInProgress()} true before return it * * @param beanName * @return {@link MetaData} * @throws IOException */ public static MetaData getSyncMetaData(String beanName) throws IOException { MetaData metaData = getMetaData(beanName); if (metaData == null) { throw new IOException(String.format("Bean %s is not deployed", beanName)); } awaitMetaData(metaData); return metaData; } /** * Gets bean name by containing archive {@link URL} address * * @param url * @return */ public static Collection<String> getBeanNames(URL url) { synchronized (MetaContainer.class) { return EJB_URLS.get(url); } } /** * checks containing archive {@link URL} address * * @param url * @return */ public static boolean chackDeployment(URL url) { synchronized (MetaContainer.class) { return EJB_URLS.containsKey(url); } } /** * Removes cached bean names {@link Collection} by containing file * {@link URL} as key * * @param url */ public static void removeBeanNames(URL url) { synchronized (MetaContainer.class) { EJB_URLS.remove(url); } } /** * Caches bean name by {@link URL} of jar ear or any file * * @param beanName */ public static void addBeanName(URL url, String beanName) { synchronized (MetaContainer.class) { Collection<String> beanNames = EJB_URLS.get(url); if (CollectionUtils.invalid(beanNames)) { beanNames = new HashSet<String>(); EJB_URLS.put(url, beanNames); } beanNames.add(beanName); } } /** * Lists set for deployed application {@link URL}'s * * @return {@link Set}<URL> */ public static Set<URL> listApplications() { Set<URL> apps = EJB_URLS.keySet(); return apps; } /** * Clears connection from cache * * @param metaData * @throws IOException */ private static void clearConnection(MetaData metaData) throws IOException { Collection<ConnectionData> connections = metaData.getConnections(); if (CollectionUtils.valid(connections)) { for (ConnectionData connection : connections) { // Gets connection to clear String unitName = connection.getUnitName(); ConnectionSemaphore semaphore = connection.getConnection(); if (semaphore == null) { semaphore = ConnectionContainer.getConnection(unitName); } if (ObjectUtils.notNull(semaphore) && semaphore.decrementUser() <= ConnectionSemaphore.MINIMAL_USERS) { ConnectionContainer.removeConnection(unitName); } } } } /** * Removes bean (removes it's {@link MetaData} from cache) by bean class * name * * @param beanName * @throws IOException */ public static void undeployBean(String beanName) throws IOException { MetaData metaData = null; try { metaData = getSyncMetaData(beanName); } catch (IOException ex) { LogUtils.error(LOG, ex, "Could not get bean resources %s cause %s", beanName, ex.getMessage()); } // Removes MetaData from cache removeMeta(beanName); if (ObjectUtils.notNull(metaData)) { // Removes appropriated resource class from REST service if (RestContainer.hasRest()) { RestProvider.remove(metaData.getBeanClass()); } clearConnection(metaData); ClassLoader loader = metaData.getLoader(); LibraryLoader.closeClassLoader(loader); metaData = null; } } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link URL} of * archive file * * @param url * @throws IOException */ public static boolean undeploy(URL url) throws IOException { synchronized (MetaContainer.class) { Collection<String> beanNames = getBeanNames(url); boolean valid = CollectionUtils.valid(beanNames); if (valid) { for (String beanName : beanNames) { undeployBean(beanName); } } removeBeanNames(url); return valid; } } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link File} * of archive file * * @param file * @throws IOException */ public static boolean undeploy(File file) throws IOException { URL url = file.toURI().toURL(); boolean valid = undeploy(url); return valid; } /** * Removes bean (removes it's {@link MetaData} from cache) by {@link File} * path of archive file * * @param path * @throws IOException */ public static boolean undeploy(String path) throws IOException { File file = new File(path); boolean valid = undeploy(file); return valid; } /** * Removed {@link MetaData} from cache * * @param beanName */ public static void removeMeta(String beanName) { EJBS.remove(beanName); } /** * Gets {@link java.util.Iterator}<MetaData> over all cached * {@link org.lightmare.cache.MetaData} * * @return {@link java.util.Iterator}<MetaData> */ public static Iterator<MetaData> getBeanClasses() { return EJBS.values().iterator(); } /** * Removes all cached resources */ public static void clear() { if (ObjectUtils.notNull(creator)) { synchronized (MetaContainer.class) { if (ObjectUtils.notNull(creator)) { creator.clear(); creator = null; } } } CONFIGS.clear(); EJBS.clear(); EJB_URLS.clear(); } }
package org.lightmare.cache; import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.glassfish.jersey.server.model.Resource; import org.lightmare.rest.RestConfig; import org.lightmare.rest.providers.RestInflector; import org.lightmare.utils.CollectionUtils; import org.lightmare.utils.ObjectUtils; /** * Container class to cache REST resource classes * * @author levan * */ public class RestContainer { // Cached REST resource classes private static final ConcurrentMap<Class<?>, Resource> REST_RESOURCES = new ConcurrentHashMap<Class<?>, Resource>(); // Cached running instance of RestConfig class private static RestConfig restConfig; public static void putResource(Class<?> handlerClass, Resource resource) { REST_RESOURCES.putIfAbsent(handlerClass, resource); } /** * Finds if {@link Resource} has handler instances and if they are instance * of {@link RestInflector} and gets appropriate bean class * * @param resource * @return {@link Class} */ private static Class<?> getFromHandlerInstance(Resource resource) { Class<?> handlerClass = null; Set<Object> handlers = resource.getHandlerInstances(); if (CollectionUtils.valid(handlers)) { Iterator<Object> iterator = handlers.iterator(); Object handler; RestInflector inflector; while (iterator.hasNext() && handlerClass == null) { handler = iterator.next(); if (handler instanceof RestInflector) { inflector = ObjectUtils.cast(handler, RestInflector.class); handlerClass = inflector.getBeanClass(); } } } return handlerClass; } /** * Gets handler bean class directly from {@link Resource} or from handler * instances * * @param resource * @return {@link Class} */ private static Class<?> getHandlerClass(Resource resource) { Class<?> handlerClass; Set<Class<?>> handlerClasses = resource.getHandlerClasses(); if (CollectionUtils.valid(handlerClasses)) { handlerClass = CollectionUtils.getFirst(handlerClasses); } else { handlerClass = getFromHandlerInstance(resource); } return handlerClass; } /** * Caches passed REST {@link Resource} associated to it's {@link Class} instance * @param resource */ public static void putResource(Resource resource) { Class<?> handlerClass = getHandlerClass(resource); if (ObjectUtils.notNull(handlerClass)) { putResource(handlerClass, resource); } } /** * Caches {@link Collection} of REST {@link Resource} instances associated * to their {@link Class} instance * * @param resources */ public static void putResources(Collection<Resource> resources) { if (CollectionUtils.valid(resources)) { for (Resource resource : resources) { putResource(resource); } } } /** * Gets REST {@link Resource} appropriate to passed {@link Class} instance * * @param resourceClass * @return {@link Resource} */ public static Resource getResource(Class<?> resourceClass) { Resource resource = REST_RESOURCES.get(resourceClass); return resource; } /** * Removes resource appropriate to passed {@link Class} instance * * @param resourceClass */ public static void removeResource(Class<?> resourceClass) { REST_RESOURCES.remove(resourceClass); } /** * Removes passed {@link Resource} from cache * * @param resource */ public static void removeResource(Resource resource) { Class<?> handlerClass = getHandlerClass(resource); if (ObjectUtils.notNull(handlerClass)) { REST_RESOURCES.remove(handlerClass); } } /** * Gets size of cached {@link Resource} instances * * @return <code>int</code> */ public static int size() { return REST_RESOURCES.size(); } /** * Removes passed set of {@link Resource} instances from REST service * * @param existingResources */ public static void removeResources(Set<Resource> existingResources) { if (CollectionUtils.valid(existingResources)) { for (Resource existingResource : existingResources) { removeResource(existingResource); } } } /** * Checks if application has REST resources * * @return <code>boolean</code> */ public static boolean hasRest() { synchronized (RestContainer.class) { return ObjectUtils.notNull(restConfig); } } public static void setRestConfig(RestConfig newConfig) { synchronized (RestContainer.class) { restConfig = newConfig; } } public static RestConfig getRestConfig() { synchronized (RestContainer.class) { return restConfig; } } /** * Clears cached rest resources */ public static void clear() { REST_RESOURCES.clear(); } }
package org.neo4j.driver; import org.neo4j.driver.exception.Neo4jClientException; import org.neo4j.driver.v1.*; import java.util.Spliterator; import java.util.stream.Stream; import java.util.stream.StreamSupport; import static java.util.Spliterators.spliterator; /** * Client transaction. */ public class Neo4jTransaction implements AutoCloseable { /** * Neo4j's underlying session. */ private Session session; /** * Neo4j's underlying transaction */ private Transaction transaction; /** * Default constructor with a session. */ public Neo4jTransaction(Session session) { this.session = session; this.transaction = session.beginTransaction(); } /** * Execute the given cypher query with its parameters. * * @param query Cypher query * @param params Query's parameters * @return A Stream of record */ public Stream<Record> run(String query, Value params) { checkSessionAndTransaction(); try { StatementResult result = this.transaction.run(query, params); return StreamSupport.stream(spliterator(result, Long.MAX_VALUE, Spliterator.ORDERED), false); } catch (Exception e) { throw new Neo4jClientException(e); } } /** * Execute the given cypher query without parameters. * * @param query Cypher query * @return A Stream of record */ public Stream<Record> run(String query) { checkSessionAndTransaction(); return this.run(query, null); } /** * Commit and close the current transaction. */ public void success() { checkSessionAndTransaction(); this.transaction.success(); this.transaction.close(); } /** * Rollback and close the current transaction. */ public void failure() { checkSessionAndTransaction(); this.transaction.failure(); this.transaction.close(); } /** * Get the last bookmarkId. * It's only works when the underline transaction has been close. * So you have to call {@link #failure()} or {@link #success()} before. * * @return the latest bookmarkId of this session. */ public String getBookmarkId() { return this.session.lastBookmark(); } @Override public void close() { if (this.transaction != null) this.transaction.close(); if (this.session != null) this.session.close(); } /** * Check if one the underlying session or transaction is closed or not. * If so, a {@link Neo4jClientException} is thrown. */ private void checkSessionAndTransaction() throws Neo4jClientException { if (this.session == null || !this.session.isOpen() || this.transaction == null || !this.transaction.isOpen()) { throw new Neo4jClientException("Session or transaction is closed"); } } }
package org.ng200.openolympus; import java.sql.SQLException; import java.util.HashSet; import java.util.Locale; import java.util.Set; import javax.servlet.MultipartConfigElement; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSource; import org.ng200.openolympus.cerberus.util.Lists; import org.ng200.openolympus.model.Role; import org.ng200.openolympus.model.User; import org.ng200.openolympus.resourceResolvers.OpenOlympusMessageSource; import org.ng200.openolympus.services.RoleService; import org.ng200.openolympus.services.UserService; import org.ng200.openolympus.sqlSupport.OpenOlympusPostgreDialect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.MultipartConfigFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.cache.Cache; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.concurrent.ConcurrentMapCache; import org.springframework.cache.support.SimpleCacheManager; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.PropertySource; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.EncodedResource; import org.springframework.data.domain.AuditorAware; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.jdbc.datasource.init.ScriptException; import org.springframework.jdbc.datasource.init.ScriptUtils; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.servlet.i18n.SessionLocaleResolver; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module; @Configuration @ComponentScan(basePackages = "org.ng200.openolympus") @EnableAutoConfiguration @PropertySource("classpath:openolympus.properties") @EnableAspectJAutoProxy(proxyTargetClass = true) @EnableCaching public class Application { public static void main(final String[] args) throws ScriptException, SQLException { final ConfigurableApplicationContext context = SpringApplication.run( Application.class, args); Application.setupContext(context); } public static void setupContext( final ApplicationContext webApplicationContext) throws SQLException { final UserService userService = webApplicationContext .getBean(UserService.class); final RoleService roleService = webApplicationContext .getBean(RoleService.class); final DataSource dataSource = webApplicationContext .getBean(DataSource.class); ScriptUtils.executeSqlScript(dataSource.getConnection(), new EncodedResource(new ClassPathResource( "sql/setupTriggers.sql")), false, false, ScriptUtils.DEFAULT_COMMENT_PREFIX, "^^^ NEW STATEMENT ^^^", ScriptUtils.DEFAULT_BLOCK_COMMENT_START_DELIMITER, ScriptUtils.DEFAULT_BLOCK_COMMENT_END_DELIMITER); if (userService.getUserByUsername("system") == null) { Application.logger.info("Creating system account"); final User system = new User("system", null, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", null, null); final Set<Role> roles = new HashSet<Role>(); roles.add(roleService.getRoleByName(Role.USER)); roles.add(roleService.getRoleByName(Role.SUPERUSER)); roles.add(roleService.getRoleByName(Role.SYSTEM)); system.setRoles(roles); userService.saveUser(system); } if (userService.getUserByUsername("admin") == null) { Application.logger.info("Creating administrator account"); final User admin = new User("admin", new BCryptPasswordEncoder().encode("admin"), "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", null, null); final Set<Role> roles = new HashSet<Role>(); roles.add(roleService.getRoleByName(Role.USER)); roles.add(roleService.getRoleByName(Role.SUPERUSER)); admin.setRoles(roles); userService.saveUser(admin); } } static final Logger logger = LoggerFactory.getLogger(Application.class); @Value("${dbPassword}") private String postgresPassword; @Value("${dbAddress}") private String postgresAddress; @Value("${serverPort}") private int serverPort; @Value("${storagePath}") private String storagePath; @Bean public AuditorAware<User> auditorProvider() { return new SpringSecurityAuditorAware(); } @Bean public DataSource dataSource() { final BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUsername("postgres"); dataSource.setPassword(this.postgresPassword); dataSource.setUrl("jdbc:postgresql://" + this.postgresAddress + "/openolympus"); Application.logger.info("Connecting: {}", dataSource.getUrl()); return dataSource; } @Bean public HibernateJpaVendorAdapter jpaVendorAdapter() { final HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); adapter.setShowSql(false); adapter.setGenerateDdl(true); adapter.setDatabasePlatform(OpenOlympusPostgreDialect.class .getCanonicalName()); return adapter; } @Bean public SessionLocaleResolver localeResolver() { final SessionLocaleResolver resolver = new SessionLocaleResolver(); resolver.setDefaultLocale(Locale.forLanguageTag("ru")); return resolver; } @Bean public OpenOlympusMessageSource messageSource() { final OpenOlympusMessageSource source = new OpenOlympusMessageSource(); source.setDefaultEncoding("UTF-8"); source.setBasename("classpath:/messages"); return source; } @Bean public MultipartConfigElement multipartConfigElement() { final MultipartConfigFactory factory = new MultipartConfigFactory(); factory.setMaxFileSize("1024MB"); factory.setMaxRequestSize("1024MB"); return factory.createMultipartConfig(); } @Bean public PasswordEncoder passwordEncoder() { Application.logger.info("Creating password encoder"); return new BCryptPasswordEncoder(); } @Bean public EmbeddedServletContainerFactory servletContainer() { final TomcatEmbeddedServletContainerFactory containerFactory = new TomcatEmbeddedServletContainerFactory( this.serverPort); containerFactory.setSessionTimeout(30); return containerFactory; } @Bean public ThreadPoolTaskExecutor taskExecutor() { final ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); pool.setCorePoolSize(5); pool.setMaxPoolSize(10); pool.setWaitForTasksToCompleteOnShutdown(true); return pool; } @Bean public MappingJackson2HttpMessageConverter jacksonMessageConverter() { MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new Hibernate4Module()); mapper.registerModule(new DurationJacksonModule()); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); messageConverter.setObjectMapper(mapper); return messageConverter; } @Bean public SimpleCacheManager cacheManager() { SimpleCacheManager cacheManager = new SimpleCacheManager(); cacheManager.setCaches(Lists.from(new ConcurrentMapCache("solutions"), new ConcurrentMapCache("contests"))); return cacheManager; } }
package org.skife.jdbi.v2; import org.skife.jdbi.v2.tweak.Argument; public interface ArgumentFactory<T> { boolean accepts(Class<? super T> expectedType, T it, StatementContext ctx); Argument build(Class<? super T> expectedType, T it, StatementContext ctx); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.xtx.ut4converter.t3d; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.logging.Logger; import javax.vecmath.Vector3d; import org.xtx.ut4converter.UTGames; import org.xtx.ut4converter.MapConverter; import org.xtx.ut4converter.t3d.T3DMatch.Match; import org.xtx.ut4converter.ucore.UPackage; import org.xtx.ut4converter.ucore.UPackageRessource; /** * * @author XtremeXp */ public abstract class T3DActor { /** * All original properties stored for this actor. * Basically is a map of "key" and value" * E.G: * Brush=Model'MyLevel.Brush' * -> Key = Brush, Value = Model'MyLevel.Brush' * Might be used after parsing t3d actor data to convert it. */ protected Map<String, String> properties; /** * Possible match for t3d actor */ protected Match match; /** * Unreal Engine 4 only. * Root Component Type */ protected T3DMatch.UE4_RCType ue4RootCompType = T3DMatch.UE4_RCType.UNKNOWN; /** * Original actor class */ protected String t3dClass; /** * UE1/2/3? property in Events->Tag */ protected String tag; /** * Name or label of actor */ protected String name; /** * Location of actor (if null means 0 location) */ protected Vector3d location; /** * Co-Location of actor * Used by some old Unreal 1 / UT99 maps ... * Useless for convert. */ protected Vector3d coLocation; /** * Old-Location of actor * Used by some old Unreal 1 / UT99 maps ... */ protected Vector3d oldLocation; /** * Rotation of actor */ protected Vector3d rotation; /** * 3D Scaling */ protected Vector3d scale3d; /** * Scale in unreal editor of sprite */ protected Double drawScale; String otherdata=""; boolean usecolocation=false; /** * Reference to map converter */ protected MapConverter mapConverter; /** * Used to add extra Z location * (for converting pickup for exemple not having same 'origin')solar */ Double offsetZLocation = 0D; /** * TODO make global StringBuilder * that we would 'reset' after write of each actor * (avoiding creating one for each single actor / perf issues) */ protected StringBuilder sbf; /** * Minimal indentation when writing t3d converted actor */ public final static String IDT = "\t"; protected boolean validWriting = true; /** * Force these lines to be written * (not used yet for each subclass of this class) */ protected List<String> forcedWrittenLines = new ArrayList<>(); protected Logger logger; /** * Linked actors to this one. * (e.g: teleporters) */ protected List<T3DActor> linkedTo = new ArrayList<>(); /** * Read line of t3d file to parse data about current t3d actor being read * @param line * @return true if data has been extracted from line false else (useful to check which data has not been parsed) */ public boolean analyseT3DData(String line){ return parseOtherData(line); } /** * * @param mc */ public T3DActor(MapConverter mc){ this.mapConverter = mc; sbf = new StringBuilder(); properties = new HashMap<>(); logger = mc.getLogger(); } /** * Get some important info about actors like location,rotation,drawscale,... * @param line T3D level line being analyzed * @return true if some Data has been parsed. */ public boolean parseOtherData(String line) { int equalsIdx = line.indexOf("="); // BlockAll hack overide if((!(this instanceof T3DBrush) || "BlockAll".equals(t3dClass)) && equalsIdx != -1){ properties.put(line.substring(0, equalsIdx).trim(), line.substring(equalsIdx+1, line.length())); } if(line.contains(" Location=")||line.contains("\tLocation=")){ location = T3DUtils.getVector3d(line, 0D); return true; } if(line.contains(" OldLocation=")||line.contains("\tOldLocation=")){ oldLocation = T3DUtils.getVector3d(line, 0D); return true; } else if(line.contains(" ColLocation=") || line.contains("\tColLocation=")|| line.contains("ColLocation=")) { coLocation = T3DUtils.getVector3d(line, 0D); return true; } else if(line.contains("DrawScale3D")){ scale3d = T3DUtils.getVector3d(line, 1D); return true; } else if(line.contains("DrawScale=")){ drawScale = T3DUtils.getDouble(line); return true; } else if(line.contains("Rotation")){ rotation = T3DUtils.getVector3dRot(line); return true; } // Begin Actor Class=Brush Name=Brush2 else if(line.contains("Begin Actor")){ t3dClass = getActorClass(line); name = T3DUtils.getString(line, "Name"); } else if(line.contains(" Group=")||line.contains("\tGroup=")){ addOtherData(line); } else if(line.contains("Tag=")){ tag = line.split("Tag=")[1]; } else { return false; } return true; } /** * Write Location Rotation and drawScale of converted actor */ protected void writeLocRotAndScale(){ String baseText = IDT+"\t\t"; if(getOutputGame().engine.version >= UTGames.UnrealEngine.UE4.version){ if(location != null){ sbf.append(baseText).append("RelativeLocation=(X=").append(fmt(location.x)).append(",Y=").append(fmt(location.y)).append(",Z=").append(fmt(location.z)).append(")\n"); } // RelativeRotation=(Pitch=14.179391,Yaw=13.995641,Roll=14.179387) if(rotation != null){ sbf.append(baseText).append("RelativeRotation=(Pitch=").append(fmt(rotation.x)).append(",Yaw=").append(fmt(rotation.y)).append(",Roll=").append(fmt(rotation.z)).append(")\n"); } // RelativeScale3D=(X=4.000000,Y=3.000000,Z=2.000000) if(scale3d != null){ sbf.append(baseText).append("RelativeScale3D=(X=").append(fmt(scale3d.x)).append(",Y=").append(fmt(scale3d.y)).append(",Z=").append(fmt(scale3d.z)).append(")\n"); } } // checked U1, UT99, U2, UT2004, UT3 else { if(location != null){ sbf.append(baseText).append("Location=(X=").append(fmt(location.x)).append(",Y=").append(fmt(location.y)).append(",Z=").append(fmt(location.z)).append(")\n"); } // RelativeRotation=(Pitch=14.179391,Yaw=13.995641,Roll=14.179387) if(rotation != null){ sbf.append(baseText).append("Rotation=(Pitch=").append(fmt(rotation.x)).append(",Yaw=").append(fmt(rotation.y)).append(",Roll=").append(fmt(rotation.z)).append(")\n"); } // RelativeScale3D=(X=4.000000,Y=3.000000,Z=2.000000) if(scale3d != null){ sbf.append(baseText).append("Scale3D=(X=").append(fmt(scale3d.x)).append(",Y=").append(fmt(scale3d.y)).append(",Z=").append(fmt(scale3d.z)).append(")\n"); } } } /** * * @param newScale */ public void scale(Double newScale){ if(newScale == null){ return; } if(newScale > 1){ if(location != null) location.scale(newScale); if(coLocation != null) coLocation.scale(newScale); if(drawScale != null ) drawScale *= newScale; if(scale3d != null) scale3d.scale(newScale); } } private void addOtherData(String somedata) { this.otherdata += somedata+"\n"; } /** * * @param otherdata */ public void setOtherdata(String otherdata) { this.otherdata = otherdata; } /** * * @return */ public Vector3d getLocation() { return location; } /** * * @param value * @return */ public String fmt(double value){ return formatValue(value); } /** * * @param value * @return */ public static String formatValue(double value) { DecimalFormat df = new DecimalFormat("0.000000",new DecimalFormatSymbols(Locale.US)); return df.format(value); } /** * * @param line * @return */ public static String getActorClass(String line) { return (line.split("=")[1]).split(" ")[0]; } /** * Get the input game this actor come from * @return */ protected UTGames.UTGame getInputGame(){ return mapConverter.getInputGame(); } /** * Get the output game to which it must be converted * @return */ protected UTGames.UTGame getOutputGame(){ return mapConverter.getOutputGame(); } /** * * @param offsetZLocation */ public void setOffsetZLocation(Double offsetZLocation) { this.offsetZLocation = offsetZLocation; } /** * * @return */ protected MapConverter getMapConverter(){ return this.mapConverter; } public void convert(){ if(coLocation != null){ if(location != null){ location.add(coLocation); } else { location = coLocation; } coLocation = null; } //changes height of actor if needed (so aligned with floor for example) if(offsetZLocation != null){ if(location != null){ location.z += offsetZLocation; } else { location = new Vector3d(0, 0, offsetZLocation); } offsetZLocation = null; } if(rotation != null){ // Rotation range changed between UE2 and UE3 // for brushes no need that since they have been transformed permanently // Vertice data updated with rotation and rotation reset if(mapConverter.isFromUE1UE2ToUE3UE4()){ rotation.x /= 360d; rotation.y /= 360d; rotation.z /= 360d; } else if(mapConverter.isFromUE3UE4ToUE1UE2()){ rotation.x *= 360d; rotation.y *= 360d; rotation.z *= 360d; } } } /** * We may not want to convert this t3d actor after analyzing data, * that's the purpose of this. * @return true is this t3d actor is allowed to be converted else not */ public boolean isValid(){ return true; } protected void writeEndActor(){ // means we did not even write "begin actor" so we skip ... if(sbf.length() == 0){ return; } if(mapConverter.toUnrealEngine4()){ if(drawScale != null){ sbf.append(IDT).append("\tSpriteScale=").append(drawScale).append("\n");; } sbf.append(IDT).append("\tActorLabel=\"").append(name).append("\"\n"); } // Checked u1, ut99, ut2004, ut3 else { if(drawScale != null){ sbf.append(IDT).append("\tDrawScale=").append(drawScale).append("\"\n");; } sbf.append(IDT).append("\tName=\"").append(name).append("\n"); } sbf.append(IDT).append("End Actor\n").toString(); } /** * * @return */ public boolean isValidWriting() { return validWriting; } /** * T3D actor properties which are ressources (basically sounds, music, textures, ...) * * @param fullRessourceName Full name of ressource (e.g: AmbModern.Looping.comp1 ) * @param type Type of ressource (sound, staticmesh, texture, ...) * @return */ protected UPackageRessource getUPackageRessource(String fullRessourceName, T3DRessource.Type type){ String packageName = fullRessourceName.split("\\.")[0]; // Ressource ever created while parsing previous t3d lines // we return it if(mapConverter.mapPackages.containsKey(packageName)){ UPackage unrealPackage = mapConverter.mapPackages.get(packageName); UPackageRessource uPackageRessource = unrealPackage.findRessource(fullRessourceName); if(uPackageRessource != null){ uPackageRessource.setIsUsedInMap(true); return uPackageRessource; } // Need to create one else { return new UPackageRessource(fullRessourceName, type, mapConverter.getInputGame(), unrealPackage, true); } } else { // need to create one (unreal package info is auto-created) UPackageRessource upRessource = new UPackageRessource(fullRessourceName, type, mapConverter.getInputGame(), true); mapConverter.mapPackages.put(packageName, upRessource.getUnrealPackage()); return upRessource; } } public String toString(){ return sbf.toString(); } /** * Null-safe property getter * @param name * @return */ protected String getProperty(String name){ if(properties.containsKey(name)){ return properties.get(name); } else { return null; } } }
package com.janosgyerik.tools.util; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.StreamSupport; /** * Utility methods related to iterators. */ public final class IterTools { private IterTools() { throw new AssertionError("utility class, forbidden constructor"); } /** * Return an iterable over all permutations of a list's elements. * Note that there are n! permutations, where n is the size of the list. * * @param list items to permutate * @param <T> type of list items * @return iterable of all permutations */ public static <T> Iterable<List<T>> permutations(List<T> list) { return () -> new PermutationIterator<>(list); } /** * Return an iterable over all permutations of the numbers 1..n. * * @param n the upper bound of the range of values to use * @return iterable of all permutations */ public static Iterable<List<Integer>> permutations(int n) { List<Integer> nums = IntStream.rangeClosed(1, n).boxed().collect(Collectors.toList()); return permutations(nums); } private static class PermutationIterator<T> implements Iterator<List<T>> { private final List<T> list; private final int size; private final int maxCount; private final int[] indexes; int count = 0; PermutationIterator(List<T> list) { this.list = list; this.size = list.size(); int factorial = factorial(size); maxCount = factorial >= size ? factorial : Integer.MAX_VALUE; indexes = createInitialIndexes(); } private int[] createInitialIndexes() { return IntStream.range(0, size).toArray(); } @Override public boolean hasNext() { return count < maxCount; } @Override public List<T> next() { if (!hasNext()) { throw new NoSuchElementException(); } List<T> current = new ArrayList<>(size); for (int index : indexes) { current.add(list.get(index)); } if (++count < maxCount) { updateIndexes(); } return current; } private void updateIndexes() { int i = indexes.length - 2; for (; i >= 0; --i) { if (indexes[i] < indexes[i + 1]) { break; } } int j = indexes.length - 1; for (; ; j if (indexes[j] > indexes[i]) { break; } } swap(i, j); int half = (indexes.length - i) / 2; for (int k = 1; k <= half; ++k) { swap(i + k, indexes.length - k); } } private void swap(int i, int j) { int tmp = indexes[i]; indexes[i] = indexes[j]; indexes[j] = tmp; } } private static int factorial(int n) { if (n < 2) { return 1; } return n * factorial(n - 1); } public static <T> List<T> toList(Iterator<T> iterator) { List<T> list = new ArrayList<>(); toList(iterator, list); return list; } public static <T> void toList(Iterator<T> iterator, List<T> list) { while (iterator.hasNext()) { list.add(iterator.next()); } } public static <T> Set<List<T>> toSet(Iterable<List<T>> permutations) { return StreamSupport.stream(permutations.spliterator(), false).collect(Collectors.toSet()); } }
package org.xtx.ut4converter.t3d; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.xtx.ut4converter.UTGames; import org.xtx.ut4converter.UTGames.UTGame; /** * Base class to match or replace "basic" actor such as pickups, weapons * and so on. * TODO use some xml file * @author XtremeXp */ public class T3DMatch { /** * Conversion property. * Must always be checked when using 1.0x scaling! * TODO move to other class * TODO enum for other conversion property */ public static String Z_OFFSET = "Z_OFFSET"; /** * Offset with "Z" location for weapons * to fit with floor. * It's import that */ private final float UT99_UT4_WP_ZOFFSET = 26f; /** * Root component type for UT4 actor. * Used when writting converted actor for UT4 */ public static enum UE4_RCType{ UNKNOWN("Unknown", "Unknown"), SCENE_COMP("SceneComponent", "DummyRoot"), CAPSULE("CapsuleComponent", "Capsule"), AUDIO("AudioComponent", "AudioComponent0"); public String name; public String alias; UE4_RCType(String name, String alias){ this.name = name; this.alias = alias; } } private void initialise(){ list = new ArrayList<>(); // TODO move that final String UT4_PROP_IT = "InventoryType"; final String UT4_CLS_PWRUP= "PowerupBase_C"; // TODO use some proper xml file to set actor 'matches' // UT99->UT4, no match / check for: // DispersionPistol, QuadShot, Stinger, Razorjack, Chainsaw, ripper, RazorAmmo // ShellBox / Clip (enforcer ammo) // Stinger Ammo, BladeHopper, SuperShockCore // U1, U2, UT99, UT2003, UT2004, UT3, UT4 ... list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"HealthVial"}, null, null, null, new String[]{"Health_Small_C"}) .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 24f})); list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"MedBox"}, null, null, null, new String[]{"Health_Medium_C"}) .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 24f})); list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"HealthPack"}, null, null, null, new String[]{"Health_Large_C"}) .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 24f})); initialiseWeapons(); initialiseAmmos(); // Items - ThighPads list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"ThighPads"}, null, null, null, new String[]{UT4_CLS_PWRUP}) .withP(UTGame.UT4, UT4_PROP_IT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Pickups/Armor/Armor_ThighPads.Armor_ThighPads_C'") .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); // Armor2 list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"Armor", "Armor2"}, null, null, null, new String[]{UT4_CLS_PWRUP}) .withP(UTGame.UT4, UT4_PROP_IT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Pickups/Armor/Armor_Chest.Armor_Chest_C'") .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"UT_ShieldBelt"}, null, null, null, new String[]{UT4_CLS_PWRUP}) .withP(UTGame.UT4, UT4_PROP_IT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Pickups/Armor/Armor_ShieldBelt.Armor_ShieldBelt_C'") .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"UT_Jumpboots"}, null, null, null, new String[]{UT4_CLS_PWRUP}) .withP(UTGame.UT4, UT4_PROP_IT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Pickups/Powerups/BP_JumpBoots.BP_JumpBoots_C'") .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"UDamage", "Amplifier"}, null, null, null, new String[]{UT4_CLS_PWRUP}) .withP(UTGame.UT4, UT4_PROP_IT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Pickups/Powerups/BP_UDamage.BP_UDamage_C'") .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); // FIXME / NOT WORKING list.add(iByGame(T3DPickup.class, UE4_RCType.SCENE_COMP.name, null, null, new String[]{"FlagBase"}, null, null, null, new String[]{"UTRedFlagBase_C"})); // UT99 Actor with class 'FlagBase' and property "Team" equals 1 = UTBlueFlagBase for UT4 // FIXME / NOT WORKING list.add(iByGame(T3DPickup.class, UE4_RCType.SCENE_COMP.name, null, null, new String[]{"FlagBase"}, null, null, null, new String[]{"UTBlueFlagBase_C"}) .withP(UTGame.UT99, "Team", "1")); } private void initialiseAmmos(){ list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"BioAmmo", "Sludge"}, null, null, null, new String[]{"BioAmmoPickup_C"}) .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"Miniammo", "EClip"}, null, null, null, new String[]{"MinigunAmmoPickup_C"}) .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"FlakAmmo", "FlakBox", "FlakShellAmmo"}, null, null, null, new String[]{"FlakAmmoPickup_C"}) .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"RocketPack", "RocketCan"}, null, null, null, new String[]{"RocketAmmoPickup_C"}) .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"ShockCore", "ASMDAmmo"}, null, null, null, new String[]{"ShockAmmoPickup_C"}) .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"BulletBox", "RifleAmmo", "RifleRound", "RifleShell"}, null, null, null, new String[]{"SniperAmmoPickup_C"}) .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); list.add(iByGame(T3DPickup.class, UE4_RCType.CAPSULE.name, null, null, new String[]{"PAmmo"}, null, null, null, new String[]{"LinkAmmoPickup_C"}) .addConvP(UTGame.UT4, new Object[]{Z_OFFSET, 8f})); } private void initialiseWeapons(){ final String UT4_CLS_WPT = "WeaponBase_C"; final String UT4_PROP_WPT = "WeaponType"; List<GlobalMatch> gmWeapons = new ArrayList<>(); Class<? extends T3DActor> pickupCls = T3DPickup.class; // Weapons - Rocket Launcher gmWeapons.add(iByGame(pickupCls, UE4_RCType.CAPSULE.name, null, null, new String[]{"Eightball", "UT_Eightball"}, null, null, null, new String[]{UT4_CLS_WPT}) .withP(UTGame.UT4, UT4_PROP_WPT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Weapons/RocketLauncher/BP_RocketLauncher.BP_RocketLauncher_C'")); // Weapons - Link Gun gmWeapons.add(iByGame(pickupCls, UE4_RCType.CAPSULE.name, null, null, new String[]{"PulseGun"}, null, null, null, new String[]{UT4_CLS_WPT}) .withP(UTGame.UT4, UT4_PROP_WPT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Weapons/LinkGun/BP_LinkGun.BP_LinkGun_C'")); // Weapons - Flak Cannon gmWeapons.add(iByGame(pickupCls, UE4_RCType.CAPSULE.name, null, null, new String[]{"UT_FlakCannon", "FlakCannon"}, null, null, null, new String[]{UT4_CLS_WPT}) .withP(UTGame.UT4, UT4_PROP_WPT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Weapons/Flak/BP_FlakCannon.BP_FlakCannon_C'")); // Weapons - Enforcer gmWeapons.add(iByGame(pickupCls, UE4_RCType.CAPSULE.name, null, null, new String[]{"AutoMag", "enforcer", "doubleenforcer"}, null, null, null, new String[]{UT4_CLS_WPT}) .withP(UTGame.UT4, UT4_PROP_WPT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Weapons/Enforcer/Enforcer.Enforcer_C'")); // Weapons - Impact Hammer gmWeapons.add(iByGame(pickupCls, UE4_RCType.CAPSULE.name, null, null, new String[]{"ImpactHammer"}, null, null, null, new String[]{UT4_CLS_WPT}) .withP(UTGame.UT4, UT4_PROP_WPT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Weapons/ImpactHammer/BP_ImpactHammer.BP_ImpactHammer_C'")); // Weapons - Redeemer gmWeapons.add(iByGame(pickupCls, UE4_RCType.CAPSULE.name, null, null, new String[]{"WarheadLauncher"}, null, null, null, new String[]{UT4_CLS_WPT}) .withP(UTGame.UT4, UT4_PROP_WPT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Weapons/Redeemer/BP_Redeemer.BP_Redeemer_C'")); // Weapons - Shock Rifle gmWeapons.add(iByGame(pickupCls, UE4_RCType.CAPSULE.name, null, null, new String[]{"ShockRifle", "ASMD"}, null, null, null, new String[]{UT4_CLS_WPT}) .withP(UTGame.UT4, UT4_PROP_WPT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Weapons/ShockRifle/ShockRifle.ShockRifle_C'")); // Weapons - Bio Rifle gmWeapons.add(iByGame(pickupCls, UE4_RCType.CAPSULE.name, null, null, new String[]{"ut_biorifle", "GESBioRifle"}, null, null, null, new String[]{UT4_CLS_WPT}) .withP(UTGame.UT4, UT4_PROP_WPT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Weapons/BioRifle/BP_BioRifle.BP_BioRifle_C'")); // Weapons - Sniper gmWeapons.add(iByGame(pickupCls, UE4_RCType.CAPSULE.name, null, null, new String[]{"SniperRifle", "Rifle"}, null, null, null, new String[]{UT4_CLS_WPT}) .withP(UTGame.UT4, UT4_PROP_WPT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Weapons/Sniper/BP_Sniper.BP_Sniper_C'")); // Weapons - Minigun gmWeapons.add(iByGame(pickupCls, UE4_RCType.CAPSULE.name, null, null, new String[]{"minigun2", "Minigun"}, null, null, null, new String[]{UT4_CLS_WPT}) .withP(UTGame.UT4, UT4_PROP_WPT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Weapons/Minigun/BP_Minigun.BP_Minigun_C'")); // Weapons - Instagib gmWeapons.add(iByGame(pickupCls, UE4_RCType.CAPSULE.name, null, null, new String[]{"SuperShockRifle"}, null, null, null, new String[]{UT4_CLS_WPT}) .withP(UTGame.UT4, UT4_PROP_WPT, "BlueprintGeneratedClass'/Game/RestrictedAssets/Weapons/ShockRifle/BP_InstagibRifle.BP_InstagibRifle_C'")); for(GlobalMatch gmWp : gmWeapons){ // UT99 -> UT4 modify "z" location to fit with floor gmWp.addConvP(UTGame.UT4, new Object[]{Z_OFFSET, UT99_UT4_WP_ZOFFSET}); } list.addAll(gmWeapons); } public class GlobalMatch { /** * Internal tag. * Might be used to set the same conversion property * for all globalmatches having this tag (e.g: z offset for all weapon pickups) */ String tag; List<Match> matches; /** * * @param matches */ public GlobalMatch(List<Match> matches) { this.matches = matches; } /** * * @param property * @param value * @param game * @return */ public GlobalMatch withP(UTGames.UTGame game, String property, String value){ for(Match m : matches){ if(m.game == game){ m.addP(property, value); } } return this; } /** * Adds a conversion property for exemple * increase or decrease offset "Z" location to fit with floor * TODO add some inGame parameter * @param outGame UT Game the actor will be converted to * @param keyValue * @return */ public GlobalMatch addConvP(UTGame outGame, Object[] keyValue){ for(Match m : matches){ if(m.game == outGame){ m.convertProperties.put(keyValue[0].toString(), keyValue[1]); } } return this; } } public class Match { UTGames.UTGame game = UTGames.UTGame.NONE; /** * Match available for this engine. * Might be useful for convert between games with same engine * or very close (eg.: UT3/UT4) */ UTGames.UnrealEngine engine = UTGames.UnrealEngine.NONE; public List<String> actorClass = new ArrayList<>(); /** * Will use this class for convert */ public Class t3dClass; /** * Properties that need to be written in t3d data for this actor. * Map of property, value * E.G: FolderPath="Pickups/Weapons" FolderPath, "Pickups/Weapons" */ public Map<String, String> properties = new HashMap<>(); /** * Internal properties used by converter * to set some other properties or other things * Like change height of actor to fit with output game and so on ... */ public Map<String, Object> convertProperties = new HashMap<>(); /** * * @param names * @param game * @param t3dClass */ public Match(String[] names, UTGames.UTGame game, Class t3dClass){ this.actorClass.addAll(Arrays.asList(names)); this.game = game; this.engine = game.engine; this.t3dClass = t3dClass; } /** * * @param names * @param game * @param t3dClass * @param convertProperty */ public Match(String[] names, UTGames.UTGame game, Class t3dClass, String convertProperty){ this.actorClass.addAll(Arrays.asList(names)); this.game = game; this.engine = game.engine; this.t3dClass = t3dClass; this.convertProperties.put(convertProperty, null); } /** * * @param names * @param game */ public Match(String[] names, UTGames.UTGame game){ this.actorClass.addAll(Arrays.asList(names)); this.game = game; this.engine = game.engine; } /** * * @param names * @param engine */ public Match(String names, UTGames.UnrealEngine engine){ this.actorClass.addAll(Arrays.asList(names)); this.engine = engine; } /** * * @param property * @param value * @return */ public Match addP(String property, String value){ this.properties.put(property, value); return this; } } List<GlobalMatch> list; public T3DMatch(){ list = new ArrayList<>(); initialise(); } private GlobalMatch iByGame(Class t3dClass, String convertProp, String[] u1Class, String[] u2Class, String[] ut99Class, String[] ut2003Class, String[] ut2004Class, String[] ut3Class, String[] ut4Class){ List<Match> matches = new ArrayList<>(); if(u1Class != null){ matches.add(new Match(u1Class, UTGames.UTGame.U1, t3dClass, convertProp)); } if(u2Class != null){ matches.add(new Match(u2Class, UTGames.UTGame.U2, t3dClass, convertProp)); } if(ut99Class != null){ matches.add(new Match(ut99Class, UTGames.UTGame.UT99, t3dClass, convertProp)); } if(ut2003Class != null){ matches.add(new Match(ut2003Class, UTGames.UTGame.UT2003, t3dClass, convertProp)); } if(ut2004Class != null){ matches.add(new Match(ut2004Class, UTGames.UTGame.UT2004, t3dClass, convertProp)); } if(ut3Class != null){ matches.add(new Match(ut3Class, UTGames.UTGame.UT3, t3dClass, convertProp)); } if(ut4Class != null){ matches.add(new Match(ut4Class, UTGames.UTGame.UT4, t3dClass, convertProp)); } return new GlobalMatch(matches); } /** * * @param inputGame * @param outputGame * @return */ public HashMap<String, Match> getActorClassMatch(UTGames.UTGame inputGame, UTGames.UTGame outputGame){ boolean goodList = true; List<String> inputClasses = new ArrayList<>(); HashMap<String, Match> hm = new HashMap<>(); for(GlobalMatch matchesForName : list ){ for(Match matchForName : matchesForName.matches){ if(matchForName.game == inputGame && matchForName.t3dClass != null){ goodList = true; inputClasses = matchForName.actorClass; break; } } if(goodList){ for(Match matchForName : matchesForName.matches){ if(matchForName.game == outputGame){ for(String inputClass : inputClasses){ hm.put(inputClass, matchForName); } break; } } } } return hm; } /** * Tries to find out converted t3d actor inActorClass (if inActorClass has changed between ut games) * @param inActorClass * @param inputGame Input game map is being converted from * @param outputGame Output game map is being converted to * @param withT3dClass * @param inActorProps * @return */ public Match getMatchFor(String inActorClass, UTGames.UTGame inputGame, UTGames.UTGame outputGame, boolean withT3dClass, Map<String, String> inActorProps){ Match m = null; List<GlobalMatch> goodMatches = new ArrayList<>(); boolean superBreak = false; for(GlobalMatch matchesForName : list ){ for(Match matchForName : matchesForName.matches){ if(matchForName.game == inputGame && inActorClass != null && matchForName.actorClass.contains(inActorClass)){ // Useful? Normally any actor has properties ... if(inActorProps == null || inActorProps.isEmpty()){ break; } else { if(matchForName.properties == null || matchForName.properties.isEmpty()){ goodMatches.add(matchesForName); break; } else { // Current Actor properties match perfectly // properties needed, this is the good one for(String key : matchForName.properties.keySet()){ if(inActorProps.containsKey(key) && inActorProps.get(key).equals(matchForName.properties.get(key))){ goodMatches.clear(); goodMatches.add(matchesForName); superBreak = true; break; } } } } } } if(superBreak){ break; } } for(GlobalMatch matchesForName : goodMatches ){ for(Match matchForName : matchesForName.matches){ if(matchForName.game == outputGame){ return matchForName; } } } return m; } }
package poc.pc.manager; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.ibm.watson.developer_cloud.conversation.v1.model.MessageResponse; @Path("/hapvida") public class ChatHapVidaManager { @Inject private Conversation conversation; private static String workspaceId = "d6fe397a-343b-47b5-a132-a1def577b235"; private static String username = "fb3ea18a-08b4-48ee-ac83-630fe19a68ef"; private static String password = "6qOUoIn3UXnD"; @GET @Path("/json/{dialog}/{conversation_id}/{system}") @Produces("application/json") public String getDialog(@PathParam("dialog") String dialog, @PathParam("conversation_id") String conversation_id, @PathParam("system") String system) { conversation.setWorkspaceId(workspaceId); conversation.setUsername(username); conversation.setPassword(password); if ("000".equals(conversation_id)) { conversation_id = null; system = null; } MessageResponse createHelloMessage = validarRetorno(conversation.createHelloMessage(dialog, conversation_id, system)); return formJson(createHelloMessage); } private MessageResponse validarRetorno(MessageResponse response) { JsonParser parser = new JsonParser(); Object objSystem = parser.parse(response.getContext().get("system").toString()); JsonObject jsonObjectSystem = (JsonObject) objSystem; JsonObject JsonObjectNodeOutput = (JsonObject) jsonObjectSystem.get("_node_output_map"); JsonArray JsonArrayDialog_stack = (JsonArray) jsonObjectSystem.get("dialog_stack"); JsonObject JsonObjectDialog = (JsonObject) JsonArrayDialog_stack.get(0); JsonElement jsonStart = JsonObjectNodeOutput.get("start"); JsonElement jsonDocumento = JsonObjectNodeOutput.get("Documento"); JsonElement jsonTransferir = JsonObjectNodeOutput.get("Transferir"); if(jsonStart != null && jsonDocumento == null && jsonTransferir == null && !JsonObjectDialog.get("dialog_node").getAsString().equals("start")){ response.getText().remove(0); response.getText().add("OK, Eu entendi, mas poderia me dizer o código da sua carteira, ou o número do CPF do titular?"); response.getContext().put("system", "{dialog_stack=[{dialog_node=Documento}], dialog_turn_counter=2.0, dialog_request_counter=2.0, _node_output_map={start=[0.0], Documento=[0.0]}}"); return response; } return response; } private String formJson(MessageResponse response) { StringBuffer retorno = new StringBuffer(); JsonParser parser = new JsonParser(); Object objSystem = parser.parse(response.getContext().get("system").toString()); JsonObject jsonObjectSystem = (JsonObject) objSystem; JsonArray JsonArrayDialog_stack = (JsonArray) jsonObjectSystem.get("dialog_stack"); JsonObject JsonObjectDialog = (JsonObject) JsonArrayDialog_stack.get(0); retorno.append("{\""); retorno.append("result\":\"" + response.getText().get(0)); retorno.append("\","); retorno.append("\"conversation_id\":\"" + response.getContext().get("conversation_id")); retorno.append("\","); retorno.append("\"system\":\"" + response.getContext().get("system")); retorno.append("\","); retorno.append("\"audio\":\"" + JsonObjectDialog.get("dialog_node").getAsString().toString().toLowerCase()); retorno.append("\","); if("transferir".equals(JsonObjectDialog.get("dialog_node").getAsString().toString().toLowerCase())){ retorno.append("\"destino\":\"2070"); retorno.append("\","); } retorno.append("\"action\":\"" + getAction(response)); retorno.append("\"}"); return retorno.toString(); } private String getAction(MessageResponse response) { List<String> tagsFinais = new ArrayList<>(); tagsFinais.add("Agenda_Doutor"); tagsFinais.add("Agenda_Doutora"); tagsFinais.add("Fim_Agendamento"); tagsFinais.add("Transferir"); String returno = "continuar"; if(tagsFinais.contains(response.getOutput().get("nodes_visited").toString())){ returno = "finalizar"; } return returno; } }
package SpecmatePageClasses; import java.util.Objects; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; //Page Class public class LoginElements { WebDriver driver; //Elements and their locators By username = By.id("login-username-textfield"); By password = By.id("login-password-textfield"); By login = By.id("login-button"); By language = By.id("language-dropdown"); By german = By.id("language-de"); By english = By.id("language-gb"); By project = By.id("login-project-dropdown"); public LoginElements(WebDriver driver1) { this.driver = driver1; //constructor } /**enter username to username field*/ public void username(String un) { driver.findElement(username).sendKeys(un); } /**enter password to password field*/ public void password(String pw) { driver.findElement(password).sendKeys(pw); } /**click on Log In Button*/ public void login() { driver.findElement(login).click(); } /**change language to English using the language dropdown*/ public void changeToEnglish() { driver.findElement(language).click(); driver.findElement(english).click(); } /**change language to German using the language dropdown*/ public void changeToGerman() { driver.findElement(language).click(); driver.findElement(german).click(); } /**change project to <code>name</code> using the project dropdown*/ public void changeToProject(String name) { driver.findElement(project).click(); driver.findElement(By.id("project-" + name)).click(); } public boolean isLoggedIn() { String URL = driver.getCurrentUrl(); String expectedURL = "http://localhost:8080/-/welcome"; return Objects.equals(URL, expectedURL); } }
package seedu.address.logic.parser; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.commons.util.StringUtil; import seedu.address.logic.commands.AddCommand; import seedu.address.logic.commands.ClearCommand; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.DeleteCommand; import seedu.address.logic.commands.DoneCommand; import seedu.address.logic.commands.EditCommand; import seedu.address.logic.commands.ExitCommand; import seedu.address.logic.commands.FindCommand; import seedu.address.logic.commands.HelpCommand; import seedu.address.logic.commands.IncorrectCommand; import seedu.address.logic.commands.ListCommand; import seedu.address.logic.commands.RefreshCommand; import seedu.address.logic.commands.SaveCommand; import seedu.address.logic.commands.SelectCommand; import seedu.address.logic.commands.UndoCommand; import seedu.address.logic.commands.ViewCommand; /** * Parses user input. */ public class Parser { /** * Used for initial separation of command word and args. */ private static final Pattern BASIC_COMMAND_FORMAT = Pattern.compile("(?<commandWord>\\S+)(?<arguments>.*)"); private static final Pattern PERSON_INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); private static final Pattern KEYWORDS_ARGS_FORMAT = Pattern.compile("(?<keywords>\\S+(?:\\s+\\S+)*)"); // one or more keywords separated by whitespace private static final Pattern PERSON_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<name>[^/]+)" + "( d/(?<description>[^/]+)){0,1}" + "( date/(?<date>[^/]+)){0,1}" + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags private static final Pattern EDIT_DATA_ARGS_FORMAT = // '/' forward slashes are reserved for delimiter prefixes Pattern.compile("(?<index>[AB][\\d]+)" + "( (?<name>[^/]+)){0,1}" + "( d/(?<description>[^/]+)){0,1}" + "( date/(?<date>[^/]*)){0,1}" // group <date> can be blank to edit DatedTask -> UndatedTask + "(?<tagArguments>(?: t/[^/]+)*)"); // variable number of tags public Parser() {} /** * Parses user input into command for execution. * * @param userInput full user input string * @return the command based on the user input */ public Command parseCommand(String userInput) { final Matcher matcher = BASIC_COMMAND_FORMAT.matcher(userInput.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } final String commandWord = matcher.group("commandWord"); final String arguments = matcher.group("arguments"); switch (commandWord.toLowerCase()) { case AddCommand.COMMAND_WORD: return prepareAdd(arguments); case SelectCommand.COMMAND_WORD: case SelectCommand.COMMAND_ALIAS: return prepareSelect(arguments); case DoneCommand.COMMAND_WORD: return prepareDone(arguments); case DeleteCommand.COMMAND_WORD: case DeleteCommand.COMMAND_ALIAS: return prepareDelete(arguments); case EditCommand.COMMAND_WORD: return prepareEdit(arguments); case ClearCommand.COMMAND_WORD: return new ClearCommand(); case UndoCommand.COMMAND_WORD: return new UndoCommand(); case FindCommand.COMMAND_WORD: return prepareFind(arguments); case ListCommand.COMMAND_WORD: case ListCommand.COMMAND_ALIAS: return prepareList(arguments); case SaveCommand.COMMAND_WORD: return prepareSave(arguments); case ExitCommand.COMMAND_WORD: return new ExitCommand(); case HelpCommand.COMMAND_WORD: return new HelpCommand(); case RefreshCommand.COMMAND_WORD: return new RefreshCommand(); case ViewCommand.COMMAND_WORD: return prepareView(arguments); default: return new IncorrectCommand(MESSAGE_UNKNOWN_COMMAND); } } //@@author A0143884W /** * Parses arguments in the context of the view task command. * * @param args full command args string * @return the prepared command */ private Command prepareView(String arguments) { try { return new ViewCommand(arguments); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } /** * Parses arguments in the context of the add task command. * * @param args full command args string * @return the prepared command */ private Command prepareAdd(String args){ final Matcher matcher = PERSON_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE)); } try { return new AddCommand( matcher.group("name"), matcher.group("description"), matcher.group("date"), getTagsFromArgs(matcher.group("tagArguments")) ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } //@@author /** * Extracts the new person's tags from the add command's tag arguments string. * Merges duplicate tag strings. */ private static Set<String> getTagsFromArgs(String tagArguments) throws IllegalValueException { // no tags if (tagArguments.isEmpty()) { return Collections.emptySet(); } // replace first delimiter prefix, then split final Collection<String> tagStrings = Arrays.asList(tagArguments.replaceFirst(" t/", "").split(" t/")); return new HashSet<>(tagStrings); } /** * Parses arguments in the context of the delete person command. * * @param args full command args string * @return the prepared command */ private Command prepareDelete(String args) { Optional<String> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE)); } return new DeleteCommand(index.get()); } //@@author A0139145E /** * Parses arguments in the context of the done task command. * * @param args full command args string * @return the prepared command */ private Command prepareDone(String args) { Optional<String> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, DoneCommand.MESSAGE_USAGE)); } return new DoneCommand(index.get()); } //@@author //@@author A0143884W /** * Parses arguments in the context of the edit person command. * * @param args full command args string * @return the prepared command */ private Command prepareEdit(String args) { final Matcher matcher = EDIT_DATA_ARGS_FORMAT.matcher(args.trim()); // Validate arg string format if (!matcher.matches()) { return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, EditCommand.MESSAGE_USAGE)); } try { return new EditCommand( (matcher.group("index")), matcher.group("name"), matcher.group("description"), matcher.group("date"), getTagsFromArgs(matcher.group("tagArguments")) ); } catch (IllegalValueException ive) { return new IncorrectCommand(ive.getMessage()); } } //@@author /** * Parses arguments in the context of the select person command. * * @param args full command args string * @return the prepared command */ private Command prepareSelect(String args) { Optional<String> index = parseIndex(args); if(!index.isPresent()){ return new IncorrectCommand( String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE)); } return new SelectCommand(index.get()); } /** * Returns the specified index in the {@code command} IF a positive unsigned integer is given as the index. * Returns an {@code Optional.empty()} otherwise. */ private Optional<String> parseIndex(String command) { final Matcher matcher = PERSON_INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if ((index.split(" ")).length == 1 && StringUtil.isUnsignedInteger(index.substring(1))) { return Optional.of(index); } else { return Optional.empty(); } } /** * Parses arguments in the context of the find person command. * * @param args full command args string * @return the prepared command */ private Command prepareFind(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE)); } // keywords delimited by whitespace final String[] keywords = matcher.group("keywords").split("\\s+"); final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords)); return new FindCommand(keywordSet); } //@@author A0139145E /** * Parses arguments in the context of the list task command. * * @param args full command args string * @return the prepared command */ private Command prepareList(String args) { final Matcher matcher = KEYWORDS_ARGS_FORMAT.matcher(args.trim()); if (!matcher.matches()) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_LIST_USAGE)); } final String[] keywords = matcher.group("keywords").split("\\s+"); if (keywords.length > 1) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ListCommand.MESSAGE_LIST_USAGE)); } try { return new ListCommand(keywords[0]); } catch (IllegalValueException ive) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ive.getMessage())); } } //@@author //@@author A0139528W /** * Parses arguments in the context of the save folder command. * * @param args full command args string * @return the prepared command */ private Command prepareSave(String args) { if (args.trim().length() == 0) { return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE)); } return new SaveCommand(args); } //@@author }
package seedu.address.model.task; import seedu.address.commons.exceptions.IllegalValueException; /** * Represents a Task's priority in the task manager. * Guarantees: immutable; is valid as declared in {@link #isValidPriority(String)} */ public class Priority { public static final String MESSAGE_PRIORITY_CONSTRAINTS = "Task priority should /low, /medium or /high"; // public static final String PRIORITY_VALIDATION_REGEX = "(high|medium|low)"; public static final String HIGH = "high"; public static final String MEDIUM = "medium"; public static final String LOW = "low"; public static final String NONE = ""; public final String value; /** * Creates a default priority object, which has value "low" * * @author A0139661Y */ public Priority() { value = LOW; } public Priority(String priority) throws IllegalValueException { assert priority != null; if (!isValidPriority(priority)) { throw new IllegalValueException(MESSAGE_PRIORITY_CONSTRAINTS); } this.value = priority.toLowerCase(); } /** * Returns true if a given string is a valid priority. * * @author A0139661Y */ public static boolean isValidPriority(String testString) { // return test.matches(PRIORITY_VALIDATION_REGEX); String test = testString.toLowerCase(); if (test.equals(HIGH) || test.equals((MEDIUM)) || test.equals(LOW) || test.equals(NONE)) return true; return false; } @Override public String toString() { return value; } /* @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Priority // instanceof handles nulls && this.value.equals(((Priority) other).value)); // state check } */ @Override public int hashCode() { return value.hashCode(); } }