answer
stringlengths
17
10.2M
package owltools.web; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import java.util.Vector; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.coode.owlapi.obo.parser.OBOOntologyFormat; import org.obolibrary.macro.ManchesterSyntaxTool; import org.semanticweb.owlapi.expression.ParserException; import org.semanticweb.owlapi.io.OWLFunctionalSyntaxOntologyFormat; import org.semanticweb.owlapi.io.OWLXMLOntologyFormat; import org.semanticweb.owlapi.io.RDFXMLOntologyFormat; import org.semanticweb.owlapi.model.AxiomType; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLAnnotation; import org.semanticweb.owlapi.model.OWLAxiom; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLClassAssertionAxiom; import org.semanticweb.owlapi.model.OWLClassExpression; import org.semanticweb.owlapi.model.OWLDataFactory; import org.semanticweb.owlapi.model.OWLIndividual; import org.semanticweb.owlapi.model.OWLNamedIndividual; import org.semanticweb.owlapi.model.OWLNamedObject; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLObjectProperty; import org.semanticweb.owlapi.model.OWLObjectPropertyAssertionAxiom; import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom; import org.semanticweb.owlapi.model.OWLOntology; import org.semanticweb.owlapi.model.OWLOntologyCreationException; import org.semanticweb.owlapi.model.OWLOntologyFormat; import org.semanticweb.owlapi.model.OWLOntologyStorageException; import org.semanticweb.owlapi.reasoner.Node; import org.semanticweb.owlapi.reasoner.OWLReasoner; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import owltools.gaf.inference.TaxonConstraintsEngine; import owltools.gaf.lego.MolecularModelManager; import owltools.gaf.lego.MolecularModelManager.OWLOperationResponse; import owltools.gfx.GraphicsConfig; import owltools.gfx.OWLGraphLayoutRenderer; import owltools.graph.OWLGraphEdge; import owltools.graph.OWLGraphWrapper; import owltools.io.OWLGsonRenderer; import owltools.io.OWLPrettyPrinter; import owltools.io.ParserWrapper; import owltools.mooncat.Mooncat; import owltools.sim2.FastOwlSim; import owltools.sim2.OwlSim; import owltools.sim2.OwlSim.ScoreAttributeSetPair; import owltools.sim2.SimJSONEngine; import owltools.sim2.SimpleOwlSim; import owltools.sim2.SimpleOwlSim.Metric; import owltools.sim2.SimpleOwlSim.ScoreAttributePair; import owltools.sim2.UnknownOWLClassException; import owltools.vocab.OBOUpperVocabulary; public class OWLHandler { private static Logger LOG = Logger.getLogger(OWLHandler.class); private OWLGraphWrapper graph; private HttpServletResponse response; private HttpServletRequest request; private OWLPrettyPrinter owlpp; private OWLServer owlserver; private String format = null; private String commandName; private OwlSim sos; // consider replacing with a generic result list private Set<OWLAxiom> cachedAxioms = new HashSet<OWLAxiom>(); private Set<OWLObject> cachedObjects = new HashSet<OWLObject>(); // not yet implemented -- // for owl, edges are translated to expressions. // axioms are added to an ontology // expressions? temp ontology? public enum ResultType { AXIOM, ENTITY, EDGE, ONTOLOGY } public enum Param { id, iri, label, taxid, expression, format, direct, reflexive, target, limit, ontology, classId, individualId, propertyId, fillerId, a, b, modelId } public OWLHandler(OWLServer owlserver, OWLGraphWrapper graph, HttpServletRequest request, HttpServletResponse response) throws IOException { super(); this.owlserver = owlserver; this.graph = graph; this.request = request; this.response = response; //this.writer = response.getWriter(); this.owlpp = new OWLPrettyPrinter(graph); } public String getFormat() { String fmtParam = getParam(Param.format); if (fmtParam != null && !fmtParam.equals("")) return fmtParam; if (format == null) return "txt"; return format; } public void setOwlSim(OwlSim sos2) { this.sos = sos2; } public void setFormat(String format) { this.format = format; } public String getCommandName() { return commandName; } public void setCommandName(String commandName) { this.commandName = commandName; } // COMMANDS public void topCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException { if (isHelp()) { info("Basic metadata about current ontology"); // TODO - json return; } headerHTML(); outputLine("<h1>OntologyID: "+this.getOWLOntology().getOntologyID()+"</h2>"); outputLine("<ul>"); for (OWLAnnotation ann : getOWLOntology().getAnnotations()) { outputLine("<li>"); output(ann.getProperty()); outputLine("<b>"+ann.getValue().toString()+"</b>"); outputLine("</li>"); } outputLine("</ul>"); } public void helpCommand() throws IOException { headerHTML(); List<String> commands = new ArrayList<String>(); outputLine("<ul>"); for (Method m : this.getClass().getMethods()) { String mn = m.getName(); if (mn.endsWith("Command")) { String c = mn.replace("Command", ""); commands.add(c); outputLine("<li>"+c+"</li>"); } } outputLine("</ul>"); } /** * Params: direct, (id | expression) * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @throws IOException * @throws ParserException */ public void getSubClassesCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, ParserException { headerOWL(); boolean direct = getParamAsBoolean(Param.direct, false); OWLReasoner r = getReasoner(); OWLClassExpression cls = this.resolveClassExpression(); LOG.info("finding subclasses of: "+cls+" using "+r); int n = 0; for (OWLClass sc : r.getSubClasses(cls, direct).getFlattened()) { output(sc); n++; } if (getParamAsBoolean(Param.reflexive, true)) { for (OWLClass sc : r.getEquivalentClasses(cls)) { output(sc); } n++; } LOG.info("results: "+n); } /** * Params: direct, (id | expression) * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @throws IOException * @throws ParserException */ public void getSuperClassesCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, ParserException { headerOWL(); boolean direct = getParamAsBoolean(Param.direct, false); OWLReasoner r = getReasoner(); OWLClassExpression cls = this.resolveClassExpression(); LOG.info("finding superclasses of: "+cls); LOG.info("R:"+r.getSuperClasses(cls, direct)); for (OWLClass sc : r.getSuperClasses(cls, direct).getFlattened()) { output(sc); } if (getParamAsBoolean(Param.reflexive, true)) { for (OWLClass sc : r.getEquivalentClasses(cls)) { output(sc); } } } /** * Params: id * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @throws IOException * @throws ParserException */ public void getAxiomsCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, ParserException { headerOWL(); boolean direct = getParamAsBoolean(Param.direct, false); OWLObject obj = this.resolveEntity(); LOG.info("finding axioms about: "+obj); Set<OWLAxiom> axioms = new HashSet<OWLAxiom>(); if (obj instanceof OWLClass) { axioms.addAll(graph.getSourceOntology().getAxioms((OWLClass)obj)); } if (obj instanceof OWLIndividual) { axioms.addAll(graph.getSourceOntology().getAxioms((OWLIndividual)obj)); } if (obj instanceof OWLObjectProperty) { axioms.addAll(graph.getSourceOntology().getAxioms((OWLObjectProperty)obj)); } for (OWLAxiom ax : axioms) { output(ax); } } /** * Params: direct * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @throws IOException */ public void allSubClassOfCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException { headerOWL(); boolean direct = getParamAsBoolean(Param.direct, true); OWLReasoner r = getReasoner(); for (OWLClass c : getOWLOntology().getClassesInSignature(true)) { for (OWLClass sc : r.getSuperClasses(c, direct).getFlattened()) { output(graph.getDataFactory().getOWLSubClassOfAxiom(c, sc)); } } } public void getOutgoingEdgesCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException { if (isHelp()) { info("Returns paths to reachable nodes in ontology graph"); return; } headerOWL(); boolean isClosure = getParamAsBoolean("closure", true); boolean isReflexive = getParamAsBoolean("reflexive", true); OWLObject obj = this.resolveEntity(); LOG.info("finding edges from: "+obj); for (OWLGraphEdge e : graph.getOutgoingEdges(obj,isClosure,isReflexive)) { output(e); } } /** * @throws IOException * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @see owltools.sim.SimEngine */ @Deprecated // public void lcsExpressionCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException { // if (isHelp()) { // info("Returns least common subsumer class expression using OWLSim"); // return; // headerOWL(); // Set<OWLObject> objs = this.resolveEntityList(); // if (objs.size() == 2) { // SimEngine se = new SimEngine(graph); // OWLObject[] objsA = objs.toArray(new OWLObject[objs.size()]); // OWLClassExpression lcs = se.getLeastCommonSubsumerSimpleClassExpression(objsA[0], objsA[1]); // else { // // TODO - throw /** * information about an ontology object (class, property, individual) * * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @throws IOException */ public void aboutCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException { if (isHelp()) { info("Returns logical relationships and metadata associated with an ontology object"); return; } headerOWL(); String id = this.getParam(Param.id); OWLClass cls = graph.getOWLClassByIdentifier(id); for (OWLAxiom axiom : getOWLOntology().getAxioms(cls)) { output(axiom); } for (OWLAxiom axiom : getOWLOntology().getAnnotationAssertionAxioms(cls.getIRI())) { output(axiom); } } /** * visualize using QuickGO graphdraw. * * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @throws IOException */ public void qvizCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException { String fmt = "png"; headerImage(fmt); GraphicsConfig gfxCfg = new GraphicsConfig(); Set<OWLObject> objs = resolveEntityList(); OWLGraphLayoutRenderer r = new OWLGraphLayoutRenderer(graph); r.graphicsConfig = gfxCfg; r.addObjects(objs); r.renderImage(fmt, response.getOutputStream()); } /** * generates a sub-ontology consisting only of classes specified using the id param. * If the include_ancestors param is true, then the transitive closure of the input classes is * included. otherwise, intermediate classes are excluded and paths are filled. * * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @throws IOException * @see Mooncat#makeMinimalSubsetOntology(Set, IRI) */ public void makeSubsetOntologyCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException { headerOWL(); Set<OWLClass> objs = resolveClassList(); Set<OWLClass> tObjs = new HashSet<OWLClass>(); if (getParamAsBoolean("include_ancestors")) { // TODO - more more efficient for (OWLClass obj : objs) { for (OWLObject t : graph.getAncestorsReflexive(obj)) { tObjs.add((OWLClass)t); } } } else { tObjs = objs; } Mooncat mooncat; mooncat = new Mooncat(graph); OWLOntology subOnt = mooncat.makeMinimalSubsetOntology(tObjs, IRI.create("http://purl.obolibrary.org/obo/temporary")); for (OWLAxiom axiom : subOnt.getAxioms()) { output(axiom); // TODO } graph.getManager().removeOntology(subOnt); } /** * tests which of a set of input classes (specified using id) is applicable for a set of taxa * (specified using taxid) * * @throws OWLOntologyCreationException * @throws OWLOntologyStorageException * @throws IOException */ public void isClassApplicableForTaxonCommand() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException { headerOWL(); TaxonConstraintsEngine tce = new TaxonConstraintsEngine(graph); Set<OWLClass> testClsSet = resolveClassList(); Set<OWLClass> testTaxSet = resolveClassList(Param.taxid); for (OWLClass testTax : testTaxSet) { Set<OWLObject> taxAncs = graph.getAncestorsReflexive(testTax); LOG.info("Tax ancs: "+taxAncs); for (OWLClass testCls : testClsSet) { Set<OWLGraphEdge> edges = graph.getOutgoingEdgesClosure(testCls); boolean isOk = tce.isClassApplicable(testCls, testTax, edges, taxAncs); // TODO - other formats output(testCls); print("\t"); output(testTax); outputLine("\t"+isOk); } } } // sim2 private OwlSim getOWLSim() throws UnknownOWLClassException { if (owlserver.sos == null) { LOG.info("Creating sim object"); // TODO - use factory owlserver.sos = new FastOwlSim(graph.getSourceOntology()); owlserver.sos.createElementAttributeMapFromOntology(); } return owlserver.sos; } public void getSimilarClassesCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("Returns semantically similar classes using OWLSim2"); return; } headerOWL(); OWLClass a = this.resolveClass(); OwlSim sos = getOWLSim(); List<ScoreAttributeSetPair> saps = new ArrayList<ScoreAttributeSetPair>(); for (OWLClass b : this.getOWLOntology().getClassesInSignature()) { double score = sos.getAttributeJaccardSimilarity(a, b); saps.add(new ScoreAttributeSetPair(score, b) ); } Collections.sort(saps); int limit = 100; int n=0; for (ScoreAttributeSetPair sap : saps) { output(sap.getArbitraryAttributeClass()); this.outputLine("score="+sap.score); // todo - jsonify n++; if (n > limit) { break; } } } public void getSimilarIndividualsCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("Returns matching individuals using OWLSim2"); return; } headerOWL(); OWLNamedIndividual i = (OWLNamedIndividual) this.resolveEntity(); LOG.info("i="+i); if (i == null) { LOG.error("Could not resolve id"); // TODO - throw return; } OwlSim sos = getOWLSim(); List<ScoreAttributeSetPair> saps = new Vector<ScoreAttributeSetPair>(); for (OWLNamedIndividual j : this.getOWLOntology().getIndividualsInSignature()) { // TODO - make configurable ScoreAttributeSetPair match = sos.getSimilarityMaxIC(i, j); saps.add(match); } Collections.sort(saps); int limit = 100; // todo - configurable int n=0; for (ScoreAttributeSetPair sap : saps) { //output(sap.attributeClass); TODO this.outputLine("score="+sap.score); // todo - jsonify n++; if (n > limit) { break; } } } public void getLowestCommonSubsumersCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("Returns LCSs using sim2"); return; } headerOWL(); OwlSim sos = getOWLSim(); Set<OWLObject> objs = this.resolveEntityList(); if (objs.size() == 2) { Iterator<OWLObject> oit = objs.iterator(); OWLClass a = (OWLClass) oit.next(); OWLClass b = (OWLClass) oit.next(); Set<Node<OWLClass>> lcsNodes = sos.getNamedCommonSubsumers(a, b); for (Node<OWLClass> n : lcsNodes) { for (OWLClass c : n.getEntities()) { output(c); } } } else { // TODO - throw } } public void compareAttributeSetsCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("Returns LCSs and their ICs for two sets of attributes (e.g. phenotypes for disease vs model) using sim2"); return; } headerText(); OwlSim sos = getOWLSim(); Set<OWLClass> objAs = this.resolveClassList(Param.a); Set<OWLClass> objBs = this.resolveClassList(Param.b); LOG.info("Comparison set A:"+objAs); LOG.info("Comparison set B:"+objBs); SimJSONEngine sj = new SimJSONEngine(graph,sos); String jsonStr = sj.compareAttributeSetPair(objAs, objBs, true); LOG.info("Finished comparison"); response.getWriter().write(jsonStr); } public void searchByAttributeSetCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("Entities that have a similar attribute profile to the specified one, using sim2"); return; } headerText(); OwlSim sos = getOWLSim(); Set<OWLClass> atts = this.resolveClassList(Param.a); SimJSONEngine sj = new SimJSONEngine(graph,sos); String targetIdSpace = getParam(Param.target); Integer limit = getParamAsInteger(Param.limit, 1000); String jsonStr = sj.search(atts, targetIdSpace, true, limit); LOG.info("Finished comparison"); response.getWriter().write(jsonStr); } // WRITE/UPDATE OPERATIONS @Deprecated public void assertTypeCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("generates ClassAssertion"); return; } OWLOntology ont = resolveOntology(Param.ontology); OWLClass c = resolveClass(Param.classId); OWLIndividual i = resolveIndividual(Param.individualId); addAxiom(ont, graph.getDataFactory().getOWLClassAssertionAxiom(c, i)); String jsonStr = ""; response.getWriter().write(jsonStr); } @Deprecated public void assertFactCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("generates ClassAssertion"); return; } OWLOntology ont = resolveOntology(Param.ontology); OWLIndividual i = resolveIndividual(Param.individualId); OWLIndividual j = resolveIndividual(Param.fillerId); OWLObjectProperty p = resolveObjectProperty(Param.propertyId); addAxiom(ont, graph.getDataFactory().getOWLObjectPropertyAssertionAxiom(p, i, j)); String jsonStr = ""; response.getWriter().write(jsonStr); } @Deprecated public void deleteFactCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("generates ClassAssertion"); return; } OWLOntology ont = resolveOntology(Param.ontology); OWLIndividual i = resolveIndividual(Param.individualId); OWLIndividual j = resolveIndividual(Param.fillerId); OWLObjectProperty p = resolveObjectProperty(Param.propertyId); for (OWLObjectPropertyAssertionAxiom ax : ont.getAxioms(AxiomType.OBJECT_PROPERTY_ASSERTION)) { if (ax.getSubject().equals(i)) { if (p == null || ax.getProperty().equals(p)) { if (j == null || ax.getObject().equals(j)) { removeAxiom(ont, graph.getDataFactory().getOWLObjectPropertyAssertionAxiom(p, i, j)); } } } } String jsonStr = ""; response.getWriter().write(jsonStr); } // Note these may eventually be replaced by either JAX-RS REST calls // or COMET/WebSockets private MolecularModelManager getMolecularModelManager() throws UnknownOWLClassException, OWLOntologyCreationException { if (owlserver.molecularModelManager == null) { LOG.info("Creating m3 object"); // TODO - use factory owlserver.molecularModelManager = new MolecularModelManager(graph); } return owlserver.molecularModelManager; } // TODO!!! private void returnResponse(OWLOperationResponse resp) throws IOException { // TODO Auto-generated method stub response.getWriter().write("{status:\"ok\"}"); } public void returnJSON(Object obj) throws IOException { Gson gson = new GsonBuilder().setPrettyPrinting().create(); String js = gson.toJson(obj); response.getWriter().write(js); } // m3 commands public void m3CreateIndividualCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("generates ObjectPropertyAssertion"); return; } MolecularModelManager mmm = getMolecularModelManager(); String id = mmm.createIndividual(getParam(Param.modelId), getParam(Param.classId)); response.getWriter().write("{\"id\":\""+id+"\"}"); } public void m3AddTypeCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("generates ClassAssertion"); return; } MolecularModelManager mmm = getMolecularModelManager(); OWLOperationResponse resp = mmm.addType(getParam(Param.ontology), getParam(Param.individualId), getParam(Param.classId)); returnResponse(resp); } public void m3AddFactCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("generates ObjectPropertyAssertion"); return; } MolecularModelManager mmm = getMolecularModelManager(); OWLOperationResponse resp = mmm.addFact(getParam(Param.propertyId), getParam(Param.ontology), getParam(Param.individualId), getParam(Param.classId)); returnResponse(resp); } public void m3RemoveFactCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("generates ObjectPropertyAssertion"); return; } MolecularModelManager mmm = getMolecularModelManager(); OWLOperationResponse resp = mmm.removeFact(getParam(Param.propertyId), getParam(Param.ontology), getParam(Param.individualId), getParam(Param.classId)); returnResponse(resp); } public void m3GetModelCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("fetches molecular model json"); return; } MolecularModelManager mmm = getMolecularModelManager(); Map<String, Object> obj = mmm.getModelObject(getParam(Param.modelId)); returnJSON(obj); } public void assertEnabledByCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("generates ClassAssertion"); return; } OWLOntology ont = resolveOntology(Param.ontology); OWLIndividual i = resolveIndividual(Param.individualId); OWLClass j = resolveClass(Param.fillerId); OWLObjectProperty p = OBOUpperVocabulary.GOREL_enabled_by.getObjectProperty(graph.getDataFactory()); addSomeValuesFromClassAssertion(ont, i, j, p); String jsonStr = ""; response.getWriter().write(jsonStr); } public void assertOccursInCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("generates ClassAssertion"); return; } OWLOntology ont = resolveOntology(Param.ontology); OWLIndividual i = resolveIndividual(Param.individualId); OWLClass j = resolveClass(Param.fillerId); OWLObjectProperty p = OBOUpperVocabulary.BFO_occurs_in.getObjectProperty(graph.getDataFactory()); addSomeValuesFromClassAssertion(ont, i, j, p); String jsonStr = ""; response.getWriter().write(jsonStr); } public void generateMolecularModelCommand() throws IOException, OWLOntologyCreationException, OWLOntologyStorageException, UnknownOWLClassException { if (isHelp()) { info("generates Minimal Model augmented with GO associations"); return; } // TODO String jsonStr = ""; response.getWriter().write(jsonStr); } // END OF COMMANDS // UTIL private void addSomeValuesFromClassAssertion(OWLOntology ont, OWLIndividual i, OWLClass j, OWLObjectProperty p) { OWLDataFactory df = ont.getOWLOntologyManager().getOWLDataFactory(); OWLObjectSomeValuesFrom svf = df.getOWLObjectSomeValuesFrom(p, j); addAxiom(ont, df.getOWLClassAssertionAxiom(svf, i)); } private void addAxiom(OWLOntology ont, OWLAxiom ax) { LOG.info("Added: " + ax); // TODO - rollbacks graph.getManager().addAxiom(ont, ax); } private void removeAxiom(OWLOntology ont, OWLAxiom ax) { LOG.info("Removed: " + ax); // TODO - rollbacks graph.getManager().removeAxiom(ont, ax); } private OWLObject resolveEntity() { String id = getParam(Param.id); if (!id.contains(":")) id = id.replace("_", ":"); return graph.getOWLObjectByIdentifier(id); } private OWLClass resolveClass() { String id = getParam(Param.id); return graph.getOWLClassByIdentifier(id); } private OWLClass resolveClass(Param p) { String id = getParam(p); return graph.getOWLClassByIdentifier(id); } private OWLClass resolveClassByLabel() { String id = getParam(Param.label); return (OWLClass) graph.getOWLObjectByLabel(id); } private OWLClassExpression resolveClassExpression() throws ParserException { if (hasParam(Param.id)) { return resolveClass(); } String expr = getParam(Param.expression); ManchesterSyntaxTool parser = new ManchesterSyntaxTool(graph.getSourceOntology(), graph.getSupportOntologySet()); return parser.parseManchesterExpression(expr); } private OWLIndividual resolveIndividual(Param p) { String id = getParam(p); return graph.getOWLIndividualByIdentifier(id); } private OWLObjectProperty resolveObjectProperty(Param p) { String id = getParam(p); return graph.getOWLObjectPropertyByIdentifier(id); } private Set<OWLObject> resolveEntityList() { return resolveEntityList(Param.id); } private Set<OWLObject> resolveEntityList(Param p) { String[] ids = getParams(p); Set<OWLObject> objs = new HashSet<OWLObject>(); for (String id : ids) { // TODO - unresolvable objs.add(graph.getOWLObjectByIdentifier(id)); } return objs; } private Set<OWLClass> resolveClassList() { return resolveClassList(Param.id); } private OWLOntology resolveOntology(Param p) { String oid = getParam(p); for (OWLOntology ont : graph.getManager().getOntologies()) { String iri = ont.getOntologyID().getOntologyIRI().toString(); // HACK if (iri.endsWith("/"+oid)) { return ont; } } return null; } private Set<OWLClass> resolveClassList(Param p) { String[] ids = getParams(p); Set<OWLClass> objs = new HashSet<OWLClass>(); LOG.info("Param "+p+" IDs: "+ids); for (String id : ids) { OWLClass c = graph.getOWLClassByIdentifier(id); if (c == null) { // TODO - strict mode - for now we include unresolvable classes IRI iri = graph.getIRIByIdentifier(id); c = graph.getDataFactory().getOWLClass(iri); } objs.add(c); } LOG.info("Num objs: "+objs.size()); return objs; } public void info(String msg) throws IOException { headerHTML(); outputLine("<h2>Command: "+this.getCommandName()+"</h2>"); outputLine(msg); } public void headerHTML() { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); } public void headerText() { response.setContentType("text/plain;charset-utf-8"); response.setStatus(HttpServletResponse.SC_OK); } public void headerImage(String fmt) { response.setContentType("image/"+fmt); response.setStatus(HttpServletResponse.SC_OK); } public void headerOWL() { if (isOWLOntologyFormat()) { LOG.info("using OWL ontology header"); OWLOntologyFormat ofmt = this.getOWLOntologyFormat(); if (ofmt instanceof RDFXMLOntologyFormat) { response.setContentType("application/rdf+xml;charset-utf-8"); } else if (ofmt instanceof OWLXMLOntologyFormat) { response.setContentType("application/xml;charset-utf-8"); } else { response.setContentType("text/plain;charset-utf-8"); } } else { response.setContentType("text/plain;charset-utf-8"); } response.setStatus(HttpServletResponse.SC_OK); } private void output(OWLAxiom axiom) throws IOException { String fmt = getFormat(); if (fmt == null) fmt = ""; if (fmt.equals("plain")) outputLine(axiom.toString()); else if (isOWLOntologyFormat(fmt)) { cache(axiom); } else if (fmt.equals("json")) { cache(axiom); } else outputLine(owlpp.render(axiom)); } private void outputLine(String s) throws IOException { getWriter().println(s); } private void print(String s) throws IOException { getWriter().print(s); } private void output(OWLObject obj) throws IOException { String fmt = getFormat(); if (fmt.equals("pretty")) outputLine(owlpp.render(obj)); else if (fmt.equals("json")) { //JSONPrinter jsonp = new JSONPrinter(response.getWriter()); //jsonp.render(obj); cache(obj); } else if (isOWLOntologyFormat()) { // TODO - place objects into ontology, eg as subclass of result outputLine(obj.toString()); } else { // TODO - do this more generically, e.g. within owlpp if (getParam("idstyle") != null && obj instanceof OWLNamedObject) { if (getParam("idstyle").toLowerCase().equals("obo")) { outputLine(graph.getIdentifier(obj)); } else { outputLine(obj.toString()); } } else print(obj.toString()); } } private void output(OWLGraphEdge e) throws IOException { if (isOWLOntologyFormat() || getFormat().equals("json")) { // todo - json format for edge OWLObject x = graph.edgeToTargetExpression(e); LOG.info("EdgeToX:"+x); output(x); } else { outputLine(owlpp.render(e)); // todo - cache } } /* private void cache(OWLAxiom axiom) { cachedAxioms.add(axiom); } */ private void cache(OWLObject obj) { cachedObjects.add(obj); } // when the result list is a collection of owl objects, we wait until // we have collected everything and then generate the results such that // the result conforms to the specified owl syntax. // TODO - redo this. Instead generate result objects public void printCachedObjects() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException { if (getFormat().equals("json")) { OWLGsonRenderer jsonp = new OWLGsonRenderer(response.getWriter()); if (cachedObjects.size() > 0) { jsonp.render(cachedObjects); } else { jsonp.render(cachedAxioms); } } else { // ontology format if (cachedAxioms.size() == 0) return; OWLOntology tmpOnt = getTemporaryOntology(); graph.getManager().addAxioms(tmpOnt, cachedAxioms); OWLOntologyFormat ofmt = getOWLOntologyFormat(); LOG.info("Format:"+ofmt); ParserWrapper pw = new ParserWrapper(); //graph.getManager().saveOntology(tmpOnt, ofmt, response.getOutputStream()); pw.saveOWL(tmpOnt, ofmt, response.getOutputStream(), null); graph.getManager().removeOntology(tmpOnt); cachedAxioms = new HashSet<OWLAxiom>(); } } // always remember to remove private OWLOntology getTemporaryOntology() throws OWLOntologyCreationException { UUID uuid = UUID.randomUUID(); IRI iri = IRI.create("http://purl.obolibrary.org/obo/temporary/"+uuid.toString()); //OWLOntology tmpOnt = graph.getManager().getOntology(iri); //if (iri == null) return graph.getManager().createOntology(iri); } private OWLOntologyFormat getOWLOntologyFormat() { return getOWLOntologyFormat(getFormat()); } private OWLOntologyFormat getOWLOntologyFormat(String fmt) { OWLOntologyFormat ofmt = null; fmt = fmt.toLowerCase(); if (fmt.equals("rdfxml")) ofmt = new RDFXMLOntologyFormat(); else if (fmt.equals("owl")) ofmt = new RDFXMLOntologyFormat(); else if (fmt.equals("rdf")) ofmt = new RDFXMLOntologyFormat(); else if (fmt.equals("owx")) ofmt = new OWLXMLOntologyFormat(); else if (fmt.equals("owf")) ofmt = new OWLFunctionalSyntaxOntologyFormat(); else if (fmt.equals("obo")) ofmt = new OBOOntologyFormat(); return ofmt; } private boolean isOWLOntologyFormat() { return isOWLOntologyFormat(getFormat()); } private boolean isOWLOntologyFormat(String fmt) { return getOWLOntologyFormat(fmt) != null; } private OWLReasoner getReasoner() { String rn = getParam("reasoner"); if (rn == null) { rn = "default"; } return owlserver.getReasoner(rn); } private boolean hasParam(Param p) { String v = request.getParameter(p.toString()); if (v == null || v.equals("")) return false; return true; } /** * @param p * @return the value of http parameter with key p */ private String getParam(Param p) { return request.getParameter(p.toString()); } private String getParam(String p) { return request.getParameter(p); } private String[] getParams(Param p) { return request.getParameterValues(p.toString()); } private String[] getParams(String p) { return request.getParameterValues(p); } private boolean isHelp() { return getParamAsBoolean("help"); } private boolean getParamAsBoolean(Param p) { return getParamAsBoolean(p.toString(), false); } private boolean getParamAsBoolean(String p) { return getParamAsBoolean(p, false); } private boolean getParamAsBoolean(Param p, boolean def) { return getParamAsBoolean(p.toString(), def); } private boolean getParamAsBoolean(String p, boolean def) { String r = request.getParameter(p); if (r != null && r.toLowerCase().equals("true")) return true; if (r != null && r.toLowerCase().equals("false")) return false; else return def; } private Integer getParamAsInteger(Param p, Integer def) { String sv = request.getParameter(p.toString()); if (sv == null || sv.equals("")) return def; Integer v = Integer.valueOf(sv); if (v == null) { v = def; } return v; } private PrintWriter getWriter() throws IOException { return response.getWriter(); } private OWLOntology getOWLOntology() { return graph.getSourceOntology(); } }
package uk.me.karlsen.ode; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class BaseMonster { private long animationSize; private long seedingSize; private long animationFilePointer; private String animationFileName; private long secondAttack; private long soundPointer; private long hasSecondAttackSound; private long usesTrnToModColor; private long trnPointer; private long idleFrameset; private long walkFrameset; private long attackFrameset; private long hitRecoveryFrameset; private long deathFrameset; private long secondAttackFrameset; private long idlePlaybackSpeed; private long walkPlaybackSpeed; private long attackPlaybackSpeed; private long hitRecoverySpeed; private long deathPlaybackSpeed; private long secondAttackSpeed; private long namePointer; private String name; private int minDungeonLevel; private int maxDungeonLevel; private int monsterItemLevel; private long minHitPoints; private long maxHitPoints; private int attackType1; private int attackType2; private int attackType3; private int attackType4; private int attackType5; private int monsterIntelligence; private int attackType7; private int attackType8; private int subType; private int monsterPriChanceToHit; private int priToHitFrame; private int priMinAttackDamage; private int priMaxAttackDamage; private int secToHitChance; private int secToHitFrame; private int secMinAttackDamage; private int secMaxAttackDamage; private int monsterAc; private int monsterType; private String resistancesNormAndNightmare; private String resistancesHell; private int itemDropSpecials; private int monsterSelectionOutline; private long experiencePoints; private int enabled; private boolean changed; private byte[] monsterBytesOrig; int slotNumber; public BaseMonster(int slotNumber, byte[] monsterBytes, byte activationByte, ReaderWriter rw) { this.slotNumber = slotNumber; animationSize = rw.convertFourBytesToNumber(monsterBytes[0], monsterBytes[1], monsterBytes[2], monsterBytes[3]); seedingSize = rw.convertFourBytesToNumber(monsterBytes[4], monsterBytes[5], monsterBytes[6], monsterBytes[7]); animationFilePointer = rw.convertFourBytesToOffset(monsterBytes[8], monsterBytes[9], monsterBytes[10], monsterBytes[11]); BinEditHelper nf = new BinEditHelper(); animationFileName = nf.getNameUsingPointer(animationFilePointer); secondAttack = rw.convertFourBytesToNumber(monsterBytes[12], monsterBytes[13], monsterBytes[14], monsterBytes[15]); soundPointer = rw.convertFourBytesToOffset(monsterBytes[16], monsterBytes[17], monsterBytes[18], monsterBytes[19]); hasSecondAttackSound = rw.convertFourBytesToNumber(monsterBytes[20], monsterBytes[21], monsterBytes[22], monsterBytes[23]); usesTrnToModColor = rw.convertFourBytesToNumber(monsterBytes[24], monsterBytes[25], monsterBytes[26], monsterBytes[27]); trnPointer = rw.convertFourBytesToOffset(monsterBytes[28], monsterBytes[29], monsterBytes[30], monsterBytes[31]); idleFrameset = rw.convertFourBytesToNumber(monsterBytes[32], monsterBytes[33], monsterBytes[34], monsterBytes[35]); walkFrameset = rw.convertFourBytesToNumber(monsterBytes[36], monsterBytes[37], monsterBytes[38], monsterBytes[39]); attackFrameset = rw.convertFourBytesToNumber(monsterBytes[40], monsterBytes[41], monsterBytes[42], monsterBytes[43]); hitRecoveryFrameset = rw.convertFourBytesToNumber(monsterBytes[44], monsterBytes[45], monsterBytes[46], monsterBytes[47]); deathFrameset = rw.convertFourBytesToNumber(monsterBytes[48], monsterBytes[49], monsterBytes[50], monsterBytes[51]); secondAttackFrameset = rw.convertFourBytesToNumber(monsterBytes[52], monsterBytes[53], monsterBytes[54], monsterBytes[55]); idlePlaybackSpeed = rw.convertFourBytesToNumber(monsterBytes[56], monsterBytes[57], monsterBytes[58], monsterBytes[59]); walkPlaybackSpeed = rw.convertFourBytesToNumber(monsterBytes[60], monsterBytes[61], monsterBytes[62], monsterBytes[63]); attackPlaybackSpeed = rw.convertFourBytesToNumber(monsterBytes[64], monsterBytes[65], monsterBytes[66], monsterBytes[67]); hitRecoverySpeed = rw.convertFourBytesToNumber(monsterBytes[68], monsterBytes[69], monsterBytes[70], monsterBytes[71]); deathPlaybackSpeed = rw.convertFourBytesToNumber(monsterBytes[72], monsterBytes[73], monsterBytes[74], monsterBytes[75]); secondAttackSpeed = rw.convertFourBytesToNumber(monsterBytes[76], monsterBytes[77], monsterBytes[78], monsterBytes[79]); namePointer = rw.convertFourBytesToOffset(monsterBytes[80], monsterBytes[81], monsterBytes[82], monsterBytes[83]); name = nf.getNameUsingPointer(namePointer); minDungeonLevel = rw.convertUnsignedByteToInt(monsterBytes[84]); maxDungeonLevel = rw.convertUnsignedByteToInt(monsterBytes[85]); // // monsterItemLevel occupies only byte monsterBytes[86]. The following // byte (monsterBytes[87]) is reserved. // TODO: Update the relevant code to reflect this. // monsterItemLevel = rw.convertTwoBytesToInt(monsterBytes[86], monsterBytes[87]); minHitPoints = rw.convertFourBytesToNumber(monsterBytes[88], monsterBytes[89], monsterBytes[90], monsterBytes[91]); maxHitPoints = rw.convertFourBytesToNumber(monsterBytes[92], monsterBytes[93], monsterBytes[94], monsterBytes[95]); attackType1 = rw.convertUnsignedByteToInt(monsterBytes[96]); attackType2 = rw.convertUnsignedByteToInt(monsterBytes[97]); attackType3 = rw.convertUnsignedByteToInt(monsterBytes[98]); attackType4 = rw.convertUnsignedByteToInt(monsterBytes[99]); attackType5 = rw.convertUnsignedByteToInt(monsterBytes[100]); monsterIntelligence = rw.convertUnsignedByteToInt(monsterBytes[101]); attackType7 = rw.convertUnsignedByteToInt(monsterBytes[102]); attackType8 = rw.convertUnsignedByteToInt(monsterBytes[103]); subType = rw.convertUnsignedByteToInt(monsterBytes[104]); monsterPriChanceToHit = rw.convertUnsignedByteToInt(monsterBytes[105]); priToHitFrame = rw.convertUnsignedByteToInt(monsterBytes[106]); priMinAttackDamage = rw.convertUnsignedByteToInt(monsterBytes[107]); priMaxAttackDamage = rw.convertUnsignedByteToInt(monsterBytes[108]); secToHitChance = rw.convertUnsignedByteToInt(monsterBytes[109]); secToHitFrame = rw.convertUnsignedByteToInt(monsterBytes[110]); secMinAttackDamage = rw.convertUnsignedByteToInt(monsterBytes[111]); secMaxAttackDamage = rw.convertUnsignedByteToInt(monsterBytes[112]); monsterAc = rw.convertUnsignedByteToInt(monsterBytes[113]); monsterType = rw.convertTwoBytesToInt(monsterBytes[114], monsterBytes[115]); resistancesNormAndNightmare = String.format("%16s", Integer.toBinaryString(rw.convertUnsignedByteToInt(monsterBytes[116]))).replace(' ', '0') + String.format("%16s", Integer.toBinaryString(rw.convertUnsignedByteToInt(monsterBytes[117]))).replace(' ', '0'); resistancesHell = String.format("%16s", Integer.toBinaryString(rw.convertUnsignedByteToInt(monsterBytes[118]))).replace(' ', '0') + String.format("%16s", Integer.toBinaryString(rw.convertUnsignedByteToInt(monsterBytes[119]))).replace(' ', '0'); itemDropSpecials = rw.convertTwoBytesToInt(monsterBytes[120], monsterBytes[121]); monsterSelectionOutline = rw.convertTwoBytesToInt(monsterBytes[122], monsterBytes[123]); experiencePoints = rw.convertFourBytesToNumber(monsterBytes[124], monsterBytes[125], monsterBytes[126], monsterBytes[127]); enabled = rw.convertUnsignedByteToInt(activationByte); changed = false; this.monsterBytesOrig = monsterBytes; } public MonsterAsBytes getMonsterAsBytes(){ byte[] monsterBytes = new byte[TomeOfKnowledge.BASE_MONSTER_LENGTH_IN_BYTES]; monsterBytes[0] = (byte)(animationSize >>> 0); monsterBytes[1] = (byte)(animationSize >>> 8); monsterBytes[2] = (byte)(animationSize >>> 16); monsterBytes[3] = (byte)(animationSize >>> 24); monsterBytes[4] = (byte)(seedingSize >>> 0); monsterBytes[5] = (byte)(seedingSize >>> 8); monsterBytes[6] = (byte)(seedingSize >>> 16); monsterBytes[7] = (byte)(seedingSize >>> 24); long animationFilePointerRev = animationFilePointer + TomeOfKnowledge.DIABLO_POINTERS_OFFSET; monsterBytes[8] = (byte)(animationFilePointerRev >>> 0); monsterBytes[9] = (byte)(animationFilePointerRev >>> 8); monsterBytes[10] = (byte)(animationFilePointerRev >>> 16); monsterBytes[11] = (byte)(animationFilePointerRev >>> 24); monsterBytes[12] = (byte)(secondAttack >>> 0); monsterBytes[13] = (byte)(secondAttack >>> 8); monsterBytes[14] = (byte)(secondAttack >>> 16); monsterBytes[15] = (byte)(secondAttack >>> 24); long soundPointerRev = soundPointer + TomeOfKnowledge.DIABLO_POINTERS_OFFSET; monsterBytes[16] = (byte)(soundPointerRev >>> 0); monsterBytes[17] = (byte)(soundPointerRev >>> 8); monsterBytes[18] = (byte)(soundPointerRev >>> 16); monsterBytes[19] = (byte)(soundPointerRev >>> 24); monsterBytes[20] = (byte)(hasSecondAttackSound >>> 0); monsterBytes[21] = (byte)(hasSecondAttackSound >>> 8); monsterBytes[22] = (byte)(hasSecondAttackSound >>> 16); monsterBytes[23] = (byte)(hasSecondAttackSound >>> 24); monsterBytes[24] = (byte)(usesTrnToModColor >>> 0); monsterBytes[25] = (byte)(usesTrnToModColor >>> 8); monsterBytes[26] = (byte)(usesTrnToModColor >>> 16); monsterBytes[27] = (byte)(usesTrnToModColor >>> 24); long trnPointerRev = trnPointer + TomeOfKnowledge.DIABLO_POINTERS_OFFSET; monsterBytes[28] = (byte)(trnPointerRev >>> 0); monsterBytes[29] = (byte)(trnPointerRev >>> 8); monsterBytes[30] = (byte)(trnPointerRev >>> 16); monsterBytes[31] = (byte)(trnPointerRev >>> 24); monsterBytes[32] = (byte)(idleFrameset >>> 0); monsterBytes[33] = (byte)(idleFrameset >>> 8); monsterBytes[34] = (byte)(idleFrameset >>> 16); monsterBytes[35] = (byte)(idleFrameset >>> 24); monsterBytes[36] = (byte)(walkFrameset >>> 0); monsterBytes[37] = (byte)(walkFrameset >>> 8); monsterBytes[38] = (byte)(walkFrameset >>> 16); monsterBytes[39] = (byte)(walkFrameset >>> 24); monsterBytes[40] = (byte)(attackFrameset >>> 0); monsterBytes[41] = (byte)(attackFrameset >>> 8); monsterBytes[42] = (byte)(attackFrameset >>> 16); monsterBytes[43] = (byte)(attackFrameset >>> 24); monsterBytes[44] = (byte)(hitRecoveryFrameset >>> 0); monsterBytes[45] = (byte)(hitRecoveryFrameset >>> 8); monsterBytes[46] = (byte)(hitRecoveryFrameset >>> 16); monsterBytes[47] = (byte)(hitRecoveryFrameset >>> 24); monsterBytes[48] = (byte)(deathFrameset >>> 0); monsterBytes[49] = (byte)(deathFrameset >>> 8); monsterBytes[50] = (byte)(deathFrameset >>> 16); monsterBytes[51] = (byte)(deathFrameset >>> 24); monsterBytes[52] = (byte)(secondAttackFrameset >>> 0); monsterBytes[53] = (byte)(secondAttackFrameset >>> 8); monsterBytes[54] = (byte)(secondAttackFrameset >>> 16); monsterBytes[55] = (byte)(secondAttackFrameset >>> 24); monsterBytes[56] = (byte)(idlePlaybackSpeed >>> 0); monsterBytes[57] = (byte)(idlePlaybackSpeed >>> 8); monsterBytes[58] = (byte)(idlePlaybackSpeed >>> 16); monsterBytes[59] = (byte)(idlePlaybackSpeed >>> 24); monsterBytes[60] = (byte)(walkPlaybackSpeed >>> 0); monsterBytes[61] = (byte)(walkPlaybackSpeed >>> 8); monsterBytes[62] = (byte)(walkPlaybackSpeed >>> 16); monsterBytes[63] = (byte)(walkPlaybackSpeed >>> 24); monsterBytes[64] = (byte)(attackPlaybackSpeed >>> 0); monsterBytes[65] = (byte)(attackPlaybackSpeed >>> 8); monsterBytes[66] = (byte)(attackPlaybackSpeed >>> 16); monsterBytes[67] = (byte)(attackPlaybackSpeed >>> 24); monsterBytes[68] = (byte)(hitRecoverySpeed >>> 0); monsterBytes[69] = (byte)(hitRecoverySpeed >>> 8); monsterBytes[70] = (byte)(hitRecoverySpeed >>> 16); monsterBytes[71] = (byte)(hitRecoverySpeed >>> 24); monsterBytes[72] = (byte)(deathPlaybackSpeed >>> 0); monsterBytes[73] = (byte)(deathPlaybackSpeed >>> 8); monsterBytes[74] = (byte)(deathPlaybackSpeed >>> 16); monsterBytes[75] = (byte)(deathPlaybackSpeed >>> 24); monsterBytes[76] = (byte)(secondAttackSpeed >>> 0); monsterBytes[77] = (byte)(secondAttackSpeed >>> 8); monsterBytes[78] = (byte)(secondAttackSpeed >>> 16); monsterBytes[79] = (byte)(secondAttackSpeed >>> 24); long namePointerRev = namePointer + TomeOfKnowledge.DIABLO_POINTERS_OFFSET; monsterBytes[80] = (byte)(namePointerRev >>> 0); monsterBytes[81] = (byte)(namePointerRev >>> 8); monsterBytes[82] = (byte)(namePointerRev >>> 16); monsterBytes[83] = (byte)(namePointerRev >>> 24); monsterBytes[84] = (byte) minDungeonLevel; monsterBytes[85] = (byte) maxDungeonLevel; monsterBytes[86] = (byte) monsterItemLevel; monsterBytes[87] = (byte)0; monsterBytes[88] = (byte)(minHitPoints >>> 0); monsterBytes[89] = (byte)(minHitPoints >>> 8); monsterBytes[90] = (byte)(minHitPoints >>> 16); monsterBytes[91] = (byte)(minHitPoints >>> 24); monsterBytes[92] = (byte)(maxHitPoints >>> 0); monsterBytes[93] = (byte)(maxHitPoints >>> 8); monsterBytes[94] = (byte)(maxHitPoints >>> 16); monsterBytes[95] = (byte)(maxHitPoints >>> 24); monsterBytes[96] = (byte) attackType1; //attackType1 monsterBytes[97] = (byte) attackType2; //attackType2 monsterBytes[98] = (byte) attackType3; //attackType3 monsterBytes[99] = (byte) attackType4; //attackType4 monsterBytes[100] = (byte) attackType5; //attackType5 monsterBytes[101] = (byte) monsterIntelligence; //monsterIntelligence monsterBytes[102] = (byte) attackType7; //attackType7 monsterBytes[103] = (byte) attackType8; //attackType8 monsterBytes[104] = (byte) subType; //subType monsterBytes[105] = (byte) monsterPriChanceToHit; //monsterPriChanceToHit monsterBytes[106] = (byte) priToHitFrame; //priToHitFrame monsterBytes[107] = (byte) priMinAttackDamage; //priMinAttackDamage monsterBytes[108] = (byte) priMaxAttackDamage; //priMaxAttackDamage monsterBytes[109] = (byte) secToHitChance; //secToHitChance monsterBytes[110] = (byte) secToHitFrame; //secToHitFrame monsterBytes[111] = (byte) secMinAttackDamage; //secMinAttackDamage monsterBytes[112] = (byte) secMaxAttackDamage; //secMaxAttackDamage monsterBytes[113] = (byte) monsterAc; //monsterAc monsterBytes[114] = (byte)(monsterType >>> 0); //monsterType monsterBytes[115] = (byte)(monsterType >>> 8); String res1 = resistancesNormAndNightmare.substring(0, 8); String res2 = resistancesNormAndNightmare.substring(8, 16); monsterBytes[116] = (byte) Integer.parseInt(res2, 2); monsterBytes[117] = (byte) Integer.parseInt(res1, 2); String res3 = resistancesHell.substring(0, 8); String res4 = resistancesHell.substring(8, 16); monsterBytes[118] = (byte) Integer.parseInt(res4, 2); //resistancesHell monsterBytes[119] = (byte) Integer.parseInt(res3, 2); monsterBytes[120] = (byte)(itemDropSpecials >>> 0); //itemDropSpecials monsterBytes[121] = (byte)(itemDropSpecials >>> 8); monsterBytes[122] = (byte)(monsterSelectionOutline >>> 0); //monsterSelectionOutline monsterBytes[123] = (byte)(monsterSelectionOutline >>> 8); monsterBytes[124] = (byte)(experiencePoints >>> 0); monsterBytes[125] = (byte)(experiencePoints >>> 8); monsterBytes[126] = (byte)(experiencePoints >>> 16); monsterBytes[127] = (byte)(experiencePoints >>> 24); MonsterAsBytes mab = new MonsterAsBytes(monsterBytes, (byte) enabled); //System.out.println("ORIG: " + Arrays.toString(monsterBytesOrig)); //System.out.println("BACK: " + Arrays.toString(monsterBytes) + "\n"); return mab; } public void printMonster() { System.out.println( "+ "| Slot number: " + slotNumber + " (hex: " + Integer.toHexString(slotNumber) + ")" + "\n" + "| Monster name: " + name + "\n" + "| Enabled: " + enabled + "\n" + "| Animation size: " + animationSize + "\n" + "| Seeding size: " + seedingSize + "\n" + "| Animation file pointer: " + animationFilePointer + "\n" + "| Animation file name: " + animationFileName + "\n" + "| Second attack: " + secondAttack + "\n" + "| Sound pointer: " + soundPointer + "\n" + "| Has second attack sound: " + hasSecondAttackSound + "\n" + "| Uses TRN to mod color: " + usesTrnToModColor + "\n" + "| TRN pointer: " + trnPointer + "\n" + "| Idle frameset: " + idleFrameset + "\n" + "| Walk frameset: " + walkFrameset + "\n" + "| Attack frameset: " + attackFrameset + "\n" + "| Hit recovery frameset: " + hitRecoveryFrameset + "\n" + "| Death frameset: " + deathFrameset + "\n" + "| Second attack frameset: " + secondAttackFrameset + "\n" + "| Idle playback speed: " + idlePlaybackSpeed + "\n" + "| Walk playback speed: " + walkPlaybackSpeed + "\n" + "| Attack playback speed: " + attackPlaybackSpeed + "\n" + "| Hit recovery speed: " + hitRecoverySpeed + "\n" + "| Death playback speed: " + deathPlaybackSpeed + "\n" + "| Second attack speed: " + secondAttackSpeed + "\n" + "| Name pointer: " + namePointer + "\n" + "| Min dungeon level: " + minDungeonLevel + "\n" + "| Max dungeon level: " + maxDungeonLevel + "\n" + "| Monster item level: " + monsterItemLevel + "\n" + "| HPs: " + minHitPoints + "--" + maxHitPoints + "\n" + "| Attack type (byte 1): " + attackType1 + "\n" + "| Attack type (byte 2): " + attackType2 + "\n" + "| Attack type (byte 3): " + attackType3 + "\n" + "| Attack type (byte 4): " + attackType4 + "\n" + "| Attack type (byte 5): " + attackType5 + "\n" + "| Monster intelligence: " + monsterIntelligence + "\n" + "| Attack type (byte 7): " + attackType7 + "\n" + "| Attack type (byte 8): " + attackType8 + "\n" + "| Monster sub-type: " + subType + "\n" + "| Primary attack % hit: " + monsterPriChanceToHit + "\n" + "| Primary to-hit frame: " + priToHitFrame + "\n" + "| Primary damage: " + priMinAttackDamage + "--" + priMaxAttackDamage + "\n" + "| Sec. attack % hit: " + secToHitChance + "\n" + "| Sec. to-hit frame: " + secToHitFrame + "\n" + "| Secondary damage: " + secMinAttackDamage + "--" + secMaxAttackDamage + "\n" + "| Monster AC: " + monsterAc + "\n" + "| Monster type: " + monsterType + "\n" + "| Resistances (norm. and nightmare): " + resistancesNormAndNightmare + "\n" + "| Resistances (hell mode): " + resistancesHell + "\n" + "| Item drop specials: " + itemDropSpecials + "\n" + "| Monster selection outline: " + monsterSelectionOutline + "\n" + "| XP: " + experiencePoints + "\n" + "+ } public long getAnimationSize() { return animationSize; } //128, 160, 96 public void setAnimationSize(long animationSize) { Integer[] animationSizes = {96, 128, 160}; List<Integer> animationSizeList = Arrays.asList(animationSizes); if(animationSizeList.contains((int) animationSize)){ this.animationSize = animationSize; this.setChanged(); } else { System.err.println("Error: BaseMonster's setAnimationSize() was" + "supplied with an argument outside the supported range of options (96, 128, 160)"); } } public long getSeedingSize() { return seedingSize; } public void setSeedingSize(long seedingSize) { if(seedingSize >= 0 && seedingSize <= 2500){ this.seedingSize = seedingSize; this.setChanged(); } else { System.err.println("Error: BaseMonster's setSetSeedingSize() was" + "supplied with an argument outside the supported range (0 to 2500)"); } } public long getAnimationFilePointer() { return animationFilePointer; } public void setAnimationFilePointer(long animationFilePointer) { if(animationFilePointer >= 1024 && animationFilePointer <= 7018496){ this.animationFilePointer = animationFilePointer; this.setChanged(); } else { System.err.println("Error: BaseMonster's setAnimationFilePointer() was" + "supplied with an argument outside the supported range (1024 to 7018496)"); } } //TODO private String getAnimationFileName() { return animationFileName; } //TODO private void setAnimationFileName(String animationFileName) { this.animationFileName = animationFileName; } public long getSecondAttackOnOrOff() { return secondAttack; } public void setSecondAttackOnOrOff(long secondAttack) { if(secondAttack == 1 || secondAttack == 0){ this.secondAttack = secondAttack; this.setChanged(); } else { System.err.println("Error: BaseMonster's setSecondAttackOnOrOff() requires" + "that the second attack either be enabled (1) or disabled (0)"); } } public long getSoundPointer() { return soundPointer; } public void setSoundPointer(long soundPointer) { if(soundPointer >= 1024 && soundPointer <= 7018496){ this.soundPointer = soundPointer; this.setChanged(); } else { System.err.println("Error: BaseMonster's setSoundPointer() was" + "supplied with an argument outside the supported range (1024 to 7018496)"); } } public long getHasSecondAttackSound() { return hasSecondAttackSound; } public void setHasSecondAttackSound(long hasSecondAttackSound) { if(hasSecondAttackSound >= 0 && hasSecondAttackSound <= 1){ this.hasSecondAttackSound = hasSecondAttackSound; this.setChanged(); } else { System.err.println("Error: BaseMonster's setHasSecondAttackSound() was" + "supplied with an argument outside the supported range (0 to 1)"); } } public long getUsesTrnToModColor() { return usesTrnToModColor; } public void setUsesTrnToModColor(long usesTrnToModColor) { if(usesTrnToModColor >= 0 && usesTrnToModColor <= 1){ this.usesTrnToModColor = usesTrnToModColor; this.setChanged(); } else { System.err.println("Error: BaseMonster's setUsesTrnToModColor() was" + "supplied with an argument outside the supported range (0 to 1)"); } } public long getTrnPointer() { return trnPointer; } public void setTrnPointer(long trnPointer) { if(trnPointer <= 1024 && trnPointer >= 7018496){ this.trnPointer = trnPointer; this.setChanged(); } else { System.err.println("Error: BaseMonster's setUsesTrnPointer() was" + "supplied with an argument outside the supported range (1024 to 7018496)"); } } public long getIdleFrameset() { return idleFrameset; } public void setIdleFrameset(long idleFrameset) { if(idleFrameset > 0 && idleFrameset <= 24){ this.idleFrameset = idleFrameset; this.setChanged(); } else { System.err.println("Error: BaseMonster's setIdleFrameset() was" + "supplied with an argument outside the supported range (1 to 24)"); } } public long getWalkFrameset() { return walkFrameset; } public void setWalkFrameset(long walkFrameset) { if(walkFrameset > 0 && walkFrameset <= 24){ this.walkFrameset = walkFrameset; this.setChanged(); } else { System.err.println("Error: BaseMonster's setWalkFrameset() was" + "supplied with an argument outside the supported range (1 to 24)"); } } public long getAttackFrameset() { return attackFrameset; } public void setAttackFrameset(long attackFrameset) { if(attackFrameset > 0 && attackFrameset <= 24){ this.attackFrameset = attackFrameset; this.setChanged(); } else { System.err.println("Error: BaseMonster's setAttackFrameset() was" + "supplied with an argument outside the supported range (1 to 24)"); } } public long getHitRecoveryFrameset() { return hitRecoveryFrameset; } public void setHitRecoveryFrameset(long hitRecoveryFrameset) { if(hitRecoveryFrameset > 0 && hitRecoveryFrameset <= 24){ this.hitRecoveryFrameset = hitRecoveryFrameset; this.setChanged(); } else { System.err.println("Error: BaseMonster's setHitRecoveryFrameset() was" + "supplied with an argument outside the supported range (1 to 24)"); } } public long getDeathFrameset() { return deathFrameset; } public void setDeathFrameset(long deathFrameset) { if(deathFrameset > 0 && deathFrameset <= 24){ this.deathFrameset = deathFrameset; this.setChanged(); } } public long getSecondAttackFrameset() { return secondAttackFrameset; } public void setSecondAttackFrameset(long secondAttackFrameset) { if(secondAttackFrameset > 0 && secondAttackFrameset <= 24){ this.secondAttackFrameset = secondAttackFrameset; this.setChanged(); } else { System.err.println("Error: BaseMonster's setSecondAttackFrameset() was" + "supplied with an argument outside the supported range (1 to 24)"); } } public long getIdlePlaybackSpeed() { return idlePlaybackSpeed; } public void setIdlePlaybackSpeed(long idlePlaybackSpeed) { if(idlePlaybackSpeed >= 0 && idlePlaybackSpeed <= 10){ this.idlePlaybackSpeed = idlePlaybackSpeed; this.setChanged(); } else { System.err.println("Error: BaseMonster's setIdlePlaybackSpeed() was" + "supplied with an argument outside the supported range (0 to 10)"); } } public long getWalkPlaybackSpeed() { return walkPlaybackSpeed; } public void setWalkPlaybackSpeed(long walkPlaybackSpeed) { if(walkPlaybackSpeed >= 0 && walkPlaybackSpeed <= 10){ this.walkPlaybackSpeed = walkPlaybackSpeed; this.setChanged(); } else { System.err.println("Error: BaseMonster's setWalkPlaybackSpeed() was" + "supplied with an argument outside the supported range (0 to 10)"); } } public long getAttackPlaybackSpeed() { return attackPlaybackSpeed; } public void setAttackPlaybackSpeed(long attackPlaybackSpeed) { if(attackPlaybackSpeed >= 0 && attackPlaybackSpeed <= 10){ this.attackPlaybackSpeed = attackPlaybackSpeed; this.setChanged(); } else { System.err.println("Error: BaseMonster's setAttackPlaybackSpeed() was" + "supplied with an argument outside the supported range (0 to 10)"); } } public long getHitRecoverySpeed() { return hitRecoverySpeed; } public void setHitRecoverySpeed(long hitRecoverySpeed) { if(hitRecoverySpeed >= 0 && hitRecoverySpeed <= 10){ this.hitRecoverySpeed = hitRecoverySpeed; this.setChanged(); } else { System.err.println("Error: BaseMonster's setHitRecoverySpeed() was" + "supplied with an argument outside the supported range (0 to 10)"); } } public long getDeathPlaybackSpeed() { return deathPlaybackSpeed; } public void setDeathPlaybackSpeed(long deathPlaybackSpeed) { if(deathPlaybackSpeed >= 0 && deathPlaybackSpeed <= 10){ this.deathPlaybackSpeed = deathPlaybackSpeed; this.setChanged(); } else { System.err.println("Error: BaseMonster's setDeathPlaybackSpeed() was" + "supplied with an argument outside the supported range (0 to 10)"); } } public long getSecondAttackSpeed() { return secondAttackSpeed; } public void setSecondAttackSpeed(long secondAttackSpeed) { if(secondAttackSpeed >= 0 && secondAttackSpeed <= 10){ this.secondAttackSpeed = secondAttackSpeed; this.setChanged(); } else { System.err.println("Error: BaseMonster's setSecondAttackSpeed() was" + "supplied with an argument outside the supported range (0 to 10)"); } } public long getNamePointer() { return namePointer; } public void setNamePointer(long namePointer) { if(namePointer <= 1024 && namePointer >= 7018496){ this.namePointer = namePointer; this.setChanged(); } else { System.err.println("Error: BaseMonster's setNamePointer() was" + "supplied with an argument outside the supported range (1024 to 7018496)"); } } //TODO private String getName() { return name; } //TODO private void setName(String name) { this.name = name; } public int getMinDungeonLevel() { return minDungeonLevel; } public void setMinDungeonLevel(int minDungeonLevel) { if(minDungeonLevel >= 0 && minDungeonLevel <= 50){ this.minDungeonLevel = minDungeonLevel; this.setChanged(); } else { System.err.println("Error: BaseMonster's setMinDungeonLevel() was" + "supplied with an argument outside the supported range (0 to 50)"); } } public int getMaxDungeonLevel() { return maxDungeonLevel; } public void setMaxDungeonLevel(int maxDungeonLevel) { if(maxDungeonLevel <= 0 && maxDungeonLevel <= 50){ this.maxDungeonLevel = maxDungeonLevel; this.setChanged(); } else { System.err.println("Error: BaseMonster's setMaxDungeonLevel() was" + "supplied with an argument outside the supported range (0 to 50)"); } } public int getMonsterItemLevel() { return monsterItemLevel; } public void setMonsterItemLevel(int monsterItemLevel) { if(monsterItemLevel <= 1 && monsterItemLevel >= 30){ this.monsterItemLevel = monsterItemLevel; this.setChanged(); } else { System.err.println("Error: BaseMonster's setMonsterItemLevel() was" + "supplied with an argument outside the supported range (1 to 30)"); } } public long getMinHitPoints() { return minHitPoints; } public void setMinHitPoints(long minHitPoints) { if(minHitPoints >= 1 && minHitPoints <= 9999){ this.minHitPoints = minHitPoints; this.setChanged(); } else { System.err.println("Error: BaseMonster's setMinHitPoints() was" + "supplied with an argument outside the supported range (1 to 9999)"); } } public long getMaxHitPoints() { return maxHitPoints; } public void setMaxHitPoints(long maxHitPoints) { if(maxHitPoints >= 1 && maxHitPoints <= 9999){ this.maxHitPoints = maxHitPoints; this.setChanged(); } else { System.err.println("Error: BaseMonster's setMaxHitPoints() was" + "supplied with an argument outside the supported range (1 to 9999)"); } } public int getAttackType1() { return attackType1; } //0 to 25 public void setAttackType1(int attackType1) { if(attackType1 >= 0 && attackType1 <= 31){ this.attackType1 = attackType1; this.setChanged(); } else { System.err.println("Error: BaseMonster's setAttackType1() was" + "supplied with an argument outside the supported range (0 to 25)"); } } public int getAttackType2() { return attackType2; } public void setAttackType2(int attackType2) { if(attackType2 >= 0 && attackType2 <= 0){ this.attackType2 = attackType2; this.setChanged(); } else { System.err.println("Error: BaseMonster's setAttackType2() was" + "supplied with an argument outside the supported range (0 to 0)"); } } public int getAttackType3() { return attackType3; } public void setAttackType3(int attackType3) { if(attackType3 >= 0 && attackType3 <= 0){ this.attackType3 = attackType3; this.setChanged(); } else { System.err.println("Error: BaseMonster's setAttackType3() was" + "supplied with an argument outside the supported range (0 to 0)"); } } public int getAttackType4() { return attackType4; } public void setAttackType4(int attackType4) { if(attackType4 >= 0 && attackType4 <= 0){ this.attackType4 = attackType4; this.setChanged(); } else { System.err.println("Error: BaseMonster's setAttackType4() was" + "supplied with an argument outside the supported range (0 to 0)"); } } public int getAttackType5() { return attackType5; } public void setAttackType5(int attackType5) { if(attackType5 >= 0 && attackType5 <= 128){ this.attackType5 = attackType5; this.setChanged(); } else { System.err.println("Error: BaseMonster's setAttackType5() was" + "supplied with an argument outside the supported range (0 to 128)"); } } public int getMonsterIntelligence() { return monsterIntelligence; } public void setMonsterIntelligence(int monsterIntelligence) { if(monsterIntelligence >=0 && monsterIntelligence <= 3){ this.monsterIntelligence = monsterIntelligence; this.setChanged(); } else { System.err.println("Error: BaseMonster's setMonsterIntelligence() was" + "supplied with an argument outside the supported range (0 to 3)"); } } public int getAttackType7() { return attackType7; } public void setAttackType7(int attackType7) { if(attackType7 == 0){ this.attackType7 = attackType7; this.setChanged(); } else { System.err.println("Error: BaseMonster's setAttackType7() was" + "supplied with an argument outside the supported range (0 to 0)"); } } public int getAttackType8() { return attackType8; } public void setAttackType8(int attackType8) { if(attackType8 == 0){ this.attackType8 = attackType8; this.setChanged(); } else { System.err.println("Error: BaseMonster's setAttackType8() was" + "supplied with an argument outside the supported range (0 to 0)"); } } public int getSubType() { return subType; } public void setSubType(int subType) { if(subType >= 0 && subType <= 3){ this.subType = subType; this.setChanged(); } else { System.err.println("Error: BaseMonster's setSubType() was" + "supplied with an argument outside the supported range (0 to 3)"); } } public int getMonsterPriChanceToHit() { return monsterPriChanceToHit; } public void setMonsterPriChanceToHit(int monsterPriChanceToHit) { if(monsterPriChanceToHit >= 0 && monsterPriChanceToHit <= 100){ this.monsterPriChanceToHit = monsterPriChanceToHit; this.setChanged(); } else { System.err.println("Error: BaseMonster's setMonsterPriChanceToHit() was" + "supplied with an argument outside the supported range (0 to 100)"); } } public int getPriToHitFrame() { return priToHitFrame; } public void setPriToHitFrame(int priToHitFrame) { if(priToHitFrame >= 0 && priToHitFrame <= 25){ this.priToHitFrame = priToHitFrame; this.setChanged(); } else { System.err.println("Error: BaseMonster's setPriToHitFrame() was" + "supplied with an argument outside the supported range (0 to 25)"); } } public int getPriMinAttackDamage() { return priMinAttackDamage; } public void setPriMinAttackDamage(int priMinAttackDamage) { if(priMinAttackDamage >= 0 && priMinAttackDamage <= 255){ this.priMinAttackDamage = priMinAttackDamage; this.setChanged(); } else { System.err.println("Error: BaseMonster's setPriMinAttackDamage() was" + "supplied with an argument outside the supported range (0 to 255)"); } } public int getPriMaxAttackDamage() { return priMaxAttackDamage; } public void setPriMaxAttackDamage(int priMaxAttackDamage) { if(priMaxAttackDamage >= 0 && priMaxAttackDamage <= 255){ this.priMaxAttackDamage = priMaxAttackDamage; this.setChanged(); } else { System.err.println("Error: BaseMonster's setPriMaxAttackDamage() was" + "supplied with an argument outside the supported range (0 to 255)"); } } public int getSecToHitChance() { return secToHitChance; } public void setSecToHitChance(int secToHitChance) { if(secToHitChance >= 0 && secToHitChance <= 100){ this.secToHitChance = secToHitChance; this.setChanged(); } else { System.err.println("Error: BaseMonster's setSecToHitChance() was" + "supplied with an argument outside the supported range (0 to 100)"); } } public int getSecToHitFrame() { return secToHitFrame; } public void setSecToHitFrame(int secToHitFrame) { if(secToHitFrame >= 0 && secToHitFrame <= 25){ this.secToHitFrame = secToHitFrame; this.setChanged(); } else { System.err.println("Error: BaseMonster's setSecToHitChance() was" + "supplied with an argument outside the supported range (0 to 25)"); } } public int getSecMinAttackDamage() { return secMinAttackDamage; } public void setSecMinAttackDamage(int secMinAttackDamage) { if(secMinAttackDamage >= 0 && secMinAttackDamage <= 255){ this.secMinAttackDamage = secMinAttackDamage; this.setChanged(); } else { System.err.println("Error: BaseMonster's setSecMinAttackDamage() was" + "supplied with an argument outside the supported range (0 to 255)"); } } public int getSecMaxAttackDamage() { return secMaxAttackDamage; } public void setSecMaxAttackDamage(int secMaxAttackDamage) { if(secMaxAttackDamage >= 0 && secMaxAttackDamage <= 255){ this.secMaxAttackDamage = secMaxAttackDamage; this.setChanged(); } else { System.err.println("Error: BaseMonster's setSecMaxAttackDamage() was" + "supplied with an argument outside the supported range (0 to 255)"); } } public int getMonsterAc() { return monsterAc; } public void setMonsterAc(int monsterAc) { if(monsterAc >= 0 & monsterAc <= 255){ this.monsterAc = monsterAc; this.setChanged(); } else { System.err.println("Error: BaseMonster's setMonsterAc() was" + "supplied with an argument outside the supported range (0 to 255)"); } } public int getMonsterType() { return monsterType; } public void setMonsterType(int monsterType) { if(monsterType >= 0 && monsterType <= 3){ this.monsterType = monsterType; this.setChanged(); } else { System.err.println("Error: BaseMonster's setMonsterType() was" + "supplied with an argument outside the supported range (0 to 3)"); } } public String getResistancesNormAndNightmare() { return resistancesNormAndNightmare; } public void setResistancesNormAndNightmare( String resistancesNormAndNightmare) { if(resistancesNormAndNightmare.matches("(0|1){16}")){ //if resistancesNormAndNightmare matches 16 x (0 or 1) [2 bytes displayed in binary] this.resistancesNormAndNightmare = resistancesNormAndNightmare; this.setChanged(); } else { System.err.println("Error: BaseMonster's setResistancesNormAndNightmare() was" + "supplied with an incorrect argument"); } } public String getResistancesHell() { return resistancesHell; } public void setResistancesHell(String resistancesHell) { if(resistancesHell.matches("(0|1){16}")){ this.resistancesHell = resistancesHell; this.setChanged(); } else { System.err.println("Error: BaseMonster's setResistancesNormAndNightmare() was" + "supplied with an incorrect argument"); } } public int getItemDropSpecials() { return itemDropSpecials; } public void setItemDropSpecials(int itemDropSpecials) { if(itemDropSpecials >=0 && itemDropSpecials <= 65536){ this.itemDropSpecials = itemDropSpecials; this.setChanged(); } else { System.err.println("Error: BaseMonster's setItemDropSpecials() was" + "supplied with an argument outside the supported range (0 to 65536)"); } } public int getMonsterSelectionOutline() { return monsterSelectionOutline; } public void setMonsterSelectionOutline(int monsterSelectionOutline) { if(monsterSelectionOutline >= 0 && monsterSelectionOutline <= 24){ this.monsterSelectionOutline = monsterSelectionOutline; this.setChanged(); } else { System.err.println("Error: BaseMonster's setMonsterSelectionOutline() was" + "supplied with an argument outside the supported range (0 to 24)"); } } public long getExperiencePoints() { return experiencePoints; } public void setExperiencePoints(long experiencePoints) { if(experiencePoints >= 0 && experiencePoints <= 99999){ this.experiencePoints = experiencePoints; this.setChanged(); } else { System.err.println("Error: BaseMonster's setExperiencePoints() was" + "supplied with an argument outside the supported range (0 to 99999)"); } } public int getEnabled() { return enabled; } public void setEnabled(int enabled) { if(enabled <= 0 && enabled >= 1){ this.enabled = enabled; this.setChanged(); } else { System.err.println("Error: BaseMonster's setEnabled() was" + "supplied with an argument outside the supported range (0 to 1)"); } } public boolean isChanged() { return changed; } public void setChanged() { this.changed = true; } public byte[] getMonsterBytesOrig() { return monsterBytesOrig; } public void setMonsterBytesOrig(byte[] monsterBytesOrig) { this.monsterBytesOrig = monsterBytesOrig; } }
package org.commcare.util.cli; import org.commcare.cases.util.CaseDBUtils; import org.commcare.cases.util.CasePurgeFilter; import org.commcare.core.interfaces.UserSandbox; import org.commcare.core.parse.CommCareTransactionParserFactory; import org.commcare.core.parse.ParseUtils; import org.commcare.core.sandbox.SandboxUtils; import org.commcare.data.xml.DataModelPullParser; import org.commcare.session.SessionFrame; import org.commcare.suite.model.FormIdDatum; import org.commcare.suite.model.SessionDatum; import org.commcare.suite.model.StackFrameStep; import org.commcare.util.CommCarePlatform; import org.commcare.util.engine.CommCareConfigEngine; import org.commcare.util.mocks.CLISessionWrapper; import org.commcare.util.mocks.MockUserDataSandbox; import org.commcare.util.screen.CommCareSessionException; import org.commcare.util.screen.EntityScreen; import org.commcare.util.screen.MenuScreen; import org.commcare.util.screen.Screen; import org.javarosa.core.model.User; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.services.PropertyManager; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.locale.Localizer; import org.javarosa.core.services.storage.IStorageIterator; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.services.storage.StorageManager; import org.javarosa.core.util.externalizable.PrototypeFactory; import org.javarosa.engine.XFormPlayer; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathParseTool; import org.javarosa.xpath.expr.FunctionUtils; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.parser.XPathSyntaxException; import org.xmlpull.v1.XmlPullParserException; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.URL; /** * CLI host for running a commcare application which has been configured and instatiated * for the provided user. * * @author ctsims */ public class ApplicationHost { private final CommCareConfigEngine mEngine; private final CommCarePlatform mPlatform; private UserSandbox mSandbox; private CLISessionWrapper mSession; private boolean mUpdatePending = false; private String mUpdateTarget = null; private boolean mSessionHasNextFrameReady = false; private final PrototypeFactory mPrototypeFactory; private final BufferedReader reader; private String[] mLocalUserCredentials; private String mRestoreFile; private boolean mRestoreStrategySet = false; public ApplicationHost(CommCareConfigEngine engine, PrototypeFactory prototypeFactory) { this.mEngine = engine; this.mPlatform = engine.getPlatform(); reader = new BufferedReader(new InputStreamReader(System.in)); this.mPrototypeFactory = prototypeFactory; } public void setRestoreToRemoteUser(String username, String password) { this.mLocalUserCredentials = new String[]{username, password}; mRestoreStrategySet = true; } public void setRestoreToLocalFile(String filename) { this.mRestoreFile = filename; mRestoreStrategySet = true; } public void setRestoreToDemoUser() { mRestoreStrategySet = true; } public void run() { if (!mRestoreStrategySet) { throw new RuntimeException("You must set up an application host by calling " + "one of hte setRestore*() methods before running the app"); } setupSandbox(); mSession = new CLISessionWrapper(mPlatform, mSandbox); try { loop(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } private void loop() throws IOException { boolean keepExecuting = true; while (keepExecuting) { if (!mSessionHasNextFrameReady) { mSession.clearAllState(); } mSessionHasNextFrameReady = false; keepExecuting = loopSession(); if (this.mUpdatePending) { processAppUpdate(); } } } private void processAppUpdate() { mSession.clearAllState(); this.mUpdatePending = false; String updateTarget = mUpdateTarget; this.mUpdateTarget = null; mEngine.attemptAppUpdate(updateTarget); } private boolean loopSession() throws IOException { Screen s = getNextScreen(); boolean screenIsRedrawing = false; boolean sessionIsLive = true; while (sessionIsLive) { while (s != null) { try { if (!screenIsRedrawing) { s.init(mSession); if (s.shouldBeSkipped()) { s = getNextScreen(); continue; } } System.out.println("\n\n\n\n\n\n"); System.out.println(s.getWrappedDisplaytitle(mSandbox, mPlatform)); System.out.println("===================="); s.prompt(System.out); System.out.print("> "); screenIsRedrawing = false; String input = reader.readLine(); //TODO: Command language if (input.startsWith(":")) { if (input.equals(":exit") || input.equals(":quit")) { return false; } if (input.startsWith(":update")) { mUpdatePending = true; if (input.contains(("--latest")) || input.contains("-f")) { mUpdateTarget = "build"; System.out.println("Updating to most recent build"); } else if (input.contains(("--preview")) || input.contains("-p")) { mUpdateTarget = "save"; System.out.println("Updating to latest app preview"); } else { mUpdateTarget = "release"; System.out.println("Updating to newest Release"); } return true; } if (input.equals(":home")) { return true; } if (input.equals(":back")) { mSession.stepBack(mSession.getEvaluationContext()); s = getNextScreen(); continue; } if (input.equals(":stack")) { printStack(mSession); continue; } if (input.startsWith(":lang")) { String[] langArgs = input.split(" "); if (langArgs.length != 2) { System.out.println("Command format\n:lang [langcode]"); continue; } String newLocale = langArgs[1]; setLocale(newLocale); continue; } if (input.startsWith(":sync")) { syncAndReport(); continue; } } screenIsRedrawing = s.handleInputAndUpdateSession(mSession, input); if (!screenIsRedrawing) { s = getNextScreen(); } } catch (CommCareSessionException ccse) { printErrorAndContinue("Error during session execution:", ccse); //Restart return true; } catch (XPathException xpe) { printErrorAndContinue("XPath Evaluation exception during session execution:", xpe); //Restart return true; } } //We have a session and are ready to fill out a form! System.out.println("Starting form entry with the following stack frame"); printStack(mSession); //Get our form object String formXmlns = mSession.getForm(); if (formXmlns == null) { finishSession(); return true; } else { XFormPlayer player = new XFormPlayer(System.in, System.out, null); player.setPreferredLocale(Localization.getGlobalLocalizerAdvanced().getLocale()); player.setSessionIIF(mSession.getIIF()); player.start(mEngine.loadFormByXmlns(formXmlns)); //If the form saved properly, process the output if (player.getExecutionResult() == XFormPlayer.FormResult.Completed) { if (!processResultInstance(player.getResultStream())) { return true; } finishSession(); return true; } else if (player.getExecutionResult() == XFormPlayer.FormResult.Cancelled) { mSession.stepBack(mSession.getEvaluationContext()); s = getNextScreen(); } else { //Handle this later return true; } } } //After we finish, continue executing return true; } private void printStack(CLISessionWrapper mSession) { SessionFrame frame = mSession.getFrame(); System.out.println("Live Frame"); System.out.println(" for (StackFrameStep step : frame.getSteps()) { if (step.getType().equals(SessionFrame.STATE_COMMAND_ID)) { System.out.println("COMMAND: " + step.getId()); } else { System.out.println("DATUM : " + step.getId() + " - " + step.getValue()); } } } private void finishSession() { mSession.clearVolitiles(); if (mSession.finishExecuteAndPop(mSession.getEvaluationContext())) { mSessionHasNextFrameReady = true; } } private boolean processResultInstance(InputStream resultStream) { try { DataModelPullParser parser = new DataModelPullParser( resultStream, new CommCareTransactionParserFactory(mSandbox), true, true); parser.parse(); } catch (Exception e) { printErrorAndContinue("Error processing the form result!", e); return false; } finally { try { resultStream.close(); } catch (IOException e) { e.printStackTrace(); } } return true; } private void printErrorAndContinue(String error, Exception e) { System.out.println(error); e.printStackTrace(); System.out.println("Press return to restart the session"); try { reader.readLine(); } catch (IOException ex) { throw new RuntimeException(ex); } } private Screen getNextScreen() { String next = mSession.getNeededData(mSession.getEvaluationContext()); if (next == null) { //XFORM TIME! return null; } else if (next.equals(SessionFrame.STATE_COMMAND_ID)) { return new MenuScreen(); } else if (next.equals(SessionFrame.STATE_DATUM_VAL)) { return new EntityScreen(); } else if (next.equalsIgnoreCase(SessionFrame.STATE_DATUM_COMPUTED)) { computeDatum(); return getNextScreen(); } throw new RuntimeException("Unexpected Frame Request: " + next); } private void computeDatum() { //compute SessionDatum datum = mSession.getNeededDatum(); XPathExpression form; try { form = XPathParseTool.parseXPath(datum.getValue()); } catch (XPathSyntaxException e) { //TODO: What. e.printStackTrace(); throw new RuntimeException(e.getMessage()); } EvaluationContext ec = mSession.getEvaluationContext(); if (datum instanceof FormIdDatum) { mSession.setXmlns(FunctionUtils.toString(form.eval(ec))); mSession.setDatum("", "awful"); } else { try { mSession.setDatum(datum.getDataId(), FunctionUtils.toString(form.eval(ec))); } catch (XPathException e) { error(e); } } } private void error(Exception e) { e.printStackTrace(); System.exit(-1); } private void setupSandbox() { //Set up our storage MockUserDataSandbox sandbox = new MockUserDataSandbox(mPrototypeFactory); //this gets configured earlier when we installed the app, should point it in the //right direction! sandbox.setAppFixtureStorageLocation((IStorageUtilityIndexed<FormInstance>) StorageManager.getStorage(FormInstance.STORAGE_KEY)); mSandbox = sandbox; if (mLocalUserCredentials != null) { restoreUserToSandbox(mSandbox, mLocalUserCredentials[0], mLocalUserCredentials[1]); } else if (mRestoreFile != null) { restoreFileToSandbox(mSandbox, mRestoreFile); } else { restoreDemoUserToSandbox(mSandbox); } } private void restoreFileToSandbox(UserSandbox sandbox, String restoreFile) { FileInputStream fios = null; try { System.out.println("Restoring user data from local file " + restoreFile); fios = new FileInputStream(restoreFile); } catch (FileNotFoundException e) { System.out.println("No restore file found at" + restoreFile); System.exit(-1); } try { ParseUtils.parseIntoSandbox(new BufferedInputStream(fios), sandbox, false); } catch (Exception e) { System.out.println("Error parsing local restore data from " + restoreFile); e.printStackTrace(); System.exit(-1); } initUser(); } private void initUser() { User u = mSandbox.getUserStorage().read(0); mSandbox.setLoggedInUser(u); System.out.println("Setting logged in user to: " + u.getUsername()); } public static void restoreUserToSandbox(UserSandbox sandbox, String username, final String password) { String urlStateParams = ""; boolean failed = true; boolean incremental = false; if (sandbox.getLoggedInUser() != null) { String syncToken = sandbox.getSyncToken(); String caseStateHash = CaseDBUtils.computeCaseDbHash(sandbox.getCaseStorage()); urlStateParams = String.format("&since=%s&state=ccsh:%s", syncToken, caseStateHash); incremental = true; if (incremental) { System.out.println(String.format( "\nIncremental sync requested. \nSync Token: %s\nState Hash: %s", syncToken, caseStateHash)); } } //fetch the restore data and set credentials String otaFreshRestoreUrl = PropertyManager.instance().getSingularProperty("ota-restore-url") + "?version=2.0"; String otaSyncUrl = otaFreshRestoreUrl + urlStateParams; String domain = PropertyManager.instance().getSingularProperty("cc_user_domain"); final String qualifiedUsername = username + "@" + domain; Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(qualifiedUsername, password.toCharArray()); } }); //Go get our sandbox! try { System.out.println("GET: " + otaSyncUrl); URL url = new URL(otaSyncUrl); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); if (conn.getResponseCode() == 412) { System.out.println("Server Response 412 - The user sandbox is not consistent with " + "the server's data. \n\nThis is expected if you have changed cases locally, " + "since data is not sent to the server for updates"); } else if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { System.out.println("\nInvalid username or password!"); } else if (conn.getResponseCode() >= 200 && conn.getResponseCode() < 300) { System.out.println("Restoring user " + username + " to domain " + domain); ParseUtils.parseIntoSandbox(new BufferedInputStream(conn.getInputStream()), sandbox); System.out.println("User data processed, new state token: " + sandbox.getSyncToken()); failed = false; } else { System.out.println("Unclear/Unexpected server response code: " + conn.getResponseCode()); } } catch (InvalidStructureException | IOException e) { e.printStackTrace(); } catch (XmlPullParserException | UnfullfilledRequirementsException e) { e.printStackTrace(); } if (failed) { if (!incremental) { System.exit(-1); } } else { //Initialize our User for (IStorageIterator<User> iterator = sandbox.getUserStorage().iterate(); iterator.hasMore(); ) { User u = iterator.nextRecord(); if (username.equalsIgnoreCase(u.getUsername())) { sandbox.setLoggedInUser(u); } } } } private void restoreDemoUserToSandbox(UserSandbox sandbox) { try { ParseUtils.parseIntoSandbox(mPlatform.getDemoUserRestore().getRestoreStream(), sandbox, false); } catch (Exception e) { System.out.println("Error parsing demo user restore from app"); e.printStackTrace(); System.exit(-1); } initUser(); } private void setLocale(String locale) { Localizer localizer = Localization.getGlobalLocalizerAdvanced(); String availableLocales = ""; for (String availabile : localizer.getAvailableLocales()) { availableLocales += availabile + "\n"; if (locale.equals(availabile)) { localizer.setLocale(locale); return; } } System.out.println("Locale '" + locale + "' is undefined in this app! Available Locales:"); System.out.println(" System.out.println(availableLocales); } private void syncAndReport() { performCasePurge(); if (mLocalUserCredentials != null) { System.out.println("Requesting sync..."); restoreUserToSandbox(mSandbox, mLocalUserCredentials[0], mLocalUserCredentials[1]); } else { System.out.println("Syncing is only available when using raw user credentials"); } } private void performCasePurge() { System.out.println("Performing Case Purge"); CasePurgeFilter purger = new CasePurgeFilter(mSandbox.getCaseStorage(), SandboxUtils.extractEntityOwners(mSandbox)); int removedCases = mSandbox.getCaseStorage().removeAll(purger).size(); System.out.println(""); System.out.println("Purge Report"); System.out.println("========================="); if (removedCases == 0) { System.out.println("0 Cases Purged"); } else { System.out.println("Cases Removed from device[" + removedCases + "]: " + purger.getRemovedCasesString()); } if (!("".equals(purger.getRemovedCasesString()))) { System.out.println("[Error/Warning] Cases Missing from Device: " + purger.getMissingCasesString()); } if (purger.invalidEdgesWereRemoved()) { System.out.println("[Error/Warning] During Purge Invalid Edges were Detected"); } } }
package org.commcare.util.cli; import org.commcare.cases.util.CaseDBUtils; import org.commcare.cases.util.CasePurgeFilter; import org.commcare.core.interfaces.UserSandbox; import org.commcare.core.parse.CommCareTransactionParserFactory; import org.commcare.core.parse.ParseUtils; import org.commcare.core.sandbox.SandboxUtils; import org.commcare.data.xml.DataModelPullParser; import org.commcare.modern.session.SessionWrapper; import org.commcare.resources.model.InstallCancelledException; import org.commcare.resources.model.UnresolvedResourceException; import org.commcare.session.SessionFrame; import org.commcare.suite.model.FormIdDatum; import org.commcare.suite.model.SessionDatum; import org.commcare.suite.model.StackFrameStep; import org.commcare.util.CommCarePlatform; import org.commcare.util.engine.CommCareConfigEngine; import org.commcare.util.mocks.CLISessionWrapper; import org.commcare.util.mocks.MockUserDataSandbox; import org.commcare.util.screen.CommCareSessionException; import org.commcare.util.screen.EntityScreen; import org.commcare.util.screen.MenuScreen; import org.commcare.util.screen.QueryScreen; import org.commcare.util.screen.Screen; import org.commcare.util.screen.SessionUtils; import org.commcare.util.screen.SyncScreen; import org.javarosa.core.model.User; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.services.PropertyManager; import org.javarosa.core.services.locale.Localization; import org.javarosa.core.services.locale.Localizer; import org.javarosa.core.services.storage.IStorageIterator; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.services.storage.StorageManager; import org.javarosa.core.util.externalizable.PrototypeFactory; import org.javarosa.engine.XFormPlayer; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.javarosa.xpath.XPathException; import org.javarosa.xpath.XPathParseTool; import org.javarosa.xpath.expr.FunctionUtils; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.parser.XPathSyntaxException; import org.xmlpull.v1.XmlPullParserException; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.PasswordAuthentication; import java.net.URL; /** * CLI host for running a commcare application which has been configured and instatiated * for the provided user. * * @author ctsims */ public class ApplicationHost { private final CommCareConfigEngine mEngine; private final CommCarePlatform mPlatform; private UserSandbox mSandbox; private CLISessionWrapper mSession; private boolean mUpdatePending = false; private String mUpdateTarget = null; private boolean mSessionHasNextFrameReady = false; private final PrototypeFactory mPrototypeFactory; private final BufferedReader reader; private final PrintStream printStream; private String username; private String qualifiedUsername; private String password; private String mRestoreFile; private boolean mRestoreStrategySet = false; public ApplicationHost(CommCareConfigEngine engine, PrototypeFactory prototypeFactory, BufferedReader reader, PrintStream out) { this.mEngine = engine; this.mPlatform = engine.getPlatform(); this.reader = reader; this.mPrototypeFactory = prototypeFactory; this.printStream = out; } public ApplicationHost(CommCareConfigEngine engine, PrototypeFactory prototypeFactory) { this(engine, prototypeFactory, new BufferedReader(new InputStreamReader(System.in)), System.out); } public void setRestoreToRemoteUser(String username, String password) { this.username = username; this.password = password; String domain = mPlatform.getPropertyManager().getSingularProperty("cc_user_domain"); this.qualifiedUsername = username + "@" + domain; mRestoreStrategySet = true; } public void setRestoreToLocalFile(String filename) { this.mRestoreFile = filename; mRestoreStrategySet = true; } public void setRestoreToDemoUser() { mRestoreStrategySet = true; } public void run() { if (!mRestoreStrategySet) { throw new RuntimeException("You must set up an application host by calling " + "one of hte setRestore*() methods before running the app"); } setupSandbox(); mSession = new CLISessionWrapper(mPlatform, mSandbox); try { loop(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } } private void loop() throws IOException { boolean keepExecuting = true; while (keepExecuting) { if (!mSessionHasNextFrameReady) { mSession.clearAllState(); } mSessionHasNextFrameReady = false; keepExecuting = loopSession(); if (this.mUpdatePending) { processAppUpdate(); } } } private void processAppUpdate() { mSession.clearAllState(); this.mUpdatePending = false; String updateTarget = mUpdateTarget; this.mUpdateTarget = null; try { mEngine.attemptAppUpdate(updateTarget); } catch (UnresolvedResourceException e) { printStream.println("Update Failed! Couldn't find or install one of the remote resources"); e.printStackTrace(); } catch (UnfullfilledRequirementsException e) { printStream.println("Update Failed! This CLI host is incompatible with the app"); e.printStackTrace(); } catch (InstallCancelledException e) { printStream.println("Update Failed! Update was cancelled"; e.printStackTrace(); } } private boolean loopSession() throws IOException { Screen s = getNextScreen(); boolean screenIsRedrawing = false; boolean sessionIsLive = true; while (sessionIsLive) { while (s != null) { try { if (!screenIsRedrawing) { s.init(mSession); if (s.shouldBeSkipped()) { s = getNextScreen(); continue; } } printStream.println("\n\n\n\n\n\n"); printStream.println(s.getWrappedDisplaytitle(mSandbox, mPlatform)); printStream.println("===================="); s.prompt(printStream); printStream.print("> "); screenIsRedrawing = false; String input = reader.readLine(); //TODO: Command language if (input.startsWith(":")) { if (input.equals(":exit") || input.equals(":quit")) { return false; } if (input.startsWith(":update")) { mUpdatePending = true; if (input.contains(("--latest")) || input.contains("-f")) { mUpdateTarget = "build"; printStream.println("Updating to most recent build"); } else if (input.contains(("--preview")) || input.contains("-p")) { mUpdateTarget = "save"; printStream.println("Updating to latest app preview"); } else { mUpdateTarget = "release"; printStream.println("Updating to newest Release"); } return true; } if (input.equals(":home")) { return true; } if (input.equals(":back")) { mSession.stepBack(mSession.getEvaluationContext()); s = getNextScreen(); continue; } if (input.equals(":stack")) { printStack(mSession); continue; } if (input.startsWith(":lang")) { String[] langArgs = input.split(" "); if (langArgs.length != 2) { printStream.println("Command format\n:lang [langcode]"); continue; } String newLocale = langArgs[1]; setLocale(newLocale); continue; } if (input.startsWith(":sync")) { syncAndReport(); continue; } } screenIsRedrawing = s.handleInputAndUpdateSession(mSession, input); if (!screenIsRedrawing) { s = getNextScreen(); } } catch (CommCareSessionException ccse) { printErrorAndContinue("Error during session execution:", ccse); //Restart return true; } catch (XPathException xpe) { printErrorAndContinue("XPath Evaluation exception during session execution:", xpe); //Restart return true; } } //We have a session and are ready to fill out a form! printStream.println("Starting form entry with the following stack frame"); printStack(mSession); //Get our form object String formXmlns = mSession.getForm(); if (formXmlns == null) { finishSession(); return true; } else { XFormPlayer player = new XFormPlayer(reader, printStream, null); player.setPreferredLocale(Localization.getGlobalLocalizerAdvanced().getLocale()); player.setSessionIIF(mSession.getIIF()); player.start(mEngine.loadFormByXmlns(formXmlns)); //If the form saved properly, process the output if (player.getExecutionResult() == XFormPlayer.FormResult.Completed) { if (!processResultInstance(player.getResultStream())) { return true; } finishSession(); return true; } else if (player.getExecutionResult() == XFormPlayer.FormResult.Cancelled) { mSession.stepBack(mSession.getEvaluationContext()); s = getNextScreen(); } else { //Handle this later return true; } } } //After we finish, continue executing return true; } private void printStack(CLISessionWrapper mSession) { SessionFrame frame = mSession.getFrame(); printStream.println("Live Frame"); printStream.println(" for (StackFrameStep step : frame.getSteps()) { if (step.getType().equals(SessionFrame.STATE_COMMAND_ID)) { printStream.println("COMMAND: " + step.getId()); } else { printStream.println("DATUM : " + step.getId() + " - " + step.getValue()); } } } private void finishSession() { mSession.clearVolatiles(); if (mSession.finishExecuteAndPop(mSession.getEvaluationContext())) { mSessionHasNextFrameReady = true; } } private boolean processResultInstance(InputStream resultStream) { try { DataModelPullParser parser = new DataModelPullParser( resultStream, new CommCareTransactionParserFactory(mSandbox), true, true); parser.parse(); } catch (Exception e) { printErrorAndContinue("Error processing the form result!", e); return false; } finally { try { resultStream.close(); } catch (IOException e) { e.printStackTrace(); } } return true; } private void printErrorAndContinue(String error, Exception e) { printStream.println(error); e.printStackTrace(); printStream.println("Press return to restart the session"); try { reader.readLine(); } catch (IOException ex) { throw new RuntimeException(ex); } } private Screen getNextScreen() { String next = mSession.getNeededData(mSession.getEvaluationContext()); if (next == null) { //XFORM TIME! return null; } else if (next.equals(SessionFrame.STATE_COMMAND_ID)) { return new MenuScreen(); } else if (next.equals(SessionFrame.STATE_DATUM_VAL)) { return new EntityScreen(true); } else if (next.equals(SessionFrame.STATE_QUERY_REQUEST)) { return new QueryScreen(qualifiedUsername, password, System.out); } else if (next.equals(SessionFrame.STATE_SYNC_REQUEST)) { return new SyncScreen(qualifiedUsername, password, System.out); } else if (next.equalsIgnoreCase(SessionFrame.STATE_DATUM_COMPUTED)) { computeDatum(); return getNextScreen(); } throw new RuntimeException("Unexpected Frame Request: " + next); } private void computeDatum() { //compute SessionDatum datum = mSession.getNeededDatum(); XPathExpression form; try { form = XPathParseTool.parseXPath(datum.getValue()); } catch (XPathSyntaxException e) { //TODO: What. e.printStackTrace(); throw new RuntimeException(e.getMessage()); } EvaluationContext ec = mSession.getEvaluationContext(); if (datum instanceof FormIdDatum) { mSession.setXmlns(FunctionUtils.toString(form.eval(ec))); mSession.setDatum("", "awful"); } else { try { mSession.setDatum(datum.getDataId(), FunctionUtils.toString(form.eval(ec))); } catch (XPathException e) { error(e); } } } private void error(Exception e) { e.printStackTrace(); System.exit(-1); } private void setupSandbox() { //Set up our storage MockUserDataSandbox sandbox = new MockUserDataSandbox(mPrototypeFactory); //this gets configured earlier when we installed the app, should point it in the //right direction! sandbox.setAppFixtureStorageLocation((IStorageUtilityIndexed<FormInstance>) mPlatform.getStorageManager().getStorage(FormInstance.STORAGE_KEY)); mSandbox = sandbox; if (username != null && password != null) { SessionUtils.restoreUserToSandbox(mSandbox, mSession, mPlatform, username, password, System.out); } else if (mRestoreFile != null) { restoreFileToSandbox(mSandbox, mRestoreFile); } else { restoreDemoUserToSandbox(mSandbox); } } private void restoreFileToSandbox(UserSandbox sandbox, String restoreFile) { FileInputStream fios = null; try { printStream.println("Restoring user data from local file " + restoreFile); fios = new FileInputStream(restoreFile); } catch (FileNotFoundException e) { printStream.println("No restore file found at" + restoreFile); System.exit(-1); } try { ParseUtils.parseIntoSandbox(new BufferedInputStream(fios), sandbox, false); } catch (Exception e) { printStream.println("Error parsing local restore data from " + restoreFile); e.printStackTrace(); System.exit(-1); } initUser(); } private void initUser() { User u = mSandbox.getUserStorage().read(0); mSandbox.setLoggedInUser(u); printStream.println("Setting logged in user to: " + u.getUsername()); } private void restoreDemoUserToSandbox(UserSandbox sandbox) { try { ParseUtils.parseIntoSandbox(mPlatform.getDemoUserRestore().getRestoreStream(), sandbox, false); } catch (Exception e) { printStream.println("Error parsing demo user restore from app"); e.printStackTrace(); System.exit(-1); } initUser(); } private void setLocale(String locale) { Localizer localizer = Localization.getGlobalLocalizerAdvanced(); String availableLocales = ""; for (String availabile : localizer.getAvailableLocales()) { availableLocales += availabile + "\n"; if (locale.equals(availabile)) { localizer.setLocale(locale); return; } } printStream.println("Locale '" + locale + "' is undefined in this app! Available Locales:"); printStream.println(" printStream.println(availableLocales); } private void syncAndReport() { performCasePurge(mSandbox); if (username != null && password != null) { System.out.println("Requesting sync..."); SessionUtils.restoreUserToSandbox(mSandbox, mSession, mPlatform, username, password, System.out); } else { printStream.println("Syncing is only available when using raw user credentials"); } } public void performCasePurge(UserSandbox sandbox) { printStream.println("Performing Case Purge"); CasePurgeFilter purger = new CasePurgeFilter(sandbox.getCaseStorage(), SandboxUtils.extractEntityOwners(sandbox)); int removedCases = sandbox.getCaseStorage().removeAll(purger).size(); printStream.println(""); printStream.println("Purge Report"); printStream.println("========================="); if (removedCases == 0) { printStream.println("0 Cases Purged"); } else { printStream.println("Cases Removed from device[" + removedCases + "]: " + purger.getRemovedCasesString()); } if (!("".equals(purger.getRemovedCasesString()))) { printStream.println("[Error/Warning] Cases Missing from Device: " + purger.getMissingCasesString()); } if (purger.invalidEdgesWereRemoved()) { printStream.println("[Error/Warning] During Purge Invalid Edges were Detected"); } } }
package au.com.subash.entity; import java.io.Serializable; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Pattern; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author subash */ @Entity @Table(name = "APPUSER") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Appuser.findAll", query = "SELECT a FROM Appuser a") , @NamedQuery(name = "Appuser.findById", query = "SELECT a FROM Appuser a WHERE a.id = :id") , @NamedQuery(name = "Appuser.findByFirstname", query = "SELECT a FROM Appuser a WHERE a.firstname = :firstname") , @NamedQuery(name = "Appuser.findByLastname", query = "SELECT a FROM Appuser a WHERE a.lastname = :lastname") , @NamedQuery(name = "Appuser.findByEmail", query = "SELECT a FROM Appuser a WHERE a.email = :email") , @NamedQuery(name = "Appuser.findByPassword", query = "SELECT a FROM Appuser a WHERE a.password = :password") , @NamedQuery(name = "Appuser.findByCategory", query = "SELECT a FROM Appuser a WHERE a.category = :category")}) public class Appuser implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name = "appuser_id_seq", sequenceName = "appuser_id_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "appuser_id_seq") @Basic(optional = false) @Column(name = "ID") private Integer id; @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "FIRSTNAME") private String firstname; @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "LASTNAME") private String lastname; @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email") @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "EMAIL") private String email; @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "PASSWORD") private String password; @Basic(optional = false) @NotNull @Size(min = 1, max = 100) @Column(name = "CATEGORY") private String category; @OneToMany(cascade = CascadeType.ALL, mappedBy = "appuser") private List<Todolist> todolistList; public Appuser() { } public Appuser(Integer id) { this.id = id; } public Appuser(Integer id, String firstname, String lastname, String email, String password, String category) { this.id = id; this.firstname = firstname; this.lastname = lastname; this.email = email; this.password = password; this.category = category; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @XmlTransient public List<Todolist> getTodolistList() { return todolistList; } public void setTodolistList(List<Todolist> todolistList) { this.todolistList = todolistList; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Appuser)) { return false; } Appuser other = (Appuser) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "au.com.subash.entity.Appuser[ id=" + id + " ]"; } }
package edu.wustl.catissuecore.flex.dag; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import edu.wustl.cab2b.client.ui.util.ClientConstants; import edu.wustl.cab2b.client.ui.util.CommonUtils; import edu.wustl.common.querysuite.queryobject.ICondition; import edu.wustl.common.querysuite.queryobject.IExpression; import edu.wustl.common.querysuite.queryobject.IRule; import edu.wustl.common.querysuite.queryobject.RelationalOperator; public class DAGNode implements Externalizable,Comparable<DAGNode>{ private String nodeName=""; private int expressionId=0; private String toolTip=""; private String operatorBetweenAttrAndAssociation=""; private String nodeType =DAGConstant.CONSTRAINT_VIEW_NODE; private List<DAGNode> associationList = new ArrayList<DAGNode>(); private List<String> operatorList = new ArrayList<String>(); private List<String> pathList = new ArrayList<String>(); public DAGNode() { setOperatorBetweenAttrAndAssociation(ClientConstants.OPERATOR_AND); } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } /** * @param expression * Expression to set */ public void setExpressionId(int expressionId) { this.expressionId = expressionId; } public int getExpressionId() { return expressionId; } public void setToolTip(IExpression expression) { StringBuffer sb = new StringBuffer(); IRule rule = null; if (!((IExpression) expression).containsRule()) { return; } else { rule = (IRule) expression.getOperand(0); } int totalConditions = rule.size(); sb.append("Condition(s) on ").append("\n"); for (int i = 0; i < totalConditions; i++) { ICondition condition = rule.getCondition(i); sb.append((i + 1)).append(") "); String formattedAttributeName = CommonUtils.getFormattedString(condition.getAttribute() .getName()); sb.append(formattedAttributeName).append(" "); List<String> values = condition.getValues(); RelationalOperator operator = condition.getRelationalOperator(); sb.append(edu.wustl.cab2b.client.ui.query.Utility .displayStringForRelationalOperator(operator)).append(" "); int size = values.size(); if (size > 0)// Special case for 'Not Equals and Equals { if (size == 1) { sb.append(values.get(0)); } else { sb.append("("); if (values.get(0).indexOf(",") != -1) { sb.append("\""); sb.append(values.get(0)); sb.append("\""); } else { sb.append(values.get(0)); } for (int j = 1; j < size; j++) { sb.append(", "); if (values.get(j).indexOf(",") != -1) { sb.append("\""); sb.append(values.get(j)); sb.append("\""); } else { sb.append(values.get(j)); } } sb.append(")"); } } sb.append("\n"); } this.toolTip=sb.toString(); } public String getToolTip() { return toolTip; } public String getOperatorBetweenAttrAndAssociation() { return operatorBetweenAttrAndAssociation; } public void setOperatorBetweenAttrAndAssociation( String operatorBetweenAttrAndAssociation) { this.operatorBetweenAttrAndAssociation = operatorBetweenAttrAndAssociation; } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // TODO Auto-generated method stub nodeName=in.readUTF(); toolTip = in.readUTF(); expressionId=in.readInt(); operatorBetweenAttrAndAssociation=in.readUTF(); nodeType =in.readUTF(); associationList = (List<DAGNode>) in.readObject(); operatorList = (List<String>) in.readObject(); pathList = (List<String>) in.readObject(); } public void writeExternal(ObjectOutput out) throws IOException { // TODO Auto-generated method stub out.writeUTF(nodeName); out.writeUTF(toolTip); out.writeInt(expressionId); out.writeUTF(operatorBetweenAttrAndAssociation); out.writeUTF(nodeType); out.writeObject(associationList); out.writeObject(operatorList); out.writeObject(pathList); } public String toString() { StringBuffer buff = new StringBuffer(""); buff.append("\n nodeName: ").append(nodeName).append("\n toolTip: ").append(toolTip). append("\n expressionId: ").append(expressionId).append("\n operatorBetweenAttrAndAssociation:"). append(operatorBetweenAttrAndAssociation); return buff.toString(); } public int compareTo(DAGNode node) { // TODO Auto-generated method stub return 0; } public boolean equals(Object obj) { DAGNode node = (DAGNode) obj; boolean equal =false; if(this.expressionId==node.expressionId) { equal = true; } return equal; } public List<DAGNode> getAssociationList() { return associationList; } public void setAssociationList(DAGNode node) { this.associationList.add(node); } public List<String> getOperatorList() { return operatorList; } public void setOperatorList(String operator) { this.operatorList.add(operator); } public List<String> getPathList() { return pathList; } public void setPathList(String path) { this.pathList.add(path); } public String getNodeType() { return nodeType; } public void setNodeType(String nodeType) { this.nodeType = nodeType; } }
package edu.wustl.common.util.tag; import java.io.IOException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; public class PagenationTag extends TagSupport { protected String name = "Bhanu"; protected int pageNum = 1; protected String prevPage = null; protected int totalResults = 1000; protected int numResultsPerPage = 5; protected int m_pageLinkStart = 1; protected int m_pageLinkEnd = 10; protected boolean m_showNext = true; protected String searchTerm = null; protected String searchTermValues = null; protected String [] selectedOrgs = null; private int numLinks = 10; private int resultLowRange = 1; private int resultHighRange = 1; private String pageName = null; public int doStartTag() { try { JspWriter out = pageContext.getOut(); out.println("<table class=\"dataTableWhiteLabel\" border=0 bordercolor=#666699 width=100%>"); if (pageNum > numLinks) { if (pageNum % numLinks != 0) m_pageLinkStart = ((pageNum / numLinks) * numLinks + 1); else m_pageLinkStart = (pageNum - numLinks) + 1; } else //For first time or for PageNum < 10. m_pageLinkStart = 1; //Set the values of the ending Links on the Page. //This checks if number of Results left in the arrayList is less than numResults i.e. showNext==zero // System.out.println("totalResults = " + totalResults // + " numResultsPerPage = " + numResultsPerPage // + " m_pageLinkStart = " + m_pageLinkStart); // System.out.println(" totalResults "+totalResults+" numResultsPerPage = "+numResultsPerPage+" "); if ((totalResults - ((m_pageLinkStart - 1) * numResultsPerPage)) >= numResultsPerPage * numLinks) { m_pageLinkEnd = m_pageLinkStart + (numLinks - 1); } else { if ((totalResults - (m_pageLinkStart * numResultsPerPage)) > 0) { if (totalResults % numResultsPerPage == 0) { m_pageLinkEnd = (m_pageLinkStart + (totalResults - (m_pageLinkStart * numResultsPerPage)) / numResultsPerPage); } else { m_pageLinkEnd = (m_pageLinkStart + (totalResults - (m_pageLinkStart * numResultsPerPage)) / numResultsPerPage) + 1; } } else { m_pageLinkEnd = (m_pageLinkStart + (totalResults - (m_pageLinkStart * numResultsPerPage)) / numResultsPerPage); } } // System.out.println("totalResults = " + totalResults // + " m_pageLinkStart" + m_pageLinkStart // + " numResultsPerPage = " + numResultsPerPage // + " numLinks = " + numLinks+" m_pageLinkEnd = "+m_pageLinkEnd); // If we have exhausted our resultset, then set m_showNext as false. which means NEXT link must not be shown if ((totalResults - ((m_pageLinkStart - 1) * numResultsPerPage)) <= (numResultsPerPage * numLinks)) { m_showNext = false; } resultLowRange = (pageNum - 1) * numResultsPerPage + 1; if (totalResults - ((pageNum - 1) * numResultsPerPage) < numResultsPerPage) { resultHighRange = resultLowRange + totalResults - ((pageNum - 1) * numResultsPerPage) - 1; } else { resultHighRange = resultLowRange + numResultsPerPage - 1; } // System.out.println("resultLowRange = "+resultLowRange+" resultHighRange "+resultHighRange+" pageNum = "+pageNum); out.println("<tr> <td class = \"formtextbg\" align=\"CENTER\">"+name+"</td>"); out.println("<td align = \"CENTER\" class = \"formtextbg\">Showing Results " + resultLowRange + " - " + resultHighRange + " of " + totalResults + "</td>"); if ((m_pageLinkEnd) > numLinks) { out.print("<td align=\"CENTER\"><a href=\"javascript:send("+(m_pageLinkStart -1)+","+totalResults+",'"+prevPage+"','"+pageName+"')" + "\"> &gt;&gt;PREV </a></td>"); } else { out.print("<td align=\"CENTER\">&nbsp;</td>"); } int i = m_pageLinkStart; for (i = m_pageLinkStart; i <= m_pageLinkEnd; i++) { if (i != pageNum) { out.print("<td align=\"CENTER\"> <a href=\"javascript:send("+i+","+totalResults+",'"+prevPage+"','"+pageName+"')" + "\">" + i + " </a></td>"); } else { out.print("<td align=\"CENTER\">" + i + " </td>"); } } if (m_showNext == true) { out.print("<td align=\"CENTER\"><a href=\"javascript:send("+i+","+totalResults+",'"+prevPage+"','"+pageName+"')" +"\"> NEXT>> </a> </td>"); } else { out.print("<td align=\"CENTER\">&nbsp;</td>"); } out.print("</tr></table>"); } catch (IOException ioe) { System.out.println("Error generating prime: " + ioe); } catch (Exception e) { e.printStackTrace(); } return (SKIP_BODY); } /** * @param name The name to set. */ public void setName(String name) { this.name = name; } /** * @param pageNum The pageNum to set. */ public void setPageNum(int pageNum) { try { this.pageNum = pageNum; } catch (NumberFormatException nfe) { this.pageNum = 1; nfe.printStackTrace(); } } /** * @param totalResults The totalResults to set. */ public void setTotalResults(int totalResults) { try { this.totalResults = totalResults; } catch (NumberFormatException nfe) { this.totalResults = 1000; } } /** * @param numResultsPerPage The numResultsPerPage to set. */ public void setNumResultsPerPage(int numResultsPerPage) { try { this.numResultsPerPage = numResultsPerPage; } catch (NumberFormatException nfe) { this.numResultsPerPage = 10; } } /** * @param searchTerm The searchTerm to set. */ public void setSearchTerm(String searchTerm) { this.searchTerm = searchTerm; } /** * @param searchTermvalues The searchTermvalues to set. */ public void setSearchTermValues(String searchTermvalues) { this.searchTermValues = searchTermvalues; } /** * @param selectedOrgs The selectedOrgs to set. */ public void setSelectedOrgs(String[] selectedOrgs) { this.selectedOrgs = selectedOrgs; } /** * @return Returns the prevPage. */ public String getPrevPage() { return prevPage; } /** * @param prevPage The prevPage to set. */ public void setPrevPage(String prevPage) { this.prevPage = prevPage; } /** * @return Returns the pageName. */ public String getPageName() { return pageName; } /** * @param pageName The pageName to set. */ public void setPageName(String pageName) { this.pageName = pageName; } }
package au.edu.unimelb.boldapp; import android.util.Log; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.content.Intent; import android.widget.Toast; import au.edu.unimelb.boldapp.sync.Client; import au.edu.unimelb.boldapp.FileIO; public class SyncSplashActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sync_splash); final Server server = (Server) getIntent().getExtras().get("ServerInfo"); Handler handler = new Handler(); // run a thread after 2 seconds to start the home screen handler.postDelayed(new Runnable() { @Override public void run() { Client client = new Client(); client.setClientBaseDir(FileIO.getAppRootPath().toString()); // Eventually want a method in Client to find it's own server // base dir by recursively searching for a writable directory. //client.setServerBaseDir("/part0/share/bold/"); if (!client.login(server.getIPAddress(), server.getUsername(), server.getPassword())) { Log.i("1234", "here2"); Toast.makeText(SyncSplashActivity.this, "Login failed." + " Are you connected to the correct wireless network?", Toast.LENGTH_LONG).show(); finish(); } else if (!client.sync()) { Log.i("1234", "here3"); Toast.makeText(SyncSplashActivity.this, "Sync failed.", Toast.LENGTH_LONG).show(); finish(); } else if (!client.logout()) { Log.i("1234", "here4"); Toast.makeText(SyncSplashActivity.this, "Logout failed.", Toast.LENGTH_LONG).show(); finish(); } else { Log.i("1234", "here"); Toast.makeText(SyncSplashActivity.this, "Syncing Complete.", Toast.LENGTH_LONG).show(); } finish(); // start the home screen /* Intent intent = new Intent(SyncSplashActivity.this, InitialUserSelectionActivity.class); SyncSplashActivity.this.startActivity(intent); */ } }, 50); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called } }
package bwyap.familyfeud.gui; import java.util.HashMap; import java.util.Map; import javax.swing.UIManager.LookAndFeelInfo; import bwyap.familyfeud.OSValidator; import bwyap.utility.logging.ConsoleLogger; /** * This class is responsible for handling UI settings to allow macOS and win10 compatibility. * This class is implemented as a singleton. * @author bwyap * */ public class UIManager { public enum SupportedOS { WINDOWS, MACOS; } private static UIManager INSTANCE; private static boolean widescreen = false; private Map<String, Integer> map; /** * Get the UI Manager instance. * @return */ public static UIManager getInstance() { if (INSTANCE == null) { INSTANCE = new UIManager(); } return INSTANCE; } private UIManager() { map = new HashMap<String, Integer>(); // Load dimensions according to detected UI if (OSValidator.isMac()) loadMacOSUI(); else if (OSValidator.isWindows()) loadWindowsUI(); } /** * Set whether wide screen dimensions should be used. * This must be called before the first {@code getInstance} call. * Default is false. * @param widescreen */ public static void setWidescreen(boolean widescreen) { UIManager.widescreen = widescreen; } /** * Get whether wide screen dimensions should be used. * Default is false, unless otherwise set by the user. * @return */ public static boolean isWidescreen() { return UIManager.widescreen; } /** * Load macOS UI settings */ private void loadMacOSUI() { loadMacOSDimensions(); } /** * Load Windows UI settings */ private void loadWindowsUI() { loadWindowsDimensions(); // Set the look and feel try { for (LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { //System.out.println(info.getName()); if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) { } } /** * Load macOS dimensions */ private void loadMacOSDimensions() { // TODO make this more dynamic map.put("controlwindow.width", 800); map.put("controlwindow.height", 640); map.put("windowcontrolpanel.width", 180); map.put("windowcontrolpanel.height", 120); map.put("statepanel.width", 180); map.put("statepanel.height", 220); map.put("consolepanel.width", map.get("controlwindow.width") - 10 - 180); map.put("consolepanel.height", 200); map.put("soundpanel.width", 180); map.put("soundpanel.height", map.get("consolepanel.height")); map.put("stateplaypanel.width", map.get("statepanel.width")); map.put("stateplaypanel.height", map.get("controlwindow.height") - map.get("consolepanel.height") - map.get("statepanel.height") - 25); map.put("familypanel.width", map.get("windowcontrolpanel.width")); map.put("familypanel.height", map.get("stateplaypanel.height")); map.put("managefamilypanel.width", map.get("statepanel.width")); map.put("managefamilypanel.height", map.get("statepanel.height") - map.get("windowcontrolpanel.height")); map.put("questionselectionpanel.width", map.get("controlwindow.width") - map.get("statepanel.width") - map.get("windowcontrolpanel.width") - 10); map.put("questionselectionpanel.height", (int)(0.8 * map.get("statepanel.height"))); map.put("questionsetloaderpanel.width", map.get("controlwindow.width") - map.get("statepanel.width") - map.get("windowcontrolpanel.width") - 10); map.put("questionsetloaderpanel.height", map.get("statepanel.height") - map.get("questionselectionpanel.height")); map.put("questioncontrolpanel.width", map.get("questionselectionpanel.width")); map.put("questioncontrolpanel.height", map.get("stateplaypanel.height")); if (widescreen) { map.put("gamewindow.width", 1280); map.put("gamewindow.height", 720); } else { map.put("gamewindow.width", 1024); map.put("gamewindow.height", 768); } map.put("questionselectionpanel.col0.width", 20); map.put("questionselectionpanel.col1.width", 40); map.put("questionselectionpanel.col2.width", 40); map.put("questionselectionpanel.col3.width", 400); map.put("questioncontrolpanel.col2.width", 60); map.put("questioncontrolpanel.col1.width", 60); map.put("questioncontrolpanel.col0.width", map.get("questioncontrolpanel.width") - 30 - map.get("questioncontrolpanel.col1.width") - map.get("questioncontrolpanel.col2.width") - 5); map.put("fastmoneywindow.width", 400); map.put("fastmoneywindow.height", 600); map.put("fastmoneyanswerpanel.width", 390); map.put("fastmoneyanswerpanel.height", 200); map.put("fastmoneytimerpanel.width", 150); map.put("fastmoneytimerpanel.height", 150); ConsoleLogger.getInstance().setFontSize(12); } /** * Load Windows dimensions */ private void loadWindowsDimensions() { loadMacOSDimensions(); // Windows10 Fix map.put("windowcontrolpanel.height", 130); map.put("statepanel.height", 230); map.put("questionsetloaderpanel.height", map.get("statepanel.height") - map.get("questionselectionpanel.height")); map.put("controlwindow.height", 680); map.put("stateplaypanel.height", map.get("stateplaypanel.height") + 10); map.put("questioncontrolpanel.height", map.get("questioncontrolpanel.height") + 10); map.put("familypanel.height", map.get("familypanel.height") + 10); map.put("questionselectionpanel.col0.width", 50); map.put("questionselectionpanel.col1.width", 50); map.put("questionselectionpanel.col2.width", 50); map.put("questionselectionpanel.col3.width", 400); map.put("questioncontrolpanel.col2.width", 80); map.put("questioncontrolpanel.col1.width", 60); map.put("questioncontrolpanel.col0.width", map.get("questioncontrolpanel.width") - 30 - map.get("questioncontrolpanel.col1.width") - map.get("questioncontrolpanel.col2.width") - 5); map.put("fastmoneywindow.width", 450); map.put("fastmoneywindow.height", 600); map.put("fastmoneyanswerpanel.width", 440); map.put("fastmoneytimerpanel.width", 200); ConsoleLogger.getInstance().setFontSize(14); } /** * Get the value for the specified property for the current OS. * @param propertyname * @return */ public int getProperty(String propertyname) { return map.get(propertyname); } }
package com.vondear.rxtools; import android.content.Context; import android.os.Handler; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class RxUtils { private static Context context; /** * * * @param context */ public static void init(Context context) { RxUtils.context = context.getApplicationContext(); RxCrashUtils.getInstance(context).init(); } /** * Context Context * <p> * ApplicationContext * * @return ApplicationContext */ public static Context getContext() { if (context != null) return context; throw new NullPointerException("init()"); } public static void delayToDo(final DelayListener delayListener, long delayTime) { new Handler().postDelayed(new Runnable() { public void run() { //execute the task delayListener.doSomething(); } }, delayTime); } /** * * * @param textView * @param waitTime * @param interval * @param hint */ public static void countDown(final TextView textView, long waitTime, long interval, final String hint) { textView.setEnabled(false); android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) { @Override public void onTick(long millisUntilFinished) { textView.setText(" " + (millisUntilFinished / 1000) + " S"); } @Override public void onFinish() { textView.setEnabled(true); textView.setText(hint); } }; timer.start(); } /** * listView * * @param listView */ public static void fixListViewHeight(ListView listView) { // ListView ListAdapter listAdapter = listView.getAdapter(); int totalHeight = 0; if (listAdapter == null) { return; } for (int index = 0, len = listAdapter.getCount(); index < len; index++) { View listViewItem = listAdapter.getView(index, null, listView); // View listViewItem.measure(0, 0); totalHeight += listViewItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); // listView.getDividerHeight() // params.heightListView params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } /** * MD532 * * @param MStr : * @return */ public static String Md5(String MStr) { try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(MStr.getBytes()); return bytesToHexString(mDigest.digest()); } catch (NoSuchAlgorithmException e) { return String.valueOf(MStr.hashCode()); } } private static String bytesToHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } /** * id * * ,ID * * * getResources().getIdentifier("ic_launcher", "drawable", getPackageName()); * * @param context * @param name * @param defType * @return */ public static final int getResIdByName(Context context,String name,String defType) { return context.getResources().getIdentifier("ic_launcher", "drawable", context.getPackageName()); } public interface DelayListener { void doSomething(); } private static long lastClickTime; public static boolean isFastClick(long millisecond) { long time = System.currentTimeMillis(); long timeD = time - lastClickTime; if ( 0 < timeD && timeD < 800) { return true; } lastClickTime = time; return false; } }
package org.roaringbitmap; import java.util.Arrays; import static java.lang.Long.numberOfTrailingZeros; /** * Various useful methods for roaring bitmaps. */ public final class Util { /** * optimization flag: whether to use hybrid binary search: hybrid formats * combine a binary search with a sequential search */ public static final boolean USE_HYBRID_BINSEARCH = true; /** * Add value "offset" to all values in the container, producing * two new containers. The existing container remains unchanged. * The new container are not converted, so they need to be checked: * e.g., we could produce two bitmap containers having low cardinality. * @param source source container * @param offsets value to add to each value in the container * @return return an array made of two containers */ public static Container[] addOffset(Container source, char offsets) { // could be a whole lot faster, this is a simple implementation if(source instanceof ArrayContainer) { ArrayContainer c = (ArrayContainer) source; ArrayContainer low = new ArrayContainer(c.cardinality); ArrayContainer high = new ArrayContainer(c.cardinality); for(int k = 0; k < c.cardinality; k++) { int val = c.content[k]; val += (int) (offsets); if(val <= 0xFFFF) { low.content[low.cardinality++] = (char) val; } else { high.content[high.cardinality++] = (char) val; } } return new Container[] {low, high}; } else if (source instanceof BitmapContainer) { BitmapContainer c = (BitmapContainer) source; BitmapContainer low = new BitmapContainer(); BitmapContainer high = new BitmapContainer(); low.cardinality = -1; high.cardinality = -1; final int b = (int) (offsets) >>> 6; final int i = (int) (offsets) % 64; if(i == 0) { System.arraycopy(c.bitmap, 0, low.bitmap, b, 1024 - b); System.arraycopy(c.bitmap, 1024 - b, high.bitmap, 0, b ); } else { low.bitmap[b + 0] = c.bitmap[0] << i; for(int k = 1; k < 1024 - b; k++) { low.bitmap[b + k] = (c.bitmap[k] << i) | (c.bitmap[k - 1] >>> (64-i)); } for(int k = 1024 - b; k < 1024 ; k++) { high.bitmap[k - (1024 - b)] = (c.bitmap[k] << i) | (c.bitmap[k - 1] >>> (64-i)); } high.bitmap[b] = (c.bitmap[1024 - 1] >>> (64-i)); } return new Container[] {low.repairAfterLazy(), high.repairAfterLazy()}; } else if (source instanceof RunContainer) { RunContainer input = (RunContainer) source; RunContainer low = new RunContainer(); RunContainer high = new RunContainer(); for(int k = 0 ; k < input.nbrruns; k++) { int val = (input.getValue(k)); val += (int) (offsets); int finalval = val + (input.getLength(k)); if(val <= 0xFFFF) { if(finalval <= 0xFFFF) { low.smartAppend((char)val,input.getLength(k)); } else { low.smartAppend((char)val,(char)(0xFFFF-val)); high.smartAppend((char) 0,(char)finalval); } } else { high.smartAppend((char)val,input.getLength(k)); } } return new Container[] {low, high}; } throw new RuntimeException("unknown container type"); // never happens } /** * Find the smallest integer larger than pos such that array[pos]&gt;= min. If none can be found, * return length. Based on code by O. Kaser. * * @param array array to search within * @param pos starting position of the search * @param length length of the array to search * @param min minimum value * @return x greater than pos such that array[pos] is at least as large as min, pos is is equal to * length if it is not possible. */ public static int advanceUntil(char[] array, int pos, int length, char min) { int lower = pos + 1; // special handling for a possibly common sequential case if (lower >= length || (array[lower]) >= (int) (min)) { return lower; } int spansize = 1; // could set larger // bootstrap an upper limit while (lower + spansize < length && (array[lower + spansize]) < (int) (min)) { spansize *= 2; // hoping for compiler will reduce to } // shift int upper = (lower + spansize < length) ? lower + spansize : length - 1; // maybe we are lucky (could be common case when the seek ahead // expected // to be small and sequential will otherwise make us look bad) if (array[upper] == min) { return upper; } if ((array[upper]) < (int) (min)) { // means array has no item >= min pos = array.length; return length; } // we know that the next-smallest span was too small lower += (spansize >>> 1); // else begin binary search // invariant: array[lower]<min && array[upper]>min while (lower + 1 != upper) { int mid = (lower + upper) >>> 1; char arraymid = array[mid]; if (arraymid == min) { return mid; } else if ((arraymid) < (int) (min)) { lower = mid; } else { upper = mid; } } return upper; } /** * Find the smallest integer larger than pos such that array[pos]&gt;= min. If none can be found, * return length. * * @param array array to search within * @param pos starting position of the search * @param length length of the array to search * @param min minimum value * @return x greater than pos such that array[pos] is at least as large as min, pos is is equal to * length if it is not possible. */ public static int iterateUntil(char[] array, int pos, int length, int min) { while (pos < length && (array[pos]) < min) { pos++; } return pos; } protected static int branchyUnsignedBinarySearch(final char[] array, final int begin, final int end, final char k) { // next line accelerates the possibly common case where the value would // be inserted at the end if ((end > 0) && ((array[end - 1]) < (int) (k))) { return -end - 1; } int low = begin; int high = end - 1; while (low <= high) { final int middleIndex = (low + high) >>> 1; final int middleValue = (array[middleIndex]); if (middleValue < (int) (k)) { low = middleIndex + 1; } else if (middleValue > (int) (k)) { high = middleIndex - 1; } else { return middleIndex; } } return -(low + 1); } /** * Compute the bitwise AND between two long arrays and write the set bits in the container. * * @param container where we write * @param bitmap1 first bitmap * @param bitmap2 second bitmap */ public static void fillArrayAND(final char[] container, final long[] bitmap1, final long[] bitmap2) { int pos = 0; if (bitmap1.length != bitmap2.length) { throw new IllegalArgumentException("not supported"); } for (int k = 0; k < bitmap1.length; ++k) { long bitset = bitmap1[k] & bitmap2[k]; while (bitset != 0) { container[pos++] = (char) (k * 64 + numberOfTrailingZeros(bitset)); bitset &= (bitset - 1); } } } /** * Compute the bitwise ANDNOT between two long arrays and write the set bits in the container. * * @param container where we write * @param bitmap1 first bitmap * @param bitmap2 second bitmap */ public static void fillArrayANDNOT(final char[] container, final long[] bitmap1, final long[] bitmap2) { int pos = 0; if (bitmap1.length != bitmap2.length) { throw new IllegalArgumentException("not supported"); } for (int k = 0; k < bitmap1.length; ++k) { long bitset = bitmap1[k] & (~bitmap2[k]); while (bitset != 0) { container[pos++] = (char) (k * 64 + numberOfTrailingZeros(bitset)); bitset &= (bitset - 1); } } } /** * Compute the bitwise XOR between two long arrays and write the set bits in the container. * * @param container where we write * @param bitmap1 first bitmap * @param bitmap2 second bitmap */ public static void fillArrayXOR(final char[] container, final long[] bitmap1, final long[] bitmap2) { int pos = 0; if (bitmap1.length != bitmap2.length) { throw new IllegalArgumentException("not supported"); } for (int k = 0; k < bitmap1.length; ++k) { long bitset = bitmap1[k] ^ bitmap2[k]; while (bitset != 0) { container[pos++] = (char) (k * 64 + numberOfTrailingZeros(bitset)); bitset &= (bitset - 1); } } } /** * flip bits at start, start+1,..., end-1 * * @param bitmap array of words to be modified * @param start first index to be modified (inclusive) * @param end last index to be modified (exclusive) */ public static void flipBitmapRange(long[] bitmap, int start, int end) { if (start == end) { return; } int firstword = start / 64; int endword = (end - 1) / 64; bitmap[firstword] ^= ~(~0L << start); for (int i = firstword; i < endword; i++) { bitmap[i] = ~bitmap[i]; } bitmap[endword] ^= ~0L >>> -end; } /** * Hamming weight of the 64-bit words involved in the range * start, start+1,..., end-1, that is, it will compute the * cardinality of the bitset from index (floor(start/64) to floor((end-1)/64)) * inclusively. * * @param bitmap array of words representing a bitset * @param start first index (inclusive) * @param end last index (exclusive) * @return the hamming weight of the corresponding words */ @Deprecated public static int cardinalityInBitmapWordRange(long[] bitmap, int start, int end) { if (start >= end) { return 0; } int firstword = start / 64; int endword = (end - 1) / 64; int answer = 0; for (int i = firstword; i <= endword; i++) { answer += Long.bitCount(bitmap[i]); } return answer; } /** * Hamming weight of the bitset in the range * start, start+1,..., end-1 * * @param bitmap array of words representing a bitset * @param start first index (inclusive) * @param end last index (exclusive) * @return the hamming weight of the corresponding range */ public static int cardinalityInBitmapRange(long[] bitmap, int start, int end) { if (start >= end) { return 0; } int firstword = start / 64; int endword = (end - 1) / 64; if (firstword == endword) { return Long.bitCount(bitmap[firstword] & ( (~0L << start) & (~0L >>> -end) )); } int answer = Long.bitCount(bitmap[firstword] & (~0L << start)); for (int i = firstword + 1; i < endword; i++) { answer += Long.bitCount(bitmap[i]); } answer += Long.bitCount(bitmap[endword] & (~0L >>> -end)); return answer; } protected static char highbits(int x) { return (char) (x >>> 16); } protected static char highbits(long x) { return (char) (x >>> 16); } // starts with binary search and finishes with a sequential search protected static int hybridUnsignedBinarySearch(final char[] array, final int begin, final int end, final char k) { // next line accelerates the possibly common case where the value would // be inserted at the end if ((end > 0) && ((array[end - 1]) < (int) k)) { return -end - 1; } int low = begin; int high = end - 1; // 32 in the next line matches the size of a cache line while (low + 32 <= high) { final int middleIndex = (low + high) >>> 1; final int middleValue = (array[middleIndex]); if (middleValue < (int) k) { low = middleIndex + 1; } else if (middleValue > (int) k) { high = middleIndex - 1; } else { return middleIndex; } } // we finish the job with a sequential search int x = low; for (; x <= high; ++x) { final int val = (array[x]); if (val >= (int) k) { if (val == (int) k) { return x; } break; } } return -(x + 1); } protected static char lowbits(int x) { return (char) x; } protected static char lowbits(long x) { return (char) x; } protected static int lowbitsAsInteger(int x) { return x & 0xFFFF; } protected static int lowbitsAsInteger(long x) { return (int)(x & 0xFFFF); } public static int maxLowBitAsInteger() { return 0xFFFF; } /** * clear bits at start, start+1,..., end-1 * * @param bitmap array of words to be modified * @param start first index to be modified (inclusive) * @param end last index to be modified (exclusive) */ public static void resetBitmapRange(long[] bitmap, int start, int end) { if (start == end) { return; } int firstword = start / 64; int endword = (end - 1) / 64; if (firstword == endword) { bitmap[firstword] &= ~((~0L << start) & (~0L >>> -end)); return; } bitmap[firstword] &= ~(~0L << start); for (int i = firstword + 1; i < endword; i++) { bitmap[i] = 0; } bitmap[endword] &= ~(~0L >>> -end); } /** * Intersects the bitmap with the array, returning the cardinality of the result * @param bitmap the bitmap, modified * @param array the array, not modified * @param length how much of the array to consume * @return the size of the intersection, i.e. how many bits still set in the bitmap */ public static int intersectArrayIntoBitmap(long[] bitmap, char[] array, int length) { int lastWordIndex = 0; int wordIndex = 0; long word = 0L; int cardinality = 0; for (int i = 0; i < length; ++i) { wordIndex = array[i] >>> 6; if (wordIndex != lastWordIndex) { bitmap[lastWordIndex] &= word; cardinality += Long.bitCount(bitmap[lastWordIndex]); word = 0L; Arrays.fill(bitmap, lastWordIndex + 1, wordIndex, 0L); lastWordIndex = wordIndex; } word |= 1L << array[i]; } if (word != 0L) { bitmap[wordIndex] &= word; cardinality += Long.bitCount(bitmap[lastWordIndex]); } if (wordIndex < bitmap.length) { Arrays.fill(bitmap, wordIndex + 1, bitmap.length, 0L); } return cardinality; } /** * Given a word w, return the position of the jth true bit. * * @param w word * @param j index * @return position of jth true bit in w */ public static int select(long w, int j) { int seen = 0; // Divide 64bit int part = (int) w; int n = Integer.bitCount(part); if (n <= j) { part = (int) (w >>> 32); seen += 32; j -= n; } int ww = part; // Divide 32bit part = ww & 0xFFFF; n = Integer.bitCount(part); if (n <= j) { part = ww >>> 16; seen += 16; j -= n; } ww = part; // Divide 16bit part = ww & 0xFF; n = Integer.bitCount(part); if (n <= j) { part = ww >>> 8; seen += 8; j -= n; } ww = part; // Lookup in final byte int counter; for (counter = 0; counter < 8; counter++) { j -= (ww >>> counter) & 1; if (j < 0) { break; } } return seen + counter; } /** * set bits at start, start+1,..., end-1 * * @param bitmap array of words to be modified * @param start first index to be modified (inclusive) * @param end last index to be modified (exclusive) */ public static void setBitmapRange(long[] bitmap, int start, int end) { if (start == end) { return; } int firstword = start / 64; int endword = (end - 1) / 64; if (firstword == endword) { bitmap[firstword] |= (~0L << start) & (~0L >>> -end); return; } bitmap[firstword] |= ~0L << start; for (int i = firstword + 1; i < endword; i++) { bitmap[i] = ~0L; } bitmap[endword] |= ~0L >>> -end; } /** * set bits at start, start+1,..., end-1 and report the * cardinality change * * @param bitmap array of words to be modified * @param start first index to be modified (inclusive) * @param end last index to be modified (exclusive) * @return cardinality change */ @Deprecated public static int setBitmapRangeAndCardinalityChange(long[] bitmap, int start, int end) { int cardbefore = cardinalityInBitmapWordRange(bitmap, start, end); setBitmapRange(bitmap, start,end); int cardafter = cardinalityInBitmapWordRange(bitmap, start, end); return cardafter - cardbefore; } /** * flip bits at start, start+1,..., end-1 and report the * cardinality change * * @param bitmap array of words to be modified * @param start first index to be modified (inclusive) * @param end last index to be modified (exclusive) * @return cardinality change */ @Deprecated public static int flipBitmapRangeAndCardinalityChange(long[] bitmap, int start, int end) { int cardbefore = cardinalityInBitmapWordRange(bitmap, start, end); flipBitmapRange(bitmap, start,end); int cardafter = cardinalityInBitmapWordRange(bitmap, start, end); return cardafter - cardbefore; } /** * reset bits at start, start+1,..., end-1 and report the * cardinality change * * @param bitmap array of words to be modified * @param start first index to be modified (inclusive) * @param end last index to be modified (exclusive) * @return cardinality change */ @Deprecated public static int resetBitmapRangeAndCardinalityChange(long[] bitmap, int start, int end) { int cardbefore = cardinalityInBitmapWordRange(bitmap, start, end); resetBitmapRange(bitmap, start,end); int cardafter = cardinalityInBitmapWordRange(bitmap, start, end); return cardafter - cardbefore; } /** * Look for value k in array in the range [begin,end). If the value is found, return its index. If * not, return -(i+1) where i is the index where the value would be inserted. The array is assumed * to contain sorted values where shorts are interpreted as unsigned integers. * * @param array array where we search * @param begin first index (inclusive) * @param end last index (exclusive) * @param k value we search for * @return count */ public static int unsignedBinarySearch(final char[] array, final int begin, final int end, final char k) { if (USE_HYBRID_BINSEARCH) { return hybridUnsignedBinarySearch(array, begin, end, k); } else { return branchyUnsignedBinarySearch(array, begin, end, k); } } /** * Compute the difference between two sorted lists and write the result to the provided output * array * * @param set1 first array * @param length1 length of first array * @param set2 second array * @param length2 length of second array * @param buffer output array * @return cardinality of the difference */ public static int unsignedDifference(final char[] set1, final int length1, final char[] set2, final int length2, final char[] buffer) { int pos = 0; int k1 = 0, k2 = 0; if (0 == length2) { System.arraycopy(set1, 0, buffer, 0, length1); return length1; } if (0 == length1) { return 0; } char s1 = set1[k1]; char s2 = set2[k2]; while (true) { if (s1 < s2) { buffer[pos++] = s1; ++k1; if (k1 >= length1) { break; } s1 = set1[k1]; } else if (s1 == s2) { ++k1; ++k2; if (k1 >= length1) { break; } if (k2 >= length2) { System.arraycopy(set1, k1, buffer, pos, length1 - k1); return pos + length1 - k1; } s1 = set1[k1]; s2 = set2[k2]; } else {// if (val1>val2) ++k2; if (k2 >= length2) { System.arraycopy(set1, k1, buffer, pos, length1 - k1); return pos + length1 - k1; } s2 = set2[k2]; } } return pos; } /** * Compute the difference between two sorted lists and write the result to the provided output * array * * @param set1 first array * @param set2 second array * @param buffer output array * @return cardinality of the difference */ public static int unsignedDifference(CharIterator set1, CharIterator set2, final char[] buffer) { int pos = 0; if (!set2.hasNext()) { while (set1.hasNext()) { buffer[pos++] = set1.next(); } return pos; } if (!set1.hasNext()) { return 0; } char v1 = set1.next(); char v2 = set2.next(); while (true) { if ((v1) < (v2)) { buffer[pos++] = v1; if (!set1.hasNext()) { return pos; } v1 = set1.next(); } else if (v1 == v2) { if (!set1.hasNext()) { break; } if (!set2.hasNext()) { while (set1.hasNext()) { buffer[pos++] = set1.next(); } return pos; } v1 = set1.next(); v2 = set2.next(); } else {// if (val1>val2) if (!set2.hasNext()) { buffer[pos++] = v1; while (set1.hasNext()) { buffer[pos++] = set1.next(); } return pos; } v2 = set2.next(); } } return pos; } /** * Compute the exclusive union of two sorted lists and write the result to the provided output * array * * @param set1 first array * @param length1 length of first array * @param set2 second array * @param length2 length of second array * @param buffer output array * @return cardinality of the exclusive union */ public static int unsignedExclusiveUnion2by2(final char[] set1, final int length1, final char[] set2, final int length2, final char[] buffer) { int pos = 0; int k1 = 0, k2 = 0; if (0 == length2) { System.arraycopy(set1, 0, buffer, 0, length1); return length1; } if (0 == length1) { System.arraycopy(set2, 0, buffer, 0, length2); return length2; } char s1 = set1[k1]; char s2 = set2[k2]; while (true) { if (s1 < s2) { buffer[pos++] = s1; ++k1; if (k1 >= length1) { System.arraycopy(set2, k2, buffer, pos, length2 - k2); return pos + length2 - k2; } s1 = set1[k1]; } else if (s1 == s2) { ++k1; ++k2; if (k1 >= length1) { System.arraycopy(set2, k2, buffer, pos, length2 - k2); return pos + length2 - k2; } if (k2 >= length2) { System.arraycopy(set1, k1, buffer, pos, length1 - k1); return pos + length1 - k1; } s1 = set1[k1]; s2 = set2[k2]; } else {// if (val1>val2) buffer[pos++] = s2; ++k2; if (k2 >= length2) { System.arraycopy(set1, k1, buffer, pos, length1 - k1); return pos + length1 - k1; } s2 = set2[k2]; } } // return pos; } /** * Intersect two sorted lists and write the result to the provided output array * * @param set1 first array * @param length1 length of first array * @param set2 second array * @param length2 length of second array * @param buffer output array * @return cardinality of the intersection */ public static int unsignedIntersect2by2(final char[] set1, final int length1, final char[] set2, final int length2, final char[] buffer) { final int THRESHOLD = 25; if (set1.length * THRESHOLD < set2.length) { return unsignedOneSidedGallopingIntersect2by2(set1, length1, set2, length2, buffer); } else if (set2.length * THRESHOLD < set1.length) { return unsignedOneSidedGallopingIntersect2by2(set2, length2, set1, length1, buffer); } else { return unsignedLocalIntersect2by2(set1, length1, set2, length2, buffer); } } /** * Checks if two arrays intersect * * @param set1 first array * @param length1 length of first array * @param set2 second array * @param length2 length of second array * @return true if they intersect */ public static boolean unsignedIntersects(char[] set1, int length1, char[] set2, int length2) { // galloping might be faster, but we do not expect this function to be slow if ((0 == length1) || (0 == length2)) { return false; } int k1 = 0; int k2 = 0; char s1 = set1[k1]; char s2 = set2[k2]; mainwhile: while (true) { if (s2 < s1) { do { ++k2; if (k2 == length2) { break mainwhile; } s2 = set2[k2]; } while (s2 < s1); } if (s1 < s2) { do { ++k1; if (k1 == length1) { break mainwhile; } s1 = set1[k1]; } while (s1 < s2); } else { return true; } } return false; } protected static int unsignedLocalIntersect2by2(final char[] set1, final int length1, final char[] set2, final int length2, final char[] buffer) { if ((0 == length1) || (0 == length2)) { return 0; } int k1 = 0; int k2 = 0; int pos = 0; char s1 = set1[k1]; char s2 = set2[k2]; mainwhile: while (true) { int v1 = (s1); int v2 = s2; if (v2 < v1) { do { ++k2; if (k2 == length2) { break mainwhile; } s2 = set2[k2]; v2 = s2; } while (v2 < v1); } if (v1 < v2) { do { ++k1; if (k1 == length1) { break mainwhile; } s1 = set1[k1]; v1 = s1; } while (v1 < v2); } else { // (set2[k2] == set1[k1]) buffer[pos++] = s1; ++k1; if (k1 == length1) { break; } ++k2; if (k2 == length2) { break; } s1 = set1[k1]; s2 = set2[k2]; } } return pos; } /** * Compute the cardinality of the intersection * @param set1 first set * @param length1 how many values to consider in the first set * @param set2 second set * @param length2 how many values to consider in the second set * @return cardinality of the intersection */ public static int unsignedLocalIntersect2by2Cardinality(final char[] set1, final int length1, final char[] set2, final int length2) { if ((0 == length1) || (0 == length2)) { return 0; } int k1 = 0; int k2 = 0; int pos = 0; char s1 = set1[k1]; char s2 = set2[k2]; mainwhile: while (true) { int v1 = s1; int v2 = s2; if (v2 < v1) { do { ++k2; if (k2 == length2) { break mainwhile; } s2 = set2[k2]; v2 = s2; } while (v2 < v1); } if (v1 < v2) { do { ++k1; if (k1 == length1) { break mainwhile; } s1 = set1[k1]; v1 = s1; } while (v1 < v2); } else { // (set2[k2] == set1[k1]) pos++; ++k1; if (k1 == length1) { break; } ++k2; if (k2 == length2) { break; } s1 = set1[k1]; s2 = set2[k2]; } } return pos; } protected static int unsignedOneSidedGallopingIntersect2by2(final char[] smallSet, final int smallLength, final char[] largeSet, final int largeLength, final char[] buffer) { if (0 == smallLength) { return 0; } int k1 = 0; int k2 = 0; int pos = 0; char s1 = largeSet[k1]; char s2 = smallSet[k2]; while (true) { if (s1 < s2) { k1 = advanceUntil(largeSet, k1, largeLength, s2); if (k1 == largeLength) { break; } s1 = largeSet[k1]; } if (s2 < s1) { ++k2; if (k2 == smallLength) { break; } s2 = smallSet[k2]; } else { // (set2[k2] == set1[k1]) buffer[pos++] = s2; ++k2; if (k2 == smallLength) { break; } s2 = smallSet[k2]; k1 = advanceUntil(largeSet, k1, largeLength, s2); if (k1 == largeLength) { break; } s1 = largeSet[k1]; } } return pos; } /** * Unite two sorted lists and write the result to the provided output array * * @param set1 first array * @param offset1 offset of first array * @param length1 length of first array * @param set2 second array * @param offset2 offset of second array * @param length2 length of second array * @param buffer output array * @return cardinality of the union */ public static int unsignedUnion2by2( final char[] set1, final int offset1, final int length1, final char[] set2, final int offset2, final int length2, final char[] buffer) { if (0 == length2) { System.arraycopy(set1, offset1, buffer, 0, length1); return length1; } if (0 == length1) { System.arraycopy(set2, offset2, buffer, 0, length2); return length2; } int pos = 0; int k1 = offset1, k2 = offset2; char s1 = set1[k1]; char s2 = set2[k2]; while (true) { int v1 = s1; int v2 = s2; if (v1 < v2) { buffer[pos++] = s1; ++k1; if (k1 >= length1 + offset1) { System.arraycopy(set2, k2, buffer, pos, length2 - k2 + offset2); return pos + length2 - k2 + offset2; } s1 = set1[k1]; } else if (v1 == v2) { buffer[pos++] = s1; ++k1; ++k2; if (k1 >= length1 + offset1) { System.arraycopy(set2, k2, buffer, pos, length2 - k2 + offset2); return pos + length2 - k2 + offset2; } if (k2 >= length2 + offset2) { System.arraycopy(set1, k1, buffer, pos, length1 - k1 + offset1); return pos + length1 - k1 + offset1; } s1 = set1[k1]; s2 = set2[k2]; } else {// if (set1[k1]>set2[k2]) buffer[pos++] = s2; ++k2; if (k2 >= length2 + offset2) { System.arraycopy(set1, k1, buffer, pos, length1 - k1 + offset1); return pos + length1 - k1 + offset1; } s2 = set2[k2]; } } // return pos; } /** * Converts the argument to a {@code long} by an unsigned conversion. In an unsigned conversion to * a {@code long}, the high-order 32 bits of the {@code long} are zero and the low-order 32 bits * are equal to the bits of the integer argument. * * Consequently, zero and positive {@code int} values are mapped to a numerically equal * {@code long} value and negative {@code * int} values are mapped to a {@code long} value equal to the input plus 2<sup>32</sup>. * * @param x the value to convert to an unsigned {@code long} * @return the argument converted to {@code long} by an unsigned conversion * @since 1.8 */ // Duplicated from jdk8 Integer.toUnsignedLong public static long toUnsignedLong(int x) { return ((long) x) & 0xffffffffL; } /** * Sorts the data by the 16 bit prefix using Radix sort. * The resulting data will be partially sorted if you just * take into account the most significant 16 bits. The least * significant 16 bits are unsorted. Note that we treat int values * as unsigned integers (from 0 to 2^32). * @param data - the data (sorted in place) */ public static void partialRadixSort(int[] data) { final int radix = 8; int shift = 16; int mask = 0xFF0000; int[] copy = new int[data.length]; int[] histogram = new int[(1 << radix) + 1]; // We want to avoid copying the data, see int[] primary = data; int[] secondary = copy; while (shift < 32) { for (int i = 0; i < data.length; ++i) { ++histogram[((primary[i] & mask) >>> shift) + 1]; } for (int i = 0; i < 1 << radix; ++i) { histogram[i + 1] += histogram[i]; } for (int i = 0; i < primary.length; ++i) { secondary[histogram[(primary[i] & mask) >>> shift]++] = primary[i]; } // swap int[] tmp = primary; primary = secondary; secondary = tmp; shift += radix; mask <<= radix; Arrays.fill(histogram, 0); } // We need to check that primary == data. // The check is entirely deterministic in this case. // We go: // shift = 16 // data == primary // shift = 24 // data == secondary // // exit: // data == primary // If unsure, we could do the following: // if(data != primary) { // System.arraycopy(secondary, 0, data, 0, data.length); } /** * Private constructor to prevent instantiation of utility class */ private Util() { } }
package edu.wustl.query.bizlogic; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.naming.InitialContext; import javax.sql.DataSource; import org.hibernate.HibernateException; import org.hibernate.Session; import edu.common.dynamicextensions.domain.DomainObjectFactory; import edu.common.dynamicextensions.domain.Entity; import edu.common.dynamicextensions.domain.userinterface.Container; import edu.common.dynamicextensions.domaininterface.AssociationInterface; import edu.common.dynamicextensions.domaininterface.AttributeInterface; import edu.common.dynamicextensions.domaininterface.EntityInterface; import edu.common.dynamicextensions.domaininterface.RoleInterface; import edu.common.dynamicextensions.domaininterface.databaseproperties.ConstraintPropertiesInterface; import edu.common.dynamicextensions.entitymanager.EntityManager; import edu.common.dynamicextensions.entitymanager.EntityManagerInterface; import edu.common.dynamicextensions.exception.DynamicExtensionsApplicationException; import edu.common.dynamicextensions.exception.DynamicExtensionsSystemException; import edu.common.dynamicextensions.util.global.Constants.AssociationDirection; import edu.common.dynamicextensions.util.global.Constants.AssociationType; import edu.common.dynamicextensions.util.global.Constants.Cardinality; import edu.wustl.cab2b.server.path.PathConstants; import edu.wustl.cab2b.server.path.PathFinder; import edu.wustl.common.exception.BizLogicException; import edu.wustl.common.util.dbManager.DBUtil; import edu.wustl.common.util.logger.Logger; import edu.wustl.query.annotations.xmi.PathObject; /** * @author vishvesh_mulay * */ public class AnnotationUtil { /** * @param staticEntityId * @param dynamicEntityId * @return * @throws DynamicExtensionsSystemException * @throws DynamicExtensionsApplicationException * @throws DynamicExtensionsSystemException * @throws BizLogicException */ public static synchronized Long addAssociation(Long staticEntityId, Long dynamicEntityId, boolean isEntityFromXmi) throws //DynamicExtensionsSystemException, DynamicExtensionsApplicationException, DynamicExtensionsSystemException, BizLogicException { // // Get instance of static entity from entity cache maintained by caB2B code // EntityInterface staticEntity = EntityCacheFactory.getInstance() // .getEntityById(staticEntityId); // //Get dynamic Entity from entity Manger // EntityInterface dynamicEntity = (entityManager // .getContainerByIdentifier(dynamicEntityId.toString())) // .getEntity(); //This change is done because when the hierarchy of objects grow in dynamic extensions then NonUniqueObjectException is thrown. //So static entity and dynamic entity are brought in one session and then associated. Session session = null; try { session = DBUtil.currentSession(); } catch (HibernateException e1) { // TODO Auto-generated catch block Logger.out.debug(e1.getMessage(),e1); throw new BizLogicException("", e1); } AssociationInterface association = null; EntityInterface staticEntity = null; EntityInterface dynamicEntity = null; try { staticEntity = (EntityInterface) session.load(Entity.class, staticEntityId); dynamicEntity = (EntityInterface) ((Container) session.load(Container.class, dynamicEntityId)).getAbstractEntity(); // Get entitygroup that is used by caB2B for path finder purpose. // Commented this line since performance issue for Bug 6433 //EntityGroupInterface entityGroupInterface = Utility.getEntityGroup(staticEntity); //List<EntityInterface> processedEntityList = new ArrayList<EntityInterface>(); //addCatissueGroup(dynamicEntity, entityGroupInterface,processedEntityList); //Create source role and target role for the association String roleName = staticEntityId.toString().concat("_").concat( dynamicEntityId.toString()); RoleInterface sourceRole = getRole(AssociationType.CONTAINTMENT, roleName, Cardinality.ZERO, Cardinality.ONE); RoleInterface targetRole = getRole(AssociationType.CONTAINTMENT, roleName, Cardinality.ZERO, Cardinality.MANY); //Create association with the created source and target roles. association = getAssociation(dynamicEntity, AssociationDirection.SRC_DESTINATION, roleName, sourceRole, targetRole); //Create constraint properties for the created association. ConstraintPropertiesInterface constraintProperties = getConstraintProperties( staticEntity, dynamicEntity); association.setConstraintProperties(constraintProperties); //Add association to the static entity and save it. staticEntity.addAssociation(association); Long start = Long.valueOf(System.currentTimeMillis()); staticEntity = EntityManager.getInstance().persistEntityMetadataForAnnotation( staticEntity, true, false, association); Long end = Long.valueOf(System.currentTimeMillis()); Logger.out.info("Time required to persist one entity is " + (end - start) / 1000 + "seconds"); //Add the column related to the association to the entity table of the associated entities. EntityManager.getInstance().addAssociationColumn(association); // Collection<AssociationInterface> staticEntityAssociation = staticEntity // .getAssociationCollection(); // for (AssociationInterface tempAssociation : staticEntityAssociation) // if (tempAssociation.getName().equals(association.getName())) // association = tempAssociation; // break; Set<PathObject> processedPathList = new HashSet<PathObject>(); addQueryPathsForAllAssociatedEntities(dynamicEntity, staticEntity, association, staticEntity.getId(), processedPathList); addEntitiesToCache(isEntityFromXmi, dynamicEntity, staticEntity); } catch (HibernateException e1) { // TODO Auto-generated catch block Logger.out.debug(e1.getMessages(),e1); throw new BizLogicException("", e1); } finally { try { DBUtil.closeSession(); } catch (HibernateException e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); throw new BizLogicException("", e); } } return association.getId(); } /** * @param dynamicEntity * @param staticEntity */ /* *Commented out by Baljeet */ /*public static void addCatissueGroup(EntityInterface dynamicEntity, EntityGroupInterface entityGroupInterface,List<EntityInterface> processedEntityList) { if (processedEntityList.contains(dynamicEntity)) { return; } else { processedEntityList.add(dynamicEntity); } //Add the entity group to the dynamic entity and all it's associated entities. if (!checkBaseEntityGroup(dynamicEntity.getEntityGroup())) { dynamicEntity.setEntityGroup(entityGroupInterface); } Collection<AssociationInterface> associationCollection = dynamicEntity .getAssociationCollection(); for (AssociationInterface associationInteface : associationCollection) { addCatissueGroup(associationInteface.getTargetEntity(), entityGroupInterface, processedEntityList); //associationInteface.getTargetEntity().addEntityGroupInterface(entityGroupInterface); } }*/ /** * @param entityGroupColl * @return */ /* * Commented out By Baljeet */ /*public static boolean checkBaseEntityGroup(EntityGroupInterface entityGroup) { if (entityGroup.getId().intValue() == Constants.CATISSUE_ENTITY_GROUP) { return true; } return false; }*/ /** * @param dynamicEntity * @param staticEntity * @param associationId * @param isEntityFromXmi * @throws BizLogicException */ public static void addQueryPathsForAllAssociatedEntities(EntityInterface dynamicEntity, EntityInterface staticEntity, AssociationInterface association, Long staticEntityId, Set<PathObject> processedPathList) throws BizLogicException { if (staticEntity != null) { PathObject pathObject = new PathObject(); pathObject.setSourceEntity(staticEntity); pathObject.setTargetEntity(dynamicEntity); pathObject.setAssociation(association); if (processedPathList.contains(pathObject)) { return; } else { processedPathList.add(pathObject); } AnnotationUtil.addPathsForQuery(staticEntity.getId(), dynamicEntity.getId(), staticEntityId, association.getId()); } Collection<AssociationInterface> associationCollection = dynamicEntity .getAssociationCollection(); for (AssociationInterface associationInteface : associationCollection) { addQueryPathsForAllAssociatedEntities(associationInteface.getTargetEntity(), dynamicEntity, associationInteface, staticEntityId, processedPathList); // AnnotationUtil.addPathsForQuery(dynamicEntity.getId(), associationInteface // .getTargetEntity().getId(), associationInteface.getId()); } } /** * @param isEntityFromXmi * @param dynamicEntity * @param staticEntity * @throws BizLogicException */ public static void addEntitiesToCache(boolean isEntityFromXmi, EntityInterface dynamicEntity, EntityInterface staticEntity) throws BizLogicException { if (!isEntityFromXmi) { Connection conn = null; try { InitialContext ctx = new InitialContext(); String DATASOURCE_JNDI_NAME = "java:/catissuecore"; DataSource dataSource = (DataSource) ctx.lookup(DATASOURCE_JNDI_NAME); conn = dataSource.getConnection(); PathFinder.getInstance().refreshCache(conn, true); } catch (Exception e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); } finally { try { if (conn != null) { conn.close(); } } catch (HibernateException e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); } catch (SQLException e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); } } } } /** * @param staticEntity * @param dynamicEntity * @return */ private static ConstraintPropertiesInterface getConstraintProperties( EntityInterface staticEntity, EntityInterface dynamicEntity) { DomainObjectFactory factory =DomainObjectFactory.getInstance(); ConstraintPropertiesInterface constrProp = factory.createConstraintProperties(); constrProp.setName(dynamicEntity.getTableProperties().getName()); for(AttributeInterface primaryAttribute : staticEntity.getPrimaryKeyAttributeCollection()) { constrProp.getTgtEntityConstraintKeyProperties().getTgtForiegnKeyColumnProperties().setName("DYEXTN_AS_" + staticEntity.getId().toString() + "_" + dynamicEntity.getId().toString()); constrProp.getTgtEntityConstraintKeyProperties().setSrcPrimaryKeyAttribute(primaryAttribute); constrProp.getSrcEntityConstraintKeyPropertiesCollection().clear(); } return constrProp; } /** * @param targetEntity * @param associationDirection * @param assoName * @param sourceRole * @param targetRole * @return * @throws DynamicExtensionsSystemException */ private static AssociationInterface getAssociation(EntityInterface targetEntity, AssociationDirection associationDirection, String assoName, RoleInterface sourceRole, RoleInterface targetRole) throws DynamicExtensionsSystemException { AssociationInterface association = DomainObjectFactory.getInstance().createAssociation(); association.setTargetEntity(targetEntity); association.setAssociationDirection(associationDirection); association.setName(assoName); association.setSourceRole(sourceRole); association.setTargetRole(targetRole); return association; } /** * @param associationType associationType * @param name name * @param minCard minCard * @param maxCard maxCard * @return RoleInterface */ private static RoleInterface getRole(AssociationType associationType, String name, Cardinality minCard, Cardinality maxCard) { RoleInterface role = DomainObjectFactory.getInstance().createRole(); role.setAssociationsType(associationType); role.setName(name); role.setMinimumCardinality(minCard); role.setMaximumCardinality(maxCard); return role; } /** * @param staticEntityId * @param dynamicEntityId * @param deAssociationID */ public static void addPathsForQuery(Long staticEntityId, Long dynamicEntityId, Long hookEntityId, Long deAssociationID) { Long maxPathId = getMaxId("path_id", "path"); maxPathId += 1; insertNewPaths(maxPathId, staticEntityId, dynamicEntityId, deAssociationID); if (hookEntityId != null && staticEntityId != hookEntityId) { maxPathId += 1; addPathFromStaticEntity(maxPathId, hookEntityId, staticEntityId, dynamicEntityId, deAssociationID); } } /** * * @param hookEntityId */ private static void addPathFromStaticEntity(Long maxPathId, Long hookEntityId, Long previousDynamicEntity, Long dynamicEntityId, Long deAssociationId) { ResultSet resultSet = null; PreparedStatement statement = null; String query = ""; Connection conn = null; try { conn = DBUtil.getConnection(); query = "select ASSOCIATION_ID from INTRA_MODEL_ASSOCIATION where DE_ASSOCIATION_ID=" + deAssociationId; statement = conn.prepareStatement(query); resultSet = statement.executeQuery(); resultSet.next(); Long intraModelAssociationId = resultSet.getLong(1); query = "select INTERMEDIATE_PATH from path where FIRST_ENTITY_ID=" + hookEntityId + " and LAST_ENTITY_ID=" + previousDynamicEntity; statement = conn.prepareStatement(query); resultSet = statement.executeQuery(); resultSet.next(); String path = resultSet.getString(1); path = path.concat("_").concat(intraModelAssociationId.toString()); query = "insert into path (PATH_ID, FIRST_ENTITY_ID,INTERMEDIATE_PATH, LAST_ENTITY_ID) values (?,?,?,?)"; statement = conn.prepareStatement(query); statement.setLong(1, maxPathId); statement.setLong(2, hookEntityId); statement.setString(3, path); statement.setLong(4, dynamicEntityId); statement.execute(); conn.commit(); } catch (SQLException e) { Logger.out.debug(e.getMessage(),e); } finally { try { resultSet.close(); statement.close(); DBUtil.closeConnection(); } catch (SQLException e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); } } } /** * @param maxPathId * @param staticEntityId * @param dynamicEntityId * @param deAssociationID */ private static void insertNewPaths(Long maxPathId, Long staticEntityId, Long dynamicEntityId, Long deAssociationID) { // StringBuffer query = new StringBuffer(); Long intraModelAssociationId = getMaxId("ASSOCIATION_ID", "ASSOCIATION"); intraModelAssociationId += 1; Connection conn = null; try { conn = DBUtil.getConnection(); String associationQuery = "insert into ASSOCIATION (ASSOCIATION_ID, ASSOCIATION_TYPE) values (" + intraModelAssociationId + "," + PathConstants.AssociationType.INTRA_MODEL_ASSOCIATION.getValue() + ")"; String intraModelQuery = "insert into INTRA_MODEL_ASSOCIATION (ASSOCIATION_ID, DE_ASSOCIATION_ID) values (" + intraModelAssociationId + "," + deAssociationID + ")"; String directPathQuery = "insert into PATH (PATH_ID, FIRST_ENTITY_ID,INTERMEDIATE_PATH, LAST_ENTITY_ID) values (" + maxPathId + "," + staticEntityId + ",'" + intraModelAssociationId + "'," + dynamicEntityId + ")"; List<String> list = new ArrayList<String>(); list.add(associationQuery); list.add(intraModelQuery); list.add(directPathQuery); executeQuery(conn, list); //addIndirectPaths(maxPathId, staticEntityId, dynamicEntityId, intraModelAssociationId, //conn); conn.commit(); } catch (Exception e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); } finally { try { DBUtil.closeConnection(); } catch (HibernateException e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); } } } /** * @param maxPathId * @param staticEntityId * @param dynamicEntityId * @param intraModelAssociationId * @param conn * @throws SQLException */ /* private static void addIndirectPaths(Long maxPathId, Long staticEntityId, Long dynamicEntityId, Long intraModelAssociationId, Connection conn) { ResultSet resultSet = null; PreparedStatement statement = null; String query = ""; try { //resultSet = getIndirectPaths(conn, staticEntityId); query = "select FIRST_ENTITY_ID,INTERMEDIATE_PATH from path where LAST_ENTITY_ID=" + staticEntityId; statement = conn.prepareStatement(query); resultSet = statement.executeQuery(); query = "insert into path (PATH_ID, FIRST_ENTITY_ID,INTERMEDIATE_PATH, LAST_ENTITY_ID) values (?,?,?,?)"; statement = conn.prepareStatement(query); while (resultSet.next()) { Long firstEntityId = resultSet.getLong(1); String path = resultSet.getString(2); path = path.concat("_").concat(intraModelAssociationId.toString()); statement.setLong(1, maxPathId); maxPathId++; statement.setLong(2, firstEntityId); statement.setString(3, path); statement.setLong(4, dynamicEntityId); statement.execute(); statement.clearParameters(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { resultSet.close(); statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } */ // /** // * @param conn // * @param staticEntityId // * @return // * @throws SQLException // */ // private static ResultSet getIndirectPaths(Connection conn, Long staticEntityId) // String query = "select FIRST_ENTITY_ID,INTERMEDIATE_PATH from path where LAST_ENTITY_ID=" // + staticEntityId; // java.sql.PreparedStatement statement = null; // ResultSet resultSet = null; // try // statement = conn.prepareStatement(query); // resultSet = statement.executeQuery(); // catch (SQLException e) // // TODO Auto-generated catch block // e.printStackTrace(); // finally // try // statement.close(); // catch (SQLException e) // // TODO Auto-generated catch block // e.printStackTrace(); // return resultSet; /** * @param conn * @param queryList * @throws SQLException */ private static void executeQuery(Connection conn, List<String> queryList) { Statement statement = null; try { statement = conn.createStatement(); for (String query : queryList) { statement.execute(query); } } catch (SQLException e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); } finally { try { statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); } } } /** * @param columnName * @param tableName * @return */ private static Long getMaxId(String columnName, String tableName) { String query = "select max(" + columnName + ") from " + tableName; // HibernateDAO hibernateDAO = (HibernateDAO) DAOFactory.getInstance().getDAO( // Constants.HIBERNATE_DAO); java.sql.PreparedStatement statement = null; ResultSet resultSet = null; Connection conn = null; try { conn = DBUtil.getConnection(); statement = conn.prepareStatement(query); resultSet = statement.executeQuery(); resultSet.next(); Long maxId = resultSet.getLong(1); return maxId; } catch (Exception e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); } finally { try { resultSet.close(); statement.close(); DBUtil.closeConnection(); } catch (HibernateException e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); } catch (SQLException e) { // TODO Auto-generated catch block Logger.out.debug(e.getMessage(),e); } } return null; } /** * @param entity_name_participant * @return * @throws DynamicExtensionsApplicationException * @throws DynamicExtensionsSystemException */ public static Long getEntityId(String entityName) throws DynamicExtensionsSystemException, DynamicExtensionsApplicationException { if (entityName != null) { EntityManagerInterface entityManager = EntityManager.getInstance(); EntityInterface entity; entity = entityManager.getEntityByName(entityName); if (entity != null) { return entity.getId(); } } return Long.valueOf(0); } }
package com.civica.grads.exercise3.model.draughts; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import com.civica.grads.exercise3.interfaces.Describable; import com.civica.grads.exercise3.interfaces.DeterminesNextMove; import com.civica.grads.exercise3.model.player.Player; public class Game implements Describable,DeterminesNextMove { final private Board board ; private static int startingPlayerCounters ; private Player[] player ; final private ArrayList<Move> moves = new ArrayList<Move>() ; /** * This operation updates the board with the data from the moves; */ private void updateBoard() { throw new RuntimeException("This code is missing"); //TODO } public int getNumberOfMoves() { return moves.size(); } public boolean hasMoves() { return moves.isEmpty(); } public boolean addMove(Move e) { return moves.add(e); } public void clearMoves() { moves.clear(); } public Game(int size, Player[] player) { try { checkBoardSizeValue(size) ; } catch (IllegalArgumentException e) { e.printStackTrace(); System.exit(-1); } this.board = new Board(size) ; this.player = player ; } private static void checkBoardSizeValue(int size) throws IllegalArgumentException { if (size < 8 || size > 12 || (size % 2) == 1) { throw new IllegalArgumentException("Board size is incorrect.") ; } else { startingPlayerCounters = (size - 2)*(size/2) ; } } public Board getBoard() { return board; } public int getStartingPlayerCounters() { return startingPlayerCounters; } public Player[] getPlayer() { return player; } public ArrayList<Move> getMoves() { return moves; } @Override public void describe(OutputStream out) throws IOException { out.write(this.toString().getBytes()) ; } @Override public String toString() { return "Game [board=" + board + ", startingPlayerCounters=" + startingPlayerCounters + ", player=" + Arrays.toString(player) + ", moves=" + moves + "]"; } @Override public Move evaluate(Board board) { // TODO Auto-generated method stub return null; } }
package com.project.bookshelf.test; import com.project.bookshelf.model.Book; import junit.framework.TestCase; /** * @author Clay * */ public class BookTest extends TestCase { /** * @param name */ public BookTest(String name) { super(name); } /* (non-Javadoc) * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); } /* (non-Javadoc) * @see junit.framework.TestCase#tearDown() */ protected void tearDown() throws Exception { super.tearDown(); } /** * Test method for {@link com.project.bookshelf.model.Book#Book()}. */ public void testBookShouldContructWhenEmpty() { Book book = new Book(); assertNotNull("an empty Book should be able to be constructed", book); } /** * Test method for {@link com.project.bookshelf.model.Book#Book(long, java.lang.String, java.lang.String, java.lang.String)}. */ public void testBookShouldConstructWithId() { long id = 1; String fileName = "file"; String title = "title"; String author = "author"; Book book = new Book(id,fileName,title,author); assertNotNull("a Book should be able to be constructed with an id"); assertTrue("A book constructed with id should set it properly",book.getId() == id); assertEquals("A book constructed with fileName should set it properly", book.getFileName(), fileName); assertEquals("A book constructed with title should set it properly", book.getTitle(), title); assertEquals("A book constructed with author should set it properly", book.getAuthor(),author); assertTrue("A book should be constructed with the default bookmark value of -1", book.getBookmark() == -1); } /** * Test method for {@link com.project.bookshelf.model.Book#Book(java.lang.String, java.lang.String, java.lang.String)}. */ public void testBookShouldConstructWithoutId() { String fileName = "file"; String title = "title"; String author = "author"; Book book = new Book(fileName,title,author); assertNotNull("a Book should be able to be constructed without an id"); assertEquals("A book constructed with fileName should set it properly", book.getFileName(), fileName); assertEquals("A book constructed with title should set it properly", book.getTitle(), title); assertEquals("A book constructed with author should set it properly", book.getAuthor(),author); assertTrue("A book should be constructed with the default bookmark value of -1", book.getBookmark() == -1); } }
package cafe.image.meta.adobe; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Collection; import java.util.List; import java.util.Map; import cafe.image.meta.iptc.IPTC; import cafe.image.meta.iptc.IPTCDataSet; public class IPTC_NAA extends _8BIM { private IPTC iptc; public IPTC_NAA() { this("IPTC_NAA"); } public IPTC_NAA(String name) { super(ImageResourceID.IPTC_NAA, name, null); iptc = new IPTC(); } public IPTC_NAA(String name, byte[] data) { super(ImageResourceID.IPTC_NAA, name, data); iptc = new IPTC(data); } public void addDataSet(IPTCDataSet dataSet) { iptc.addDataSet(dataSet); } public void addDataSets(Collection<? extends IPTCDataSet> dataSets) { iptc.addDataSets(dataSets); } /** * Get all the IPTCDataSet as a map for this IPTC data * * @return a map with the key for the IPTCDataSet name and a list of IPTCDataSet as the value */ public Map<String, List<IPTCDataSet>> getDataSets() { return iptc.getDataSets(); } /** * Get a list of IPTCDataSet associated with a key * * @param key name of the data set * @return a list of IPTCDataSet associated with the key */ public List<IPTCDataSet> getDataSet(String key) { return iptc.getDataSet(key); } public void print() { super.print(); // Print multiple entry IPTCDataSet for(List<IPTCDataSet> datasets : iptc.getDataSets().values()) for(IPTCDataSet dataset : datasets) dataset.print(); } public void write(OutputStream os) throws IOException { if(data == null) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); iptc.write(bout); data = bout.toByteArray(); size = data.length; } super.write(os); } }
package com.planb.restful.school; import java.sql.ResultSet; import java.sql.SQLException; import org.json.JSONArray; import org.json.JSONObject; import com.planb.support.routing.Route; import com.planb.support.utilities.MySQL; import io.vertx.core.Handler; import io.vertx.core.http.HttpMethod; import io.vertx.ext.web.RoutingContext; @Route(uri = "/meal", method = HttpMethod.GET) public class Meal implements Handler<RoutingContext> { @Override public void handle(RoutingContext ctx) { String date = ctx.request().getParam("date"); ResultSet rs = MySQL.executeQuery("SELECT * FROM meal WHERE date=?", date); try { if(rs.next()) { JSONObject resp = new JSONObject(); resp.put("breakfast", new JSONArray(rs.getString("breakfast"))); resp.put("lunch", new JSONArray(rs.getString("lunch"))); resp.put("dinner", new JSONArray(rs.getString("dinner"))); ctx.response().setStatusCode(200).end(resp.toString()); ctx.response().close(); } else { ctx.response().setStatusCode(204).end(); ctx.response().close(); } } catch (SQLException e) { e.printStackTrace(); } } }
package net.hawkengine.services; import net.hawkengine.db.DbRepositoryFactory; import net.hawkengine.db.IDbRepository; import net.hawkengine.model.*; import net.hawkengine.model.enums.JobStatus; import net.hawkengine.model.enums.NotificationType; import net.hawkengine.model.enums.StageStatus; import net.hawkengine.model.payload.WorkInfo; import net.hawkengine.services.interfaces.IAgentService; import net.hawkengine.services.interfaces.IJobService; import net.hawkengine.services.interfaces.IPipelineService; import net.hawkengine.ws.EndpointConnector; import java.util.List; import java.util.stream.Collectors; public class AgentService extends CrudService<Agent> implements IAgentService { private static final Class CLASS_TYPE = Agent.class; private IPipelineService pipelineService; private IJobService jobService; public AgentService() { IDbRepository repository = DbRepositoryFactory.create(DATABASE_TYPE, CLASS_TYPE); super.setRepository(repository); super.setObjectType(CLASS_TYPE.getSimpleName()); this.pipelineService = new PipelineService(); this.jobService = new JobService(); } public AgentService(IDbRepository repository, IPipelineService pipelineService) { super.setRepository(repository); super.setObjectType(CLASS_TYPE.getSimpleName()); this.pipelineService = pipelineService; } @Override public ServiceResult getById(String agentId) { return super.getById(agentId); } @Override public ServiceResult getAll() { return super.getAll(); } @Override public ServiceResult add(Agent agent) { ServiceResult result = super.add(agent); EndpointConnector.passResultToEndpoint(AgentService.class.getSimpleName(), "add", result); return result; } @Override public ServiceResult update(Agent agent) { ServiceResult result = super.update(agent); EndpointConnector.passResultToEndpoint(AgentService.class.getSimpleName(), "update", result); return result; } @Override public ServiceResult delete(String agentId) { return super.delete(agentId); } @Override public ServiceResult getAllAssignableAgents() { List<Agent> agents = (List<Agent>) super.getAll().getObject(); List<Agent> assignableAgents = agents .stream() .filter(a -> a.isConnected() && a.isEnabled() && !a.isRunning() && !a.isAssigned()) .collect(Collectors.toList()); ServiceResult result = super.createServiceResultArray(assignableAgents, NotificationType.SUCCESS, "retrieved successfully"); return result; } public ServiceResult getWorkInfo(String agentId) { ServiceResult result = null; Agent agent = (Agent) this.getById(agentId).getObject(); if (agent == null) { result = createResult(null, NotificationType.ERROR, "This agent has no job assigned."); } else if (agent.isAssigned()) { List<Pipeline> pipelines = (List<Pipeline>) this.pipelineService.getAllPreparedPipelinesInProgress().getObject(); for (Pipeline pipeline : pipelines) { WorkInfo workInfo = new WorkInfo(); Stage stageInProgress = pipeline.getStages() .stream() .filter(s -> s.getStatus() == StageStatus.IN_PROGRESS) .findFirst() .orElse(null); if (stageInProgress == null) { continue; } Job scheduledJob = stageInProgress .getJobs() .stream() .filter(j -> j.getStatus() == JobStatus.ASSIGNED) .filter(j -> j.getAssignedAgentId().equals(agentId)) .findFirst() .orElse(null); if (scheduledJob == null) { continue; } workInfo.setPipelineDefinitionName(pipeline.getPipelineDefinitionName()); workInfo.setPipelineExecutionID(pipeline.getExecutionId()); workInfo.setStageDefinitionName(stageInProgress.getStageDefinitionName()); workInfo.setStageExecutionID(stageInProgress.getExecutionId()); workInfo.setJobDefinitionName(scheduledJob.getJobDefinitionName()); scheduledJob.setStatus(JobStatus.RUNNING); workInfo.setJob(scheduledJob); this.jobService.update(scheduledJob); result = createResult(workInfo, NotificationType.SUCCESS, "WorkInfo retrieved successfully"); } } if (result == null) { agent.setAssigned(false); this.update(agent); result = createResult(null, NotificationType.ERROR, "This agent has no job assigned."); } return result; } private ServiceResult createResult(Object object, NotificationType notificationType, String message) { ServiceResult result = new ServiceResult(object, notificationType, message); return result; } }
package cellsociety_team08; import java.util.ArrayList; import java.util.List; import java.util.Map; import javafx.scene.paint.Color; public class Segregation extends RuleSet { private static final String SEGREGATION = "Segregation"; private static final String MIN_SAT_A = "minSatA"; private static final String MIN_SAT_B = "minSatB"; private static double myMinSatA, myMinSatB; /* * States accessed by this class will have the a parameter for isSatisfied * which will be a boolean value */ private static final State[] possibleStates = new State[] { new State("Agent A", 0, Color.BLUE, null), // index 0 new State("Agent B", 1, Color.RED, null) // index 1 }; public Segregation(Map<String, Object> params) { super(params); myMinSatA = (double) myParams.get(MIN_SAT_A); myMinSatB = (double) myParams.get(MIN_SAT_B); } @Override public Patch getNext(Patch patch, List<Patch> neighborhood) { // If the current cell is satisfied with its neighbors, return its // current state! if (isSatisfied(patch) || patch.flagged) return patch; double currSat = getSatisfaction(patch, neighborhood); if ((patch.myCell.getState().myIndex == 0 && currSat >= myMinSatA) || (patch.myCell.getState().myIndex == 1 && currSat >= myMinSatB)) { return satisfiedPatch(patch); } else { move(patch, neighborhood); return notSatisfiedPatch(patch); } } /*public List<Patch> getAvaliableNeighbors(List<Patch> neighborhood) { List<Patch> availableNeighbors = new ArrayList<Patch>(); for (Patch patch: neighborhood) { if (patch.isEmpty) { availableNeighbors.add(patch); } } return availableNeighbors; }*/ public void move(Patch patch, List<Patch> neighborhood) { if (neighborhood.size() > 0) { int patchesLeft = 1; for(Patch p: neighborhood) { if (p.isEmpty && !patch.flagged) { if (patchesLeft == 1) { //only move once p.myCell = patch.myCell; patch.clear(); p.flagged = true; patchesLeft } } } } } private double getSatisfaction(Patch patch, List<Patch> neighborhood) { double newSat = 0; double total = 0; for (Patch p : neighborhood) { if (p.containsCell()) { if (p.myCell.getState().equals(patch.myCell.getState())) { newSat++; } total++; } } newSat = newSat / total; return newSat; } private Patch satisfiedPatch(Patch p) { State s = p.myCell.getState(); s.setParams(new Object[] { true }); p.myCell.setState(s); return p; } private Patch notSatisfiedPatch(Patch p) { State s = p.myCell.getState(); s.setParams(new Object[] { false }); p.myCell.setState(s); return p; } private boolean isSatisfied(Patch p) { return (boolean) p.myCell.getState().getParams()[0]; } public int[] getNewLocation(Cell c) { /* * Not sure how to implement this yet. May have to work with Justin to * do this */ return null; } }
package cgeo.geocaching; import android.os.Handler; import android.util.Log; public class cgSearchThread extends Thread { private Handler recaptchaHandler = null; private String recaptchaChallenge = null; private String recaptchaText = null; public void setRecaptchaHandler(Handler recaptchaHandlerIn) { recaptchaHandler = recaptchaHandlerIn; } public void notifyNeed() { if (recaptchaHandler != null) { recaptchaHandler.sendEmptyMessage(1); } } public synchronized void waitForUser() { try { wait(); } catch (InterruptedException e) { Log.w(cgSettings.tag, "searchThread is not waiting for user..."); } } public void setChallenge(String challenge) { recaptchaChallenge = challenge; } public String getChallenge() { return recaptchaChallenge; } public synchronized void setText(String text) { recaptchaText = text; notify(); } public synchronized String getText() { return recaptchaText; } }
package com.github.yuukis.businessmap.app; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import com.github.yuukis.businessmap.R; import com.github.yuukis.businessmap.model.ContactsGroup; import com.github.yuukis.businessmap.model.ContactsItem; import com.github.yuukis.businessmap.utils.CursorJoinerWithIntKey; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.os.Handler; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Groups; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.CommonDataKinds.StructuredPostal; import android.app.ActionBar; import android.app.Activity; import android.app.FragmentManager; import android.database.Cursor; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.ArrayAdapter; public class MainActivity extends Activity implements ActionBar.OnNavigationListener { private static final int PROGRESS_MAX = 10000; private List<ContactsGroup> mGroupList; private List<ContactsItem> mContactsList; private ContactsListFragment mListFragment; private GoogleMap mMap; private Handler mHandler = new Handler(); private GeocodingThread mThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_PROGRESS); setContentView(R.layout.activity_main); setProgressBarVisibility(false); FragmentManager fm = getFragmentManager(); mListFragment = (ContactsListFragment) fm .findFragmentById(R.id.contacts_list); mMap = ((MapFragment) fm.findFragmentById(R.id.map)).getMap(); mGroupList = getContactsGroupList(); mContactsList = new ArrayList<ContactsItem>(); loadAllContacts(); ArrayAdapter<ContactsGroup> adapter = new ArrayAdapter<ContactsGroup>( this, android.R.layout.simple_spinner_dropdown_item, mGroupList); ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); actionBar.setListNavigationCallbacks(adapter, this); } @Override protected void onDestroy() { if (mThread != null) { mThread.halt(); } super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.action_contacts: View listContainer = findViewById(R.id.list_container); if (listContainer.getVisibility() == View.VISIBLE) { listContainer.setVisibility(View.INVISIBLE); item.setIcon(R.drawable.ic_action_list); } else { listContainer.setVisibility(View.VISIBLE); item.setIcon(R.drawable.ic_action_list_on); } return true; } return false; } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { if (mGroupList.size() <= itemPosition) { return false; } ContactsGroup group = mGroupList.get(itemPosition); // TODO: //loadContactsByGroupId(group.getId()); return true; } public List<ContactsItem> getContactsList() { return mContactsList; } public List<ContactsGroup> getContactsGroupList() { Cursor groupCursor = getContentResolver().query( Groups.CONTENT_URI, new String[] { Groups._ID, Groups.TITLE, Groups.ACCOUNT_NAME }, Groups.DELETED + "=0", null, null); List<ContactsGroup> list = new ArrayList<ContactsGroup>(); while (groupCursor.moveToNext()) { long _id = groupCursor.getLong(0); String title = groupCursor.getString(1); String accountName = groupCursor.getString(2); ContactsGroup group = new ContactsGroup(_id, title, accountName); list.add(group); } return list; } public void loadAllContacts() { if (mThread != null) { mThread.halt(); } Cursor groupCursor = getContentResolver().query( Data.CONTENT_URI, new String[]{ GroupMembership.RAW_CONTACT_ID, GroupMembership.DISPLAY_NAME, GroupMembership.GROUP_ROW_ID }, Data.MIMETYPE + "=?", new String[] { GroupMembership.CONTENT_ITEM_TYPE}, Data.RAW_CONTACT_ID); Cursor postalCursor = getContentResolver().query( StructuredPostal.CONTENT_URI, new String[] { StructuredPostal.RAW_CONTACT_ID, StructuredPostal.FORMATTED_ADDRESS }, null, null, StructuredPostal.RAW_CONTACT_ID); CursorJoinerWithIntKey joiner = new CursorJoinerWithIntKey( groupCursor, new String[] { Data.RAW_CONTACT_ID }, postalCursor, new String[] { Data.RAW_CONTACT_ID }); mContactsList.clear(); mHandler.post(new Runnable() { @Override public void run() { mListFragment.notifyDataSetChanged(); } }); for (CursorJoinerWithIntKey.Result result : joiner) { String name, address; int groupId; switch (result) { case LEFT: name = groupCursor.getString(1); groupId = groupCursor.getInt(2); address = null; break; case BOTH: name = groupCursor.getString(1); groupId = groupCursor.getInt(2); address = postalCursor.getString(1); break; default: continue; } mContactsList.add(new ContactsItem(name, groupId, address)); } groupCursor.close(); postalCursor.close(); mThread = new GeocodingThread(); mThread.start(); } private void setUpMap() { mMap.clear(); for (ContactsItem contact : mContactsList) { if (contact.getLat() == null || contact.getLng() == null) { continue; } LatLng latLng = new LatLng(contact.getLat(), contact.getLng()); mMap.addMarker(new MarkerOptions() .position(latLng) .title(contact.getName()) .snippet(contact.getDisplayAddress())); } } private class GeocodingThread extends Thread { private boolean halt; public GeocodingThread() { halt = false; } @Override public void run() { findLatLng(); mHandler.post(new Runnable() { @Override public void run() { if (!halt) { mListFragment.notifyDataSetChanged(); setUpMap(); } } }); } public void halt() { halt = true; interrupt(); } private void findLatLng() { final int listSize = mContactsList.size(); for (int i = 0; i < listSize; i++) { if (halt) { return; } final int progress = i * PROGRESS_MAX / listSize; mHandler.post(new Runnable() { @Override public void run() { setProgress(progress); } }); ContactsItem contact = mContactsList.get(i); String address = contact.getAddress(); if (address == null) { continue; } try { List<Address> list = new Geocoder(MainActivity.this, Locale.getDefault()) .getFromLocationName(address, 1); if (halt) { return; } if (list.size() > 0) { Address addr = list.get(0); contact.setLat(addr.getLatitude()); contact.setLng(addr.getLongitude()); mContactsList.set(i, contact); } } catch (IOException e) { } } mHandler.post(new Runnable() { @Override public void run() { setProgress(PROGRESS_MAX); } }); } } }
package org.geotools.data; public class Base64 { /** No options specified. Value is zero. */ public final static int NO_OPTIONS = 0; /** Specify encoding. */ public final static int ENCODE = 1; /** Specify decoding. */ public final static int DECODE = 0; /** Specify that data should be gzip-compressed. */ public final static int GZIP = 2; /** Don't break lines when encoding (violates strict Base64 specification) */ public final static int DONT_BREAK_LINES = 8; /** Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte)'='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte)'\n'; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "UTF-8"; /** The 64 valid Base64 values. */ private final static byte[] ALPHABET; private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */ { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** Determine which ALPHABET to use. */ static { byte[] __bytes; try { __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes( PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException use) { __bytes = _NATIVE_ALPHABET; // Fall back to native encoding } // end catch ALPHABET = __bytes; } // end static /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9 // Decimal 123 - 126 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // I think I end up not using the BAD_ENCODING indicator. //private final static byte BAD_ENCODING = -9; // Indicates error in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /** Defeats instantiation. */ private Base64(){} /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0 ); return b4; } // end encode3to4 /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset ) { // 1 2 3 // 01234567890123456789012345678901 Bit position // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); switch( numSigBytes ) { case 3: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; return destination; case 2: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; case 1: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = EQUALS_SIGN; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * The object is not GZip-compressed before being encoded. * * @param serializableObject The object to encode * @return The Base64-encoded object * @since 1.4 */ public static String encodeObject( java.io.Serializable serializableObject ) { return encodeObject( serializableObject, NO_OPTIONS ); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeObject( java.io.Serializable serializableObject, int options ) { // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.io.ObjectOutputStream oos = null; java.util.zip.GZIPOutputStream gzos = null; // Isolate options int gzip = (options & GZIP); int dontBreakLines = (options & DONT_BREAK_LINES); try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); // GZip? if( gzip == GZIP ) { gzos = new java.util.zip.GZIPOutputStream( b64os ); oos = new java.io.ObjectOutputStream( gzos ); } // end if: gzip else oos = new java.io.ObjectOutputStream( b64os ); oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @since 1.4 */ public static String encodeBytes( byte[] source ) { return encodeBytes( source, 0, source.length, NO_OPTIONS ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * * @param source The data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int options ) { return encodeBytes( source, 0, source.length, options ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @since 1.4 */ public static String encodeBytes( byte[] source, int off, int len ) { return encodeBytes( source, off, len, NO_OPTIONS ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int off, int len, int options ) { // Isolate options int dontBreakLines = ( options & DONT_BREAK_LINES ); int gzip = ( options & GZIP ); // Compress? if( gzip == GZIP ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); } // end catch } // end if: compress // Else, don't compress. Better not to use streams at all then. else { // Convert option to boolean in way that code likes it. boolean breakLines = dontBreakLines == 0; int len43 = len * 4 / 3; byte[] outBuff = new byte[ ( len43 ) // Main 4:3 + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e ); lineLength += 4; if( breakLines && lineLength == MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e ); e += 4; } // end if: some padding needed // Return value according to relevant encoding. try { return new String( outBuff, 0, e, PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( outBuff, 0, e ); } // end catch } // end else: don't compress } // end encodeBytes /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset ) { // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { try{ // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; }catch( Exception e){ System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); return -1; } //e nd catch } } // end decodeToBytes /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the number of decoded bytes converted * @since 1.3 * final private static int decode4to3new( byte[] source, int srcOffset, byte[] destination, int destOffset ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( source[ srcOffset ] & 0xFF ) << 18 ) | ( ( source[ srcOffset + 1 ] & 0xFF ) << 12 ) | ( ( source[ srcOffset + 2 ] & 0xFF ) << 6) | ( ( source[ srcOffset + 3 ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; }*/ /** * Very low-level access to decoding ASCII characters in * the form of a byte array. Does not support automatically * gunzipping or any other "fancy" features. * * @param source The Base64 encoded data * * @return decoded data * @since 1.3 */ public static byte[] decode( byte[] source ) { int len = source.length; int len34 = len * 3 / 4; byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; //byte sbiCrop = 0; byte sbiDecode = 0; for( i = 0; i < len; i++ ) { //sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits sbiDecode = DECODABET[ source[i] ]; if( sbiDecode > EQUALS_SIGN_ENC ) // White space, Equals sign or better { b4[ b4Posn++ ] = sbiDecode; if( b4Posn > 3 ) { int temp = ( ( b4[ 0 ] & 0xFF ) << 18 ) | ( ( b4[ 1 ] & 0xFF ) << 12 ) | ( ( b4[ 2 ] & 0xFF ) << 6) | ( ( b4[ 3 ] & 0xFF ) ); outBuff[ outBuffPosn++ ] = (byte)( temp >> 16 ); outBuff[ outBuffPosn++ ] = (byte)( temp >> 8 ); outBuff[ outBuffPosn++ ] = (byte)( temp ); //outBuffPosn += decode4to3new( b4, 0, outBuff, outBuffPosn ); b4Posn = 0; } // end if: quartet built } // end if: white space, equals sign or better else if ( sbiDecode == EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = 0; if( b4Posn > 3 ) { int temp = ( ( b4[ 0 ] & 0xFF ) << 18 ) | ( ( b4[ 1 ] & 0xFF ) << 12 ) | ( ( b4[ 2 ] & 0xFF ) << 6) | ( ( b4[ 3 ] & 0xFF ) ); outBuff[ outBuffPosn++ ] = (byte)( temp >> 16 ); outBuff[ outBuffPosn++ ] = (byte)( temp >> 8 ); outBuff[ outBuffPosn++ ] = (byte)( temp ); //outBuffPosn += decode4to3new( b4, 0, outBuff, outBuffPosn ); b4Posn = 0; } // end if: quartet built } } return outBuff; } // end decode /** * Very low-level access to decoding ASCII characters in * the form of a byte array. Does not support automatically * gunzipping or any other "fancy" features. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @return decoded data * @since 1.3 */ public static byte[] decode( byte[] source, int off, int len ) { int len34 = len * 3 / 4; byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for( i = off; i < off+len; i++ ) { sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits sbiDecode = DECODABET[ sbiCrop ]; if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = sbiCrop; if( b4Posn > 3 ) { outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( sbiCrop == EQUALS_SIGN ) break; } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" ); return null; } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @since 1.4 */ public static byte[] decode( String s ) { byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) if( bytes != null && bytes.length >= 4 ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @since 1.5 */ public static Object decodeToObject( String encodedObject ) { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); ois = new java.io.ObjectInputStream( bais ); obj = ois.readObject(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); obj = null; } // end catch catch( java.lang.ClassNotFoundException e ) { e.printStackTrace(); obj = null; } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } // end decodeObject /** * Convenience method for encoding data to a file. * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise * * @since 2.1 */ public static boolean encodeToFile( byte[] dataToEncode, String filename ) { boolean success = false; Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.ENCODE ); bos.write( dataToEncode ); success = true; } // end try catch( java.io.IOException e ) { success = false; } // end catch: IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally return success; } // end encodeToFile /** * Convenience method for decoding data to a file. * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise * * @since 2.1 */ public static boolean decodeToFile( String dataToDecode, String filename ) { boolean success = false; Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.DECODE ); bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); success = true; } // end try catch( java.io.IOException e ) { success = false; } // end catch: IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally return success; } // end decodeToFile /** * Convenience method for reading a base64-encoded * file and decoding it. * * @param filename Filename for reading encoded data * @return decoded byte array or null if unsuccessful * * @since 2.1 */ public static byte[] decodeFromFile( String filename ) { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if( file.length() > Integer.MAX_VALUE ) { System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." ); return null; } // end if: file too big for int index buffer = new byte[ (int)file.length() ]; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.DECODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) length += numBytes; // Save in a variable to return decodedData = new byte[ length ]; System.arraycopy( buffer, 0, decodedData, 0, length ); } // end try catch( java.io.IOException e ) { System.err.println( "Error decoding from file " + filename ); } // end catch: IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return decodedData; } // end decodeFromFile /** * Convenience method for reading a binary file * and base64-encoding it. * * @param filename Filename for reading binary data * @return base64-encoded string or null if unsuccessful * * @since 2.1 */ public static String encodeFromFile( String filename ) { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = new byte[ (int)(file.length() * 1.4) ]; int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.ENCODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) length += numBytes; // Save in a variable to return encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); } // end try catch( java.io.IOException e ) { System.err.println( "Error encoding from file " + filename ); } // end catch: IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return encodedData; } // end encodeFromFile /** * A {@link Base64.InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters /** * Constructs a {@link Base64.InputStream} in DECODE mode. * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream( java.io.InputStream in ) { this( in, DECODE ); } // end constructor /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public InputStream( java.io.InputStream in, int options ) { super( in ); this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[ bufferLength ]; this.position = -1; this.lineLength = 0; } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ public int read() throws java.io.IOException { // Do we need to get data? if( position < 0 ) { if( encode ) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for( int i = 0; i < 3; i++ ) { try { int b = in.read(); // If end of stream, b is -1. if( b >= 0 ) { b3[i] = (byte)b; numBinaryBytes++; } // end if: not end of stream } // end try: read catch( java.io.IOException e ) { // Only a problem if we got no data at all. if( i == 0 ) throw e; } // end catch } // end for: each needed input byte if( numBinaryBytes > 0 ) { encode3to4( b3, 0, numBinaryBytes, buffer, 0 ); position = 0; numSigBytes = 4; } // end if: got data else { return -1; } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for( i = 0; i < 4; i++ ) { // Read four "meaningful" bytes: int b = 0; do{ b = in.read(); } while( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC ); if( b < 0 ) break; // Reads a -1 if end of stream b4[i] = (byte)b; } // end for: each needed input byte if( i == 4 ) { numSigBytes = decode4to3( b4, 0, buffer, 0 ); position = 0; } // end if: got four characters else if( i == 0 ){ return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input." ); } // end } // end else: decode } // end else: get data // Got data? if( position >= 0 ) { // End of relevant data? if( /*!encode &&*/ position >= numSigBytes ) return -1; if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[ position++ ]; if( position >= bufferLength ) position = -1; return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException( "Error in Base64 code reading stream." ); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; int b; for( i = 0; i < len; i++ ) { b = read(); //if( b < 0 && i == 0 ) // return -1; if( b >= 0 ) dest[off + i] = (byte)b; else if( i == 0 ) return -1; else break; // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /** * A {@link Base64.OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @since 1.3 */ public OutputStream( java.io.OutputStream out ) { this( out, ENCODE ); } // end constructor /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 1.3 */ public OutputStream( java.io.OutputStream out, int options ) { super( out ); this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[ bufferLength ]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * * @param theByte the byte to write * @since 1.3 */ public void write(int theByte) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theByte ); return; } // end if: supsended // Encode? if( encode ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) // Enough to encode. { out.write( encode3to4( b4, buffer, bufferLength ) ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { out.write( NEW_LINE ); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) // Enough to output. { int len = Base64.decode4to3( buffer, 0, b4, 0 ); out.write( b4, 0, len ); //out.write( Base64.decode4to3( buffer ) ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { throw new java.io.IOException( "Invalid character in Base64 data." ); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> * bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theBytes, off, len ); return; } // end if: supsended for( int i = 0; i < len; i++ ) { write( theBytes[ off + i ] ); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. */ public void flushBase64() throws java.io.IOException { if( position > 0 ) { if( encode ) { out.write( encode3to4( b4, buffer, position ) ); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded." ); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64
package org.voovan.tools; import org.voovan.tools.json.JSON; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class MultiMap<K,V> extends ConcurrentHashMap<K, List<V>> { public MultiMap() {} public MultiMap(Map<K, List<V>> map) { super(map); } /** * * @param key * @return */ public List<V> getValues(K key) { List<V> vals = (List)super.get(key); if ((vals == null) || (vals.isEmpty())) { return null; } return vals; } /** * * @param key * @param i * @return */ public V getValue(K key, int i) { List<V> vals = getValues(key); if (vals == null) { return null; } if ((i == 0) && (vals.isEmpty())) { return null; } return (V)vals.get(i); } /** * * @param key * @param value * @return */ public List<V> putValue(K key, V value) { if (value == null) { return (List)super.put(key, null); } List<V> vals = get(key); if(vals == null) { vals = new ArrayList(); put(key, vals); } vals.add(value); return (List)super.put((K)key, vals); } /** * * @param input /(List) Map */ public void putAllValues(Map<K, V> input) { for (Entry<K, V> entry : input.entrySet()) { putValue((K)entry.getKey(), entry.getValue()); } } /** * * @param key * @param values * @return */ public List<V> putValues(K key, List<V> values) { return (List)super.put(key, values); } /** * * @param key * @param values * @return */ @SafeVarargs public final List<V> putValues(K key, V... values) { List<V> list = new ArrayList(); list.addAll(Arrays.asList(values)); return (List)super.put(key, list); } /** * * @param key * @param value */ public void add(K key, V value) { List<V> lo = (List)get(key); if (lo == null) { lo = new ArrayList(); } lo.add(value); super.put(key, lo); } /** * * @param key * @param values */ public void addValues(K key, List<V> values) { List<V> lo = get(key); if (lo == null) { lo = new ArrayList(); } lo.addAll(values); super.put(key, lo); } /** * * @param key * @param values */ public void addValues(K key, V[] values) { List<V> lo = (List)get(key); if (lo == null) { lo = new ArrayList(); } lo.addAll(Arrays.asList(values)); super.put(key, lo); } /** * / * @param map /(List) Map * @return true:,false: */ public boolean addAllValues(MultiMap<K,V> map) { boolean merged = false; if ((map == null) || (map.isEmpty())) { return merged; } for (Entry<K, List<V>> entry : map.entrySet()) { K name = (K)entry.getKey(); List<V> values = (List)entry.getValue(); if (containsKey(name)) { merged = true; } addValues(name, values); } return merged; } /** * * @param key * @param index * @return : , : null */ public V removeValue(K key, int index) { List<V> lo = (List)get(key); if ((lo == null) || (lo.isEmpty())) { return null; } V ret = lo.remove(index); if (lo.isEmpty()) { remove(key); } return ret; } /** * * @param key * @param value * @return :true , :false */ public boolean removeValue(K key, V value) { List<V> lo = (List)get(key); if ((lo == null) || (lo.isEmpty())) { return false; } boolean ret = lo.remove(value); if (lo.isEmpty()) { remove(key); } else { super.put(key, lo); } return ret; } /** * * @param value * @return :true , :false */ public boolean containsValues(V value) { for (List<V> vals : values()) { if ((vals.size() >0) && (vals.contains(value))) { return true; } } return false; } public String toString() { return JSON.toJSON(this); } }
package wraithaven.conquest.client; import wraith.library.LWJGL.CubeTextures; import wraith.library.LWJGL.Texture; import wraith.library.LWJGL.Voxel.BlockType; import wraith.library.LWJGL.Voxel.VoxelWorld; public class BasicBlock implements BlockType{ private VoxelWorld world; private boolean block_dd, block_d0, block_du, block_0d, block_0u, block_ud, block_u0, block_uu; private final CubeTextures textures; public static final float shadowIntensity = 0.25f; public BasicBlock(CubeTextures textures, VoxelWorld world){ this.textures=textures; this.world=world; } public Texture getTexture(int side){ if(side==0)return textures.xUp; if(side==1)return textures.xDown; if(side==2)return textures.yUp; if(side==3)return textures.yDown; if(side==4)return textures.zUp; if(side==5)return textures.zDown; return null; } public int getRotation(int side){ if(side==0)return textures.xUpRotation; if(side==1)return textures.xDownRotation; if(side==2)return textures.yUpRotation; if(side==3)return textures.yDownRotation; if(side==4)return textures.zUpRotation; if(side==5)return textures.zDownRotation; return 0; } public boolean setupShadows(float[] colors, int side, int x, int y, int z){ if(side==0){ block_dd=world.getBlock(x+1, y-1, z-1, false)!=null; block_d0=world.getBlock(x+1, y-1, z, false)!=null; block_du=world.getBlock(x+1, y-1, z+1, false)!=null; block_0d=world.getBlock(x+1, y, z-1, false)!=null; block_0u=world.getBlock(x+1, y, z+1, false)!=null; block_ud=world.getBlock(x+1, y+1, z-1, false)!=null; block_u0=world.getBlock(x+1, y+1, z, false)!=null; block_uu=world.getBlock(x+1, y+1, z+1, false)!=null; if(block_uu||block_0u||block_u0)colors[0]=colors[1]=colors[2]=shadowIntensity; else colors[0]=colors[1]=colors[2]=1f; if(block_du||block_d0||block_0u)colors[3]=colors[4]=colors[5]=shadowIntensity; else colors[3]=colors[4]=colors[5]=1f; if(block_dd||block_0d||block_d0)colors[6]=colors[7]=colors[8]=shadowIntensity; else colors[6]=colors[7]=colors[8]=1f; if(block_ud||block_0d||block_u0)colors[9]=colors[10]=colors[11]=shadowIntensity; else colors[9]=colors[10]=colors[11]=1f; } if(side==1){ block_dd=world.getBlock(x-1, y-1, z-1, false)!=null; block_d0=world.getBlock(x-1, y-1, z, false)!=null; block_du=world.getBlock(x-1, y-1, z+1, false)!=null; block_0d=world.getBlock(x-1, y, z-1, false)!=null; block_0u=world.getBlock(x-1, y, z+1, false)!=null; block_ud=world.getBlock(x-1, y+1, z-1, false)!=null; block_u0=world.getBlock(x-1, y+1, z, false)!=null; block_uu=world.getBlock(x-1, y+1, z+1, false)!=null; if(block_dd||block_0d||block_d0)colors[0]=colors[1]=colors[2]=shadowIntensity; else colors[0]=colors[1]=colors[2]=1f; if(block_du||block_d0||block_0u)colors[3]=colors[4]=colors[5]=shadowIntensity; else colors[3]=colors[4]=colors[5]=1f; if(block_uu||block_0u||block_u0)colors[6]=colors[7]=colors[8]=shadowIntensity; else colors[6]=colors[7]=colors[8]=1f; if(block_ud||block_0d||block_u0)colors[9]=colors[10]=colors[11]=shadowIntensity; else colors[9]=colors[10]=colors[11]=1f; } if(side==2){ block_dd=world.getBlock(x-1, y+1, z-1, false)!=null; block_d0=world.getBlock(x-1, y+1, z, false)!=null; block_du=world.getBlock(x-1, y+1, z+1, false)!=null; block_0d=world.getBlock(x, y+1, z-1, false)!=null; block_0u=world.getBlock(x, y+1, z+1, false)!=null; block_ud=world.getBlock(x+1, y+1, z-1, false)!=null; block_u0=world.getBlock(x+1, y+1, z, false)!=null; block_uu=world.getBlock(x+1, y+1, z+1, false)!=null; if(block_dd||block_0d||block_d0)colors[0]=colors[1]=colors[2]=shadowIntensity; else colors[0]=colors[1]=colors[2]=1f; if(block_du||block_d0||block_0u)colors[3]=colors[4]=colors[5]=shadowIntensity; else colors[3]=colors[4]=colors[5]=1f; if(block_uu||block_0u||block_u0)colors[6]=colors[7]=colors[8]=shadowIntensity; else colors[6]=colors[7]=colors[8]=1f; if(block_ud||block_0d||block_u0)colors[9]=colors[10]=colors[11]=shadowIntensity; else colors[9]=colors[10]=colors[11]=1f; } if(side==3){ block_dd=world.getBlock(x-1, y-1, z-1, false)!=null; block_d0=world.getBlock(x-1, y-1, z, false)!=null; block_du=world.getBlock(x-1, y-1, z+1, false)!=null; block_0d=world.getBlock(x, y-1, z-1, false)!=null; block_0u=world.getBlock(x, y-1, z+1, false)!=null; block_ud=world.getBlock(x+1, y-1, z-1, false)!=null; block_u0=world.getBlock(x+1, y-1, z, false)!=null; block_uu=world.getBlock(x+1, y-1, z+1, false)!=null; if(block_uu||block_u0||block_0u)colors[0]=colors[1]=colors[2]=shadowIntensity; else colors[0]=colors[1]=colors[2]=1f; if(block_du||block_0u||block_d0)colors[3]=colors[4]=colors[5]=shadowIntensity; else colors[3]=colors[4]=colors[5]=1f; if(block_dd||block_0d||block_d0)colors[6]=colors[7]=colors[8]=shadowIntensity; else colors[6]=colors[7]=colors[8]=1f; if(block_ud||block_0d||block_u0)colors[9]=colors[10]=colors[11]=shadowIntensity; else colors[9]=colors[10]=colors[11]=1f; } if(side==4){ block_dd=world.getBlock(x-1, y-1, z+1, false)!=null; block_d0=world.getBlock(x-1, y, z+1, false)!=null; block_du=world.getBlock(x-1, y+1, z+1, false)!=null; block_0d=world.getBlock(x, y-1, z+1, false)!=null; block_0u=world.getBlock(x, y+1, z+1, false)!=null; block_ud=world.getBlock(x+1, y-1, z+1, false)!=null; block_u0=world.getBlock(x+1, y, z+1, false)!=null; block_uu=world.getBlock(x+1, y+1, z+1, false)!=null; if(block_dd||block_0d||block_d0)colors[6]=colors[7]=colors[8]=shadowIntensity; else colors[6]=colors[7]=colors[8]=1f; if(block_du||block_d0||block_0u)colors[3]=colors[4]=colors[5]=shadowIntensity; else colors[3]=colors[4]=colors[5]=1f; if(block_uu||block_0u||block_u0)colors[0]=colors[1]=colors[2]=shadowIntensity; else colors[0]=colors[1]=colors[2]=1f; if(block_ud||block_0d||block_u0)colors[9]=colors[10]=colors[11]=shadowIntensity; else colors[9]=colors[10]=colors[11]=1f; } if(side==5){ block_dd=world.getBlock(x-1, y-1, z-1, false)!=null; block_d0=world.getBlock(x-1, y, z-1, false)!=null; block_du=world.getBlock(x-1, y+1, z-1, false)!=null; block_0d=world.getBlock(x, y-1, z-1, false)!=null; block_0u=world.getBlock(x, y+1, z-1, false)!=null; block_ud=world.getBlock(x+1, y-1, z-1, false)!=null; block_u0=world.getBlock(x+1, y, z-1, false)!=null; block_uu=world.getBlock(x+1, y+1, z-1, false)!=null; if(block_dd||block_0d||block_d0)colors[0]=colors[1]=colors[2]=shadowIntensity; else colors[0]=colors[1]=colors[2]=1f; if(block_du||block_d0||block_0u)colors[3]=colors[4]=colors[5]=shadowIntensity; else colors[3]=colors[4]=colors[5]=1f; if(block_uu||block_0u||block_u0)colors[6]=colors[7]=colors[8]=shadowIntensity; else colors[6]=colors[7]=colors[8]=1f; if(block_ud||block_0d||block_u0)colors[9]=colors[10]=colors[11]=shadowIntensity; else colors[9]=colors[10]=colors[11]=1f; } if((block_d0&&block_u0)||(block_0d&&block_0u)||(block_0d&&block_d0)||(block_0u&&block_u0)||(block_0d&&block_u0)||(block_0u&&block_d0))colors[12]=colors[13]=colors[14]=shadowIntensity; else if(block_d0||block_u0||block_0d||block_0u)return false; else colors[12]=colors[13]=colors[14]=1f; return true; } }
package com.KST.eCommerce; import java.util.ArrayList; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.layout.Background; import javafx.stage.Stage; /** * * @author Ken */ public class EcommerceGUI extends Application { public final static String BACKGROUND = "#4286f4"; public final static String FOREGROUND = "#fff"; public final static String VIEW_STORE = "views/viewHome.fxml"; public final static String VIEW_CART = "views/viewCart.fxml"; public final static String VIEW_LOGIN = "views/viewLogin.fxml"; public final static String VIEW_ITEMS = "views/viewItems.fxml"; public final static String VIEW_ADD_ITEM = "views/viewAddItem.fxml"; public static EcommercePlatform platform; @Override public void start(Stage stage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("views/viewHome.fxml")); stage.setScene(new Scene(root)); stage.setTitle("eCommerce"); stage.show(); } public static void showGUI(EcommercePlatform platform) { EcommerceGUI.platform = platform; launch(); } }
package com.baasbox.android; import com.baasbox.android.exceptions.BAASBoxException; import com.baasbox.android.impl.BAASLogging; import com.baasbox.android.json.JsonObject; import com.baasbox.android.spi.CredentialStore; import com.baasbox.android.spi.HttpRequest; import org.apache.http.HttpResponse; public abstract class BaasObject<E extends BaasObject<E>> { // todo this should provide common interface among remote objects // such as dirty tracking timestamps ecc public abstract String getId(); public abstract long getVersion(); public abstract String getAuthor(); public abstract String getCreationDate(); public abstract BaasResult<Void> revokeSync(Grant grant, String user); public abstract BaasResult<Void> revokeAllSync(Grant grant, String role); public abstract BaasResult<Void> grantSync(Grant grant, String user); public abstract BaasResult<Void> grantAllSync(Grant grant, String role); public abstract <T> RequestToken grant(Grant grant, String username, T tag, Priority priority, BAASBox.BAASHandler<Void, T> handler); public final RequestToken grant(Grant grant, String username, BAASBox.BAASHandler<Void, ?> handler) { return grant(grant, username, null, Priority.NORMAL, handler); } public abstract <T> RequestToken grantAll(Grant grant, String role, T tag, Priority priority, BAASBox.BAASHandler<Void, T> handler); public final RequestToken grantAll(Grant grant, String role, BAASBox.BAASHandler<Void, ?> handler) { return grantAll(grant, role, null, Priority.NORMAL, handler); } public abstract <T> RequestToken revoke(Grant grant, String username, T tag, Priority priority, BAASBox.BAASHandler<Void, T> handler); public final RequestToken revoke(Grant grant, String username, BAASBox.BAASHandler<Void, ?> handler) { return grant(grant, username, null, Priority.NORMAL, handler); } public abstract <T> RequestToken revokeAll(Grant grant, String role, T tag, Priority priority, BAASBox.BAASHandler<Void, T> handler); public final RequestToken revokeAll(Grant grant, String role, BAASBox.BAASHandler<Void, ?> handler) { return grantAll(grant, role, null, Priority.NORMAL, handler); } static final class GrantRequest<T> extends BaseRequest<Void, T> { static <T> GrantRequest<T> grantAsync(BAASBox box, boolean add, Grant grant, boolean role, String collection, String id, String user, T tag, Priority priority, BAASBox.BAASHandler<Void, T> handler) { if (handler == null) throw new NullPointerException("handler cannot be null"); priority = priority == null ? Priority.NORMAL : priority; return grant(box, add, grant, role, collection, id, user, tag, priority, handler); } static <T> GrantRequest<T> grant(BAASBox box, boolean add, Grant grant, boolean role, String collection, String docId, String userOrRole, T tag, Priority priority, BAASBox.BAASHandler<Void, T> handler) { if (grant == null) throw new NullPointerException("grant cannot be null"); if (userOrRole == null) throw new NullPointerException("userOrRole cannot be null"); String type = role ? "role" : "user"; String endpoint; if (collection != null) { endpoint = box.requestFactory.getEndpoint("document/?/?/?/?/?", collection, docId, grant.action, type, userOrRole); } else { endpoint = box.requestFactory.getEndpoint("file/?/?/?/?", docId, grant.action, type, userOrRole); } HttpRequest request; if (add) { request = box.requestFactory.put(endpoint); } else { request = box.requestFactory.delete(endpoint); } return new GrantRequest<T>(request, priority, tag, handler); } private GrantRequest(HttpRequest request, Priority priority, T t, BAASBox.BAASHandler<Void, T> handler) { super(request, priority, t, handler); } @Override protected Void handleOk(HttpResponse response, BAASBox.Config config, CredentialStore credentialStore) throws BAASBoxException { return null; } } final static class DebugRequest<R, T> extends BaseRequest<R, T> { DebugRequest(HttpRequest request, Priority priority, T t, BAASBox.BAASHandler<R, T> handler, boolean retry) { super(request, priority, t, handler, retry); } DebugRequest(HttpRequest request, Priority priority, T t, BAASBox.BAASHandler<R, T> handler) { super(request, priority, t, handler); } @Override protected R handleOk(HttpResponse response, BAASBox.Config config, CredentialStore credentialStore) throws BAASBoxException { JsonObject o = getJsonEntity(response, config.HTTP_CHARSET); BAASLogging.debug(o.toString()); return null; } } final static class DeleteRequest<T> extends BaseRequest<Void, T> { DeleteRequest(HttpRequest request, Priority priority, T t, BAASBox.BAASHandler<Void, T> handler) { super(request, priority, t, handler); } @Override protected Void handleOk(HttpResponse response, BAASBox.Config config, CredentialStore credentialStore) throws BAASBoxException { return null; } } }
package com.gregswebserver.catan.common.game; import com.gregswebserver.catan.common.crypto.Username; import com.gregswebserver.catan.common.event.EventConsumerException; import com.gregswebserver.catan.common.event.ReversibleEventConsumer; import com.gregswebserver.catan.common.game.board.BoardEvent; import com.gregswebserver.catan.common.game.board.BoardEventType; import com.gregswebserver.catan.common.game.board.GameBoard; import com.gregswebserver.catan.common.game.board.hexarray.CoordTransforms; import com.gregswebserver.catan.common.game.board.hexarray.Coordinate; import com.gregswebserver.catan.common.game.board.tiles.ResourceTile; import com.gregswebserver.catan.common.game.board.towns.City; import com.gregswebserver.catan.common.game.board.towns.Settlement; import com.gregswebserver.catan.common.game.board.towns.Town; import com.gregswebserver.catan.common.game.gameplay.rules.GameRules; import com.gregswebserver.catan.common.game.gameplay.trade.PermanentTrade; import com.gregswebserver.catan.common.game.gameplay.trade.TemporaryTrade; import com.gregswebserver.catan.common.game.gameplay.trade.Trade; import com.gregswebserver.catan.common.game.gameplay.trade.TradingPostType; import com.gregswebserver.catan.common.game.gamestate.*; import com.gregswebserver.catan.common.game.players.*; import com.gregswebserver.catan.common.game.teams.TeamColor; import com.gregswebserver.catan.common.game.teams.TeamEvent; import com.gregswebserver.catan.common.game.teams.TeamEventType; import com.gregswebserver.catan.common.game.teams.TeamPool; import com.gregswebserver.catan.common.game.util.EnumCounter; import com.gregswebserver.catan.common.game.util.GameResource; import com.gregswebserver.catan.common.structure.game.GameSettings; import org.junit.ComparisonFailure; import java.util.*; public class CatanGame implements ReversibleEventConsumer<GameEvent> { //Permanent data private final GameRules rules; private final Set<Trade> bankTrades; //Game state storage. private final GameBoard board; private final PlayerPool players; private final TeamPool teams; private final SharedState state; //Historical event data private final Stack<GameHistory> history; public CatanGame(GameSettings settings) { rules = settings.gameRules; bankTrades = new HashSet<>(); for (GameResource target : GameResource.values()) for (GameResource source : GameResource.values()) if (target != source) bankTrades.add(new PermanentTrade(source, target, 4)); board = settings.boardGenerator.generate(settings.boardLayout, settings.seed); players = new PlayerPool(settings); teams = new TeamPool(settings); state = new SharedState(settings); history = new Stack<>(); history.push(new GameHistory(new GameEvent(null, GameEventType.Start, null), new LogicEvent(this, LogicEventType.NOP, null))); } public GameBoard getBoard() { return board; } public PlayerPool getTeams() { return players; } public List<GameEvent> getEventList() { ArrayList<GameEvent> out = new ArrayList<>(history.size()); for (GameHistory h : history) out.add(h.getGameEvent()); return out; } public List<Trade> getTrades(Username user) { List<Trade> trades = new ArrayList<>(); Player player = players.getPlayer(user); for (Username u : players.getAll()) { Trade trade = players.getPlayer(u).getTrade(); if (trade != null && player.canMakeTrade(trade)) trades.add(trade); } for (TradingPostType t1 : board.getTrades(player.getTeamColor())) { for (Trade trade : t1.getTrades()) if (player.canMakeTrade(trade)) trades.add(trade); } for (Trade trade : bankTrades) if (player.canMakeTrade(trade)) trades.add(trade); Collections.sort(trades); return trades; } public boolean isPlayerActive(Username user) { Player player = players.getPlayer(user); return player != null && player.getTeamColor() == state.getActiveTeam(); } private LogicEvent createPlayerEvent(Username origin, PlayerEventType type, Object payload) { return new LogicEvent(this, LogicEventType.Player_Event, new PlayerEvent(origin, type, payload)); } private LogicEvent createBoardEvent(TeamColor origin, BoardEventType type, Object payload) { return new LogicEvent(this, LogicEventType.Board_Event, new BoardEvent(origin, type, payload)); } private LogicEvent createTeamEvent(TeamColor origin, TeamEventType type, Object payload) { return new LogicEvent(this, LogicEventType.Team_Event, new TeamEvent(origin, type, payload)); } private LogicEvent createStateEvent(Object origin, GameStateEventType type, Object payload) { return new LogicEvent(this, LogicEventType.GameState_Event, new GameStateEvent(origin, type, payload)); } private LogicEvent getLogicEvent(GameEvent event) { Username origin = event.getOrigin(); TeamColor teamColor = players.getPlayer(origin).getTeamColor(); switch (event.getType()) { case Start: break; case Turn_Advance: //Advancing the turn requires all of these events to fire. return new LogicEvent(this, LogicEventType.AND, Arrays.asList( //Need to pass the turn to the next team createStateEvent(this, GameStateEventType.Advance_Turn, null), //Roll the dice to get the next income round. createStateEvent(this, GameStateEventType.Roll_Dice, null), //Choose whether this is a starter turn or a real turn. new LogicEvent(this, LogicEventType.OR, Arrays.asList( //If its a starter turn, signal we are ready to advance. createTeamEvent(teamColor, TeamEventType.Finish_Setup_Turn, null), //Otherwise it might be a regular turn. new LogicEvent(this, LogicEventType.AND, Arrays.asList( //Advance the turn as regular createTeamEvent(teamColor, TeamEventType.Finish_Turn, null), //ive everyone their income getIncomeEvents(state.getDiceRoll()) )) )), //Mature all of the cards that a user bought this turn. new LogicEvent(this, LogicEventType.Player_Event, players.getPlayer(origin).getMatureEvent()) )); case Player_Move_Robber: //Moving the robber requires checking if the move can be made, and the player is allowed to do it. return new LogicEvent(this, LogicEventType.AND, Arrays.asList( //Choose whether to use up the free robber from the start of turn or use a development card. new LogicEvent(this, LogicEventType.OR, Arrays.asList( createTeamEvent(teamColor, TeamEventType.Use_Robber, event.getPayload()), createPlayerEvent(origin, PlayerEventType.Use_DevelopmentCard, DevelopmentCard.Knight) )), //Check the board to see if the robber is in a valid location. createBoardEvent(teamColor, BoardEventType.Place_Robber, event.getPayload()) )); case Build_Settlement: //A settlement build can happen as an outpost or as a normal settlement. return new LogicEvent(this, LogicEventType.OR, Arrays.asList( //If we make a regular settlement, the purchase and placement must be valid new LogicEvent(this, LogicEventType.AND, Arrays.asList( createPlayerEvent(origin, PlayerEventType.Make_Purchase, Purchase.Settlement), createBoardEvent(teamColor, BoardEventType.Place_Settlement, event.getPayload()) )), //If we make a first outpost, we need to check for outpost placement new LogicEvent(this, LogicEventType.AND, Arrays.asList( createTeamEvent(teamColor, TeamEventType.Build_First_Outpost, event.getPayload()), createBoardEvent(teamColor, BoardEventType.Place_Outpost, event.getPayload()) )), //If we make a second outpost, we need to allocate the correct resources. new LogicEvent(this, LogicEventType.AND, Arrays.asList( createTeamEvent(teamColor, TeamEventType.Build_Second_Outpost, event.getPayload()), createBoardEvent(teamColor, BoardEventType.Place_Outpost, event.getPayload()), createPlayerEvent(origin, PlayerEventType.Gain_Resources, getTownIncome((Coordinate) event.getPayload())) )) )); case Build_City: //All cities are purchased manually. return new LogicEvent(this, LogicEventType.AND, Arrays.asList( createPlayerEvent(origin, PlayerEventType.Make_Purchase, Purchase.City), createBoardEvent(teamColor, BoardEventType.Place_City, event.getPayload()) )); case Build_Road: //A road can be built either using the free outpost or as a purchase. return new LogicEvent(this, LogicEventType.AND, Arrays.asList( new LogicEvent(this, LogicEventType.OR, Arrays.asList( createTeamEvent(teamColor, TeamEventType.Build_Free_Road, event.getPayload()), createPlayerEvent(origin, PlayerEventType.Make_Purchase, Purchase.Road) )), createBoardEvent(teamColor, BoardEventType.Place_Road, event.getPayload()) )); case Buy_Development: //In order to gain a development card, one must exist and the user must have enough resources. return new LogicEvent(this, LogicEventType.AND, Arrays.asList( createStateEvent(this, GameStateEventType.Draw_DevelopmentCard, null), createPlayerEvent(origin, PlayerEventType.Make_Purchase, Purchase.DevelopmentCard), createPlayerEvent(origin, PlayerEventType.Gain_DevelopmentCard, state.getDevelopmentCard()) )); case Offer_Trade: return createPlayerEvent(origin, PlayerEventType.Offer_Trade, event.getPayload()); case Make_Trade: if (event.getPayload() instanceof TemporaryTrade) { TemporaryTrade t = (TemporaryTrade) event.getPayload(); return new LogicEvent(this, LogicEventType.AND, Arrays.asList( createPlayerEvent(origin, PlayerEventType.Make_Trade, t), createPlayerEvent(t.seller, PlayerEventType.Fill_Trade, t) )); } else { return createPlayerEvent(origin, PlayerEventType.Make_Trade, event.getPayload()); } } return new LogicEvent(this, LogicEventType.NOP, null); } private LogicEvent getIncomeEvents(DiceRoll roll) { List<Coordinate> spaces = board.getActiveTiles(roll); if (spaces == null || spaces.isEmpty()) return new LogicEvent(this, LogicEventType.NOP, null); Map<TeamColor, EnumCounter<GameResource>> income = new EnumMap<>(TeamColor.class); for (Coordinate space : spaces) { GameResource resource = ((ResourceTile) board.getTile(space)).getResource(); if (resource != null) { for (Town town : board.getAdjacentTowns(space)) { TeamColor teamColor = (town != null ? town.getTeam() : TeamColor.None); if (teamColor != TeamColor.None) { EnumCounter<GameResource> teamIncome = income.get(teamColor); if (teamIncome == null) income.put(teamColor, teamIncome = new EnumCounter<>(GameResource.class)); if (town instanceof Settlement) teamIncome.increment(resource, rules.getSettlementResources()); if (town instanceof City) teamIncome.increment(resource, rules.getCityResources()); } } } } ArrayList<LogicEvent> events = new ArrayList<>(); for (Map.Entry<TeamColor, EnumCounter<GameResource>> entry : income.entrySet()) for (Username name : teams.getTeam(entry.getKey()).getPlayers()) events.add(createPlayerEvent(name, PlayerEventType.Gain_Resources, entry.getValue())); return new LogicEvent(this, LogicEventType.AND, events); } private EnumCounter<GameResource> getTownIncome(Coordinate vertex) { EnumCounter<GameResource> counter = new EnumCounter<>(GameResource.class); for (Coordinate space : CoordTransforms.getAdjacentSpacesFromVertex(vertex).values()) { if (board.getTile(space) instanceof ResourceTile) { ResourceTile tile = (ResourceTile) board.getTile(space); GameResource resource = tile.getResource(); if (resource != null) counter.increment(resource, 1); } } return counter; } @SuppressWarnings("unchecked") private void test(LogicEvent event) throws EventConsumerException { Object payload = event.getPayload(); switch (event.getType()) { case AND: for (LogicEvent child : (List<LogicEvent>) payload) test(child); break; case OR: EventConsumerException fail = new EventConsumerException("No successful case", event); for (LogicEvent child : (List<LogicEvent>) payload) try { test(child); return; } catch (EventConsumerException e) { fail.addSuppressed(e); } throw fail; case NOT: boolean success = true; try { test((LogicEvent) payload); } catch (EventConsumerException ignored) { success = false; } if (success) throw new EventConsumerException("Event successful", (LogicEvent) payload); case NOP: break; case Player_Event: players.test((PlayerEvent) payload); break; case Board_Event: board.test((BoardEvent) payload); break; case Team_Event: teams.test((TeamEvent) payload); break; case GameState_Event: state.test((GameStateEvent) payload); break; } } @Override public void test(GameEvent event) throws EventConsumerException { test(getLogicEvent(event)); } @SuppressWarnings("unchecked") private LogicEvent execute(LogicEvent event) throws EventConsumerException { test(event); Object payload = event.getPayload(); switch (event.getType()) { case AND: ArrayList<LogicEvent> newChildren = new ArrayList<>(); for (LogicEvent child : (List<LogicEvent>) payload) newChildren.add(execute(child)); return new LogicEvent(this, LogicEventType.AND, newChildren); case OR: EventConsumerException inconsistent = new EventConsumerException("Inconsistent", event); for (LogicEvent child : (List<LogicEvent>) payload) { try { test(child); return execute(child); } catch (EventConsumerException e) { inconsistent.addSuppressed(e); } } throw inconsistent; case NOT: try { test((LogicEvent) payload); } catch (EventConsumerException e) { return new LogicEvent(this, LogicEventType.NOP, null); } throw new EventConsumerException("Inconsistent", event); case NOP: break; case Player_Event: players.execute((PlayerEvent) payload); break; case Board_Event: board.execute((BoardEvent) payload); break; case Team_Event: teams.execute((TeamEvent) payload); break; case GameState_Event: state.execute((GameStateEvent) payload); break; } return event; } @Override public void execute(GameEvent event) throws EventConsumerException { test(event); try { LogicEvent logic = getLogicEvent(event); LogicEvent actions = execute(logic); history.push(new GameHistory(event, actions)); } catch (Exception e) { throw new EventConsumerException(event, e); } } @SuppressWarnings("unchecked") private void undo(LogicEvent event) throws EventConsumerException { try { switch (event.getType()) { case AND: case OR: for (LogicEvent child : (List<LogicEvent>) event.getPayload()) undo(child); break; case NOT: undo((LogicEvent) event.getPayload()); break; case NOP: break; case Player_Event: players.undo(); break; case Board_Event: board.undo(); break; case Team_Event: teams.undo(); break; case GameState_Event: state.undo(); break; } } catch (Exception e) { throw new EventConsumerException(event, e); } } @Override public void undo() throws EventConsumerException { if (history.isEmpty()) throw new EventConsumerException("No event"); undo(history.pop().getLogicEvent()); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CatanGame catanGame = (CatanGame) o; if (!rules.equals(catanGame.rules)) return false; if (!bankTrades.equals(catanGame.bankTrades)) return false; if (!board.equals(catanGame.board)) return false; if (!players.equals(catanGame.players)) return false; if (!teams.equals(catanGame.teams)) return false; if (!state.equals(catanGame.state)) return false; return history.equals(catanGame.history); } public void assertEquals(CatanGame o) { if (this == o) return; if (!rules.equals(o.rules)) throw new ComparisonFailure("Rules", rules.toString(), o.rules.toString()); if (!bankTrades.equals(o.bankTrades)) throw new ComparisonFailure("BankTrades", bankTrades.toString(), o.bankTrades.toString()); if (!board.equals(o.board)) throw new ComparisonFailure("Board", board.toString(), o.board.toString()); if (!players.equals(o.players)) throw new ComparisonFailure("Players", players.toString(), o.players.toString()); if (!teams.equals(o.teams)) throw new ComparisonFailure("DiceRolls", teams.toString(), o.teams.toString()); if (!state.equals(o.state)) throw new ComparisonFailure("Cards", state.toString(), o.state.toString()); if (!history.equals(o.history)) throw new ComparisonFailure("EventStack", history.toString(), o.history.toString()); } @Override public String toString() { return "CatanGame"; } }
package com.iskrembilen.quasseldroid.gui; import java.io.IOException; import java.net.UnknownHostException; import java.security.GeneralSecurityException; import java.util.Observable; import java.util.Observer; import android.R.bool; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.database.Cursor; import android.net.ConnectivityManager; import android.os.Bundle; import android.os.IBinder; import android.os.ResultReceiver; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.SimpleAdapter; import android.widget.SimpleCursorAdapter; import android.widget.Spinner; import android.widget.Toast; import com.iskrembilen.quasseldroid.io.CoreConnection; import com.iskrembilen.quasseldroid.io.QuasselDbHelper; import com.iskrembilen.quasseldroid.service.CoreConnService; import com.iskrembilen.quasseldroid.R; public class LoginActivity extends Activity implements Observer { private static final String TAG = LoginActivity.class.getSimpleName(); public static final String PREFS_ACCOUNT = "AccountPreferences"; public static final String PREFS_CORE = "coreSelection"; public static final String PREFS_USERNAME = "username"; public static final String PREFS_PASSWORD = "password"; public static final String PREFS_REMEMBERME = "rememberMe"; SharedPreferences settings; QuasselDbHelper dbHelper; private ResultReceiver statusReceiver; Spinner core; EditText username; EditText password; CheckBox rememberMe; Button connect; private String hashedCert;//ugly /* EXample of how to get a preference * SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); boolean update = prefs.getBoolean("updatePref", false); * */ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, "Create"); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.login); settings = getSharedPreferences(PREFS_ACCOUNT, MODE_PRIVATE); dbHelper = new QuasselDbHelper(this); dbHelper.open(); core = (Spinner)findViewById(R.id.serverSpinner); username = (EditText)findViewById(R.id.usernameField); password = (EditText)findViewById(R.id.passwordField); rememberMe = (CheckBox)findViewById(R.id.remember_me_checkbox); //setup the core spinner //dbHelper.addCore("testcore", "test.core.com", 8848); Cursor c = dbHelper.getAllCores(); startManagingCursor(c); String[] from = new String[] {QuasselDbHelper.KEY_NAME}; int[] to = new int[] {android.R.id.text1}; SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, c, from, to); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //TODO: Ken:Implement view reuse core.setAdapter(adapter); //Use saved settings if(core.getCount()>settings.getInt(PREFS_CORE, 0)) core.setSelection(settings.getInt(PREFS_CORE, 0)); username.setText(settings.getString(PREFS_USERNAME,"")); password.setText(settings.getString(PREFS_PASSWORD,"")); rememberMe.setChecked(settings.getBoolean(PREFS_REMEMBERME, false)); connect = (Button)findViewById(R.id.connect_button); connect.setOnClickListener(onConnect); statusReceiver = new ResultReceiver(null) { @Override protected void onReceiveResult(int resultCode, Bundle resultData) { if (resultCode==CoreConnService.CONNECTION_CONNECTED) { removeDialog(R.id.DIALOG_CONNECTING); LoginActivity.this.startActivity(new Intent(LoginActivity.this, BufferActivity.class)); }else if (resultCode==CoreConnService.CONNECTION_DISCONNECTED) { if (resultData!=null){ removeDialog(R.id.DIALOG_CONNECTING); Toast.makeText(LoginActivity.this, resultData.getString(CoreConnService.STATUS_KEY), Toast.LENGTH_LONG).show(); } } else if (resultCode == CoreConnService.CONNECTION_NEW_CERTIFICATE) { hashedCert = resultData.getString(CoreConnService.CERT_KEY); removeDialog(R.id.DIALOG_CONNECTING); showDialog(R.id.DIALOG_NEW_CERTIFICATE); } super.onReceiveResult(resultCode, resultData); } }; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.login_menu, menu); return super.onCreateOptionsMenu(menu); } @Override protected void onStart() { super.onStart(); doBindService(); } @Override protected void onStop() { super.onStop(); doUnbindService(); } @Override protected void onDestroy() { super.onDestroy(); if (dbHelper != null) { dbHelper.close(); dbHelper=null; } } @Override public boolean onPrepareOptionsMenu(Menu menu) { return super.onPrepareOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_add_core: showDialog(R.id.DIALOG_ADD_CORE); break; case R.id.menu_edit_core: showDialog(R.id.DIALOG_EDIT_CORE); break; case R.id.menu_delete_core: dbHelper.deleteCore(core.getSelectedItemId()); Toast.makeText(LoginActivity.this, "Deleted core", Toast.LENGTH_LONG).show(); updateCoreSpinner(); //TODO: mabye add some confirm dialog when deleting a core break; case R.id.menu_preferences: Intent i = new Intent(LoginActivity.this, PreferenceView.class); startActivity(i); break; } return super.onOptionsItemSelected(item); } @Override protected void onPrepareDialog(int id, Dialog dialog) { switch(id) { case R.id.DIALOG_ADD_CORE: dialog.setTitle("Add new core"); break; case R.id.DIALOG_EDIT_CORE: dialog.setTitle("Edit core"); Bundle res = dbHelper.getCore(core.getSelectedItemId()); ((EditText)dialog.findViewById(R.id.dialog_name_field)).setText(res.getString(QuasselDbHelper.KEY_NAME)); ((EditText)dialog.findViewById(R.id.dialog_address_field)).setText(res.getString(QuasselDbHelper.KEY_ADDRESS)); ((EditText)dialog.findViewById(R.id.dialog_port_field)).setText(Integer.toString(res.getInt(QuasselDbHelper.KEY_PORT))); ((CheckBox)dialog.findViewById(R.id.dialog_usessl_checkbox)).setChecked(res.getBoolean(QuasselDbHelper.KEY_SSL)); break; } super.onPrepareDialog(id, dialog); } @Override protected Dialog onCreateDialog(int id) { final Dialog dialog; switch (id) { case R.id.DIALOG_EDIT_CORE: //fallthrough case R.id.DIALOG_ADD_CORE: dialog = new Dialog(this); dialog.setContentView(R.layout.dialog_add_core); dialog.setTitle("Add new core"); OnClickListener buttonListener = new OnClickListener() { @Override public void onClick(View v) { EditText nameField = (EditText)dialog.findViewById(R.id.dialog_name_field); EditText addressField = (EditText)dialog.findViewById(R.id.dialog_address_field); EditText portField = (EditText)dialog.findViewById(R.id.dialog_port_field); CheckBox sslBox = (CheckBox)dialog.findViewById(R.id.dialog_usessl_checkbox); if (v.getId()==R.id.cancel_button) { nameField.setText(""); addressField.setText(""); portField.setText(""); sslBox.setChecked(false); dialog.dismiss(); }else if (v.getId()==R.id.save_button && !nameField.getText().toString().equals("") &&!addressField.getText().toString().equals("") && !portField.getText().toString().equals("")) { String name = nameField.getText().toString().trim(); String address = addressField.getText().toString().trim(); int port = Integer.parseInt(portField.getText().toString().trim()); boolean useSSL = sslBox.isChecked(); //TODO: Ken: mabye add some better check on what state the dialog is used for, edit/add. Atleast use a string from the resources so its the same if you change it. if ((String)dialog.getWindow().getAttributes().getTitle()=="Add new core") { dbHelper.addCore(name, address, port, useSSL); }else if ((String)dialog.getWindow().getAttributes().getTitle()=="Edit core") { dbHelper.updateCore(core.getSelectedItemId(), name, address, port, useSSL); } LoginActivity.this.updateCoreSpinner(); nameField.setText(""); addressField.setText(""); portField.setText(""); sslBox.setChecked(false); dialog.dismiss(); if ((String)dialog.getWindow().getAttributes().getTitle()=="Add new core") { Toast.makeText(LoginActivity.this, "Added core", Toast.LENGTH_LONG).show(); }else if ((String)dialog.getWindow().getAttributes().getTitle()=="Edit core") { Toast.makeText(LoginActivity.this, "Edited core", Toast.LENGTH_LONG).show(); } } } }; dialog.findViewById(R.id.cancel_button).setOnClickListener(buttonListener); dialog.findViewById(R.id.save_button).setOnClickListener(buttonListener); break; case R.id.DIALOG_CONNECTING: ProgressDialog prog = new ProgressDialog(LoginActivity.this); prog.setMessage("Connecting..."); prog.setCancelable(false); dialog = prog; break; case R.id.DIALOG_NEW_CERTIFICATE: AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this); final SharedPreferences certPrefs = getSharedPreferences("CertificateStorage", Context.MODE_PRIVATE); builder.setMessage("Received a new certificate, do you trust it?\n" + hashedCert) .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { certPrefs.edit().putString("certificate", hashedCert).commit(); onConnect.onClick(null); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); dialog = builder.create(); break; default: dialog = null; break; } return dialog; } private OnClickListener onConnect = new OnClickListener() { public void onClick(View v) { if(username.getText().length()==0 || password.getText().length()==0 || core.getCount() == 0){ AlertDialog.Builder diag=new AlertDialog.Builder(LoginActivity.this); diag.setMessage("Error, connection information not filled out properly"); diag.setCancelable(false); AlertDialog dg = diag.create(); dg.setOwnerActivity(LoginActivity.this); dg.setButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) {}}); dg.show(); return; } SharedPreferences.Editor settingsedit = settings.edit(); if(rememberMe.isChecked()){//save info settingsedit.putInt(PREFS_CORE, core.getSelectedItemPosition()); settingsedit.putString(PREFS_USERNAME,username.getText().toString()); settingsedit.putString(PREFS_PASSWORD, password.getText().toString()); settingsedit.putBoolean(PREFS_REMEMBERME, true); }else { settingsedit.putInt(PREFS_CORE, core.getSelectedItemPosition()); settingsedit.remove(PREFS_USERNAME); settingsedit.remove(PREFS_PASSWORD); settingsedit.remove(PREFS_REMEMBERME); } settingsedit.commit(); //dbHelper.open(); Bundle res = dbHelper.getCore(core.getSelectedItemId()); //TODO: quick fix for checking if we have internett before connecting, should remove some force closes, not sure if we should do it in another place tho, mabye in CoreConn //Check that the phone has either mobile or wifi connection to querry teh bus oracle ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); //0 is mobile, 1 is wifi if (!(conn.getNetworkInfo(0).isConnected() || conn.getNetworkInfo(1).isConnected())) { Toast.makeText(LoginActivity.this, "This application requires a internett connection", Toast.LENGTH_LONG).show(); return; } showDialog(R.id.DIALOG_CONNECTING); //Make intent to send to the CoreConnect service, with connection data Intent connectIntent = new Intent(LoginActivity.this, CoreConnService.class); connectIntent.putExtra("name", res.getString(QuasselDbHelper.KEY_NAME)); connectIntent.putExtra("address", res.getString(QuasselDbHelper.KEY_ADDRESS)); connectIntent.putExtra("port", res.getInt(QuasselDbHelper.KEY_PORT)); connectIntent.putExtra("ssl", res.getBoolean(QuasselDbHelper.KEY_SSL)); connectIntent.putExtra("username", username.getText().toString().trim()); connectIntent.putExtra("password", password.getText().toString()); startService(connectIntent); } }; public void updateCoreSpinner() { ((SimpleCursorAdapter)core.getAdapter()).getCursor().requery(); } public void update(Observable observable, Object data) { // TODO Auto-generated method stub } private CoreConnService boundConnService = null; private boolean isBound = false; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { // This is called when the connection with the service has been // established, giving us the service object we can use to // interact with the service. Because we have bound to a explicit // service that we know is running in our own process, we can // cast its IBinder to a concrete class and directly access it. Log.i(TAG, "BINDING ON SERVICE DONE"); boundConnService = ((CoreConnService.LocalBinder)service).getService(); boundConnService.registerStatusReceiver(statusReceiver); } public void onServiceDisconnected(ComponentName className) { boundConnService = null; } }; void doBindService() { // Establish a connection with the service. We use an explicit // class name because we want a specific service implementation that // we know will be running in our own process (and thus won't be // supporting component replacement by other applications). bindService(new Intent(LoginActivity.this, CoreConnService.class), mConnection, Context.BIND_AUTO_CREATE); isBound = true; Log.i(TAG, "Binding Service"); } void doUnbindService() { if (isBound) { Log.i(TAG, "Unbinding service"); if (boundConnService != null) boundConnService.unregisterStatusReceiver(statusReceiver); unbindService(mConnection); isBound = false; } } }
package com.googlecode.totallylazy; import com.googlecode.totallylazy.iterators.NodeIterator; import com.googlecode.totallylazy.iterators.PoppingIterator; import org.w3c.dom.Attr; import org.w3c.dom.CharacterData; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.util.Iterator; import java.util.List; import static com.googlecode.totallylazy.Runnables.VOID; import static com.googlecode.totallylazy.XPathFunctions.resolver; public class Xml { public static final Escaper DEFAULT_ESCAPER = new Escaper(). withRule('&', "&amp;"). withRule('<', "&lt;"). withRule('>', "&gt;"). withRule('\'', "& withRule('"', "&quot;"). withRule(Strings.unicodeControlOrUndefinedCharacter(), toXmlEntity()); private static final Document DOCUMENT = document("<totallylazy/>"); public static String selectContents(final Node node, final String expression) { return contents(internalSelectNodes(node, expression)); } public static Sequence<Node> selectNodes(final Node node, final String expression) { return internalSelectNodes(node, expression); } public static Sequence<Node> selectNodesForwardOnly(final Node node, final String expression) { return Sequences.forwardOnly(new PoppingIterator<Node>(selectNodes(node, expression).toList().iterator())); } public static Number selectNumber(final Node node, final String expression) { try { return (Number) xpath().evaluate(expression, node, XPathConstants.NUMBER); } catch (XPathExpressionException e) { throw LazyException.lazyException(e); } } public static boolean matches(final Node node, final String expression) { try { return (Boolean) xpath().evaluate(expression, node, XPathConstants.BOOLEAN); } catch (XPathExpressionException e) { throw LazyException.lazyException(e); } } private static Sequence<Node> internalSelectNodes(final Node node, final String expression) { try { return sequence((NodeList) xpath().evaluate(expression, node, XPathConstants.NODESET)); } catch (XPathExpressionException e) { try { String nodeAsString = (String) xpath().evaluate(expression, node, XPathConstants.STRING); return Sequences.<Node>sequence(createTextNode(nodeAsString)); } catch (XPathExpressionException ignore) { throw LazyException.lazyException(e); } } } public static Text createTextNode(String value) { return DOCUMENT.createTextNode(value); } public static Option<Node> selectNode(final Node node, final String expression) { return selectNodes(node, expression).headOption(); } public static Sequence<Element> selectElements(final Node node, final String expression) { return selectNodes(node, expression).safeCast(Element.class); } public static Option<Element> selectElement(final Node node, final String expression) { return selectElements(node, expression).headOption(); } public static XPath xpath() { XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setXPathFunctionResolver(resolver()); return xPath; } public static Sequence<Node> sequence(final NodeList nodes) { return new Sequence<Node>() { public Iterator<Node> iterator() { return new NodeIterator(nodes); } }; } public static String contents(Sequence<Node> nodes) { return contentsSequence(nodes).toString(""); } public static Sequence<String> contentsSequence(Sequence<Node> nodes) { return nodes.map(contents()); } public static Sequence<String> textContents(Sequence<Node> nodes) { return nodes.map(textContent()); } public static Sequence<String> textContents(NodeList nodes) { return Xml.textContents(Xml.sequence(nodes)); } public static Function1<Node, String> textContent() { return new Function1<Node, String>() { @Override public String call(Node node) throws Exception { return node.getTextContent(); } }; } public static Function1<Element, Void> removeAttribute(final String name) { return new Function1<Element, Void>() { public Void call(Element element) throws Exception { element.removeAttribute(name); return VOID; } }; } public static Function1<Node, String> contents() { return new Function1<Node, String>() { public String call(Node node) throws Exception { return contents(node); } }; } public static String contents(Node node) throws Exception { if (node instanceof Attr) { return contents((Attr) node); } if (node instanceof CharacterData) { return contents((CharacterData) node); } if (node instanceof Element) { return contents((Element) node); } throw new UnsupportedOperationException("Unknown node type " + node.getClass()); } public static String contents(CharacterData characterData) { return characterData.getData(); } public static String contents(Attr attr) { return attr.getValue(); } public static String contents(Element element) throws Exception { return sequence(element.getChildNodes()).map(new Callable1<Node, String>() { public String call(Node node) throws Exception { if (node instanceof Element) { return asString((Element) node); } return contents(node); } }).toString(""); } public static String asString(Element element) throws Exception { Transformer transformer = transformer(); StringWriter writer = new StringWriter(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(element), new StreamResult(writer)); return writer.toString(); } @SuppressWarnings("unchecked") public static Transformer transformer() throws TransformerConfigurationException { return internalTransformer(); } public static Transformer transformer(Pair<String, Object>... attributes) throws TransformerConfigurationException { return internalTransformer(attributes); } private static Transformer internalTransformer(Pair<String, Object>... attributes) throws TransformerConfigurationException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); for (Pair<String, Object> attribute : attributes) { transformerFactory.setAttribute(attribute.first(), attribute.second()); } return transformerFactory.newTransformer(); } public static Document document(byte[] bytes) { try { return document(new String(bytes, "UTF-8")); } catch (UnsupportedEncodingException e) { throw LazyException.lazyException(e); } } public static Document document(String xml) { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver(ignoreEntities()); documentBuilder.setErrorHandler(null); return documentBuilder.parse(new ByteArrayInputStream(xml.getBytes())); } catch (Exception e) { throw LazyException.lazyException(e); } } private static EntityResolver ignoreEntities() { return new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } }; } public static Sequence<Node> remove(final Node root, final String expression) { return remove(selectNodes(root, expression)); } public static Sequence<Node> remove(final Sequence<Node> nodes) { return nodes.map(remove()).realise(); } private static Function1<Node, Node> remove() { return new Function1<Node, Node>() { public Node call(Node node) throws Exception { return node.getParentNode().removeChild(node); } }; } @SuppressWarnings("unchecked") public static String format(final Node node) throws Exception { return format(node, Pair.<String, Object>pair("indent-number", 4)); } public static String format(final Node node, final Pair<String, Object>... attributes) throws Exception { Transformer transformer = transformer(attributes); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); } public static String escape(Object value) { return DEFAULT_ESCAPER. escape(value); } public static Function1<Object, String> escape() { return new Function1<Object, String>() { public String call(Object value) throws Exception { return escape(value); } }; } public static Function1<Character, String> toXmlEntity() { return new Function1<Character, String>() { public String call(Character character) throws Exception { return String.format("&#%s;", Integer.toString(character, 10)); } }; } public static class functions { public static Function2<Node, String, String> selectContents() { return new Function2<Node, String, String>() { @Override public String call(Node node, String expression) throws Exception { return Xml.selectContents(node, expression); } }; } public static Function2<Node, String, Sequence<Node>> selectNodes() { return new Function2<Node, String, Sequence<Node>>() { @Override public Sequence<Node> call(final Node node, final String expression) throws Exception { return Xml.selectNodes(node, expression); } }; } } }
package com.multiwork.andres; import com.actionbarsherlock.app.ActionBar; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.protocolanalyzer.andres.LogicData; import com.protocolanalyzer.andres.LogicData.Protocol; import android.os.Bundle; import android.text.method.ScrollingMovementMethod; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class LogicAnalizerListFragment extends SherlockFragment implements OnDataDecodedListener{ private static final boolean DEBUG = true; private static SherlockFragmentActivity mActivity; private static ActionBar mActionBar; private static TextView mRawData[] = new TextView[LogicAnalizerActivity.channelsNumber]; private static OnActionBarClickListener mActionBarListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(DEBUG) Log.i("mFragment2","onCreate()"); // Obtengo la Activity que contiene el Fragment mActivity = getSherlockActivity(); mActionBar = mActivity.getSupportActionBar(); // Obtengo el ActionBar mActionBar.setDisplayHomeAsUpEnabled(true); // El icono de la aplicacion funciona como boton HOME mActionBar.setTitle(getString(R.string.AnalyzerName)) ; // Nombre this.setHasOptionsMenu(true); // Obtengo el OnActionBarClickListener de la Activity try { mActionBarListener = (OnActionBarClickListener) mActivity; } catch (ClassCastException e) { throw new ClassCastException(mActivity.toString() + " must implement OnActionBarClickListener"); } mActionBarListener.onActionBarClickListener(R.id.PlayPauseLogic); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.logic_rawdata, container, false); mRawData[0] = (TextView) v.findViewById(R.id.tvRawDataLogic1); mRawData[0].setMovementMethod(new ScrollingMovementMethod()); mRawData[1] = (TextView) v.findViewById(R.id.tvRawDataLogic2); mRawData[1].setMovementMethod(new ScrollingMovementMethod()); mRawData[2] = (TextView) v.findViewById(R.id.tvRawDataLogic3); mRawData[2].setMovementMethod(new ScrollingMovementMethod()); mRawData[3] = (TextView) v.findViewById(R.id.tvRawDataLogic4); mRawData[3].setMovementMethod(new ScrollingMovementMethod()); mRawData[1].setPadding(40, 0, 0, 0); mRawData[2].setPadding(40, 0, 0, 0); mRawData[3].setPadding(40, 0, 0, 0); /** Hace que todos los toques en la pantalla sean para esta Fragment y no el que esta detras */ v.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); return v; } @Override public void onResume() { super.onResume(); if(DEBUG) Log.i("mFragment2","Resume"); } @Override public double onDataDecodedListener(LogicData[] mLogicData, int samplesCount) { if(DEBUG) Log.i("mFragment2","onDataDecodedListener() - " + mLogicData.length + " channels"); for(int n=0; n < mRawData.length; ++n) mRawData[n].setText(""); for(int n=0; n < mRawData.length; ++n){ if(mLogicData[n].getProtocol() != Protocol.CLOCK){ mRawData[n].append("Canal " + n + " - " + mLogicData[n].getProtocol().toString() + "\n"); for(int i=0; i < mLogicData[n].getStringCount(); ++i){ mRawData[n].append(mLogicData[n].getString(i) + "\t String.format("%.2f", (mLogicData[n].getPositionAt(i)[0]*1000000)) + "uS\n"); } mRawData[n].append("\n"); } } return 0; } }
// Kyle Russell // AUT University 2015 package com.graphi.display; import cern.colt.matrix.impl.SparseDoubleMatrix2D; import com.graphi.io.AdjMatrixParser; import com.graphi.io.GMLParser; import com.graphi.io.GraphMLParser; import com.graphi.io.Storage; import com.graphi.sim.GraphPlayback; import com.graphi.util.Edge; import com.graphi.sim.Network; import com.graphi.sim.PlaybackEntry; import com.graphi.util.EdgeFactory; import com.graphi.util.EdgeLabelTransformer; import com.graphi.util.GraphData; import com.graphi.util.GraphUtilities; import com.graphi.util.MatrixTools; import com.graphi.util.Node; import com.graphi.util.NodeFactory; import com.graphi.util.ObjectFillTransformer; import com.graphi.util.VertexLabelTransformer; import com.graphi.util.WeightTransformer; import de.javasoft.swing.DateComboBox; import edu.uci.ics.jung.algorithms.layout.AggregateLayout; import edu.uci.ics.jung.algorithms.layout.FRLayout; import edu.uci.ics.jung.algorithms.matrix.GraphMatrixOperations; import edu.uci.ics.jung.algorithms.scoring.BetweennessCentrality; import edu.uci.ics.jung.algorithms.scoring.ClosenessCentrality; import edu.uci.ics.jung.graph.Graph; import edu.uci.ics.jung.graph.SparseMultigraph; import edu.uci.ics.jung.graph.util.EdgeType; import edu.uci.ics.jung.visualization.VisualizationViewer; import edu.uci.ics.jung.visualization.control.CrossoverScalingControl; import edu.uci.ics.jung.visualization.control.EditingModalGraphMouse; import edu.uci.ics.jung.visualization.control.GraphMouseListener; import edu.uci.ics.jung.visualization.control.ModalGraphMouse; import edu.uci.ics.jung.visualization.control.ScalingControl; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.util.List; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.MouseEvent; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import javax.imageio.ImageIO; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JColorChooser; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.border.Border; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; import net.miginfocom.swing.MigLayout; import org.apache.commons.collections15.Transformer; import org.apache.commons.io.FilenameUtils; public class LayoutPanel extends JPanel { protected final ControlPanel controlPanel; protected final ScreenPanel screenPanel; protected final JSplitPane splitPane; protected final JScrollPane controlScroll; protected BufferedImage addIcon, removeIcon, colourIcon; protected BufferedImage clipIcon, openIcon, saveIcon; protected BufferedImage editBlackIcon, pointerIcon, moveIcon; protected BufferedImage moveSelectedIcon, editSelectedIcon, pointerSelectedIcon; protected BufferedImage graphIcon, tableIcon, resetIcon, executeIcon; protected BufferedImage editIcon, playIcon, stopIcon, recordIcon, closeIcon; public static final Color TRANSPARENT = new Color(255, 255, 255, 0); public static final Color PRESET_BG = new Color(200, 200, 200); protected GraphData data; protected MainMenu menu; protected JFrame frame; public LayoutPanel(MainMenu menu, JFrame frame) { setPreferredSize(new Dimension((int)(Window.WIDTH * 0.7), (int) (Window.HEIGHT * 0.85))); setLayout(new BorderLayout()); initResources(); this.menu = menu; this.frame = frame; data = new GraphData(); controlPanel = new ControlPanel(); screenPanel = new ScreenPanel(); splitPane = new JSplitPane(); controlScroll = new JScrollPane(controlPanel); controlScroll.setBorder(null); splitPane.setLeftComponent(screenPanel); splitPane.setRightComponent(controlScroll); splitPane.setResizeWeight(0.7); add(splitPane, BorderLayout.CENTER); } protected void sendToOutput(String output) { SimpleDateFormat sdf = new SimpleDateFormat("K:MM a dd.MM.yy"); String date = sdf.format(new Date()); String prefix = "\n[" + date + "] "; JTextArea outputArea = screenPanel.outputPanel.outputArea; SwingUtilities.invokeLater(()-> { outputArea.setText(outputArea.getText() + prefix + output); }); } protected File getFile(boolean open, String desc, String...extensions) { JFileChooser jfc = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter(desc, extensions); jfc.setFileFilter(filter); if(open) jfc.showOpenDialog(null); else jfc.showSaveDialog(null); return jfc.getSelectedFile(); } protected String getFileExtension(File file) { if(file == null) return ""; return FilenameUtils.getExtension(file.getPath()); } public static JPanel wrapComponents(Border border, Component... components) { JPanel panel = new JPanel(); panel.setBorder(border); for(Component component : components) panel.add(component); return panel; } protected void initResources() { try { addIcon = ImageIO.read(new File("resources/images/addSmallIcon.png")); removeIcon = ImageIO.read(new File("resources/images/removeSmallIcon.png")); colourIcon = ImageIO.read(new File("resources/images/color_icon.png")); clipIcon = ImageIO.read(new File("resources/images/clipboard.png")); saveIcon = ImageIO.read(new File("resources/images/new_file.png")); openIcon = ImageIO.read(new File("resources/images/open_icon.png")); editBlackIcon = ImageIO.read(new File("resources/images/editblack.png")); pointerIcon = ImageIO.read(new File("resources/images/pointer.png")); moveIcon = ImageIO.read(new File("resources/images/move.png")); moveSelectedIcon = ImageIO.read(new File("resources/images/move_selected.png")); editSelectedIcon = ImageIO.read(new File("resources/images/editblack_selected.png")); pointerSelectedIcon = ImageIO.read(new File("resources/images/pointer_selected.png")); graphIcon = ImageIO.read(new File("resources/images/graph.png")); tableIcon = ImageIO.read(new File("resources/images/table.png")); executeIcon = ImageIO.read(new File("resources/images/execute.png")); resetIcon = ImageIO.read(new File("resources/images/reset.png")); editIcon = ImageIO.read(new File("resources/images/edit.png")); playIcon = ImageIO.read(new File("resources/images/play.png")); stopIcon = ImageIO.read(new File("resources/images/stop.png")); recordIcon = ImageIO.read(new File("resources/images/record.png")); closeIcon = ImageIO.read(new File("resources/images/close.png")); } catch(IOException e) { JOptionPane.showMessageDialog(null, "Failed to load resources: " + e.getMessage()); } } // CONTROL PANEL protected class ControlPanel extends JPanel implements ActionListener { protected final String BA_PANEL_CARD = "ba_panel"; protected final String KL_PANEL_CARD = "kl_panel"; protected final String CLUSTER_PANEL_CARD = "cluster_panel"; protected final String SPATH_PANEL_CARD = "spath_panel"; protected final String CENTRALITY_PANEL_CARD = "centrality_panel"; protected JPanel dataControlPanel, outputControlPanel, displayControlPanel; protected JPanel modePanel; protected JPanel simPanel; protected JRadioButton editCheck, selectCheck, moveCheck; protected ButtonGroup modeGroup; protected JComboBox genAlgorithmsBox; protected JButton resetGeneratorBtn, executeGeneratorBtn; protected JPanel genPanel, baGenPanel, klGenPanel; protected JSpinner latticeSpinner, clusteringSpinner; protected JSpinner initialNSpinner, addNSpinner; protected JCheckBox simTiesCheck; protected JSpinner simTiesPSpinner; protected JLabel simTiesPLabel; protected IOPanel ioPanel; protected JPanel editPanel; protected JLabel selectedLabel; protected JButton gObjAddBtn, gObjEditBtn, gObjRemoveBtn; protected JPanel computePanel; protected JPanel computeInnerPanel; protected JPanel clusterPanel, spathPanel; protected JSpinner clusterEdgeRemoveSpinner; protected JCheckBox clusterTransformCheck; protected JComboBox computeBox; protected JTextField spathFromField, spathToField; protected JButton computeBtn; protected JPanel centralityPanel; protected JComboBox centralityTypeBox; protected ButtonGroup centralityOptions; protected JCheckBox centralityMorphCheck; protected ButtonGroup editObjGroup; protected JRadioButton editVertexRadio, editEdgeRadio; protected JPanel viewerPanel; protected JCheckBox viewerVLabelsCheck; protected JCheckBox viewerELabelsCheck; protected JButton viewerBGBtn, vertexBGBtn, edgeBGBtn; protected JPanel playbackPanel; protected JButton recordCtrlsBtn; protected boolean recording; protected JButton displayCtrlsBtn; protected JLabel activeScriptLabel; public ControlPanel() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); setBorder(BorderFactory.createEmptyBorder(15, 0, 3, 8)); setPreferredSize(new Dimension(230, 1650)); ioPanel = new IOPanel(); modePanel = new JPanel(); simPanel = new JPanel(new MigLayout("fillx")); modePanel.setPreferredSize(new Dimension(230, 100)); modePanel.setBorder(BorderFactory.createTitledBorder("Mode controls")); simPanel.setBorder(BorderFactory.createTitledBorder("Simulation controls")); modeGroup = new ButtonGroup(); editCheck = new JRadioButton("Edit"); selectCheck = new JRadioButton("Select"); moveCheck = new JRadioButton("Move"); editCheck.setIcon(new ImageIcon(editBlackIcon)); selectCheck.setIcon(new ImageIcon(pointerIcon)); moveCheck.setIcon(new ImageIcon(moveIcon)); moveCheck.setSelectedIcon(new ImageIcon(moveSelectedIcon)); editCheck.setSelectedIcon(new ImageIcon(editSelectedIcon)); selectCheck.setSelectedIcon(new ImageIcon(pointerSelectedIcon)); editCheck.addActionListener(this); selectCheck.addActionListener(this); moveCheck.addActionListener(this); modeGroup.add(editCheck); modeGroup.add(selectCheck); modeGroup.add(moveCheck); modePanel.add(editCheck); modePanel.add(selectCheck); modePanel.add(moveCheck); selectCheck.setSelected(true); genAlgorithmsBox = new JComboBox(); simTiesCheck = new JCheckBox("Interpersonal ties"); simTiesPLabel = new JLabel("P"); simTiesPSpinner = new JSpinner(new SpinnerNumberModel(0.5, 0.0, 1.0, 0.1)); simTiesPSpinner.setPreferredSize(new Dimension(50, 25)); simTiesPLabel.setVisible(false); simTiesPSpinner.setVisible(false); genAlgorithmsBox.addItem("Kleinberg"); genAlgorithmsBox.addItem("Barabasi-Albert"); genAlgorithmsBox.addActionListener(this); resetGeneratorBtn = new JButton("Reset"); executeGeneratorBtn = new JButton("Generate"); executeGeneratorBtn.addActionListener(this); resetGeneratorBtn.addActionListener(this); simTiesCheck.addActionListener(this); resetGeneratorBtn.setBackground(Color.WHITE); executeGeneratorBtn.setBackground(Color.WHITE); resetGeneratorBtn.setIcon(new ImageIcon(resetIcon)); executeGeneratorBtn.setIcon(new ImageIcon(executeIcon)); genPanel = new JPanel(new CardLayout()); baGenPanel = new JPanel(new MigLayout()); klGenPanel = new JPanel(new MigLayout()); genPanel.add(klGenPanel, KL_PANEL_CARD); genPanel.add(baGenPanel, BA_PANEL_CARD); genPanel.setBackground(TRANSPARENT); baGenPanel.setBackground(TRANSPARENT); klGenPanel.setBackground(TRANSPARENT); latticeSpinner = new JSpinner(new SpinnerNumberModel(15, 0, 100, 1)); clusteringSpinner = new JSpinner(new SpinnerNumberModel(2, 0, 10, 1)); latticeSpinner.setPreferredSize(new Dimension(50, 20)); clusteringSpinner.setPreferredSize(new Dimension(50, 20)); latticeSpinner.setOpaque(true); clusteringSpinner.setOpaque(true); initialNSpinner = new JSpinner(new SpinnerNumberModel(2, 0, 1000, 1)); addNSpinner = new JSpinner(new SpinnerNumberModel(100, 0, 1000, 1)); initialNSpinner.setOpaque(true); addNSpinner.setOpaque(true); baGenPanel.add(new JLabel("Initial nodes")); baGenPanel.add(initialNSpinner, "wrap"); baGenPanel.add(new JLabel("Generated nodes")); baGenPanel.add(addNSpinner); klGenPanel.add(new JLabel("Lattice size")); klGenPanel.add(latticeSpinner, "wrap"); klGenPanel.add(new JLabel("Clustering exp.")); klGenPanel.add(clusteringSpinner); simPanel.add(new JLabel("Generator"), "al right"); simPanel.add(genAlgorithmsBox, "wrap"); simPanel.add(genPanel, "wrap, span 2, al center"); simPanel.add(simTiesCheck, "al center, span 2, wrap"); simPanel.add(simTiesPLabel, "al right"); simPanel.add(simTiesPSpinner, "wrap"); simPanel.add(resetGeneratorBtn, "al right"); simPanel.add(executeGeneratorBtn, ""); JPanel simWrapperPanel = new JPanel(new BorderLayout()); simWrapperPanel.add(simPanel); editPanel = new JPanel(new GridLayout(3, 1)); editPanel.setBorder(BorderFactory.createTitledBorder("Graph object Controls")); editPanel.setBackground(TRANSPARENT); editObjGroup = new ButtonGroup(); editVertexRadio = new JRadioButton("Vertex"); editEdgeRadio = new JRadioButton("Edge"); gObjAddBtn = new JButton("Add"); gObjEditBtn = new JButton("Edit"); gObjRemoveBtn = new JButton("Delete"); selectedLabel = new JLabel("None"); gObjAddBtn.setBackground(Color.WHITE); gObjEditBtn.setBackground(Color.WHITE); gObjRemoveBtn.setBackground(Color.WHITE); gObjAddBtn.setIcon(new ImageIcon(addIcon)); gObjRemoveBtn.setIcon(new ImageIcon(removeIcon)); gObjEditBtn.setIcon(new ImageIcon(editIcon)); selectedLabel.setFont(new Font("Arial", Font.BOLD, 12)); gObjAddBtn.addActionListener(this); gObjEditBtn.addActionListener(this); gObjRemoveBtn.addActionListener(this); editObjGroup.add(editVertexRadio); editObjGroup.add(editEdgeRadio); editVertexRadio.setSelected(true); JPanel selectedPanel = wrapComponents(null, new JLabel("Selected: "), selectedLabel); JPanel editObjPanel = wrapComponents(null, editVertexRadio, editEdgeRadio); JPanel gObjOptsPanel = wrapComponents(null, gObjAddBtn, gObjEditBtn, gObjRemoveBtn); selectedPanel.setBackground(PRESET_BG); gObjOptsPanel.setBackground(PRESET_BG); editObjPanel.setBackground(PRESET_BG); editPanel.add(selectedPanel); editPanel.add(editObjPanel); editPanel.add(gObjOptsPanel); computePanel = new JPanel(new MigLayout("fillx")); computeInnerPanel = new JPanel(new CardLayout()); clusterPanel = new JPanel(); centralityPanel = new JPanel(new MigLayout()); spathPanel = new JPanel(); computeBox = new JComboBox(); computeBtn = new JButton("Execute"); computePanel.setPreferredSize(new Dimension(230, 180)); computePanel.setBorder(BorderFactory.createTitledBorder("Computation controls")); spathPanel.setLayout(new BoxLayout(spathPanel, BoxLayout.Y_AXIS)); spathPanel.setBackground(TRANSPARENT); computeBtn.setBackground(Color.WHITE); computeBtn.addActionListener(this); computeBtn.setIcon(new ImageIcon(executeIcon)); computeBox.addItem("Clusters"); computeBox.addItem("Centrality"); computeBox.addActionListener(this); clusterEdgeRemoveSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 100, 1)); clusterTransformCheck = new JCheckBox("Transform graph"); clusterEdgeRemoveSpinner.setPreferredSize(new Dimension(50, 25)); JPanel clusterEdgesPanel = wrapComponents(null, new JLabel("Delete edges"), clusterEdgeRemoveSpinner); clusterPanel.setLayout(new MigLayout()); clusterPanel.add(clusterEdgesPanel, "wrap"); clusterPanel.add(clusterTransformCheck); clusterEdgesPanel.setBackground(PRESET_BG); clusterPanel.setBackground(PRESET_BG); spathFromField = new JTextField(); spathToField = new JTextField(); spathFromField.setPreferredSize(new Dimension(50, 20)); spathToField.setPreferredSize(new Dimension(50, 20)); JLabel tLabel = new JLabel("To ID"); JPanel spathFromPanel = wrapComponents(null, new JLabel("From ID"), spathFromField); JPanel spathToPanel = wrapComponents(null, tLabel, spathToField); JPanel spathWrapper = new JPanel(new MigLayout()); spathWrapper.add(spathFromPanel, "wrap"); spathWrapper.add(spathToPanel); spathWrapper.setBackground(TRANSPARENT); spathFromPanel.setBackground(TRANSPARENT); spathToPanel.setBackground(TRANSPARENT); spathPanel.add(spathWrapper); centralityTypeBox = new JComboBox(); centralityOptions = new ButtonGroup(); centralityMorphCheck = new JCheckBox("Transform graph"); centralityTypeBox.addItem("Eigenvector"); centralityTypeBox.addItem("Closeness"); centralityTypeBox.addItem("Betweenness"); centralityTypeBox.addActionListener(this); JPanel cenTypePanel = wrapComponents(null, new JLabel("Type"), centralityTypeBox); centralityPanel.add(cenTypePanel, "wrap"); centralityPanel.add(centralityMorphCheck); cenTypePanel.setBackground(PRESET_BG); centralityPanel.setBackground(PRESET_BG); computeInnerPanel.add(clusterPanel, CLUSTER_PANEL_CARD); computeInnerPanel.add(spathPanel, SPATH_PANEL_CARD); computeInnerPanel.add(centralityPanel, CENTRALITY_PANEL_CARD); computePanel.add(new JLabel("Compute "), "al right"); computePanel.add(computeBox, "wrap"); computePanel.add(computeInnerPanel, "wrap, span 2, al center"); computePanel.add(computeBtn, "span 2, al center"); JPanel computeWrapperPanel = new JPanel(new BorderLayout()); computeWrapperPanel.add(computePanel); CardLayout clusterInnerLayout = (CardLayout) computeInnerPanel.getLayout(); clusterInnerLayout.show(computeInnerPanel, CLUSTER_PANEL_CARD); viewerPanel = new JPanel(new MigLayout("fillx")); viewerVLabelsCheck = new JCheckBox("Vertex labels"); viewerELabelsCheck = new JCheckBox("Edge labels"); viewerBGBtn = new JButton("Choose"); vertexBGBtn = new JButton("Choose"); edgeBGBtn = new JButton("Choose"); viewerBGBtn.setIcon(new ImageIcon(colourIcon)); vertexBGBtn.setIcon(new ImageIcon(colourIcon)); edgeBGBtn.setIcon(new ImageIcon(colourIcon)); viewerBGBtn.addActionListener(this); vertexBGBtn.addActionListener(this); edgeBGBtn.addActionListener(this); viewerVLabelsCheck.addActionListener(this); viewerELabelsCheck.addActionListener(this); viewerPanel.setBorder(BorderFactory.createTitledBorder("Viewer controls")); viewerPanel.setPreferredSize(new Dimension(500, 200)); viewerPanel.add(viewerVLabelsCheck, "wrap, span 2, al center"); viewerPanel.add(viewerELabelsCheck, "wrap, span 2, al center"); viewerPanel.add(new JLabel("Vertex background"), "al right"); viewerPanel.add(vertexBGBtn, "wrap"); viewerPanel.add(new JLabel("Edge background"), "al right"); viewerPanel.add(edgeBGBtn, "wrap"); viewerPanel.add(new JLabel("Viewer background"), "al right"); viewerPanel.add(viewerBGBtn, "wrap"); JPanel viewerWrapperPanel = new JPanel(new BorderLayout()); viewerWrapperPanel.add(viewerPanel); playbackPanel = new JPanel(new MigLayout("fillx")); activeScriptLabel = new JLabel("None"); recordCtrlsBtn = new JButton("Record controls"); displayCtrlsBtn = new JButton("Playback controls"); recording = false; recordCtrlsBtn.setIcon(new ImageIcon(recordIcon)); displayCtrlsBtn.setIcon(new ImageIcon(playIcon)); activeScriptLabel.setFont(new Font("Arial", Font.BOLD, 12)); playbackPanel.setBorder(BorderFactory.createTitledBorder("Script controls")); playbackPanel.add(new JLabel("Active script: "), "al right"); playbackPanel.add(activeScriptLabel, "wrap"); playbackPanel.add(recordCtrlsBtn, "span 2, al center, wrap"); playbackPanel.add(displayCtrlsBtn, "span 2, al center"); recordCtrlsBtn.addActionListener(this); displayCtrlsBtn.addActionListener(this); JPanel pbWrapperPanel = new JPanel(new BorderLayout()); pbWrapperPanel.add(playbackPanel); menu.exitItem.addActionListener(this); menu.miniItem.addActionListener(this); menu.maxItem.addActionListener(this); menu.importGraphItem.addActionListener(this); menu.exportGraphItem.addActionListener(this); menu.importLogItem.addActionListener(this); menu.exportLogItem.addActionListener(this); menu.vLabelsItem.addActionListener(this); menu.eLabelsItem.addActionListener(this); menu.viewerBGItem.addActionListener(this); menu.edgeBGItem.addActionListener(this); menu.vertexBGItem.addActionListener(this); menu.clearLogItem.addActionListener(this); menu.resetGraphItem.addActionListener(this); menu.addVertexItem.addActionListener(this); menu.editVertexItem.addActionListener(this); menu.removeVertexItem.addActionListener(this); menu.addEdgeItem.addActionListener(this); menu.editEdgeItem.addActionListener(this); menu.removeEdgeItem.addActionListener(this); menu.aboutItem.addActionListener(this); add(modePanel); add(Box.createRigidArea(new Dimension(230, 30))); add(simWrapperPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(ioPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(editPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(computeWrapperPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(viewerWrapperPanel); add(Box.createRigidArea(new Dimension(230, 30))); add(pbWrapperPanel); } protected void updateSelectedComponents() { if(data.getSelectedItems() == null || data.getSelectedItems().length == 0) selectedLabel.setText("None"); else { if(data.getSelectedItems().length > 1) selectedLabel.setText(data.getSelectedItems().length + " objects"); else { Object selectedObj = data.getSelectedItems()[0]; if(selectedObj instanceof Node) selectedLabel.setText("Node (ID=" + ((Node) selectedObj).getID() + ")"); else if(selectedObj instanceof Edge) selectedLabel.setText("Edge (ID=" + ((Edge) selectedObj).getID() + ")"); } } } protected void computeExecute() { int selectedIndex = computeBox.getSelectedIndex(); switch(selectedIndex) { case 0: screenPanel.graphPanel.showCluster(); case 1: screenPanel.graphPanel.showCentrality(); } } protected void showGeneratorSim() { int genIndex = genAlgorithmsBox.getSelectedIndex(); data.getNodeFactory().setLastID(0); data.getEdgeFactory().setLastID(0); switch(genIndex) { case 0: showKleinbergSim(); break; case 1: showBASim(); break; } if(simTiesCheck.isSelected()) Network.simulateInterpersonalTies(data.getGraph(), data.getEdgeFactory(), (double) simTiesPSpinner.getValue()); screenPanel.graphPanel.reloadGraph(); } protected void showAbout() { JLabel nameLabel = new JLabel("Kyle Russell 2015", SwingConstants.CENTER); JLabel locLabel = new JLabel("AUT University"); JLabel repoLabel = new JLabel("https://github.com/denkers/graphi"); JPanel aboutPanel = new JPanel(); aboutPanel.setLayout(new BoxLayout(aboutPanel, BoxLayout.Y_AXIS)); aboutPanel.add(nameLabel); aboutPanel.add(locLabel); aboutPanel.add(repoLabel); JOptionPane.showMessageDialog(null, aboutPanel, "Graphi - Author", JOptionPane.INFORMATION_MESSAGE); } protected void resetSim() { data.setGraph(new SparseMultigraph()); screenPanel.graphPanel.reloadGraph(); } protected void showKleinbergSim() { int latticeSize = (int) latticeSpinner.getValue(); int clusterExp = (int) clusteringSpinner.getValue(); data.setGraph(Network.generateKleinberg(latticeSize, clusterExp, data.getNodeFactory(), data.getEdgeFactory())); } protected void showBASim() { int m = (int) initialNSpinner.getValue(); int n = (int) addNSpinner.getValue(); data.setGraph(Network.generateBerbasiAlbert(data.getNodeFactory(), data.getEdgeFactory(), n, m)); } protected void showVertexBGChange() { Color selectedColour = JColorChooser.showDialog(null, "Choose vertex colour", Color.BLACK); if(selectedColour != null) screenPanel.graphPanel.setVertexColour(selectedColour, null); } protected void showEdgeBGChange() { Color selectedColour = JColorChooser.showDialog(null, "Choose edge colour", Color.BLACK); if(selectedColour != null) screenPanel.graphPanel.setEdgeColour(selectedColour, null); } protected void showViewerBGChange() { Color selectedColour = JColorChooser.showDialog(null, "Choose viewer background colour", Color.WHITE); if(selectedColour != null) screenPanel.graphPanel.gViewer.setBackground(selectedColour); } // IO PANEL protected class IOPanel extends JPanel implements ActionListener { protected JButton exportBtn, importBtn; protected JLabel currentStorageLabel; protected ButtonGroup storageGroup; protected JRadioButton storageGraphRadio, storageLogRadio, storageScriptRadio; protected JCheckBox directedCheck; protected JPanel directedCheckWrapper; public IOPanel() { setLayout(new GridLayout(4, 1)); setBorder(BorderFactory.createTitledBorder("I/O Controls")); currentStorageLabel = new JLabel("None"); importBtn = new JButton("Import"); exportBtn = new JButton("Export"); storageGroup = new ButtonGroup(); storageGraphRadio = new JRadioButton("Graph"); storageLogRadio = new JRadioButton("Log"); storageScriptRadio = new JRadioButton("Script"); directedCheck = new JCheckBox("Directed"); importBtn.setIcon(new ImageIcon(openIcon)); exportBtn.setIcon(new ImageIcon(saveIcon)); storageGroup.add(storageGraphRadio); storageGroup.add(storageLogRadio); storageGroup.add(storageScriptRadio); importBtn.addActionListener(this); exportBtn.addActionListener(this); storageGraphRadio.addActionListener(this); storageLogRadio.addActionListener(this); storageScriptRadio.addActionListener(this); importBtn.setBackground(Color.WHITE); exportBtn.setBackground(Color.WHITE); storageGraphRadio.setSelected(true); JPanel storageBtnWrapper = wrapComponents(null, importBtn, exportBtn); JPanel currentGraphWrapper = wrapComponents(null, new JLabel("Active: "), currentStorageLabel); JPanel storageOptsWrapper = wrapComponents(null, storageGraphRadio, storageLogRadio, storageScriptRadio); directedCheckWrapper = wrapComponents(null, directedCheck); storageBtnWrapper.setBackground(PRESET_BG); currentGraphWrapper.setBackground(PRESET_BG); storageOptsWrapper.setBackground(PRESET_BG); directedCheckWrapper.setBackground(PRESET_BG); add(currentGraphWrapper); add(storageOptsWrapper); add(directedCheckWrapper); add(storageBtnWrapper); currentStorageLabel.setFont(new Font("Arial", Font.BOLD, 12)); } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == importBtn) { if(storageGraphRadio.isSelected()) importGraph(); else if(storageLogRadio.isSelected()) importLog(); else if(storageScriptRadio.isSelected()) importScript(); } else if(src == exportBtn) { if(storageGraphRadio.isSelected()) exportGraph(); else if(storageLogRadio.isSelected()) exportLog(); else if(storageScriptRadio.isSelected()) exportScript(); } else if(src == storageGraphRadio || src == storageLogRadio || src == storageScriptRadio) directedCheckWrapper.setVisible(storageGraphRadio.isSelected()); } } protected void showCurrentComputePanel() { int selectedIndex = computeBox.getSelectedIndex(); String card; switch(selectedIndex) { case 0: card = CLUSTER_PANEL_CARD; break; case 1: card = CENTRALITY_PANEL_CARD; break; case 2: card = SPATH_PANEL_CARD; break; default: return; } CardLayout clusterInnerLayout = (CardLayout) computeInnerPanel.getLayout(); clusterInnerLayout.show(computeInnerPanel, card); } protected void showSimPanel() { int selectedIndex = genAlgorithmsBox.getSelectedIndex(); String card; switch(selectedIndex) { case 0: card = KL_PANEL_CARD; break; case 1: card = BA_PANEL_CARD; break; default: return; } CardLayout gLayout = (CardLayout) genPanel.getLayout(); gLayout.show(genPanel, card); } protected void exportGraph() { File file = getFile(false, "Graphi .graph, adjacency matrix .txt, .gml, graphML .xml", "graph", "txt", "gml", "xml"); String extension = getFileExtension(file); if(file != null && data.getGraph() != null) { if(extension.equalsIgnoreCase("graph")) Storage.saveObj(data.getGraph(), file); else if(extension.equalsIgnoreCase("txt")) AdjMatrixParser.exportGraph(data.getGraph(), file, ioPanel.directedCheck.isSelected()); else if(extension.equalsIgnoreCase("gml")) GMLParser.exportGraph(data.getGraph(), file, ioPanel.directedCheck.isSelected()); else if(extension.equalsIgnoreCase("xml")) GraphMLParser.exportGraph(file, data.getGraph()); } } protected void importGraph() { File file = getFile(true, "Graphi .graph, adjacency matrix .txt, .gml, graphML .xml", "graph", "txt", "gml", "xml"); String extension = getFileExtension(file); if(file != null) { data.getNodeFactory().setLastID(0); data.getEdgeFactory().setLastID(0); if(extension.equalsIgnoreCase("graph")) data.setGraph((Graph) Storage.openObj(file)); else if(extension.equalsIgnoreCase("txt")) data.setGraph(AdjMatrixParser.importGraph(file, ioPanel.directedCheck.isSelected(), data.getNodeFactory(), data.getEdgeFactory())); else if(extension.equalsIgnoreCase("gml")) data.setGraph(GMLParser.importGraph(file, data.getNodeFactory(), data.getEdgeFactory())); else if(extension.equalsIgnoreCase("xml")) data.setGraph(GraphMLParser.importGraph(file, data.getNodeFactory(), data.getEdgeFactory())); ioPanel.currentStorageLabel.setText(file.getName()); initCurrentNodes(); initCurrentEdges(); screenPanel.graphPanel.gLayout.setGraph(data.getGraph()); screenPanel.graphPanel.gViewer.repaint(); screenPanel.dataPanel.loadNodes(data.getGraph()); screenPanel.dataPanel.loadEdges(data.getGraph()); } } protected void importScript() { File file = getFile(true, "Graphi .gscript file", "gscript"); if(file != null) { screenPanel.graphPanel.gPlayback = (GraphPlayback) Storage.openObj(file); ioPanel.currentStorageLabel.setText(file.getName()); activeScriptLabel.setText(file.getName()); screenPanel.graphPanel.addPlaybackEntries(); } } protected void exportScript() { File file = getFile(false, "Graphi .gscript file", "gscript"); if(file != null) Storage.saveObj(screenPanel.graphPanel.gPlayback, file); } protected void initCurrentNodes() { if(data.getGraph() == null) return; data.getNodes().clear(); Collection<Node> nodes = data.getGraph().getVertices(); for(Node node : nodes) data.getNodes().put(node.getID(), node); } protected void initCurrentEdges() { if(data.getGraph() == null) return; data.getEdges().clear(); Collection<Edge> edges = data.getGraph().getEdges(); for(Edge edge : edges) data.getEdges().put(edge.getID(), edge); } protected void exportLog() { File file = getFile(false, "Graphi .log file", "log"); if(file != null) Storage.saveOutputLog(screenPanel.outputPanel.outputArea.getText(), file); } protected void importLog() { File file = getFile(true, "Graphi .log file", "log"); if(file != null) { ioPanel.currentStorageLabel.setText(file.getName()); screenPanel.outputPanel.outputArea.setText(Storage.openOutputLog(file)); } } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == computeBox) showCurrentComputePanel(); else if(src == gObjAddBtn) { if(editVertexRadio.isSelected()) screenPanel.dataPanel.addVertex(); else screenPanel.dataPanel.addEdge(); } else if(src == gObjEditBtn) { if(editVertexRadio.isSelected()) screenPanel.dataPanel.editVertex(); else screenPanel.dataPanel.editEdge(); } else if(src == gObjRemoveBtn) { if(editVertexRadio.isSelected()) screenPanel.dataPanel.removeVertex(); else screenPanel.dataPanel.removeEdge(); } else if(src == editCheck) { screenPanel.graphPanel.mouse.setMode(ModalGraphMouse.Mode.EDITING); screenPanel.graphPanel.mouse.remove(screenPanel.graphPanel.mouse.getPopupEditingPlugin()); } else if(src == moveCheck) screenPanel.graphPanel.mouse.setMode(ModalGraphMouse.Mode.TRANSFORMING); else if(src == selectCheck) screenPanel.graphPanel.mouse.setMode(ModalGraphMouse.Mode.PICKING); else if(src == executeGeneratorBtn) showGeneratorSim(); else if(src == resetGeneratorBtn) resetSim(); else if(src == computeBtn) computeExecute(); else if(src == genAlgorithmsBox) showSimPanel(); else if(src == vertexBGBtn) showVertexBGChange(); else if(src == edgeBGBtn) showEdgeBGChange(); else if(src == viewerBGBtn) showViewerBGChange(); else if(src == viewerVLabelsCheck) screenPanel.graphPanel.showVertexLabels(viewerVLabelsCheck.isSelected()); else if(src == viewerELabelsCheck) screenPanel.graphPanel.showEdgeLabels(viewerELabelsCheck.isSelected()); else if(src == menu.aboutItem) showAbout(); else if(src == menu.exitItem) System.exit(0); else if(src == menu.miniItem) frame.setState(JFrame.ICONIFIED); else if(src == menu.maxItem) frame.setExtendedState(JFrame.MAXIMIZED_BOTH); else if(src == menu.importGraphItem) importGraph(); else if(src == menu.exportGraphItem) exportGraph(); else if(src == menu.importLogItem) importLog(); else if(src == menu.exportLogItem) exportLog(); else if(src == menu.vLabelsItem) screenPanel.graphPanel.showVertexLabels(true); else if(src == menu.eLabelsItem) screenPanel.graphPanel.showEdgeLabels(true); else if(src == menu.viewerBGItem) showViewerBGChange(); else if(src == menu.edgeBGItem) showEdgeBGChange(); else if(src == menu.vertexBGItem) showVertexBGChange(); else if(src == menu.clearLogItem) screenPanel.outputPanel.clearLog(); else if(src == menu.resetGraphItem) screenPanel.graphPanel.resetGraph(); else if(src == menu.addVertexItem) screenPanel.dataPanel.addVertex(); else if(src == menu.editVertexItem) screenPanel.dataPanel.editVertex(); else if(src == menu.removeVertexItem) screenPanel.dataPanel.removeVertex(); else if(src == menu.addEdgeItem) screenPanel.dataPanel.addEdge(); else if(src == menu.editEdgeItem) screenPanel.dataPanel.editEdge(); else if(src == menu.removeEdgeItem) screenPanel.dataPanel.removeEdge(); else if(src == displayCtrlsBtn) screenPanel.graphPanel.changePlaybackPanel(screenPanel.graphPanel.PLAYBACK_CARD); else if(src == recordCtrlsBtn) screenPanel.graphPanel.changePlaybackPanel(screenPanel.graphPanel.RECORD_CARD); else if(src == simTiesCheck) { simTiesPSpinner.setVisible(!simTiesPSpinner.isVisible()); simTiesPLabel.setVisible(!simTiesPLabel.isVisible()); } } } // SCREEN PANEL protected class ScreenPanel extends JPanel { protected final DataPanel dataPanel; protected final GraphPanel graphPanel; protected final OutputPanel outputPanel; protected final JTabbedPane tabPane; public ScreenPanel() { setLayout(new BorderLayout()); setBorder(BorderFactory.createEmptyBorder(15, 5, 5, 5)); tabPane = new JTabbedPane(); dataPanel = new DataPanel(); graphPanel = new GraphPanel(); outputPanel = new OutputPanel(); tabPane.addTab("", graphPanel); tabPane.addTab("", dataPanel); tabPane.addTab("", outputPanel); JLabel dispLabel = new JLabel("Display", JLabel.CENTER); JLabel dataLabel = new JLabel("Data", JLabel.CENTER); JLabel outLabel = new JLabel("Output", JLabel.CENTER); dispLabel.setIcon(new ImageIcon(graphIcon)); outLabel.setIcon(new ImageIcon(clipIcon)); dataLabel.setIcon(new ImageIcon(tableIcon)); tabPane.setTabComponentAt(0, dispLabel); tabPane.setTabComponentAt(1, dataLabel); tabPane.setTabComponentAt(2, outLabel); add(tabPane); } protected class DataPanel extends JPanel { protected final JTable vertexTable, edgeTable; protected final DefaultTableModel vertexDataModel, edgeDataModel; protected final JTabbedPane dataTabPane; protected final JScrollPane vertexScroller, edgeScroller; public DataPanel() { setLayout(new BorderLayout()); dataTabPane = new JTabbedPane(); vertexDataModel = new DefaultTableModel(); vertexTable = new JTable(vertexDataModel) { @Override public boolean isCellEditable(int row, int col) { return false; }; }; edgeDataModel = new DefaultTableModel(); edgeTable = new JTable(edgeDataModel) { @Override public boolean isCellEditable(int row, int col) { return false; } }; vertexScroller = new JScrollPane(vertexTable); edgeScroller = new JScrollPane(edgeTable); vertexTable.setPreferredScrollableViewportSize(new Dimension(630, 500)); vertexDataModel.addColumn("ID"); vertexDataModel.addColumn("Name"); edgeDataModel.addColumn("ID"); edgeDataModel.addColumn("FromVertex"); edgeDataModel.addColumn("ToVertex"); edgeDataModel.addColumn("Weight"); edgeDataModel.addColumn("EdgeType"); dataTabPane.addTab("Vertex table", vertexScroller); dataTabPane.addTab("Edge table", edgeScroller); add(dataTabPane); } protected void loadNodes(Graph graph) { ArrayList<Node> vertices = new ArrayList<>(graph.getVertices()); Collections.sort(vertices, (Node n1, Node n2) -> Integer.compare(n1.getID(), n2.getID())); data.getNodeFactory().setLastID(0); data.getNodes().clear(); SwingUtilities.invokeLater(() -> { vertexDataModel.setRowCount(0); for(Node vertex : vertices) { int vID = vertex.getID(); String vName = vertex.getName(); data.getNodes().put(vID, vertex); vertexDataModel.addRow(new Object[] { vID, vName }); if(vID > data.getNodeFactory().getLastID()) data.getNodeFactory().setLastID(vID); } }); } protected void loadEdges(Graph graph) { ArrayList<Edge> edges = new ArrayList<>(graph.getEdges()); Collections.sort(edges, (Edge e1, Edge e2) -> Integer.compare(e1.getID(), e2.getID())); //data.getEdgeFactory().setLastID(0); data.getEdges().clear(); SwingUtilities.invokeLater(() -> { edgeDataModel.setRowCount(0); for(Edge edge : edges) { int eID = edge.getID(); double weight = edge.getWeight(); Collection<Node> vertices = graph.getIncidentVertices(edge); String edgeType = graph.getEdgeType(edge).toString(); Node n1, n2; int n1_id, n2_id; Iterator<Node> iter = vertices.iterator(); n1 = iter.next(); n2 = iter.next(); edge.setSourceNode(n1); edge.setDestNode(n2); if(n1 != null) n1_id = n1.getID(); else n1_id = -1; if(n2 != null) n2_id = n2.getID(); else n2_id = -1; data.getEdges().put(eID, edge); edgeDataModel.addRow(new Object[] { eID, n1_id, n2_id, weight, edgeType }); if(eID > data.getEdgeFactory().getLastID()) data.getEdgeFactory().setLastID(eID); } }); } protected void addVertex() { VertexAddPanel addPanel = new VertexAddPanel(); int option = JOptionPane.showConfirmDialog(null, addPanel, "Add vertex", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { int id = (int) addPanel.idSpinner.getValue(); if(data.getNodes().containsKey(id)) { JOptionPane.showMessageDialog(null, "Vertex already exists"); return; } String name = addPanel.nameField.getText(); Node node = new Node(id, name); data.getGraph().addVertex(node); graphPanel.gViewer.repaint(); loadNodes(data.getGraph()); data.getNodes().put(id, node); } } protected void editVertex() { Node editNode; Set<Node> selectedVertices = graphPanel.gViewer.getPickedVertexState().getPicked(); if(selectedVertices.size() == 1) editNode = selectedVertices.iterator().next(); else { int[] selectedRows = dataPanel.vertexTable.getSelectedRows(); if(selectedRows.length == 1) { int id = (int) dataPanel.vertexDataModel.getValueAt(selectedRows[0], 0); editNode = data.getNodes().get(id); } else { int id = getDialogID("Enter vertex ID to edit", data.getNodes()); if(id != -1) editNode = data.getNodes().get(id); else return; } } VertexAddPanel editPanel = new VertexAddPanel(); editPanel.idSpinner.setValue(editNode.getID()); editPanel.nameField.setText(editNode.getName()); editPanel.idSpinner.setEnabled(false); editPanel.autoCheck.setVisible(false); int option = JOptionPane.showConfirmDialog(null, editPanel, "Edit vertex", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { editNode.setID((int) editPanel.idSpinner.getValue()); editNode.setName(editPanel.nameField.getText()); loadNodes(data.getGraph()); } } protected void removeVertices(Set<Node> vertices) { if(vertices.isEmpty()) return; for(Node node : vertices) { int id = node.getID(); data.getNodes().remove(id); data.getGraph().removeVertex(node); graphPanel.gViewer.repaint(); loadNodes(data.getGraph()); } } protected void removeVertex() { Set<Node> pickedNodes = graphPanel.gViewer.getPickedVertexState().getPicked(); if(!pickedNodes.isEmpty()) removeVertices(pickedNodes); else { int[] selectedRows = dataPanel.vertexTable.getSelectedRows(); if(selectedRows.length > 0) { Set<Node> selectedNodes = new HashSet<>(); for(int row : selectedRows) { int id = (int) dataPanel.vertexDataModel.getValueAt(row, 0); Node current = data.getNodes().get(id); if(current != null) selectedNodes.add(current); } removeVertices(selectedNodes); } else { int id = getDialogID("Enter vertex ID to remove", data.getNodes()); if(id != -1) { Node removedNode = data.getNodes().remove(id); data.getGraph().removeVertex(removedNode); loadNodes(data.getGraph()); graphPanel.gViewer.repaint(); } } } } protected void addEdge() { EdgeAddPanel addPanel = new EdgeAddPanel(); int option = JOptionPane.showConfirmDialog(null, addPanel, "Add edge", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { int id = (int) addPanel.idSpinner.getValue(); if(data.getEdges().containsKey(id)) { JOptionPane.showMessageDialog(null, "Edge ID already exists"); return; } int fromID = (int) addPanel.fromSpinner.getValue(); int toID = (int) addPanel.toSpinner.getValue(); double weight = (double) addPanel.weightSpinner.getValue(); int eType = addPanel.edgeTypeBox.getSelectedIndex(); EdgeType edgeType = (eType == 0)? EdgeType.UNDIRECTED : EdgeType.DIRECTED; if(data.getNodes().containsKey(fromID) && data.getNodes().containsKey(toID)) { Edge edge = new Edge(id, weight, edgeType); Node n1 = data.getNodes().get(fromID); Node n2 = data.getNodes().get(toID); edge.setSourceNode(n1); edge.setDestNode(n2); data.getEdges().put(id, edge); data.getGraph().addEdge(edge, n1, n2, edgeType); loadEdges(data.getGraph()); graphPanel.gViewer.repaint(); } else JOptionPane.showMessageDialog(null, "Vertex ID does not exist"); } } protected void editEdge() { Edge editEdge; Set<Edge> selectedEdges = graphPanel.gViewer.getPickedEdgeState().getPicked(); if(selectedEdges.size() == 1) editEdge = selectedEdges.iterator().next(); else { int[] selectedRows = dataPanel.edgeTable.getSelectedRows(); if(selectedRows.length == 1) { int id = (int) dataPanel.edgeDataModel.getValueAt(selectedRows[0], 0); editEdge = data.getEdges().get(id); } else { int id = getDialogID("Enter edge ID to edit", data.getEdges()); if(id != -1) editEdge = data.getEdges().get(id); else return; } } EdgeAddPanel editPanel = new EdgeAddPanel(); editPanel.idSpinner.setValue(editEdge.getID()); editPanel.fromSpinner.setValue(editEdge.getSourceNode().getID()); editPanel.toSpinner.setValue(editEdge.getDestNode().getID()); editPanel.weightSpinner.setValue(editEdge.getWeight()); editPanel.edgeTypeBox.setSelectedIndex(editEdge.getEdgeType() == EdgeType.UNDIRECTED? 0 : 1); editPanel.idSpinner.setEnabled(false); editPanel.autoCheck.setVisible(false); int option = JOptionPane.showConfirmDialog(null, editPanel, "Edit edge", JOptionPane.OK_CANCEL_OPTION); if(option == JOptionPane.OK_OPTION) { editEdge.setWeight((double) editPanel.weightSpinner.getValue()); editEdge.setEdgeType(editPanel.edgeTypeBox.getSelectedIndex() == 0? EdgeType.UNDIRECTED : EdgeType.DIRECTED); Node from = data.getNodes().get(Integer.parseInt(editPanel.fromSpinner.getValue().toString())); Node to = data.getNodes().get(Integer.parseInt(editPanel.toSpinner.getValue().toString())); editEdge.setSourceNode(from); editEdge.setDestNode(to); data.getGraph().removeEdge(editEdge); data.getGraph().addEdge(editEdge, from, to, editEdge.getEdgeType()); loadEdges(data.getGraph()); graphPanel.gViewer.repaint(); } } protected void removeEdge() { Set<Edge> selectedEdges = graphPanel.gViewer.getPickedEdgeState().getPicked(); if(selectedEdges.isEmpty()) { int[] selectedRows = dataPanel.edgeTable.getSelectedRows(); if(selectedRows.length > 0) { for(int row : selectedRows) { int id = (int) dataPanel.edgeDataModel.getValueAt(row, 0); Edge current = data.getEdges().remove(id); data.getGraph().removeEdge(current); } } else { int id = getDialogID("Enter edge ID to remove", data.getEdges()); if(id != -1) { Edge removeEdge = data.getEdges().remove(id); data.getGraph().removeEdge(removeEdge); } else return; } } else { for(Edge edge : selectedEdges) { data.getEdges().remove(edge.getID()); data.getGraph().removeEdge(edge); } } loadEdges(data.getGraph()); graphPanel.gViewer.repaint(); } protected int getDialogID(String message, Map collection) { String idStr = JOptionPane.showInputDialog(message); int id = -1; while(idStr != null && id == -1) { try { id = Integer.parseInt(idStr); if(collection.containsKey(id)) break; else { id = -1; JOptionPane.showMessageDialog(null, "ID was not found"); idStr = JOptionPane.showInputDialog(message); } } catch(NumberFormatException e) { JOptionPane.showMessageDialog(null, "Invalid input found"); idStr = JOptionPane.showInputDialog(message); } } return id; } // VERTEX ADD PANEL protected class VertexAddPanel extends JPanel implements ActionListener { protected JSpinner idSpinner; protected JCheckBox autoCheck; protected JTextField nameField; public VertexAddPanel() { setLayout(new MigLayout()); idSpinner = new JSpinner(new SpinnerNumberModel(0, 0, 10000, 1)); autoCheck = new JCheckBox("Auto"); nameField = new JTextField(); autoCheck.setSelected(true); idSpinner.setValue(data.getNodeFactory().getLastID() + 1); idSpinner.setEnabled(false); add(new JLabel("ID ")); add(idSpinner, "width :40:"); add(autoCheck, "wrap"); add(new JLabel("Name: ")); add(nameField, "span 3, width :100:"); autoCheck.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == autoCheck) idSpinner.setEnabled(!autoCheck.isSelected()); } } // EDGE ADD PANEL protected class EdgeAddPanel extends JPanel implements ActionListener { protected JSpinner idSpinner, fromSpinner, toSpinner, weightSpinner; protected JCheckBox autoCheck; protected JComboBox edgeTypeBox; public EdgeAddPanel() { setLayout(new MigLayout()); idSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); fromSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); toSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1)); weightSpinner = new JSpinner(new SpinnerNumberModel(0.0, 0.0, 10000.0, 0.1)); autoCheck = new JCheckBox("Auto"); edgeTypeBox = new JComboBox(); edgeTypeBox.addItem("Undirected"); edgeTypeBox.addItem("Directed"); idSpinner.setValue(data.getEdgeFactory().getLastID() + 1); idSpinner.setEnabled(false); autoCheck.setSelected(true); autoCheck.addActionListener(this); add(new JLabel("ID ")); add(idSpinner, "width :40:"); add(autoCheck, "wrap"); add(new JLabel("From vertex ID")); add(fromSpinner, "span 2, width :40:, wrap"); add(new JLabel("To vertex ID")); add(toSpinner, "span 2, width :40:, wrap"); add(new JLabel("Weight")); add(weightSpinner, "span 2, width :70:, wrap"); add(new JLabel("Type")); add(edgeTypeBox, "span 2"); } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == autoCheck) idSpinner.setEnabled(!autoCheck.isSelected()); } } } // GRAPH PANEL protected class GraphPanel extends JPanel implements ItemListener, GraphMouseListener, ActionListener, ChangeListener { protected final String RECORD_CARD = "rec"; protected final String PLAYBACK_CARD = "pb"; protected final int INITIAL_DELAY = 500; protected final VisualizationViewer<Node, Edge> gViewer; protected AggregateLayout<Node, Edge> gLayout; protected EditingModalGraphMouse mouse; protected GraphPlayback gPlayback; protected JPanel gpControlsWrapper; protected JPanel gpControlsPanel; protected JButton gpCtrlsClose; protected JPanel pbControls; protected JButton pbToggle; protected JSlider pbProgress; protected JSpinner pbProgressSpeed; protected JLabel pbName, pbDate; protected boolean pbPlaying; protected JPanel gpRecControls; protected JButton gpRecSaveBtn; protected JButton gpRecRemoveBtn; protected JTextField gpRecEntryName; protected DateComboBox gpRecDatePicker; protected JComboBox gpRecEntries; public GraphPanel() { setLayout(new BorderLayout()); gLayout = new AggregateLayout(new FRLayout(data.getGraph())); gViewer = new VisualizationViewer<>(gLayout); gPlayback = new GraphPlayback(); ScalingControl scaler = new CrossoverScalingControl(); scaler.scale(gViewer, 0.7f, gViewer.getCenter()); gViewer.scaleToLayout(scaler); gViewer.setBackground(Color.WHITE); gViewer.getRenderContext().setVertexFillPaintTransformer(new ObjectFillTransformer<>(gViewer.getPickedVertexState())); gViewer.getRenderContext().setEdgeDrawPaintTransformer(new ObjectFillTransformer(gViewer.getPickedEdgeState())); gViewer.getPickedVertexState().addItemListener(this); gViewer.getPickedEdgeState().addItemListener(this); mouse = new EditingModalGraphMouse(gViewer.getRenderContext(), data.getNodeFactory(), data.getEdgeFactory()); mouse.setMode(ModalGraphMouse.Mode.PICKING); gViewer.addGraphMouseListener(this); mouse.remove(mouse.getPopupEditingPlugin()); gViewer.setGraphMouse(mouse); pbControls = new JPanel(new MigLayout("fillx")); pbToggle = new JButton("Play"); pbProgress = new JSlider(); pbProgressSpeed = new JSpinner(new SpinnerNumberModel(0, 0, 10000, 1)); pbName = new JLabel("N/A"); pbDate = new JLabel("N/A"); pbPlaying = false; pbToggle.setIcon(new ImageIcon(playIcon)); pbProgress.addChangeListener(this); pbProgressSpeed.addChangeListener(this); pbProgressSpeed.setValue(INITIAL_DELAY); pbProgress.setPaintTicks(true); pbProgress.setValue(0); pbProgress.setMinimum(0); pbProgress.setPaintTrack(true); pbToggle.addActionListener(this); pbName.setFont(new Font("Arial", Font.BOLD, 12)); pbDate.setFont(new Font("Arial", Font.BOLD, 12)); JPanel pbInnerWrapper = new JPanel(); pbInnerWrapper.add(pbToggle); pbInnerWrapper.add(new JLabel("Speed")); pbInnerWrapper.add(pbProgressSpeed); JPanel pbInfoWrapper = new JPanel(new MigLayout()); pbInfoWrapper.add(new JLabel("Name: ")); pbInfoWrapper.add(pbName, "wrap"); pbInfoWrapper.add(new JLabel("Timestamp: ")); pbInfoWrapper.add(pbDate); pbControls.add(pbProgress, "al center, wrap"); pbControls.add(pbInnerWrapper, "al center, wrap"); pbControls.add(pbInfoWrapper, "al center"); JPanel pbControlsWrapper = new JPanel(new BorderLayout()); pbControlsWrapper.add(pbControls); gpRecControls = new JPanel(new MigLayout("fillx")); gpRecSaveBtn = new JButton("Save entry"); gpRecRemoveBtn = new JButton("Remove entry"); gpRecDatePicker = new DateComboBox(); gpRecEntryName = new JTextField(); gpRecEntries = new JComboBox(); gpRecEntries.setPreferredSize(new Dimension(120, 20)); gpRecEntryName.setPreferredSize(new Dimension(120, 20)); gpRecSaveBtn.setIcon(new ImageIcon(addIcon)); gpRecRemoveBtn.setIcon(new ImageIcon(removeIcon)); gpRecEntries.addItem("-- New entry --"); JPanel gpRecInnerWrapper = new JPanel(new MigLayout()); gpRecInnerWrapper.add(gpRecSaveBtn); gpRecInnerWrapper.add(gpRecRemoveBtn); gpRecInnerWrapper.add(new JLabel("Entries")); gpRecInnerWrapper.add(gpRecEntries, "wrap"); gpRecInnerWrapper.add(new JLabel("Entry date")); gpRecInnerWrapper.add(gpRecDatePicker, "wrap"); gpRecInnerWrapper.add(new JLabel("Entry name (optional)")); gpRecInnerWrapper.add(gpRecEntryName, "span 2"); gpRecControls.add(gpRecInnerWrapper, "al center"); JPanel gpRecWrapper = new JPanel(new BorderLayout()); gpRecWrapper.add(gpRecControls); gpControlsWrapper = new JPanel(new CardLayout()); gpControlsWrapper.add(pbControlsWrapper, PLAYBACK_CARD); gpControlsWrapper.add(gpRecWrapper, RECORD_CARD); gpControlsPanel = new JPanel(new BorderLayout()); gpCtrlsClose = new JButton("Close"); JPanel gpControlsExitPanel = new JPanel(); gpCtrlsClose.setIcon(new ImageIcon(closeIcon)); gpControlsExitPanel.add(gpCtrlsClose); gpControlsPanel.add(gpControlsWrapper, BorderLayout.CENTER); gpControlsPanel.add(gpControlsExitPanel, BorderLayout.EAST); gpControlsPanel.setVisible(false); gpRecSaveBtn.addActionListener(this); gpRecRemoveBtn.addActionListener(this); gpRecEntries.addActionListener(this); gpCtrlsClose.addActionListener(this); add(gViewer, BorderLayout.CENTER); add(gpControlsPanel, BorderLayout.SOUTH); } protected void addPlaybackEntries() { gpRecEntries.removeAllItems(); gpRecEntries.addItem("-- New entry --"); List<PlaybackEntry> entries = gPlayback.getEntries(); for(PlaybackEntry entry : entries) gpRecEntries.addItem(entry); gpRecEntries.setSelectedIndex(0); } protected void changePlaybackPanel(String card) { CardLayout cLayout = (CardLayout) gpControlsWrapper.getLayout(); cLayout.show(gpControlsWrapper, card); if(card.equals(PLAYBACK_CARD)) { pbProgress.setMinimum(0); pbProgress.setValue(0); pbProgress.setMaximum(gPlayback.getSize() - 1); } gpControlsPanel.setVisible(true); } protected final Timer PB_TIMER = new Timer(INITIAL_DELAY, (ActionEvent e) -> { if(gPlayback.hasNext()) pbProgress.setValue(pbProgress.getValue() + 1); else togglePlayback(); }); protected void startPlayback() { pbProgress.setMinimum(0); pbProgress.setMaximum(gPlayback.getSize() - 1); if(pbProgress.getValue() == pbProgress.getMaximum()) { gPlayback.setIndex(0); pbProgress.setValue(0); } PB_TIMER.setRepeats(true); PB_TIMER.start(); PB_TIMER.setDelay((int) pbProgressSpeed.getValue()); } protected void stopPlayback() { PB_TIMER.stop(); } protected void addRecordedGraph() { PlaybackEntry entry; int selectedIndex = gpRecEntries.getSelectedIndex(); if(selectedIndex == 0) { Graph<Node, Edge> graph = new SparseMultigraph<>(); GraphUtilities.copyGraph(data.getGraph(), graph); Date date = gpRecDatePicker.getDate(); String name = gpRecEntryName.getText(); if(name.equals("")) entry = new PlaybackEntry(graph, date); else entry = new PlaybackEntry(graph, date, name); gPlayback.add(entry); gpRecEntries.addItem(entry); gpRecEntryName.setText(""); } else { entry = (PlaybackEntry) gpRecEntries.getSelectedItem(); entry.setName(gpRecEntryName.getText()); entry.setDate(gpRecDatePicker.getDate()); entry.setGraph(GraphUtilities.copyNewGraph(data.getGraph())); } } protected void togglePlayback() { if(pbPlaying) { pbPlaying = false; pbToggle.setIcon(new ImageIcon(playIcon)); pbToggle.setText("Play"); stopPlayback(); } else { pbPlaying = true; pbToggle.setIcon(new ImageIcon(stopIcon)); pbToggle.setText("Stop"); startPlayback(); } } protected void displayRecordedGraph() { int selectedIndex = gpRecEntries.getSelectedIndex(); if(selectedIndex != 0) { PlaybackEntry entry = (PlaybackEntry) gpRecEntries.getSelectedItem(); if(entry != null) { gpRecEntryName.setText(entry.getName()); gpRecDatePicker.setDate(entry.getDate()); data.setGraph(GraphUtilities.copyNewGraph(entry.getGraph())); reloadGraph(); } } else { gpRecEntryName.setText(""); gpRecDatePicker.setDate(new Date()); } } protected void removeRecordedGraph() { int selectedIndex = gpRecEntries.getSelectedIndex(); if(selectedIndex != 0) { PlaybackEntry entry = (PlaybackEntry) gpRecEntries.getSelectedItem(); gPlayback.remove(entry); gpRecEntries.removeItemAt(selectedIndex); gpRecEntries.setSelectedIndex(0); gpRecEntryName.setText(""); gpRecDatePicker.setDate(new Date()); } } @Override public void graphClicked(Object v, MouseEvent me) {} @Override public void graphPressed(Object v, MouseEvent me) {} @Override public void graphReleased(Object v, MouseEvent me) { if(controlPanel.editCheck.isSelected()) { dataPanel.loadNodes(data.getGraph()); dataPanel.loadEdges(data.getGraph()); } } @Override public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src == gpRecSaveBtn) addRecordedGraph(); else if(src == gpRecRemoveBtn) removeRecordedGraph(); else if(src == gpRecEntries) displayRecordedGraph(); else if(src == pbToggle) togglePlayback(); else if(src == gpCtrlsClose) gpControlsPanel.setVisible(false); } @Override public void stateChanged(ChangeEvent e) { Object src = e.getSource(); if(src == pbProgressSpeed) PB_TIMER.setDelay((int) pbProgressSpeed.getValue()); else if(src == pbProgress) { int index = pbProgress.getValue(); gPlayback.setIndex(index); PlaybackEntry entry = gPlayback.current(); if(entry != null) { pbName.setText(entry.getName()); pbDate.setText(entry.getDateFormatted()); data.setGraph(GraphUtilities.copyNewGraph(entry.getGraph())); reloadGraph(); } } } // CENTRALITY TRANSFORMER protected class CentralityTransformer implements Transformer<Node, Shape> { List<Node> centralNodes; int numRanks; public CentralityTransformer(List<Node> centralNodes, int numRanks) { this.centralNodes = centralNodes; this.numRanks = numRanks; } @Override public Shape transform(Node node) { for(int i = 0; i < numRanks; i++) { if(node.equals(centralNodes.get(i))) { int size = 20 + ((numRanks - i) * 10); return new Ellipse2D.Double(-10, -10, size, size); } } return new Ellipse2D.Double(-10, -10, 20, 20); } } protected void setVertexColour(Color colour, Collection<Node> vertices) { if(vertices == null) vertices = data.getGraph().getVertices(); for(Node vertex : vertices) vertex.setFill(colour); gViewer.repaint(); } protected void setEdgeColour(Color colour, Collection<Edge> edges) { if(edges == null) edges = data.getGraph().getEdges(); for(Edge edge : edges) edge.setFill(colour); gViewer.repaint(); } protected void showVertexLabels(boolean show) { gViewer.getRenderContext().setVertexLabelTransformer(new VertexLabelTransformer(show)); gViewer.repaint(); } protected void showEdgeLabels(boolean show) { gViewer.getRenderContext().setEdgeLabelTransformer(new EdgeLabelTransformer(show)); gViewer.repaint(); } protected void showCluster() { int numRemoved = (int) controlPanel.clusterEdgeRemoveSpinner.getValue(); boolean group = controlPanel.clusterTransformCheck.isSelected(); GraphUtilities.cluster(gLayout, data.getGraph(), numRemoved, group); gViewer.repaint(); } protected void showCentrality() { Map<Node, Double> centrality; if(data.getGraph().getVertexCount() <= 1) return; SparseDoubleMatrix2D matrix = GraphMatrixOperations.graphToSparseMatrix(data.getGraph()); int selectedCentrality = controlPanel.centralityTypeBox.getSelectedIndex(); boolean transform = controlPanel.centralityMorphCheck.isSelected(); String prefix; switch(selectedCentrality) { case 0: centrality = MatrixTools.getScores(MatrixTools.powerIterationFull(matrix), data.getGraph()); prefix = "EigenVector"; break; case 1: centrality = MatrixTools.getScores(new ClosenessCentrality(data.getGraph(), new WeightTransformer()), data.getGraph()); prefix = "Closeness"; break; case 2: centrality = MatrixTools.getScores(new BetweennessCentrality(data.getGraph(), new WeightTransformer()), data.getGraph()); prefix = "Betweenness"; break; default: return; } Collection<Node> vertices = data.getGraph().getVertices(); PriorityQueue<SimpleEntry<Node, Double>> scores = null; if(transform) { scores = new PriorityQueue<>((SimpleEntry<Node, Double> a1, SimpleEntry<Node, Double> a2) -> Double.compare(a2.getValue(), a1.getValue())); } for(Node node : vertices) { double score = centrality.get(node); String output = MessageFormat.format("({0}) Vertex: {1}, Score: {2}", prefix, node.getID(), score); sendToOutput(output); if(transform) scores.add(new SimpleEntry(node, score)); } if(transform) { ArrayList<Node> centralNodes = new ArrayList<>(); Color[] centralColours = new Color[] { Color.RED, Color.ORANGE, Color.BLUE }; for(int i = 0; i < 3; i++) { SimpleEntry<Node, Double> entry = scores.poll(); centralNodes.add(entry.getKey()); entry.getKey().setFill(centralColours[i]); } graphPanel.gViewer.getRenderContext().setVertexShapeTransformer(new CentralityTransformer(centralNodes, 3)); graphPanel.gViewer.repaint(); } } protected void reloadGraph() { gViewer.getPickedVertexState().clear(); gViewer.getPickedEdgeState().clear(); data.setSelectedItems(null); gLayout.removeAll(); gLayout.setGraph(data.getGraph()); gViewer.repaint(); dataPanel.loadNodes(data.getGraph()); dataPanel.loadEdges(data.getGraph()); } protected void resetGraph() { data.setGraph(new SparseMultigraph<>()); reloadGraph(); } @Override public void itemStateChanged(ItemEvent e) { if(controlPanel.selectCheck.isSelected()) { data.setSelectedItems(e.getItemSelectable().getSelectedObjects()); controlPanel.updateSelectedComponents(); } } } // OUTPUT PANEL protected class OutputPanel extends JPanel { protected JTextArea outputArea; public OutputPanel() { setLayout(new BorderLayout()); outputArea = new JTextArea(""); outputArea.setBackground(Color.WHITE); outputArea.setEditable(false); JScrollPane outputScroller = new JScrollPane(outputArea); outputScroller.setPreferredSize(new Dimension(650, 565)); outputScroller.setBorder(null); add(outputScroller); } protected void clearLog() { outputArea.setText(""); } } } }
package com.valkryst.VTerminal.builder; import com.valkryst.VJSON.VJSONParser; import com.valkryst.VTerminal.component.CheckBox; import lombok.Data; import lombok.NoArgsConstructor; import org.json.simple.JSONObject; @Data @NoArgsConstructor public class CheckBoxBuilder extends ButtonBuilder implements VJSONParser { /** The character to display when the check box is not checked. */ private char emptyBoxChar; /** The character to display when the check box is checked. */ private char checkedBoxChar; /** Whether or not the check box is checked. */ private boolean isChecked; @Override public CheckBox build() { checkState(); super.setDimensions(super.getText().length() + 2, 1); super.setText(emptyBoxChar + " " + super.getText()); return new CheckBox(this); } @Override public void reset() { super.reset(); emptyBoxChar = ''; checkedBoxChar = ''; isChecked = false; } @Override public void parse(final JSONObject jsonObject) { if (jsonObject == null) { return; } super.parse(jsonObject); final Character emptyBoxChar = getChar(jsonObject, "emptyBoxChar"); final Character checkedBoxChar = getChar(jsonObject, "checkedBoxChar"); // todo Add isChecked if (emptyBoxChar == null) { throw new NullPointerException("The 'emptyBoxChar' value was not found."); } else { this.emptyBoxChar = emptyBoxChar; } if (checkedBoxChar == null) { throw new NullPointerException("The 'checkedBoxChar' value was not found."); } else { this.checkedBoxChar = checkedBoxChar; } } }
package com.jme.input.action; import com.jme.input.Mouse; import com.jme.input.MouseInput; import com.jme.math.Vector3f; import com.jme.renderer.Camera; /** * <code>MouseLook</code> defines a mouse action that detects mouse movement * and converts it into camera rotations and camera tilts. * * @author Mark Powell * @version $Id: MouseLook.java,v 1.18 2007-08-02 21:38:55 nca Exp $ */ public class MouseLook extends MouseInputAction { //actions to handle looking up down left and right. private KeyLookDownAction lookDown; private KeyLookUpAction lookUp; private KeyRotateLeftAction rotateLeft; private KeyRotateRightAction rotateRight; //the axis to lock. private Vector3f lockAxis; //the event to distribute to the looking actions. private InputActionEvent event; private boolean buttonPressRequired = false; /** * Constructor creates a new <code>MouseLook</code> object. It takes the * mouse, camera and speed of the looking. * * @param mouse * the mouse to calculate view changes. * @param camera * the camera to move. * @param speed * the speed at which to alter the camera. */ public MouseLook(Mouse mouse, Camera camera, float speed) { this.mouse = mouse; this.speed = speed; lookDown = new KeyLookDownAction(camera, speed); lookUp = new KeyLookUpAction(camera, speed); rotateLeft = new KeyRotateLeftAction(camera, speed); rotateRight = new KeyRotateRightAction(camera, speed); event = new InputActionEvent(); } /** * * <code>setLockAxis</code> sets the axis that should be locked down. This * prevents "rolling" about a particular axis. Typically, this is set to the * mouse's up vector. Note this is only a shallow copy. * * @param lockAxis * the axis that should be locked down to prevent rolling. */ public void setLockAxis(Vector3f lockAxis) { this.lockAxis = lockAxis; rotateLeft.setLockAxis(lockAxis); rotateRight.setLockAxis(lockAxis); } /** * Returns the axis that is currently locked. * * @return The currently locked axis * @see #setLockAxis(com.jme.math.Vector3f) */ public Vector3f getLockAxis() { return lockAxis; } /** * * <code>setSpeed</code> sets the speed of the mouse look. * * @param speed * the speed of the mouse look. */ public void setSpeed(float speed) { super.setSpeed( speed ); lookDown.setSpeed(speed); lookUp.setSpeed(speed); rotateRight.setSpeed(speed); rotateLeft.setSpeed(speed); } /** * <code>performAction</code> checks for any movement of the mouse, and * calls the appropriate method to alter the camera's orientation when * applicable. * * @see com.jme.input.action.MouseInputAction#performAction(InputActionEvent) */ public void performAction(InputActionEvent evt) { float time = 0.01f * speed; if(!buttonPressRequired || MouseInput.get().isButtonDown(0)) { if (mouse.getLocalTranslation().x > 0) { event.setTime(time * mouse.getLocalTranslation().x); rotateRight.performAction(event); } else if (mouse.getLocalTranslation().x < 0) { event.setTime(time * mouse.getLocalTranslation().x * -1); rotateLeft.performAction(event); } if (mouse.getLocalTranslation().y > 0) { event.setTime(time * mouse.getLocalTranslation().y); lookUp.performAction(event); } else if (mouse.getLocalTranslation().y < 0) { event.setTime(time * mouse.getLocalTranslation().y * -1); lookDown.performAction(event); } } } public boolean isButtonPressRequired() { return buttonPressRequired; } public void setButtonPressRequired(boolean buttonPressRequired) { this.buttonPressRequired = buttonPressRequired; } }
package org.wyona.yanel.servlet; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.net.URL; import java.util.Enumeration; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.api.attributes.ModifiableV1; import org.wyona.yanel.core.api.attributes.ModifiableV2; import org.wyona.yanel.core.api.attributes.ViewableV1; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.map.Map; import org.wyona.yanel.core.map.MapFactory; import org.wyona.yanel.core.map.Realm; import org.wyona.yanel.util.ResourceAttributeHelper; import org.wyona.security.core.IdentityManagerFactory; import org.wyona.security.core.PolicyManagerFactory; import org.wyona.security.core.api.Identity; import org.wyona.security.core.api.IdentityManager; import org.wyona.security.core.api.PolicyManager; import org.wyona.security.core.api.Role; import org.apache.log4j.Category; import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; public class YanelServlet extends HttpServlet { private static Category log = Category.getInstance(YanelServlet.class); private ServletConfig config; ResourceTypeRegistry rtr; PolicyManager pm; IdentityManager im; Map map; private static String IDENTITY_KEY = "identity"; String proxyServerName = null; String proxyPort = null; String proxyPrefix = null; private static final String METHOD_PROPFIND = "PROPFIND"; private static final String METHOD_GET = "GET"; private static final String METHOD_POST = "POST"; private static final String METHOD_PUT = "PUT"; public void init(ServletConfig config) { this.config = config; rtr = new ResourceTypeRegistry(); PolicyManagerFactory pmf = PolicyManagerFactory.newInstance(); pm = pmf.newPolicyManager(); IdentityManagerFactory imf = IdentityManagerFactory.newInstance(); im = imf.newIdentityManager(); MapFactory mf = MapFactory.newInstance(); map = mf.newMap(); proxyServerName = rtr.proxyHostName; proxyPort = rtr.proxyPort; proxyPrefix = rtr.proxyPrefix; } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String httpAcceptMediaTypes = request.getHeader("Accept"); log.debug("HTTP Accept Media Types: " + httpAcceptMediaTypes); String httpUserAgent = request.getHeader("User-Agent"); log.debug("HTTP User Agent: " + httpUserAgent); String httpAcceptLanguage = request.getHeader("Accept-Language"); log.debug("HTTP Accept Language: " + httpAcceptLanguage); // Logout from Yanel String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("logout")) { if(doLogout(request, response) != null) return; } // Authentication if(doAuthenticate(request, response) != null) return; // Check authorization if(doAuthorize(request, response) != null) return; // Delegate ... String method = request.getMethod(); if (method.equals(METHOD_PROPFIND)) { doPropfind(request, response); } else if (method.equals(METHOD_GET)) { doGet(request, response); } else if (method.equals(METHOD_POST)) { doPost(request, response); } else if (method.equals(METHOD_PUT)) { doPut(request, response); } else { log.error("No such method implemented: " + method); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { getContent(request, response); } private void getContent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { View view = null; org.w3c.dom.Document doc = null; javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); org.w3c.dom.DOMImplementation impl = parser.getDOMImplementation(); org.w3c.dom.DocumentType doctype = null; doc = impl.createDocument("http: } catch(Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } Element rootElement = doc.getDocumentElement(); String servletContextRealPath = config.getServletContext().getRealPath("/"); rootElement.setAttribute("servlet-context-real-path", servletContextRealPath); Element requestElement = (Element) rootElement.appendChild(doc.createElement("request")); requestElement.setAttribute("uri", request.getRequestURI()); requestElement.setAttribute("servlet-path", request.getServletPath()); HttpSession session = request.getSession(true); Element sessionElement = (Element) rootElement.appendChild(doc.createElement("session")); sessionElement.setAttribute("id", session.getId()); Enumeration enum = session.getAttributeNames(); if (!enum.hasMoreElements()) { Element sessionNoAttributesElement = (Element) sessionElement.appendChild(doc.createElement("no-attributes")); } while (enum.hasMoreElements()) { String name = (String)enum.nextElement(); String value = session.getAttribute(name).toString(); Element sessionAttributeElement = (Element) sessionElement.appendChild(doc.createElement("attribute")); sessionAttributeElement.setAttribute("name", name); sessionAttributeElement.appendChild(doc.createTextNode(value)); } String rti = map.getResourceTypeIdentifier(new Path(request.getServletPath())); Resource res = null; long lastModified = -1; if (rti != null) { ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti); if (rtd == null) { String message = "No such resource type registered: " + rti + ", check " + rtr.getConfigurationFile(); log.error(message); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } Element rtiElement = (Element) rootElement.appendChild(doc.createElement("resource-type-identifier")); rtiElement.setAttribute("namespace", rtd.getResourceTypeNamespace()); rtiElement.setAttribute("local-name", rtd.getResourceTypeLocalName()); try { res = rtr.newResource(rti); if (res != null) { res.setRTD(rtd); Element resourceElement = (Element) rootElement.appendChild(doc.createElement("resource")); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Viewable", "1")) { Element viewElement = (Element) resourceElement.appendChild(doc.createElement("view")); viewElement.appendChild(doc.createTextNode("View Descriptors: " + ((ViewableV1) res).getViewDescriptors())); String viewId = request.getParameter("yanel.resource.viewid"); try { view = ((ViewableV1) res).getView(request, viewId); } catch(org.wyona.yarep.core.NoSuchNodeException e) { // TODO: Log all 404 within a dedicated file (with client info attached) such that an admin can react to it ... String message = "No such node exception: " + e; log.warn(e); //log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttribute("status", "404"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND); setYanelOutput(response, doc); return; } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString(); log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); exceptionElement.setAttribute("status", "500"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); setYanelOutput(response, doc); return; } } else { Element noViewElement = (Element) resourceElement.appendChild(doc.createElement("no-view")); noViewElement.appendChild(doc.createTextNode(res.getClass().getName() + " is not viewable!")); } if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { lastModified = ((ModifiableV2) res).getLastModified(new Path(request.getServletPath())); Element lastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("last-modified")); lastModifiedElement.appendChild(doc.createTextNode(new java.util.Date(lastModified).toString())); } else { Element noLastModifiedElement = (Element) resourceElement.appendChild(doc.createElement("no-last-modified")); } } else { Element resourceIsNullElement = (Element) rootElement.appendChild(doc.createElement("resource-is-null")); } } catch(Exception e) { log.error(e.getMessage(), e); String message = e.toString(); log.error(e.getMessage(), e); Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } else { Element noRTIFoundElement = (Element) rootElement.appendChild(doc.createElement("no-resource-type-identifier-found")); noRTIFoundElement.setAttribute("servlet-path", request.getServletPath()); } String usecase = request.getParameter("yanel.resource.usecase"); if (usecase != null && usecase.equals("checkout")) { log.debug("Checkout data ..."); // TODO: Implement checkout ... log.warn("Acquire lock has not been implemented yet ...!"); // acquireLock(); } String meta = request.getParameter("yanel.resource.meta"); if (meta != null) { if (meta.length() > 0) { log.error("DEBUG: meta length: " + meta.length()); } else { log.error("DEBUG: Show all meta"); } response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); setYanelOutput(response, doc); return; } if (view != null) { response.setContentType(patchContentType(view.getMimeType(), request)); InputStream is = view.getInputStream(); byte buffer[] = new byte[8192]; int bytesRead; if (is != null) { // TODO: Yarep does not set returned Stream to null resp. is missing Exception Handling for the constructor. Exceptions should be handled here, but rather within Yarep or whatever repositary layer is being used ... bytesRead = is.read(buffer); if (bytesRead == -1) { String message = "InputStream of view does not seem to contain any data!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); setYanelOutput(response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // TODO: Compare If-Modified-Since with lastModified and return 304 without content resp. check on ETag String ifModifiedSince = request.getHeader("If-Modified-Since"); if (ifModifiedSince != null) { log.error("DEBUG: TODO: Implement 304 ..."); } java.io.OutputStream os = response.getOutputStream(); os.write(buffer, 0, bytesRead); while ((bytesRead = is.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } if(lastModified >= 0) response.setDateHeader("Last-Modified", lastModified); return; } else { String message = "InputStream of view is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); } } else { String message = "View is null!"; Element exceptionElement = (Element) rootElement.appendChild(doc.createElement("exception")); exceptionElement.appendChild(doc.createTextNode(message)); } setYanelOutput(response, doc); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response); // TODO: Implement checkin ... log.warn("Release lock has not been implemented yet ..."); // releaseLock(); return; } else { log.warn("No parameter yanel.resource.usecase!"); String contentType = request.getContentType(); log.error("DEBUG: Content Type: " + contentType); InputStream in = intercept(request.getInputStream()); if (contentType.equals("application/atom+xml")) { try { Resource atomEntry = rtr.newResource("<{http: // TODO: Replace hardcoded path ... Path entryPath = new Path("/demo/atom/entries/" + new java.util.Date().getTime() + ".xml"); //Path entryPath = new Path("/atom/entries/" + new java.util.Date().getTime() + ".xml"); OutputStream out = ((ModifiableV2)atomEntry).getOutputStream(entryPath); byte buffer[] = new byte[8192]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } log.error("DEBUG: Atom entry has been created: " + entryPath); InputStream resourceIn = ((ModifiableV2)atomEntry).getInputStream(entryPath); OutputStream responseOut = response.getOutputStream(); while ((bytesRead = resourceIn.read(buffer)) != -1) { responseOut.write(buffer, 0, bytesRead); } // TODO: Fix Location ... response.setHeader("Location", "http://ulysses.wyona.org" + entryPath); response.setStatus(javax.servlet.http.HttpServletResponse.SC_CREATED); return; } catch (Exception e) { log.error(e.getMessage(), e); throw new IOException(e.getMessage()); } } getContent(request, response); } } /** * HTTP PUT implementation */ public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO: Reuse code doPost resp. share code with doPut String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.debug("Save data ..."); save(request, response); return; } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); save(request, response); // TODO: Implement checkin ... log.warn("Release lock has not been implemented yet ...!"); // releaseLock(); return; } else { log.warn("No parameter yanel.resource.usecase!"); getContent(request, response); } } private Resource getResource(HttpServletRequest request) { String rti = map.getResourceTypeIdentifier(new Path(request.getServletPath())); if (rti != null) { ResourceTypeDefinition rtd = rtr.getResourceTypeDefinition(rti); try { Resource res = rtr.newResource(rti); res.setRTD(rtd); return res; } catch(Exception e) { log.error(e.getMessage(), e); return null; } } else { log.error("<no-resource-type-identifier-found servlet-path=\""+request.getServletPath()+"\"/>"); return null; } } private void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Save data ..."); InputStream in = request.getInputStream(); java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) byte[] memBuffer = baos.toByteArray(); // Check on well-formedness ... String contentType = request.getContentType(); log.debug("Content-Type: " + contentType); if (contentType.indexOf("application/xml") >= 0 || contentType.indexOf("application/xhtml+xml") >= 0) { log.info("Check well-formedness ..."); javax.xml.parsers.DocumentBuilderFactory dbf= javax.xml.parsers.DocumentBuilderFactory.newInstance(); try { javax.xml.parsers.DocumentBuilder parser = dbf.newDocumentBuilder(); // TODO: Get log messages into log4j ... //parser.setErrorHandler(...); // NOTE: DOCTYPE is being resolved/retrieved (e.g. xhtml schema from w3.org) also // if isValidating is set to false. // Hence, for performance and network reasons we use a local catalog ... // TODO: What about a resolver factory? parser.setEntityResolver(new org.apache.xml.resolver.tools.CatalogResolver()); parser.parse(new java.io.ByteArrayInputStream(memBuffer)); //org.w3c.dom.Document document = parser.parse(new ByteArrayInputStream(memBuffer)); } catch (org.xml.sax.SAXException e) { log.warn("Data is not well-formed: "+e.getMessage()); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Data is not well-formed: "+e.getMessage()+"</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } catch (Exception e) { log.error(e.getMessage(), e); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: //sb.append("<message>" + e.getStackTrace() + "</message>"); //sb.append("<message>" + e.getMessage() + "</message>"); sb.append("<message>" + e + "</message>"); sb.append("</exception>"); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); PrintWriter w = response.getWriter(); w.print(sb); return; } log.info("Data seems to be well-formed :-)"); } else { log.info("No well-formedness check required for content type: " + contentType); } /* if (bytesRead == -1) { response.setContentType("text/plain"); PrintWriter writer = response.getWriter(); writer.print("No content!"); return; } */ OutputStream out = null; Resource res = getResource(request); if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "1")) { out = ((ModifiableV1) res).getOutputStream(new Path(request.getServletPath())); } else if (ResourceAttributeHelper.hasAttributeImplemented(res, "Modifiable", "2")) { out = ((ModifiableV2) res).getOutputStream(new Path(request.getServletPath())); } else { String message = res.getClass().getName() + " is not modifiable (neither V1 nor V2)!"; log.warn(message); StringBuffer sb = new StringBuffer(); // TODO: Differentiate between Neutron based and other clients ... /* sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<resource>" + message + "</resource>"); sb.append("</body>"); sb.append("</html>"); response.setContentType("application/xhtml+xml"); */ sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>" + message + "</message>"); sb.append("</exception>"); response.setContentType("application/xml"); PrintWriter w = response.getWriter(); w.print(sb); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (out != null) { log.debug("Content-Type: " + contentType); // TODO: Compare mime-type from response with mime-type of resource //if (contentType.equals("text/xml")) { ... } byte[] buffer = new byte[8192]; int bytesRead; java.io.ByteArrayInputStream memIn = new java.io.ByteArrayInputStream(memBuffer); while ((bytesRead = memIn.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Data has been saved ...</p>"); sb.append("</body>"); sb.append("</html>"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_OK); response.setContentType("application/xhtml+xml"); PrintWriter w = response.getWriter(); w.print(sb); log.info("Data has been saved ..."); return; } else { log.error("OutputStream is null!"); StringBuffer sb = new StringBuffer(); sb.append("<?xml version=\"1.0\"?>"); sb.append("<html>"); sb.append("<body>"); sb.append("<p>Exception: OutputStream is null!</p>"); sb.append("</body>"); sb.append("</html>"); PrintWriter w = response.getWriter(); w.print(sb); response.setContentType("application/xhtml+xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } } /** * Authorize request * TODO: Replace hardcoded roles by mapping between roles amd query strings ... */ private HttpServletResponse doAuthorize(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Role role = null; String value = request.getParameter("yanel.resource.usecase"); if (value != null && value.equals("save")) { log.debug("Save data ..."); role = new Role("write"); } else if (value != null && value.equals("checkin")) { log.debug("Checkin data ..."); role = new Role("write"); } else if (value != null && value.equals("checkout")) { log.debug("Checkout data ..."); role = new Role("open"); } else { log.debug("No parameter yanel.resource.usecase!"); role = new Role("view"); } boolean authorized = false; // HTTP BASIC Authorization (For clients without session handling, e.g. OpenOffice or cadaver) String authorization = request.getHeader("Authorization"); log.debug("Checking for Authorization Header: " + authorization); if (authorization != null) { if (authorization.toUpperCase().startsWith("BASIC")) { log.debug("Using BASIC authorization ..."); // Get encoded user and password, comes after "BASIC " String userpassEncoded = authorization.substring(6); // Decode it, using any base 64 decoder sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder(); String userpassDecoded = new String(dec.decodeBuffer(userpassEncoded)); log.error("DEBUG: userpassDecoded: " + userpassDecoded); // TODO: Use security package and remove hardcoded ... // Authenticate every request ... //if (im.authenticate(...)) { if (userpassDecoded.equals("lenya:levi")) { //return pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), new Identity(...), new Role("view")); authorized = true; return null; } authorized = false; PrintWriter writer = response.getWriter(); writer.print("BASIC Authorization/Authentication Failed!"); response.sendError(response.SC_UNAUTHORIZED); return response; } else if (authorization.toUpperCase().startsWith("DIGEST")) { log.error("DIGEST is not implemented"); authorized = false; PrintWriter writer = response.getWriter(); writer.print("DIGEST is not implemented!"); response.sendError(response.SC_UNAUTHORIZED); return response; } else { log.warn("No such authorization implemented resp. handled by session based authorization: " + authorization); authorized = false; } } // Custom Authorization log.debug("Do session based custom authorization"); //String[] groupnames = {"null", "null"}; HttpSession session = request.getSession(true); Identity identity = (Identity) session.getAttribute(IDENTITY_KEY); if (identity == null) { log.debug("Identity is WORLD"); identity = new Identity(); } authorized = pm.authorize(new org.wyona.commons.io.Path(request.getServletPath()), identity, role); if(!authorized) { log.warn("Access denied: " + getRequestURLQS(request, null, false)); // TODO: Shouldn't this be here instead at the beginning of service() ...? //if(doAuthenticate(request, response) != null) return response; // HTTP Authorization/Authentication // TODO: Ulysses has not HTTP BASIC or DIGEST implemented yet! /* response.setHeader("WWW-Authenticate", "BASIC realm=\"yanel\""); response.sendError(response.SC_UNAUTHORIZED); */ // Custom Authorization/Authentication // TODO: Check if this is a neutron request or just a common GET request StringBuffer sb = new StringBuffer(""); String neutronVersions = request.getHeader("Neutron"); String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate"); Realm realm = map.getRealm(new Path(request.getServletPath())); if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) { log.debug("Neutron Versions supported by client: " + neutronVersions); log.debug("Authentication Scheme supported by client: " + clientSupportedAuthScheme); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authorization denied: " + getRequestURLQS(request, null, true) + "</message>"); sb.append("<authentication>"); sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... sb.append("<logout url=\"" + getRequestURLQS(request, "yanel.usecase=logout", true) + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); log.debug("Neutron-Auth response: " + sb); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); } else { // Custom HTML Form authentication // TODO: Use configurable XSLT for layout, whereas each realm should be able to overwrite ... sb.append("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http: sb.append("<body>"); sb.append("<p>Authorization denied: " + getRequestURLQS(request, null, true) + "</p>"); sb.append("<p>Enter username and password for realm \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\" (Context Path: " + request.getContextPath() + ")</p>"); sb.append("<form method=\"POST\">"); sb.append("<p>"); sb.append("<table>"); sb.append("<tr><td>Username:</td><td>&#160;</td><td><input type=\"text\" name=\"yanel.login.username\"/></td></tr>"); sb.append("<tr><td>Password:</td><td>&#160;</td><td><input type=\"password\" name=\"yanel.login.password\"/></td></tr>"); sb.append("<tr><td colspan=\"2\">&#160;</td><td align=\"right\"><input type=\"submit\" value=\"Login\"/></td></tr>"); sb.append("</table>"); sb.append("</p>"); sb.append("</form>"); sb.append("</body>"); sb.append("</html>"); response.setContentType("application/xhtml+xml"); } PrintWriter w = response.getWriter(); w.print(sb); return response; } else { log.info("Access granted: " + getRequestURLQS(request, null, false)); return null; } } private String getRequestURLQS(HttpServletRequest request, String addQS, boolean xml) { URL url = null; try { url = new URL(request.getRequestURL().toString()); if (proxyServerName != null) { url = new URL(url.getProtocol(), proxyServerName, url.getPort(), url.getFile()); } if (proxyPort != null) { if (proxyPort.length() > 0) { url = new URL(url.getProtocol(), url.getHost(), new Integer(proxyPort).intValue(), url.getFile()); } else { url = new URL(url.getProtocol(), url.getHost(), url.getDefaultPort(), url.getFile()); } } if (proxyPrefix != null) { url = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile().substring(proxyPrefix.length())); } if(proxyServerName != null || proxyPort != null || proxyPrefix != null) { log.debug("Proxy enabled request: " + url); } } catch (Exception e) { log.error(e); } String urlQS = url.toString(); if (request.getQueryString() != null) { urlQS = urlQS + "?" + request.getQueryString(); if (addQS != null) urlQS = urlQS + "&" + addQS; } else { if (addQS != null) urlQS = urlQS + "?" + addQS; } if (xml) urlQS = urlQS.replaceAll("&", "&amp;"); log.debug("Request: " + urlQS); return urlQS; } public void doPropfind(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/xml"); StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<D:multistatus xmlns:D=\"DAV:\">"); sb.append("<D:response xmlns:lp1=\"DAV:\">"); sb.append("<D:href>" + request.getRequestURL() + "</D:href>"); sb.append("<D:propstat>"); sb.append("<D:prop>"); sb.append("<lp1:resourcetype>"); //sb.append("<D:collection/>"); sb.append("<D:resource/>"); sb.append("</lp1:resourcetype>"); //sb.append("<D:getcontenttype>httpd/unix-directory</D:getcontenttype>"); sb.append("</D:prop>"); sb.append("</D:propstat>"); sb.append("<D:status>HTTP/1.1 200 OK</D:status>"); sb.append("</D:response>"); sb.append("</D:multistatus>"); log.error("DEBUG: " + sb.toString()); response.setStatus(response.SC_OK); PrintWriter writer = response.getWriter(); writer.print(sb.toString()); return; } public HttpServletResponse doAuthenticate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Realm realm = map.getRealm(new Path(request.getServletPath())); // HTML Form based authentication String loginUsername = request.getParameter("yanel.login.username"); if(loginUsername != null) { HttpSession session = request.getSession(true); if (im.authenticate(loginUsername, request.getParameter("yanel.login.password"), realm.getID())) { log.debug("Realm: " + realm); session.setAttribute(IDENTITY_KEY, new Identity(loginUsername, null)); return null; } else { log.warn("Login failed: " + loginUsername); // TODO: Implement form based response ... response.setHeader("WWW-Authenticate", "BASIC realm=\"yanel\""); response.sendError(response.SC_UNAUTHORIZED); return response; } } // Neutron-Auth based authentication String yanelUsecase = request.getParameter("yanel.usecase"); if(yanelUsecase != null && yanelUsecase.equals("neutron-auth")) { log.debug("Neutron Authentication ..."); String username = null; String password = null; String originalRequest = null; DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(); try { Configuration config = builder.build(request.getInputStream()); Configuration originalRequestConfig = config.getChild("original-request"); originalRequest = originalRequestConfig.getAttribute("url", null); Configuration[] paramConfig = config.getChildren("param"); for (int i = 0; i < paramConfig.length; i++) { String paramName = paramConfig[i].getAttribute("name", null); if (paramName != null) { if (paramName.equals("username")) { username = paramConfig[i].getValue(); } else if (paramName.equals("password")) { password = paramConfig[i].getValue(); } } } } catch(Exception e) { log.warn(e); } log.debug("Username: " + username); if (username != null) { HttpSession session = request.getSession(true); log.debug("Realm ID: " + realm.getID()); if (im.authenticate(username, password, realm.getID())) { log.info("Authentication successful: " + username); session.setAttribute(IDENTITY_KEY, new Identity(username, null)); // TODO: send some XML content, e.g. <authentication-successful/> response.setContentType("text/plain"); response.setStatus(response.SC_OK); PrintWriter writer = response.getWriter(); writer.print("Neutron Authentication Successful!"); return response; } else { log.warn("Neutron Authentication failed: " + username); // TODO: Refactor this code with the one from doAuthenticate ... log.debug("Original Request: " + originalRequest); StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authentication failed!</message>"); sb.append("<authentication>"); // TODO: ... sb.append("<original-request url=\"" + originalRequest + "\"/>"); //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... // TODO: ... sb.append("<login url=\"" + originalRequest + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">"); //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... // TODO: ... sb.append("<logout url=\"" + originalRequest + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); log.debug("Neutron-Auth response: " + sb); PrintWriter w = response.getWriter(); w.print(sb); response.setContentType("application/xml"); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); return response; } } else { // TODO: Refactor resp. reuse response from above ... log.warn("Neutron Authentication failed because username is NULL!"); StringBuffer sb = new StringBuffer(""); sb.append("<?xml version=\"1.0\"?>"); sb.append("<exception xmlns=\"http: sb.append("<message>Authentication failed because no username was sent!</message>"); sb.append("<authentication>"); // TODO: ... sb.append("<original-request url=\"" + originalRequest + "\"/>"); //sb.append("<original-request url=\"" + getRequestURLQS(request, null, true) + "\"/>"); //TODO: Also support https ... // TODO: ... sb.append("<login url=\"" + originalRequest + "&amp;yanel.usecase=neutron-auth" + "\" method=\"POST\">"); //sb.append("<login url=\"" + getRequestURLQS(request, "yanel.usecase=neutron-auth", true) + "\" method=\"POST\">"); sb.append("<form>"); sb.append("<message>Enter username and password for \"" + realm.getName() + "\" at \"" + realm.getMountPoint() + "\"</message>"); sb.append("<param description=\"Username\" name=\"username\"/>"); sb.append("<param description=\"Password\" name=\"password\"/>"); sb.append("</form>"); sb.append("</login>"); // NOTE: Needs to be a full URL, because user might switch the server ... // TODO: ... sb.append("<logout url=\"" + originalRequest + "&amp;yanel.usecase=logout" + "\" realm=\"" + realm.getName() + "\"/>"); sb.append("</authentication>"); sb.append("</exception>"); PrintWriter writer = response.getWriter(); response.setContentType("application/xml"); writer.print(sb); response.setStatus(javax.servlet.http.HttpServletResponse.SC_UNAUTHORIZED); return response; } } else { log.debug("Neutron Authentication successful."); return null; } } public HttpServletResponse doLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.info("Logout from Yanel ..."); HttpSession session = request.getSession(true); session.setAttribute(IDENTITY_KEY, null); String clientSupportedAuthScheme = request.getHeader("WWW-Authenticate"); if (clientSupportedAuthScheme != null && clientSupportedAuthScheme.equals("Neutron-Auth")) { // TODO: send some XML content, e.g. <logout-successful/> response.setContentType("text/plain"); response.setStatus(response.SC_OK); PrintWriter writer = response.getWriter(); writer.print("Neutron Logout Successful!"); return response; } return null; } public String patchContentType(String contentType, HttpServletRequest request) throws ServletException, IOException { String httpAcceptMediaTypes = request.getHeader("Accept"); log.debug("HTTP Accept Media Types: " + httpAcceptMediaTypes); if (contentType.equals("application/xhtml+xml") && httpAcceptMediaTypes != null && httpAcceptMediaTypes.indexOf("application/xhtml+xml") < 0) { log.error("DEBUG: Patch contentType with text/html because client (" + request.getHeader("User-Agent") + ") does not seem to understand application/xhtml+xml"); return "text/html"; } return contentType; } /** * Intercept InputStream and log content ... */ public InputStream intercept(InputStream in) throws IOException { java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); byte[] buf = new byte[8192]; int bytesR; while ((bytesR = in.read(buf)) != -1) { baos.write(buf, 0, bytesR); } // Buffer within memory (TODO: Maybe replace with File-buffering ...) byte[] memBuffer = baos.toByteArray(); log.error("DEBUG: InputStream: " + baos); return new java.io.ByteArrayInputStream(memBuffer); } private void setYanelOutput(HttpServletResponse response, Document doc) throws ServletException { response.setContentType("application/xml"); try { javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(response.getWriter())); /* OutputStream out = response.getOutputStream(); javax.xml.transform.TransformerFactory.newInstance().newTransformer().transform(new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out)); out.close(); */ } catch (Exception e) { log.error(e.getMessage(), e); throw new ServletException(e.getMessage()); } } }
package org.apache.jmeter.gui.tree; import java.util.Collection; import javax.swing.ImageIcon; import javax.swing.JPopupMenu; import javax.swing.tree.DefaultMutableTreeNode; import org.apache.jmeter.gui.GUIFactory; import org.apache.jmeter.gui.GuiPackage; import org.apache.jmeter.gui.JMeterGUIComponent; import org.apache.jmeter.testelement.AbstractTestElement; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.testelement.property.BooleanProperty; import org.apache.jmeter.testelement.property.StringProperty; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; /** * @author Michael Stover * @version $Revision$ */ public class JMeterTreeNode extends DefaultMutableTreeNode implements JMeterGUIComponent { transient private static Logger log = LoggingManager.getLoggerForClass(); private JMeterTreeModel treeModel; //boolean enabled = true; JMeterTreeNode(){// Allow guiTest and serializable test to work } public JMeterTreeNode(TestElement userObj, JMeterTreeModel treeModel) { super(userObj); this.treeModel = treeModel; } public boolean isEnabled() { return ( (AbstractTestElement) createTestElement()).getPropertyAsBoolean( TestElement.ENABLED); } public void setEnabled(boolean enabled) { createTestElement().setProperty( new BooleanProperty(TestElement.ENABLED, enabled)); } public void clear() { } public ImageIcon getIcon() { try { return GUIFactory.getIcon( Class.forName( createTestElement().getPropertyAsString( TestElement.GUI_CLASS))); } catch (ClassNotFoundException e) { log.warn("Can't get icon for class " + createTestElement(), e); return null; } } public Collection getMenuCategories() { try { return GuiPackage .getInstance() .getGui(createTestElement()) .getMenuCategories(); } catch (Exception e) { log.error("Can't get popup menu for gui", e); return null; } } public JPopupMenu createPopupMenu() { try { return GuiPackage .getInstance() .getGui(createTestElement()) .createPopupMenu(); } catch (Exception e) { log.error("Can't get popup menu for gui", e); return null; } } public void configure(TestElement element) { } /** * Modifies a given TestElement to mirror the data in the gui components. */ public void modifyTestElement(TestElement el) { } public TestElement createTestElement() { return (TestElement) getUserObject(); } public String getStaticLabel() { return GuiPackage .getInstance() .getGui((TestElement) getUserObject()) .getStaticLabel(); } public void setName(String name) { ((TestElement) getUserObject()).setProperty( new StringProperty(TestElement.NAME, name)); } public String getName() { return ((TestElement) getUserObject()).getPropertyAsString( TestElement.NAME); } public void setNode(JMeterTreeNode node) { } public void nameChanged() { treeModel.nodeChanged(this); } }
package de.matthiasmann.twlthemeeditor.gui; import de.matthiasmann.twlthemeeditor.gui.testwidgets.PreviewWidgets; import de.matthiasmann.twl.Dimension; import de.matthiasmann.twlthemeeditor.gui.testwidgets.TestFrameWithWidgets; import de.matthiasmann.twl.Button; import de.matthiasmann.twl.DialogLayout; import de.matthiasmann.twl.EditField; import de.matthiasmann.twl.GUI; import de.matthiasmann.twl.Label; import de.matthiasmann.twl.PopupWindow; import de.matthiasmann.twl.ScrollPane; import de.matthiasmann.twl.Scrollbar; import de.matthiasmann.twl.TextArea; import de.matthiasmann.twl.ToggleButton; import de.matthiasmann.twl.Widget; import de.matthiasmann.twl.model.AbstractProperty; import de.matthiasmann.twl.model.IntegerModel; import de.matthiasmann.twl.model.OptionBooleanModel; import de.matthiasmann.twl.model.Property; import de.matthiasmann.twl.model.SimpleIntegerModel; import de.matthiasmann.twl.model.SimpleTextAreaModel; import de.matthiasmann.twl.model.TextAreaModel; import de.matthiasmann.twl.utils.ClassUtils; import de.matthiasmann.twlthemeeditor.gui.testwidgets.TestLabel; import de.matthiasmann.twlthemeeditor.properties.BoundProperty; import de.matthiasmann.twlthemeeditor.properties.RectProperty; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.PrintWriter; import java.io.StringWriter; import java.net.URL; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Matthias Mann */ public class PreviewPane extends DialogLayout { static class WidgetEntry { final Class<? extends Widget> clazz; final String name; public WidgetEntry(Class<? extends Widget> clazz, String name) { this.clazz = clazz; this.name = name; } } private final PreviewWidget previewWidget; private final Label labelErrorDisplay; private final Button btnClearStackTrace; private final Button btnShowStackTrace; private final SimpleIntegerModel testWidgetModel; private final CollapsiblePanel collapsiblePanel; private final ScrollPane widgetPropertiesScrollPane; private Context ctx; private static final WidgetEntry[] TEST_WIDGET_CLASSES = { new WidgetEntry(Widget.class, "Widget"), new WidgetEntry(TestLabel.class, "Label"), new WidgetEntry(Button.class, "Button"), new WidgetEntry(ToggleButton.class, "ToggleButton"), new WidgetEntry(EditField.class, "EditField"), new WidgetEntry(Scrollbar.class, "Scrollbar"), new WidgetEntry(PreviewWidgets.class, "Widgets"), new WidgetEntry(TestFrameWithWidgets.class, "Frame with Widgets"), }; public PreviewPane() { this.previewWidget = new PreviewWidget(); this.labelErrorDisplay = new Label() { @Override public int getMinWidth() { return 0; } }; this.btnClearStackTrace = new Button("Clear"); this.btnShowStackTrace = new Button("Stack Trace"); ToggleButton[] testWidgetButtons = new ToggleButton[TEST_WIDGET_CLASSES.length]; testWidgetModel = new SimpleIntegerModel(0, testWidgetButtons.length-1, 0); for(int i=0 ; i<testWidgetButtons.length ; i++) { ToggleButton button = new ToggleButton(new OptionBooleanModel(testWidgetModel, i)); button.setTheme("radiobutton"); button.setText(TEST_WIDGET_CLASSES[i].name); testWidgetButtons[i] = button; } labelErrorDisplay.setTheme("errorDisplay"); labelErrorDisplay.setClip(true); btnClearStackTrace.setEnabled(false); btnShowStackTrace.setEnabled(false); widgetPropertiesScrollPane = new ScrollPane(); widgetPropertiesScrollPane.setTheme("propertyEditor"); widgetPropertiesScrollPane.setFixed(ScrollPane.Fixed.HORIZONTAL); collapsiblePanel = new CollapsiblePanel(CollapsiblePanel.Direction.HORIZONTAL, "", widgetPropertiesScrollPane, null); setHorizontalGroup(createParallelGroup() .addGroup(createSequentialGroup().addGap().addWidgetsWithGap("radiobutton", testWidgetButtons).addGap()) .addGroup(createSequentialGroup(previewWidget, collapsiblePanel)) .addGroup(createSequentialGroup(labelErrorDisplay, btnClearStackTrace, btnShowStackTrace).addGap(SMALL_GAP))); setVerticalGroup(createSequentialGroup() .addGroup(createParallelGroup(testWidgetButtons)) .addGroup(createParallelGroup(previewWidget, collapsiblePanel)) .addGroup(createParallelGroup(labelErrorDisplay, btnClearStackTrace, btnShowStackTrace))); previewWidget.getExceptionHolder().addCallback(new Runnable() { public void run() { updateException(); } }); btnClearStackTrace.addCallback(new Runnable() { public void run() { clearException(); } }); btnShowStackTrace.addCallback(new Runnable() { public void run() { showStackTrace(); } }); testWidgetModel.addCallback(new Runnable() { public void run() { changeTestWidget(); } }); previewWidget.setTestWidgetChangedCB(new Runnable() { public void run() { updateTestWidgetProperties(); } }); changeTestWidget(); } public void setURL(URL url) { previewWidget.setURL(url); } public void reloadTheme() { previewWidget.reloadTheme(); } public Object getThemeLoadErrorLocation() { return previewWidget.getThemeLoadErrorLocation(); } public void removeCallback(Runnable cb) { previewWidget.getExceptionHolder().removeCallback(cb); } public void addCallback(Runnable cb) { previewWidget.getExceptionHolder().addCallback(cb); } public void setContext(Context ctx) { this.ctx = ctx; } void updateException() { int nr = selectException(); if(nr >= 0) { ExceptionHolder exceptionHolder = previewWidget.getExceptionHolder(); Throwable ex = exceptionHolder.getException(nr); labelErrorDisplay.setText(exceptionHolder.getExceptionName(nr) + " exception: " + ex.getMessage()); btnClearStackTrace.setEnabled(true); btnShowStackTrace.setEnabled(true); } else { labelErrorDisplay.setText(""); btnClearStackTrace.setEnabled(false); btnShowStackTrace.setEnabled(false); } } void clearException() { clearException(selectException()); } void clearException(int nr) { if(nr >= 0) { previewWidget.clearException(nr); } } void showStackTrace() { final int nr = selectException(); if(nr < 0) { return; } final Throwable ex = previewWidget.getExceptionHolder().getException(nr); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); ex.printStackTrace(pw); pw.flush(); TextAreaModel model = new SimpleTextAreaModel(sw.toString()); TextArea textArea = new TextArea(model); ScrollPane scrollPane = new ScrollPane(textArea); scrollPane.setFixed(ScrollPane.Fixed.HORIZONTAL); Button btnClear = new Button("Clear Exception and Close"); Button btnClose = new Button("Close"); DialogLayout layout = new DialogLayout(); layout.setHorizontalGroup(layout.createParallelGroup() .addWidget(scrollPane) .addGroup(layout.createSequentialGroup().addGap().addWidgets(btnClear, btnClose))); layout.setVerticalGroup(layout.createSequentialGroup() .addWidget(scrollPane) .addGroup(layout.createParallelGroup().addWidgets(btnClear, btnClose))); final PopupWindow popupWindow = new PopupWindow(this); popupWindow.setTheme("previewExceptionPopup"); popupWindow.setCloseOnClickedOutside(false); popupWindow.setCloseOnEscape(true); popupWindow.add(layout); btnClear.addCallback(new Runnable() { public void run() { clearException(nr); popupWindow.closePopup(); } }); btnClose.addCallback(new Runnable() { public void run() { popupWindow.closePopup(); } }); GUI gui = getGUI(); popupWindow.setSize(gui.getWidth()*4/5, gui.getHeight()*4/5); popupWindow.setPosition( (gui.getWidth() - popupWindow.getWidth())/2, (gui.getHeight() - popupWindow.getHeight())/2); popupWindow.openPopup(); } private int selectException() { return previewWidget.getExceptionHolder().getHighestPriority(); } void changeTestWidget() { previewWidget.setWidgetClass(TEST_WIDGET_CLASSES[testWidgetModel.getValue()].clazz); } void updateTestWidgetProperties() { final Widget testWidget = previewWidget.getTestWidget(); if(testWidget == null || ctx == null) { widgetPropertiesScrollPane.setContent(null); return; } ArrayList<Property<?>> properties = new ArrayList<Property<?>>(); properties.add(new WidgetRectProperty(testWidget)); properties.add(new AbstractProperty<String>() { public boolean canBeNull() { return false; } public String getName() { return "Theme name"; } public String getPropertyValue() { return testWidget.getTheme(); } public Class<String> getType() { return String.class; } public boolean isReadOnly() { return false; } public void setPropertyValue(String value) throws IllegalArgumentException { testWidget.setTheme(value); testWidget.reapplyTheme(); } }); addBeanProperties(testWidget, properties); PropertyPanel panel = new PropertyPanel(ctx, properties.toArray(new Property<?>[properties.size()])); widgetPropertiesScrollPane.setContent(panel); } @SuppressWarnings("unchecked") private void addBeanProperties(final Widget testWidget, ArrayList<Property<?>> properties) { try { BeanInfo beanInfo = Introspector.getBeanInfo(testWidget.getClass()); for(PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) { if(pd.getReadMethod() != null && pd.getWriteMethod() != null) { if(pd.getReadMethod().getDeclaringClass() != Widget.class) { properties.add(new BoundProperty(testWidget, pd, ClassUtils.mapPrimitiveToWrapper(pd.getPropertyType()))); } } } } catch(Throwable ex) { Logger.getLogger(PreviewPane.class.getName()).log(Level.SEVERE, "can't collect bean properties", ex); } } static abstract class BoundIntegerProperty extends BoundProperty<Integer> implements IntegerModel { public BoundIntegerProperty(Object bean, String name) { super(bean, name, Integer.class); } public void addCallback(Runnable callback) { addValueChangedCallback(callback); } public void removeCallback(Runnable callback) { removeValueChangedCallback(callback); } public int getMinValue() { return 0; } public int getValue() { return getPropertyValue(); } @Override public boolean isReadOnly() { return false; } } static class WidgetRectProperty extends RectProperty { final Widget widget; public WidgetRectProperty(final Widget widget) { super(new BoundIntegerProperty(widget, "x") { public int getMaxValue() { return widget.getParent().getInnerWidth()-1; } public void setValue(int value) { widget.setPosition(value, widget.getY()); } }, new BoundIntegerProperty(widget, "y") { public int getMaxValue() { return widget.getParent().getInnerHeight()-1; } public void setValue(int value) { widget.setPosition(widget.getX(), value); } }, new BoundIntegerProperty(widget, "width") { public int getMaxValue() { return widget.getParent().getInnerWidth(); } public void setValue(int value) { widget.setSize(value, widget.getHeight()); } }, new BoundIntegerProperty(widget, "height") { public int getMaxValue() { return widget.getParent().getInnerHeight(); } public void setValue(int value) { widget.setSize(widget.getWidth(), value); } }, "Widget position & size"); this.widget = widget; } @Override public Dimension getLimit() { Widget parent = widget.getParent(); return new Dimension(parent.getInnerWidth(), parent.getInnerHeight()); } } }
package donnu.zolotarev.SpaceShip.Scenes; import android.opengl.GLES20; import android.util.Log; import android.view.KeyEvent; import donnu.zolotarev.SpaceShip.Activity.GameActivity; import donnu.zolotarev.SpaceShip.Bullets.BaseBullet; import donnu.zolotarev.SpaceShip.Effects.FogManager; import donnu.zolotarev.SpaceShip.GameData.HeroFeatures; import donnu.zolotarev.SpaceShip.GameState.IHeroDieListener; import donnu.zolotarev.SpaceShip.GameState.IParentScene; import donnu.zolotarev.SpaceShip.GameState.IWaveBar; import donnu.zolotarev.SpaceShip.R; import donnu.zolotarev.SpaceShip.Scenes.Interfaces.ISimpleClick; import donnu.zolotarev.SpaceShip.Effects.Shield; import donnu.zolotarev.SpaceShip.Textures.TextureLoader; import donnu.zolotarev.SpaceShip.UI.IHealthBar; import donnu.zolotarev.SpaceShip.UI.IScoreBar; import donnu.zolotarev.SpaceShip.Units.BaseUnit; import donnu.zolotarev.SpaceShip.Units.Hero; import donnu.zolotarev.SpaceShip.Utils.*; import donnu.zolotarev.SpaceShip.Waves.IAddedEnemy; import donnu.zolotarev.SpaceShip.Waves.IWaveController; import org.andengine.engine.Engine; import org.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.andengine.engine.handler.timer.ITimerCallback; import org.andengine.engine.handler.timer.TimerHandler; import org.andengine.entity.scene.IOnSceneTouchListener; import org.andengine.entity.scene.Scene; import org.andengine.entity.scene.background.AutoParallaxBackground; import org.andengine.entity.scene.background.ParallaxBackground; import org.andengine.entity.scene.menu.MenuScene; import org.andengine.entity.sprite.Sprite; import org.andengine.entity.text.Text; import org.andengine.entity.text.TextOptions; import org.andengine.entity.util.FPSCounter; import org.andengine.input.touch.TouchEvent; import org.andengine.util.HorizontalAlign; import org.andengine.util.color.Color; public abstract class BaseGameScene extends MyScene implements IAddedEnemy, IScoreBar { protected Color textColor = Color.WHITE; protected static BaseGameScene activeScene; protected static Engine engine; protected final GameActivity shipActivity; protected IWaveController waveController; private final ObjectCollisionController enemyController; private final ObjectCollisionController bulletController; private final IParentScene parentScene; private AnalogOnScreenControl analogOnScreenControl; protected Hero hero; private Text waveCountBar; private Text scoreBar; private Text healthBar; private Text shueldBar; private MenuScene menuScene; private MenuScene dieMenuScene; private boolean isShowMenuScene = false; private boolean enablePauseMenu = true; private boolean isActive = false; protected int score; protected int waveIndex = 0; protected IHealthBar textHealthBarCallback = new IHealthBar() { @Override public void updateHealthBar(int health) { healthBar.setText(String.valueOf(health)); } @Override public void updateShueldBar(int health) { shueldBar.setText(String.valueOf(health)); } }; protected IWaveBar textWaveBarCallback = new IWaveBar() { @Override public void onNextWave(int count) { waveCountBar.setText(String.format("%02d", count)); } }; private int status; private ISimpleClick exit; private ISimpleClick restart; private Text rocketBar; private IHeroDieListener heroDieListener = new IHeroDieListener() { @Override public void heroDie() { status = IParentScene.EXIT_DIE; beforeReturnToParent(IParentScene.EXIT_DIE); String str = shipActivity.getString(R.string.text_die_money,score); dieMenuScene = MenuFactory.createMenu(engine,shipActivity.getCamera()) .addedText(shipActivity.getString(R.string.lose_text),TextureLoader.getFont(), Constants.CAMERA_WIDTH_HALF,100, WALIGMENT.CENTER, HALIGMENT.CENTER) .addedText(str,TextureLoader.getFont()) .addedItem(TextureLoader.getMenuRestartTextureRegion(), new ISimpleClick() { @Override public void onClick(int id) { restart.onClick(id); } }/*restart*/) .addedItem(TextureLoader.getMenuBackToMainMenuTextureRegion(), exit) .enableAnimation() .build(); shipActivity.runOnUiThread(new Runnable() { @Override public void run() { isActive = false; enablePauseMenu = false; setChildScene(dieMenuScene, false, true, true); } }); } }; public BaseGameScene(IParentScene self) { super(self); parentScene = self; activeScene = this; shipActivity = GameActivity.getInstance(); engine = shipActivity.getEngine(); final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5); Sprite background = new Sprite(0,0,TextureLoader.getGameBK(),shipActivity.getVertexBufferObjectManager()); autoParallaxBackground.attachParallaxEntity(new ParallaxBackground.ParallaxEntity(-20.0f, background)); setBackground(autoParallaxBackground); enemyController = new ObjectCollisionController<BaseUnit>(); bulletController = new ObjectCollisionController<BaseBullet>(); createFPSBase(); createHealthBar(); createScoreBar(); createWaveCountBar(); initUnitsPools(); initHero(); initBulletsPools(); addHeroMoveControl(); BaseBullet.setDieListener(heroDieListener); BaseUnit.setDieListener(heroDieListener); initWave(); createMenu(); status = IParentScene.EXIT_USER; } protected abstract void initWave(); protected abstract void initHero(); protected abstract void initBulletsPools(); protected abstract void initUnitsPools(); protected abstract void beforeReturnToParent(int status); private void createMenu() { restart = new ISimpleClick() { @Override public void onClick(int id) { clearItem(); parentScene.restart(status); } }; exit = new ISimpleClick() { @Override public void onClick(int id) { returnToParentScene(status); } }; menuScene = MenuFactory.createMenu(engine, shipActivity.getCamera()) .addedItem(TextureLoader.getMenuResumeTextureRegion(), new ISimpleClick() { @Override public void onClick(int id) { activeScene.detachChild(menuScene); activeScene.setChildScene(analogOnScreenControl); isShowMenuScene = false; isActive = true; } }) .addedItem(TextureLoader.getMenuRestartTextureRegion(), restart) .addedItem(TextureLoader.getMenuBackToMainMenuTextureRegion(), exit) .enableAnimation() .build(); } boolean flag = false; protected void addHeroMoveControl() { analogOnScreenControl = new AnalogOnScreenControl(70, GameActivity.getCameraHeight() - TextureLoader.getScreenControlBaseTextureRegion().getHeight() - 50, shipActivity.getCamera(), TextureLoader.getScreenControlBaseTextureRegion(), TextureLoader.getScreenControlKnobTextureRegion(), 0.1f, 100, shipActivity.getEngine().getVertexBufferObjectManager(), hero.getCallback()); analogOnScreenControl.getControlBase().setBlendFunction(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); analogOnScreenControl.getControlBase().setAlpha(0.5f); analogOnScreenControl.getControlBase().setScaleCenter(0, 128); analogOnScreenControl.getControlBase().setScale(1.5f); analogOnScreenControl.getControlKnob().setScale(1.5f); analogOnScreenControl.refreshControlKnobPosition(); setChildScene(analogOnScreenControl); analogOnScreenControl.setZIndex(1000); setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) { hero.canFire(flag); flag = false; return false; } }); final Sprite btnFire = new Sprite(GameActivity.getCameraWidth()-130, GameActivity.getCameraHeight()-150, TextureLoader.getBtnFire1(),shipActivity.getEngine().getVertexBufferObjectManager()){ public int pId = -1; @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) { /* shipActivity.runOnUiThread(new Runnable() { @Override public void run() {*/ if(pSceneTouchEvent.isActionDown() || pSceneTouchEvent.isActionMove()){ // hero.canFire(true); flag = true; } if(pSceneTouchEvent.isActionUp() || pSceneTouchEvent.isActionOutside() || pSceneTouchEvent.isActionCancel()){ if ( Constants.CAMERA_WIDTH_HALF < pSceneTouchEvent.getX()){ flag = false; } } return super.onAreaTouched(pSceneTouchEvent, pTouchAreaLocalX, pTouchAreaLocalY); } }; /* btnFire.setColor(Color.BLACK); btnFire.setAlpha(0.5f);*/ analogOnScreenControl.attachChild(btnFire); analogOnScreenControl.registerTouchArea(btnFire); final HeroFeatures heroFeatures = HeroFeatures.get(); if (heroFeatures.isHaveRocketGun()){ final Sprite btnFire2 = new Sprite(GameActivity.getCameraWidth()- 300, GameActivity.getCameraHeight()-150, TextureLoader.getBtnFire2(),shipActivity.getEngine().getVertexBufferObjectManager()){ boolean flag = false; public int pId = -1; @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) { if (heroFeatures.isHaveRocket()){ shipActivity.runOnUiThread(new Runnable() { @Override public void run() { if(pSceneTouchEvent.isActionDown()){ hero.fireRocket(); rocketBar.setText(String.valueOf(heroFeatures.useRocket())); } } }); } return flag; } }; // btnFire2.setAlpha(0.5f); btnFire.setScale(1.25f); btnFire2.setScale(1.25f); analogOnScreenControl.attachChild(btnFire2); analogOnScreenControl.registerTouchArea(btnFire2); createRocketBar(); rocketBar.setText(String.valueOf(heroFeatures.getRocketCount())); } } private void createRocketBar(){ try { int x = GameActivity.getCameraWidth()- 235; int y = GameActivity.getCameraHeight()- 85; rocketBar = new Text(x,y,TextureLoader.getFont(),"00",new TextOptions(HorizontalAlign.LEFT),engine.getVertexBufferObjectManager()); analogOnScreenControl.attachChild(rocketBar); rocketBar.setText("0"); analogOnScreenControl.setZIndex(1000); } catch (Exception e) { e.printStackTrace(); } } @Override protected void onManagedUpdate(float pSecondsElapsed) { if (isActive){ waveController.updateWave(pSecondsElapsed); FogManager.fogUpdate(); } super.onManagedUpdate(pSecondsElapsed); } public void onKeyPressed(int keyCode, KeyEvent event) { if (enablePauseMenu){ if (!isShowMenuScene){ isShowMenuScene = true; isActive = false; setChildScene(menuScene, false, true, true); }else{ isActive = true; isShowMenuScene = false; activeScene.detachChild(menuScene); activeScene.setChildScene(analogOnScreenControl); } } } protected void returnToParentScene(int statusCode){ beforeReturnToParent(statusCode); clearItem(); System.gc(); FogManager.fogOff(); parentScene.returnToParentScene(statusCode); } protected void clearItem(){ activeScene.clearUpdateHandlers(); activeScene.clearChildScene(); activeScene.clearEntityModifiers(); activeScene.clearTouchAreas(); hero.destroy(true); getEnemyController().cleer(); getBulletController().cleer(); detachSelf(); BaseBullet.resetPool(); BaseUnit.resetPool(); Shield.resetPool(); FogManager.fogOff(); System.gc(); } public void addToScore(int value){ score += value; scoreBar.setText(String.format("%08d", score)); } private void createHealthBar(){ try { int y = 0; int x = (int)TextureLoader.getScreenControlBaseTextureRegion().getWidth() + 30 +100; String str = shipActivity.getString(R.string.text_strength); Text text = new Text(x,y,TextureLoader.getFont(),str,new TextOptions(HorizontalAlign.LEFT),engine.getVertexBufferObjectManager()); attachChild(text); text.setZIndex(1000); x += text.getWidth(); healthBar = new Text(x,y,TextureLoader.getFont(),"123456",new TextOptions(HorizontalAlign.LEFT),engine.getVertexBufferObjectManager()); healthBar.setColor(textColor); attachChild(healthBar); healthBar.setZIndex(1000); final HeroFeatures heroFeatures = HeroFeatures.get(); x += healthBar.getWidth()+5; str = shipActivity.getString(R.string.text_shield); text = new Text(x,y,TextureLoader.getFont(),str,new TextOptions(HorizontalAlign.LEFT),engine.getVertexBufferObjectManager()); attachChild(text); x += text.getWidth(); text.setZIndex(1000); shueldBar = new Text(x,y,TextureLoader.getFont(),"12345",new TextOptions(HorizontalAlign.LEFT),engine.getVertexBufferObjectManager()); shueldBar.setColor(textColor); attachChild(shueldBar); shueldBar.setZIndex(1000); text.setVisible(heroFeatures.isHaveShield()); shueldBar.setVisible(heroFeatures.isHaveShield()); //shueldBar } catch (Exception e) { e.printStackTrace(); } } private void createFPSBase() { final FPSCounter fpsCounter = new FPSCounter(); engine.registerUpdateHandler(fpsCounter); final Text fpsText = new Text(0, 0, TextureLoader.getFont(), "FPS:", "FPS: 1234567890.".length(),engine.getVertexBufferObjectManager()); fpsText.setColor(textColor); attachChild(fpsText); fpsText.setZIndex(1000); registerUpdateHandler(new TimerHandler(1 / 20.0f, true, new ITimerCallback() { @Override public void onTimePassed(final TimerHandler pTimerHandler) { fpsText.setText("FPS: " + String.valueOf(fpsCounter.getFPS())); } })); } private void createWaveCountBar() { try { waveCountBar = new Text(0,0, TextureLoader.getFont(),"00",new TextOptions(HorizontalAlign.RIGHT),engine.getVertexBufferObjectManager()); int x = GameActivity.getCameraWidth() - (int)scoreBar.getWidth() - (int)scoreBar.getWidth() -20; waveCountBar.setPosition(x,0); waveCountBar.setColor(textColor); attachChild(waveCountBar); waveCountBar.setZIndex(1000); } catch (Exception e) { e.printStackTrace(); } } private void createScoreBar() { try { scoreBar = new Text(0,0,TextureLoader.getFont(),"000000000",new TextOptions(HorizontalAlign.RIGHT),engine.getVertexBufferObjectManager()); int x = GameActivity.getCameraWidth() - (int)scoreBar.getWidth(); scoreBar.setPosition(x,0); scoreBar.setColor(textColor); attachChild(scoreBar); scoreBar.setZIndex(1000); } catch (Exception e) { e.printStackTrace(); } } public Hero getHero() { return hero; } public ObjectCollisionController getEnemyController() { return enemyController; } public ObjectCollisionController getBulletController() { return bulletController; } public static Engine getEngine() { return engine; } public static BaseGameScene getActiveScene() { return activeScene; } protected void start(){ isActive = true; } public void addNewWaveController(IWaveController controller){ waveController = controller; start(); } @Override public void onResume() { } @Override public void onPause() { System.gc(); Log.i("XXX", "isShowMenuScene = " + (isShowMenuScene)); if (enablePauseMenu){ if (!isShowMenuScene){ isShowMenuScene = true; isActive = false; setChildScene(menuScene, false, true, true); } } } @Override public boolean addEnemy(AddedEnemyParam param) { if (param.isEnemy()){ return true; }else{ switch (param.getKind()){ case FogManager.START_FOG: FogManager.fogOn(); break; case FogManager.STOP_FOG: FogManager.fogOff(); break; } return false; } } }
package dr.evomodel.continuous; import dr.evolution.tree.Tree; import dr.evolution.tree.NodeRef; import dr.xml.*; import dr.evomodel.tree.TreeModel; import dr.evomodel.tree.TreeStatistic; import dr.inference.model.Statistic; import dr.geo.math.SphericalPolarCoordinates; import java.util.ArrayList; import java.util.List; /** * @author Marc Suchard * @author Philippe Lemey */ public class TreeDispersionStatistic extends Statistic.Abstract implements TreeStatistic { public static final String TREE_DISPERSION_STATISTIC = "treeDispersionStatistic"; public static final String BOOLEAN_OPTION = "greatCircleDistance"; public TreeDispersionStatistic(String name, TreeModel tree, List<AbstractMultivariateTraitLikelihood> traitLikelihoods, boolean genericOption) { super(name); this.tree = tree; this.traitLikelihoods = traitLikelihoods; this.genericOption = genericOption; } public void setTree(Tree tree) { this.tree = (TreeModel) tree; } public Tree getTree() { return tree; } public int getDimension() { return 1; } /** * @return whatever Philippe wants */ public double getStatisticValue(int dim) { String traitName = traitLikelihoods.get(0).getTraitName(); double treelength = 0; double treeDistance = 0; for (AbstractMultivariateTraitLikelihood traitLikelihood : traitLikelihoods) { for (int i = 0; i < tree.getNodeCount(); i++) { NodeRef node = tree.getNode(i); double[] trait = traitLikelihood.getTraitForNode(tree, node, traitName); if (node != tree.getRoot()) { double[] parentTrait = traitLikelihood.getTraitForNode(tree, tree.getParent(node), traitName); treelength += tree.getBranchLength(node); if (genericOption) { // Great Circle distance SphericalPolarCoordinates coord1 = new SphericalPolarCoordinates(trait[0], trait[1]); SphericalPolarCoordinates coord2 = new SphericalPolarCoordinates(parentTrait[0], parentTrait[1]); treeDistance += coord1.distance(coord2); } else { treeDistance += getNativeDistance(trait, parentTrait); } } } } return treeDistance / treelength; } private double getNativeDistance(double[] location1, double[] location2) { return Math.sqrt(Math.pow((location2[0] - location1[0]), 2.0) + Math.pow((location2[1] - location1[1]), 2.0)); } public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { public String getParserName() { return TREE_DISPERSION_STATISTIC; } public Object parseXMLObject(XMLObject xo) throws XMLParseException { String name = xo.getAttribute(NAME, xo.getId()); TreeModel tree = (TreeModel) xo.getChild(Tree.class); boolean option = xo.getAttribute(BOOLEAN_OPTION, false); // Default value is false List<AbstractMultivariateTraitLikelihood> traitLikelihoods = new ArrayList<AbstractMultivariateTraitLikelihood>(); for (int i = 0; i < xo.getChildCount(); i++) { if (xo.getChild(i) instanceof AbstractMultivariateTraitLikelihood) { traitLikelihoods.add((AbstractMultivariateTraitLikelihood) xo.getChild(i)); } } return new TreeDispersionStatistic(name, tree, traitLikelihoods, option); }
package dr.inference.model; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.impl.DenseDoubleMatrix2D; import dr.evolution.tree.TreeTrait; import dr.evomodel.continuous.MultivariateDiffusionModel; import dr.evomodel.tree.TreeModel; import dr.evomodel.treedatalikelihood.RateRescalingScheme; import dr.evomodel.treedatalikelihood.TreeDataLikelihood; import dr.evomodel.treedatalikelihood.continuous.MultivariateTraitDebugUtilities; import dr.evomodel.treedatalikelihood.continuous.RepeatedMeasuresTraitDataModel; import dr.math.matrixAlgebra.IllegalDimension; import dr.math.matrixAlgebra.Matrix; import dr.math.matrixAlgebra.RobustEigenDecomposition; import dr.math.matrixAlgebra.missingData.MissingOps; import dr.xml.*; import org.ejml.data.DenseMatrix64F; import org.ejml.ops.CommonOps; import java.util.Arrays; import static dr.evomodel.treedatalikelihood.preorder.AbstractRealizedContinuousTraitDelegate.REALIZED_TIP_TRAIT; /** * A Statistic class that computes the expected proportion of the variance in the data due to diffusion on the tree * versus sampling error. * * @author Gabriel Hassler */ public class VarianceProportionStatistic extends Statistic.Abstract implements VariableListener, ModelListener { public static final String PARSER_NAME = "varianceProportionStatistic"; private static final String MATRIX_RATIO = "matrixRatio"; private static final String ELEMENTWISE = "elementWise"; private static final String SYMMETRIC_DIVISION = "symmetricDivision"; private final TreeModel tree; private final MultivariateDiffusionModel diffusionModel; private final RepeatedMeasuresTraitDataModel dataModel; private final TreeDataLikelihood treeLikelihood; private DenseMatrix64F diffusionProportion; private TreeVarianceSums treeSums; private Matrix diffusionVariance; private Matrix samplingVariance; private DenseMatrix64F diffusionComponent; private DenseMatrix64F samplingComponent; private boolean treeKnown = false; private boolean varianceKnown = false; private final MatrixRatios ratio; private final int dimTrait; private final static boolean useEmpiricalVariance = true; public VarianceProportionStatistic(TreeModel tree, TreeDataLikelihood treeLikelihood, RepeatedMeasuresTraitDataModel dataModel, MultivariateDiffusionModel diffusionModel, MatrixRatios ratio) { this.tree = tree; this.treeLikelihood = treeLikelihood; this.diffusionModel = diffusionModel; this.dataModel = dataModel; this.dimTrait = dataModel.getTraitDimension(); this.diffusionVariance = new Matrix(dimTrait, dimTrait); this.samplingVariance = new Matrix(dimTrait, dimTrait); this.diffusionProportion = new DenseMatrix64F(dimTrait, dimTrait); this.diffusionComponent = new DenseMatrix64F(dimTrait, dimTrait); this.samplingComponent = new DenseMatrix64F(dimTrait, dimTrait); this.treeSums = new TreeVarianceSums(0, 0); tree.addModelListener(this); diffusionModel.getPrecisionParameter().addParameterListener(this); dataModel.getPrecisionMatrix().addParameterListener(this); this.ratio = ratio; } /** * a class that stores the sum of the diagonal elements and all elements of a matrix */ private class TreeVarianceSums { private double diagonalSum; private double totalSum; private TreeVarianceSums(double diagonalSum, double totalSum) { this.diagonalSum = diagonalSum; this.totalSum = totalSum; } } private enum MatrixRatios { ELEMENT_WISE { @Override void setMatrixRatio(DenseMatrix64F numeratorMatrix, DenseMatrix64F otherMatrix, DenseMatrix64F destination) { int dim = destination.numRows; for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { double n = Math.abs(numeratorMatrix.get(i, j)); double d = Math.abs(otherMatrix.get(i, j)); if (n == 0 && d == 0) { destination.set(i, j, 0); } else { destination.set(i, j, n / (n + d)); } } } } }, SYMMETRIC_DIVISION { @Override void setMatrixRatio(DenseMatrix64F numeratorMatrix, DenseMatrix64F otherMatrix, DenseMatrix64F destination) throws IllegalDimension { //TODO: implement for eigendecomposition with DensMatrix64F System.err.println(this.name() + " not yet implemented for " + SYMMETRIC_DIVISION + "."); // int dim = destination.numRows; // Matrix M1 = numeratorMatrix.add(otherMatrix); //M1 = numeratorMatrix + otherMatrix // Matrix M2 = getMatrixSqrt(M1, true); //M2 = inv(sqrt(numeratorMatrix + otherMatrix)) // Matrix M3 = M2.product(numeratorMatrix.product(M2));//M3 = inv(sqrt(numeratorMatrix + otherMatrix)) * // // numeratorMatrix * inv(sqrt(numeratorMatrix + otherMatrix)) // for (int i = 0; i < dim; i++) { // for (int j = 0; j < dim; j++) { // destination.set(i, j, M3.component(i, j)); } }; abstract void setMatrixRatio(DenseMatrix64F numeratorMatrix, DenseMatrix64F otherMatrix, DenseMatrix64F destination) throws IllegalDimension; } private void updateDiffsionProportion() throws IllegalDimension { updateVarianceComponents(); ratio.setMatrixRatio(diffusionComponent, samplingComponent, diffusionProportion); } /** * recalculates the diffusionProportion statistic based on current parameters */ //TODO: Move method below to a different class private static Matrix getMatrixSqrt(Matrix M, Boolean invert) { DoubleMatrix2D S = new DenseDoubleMatrix2D(M.toComponents()); RobustEigenDecomposition eigenDecomp = new RobustEigenDecomposition(S, 100); DoubleMatrix1D eigenValues = eigenDecomp.getRealEigenvalues(); int dim = eigenValues.size(); for (int i = 0; i < dim; i++) { double value = Math.sqrt(eigenValues.get(i)); if (invert) { value = 1 / value; } eigenValues.set(i, value); } DoubleMatrix2D eigenVectors = eigenDecomp.getV(); for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { eigenVectors.set(i, j, eigenVectors.get(i, j) * eigenValues.get(j)); } } DoubleMatrix2D storageMatrix = new DenseDoubleMatrix2D(dim, dim); eigenVectors.zMult(eigenDecomp.getV(), storageMatrix, 1, 0, false, true); return new Matrix(storageMatrix.toArray()); } private void updateVarianceComponents() { double n = tree.getExternalNodeCount(); double diffusionScale = (treeSums.diagonalSum / n - treeSums.totalSum / (n * n)); double samplingScale = (n - 1) / n; for (int i = 0; i < dimTrait; i++) { diffusionComponent.set(i, i, diffusionScale * diffusionVariance.component(i, i)); samplingComponent.set(i, i, samplingScale * samplingVariance.component(i, i)); for (int j = i + 1; j < dimTrait; j++) { double diffValue = diffusionScale * diffusionVariance.component(i, j); double sampValue = samplingScale * samplingVariance.component(i, j); diffusionComponent.set(i, j, diffValue); samplingComponent.set(i, j, sampValue); diffusionComponent.set(j, i, diffValue); samplingComponent.set(j, i, sampValue); } } } /** * recalculates the the sum of the diagonal elements and sum of all the elements of the tree variance * matrix statistic based on current parameters */ private void updateTreeSums() { double diagonalSum = MultivariateTraitDebugUtilities.getVarianceDiagonalSum(tree, treeLikelihood.getBranchRateModel(), 1.0); double offDiagonalSum = MultivariateTraitDebugUtilities.getVarianceOffDiagonalSum(tree, treeLikelihood.getBranchRateModel(), 1.0); RateRescalingScheme rescalingScheme = treeLikelihood.getDataLikelihoodDelegate().getRateRescalingScheme(); double normalization = 1.0; if (rescalingScheme == RateRescalingScheme.TREE_HEIGHT) { normalization = tree.getNodeHeight(tree.getRoot()); } else if (rescalingScheme == RateRescalingScheme.TREE_LENGTH) { //TODO: find function that returns tree length System.err.println("VarianceProportionStatistic not yet implemented for " + "traitDataLikelihood argument useTreeLength='true'."); } else if (rescalingScheme != RateRescalingScheme.NONE) { System.err.println("VarianceProportionStatistic not yet implemented for RateRescalingShceme" + rescalingScheme.getText() + "."); } treeSums.diagonalSum = diagonalSum / normalization; treeSums.totalSum = (diagonalSum + offDiagonalSum) / normalization; } private void updateSamplingVariance() { //TODO: make sure you do diffusion variance THEN sampling variance //TODO: compute sampling variance from diffusion variance and total variance if (useEmpiricalVariance) { //TODO: make sure they're using simulated values and not the zeros double[] data = dataModel.getParameter().getParameterValues(); int nTaxa = tree.getExternalNodeCount(); computeVariance(samplingComponent, data, nTaxa, dimTrait); CommonOps.addEquals(samplingComponent, -1, diffusionComponent); } else { samplingVariance = dataModel.getSamplingVariance(); } } private void updateDiffusionVariance() { if (useEmpiricalVariance) { updateEmpiricalDiffusionVariance(); } else { diffusionVariance = new Matrix(diffusionModel.getPrecisionmatrix()).inverse(); } } private void updateEmpiricalDiffusionVariance() { String key = REALIZED_TIP_TRAIT + "." + dataModel.getTraitName(); TreeTrait trait = treeLikelihood.getTreeTrait(key); double[] tipTraits = (double[]) trait.getTrait(treeLikelihood.getTree(), null); int nTaxa = tree.getExternalNodeCount(); computeVariance(diffusionComponent, tipTraits, nTaxa, dimTrait); } private void computeVariance(DenseMatrix64F matrix, double[] data, int numRows, int numCols) { double[] buffer = new double[numRows]; DenseMatrix64F sumVec = new DenseMatrix64F(numRows, 1); DenseMatrix64F matrixBuffer = new DenseMatrix64F(numCols, numCols); Arrays.fill(matrix.getData(), 0); for (int i = 0; i < numRows; i++) { int offset = numCols * i; DenseMatrix64F wrapper = MissingOps.wrap(data, offset, numCols, 1, buffer); CommonOps.multTransB(wrapper, wrapper, matrixBuffer); CommonOps.addEquals(matrix, matrixBuffer); CommonOps.addEquals(sumVec, wrapper); } CommonOps.multTransB(sumVec, sumVec, matrixBuffer); CommonOps.addEquals(matrix, -1 / numRows, matrixBuffer); } @Override public int getDimension() { return dimTrait * dimTrait; } @Override public double getStatisticValue(int dim) { boolean needToUpdate = false; if (!treeKnown) { updateTreeSums(); treeKnown = true; needToUpdate = true; } if (!varianceKnown) { updateSamplingVariance(); updateDiffusionVariance(); varianceKnown = true; needToUpdate = true; } if (needToUpdate) { try { updateDiffsionProportion(); } catch (IllegalDimension illegalDimension) { illegalDimension.printStackTrace(); } } int d1 = dim / dimTrait; int d2 = dim - d1 * dimTrait; return diffusionProportion.get(d1, d2); } @Override public void variableChangedEvent(Variable variable, int index, Variable.ChangeType type) { assert (variable == dataModel.getSamplingPrecision() || variable == diffusionModel.getPrecisionParameter()); varianceKnown = false; } @Override public void modelChangedEvent(Model model, Object object, int index) { assert (model == tree); treeKnown = false; } //TODO: make its own class in evomodelxml public static XMLObjectParser PARSER = new AbstractXMLObjectParser() { @Override public Object parseXMLObject(XMLObject xo) throws XMLParseException { TreeModel tree = (TreeModel) xo.getChild(TreeModel.class); RepeatedMeasuresTraitDataModel dataModel = (RepeatedMeasuresTraitDataModel) xo.getChild(RepeatedMeasuresTraitDataModel.class); MultivariateDiffusionModel diffusionModel = (MultivariateDiffusionModel) xo.getChild(MultivariateDiffusionModel.class); TreeDataLikelihood treeLikelihood = (TreeDataLikelihood) xo.getChild(TreeDataLikelihood.class); String ratioString = xo.getStringAttribute(MATRIX_RATIO); MatrixRatios ratio = null; if (ratioString.equalsIgnoreCase(ELEMENTWISE)) { ratio = MatrixRatios.ELEMENT_WISE; } else if (ratioString.equalsIgnoreCase(SYMMETRIC_DIVISION)) { ratio = MatrixRatios.SYMMETRIC_DIVISION; } else { throw new RuntimeException(PARSER_NAME + " must have attibute " + MATRIX_RATIO + " with one of the following values: " + MatrixRatios.values()); } return new VarianceProportionStatistic(tree, treeLikelihood, dataModel, diffusionModel, ratio); } private final XMLSyntaxRule[] rules = new XMLSyntaxRule[]{ AttributeRule.newStringRule(MATRIX_RATIO, false), new ElementRule(TreeModel.class), new ElementRule(TreeDataLikelihood.class), new ElementRule(RepeatedMeasuresTraitDataModel.class), new ElementRule(MultivariateDiffusionModel.class) }; @Override public XMLSyntaxRule[] getSyntaxRules() { return rules; } @Override public String getParserDescription() { return "This element returns a statistic that computes proportion of variance due to diffusion on the tree"; } @Override public Class getReturnType() { return VarianceProportionStatistic.class; } @Override public String getParserName() { return PARSER_NAME; } }; @Override public void modelRestored(Model model) { // Do nothing } }
package edu.wustl.xipHost.hostControl; import java.awt.Dimension; import java.awt.Toolkit; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.swing.JFrame; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.xml.ws.Endpoint; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; import org.jdom.output.XMLOutputter; import org.nema.dicom.wg23.State; import org.xmldb.api.base.XMLDBException; import edu.wustl.xipHost.application.Application; import edu.wustl.xipHost.application.ApplicationManager; import edu.wustl.xipHost.application.ApplicationManagerFactory; import edu.wustl.xipHost.caGrid.GridManager; import edu.wustl.xipHost.caGrid.GridManagerFactory; import edu.wustl.xipHost.dicom.DicomManager; import edu.wustl.xipHost.dicom.DicomManagerFactory; import edu.wustl.xipHost.gui.ConfigPanel; import edu.wustl.xipHost.gui.ExceptionDialog; import edu.wustl.xipHost.gui.HostMainWindow; import edu.wustl.xipHost.gui.LoginDialog; import edu.wustl.xipHost.worklist.Worklist; import edu.wustl.xipHost.worklist.WorklistFactory; public class HostConfigurator { Login login = new Login(); File hostTmpDir; File hostOutDir; File hostConfig; HostMainWindow mainWindow; ConfigPanel configPanel = new ConfigPanel(new JFrame()); //ConfigPanel is used to specify tmp and output dirs GridManager gridMgr; DicomManager dicomMgr; ApplicationManager appMgr; File xipApplicationsConfig; public static final String OS = System.getProperty("os.name"); String userName; public boolean runHostStartupSequence(){ //DisplayLoginDialog LoginDialog loginDialog = new LoginDialog(); loginDialog.setLogin(login); Thread t = new Thread(loginDialog); t.run(); try { t.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } userName = login.getUserName(); hostConfig = new File("./config/xipConfig.xml"); if(loadHostConfigParameters(hostConfig) == false || loadPixelmedSavedImagesFolder(serverConfig) == false){ new ExceptionDialog("Unable to load Host configuration parameters.", "Ensure host config file and Pixelmed/HSQLQB config file are valid.", "Host Startup Dialog"); System.exit(0); } //if config contains displayConfigDialog true -> displayConfigDialog if(getDisplayStartUp()){ displayConfigDialog(); } hostTmpDir = createSubTmpDir(getParentOfTmpDir()); hostOutDir = createSubOutDir(getParentOfOutDir()); prop.setProperty("Application.SavedImagesFolderName", getPixelmedSavedImagesFolder()); try { prop.store(new FileOutputStream(serverConfig), "Updated Application.SavedImagesFolderName"); } catch (FileNotFoundException e1) { System.exit(0); } catch (IOException e1) { System.exit(0); } //run GridManagerImpl startup gridMgr = GridManagerFactory.getInstance(); gridMgr.runGridStartupSequence(); //test for gridMgr == null gridMgr.setImportDirectory(hostTmpDir); //run WorkList startup Worklist worklist = WorklistFactory.getInstance(); //Injector injector = Guice.createInjector(new WorklistModule()); //Worklist worklist = injector.getInstance(Worklist.class); String path = "./config/worklist.xml"; File xmlWorklistFile = new File(path); worklist.loadWorklist(xmlWorklistFile); dicomMgr = DicomManagerFactory.getInstance(); dicomMgr.runDicomStartupSequence(); appMgr = ApplicationManagerFactory.getInstance(); xipApplicationsConfig = new File("./config/applications.xml"); try { appMgr.loadApplications(xipApplicationsConfig); //Load test applications, RECIST is currently supported on Windows only if(false){ loadTestApplications(); } } catch (JDOMException e) { new ExceptionDialog("Unable to load applications.", "Ensure applications xml config file exists and is valid.", "Host Startup Dialog"); System.exit(0); } catch (IOException e) { new ExceptionDialog("Unable to load applications.", "Ensure applications xml config file exists and is valid.", "Host Startup Dialog"); System.exit(0); } //hostOutDir and hostTmpDir are hold in static variables in ApplicationManager appMgr.setOutputDir(hostOutDir); appMgr.setTmpDir(hostTmpDir); //XindiceManager is used to register XMLDB database used to store and manage //XML Native Models XindiceManager xm = XindiceManagerFactory.getInstance(); try { xm.startup(); } catch (XMLDBException e) { // TODO Auto-generated catch block //TODO Auto-generated catch block //Q: what to do if Xindice is not launched //1. Go with no native model support or //2. prompt user and exit e.printStackTrace(); } mainWindow = new HostMainWindow(); mainWindow.setUserName(userName); mainWindow.display(); return true; } SAXBuilder builder = new SAXBuilder(); Document document; Element root; String parentOfTmpDir; String parentOfOutDir; Boolean displayStartup; /** * (non-Javadoc) * @see edu.wustl.xipHost.hostControl.HostManager#loadHostConfigParameters() */ public boolean loadHostConfigParameters (File hostConfigFile) { if(hostConfigFile == null){ return false; }else if(!hostConfigFile.exists()){ return false; }else{ try{ document = builder.build(hostConfigFile); root = document.getRootElement(); //path for the parent of TMP directory if(root.getChild("tmpDir") == null){ parentOfTmpDir = ""; }else if(root.getChild("tmpDir").getValue().trim().isEmpty() || new File(root.getChild("tmpDir").getValue()).exists() == false){ parentOfTmpDir = ""; }else{ parentOfTmpDir = root.getChild("tmpDir").getValue(); } if(root.getChild("outputDir") == null){ parentOfOutDir = ""; }else if(root.getChild("outputDir").getValue().trim().isEmpty() || new File(root.getChild("outputDir").getValue()).exists() == false){ parentOfOutDir = ""; }else{ //path for the parent of output directory. //parentOfOutDir used to store data produced by the xip application parentOfOutDir = root.getChild("outputDir").getValue(); } if(root.getChild("displayStartup") == null){ displayStartup = new Boolean(true); }else{ if(root.getChild("displayStartup").getValue().equalsIgnoreCase("true") || root.getChild("displayStartup").getValue().trim().isEmpty() || parentOfTmpDir.isEmpty() || parentOfOutDir.isEmpty() || parentOfTmpDir.equalsIgnoreCase(parentOfOutDir)){ if(parentOfTmpDir.equalsIgnoreCase(parentOfOutDir)){ parentOfTmpDir = ""; parentOfOutDir = ""; } displayStartup = new Boolean(true); }else if (root.getChild("displayStartup").getValue().equalsIgnoreCase("false")){ displayStartup = new Boolean(false); }else{ displayStartup = new Boolean(true); } } } catch (JDOMException e) { return false; } catch (IOException e) { return false; } } return true; } File serverConfig = new File("./pixelmed-server-hsqldb/workstation1.properties"); Properties prop = new Properties(); String pixelmedSavedImagesFolder; boolean loadPixelmedSavedImagesFolder(File serverConfig){ if(serverConfig == null){return false;} try { prop.load(new FileInputStream(serverConfig)); pixelmedSavedImagesFolder = prop.getProperty("Application.SavedImagesFolderName"); if(new File(pixelmedSavedImagesFolder).exists() == false){ pixelmedSavedImagesFolder = ""; displayStartup = new Boolean(true); } } catch (FileNotFoundException e) { return false; } catch (IOException e) { return false; } return true; } public String getParentOfOutDir(){ return parentOfOutDir; } public void setParentOfOutDir(String newDir){ parentOfOutDir = newDir; } public String getParentOfTmpDir(){ return parentOfTmpDir; } public File getHostTmpDir(){ return hostTmpDir; } public void setParentOfTmpDir(String newDir){ parentOfTmpDir = newDir; } public String getPixelmedSavedImagesFolder(){ return pixelmedSavedImagesFolder; } public void setPixelmedSavedImagesFolder(String pixelmedDir){ pixelmedSavedImagesFolder = pixelmedDir; } public Boolean getDisplayStartUp(){ return displayStartup; } public void setDisplayStartUp(Boolean display){ displayStartup = display; } public String getUser(){ return userName; } /** * method creates subdirectory under parent of tmp directory. * Creating sub directory is meant to prevent situations when tmp dirs * would be created directly on system main dir path e.g. C:\ * @return */ File createSubTmpDir(String parentOfTmpDir){ if(parentOfTmpDir == null || parentOfTmpDir.trim().isEmpty()){return null;} try { File tmpFile = Util.create("TmpXIP", ".tmp", new File(parentOfTmpDir)); tmpFile.deleteOnExit(); return tmpFile; } catch (IOException e) { return null; } } /** * method creates subdirectory under parent of output directory. * Creating sub directory is meant to prevent situations when output dirs * would be created directly on system main dir path e.g. C:\ * @return */ File createSubOutDir(String parentOfOutDir){ if(parentOfOutDir == null || parentOfOutDir.trim().isEmpty()){return null;} if(new File(parentOfOutDir).exists() == false){return null;} File outFile = new File(parentOfOutDir, "OutputXIP"); if(!outFile.exists()){ outFile.mkdir(); } return outFile; } void displayConfigDialog(){ configPanel.setParentOfTmpDir(getParentOfTmpDir()); configPanel.setParentOfOutDir(getParentOfOutDir()); configPanel.setPixelmedSavedImagesDir(getPixelmedSavedImagesFolder()); configPanel.setDisplayStartup(getDisplayStartUp()); configPanel.display(); setParentOfTmpDir(configPanel.getParentOfTmpDir()); setParentOfOutDir(configPanel.getParentOfOutDir()); setPixelmedSavedImagesFolder(configPanel.getPixelmedSavedImagesDir()); setDisplayStartUp(configPanel.getDisplayStartup()); } public void storeHostConfigParameters(File hostConfigFile) { root.getChild("tmpDir").setText(parentOfTmpDir); root.getChild("outputDir").setText(parentOfOutDir); root.getChild("displayStartup").setText(displayStartup.toString()); try { FileOutputStream outStream = new FileOutputStream(hostConfigFile); XMLOutputter outToXMLFile = new XMLOutputter(); outToXMLFile.output(document, outStream); outStream.flush(); outStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } List<URL []> EPRs = new ArrayList<URL []>(); int numOfDeplayedServices = 0; Endpoint ep; static HostConfigurator hostConfigurator; public static void main (String [] args){ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Turn off commons loggin for better performance System.setProperty("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog"); hostConfigurator = new HostConfigurator(); boolean startupOK = hostConfigurator.runHostStartupSequence(); if(startupOK == false){ System.exit(0); } /*final long MEGABYTE = 1024L * 1024L; System.out.println("Total heap size: " + (Runtime.getRuntime().maxMemory())/MEGABYTE); System.out.println("Used heap size: " + (Runtime.getRuntime().totalMemory())/MEGABYTE); System.out.println("Free heap size: " + (Runtime.getRuntime().freeMemory())/MEGABYTE);*/ } public static HostConfigurator getHostConfigurator(){ return hostConfigurator; } public HostMainWindow getMainWindow(){ return mainWindow; } public void runHostShutdownSequence(){ //TODO //Host can terminate only if no applications are running (verify applications are not running) List<Application> applications = appMgr.getApplications(); for(Application app : applications){ State state = app.getState(); if(state != null && state.equals(State.EXIT) == false ){ if(app.shutDown() == false){ new ExceptionDialog(app.getName() + " cannot be terminated by host.", "Application current state: " + app.getState().toString() + ".", "Host Shutdown Dialog"); return; } } } System.out.println("XIP Host is shutting down ..."); //Store Host configuration parameters storeHostConfigParameters(hostConfig); //Store Applications appMgr.storeApplications(applications, xipApplicationsConfig); //Perform Grid shutdown that includes store grid locations if(gridMgr.runGridShutDownSequence() == false){ new ExceptionDialog("Error when storing grid locations.", "System will save any modifications made to grid locations.", "Host Shutdown Dialog"); } //Clear content of TmpDir but do not delete TmpDir itself File dir = new File(getParentOfTmpDir()); boolean bln = Util.deleteHostTmpFiles(dir); if(bln == false){ new ExceptionDialog("Not all content of Host TMP directory " + hostTmpDir + " was cleared.", "Only subdirs starting with 'TmpXIP' and ending with '.tmp' and their content is deleted.", "Host Shutdown Dialog"); } XindiceManagerFactory.getInstance().shutdown(); //Clear Xindice directory. Ensures all documents and collections are cleared even when application //does not terminate properly Util.delete(new File("./db")); System.out.println("Thank you for using XIP Host."); System.exit(0); } void loadTestApplications(){ if(OS.contains("Windows")){ if(appMgr.getApplication("TestApp_WG23FileAccess") == null){ try { String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPApplication_WashU_3.bat").getCanonicalPath(); File exeFile = new File(pathExe); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23FileAccess", exeFile, "", "", iconFile)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(appMgr.getApplication("TestApp_WG23NativeModel") == null){ try{ String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPAppNativeModel.bat").getCanonicalPath(); File exeFile = new File(pathExe); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23NativeModel", exeFile, "", "", iconFile)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(appMgr.getApplication("RECIST_Adjudicator") == null){ try { String pathExe = new File("../XIPApp/bin/RECISTFollowUpAdjudicator.bat").getCanonicalPath(); File exeFile = new File(pathExe); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("RECIST_Adjudicator", exeFile, "", "", iconFile)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }else{ if(appMgr.getApplication("TestApp_WG23FileAccess") == null){ try { String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPApplication_WashU_3.sh").getCanonicalPath(); File exeFile = new File(pathExe); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23FileAccess", exeFile, "", "", iconFile)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(appMgr.getApplication("TestApp_WG23NativeModel") == null){ try{ String pathExe = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/XIPAppNativeModel.sh").getCanonicalPath(); File exeFile = new File(pathExe); String pathIcon = new File("./../XIPApp/bin/edu/wustl/xipApplication/samples/ApplicationIcon-16x16.png").getCanonicalPath(); File iconFile = new File(pathIcon); appMgr.addApplication(new Application("TestApp_WG23NativeModel", exeFile, "", "", iconFile)); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public static int adjustForResolution(){ Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int height = (int)screenSize.getHeight(); int preferredHeight = 600; if (height < 768 && height >= 600 ){ preferredHeight = 350; }else if(height < 1024 && height >= 768 ){ preferredHeight = 470; }else if (height >= 1024 && height < 1200){ preferredHeight = 600; }else if(height > 1200 && height <= 1440){ preferredHeight = 800; } return preferredHeight; } }
package org.voltdb.sysprocs; import java.io.File; import java.net.InetAddress; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.voltdb.DependencyPair; import org.voltdb.SystemProcedureExecutionContext; import org.voltdb.ParameterSet; import org.voltdb.ProcInfo; import org.voltdb.VoltDB; import org.voltdb.VoltSystemProcedure; import org.voltdb.VoltTable; import org.voltdb.VoltTable.ColumnInfo; import org.voltdb.VoltType; import org.voltdb.catalog.CommandLog; import org.voltdb.catalog.Connector; import org.voltdb.catalog.Deployment; import org.voltdb.catalog.GroupRef; import org.voltdb.catalog.SnapshotSchedule; import org.voltdb.catalog.User; import org.voltdb.dtxn.DtxnConstants; import org.voltcore.logging.VoltLogger; /** * Access key/value tables of cluster info that correspond to the REST * API members/properties */ @ProcInfo( singlePartition = false ) public class SystemInformation extends VoltSystemProcedure { private static final VoltLogger hostLog = new VoltLogger("HOST"); static final int DEP_DISTRIBUTE = (int) SysProcFragmentId.PF_systemInformationOverview | DtxnConstants.MULTIPARTITION_DEPENDENCY; static final int DEP_AGGREGATE = (int) SysProcFragmentId.PF_systemInformationOverviewAggregate; static final int DEP_systemInformationDeployment = (int) SysProcFragmentId.PF_systemInformationDeployment | DtxnConstants.MULTIPARTITION_DEPENDENCY; static final int DEP_systemInformationAggregate = (int) SysProcFragmentId.PF_systemInformationAggregate; public static final ColumnInfo clusterInfoSchema[] = new ColumnInfo[] { new ColumnInfo("PROPERTY", VoltType.STRING), new ColumnInfo("VALUE", VoltType.STRING) }; @Override public void init() { registerPlanFragment(SysProcFragmentId.PF_systemInformationOverview); registerPlanFragment(SysProcFragmentId.PF_systemInformationOverviewAggregate); registerPlanFragment(SysProcFragmentId.PF_systemInformationDeployment); registerPlanFragment(SysProcFragmentId.PF_systemInformationAggregate); } @Override public DependencyPair executePlanFragment(Map<Integer, List<VoltTable>> dependencies, long fragmentId, ParameterSet params, SystemProcedureExecutionContext context) { if (fragmentId == SysProcFragmentId.PF_systemInformationOverview) { VoltTable result = null; // Choose the lowest site ID on this host to do the info gathering // All other sites should just return empty results tables. if (context.isLowestSiteId()) { result = populateOverviewTable(context); } else { result = new VoltTable( new ColumnInfo(CNAME_HOST_ID, CTYPE_ID), new ColumnInfo("KEY", VoltType.STRING), new ColumnInfo("VALUE", VoltType.STRING)); } return new DependencyPair(DEP_DISTRIBUTE, result); } else if (fragmentId == SysProcFragmentId.PF_systemInformationOverviewAggregate) { VoltTable result = unionTables(dependencies.get(DEP_DISTRIBUTE)); return new DependencyPair(DEP_AGGREGATE, result); } else if (fragmentId == SysProcFragmentId.PF_systemInformationDeployment) { VoltTable result = null; // Choose the lowest site ID on this host to do the info gathering // All other sites should just return empty results tables. if (context.isLowestSiteId()) { result = populateDeploymentProperties(context); } else { result = new VoltTable(clusterInfoSchema); } return new DependencyPair(DEP_systemInformationDeployment, result); } else if (fragmentId == SysProcFragmentId.PF_systemInformationAggregate) { VoltTable result = null; // Check for KEY/VALUE consistency List<VoltTable> answers = dependencies.get(DEP_systemInformationDeployment); for (VoltTable answer : answers) { // if we got an empty table from a non-lowest execution site ID, // ignore it if (answer.getRowCount() == 0) { continue; } // Save the first real answer we got and compare all future // answers with it if (result == null) { result = answer; } else { if (!verifyReturnedTablesMatch(answer, result)) { StringBuilder sb = new StringBuilder(); sb.append("Inconsistent results returned for @SystemInformation: \n"); sb.append("Result sb.append(result.toString()); sb.append("\n"); sb.append("Result sb.append(answer.toString()); sb.append("\n"); hostLog.error(sb.toString()); throw new VoltAbortException(sb.toString()); } } } return new DependencyPair(DEP_systemInformationAggregate, result); } assert(false); return null; } boolean verifyReturnedTablesMatch(VoltTable first, VoltTable second) { boolean retval = true; HashMap<String, String> first_map = new HashMap<String, String>(); HashMap<String, String> second_map = new HashMap<String, String>(); try { while (first.advanceRow()) { first_map.put(first.getString(0), first.getString(1)); } while (second.advanceRow()) { second_map.put(second.getString(0), second.getString(1)); } if (first_map.size() != second_map.size()) { retval = false; } else { for (Entry<String, String> first_entry : first_map.entrySet()) { String second_value = second_map.get(first_entry.getKey()); if (second_value == null || !second_value.equals(first_entry.getValue())) { // Ignore deltas due to LocalCluster's use of // VoltFileRoot if ((((first_entry.getKey())).contains("path") || ((first_entry.getKey())).contains("root")) && (System.getProperty("VoltFilePrefix") != null)) { continue; } else { retval = false; break; } } } } } finally { if (first != null) { first.resetRowPosition(); } if (second != null) { second.resetRowPosition(); } } return retval; } /** * Returns the cluster info requested by the provided selector * @param ctx Internal. Not exposed to the end-user. * @param selector Selector requested * @return The property/value table for the provided selector * @throws VoltAbortException */ public VoltTable[] run(SystemProcedureExecutionContext ctx, String selector) throws VoltAbortException { VoltTable[] results; // This selector provides the old @SystemInformation behavior if (selector.toUpperCase().equals("OVERVIEW")) { results = getOverviewInfo(); } else if (selector.toUpperCase().equals("DEPLOYMENT")) { results = getDeploymentInfo(); } else { throw new VoltAbortException(String.format("Invalid @SystemInformation selector %s.", selector)); } return results; } /** * Retrieve basic management information about the cluster. * Use this procedure to read the ipaddress, hostname, buildstring * and version of each node of the cluster. * * @return A table with three columns: * HOST_ID(INTEGER), KEY(STRING), VALUE(STRING). */ private VoltTable[] getOverviewInfo() { SynthesizedPlanFragment spf[] = new SynthesizedPlanFragment[2]; spf[0] = new SynthesizedPlanFragment(); spf[0].fragmentId = SysProcFragmentId.PF_systemInformationOverview; spf[0].outputDepId = DEP_DISTRIBUTE; spf[0].inputDepIds = new int[] {}; spf[0].multipartition = true; spf[0].parameters = new ParameterSet(); spf[1] = new SynthesizedPlanFragment(); spf[1] = new SynthesizedPlanFragment(); spf[1].fragmentId = SysProcFragmentId.PF_systemInformationOverviewAggregate; spf[1].outputDepId = DEP_AGGREGATE; spf[1].inputDepIds = new int[] { DEP_DISTRIBUTE }; spf[1].multipartition = false; spf[1].parameters = new ParameterSet(); return executeSysProcPlanFragments(spf, DEP_AGGREGATE); } private VoltTable[] getDeploymentInfo() { VoltTable[] results; SynthesizedPlanFragment pfs[] = new SynthesizedPlanFragment[2]; // create a work fragment to gather deployment data from each of the sites. pfs[1] = new SynthesizedPlanFragment(); pfs[1].fragmentId = SysProcFragmentId.PF_systemInformationDeployment; pfs[1].outputDepId = DEP_systemInformationDeployment; pfs[1].inputDepIds = new int[]{}; pfs[1].multipartition = true; pfs[1].parameters = new ParameterSet(); //pfs[1].parameters.setParameters((byte)interval, now); // create a work fragment to aggregate the results. pfs[0] = new SynthesizedPlanFragment(); pfs[0].fragmentId = SysProcFragmentId.PF_systemInformationAggregate; pfs[0].outputDepId = DEP_systemInformationAggregate; pfs[0].inputDepIds = new int[]{DEP_systemInformationDeployment}; pfs[0].multipartition = false; pfs[0].parameters = new ParameterSet(); // distribute and execute these fragments providing pfs and id of the // aggregator's output dependency table. results = executeSysProcPlanFragments(pfs, DEP_systemInformationAggregate); return results; } public static VoltTable constructOverviewTable() { return new VoltTable( new ColumnInfo(VoltSystemProcedure.CNAME_HOST_ID, VoltSystemProcedure.CTYPE_ID), new ColumnInfo("KEY", VoltType.STRING), new ColumnInfo("VALUE", VoltType.STRING)); } /** * Accumulate per-host information and return as a table. * This function does the real work. Everything else is * boilerplate sysproc stuff. */ private VoltTable populateOverviewTable(SystemProcedureExecutionContext context) { VoltTable vt = constructOverviewTable(); int hostId = VoltDB.instance().getHostMessenger().getHostId(); // host name and IP address. InetAddress addr = org.voltcore.utils.CoreUtils.getLocalAddress(); vt.addRow(hostId, "IPADDRESS", addr.getHostAddress()); vt.addRow(hostId, "HOSTNAME", addr.getHostName()); // build string vt.addRow(hostId, "BUILDSTRING", VoltDB.instance().getBuildString()); // version vt.addRow(hostId, "VERSION", VoltDB.instance().getVersionString()); // catalog path String path = VoltDB.instance().getConfig().m_pathToCatalog; if (!path.startsWith("http")) path = (new File(path)).getAbsolutePath(); vt.addRow(hostId, "CATALOG", path); // deployment path path = VoltDB.instance().getConfig().m_pathToDeployment; if (!path.startsWith("http")) path = (new File(path)).getAbsolutePath(); vt.addRow(hostId, "DEPLOYMENT", path); String cluster_state = VoltDB.instance().getMode().toString(); vt.addRow(hostId, "CLUSTERSTATE", cluster_state); String replication_role = VoltDB.instance().getReplicationRole().toString(); vt.addRow(hostId, "REPLICATIONROLE", replication_role); vt.addRow(hostId, "LASTCATALOGUPDATETXNID", Long.toString(VoltDB.instance().getCatalogContext().m_transactionId)); vt.addRow(hostId, "CATALOGCRC", Long.toString(VoltDB.instance().getCatalogContext().getCatalogCRC())); if (VoltDB.instance().isIV2Enabled()) { vt.addRow(hostId, "IV2ENABLED", true); } return vt; } private VoltTable populateDeploymentProperties(SystemProcedureExecutionContext context) { VoltTable results = new VoltTable(clusterInfoSchema); // it would be awesome if these property names could come // from the RestApiDescription.xml (or the equivalent thereof) someday --izzy results.addRow("voltdbroot", context.getCluster().getVoltroot()); Deployment deploy = context.getCluster().getDeployment().get("deployment"); results.addRow("hostcount", Integer.toString(deploy.getHostcount())); results.addRow("kfactor", Integer.toString(deploy.getKfactor())); results.addRow("sitesperhost", Integer.toString(deploy.getSitesperhost())); String http_enabled = "false"; int http_port = context.getCluster().getHttpdportno(); if (http_port != -1) { http_enabled = "true"; results.addRow("httpport", Integer.toString(http_port)); } results.addRow("httpenabled", http_enabled); String json_enabled = "false"; if (context.getCluster().getJsonapi()) { json_enabled = "true"; } results.addRow("jsonenabled", json_enabled); SnapshotSchedule snaps = context.getDatabase().getSnapshotschedule().get("default"); String snap_enabled = "false"; if (snaps != null && snaps.getEnabled()) { snap_enabled = "true"; String snap_freq = Integer.toString(snaps.getFrequencyvalue()) + snaps.getFrequencyunit(); results.addRow("snapshotpath", snaps.getPath()); results.addRow("snapshotprefix", snaps.getPrefix()); results.addRow("snapshotfrequency", snap_freq); results.addRow("snapshotretain", Integer.toString(snaps.getRetain())); } results.addRow("snapshotenabled", snap_enabled); Connector export_conn = context.getDatabase().getConnectors().get("0"); String export_enabled = "false"; if (export_conn != null && export_conn.getEnabled()) { export_enabled = "true"; results.addRow("exportoverflowpath", context.getCluster().getExportoverflow()); } results.addRow("export", export_enabled); String partition_detect_enabled = "false"; if (context.getCluster().getNetworkpartition()) { partition_detect_enabled = "true"; String partition_detect_snapshot_path = context.getCluster().getFaultsnapshots().get("CLUSTER_PARTITION").getPath(); String partition_detect_snapshot_prefix = context.getCluster().getFaultsnapshots().get("CLUSTER_PARTITION").getPrefix(); results.addRow("snapshotpath", partition_detect_snapshot_path); results.addRow("partitiondetectionsnapshotprefix", partition_detect_snapshot_prefix); } results.addRow("partitiondetection", partition_detect_enabled); results.addRow("heartbeattimeout", Integer.toString(context.getCluster().getHeartbeattimeout())); results.addRow("adminport", Integer.toString(context.getCluster().getAdminport())); String adminstartup = "false"; if (context.getCluster().getAdminstartup()) { adminstartup = "true"; } results.addRow("adminstartup", adminstartup); String command_log_enabled = "false"; // log name is MAGIC, you knoooow CommandLog command_log = context.getCluster().getLogconfig().get("log"); if (command_log.getEnabled()) { command_log_enabled = "true"; String command_log_mode = "async"; if (command_log.getSynchronous()) { command_log_mode = "sync"; } String command_log_path = command_log.getLogpath(); String command_log_snaps = command_log.getInternalsnapshotpath(); String command_log_fsync_interval = Integer.toString(command_log.getFsyncinterval()); String command_log_max_txns = Integer.toString(command_log.getMaxtxns()); results.addRow("commandlogmode", command_log_mode); results.addRow("commandlogfreqtime", command_log_fsync_interval); results.addRow("commandlogfreqtxns", command_log_max_txns); results.addRow("commandlogpath", command_log_path); results.addRow("commandlogsnapshotpath", command_log_snaps); } results.addRow("commandlogenabled", command_log_enabled); String users = ""; for (User user : context.getDatabase().getUsers()) { users += addEscapes(user.getTypeName()); if (user.getGroups() != null && user.getGroups().size() > 0) { users += ":"; for (GroupRef gref : user.getGroups()) { users += addEscapes(gref.getGroup().getTypeName()); users += ","; } users = users.substring(0, users.length() - 1); } users += ";"; } results.addRow("users", users); return results; } private String addEscapes(String name) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < name.length(); i++) { if (name.charAt(i) == ';' || name.charAt(i) == ':' || name.charAt(i) == '\\') { sb.append('\\'); } sb.append(name.charAt(i)); } return sb.toString(); } }
package de.tr7zw.nbtinjector; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; import org.bukkit.Bukkit; import de.tr7zw.changeme.nbtapi.ClassWrapper; import de.tr7zw.changeme.nbtapi.NBTCompound; import de.tr7zw.changeme.nbtapi.NBTContainer; import de.tr7zw.changeme.nbtapi.NBTEntity; import de.tr7zw.changeme.nbtapi.NBTReflectionUtil; import de.tr7zw.changeme.nbtapi.NBTTileEntity; import de.tr7zw.changeme.nbtapi.NbtApiException; import de.tr7zw.changeme.nbtapi.ObjectCreator; import de.tr7zw.changeme.nbtapi.ReflectionMethod; import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion; import javassist.ClassPool; public class NBTInjector { static Logger logger = Logger.getLogger("NBTInjector"); private static final List<String> skippingEntities = Arrays.asList(new String[]{"minecraft:player", "minecraft:fishing_bobber", "minecraft:lightning_bolt"}); //These are broken/won't work private static final Map<String, String> classMappings = new HashMap<>(); static { classMappings.put("minecraft:wandering_trader", "VillagerTrader"); classMappings.put("minecraft:trader_llama", "LlamaTrader"); classMappings.put("minecraft:area_effect_cloud", "AreaEffectCloud"); classMappings.put("minecraft:donkey", "HorseDonkey"); classMappings.put("minecraft:ender_dragon", "EnderDragon"); classMappings.put("minecraft:skeleton_horse", "HorseSkeleton"); classMappings.put("minecraft:fireball", "LargeFireball"); classMappings.put("minecraft:mule", "HorseMule"); classMappings.put("minecraft:zombie_horse", "HorseZombie"); classMappings.put("minecraft:mooshroom", "MushroomCow"); } /** * Replaces the vanilla classes with Wrapped classes that support custom NBT. * This method needs to be called during onLoad so classes are replaced before worlds load. * If your plugin adds a new Entity(probably during onLoad) recall this method so it's class gets Wrapped. */ public static void inject() { try { ClassPool classPool = ClassPool.getDefault(); logger.info("[NBTINJECTOR] Injecting Entity classes..."); if(MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_10_R1.getVersionId()) { for (Map.Entry<String, Class<?>> entry : new HashSet<>(Entity.getCMap().entrySet())) { try { if (INBTWrapper.class.isAssignableFrom(entry.getValue())) { continue; }//Already injected int entityId = Entity.getFMap().get(entry.getValue()); Class<?> wrapped = ClassGenerator.wrapEntity(classPool, entry.getValue(), "__extraData"); Entity.getCMap().put(entry.getKey(), wrapped); Entity.getDMap().put(wrapped, entry.getKey()); Entity.getEMap().put(entityId, wrapped); Entity.getFMap().put(wrapped, entityId); } catch (Exception e) { throw new RuntimeException("Exception while injecting " + entry.getKey(), e); } } } else if (MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_12_R1.getVersionId()){ Object registry = Entity.getRegistry(); Map<Object, Object> inverse = new HashMap<>(); Set<?> it = new HashSet<>((Set<?>) ReflectionMethod.REGISTRY_KEYSET.run(registry)); for(Object mckey : it) { Class<?> tileclass = (Class<?>) ReflectionMethod.REGISTRY_GET.run(registry, mckey); inverse.put(tileclass, mckey); try { if (INBTWrapper.class.isAssignableFrom(tileclass)) { continue; }//Already injected Class<?> wrapped = ClassGenerator.wrapEntity(classPool, tileclass, "__extraData"); ReflectionMethod.REGISTRY_SET.run(registry, mckey, wrapped); inverse.put(wrapped, mckey); } catch (Exception e) { throw new RuntimeException("Exception while injecting " + mckey, e); } } Field inverseField = registry.getClass().getDeclaredField("b"); setFinal(registry, inverseField, inverse); } else if (MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_13_R2.getVersionId()) { Object entityRegistry = ClassWrapper.NMS_IREGISTRY.getClazz().getField("ENTITY_TYPE").get(null); Set<?> registryentries = new HashSet<>((Set<?>) ReflectionMethod.REGISTRYMATERIALS_KEYSET.run(entityRegistry)); for(Object mckey : registryentries) { Object entityTypesObj = ReflectionMethod.REGISTRYMATERIALS_GET.run(entityRegistry, mckey); Field supplierField = entityTypesObj.getClass().getDeclaredField("aT"); Field classField = entityTypesObj.getClass().getDeclaredField("aS"); classField.setAccessible(true); supplierField.setAccessible(true); Function<Object,Object> function = (Function<Object,Object>) supplierField.get(entityTypesObj); Class<?> nmsclass = (Class<?>) classField.get(entityTypesObj); try { if (INBTWrapper.class.isAssignableFrom(nmsclass)) { continue; }//Already injected Class<?> wrapped = ClassGenerator.wrapEntity(classPool, nmsclass, "__extraData"); setFinal(entityTypesObj, classField, wrapped); setFinal(entityTypesObj, supplierField, new Function<Object, Object>() { @Override public Object apply(Object t) { try { return wrapped.getConstructor(ClassWrapper.NMS_WORLD.getClazz()).newInstance(t); }catch(Exception ex) { logger.log(Level.SEVERE, "Error while creating custom entity instance! ",ex); return function.apply(t);//Fallback to the original one } } }); } catch (Exception e) { throw new RuntimeException("Exception while injecting " + mckey, e); } } } else { //1.14+ Object entityRegistry = ClassWrapper.NMS_IREGISTRY.getClazz().getField("ENTITY_TYPE").get(null); Set<?> registryentries = new HashSet<>((Set<?>) ReflectionMethod.REGISTRYMATERIALS_KEYSET.run(entityRegistry)); for(Object mckey : registryentries) { if(skippingEntities.contains(mckey.toString())) { logger.info("Skipping, won't be able add NBT to '" + mckey + "' entities!"); continue; } Object entityTypesObj = ReflectionMethod.REGISTRYMATERIALS_GET.run(entityRegistry, mckey); Field creatorField = entityTypesObj.getClass().getDeclaredField("aZ"); creatorField.setAccessible(true); Object creator = creatorField.get(entityTypesObj); Method createEntityMethod = creator.getClass().getMethod("create", ClassWrapper.NMS_ENTITYTYPES.getClazz(), ClassWrapper.NMS_WORLD.getClazz()); createEntityMethod.setAccessible(true); Class<?> nmsclass = null; try { nmsclass = createEntityMethod.invoke(creator, entityTypesObj, null).getClass(); }catch(Exception ignore) { // ignore } if(nmsclass == null) { String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; String name = mckey.toString().replace("minecraft:", ""); name = name.substring(0, 1).toUpperCase() + name.substring(1); name = "Entity" + name; if(classMappings.containsKey(mckey.toString())) name = "Entity" + classMappings.get(mckey.toString()); try { nmsclass = Class.forName("net.minecraft.server." + version + "." + name); }catch(Exception ignore) { logger.info("Not found: " + "net.minecraft.server." + version + "." + name); // ignore } } if(nmsclass == null) { logger.info("Wasn't able to create an Entity instace, won't be able add NBT to '" + mckey + "' entities!"); continue; } try { if (INBTWrapper.class.isAssignableFrom(nmsclass)) { continue; }//Already injected Class<?> wrapped = ClassGenerator.wrapEntity(classPool, nmsclass, "__extraData"); setFinal(entityTypesObj, creatorField, ClassGenerator.createEntityTypeWrapper(classPool, wrapped).newInstance()); } catch (Exception e) { throw new RuntimeException("Exception while injecting " + mckey, e); } } } logger.info("[NBTINJECTOR] Injecting Tile Entity classes..."); if(MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_10_R1.getVersionId()) { for (Map.Entry<String, Class<?>> entry : new HashSet<>(TileEntity.getFMap().entrySet())) { try { if (INBTWrapper.class.isAssignableFrom(entry.getValue())) { continue; }//Already injected Class<?> wrapped = ClassGenerator.wrapTileEntity(classPool, entry.getValue(), "__extraData"); TileEntity.getFMap().put(entry.getKey(), wrapped); TileEntity.getGMap().put(wrapped, entry.getKey()); } catch (Exception e) { throw new RuntimeException("Exception while injecting " + entry.getKey(), e); } } } else if (MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_12_R1.getVersionId()){ Object registry = TileEntity.getRegistry(); Map<Object, Object> inverse = new HashMap<>(); Set<?> it = new HashSet<>((Set<?>) ReflectionMethod.REGISTRY_KEYSET.run(registry)); for(Object mckey : it) { Class<?> tileclass = (Class<?>) ReflectionMethod.REGISTRY_GET.run(registry, mckey); inverse.put(tileclass, mckey); try { if (INBTWrapper.class.isAssignableFrom(tileclass)) { continue; }//Already injected Class<?> wrapped = ClassGenerator.wrapTileEntity(classPool, tileclass, "__extraData"); ReflectionMethod.REGISTRY_SET.run(registry, mckey, wrapped); inverse.put(wrapped, mckey); } catch (Exception e) { throw new RuntimeException("Exception while injecting " + mckey, e); } } Field inverseField = registry.getClass().getDeclaredField("b"); setFinal(registry, inverseField, inverse); } else { // 1.13+ Object tileRegistry = ClassWrapper.NMS_IREGISTRY.getClazz().getField("BLOCK_ENTITY_TYPE").get(null); Set<?> registryentries = new HashSet<>((Set<?>) ReflectionMethod.REGISTRYMATERIALS_KEYSET.run(tileRegistry)); for(Object mckey : registryentries) { Object tileEntityTypesObj = ReflectionMethod.REGISTRYMATERIALS_GET.run(tileRegistry, mckey); String supplierFieldName = "A"; if(MinecraftVersion.getVersion().getVersionId() >= MinecraftVersion.MC1_14_R1.getVersionId()) supplierFieldName = "H"; Field supplierField = tileEntityTypesObj.getClass().getDeclaredField(supplierFieldName); supplierField.setAccessible(true); Supplier<Object> supplier = (Supplier<Object>) supplierField.get(tileEntityTypesObj); Class<?> nmsclass = supplier.get().getClass(); try { if (INBTWrapper.class.isAssignableFrom(nmsclass)) { continue; }//Already injected Class<?> wrapped = ClassGenerator.wrapTileEntity(classPool, nmsclass, "__extraData"); setFinal(tileEntityTypesObj, supplierField, new Supplier<Object>() { @Override public Object get() { try { return wrapped.newInstance(); } catch (InstantiationException | IllegalAccessException e) { logger.log(Level.SEVERE, "Error while creating custom tile instance! ",e); return supplier.get(); //Use the original one as fallback } } }); } catch (Exception e) { throw new RuntimeException("Exception while injecting " + mckey, e); } } } } catch (Exception e) { throw new RuntimeException(e); } } private static NBTCompound getNbtData(Object object) { if (object instanceof INBTWrapper) { return ((INBTWrapper) object).getNbtData(); } return null; } /** * Entities that have just been spawned(from plugins or natually) may use the wrong(Vanilla) class. * Calling this method removes the wrong entity and respawns it using the correct class. It also tries * to keep all data of the original entity, but some stuff like passengers will probably cause problems. * Recalling this method on a patched Entity doesn nothing and returns the Entity instance. * * WARNING: This causes the entity to get a new Bukkit Entity instance. For other plugins the entity will * be a dead/removed entity, even if it's still kinda there. Bestcase you spawn an Entity and directly replace * your instance with a patched one. * Also, for players ingame the entity will quickly flash, since it's respawned. * * @param entity Entity to respawn with the correct class. * @return Entity The new instance of the entity. */ public static org.bukkit.entity.Entity patchEntity(org.bukkit.entity.Entity entity){ if (entity == null) { return null; } try { Object ent = NBTReflectionUtil.getNMSEntity(entity); if (!(ent instanceof INBTWrapper)) {//Replace Entity with custom one Object cworld = ClassWrapper.CRAFT_WORLD.getClazz().cast(entity.getWorld()); Object nmsworld = ReflectionMethod.CRAFT_WORLD_GET_HANDLE.run(cworld); NBTContainer oldNBT = new NBTContainer(new NBTEntity(entity).getCompound()); Method create = ClassWrapper.NMS_ENTITYTYPES.getClazz().getMethod("a", ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), ClassWrapper.NMS_WORLD.getClazz()); String id = ""; if(MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_10_R1.getVersionId()) { id = Entity.getBackupMap().get(ent.getClass()); } else if(MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_13_R1.getVersionId()){ id = ReflectionMethod.REGISTRY_GET_INVERSE.run(Entity.getRegistry(), ent.getClass()).toString(); } else { id = (String) ReflectionMethod.NMS_ENTITY_GETSAVEID.run(ent); } oldNBT.setString("id", id); oldNBT.removeKey("UUIDMost"); oldNBT.removeKey("UUIDLeast"); entity.remove(); Object newEntity = create.invoke(null, oldNBT.getCompound(), nmsworld); if(newEntity instanceof Optional<?>) newEntity = ((Optional<?>)newEntity).get(); Method spawn = ClassWrapper.NMS_WORLD.getClazz().getMethod("addEntity", ClassWrapper.NMS_ENTITY.getClazz()); spawn.invoke(nmsworld, newEntity); logger.info("Created patched instance: " + newEntity.getClass().getName()); Method asBukkit = newEntity.getClass().getMethod("getBukkitEntity"); return (org.bukkit.entity.Entity) asBukkit.invoke(newEntity); } } catch (Exception e) { throw new NbtApiException("Error while patching an Entity '" + entity + "'", e); } return entity; } /** * Gets the persistant NBTCompound from a given entity. If the Entity isn't yet patched, * this method will return null. * * @param entity Entity to get the NBTCompound from * @return NBTCompound instance */ public static NBTCompound getNbtData(org.bukkit.entity.Entity entity) { if (entity == null) { return null; } try { Object ent = NBTReflectionUtil.getNMSEntity(entity); if (!(ent instanceof INBTWrapper)) { logger.info("Entity wasn't the correct class! '" + ent.getClass().getName() + "'"); } /*if (!(ent instanceof INBTWrapper)) {//Replace Entity with custom one entity = patchEntity(entity); System.out.println("Autopatched Entity: " + entity); return getNbtData(NBTReflectionUtil.getNMSEntity(entity)); return null; // For now don't do anything, just return null. }*/ return getNbtData(ent); } catch (Exception e) { throw new NbtApiException("Error while getting the NBT from an Entity '" + entity + "'.", e); } } /** * Gets the persistant NBTCompound from a given TileEntity. If the Tile isn't yet patched, * this method will autopatch it. This will unlink the given BlockState, so calling block.getState() * again may be necessary. This behavior may change in the future. * * @param tile TileEntity to get the NBTCompound from * @return NBTCompound instance */ public static NBTCompound getNbtData(org.bukkit.block.BlockState tile) { if (tile == null) { return null; } try { Object pos = ObjectCreator.NMS_BLOCKPOSITION.getInstance(tile.getX(), tile.getY(), tile.getZ()); Object cworld = ClassWrapper.CRAFT_WORLD.getClazz().cast(tile.getWorld()); Object nmsworld = ReflectionMethod.CRAFT_WORLD_GET_HANDLE.run(cworld); Object tileEntity = ReflectionMethod.NMS_WORLD_GET_TILEENTITY.run(nmsworld, pos); if(tileEntity == null) { // Not a tile block return null; } if (!(tileEntity instanceof INBTWrapper)) { //Loading Updated Tile Object tileEntityUpdated; if(MinecraftVersion.getVersion() == MinecraftVersion.MC1_9_R1) { tileEntityUpdated = ReflectionMethod.TILEENTITY_LOAD_LEGACY191.run(null, null, new NBTTileEntity(tile).getCompound()); } else if(MinecraftVersion.getVersion() == MinecraftVersion.MC1_8_R3 || MinecraftVersion.getVersion() == MinecraftVersion.MC1_9_R2) { tileEntityUpdated = ReflectionMethod.TILEENTITY_LOAD_LEGACY183.run(null, new NBTTileEntity(tile).getCompound()); } else if(MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_12_R1.getVersionId()){ tileEntityUpdated = ReflectionMethod.TILEENTITY_LOAD_LEGACY1121.run(null, nmsworld, new NBTTileEntity(tile).getCompound()); } else { tileEntityUpdated = ReflectionMethod.TILEENTITY_LOAD.run(null, new NBTTileEntity(tile).getCompound()); } ReflectionMethod.NMS_WORLD_REMOVE_TILEENTITY.run(nmsworld, pos); ReflectionMethod.NMS_WORLD_SET_TILEENTITY.run(nmsworld, pos, tileEntityUpdated); return getNbtData(tileEntityUpdated); } return getNbtData(tileEntity); } catch (Exception e) { throw new RuntimeException(e); } } private static void setFinal(Object obj, Field field, Object newValue) throws Exception { field.setAccessible(true); Field modifiersField = Field.class.getDeclaredField("modifiers"); modifiersField.setAccessible(true); modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); field.set(obj, newValue); } private static Field getAccessable(Field field) { field.setAccessible(true); return field; } static class Entity { private static Map<Class<?>, String> backupMap = new HashMap<>(); static { try { if(MinecraftVersion.getVersion().getVersionId() <= MinecraftVersion.MC1_10_R1.getVersionId()) { backupMap.putAll(getDMap()); } } catch (ReflectiveOperationException e) { e.printStackTrace(); } } static Object getRegistry() throws ReflectiveOperationException { return getAccessable(ClassWrapper.NMS_ENTITYTYPES.getClazz().getDeclaredField("b")).get(null); } static Map<Class<?>, String> getBackupMap() throws ReflectiveOperationException { return backupMap; } static Map<String, Class<?>> getCMap() throws ReflectiveOperationException { return (Map<String, Class<?>>) getAccessable(ClassWrapper.NMS_ENTITYTYPES.getClazz().getDeclaredField("c")).get(null); } static Map<Class<?>, String> getDMap() throws ReflectiveOperationException { return (Map<Class<?>, String>) getAccessable(ClassWrapper.NMS_ENTITYTYPES.getClazz().getDeclaredField("d")).get(null); } static Map<Integer, Class<?>> getEMap() throws ReflectiveOperationException { return (Map<Integer, Class<?>>) getAccessable(ClassWrapper.NMS_ENTITYTYPES.getClazz().getDeclaredField("e")).get(null); } static Map<Class<?>, Integer> getFMap() throws ReflectiveOperationException { return (Map<Class<?>, Integer>) getAccessable(ClassWrapper.NMS_ENTITYTYPES.getClazz().getDeclaredField("f")).get(null); } } static class TileEntity { static Object getRegistry() throws ReflectiveOperationException { return getAccessable(ClassWrapper.NMS_TILEENTITY.getClazz().getDeclaredField("f")).get(null); } static Map<String, Class<?>> getFMap() throws ReflectiveOperationException { return (Map<String, Class<?>>) getAccessable(ClassWrapper.NMS_TILEENTITY.getClazz().getDeclaredField("f")).get(null); } static Map<Class<?>, String> getGMap() throws ReflectiveOperationException { return (Map<Class<?>, String>) getAccessable(ClassWrapper.NMS_TILEENTITY.getClazz().getDeclaredField("g")).get(null); } } }
package com.voxelwind.nbt.util; import com.voxelwind.nbt.tags.*; import lombok.AccessLevel; import lombok.NoArgsConstructor; import java.util.HashMap; import java.util.Map; @NoArgsConstructor(access = AccessLevel.PRIVATE) public class CompoundTagBuilder { private final Map<String, Tag<?>> tagMap = new HashMap<>(); public static CompoundTagBuilder builder() { return new CompoundTagBuilder(); } public static CompoundTagBuilder from(CompoundTag tag) { CompoundTagBuilder builder = new CompoundTagBuilder(); builder.tagMap.putAll(tag.getValue()); return builder; } public CompoundTagBuilder tag(Tag<?> tag) { tagMap.put(tag.getName(), tag); return this; } public CompoundTagBuilder tag(String name, byte value) { return tag(new ByteTag(name, value)); } public CompoundTagBuilder tag(String name, byte [] value) { return tag(new ByteArrayTag(name, value)); } public CompoundTagBuilder tag(String name, double value) { return tag(new DoubleTag(name, value)); } public CompoundTagBuilder tag(String name, float value) { return tag(new FloatTag(name, value)); } public CompoundTagBuilder tag(String name, int[] value) { return tag(new IntArrayTag(name, value)); } public CompoundTagBuilder tag(String name, int value) { return tag(new IntTag(name, value)); } public CompoundTagBuilder tag(String name, long value) { return tag(new LongTag(name, value)); } public CompoundTagBuilder tag(String name, short value) { return tag(new ShortTag(name, value)); } public CompoundTagBuilder tag(String name, String value) { return tag(new StringTag(name, value)); } public CompoundTag buildRootTag() { return new CompoundTag("", tagMap); } public CompoundTag build(String tagName) { return new CompoundTag(tagName, tagMap); } }
package io.tetrapod.core.web; import static io.netty.handler.codec.http.HttpHeaders.isKeepAlive; import static io.netty.handler.codec.http.HttpHeaders.setContentLength; import static io.netty.handler.codec.http.HttpHeaders.Names.*; import static io.netty.handler.codec.http.HttpResponseStatus.*; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; import static io.tetrapod.protocol.core.Core.*; import static io.tetrapod.protocol.core.CoreContract.*; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.*; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.*; import io.netty.handler.codec.http.websocketx.*; import io.netty.util.CharsetUtil; import io.netty.util.ReferenceCountUtil; import io.tetrapod.core.*; import io.tetrapod.core.json.JSONArray; import io.tetrapod.core.json.JSONObject; import io.tetrapod.core.registry.EntityToken; import io.tetrapod.core.rpc.*; import io.tetrapod.core.rpc.Error; import io.tetrapod.core.serialize.datasources.ByteBufDataSource; import io.tetrapod.core.utils.Util; import io.tetrapod.protocol.core.*; import java.io.IOException; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.codahale.metrics.Timer; import com.codahale.metrics.Timer.Context; public class WebHttpSession extends WebSession { protected static final Logger logger = LoggerFactory.getLogger(WebHttpSession.class); public static final Timer requestTimes = Metrics.timer(WebHttpSession.class, "requests", "time"); private static final int FLOOD_TIME_PERIOD = 2000; private static final int FLOOD_WARN = 200; private static final int FLOOD_IGNORE = 300; private static final int FLOOD_KILL = 400; private volatile long floodPeriod; private int reqCounter = 0; private final String wsLocation; private WebSocketServerHandshaker handshaker; private Map<Integer, ChannelHandlerContext> contexts; public WebHttpSession(SocketChannel ch, Session.Helper helper, Map<String, WebRoot> roots, String wsLocation) { super(ch, helper); this.wsLocation = wsLocation; ch.pipeline().addLast("codec-http", new HttpServerCodec()); ch.pipeline().addLast("aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("api", this); ch.pipeline().addLast("deflater", new HttpContentCompressor(6)); ch.pipeline().addLast("files", new WebStaticFileHandler(roots)); } @Override public void checkHealth() { if (isConnected()) { timeoutPendingRequests(); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof FullHttpRequest) { handleHttpRequest(ctx, (FullHttpRequest) msg); } else if (msg instanceof WebSocketFrame) { handleWebSocketFrame(ctx, (WebSocketFrame) msg); } } @Override public void channelActive(final ChannelHandlerContext ctx) throws Exception { fireSessionStartEvent(); scheduleHealthCheck(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { fireSessionStopEvent(); cancelAllPendingRequests(); } public synchronized boolean isWebSocket() { return handshaker != null; } public synchronized void initLongPoll() { if (contexts == null) { contexts = new HashMap<>(); } } private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), new CloseWebSocketFrame()); return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (!(frame instanceof TextWebSocketFrame)) { throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName())); } String request = ((TextWebSocketFrame) frame).text(); ReferenceCountUtil.release(frame); try { JSONObject jo = new JSONObject(request); WebContext webContext = new WebContext(jo); RequestHeader header = webContext.makeRequestHeader(this, null); readAndDispatchRequest(header, webContext.getRequestParams()); return; } catch (IOException e) { logger.error("error processing websocket request", e); ctx.channel().writeAndFlush(new TextWebSocketFrame("Illegal request: " + request)); } } private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception { if (logger.isDebugEnabled()) { synchronized (this) { logger.debug(String.format("%s REQUEST[%d] = %s : %s", this, ++reqCounter, ctx.channel().remoteAddress(), req.getUri())); } } // see if we need to start a web socket session if (wsLocation.equals(req.getUri())) { WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(wsLocation, null, false); synchronized (this) { handshaker = wsFactory.newHandshaker(req); } if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { handshaker.handshake(ctx.channel(), req); } } else { final Context metricContext = requestTimes.time(); if (!req.getDecoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } // this handles long-polling calls when we fall back to long-polling for browsers with no websockets if (req.getUri().equals("/poll")) { handlePoll(ctx, req); return; } // check for web-route handler final WebRoute route = relayHandler.getWebRoutes().findRoute(req.getUri()); if (route != null) { handleWebRoute(ctx, req, route); } else { // pass request down the pipeline ctx.fireChannelRead(req); } metricContext.stop(); } } private String getContent(final FullHttpRequest req) { final ByteBuf contentBuf = req.content(); try { return contentBuf.toString(Charset.forName("UTF-8")); } finally { contentBuf.release(); } } private void handlePoll(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception { //logger.debug("{} POLLER: {} keepAlive = {}", this, req.getUri(), HttpHeaders.isKeepAlive(req)); final JSONObject params = new JSONObject(getContent(req)); // authenticate this session, if needed if (params.has("_token")) { final EntityToken t = EntityToken.decode(params.getString("_token")); if (t != null) { if (relayHandler.validate(t.entityId, t.nonce)) { setTheirEntityId(t.entityId); setTheirEntityType(Core.TYPE_CLIENT); } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return; } } } initLongPoll(); if (params.has("_requestId")) { logger.debug("{} RPC: structId={}", this, params.getInt("_structId")); // dispatch a request final RequestHeader header = WebContext.makeRequestHeader(this, null, params); header.fromType = Core.TYPE_CLIENT; header.fromId = getTheirEntityId(); synchronized (contexts) { contexts.put(header.requestId, ctx); } readAndDispatchRequest(header, params); } else { getDispatcher().dispatch(new Runnable() { public void run() { final LongPollQueue messages = LongPollQueue.getQueue(getTheirEntityId()); final long startTime = System.currentTimeMillis(); // long poll -- wait until there are messages in queue, and return them assert messages != null; // we grab a lock so only one poll request processes at a time longPoll(25, messages, startTime, ctx, req); } }); } } private void longPoll(final int millis, final LongPollQueue messages, final long startTime, final ChannelHandlerContext ctx, final FullHttpRequest req) { getDispatcher().dispatch(millis, TimeUnit.MILLISECONDS, new Runnable() { public void run() { if (messages.tryLock()) { try { if (messages.size() > 0) { final JSONArray arr = new JSONArray(); while (!messages.isEmpty()) { JSONObject jo = messages.poll(); if (jo != null) { arr.put(jo); } } logger.debug("{} long poll {} has {} items\n", this, messages.getEntityId(), messages.size()); ctx.writeAndFlush(makeFrame(new JSONObject().put("messages", arr), HttpHeaders.isKeepAlive(req))); } else { if (System.currentTimeMillis() - startTime > Util.ONE_SECOND * 10) { ctx.writeAndFlush(makeFrame(new JSONObject().put("messages", new JSONArray()), HttpHeaders.isKeepAlive(req))); } else { // wait a bit and check again longPoll(50, messages, startTime, ctx, req); } } } finally { messages.unlock(); } } else { ctx.writeAndFlush(makeFrame(new JSONObject().put("error", "locked"), HttpHeaders.isKeepAlive(req))); } } }); } // handle a JSON API call private void handleWebRoute(final ChannelHandlerContext ctx, final FullHttpRequest req, final WebRoute route) throws Exception { final WebContext context = new WebContext(req, route.path); final RequestHeader header = context.makeRequestHeader(this, route); if (header != null) { //final long t0 = System.currentTimeMillis(); logger.debug("{} WEB API REQUEST: {} keepAlive = {}", this, req.getUri(), HttpHeaders.isKeepAlive(req)); header.requestId = requestCounter.incrementAndGet(); header.fromType = Core.TYPE_WEBAPI; header.fromId = getMyEntityId(); final ResponseHandler handler = new ResponseHandler() { @Override public void onResponse(Response res) { //logger.info("{} WEB API RESPONSE: {} {} ms", WebHttpSession.this, res, (System.currentTimeMillis() - t0)); handleWebAPIResponse(ctx, req, res); } }; // TEMP DEBUG LOGGING String debug = String.format("webapi: %s\nHEADERS\n%s\nPARAMS\n%s\nCONTENT\n%s", req.getUri(), getHeaders(req).toString(), context.getRequestParams().toString(), req.content().toString(CharsetUtil.UTF_8)); logger.debug(debug); try { if (header.structId == WebAPIRequest.STRUCT_ID) { // @webapi() generic WebAPIRequest call final WebAPIRequest request = new WebAPIRequest(route.path, getHeaders(req).toString(), context.getRequestParams() .toString(), req.content().toString(CharsetUtil.UTF_8)); final int toEntityId = relayHandler.getAvailableService(header.contractId); if (toEntityId != 0) { final Session ses = relayHandler.getRelaySession(toEntityId, header.contractId); if (ses != null) { header.contractId = Core.CONTRACT_ID; header.toId = toEntityId; //logger.info("{} WEB API REQEUST ROUTING TO {} {}", this, toEntityId, header.dump()); relayRequest(header, request, ses, handler); } else { logger.debug("{} Could not find a relay session for {} {}", this, header.toId, header.contractId); handler.onResponse(new Error(ERROR_SERVICE_UNAVAILABLE)); } } else { logger.debug("{} Could not find a service for {}", this, header.contractId); handler.onResponse(new Error(ERROR_SERVICE_UNAVAILABLE)); } } else { // @web() specific Request mapping final Structure request = readRequest(header, context.getRequestParams()); if (request != null) { relayRequest(header, request, handler); } else { handler.onResponse(new Error(ERROR_UNKNOWN_REQUEST)); } } } finally { ReferenceCountUtil.release(req); } } else { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); } } private void handleWebAPIResponse(final ChannelHandlerContext ctx, final FullHttpRequest req, Response res) { final boolean keepAlive = HttpHeaders.isKeepAlive(req); try { ChannelFuture cf = null; if (res.isError()) { if (res.errorCode() == CoreContract.ERROR_TIMEOUT) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, REQUEST_TIMEOUT)); } else { JSONObject jo = new JSONObject(); jo.put("result", "ERROR"); jo.put("error", res.errorCode()); jo.put("message", Contract.getErrorCode(res.errorCode(), res.getContractId())); cf = ctx.writeAndFlush(makeFrame(jo, keepAlive)); } } else if (res.isGenericSuccess()) { // bad form to allow two types of non-error response but most calls will just want to return SUCCESS JSONObject jo = new JSONObject(); jo.put("result", "SUCCESS"); cf = ctx.writeAndFlush(makeFrame(jo, keepAlive)); } else if (res instanceof WebAPIResponse) { WebAPIResponse resp = (WebAPIResponse) res; if (resp.redirect != null && !resp.redirect.isEmpty()) { redirect(resp.redirect, ctx); } else { cf = ctx.writeAndFlush(makeFrame(new JSONObject(resp.json), keepAlive)); } } else { ctx.writeAndFlush(makeFrame(res, 0)); } if (cf != null && !keepAlive) { cf.addListener(ChannelFutureListener.CLOSE); } } catch (Throwable e) { logger.error(e.getMessage(), e); } } private JSONObject getHeaders(FullHttpRequest req) { JSONObject jo = new JSONObject(); for (Map.Entry<String, String> e : req.headers()) { jo.put(e.getKey(), e.getValue()); } return jo; } protected void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); try { res.content().writeBytes(buf); } finally { buf.release(); } setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } } @Override protected Object makeFrame(JSONObject jo, boolean keepAlive) { if (isWebSocket()) { return new TextWebSocketFrame(jo.toString(3)); } else { ByteBuf buf = WebContext.makeByteBufResult(jo.toString(3)); FullHttpResponse httpResponse = new DefaultFullHttpResponse(HTTP_1_1, OK, buf); httpResponse.headers().set(CONTENT_TYPE, "text/json"); httpResponse.headers().set(CONTENT_LENGTH, httpResponse.content().readableBytes()); if (keepAlive) { httpResponse.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); } else { httpResponse.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); } // logger.debug("MAKE FRAME " + jo); return httpResponse; } } private void relayRequest(RequestHeader header, Structure request, ResponseHandler handler) throws IOException { final Session ses = relayHandler.getRelaySession(header.toId, header.contractId); if (ses != null) { relayRequest(header, request, ses, handler); } else { logger.debug("{} Could not find a relay session for {} {}", this, header.toId, header.contractId); handler.onResponse(new Error(ERROR_SERVICE_UNAVAILABLE)); } } protected Async relayRequest(RequestHeader header, Structure request, Session ses, ResponseHandler handler) throws IOException { final ByteBuf in = convertToByteBuf(request); try { return ses.sendRelayedRequest(header, in, this, handler); } finally { in.release(); } } protected ByteBuf convertToByteBuf(Structure struct) throws IOException { ByteBuf buffer = channel.alloc().buffer(32); ByteBufDataSource data = new ByteBufDataSource(buffer); struct.write(data); return buffer; } private void redirect(String newURL, ChannelHandlerContext ctx) { HttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, FOUND); response.headers().set(LOCATION, newURL); response.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } protected void readAndDispatchRequest(RequestHeader header, JSONObject params) { long now = System.currentTimeMillis(); lastHeardFrom.set(now); if (floodCheck(now, header)) { // could move flood check after comms log just for the logging return; } try { final Structure request = readRequest(header, params); if (request != null) { if (header.toId == DIRECT || header.toId == myId) { if (request instanceof Request) { dispatchRequest(header, (Request) request); } else { logger.error("Asked to process a request I can't deserialize {}", header.dump()); sendResponse(new Error(ERROR_SERIALIZATION), header.requestId); } } else { relayRequest(header, request); } } else { sendResponse(new Error(ERROR_UNKNOWN_REQUEST), header.requestId); } } catch (IOException e) { logger.error("Error processing request {}", header.dump()); sendResponse(new Error(ERROR_UNKNOWN), header.requestId); } } private ChannelHandlerContext getContext(int requestId) { synchronized (contexts) { return contexts.remove(requestId); } } @Override public void sendResponse(Response res, int requestId) { if (isWebSocket()) { super.sendResponse(res, requestId); } else { // HACK: for http responses we need to write to the response to the correct ChannelHandlerContext if (res != Response.PENDING) { if (!commsLogIgnore(res)) commsLog("%s [%d] => %s", this, requestId, res.dump()); final Object buffer = makeFrame(res, requestId); if (buffer != null && channel.isActive()) { ChannelHandlerContext ctx = getContext(requestId); if (ctx != null) { ctx.writeAndFlush(buffer); } else { logger.warn("{} Could not find context for {}", this, requestId); writeFrame(buffer); } } } } } @Override public void sendRelayedResponse(ResponseHeader header, ByteBuf payload) { if (isWebSocket()) { super.sendRelayedResponse(header, payload); } else { // HACK: for http responses we need to write to the response to the correct ChannelHandlerContext if (!commsLogIgnore(header.structId)) commsLog("%s [%d] ~> Response:%d", this, header.requestId, header.structId); ChannelHandlerContext ctx = getContext(header.requestId); final Object buffer = makeFrame(header, payload, ENVELOPE_RESPONSE); if (ctx != null) { ctx.writeAndFlush(buffer); } else { writeFrame(buffer); } } } private Async relayRequest(RequestHeader header, Structure request) throws IOException { final Session ses = relayHandler.getRelaySession(header.toId, header.contractId); if (ses != null) { return relayRequest(header, request, ses, null); } else { logger.debug("Could not find a relay session for {} {}", header.toId, header.contractId); sendResponse(new Error(ERROR_SERVICE_UNAVAILABLE), header.requestId); return null; } } @Override public void sendRelayedMessage(MessageHeader header, ByteBuf payload, boolean broadcast) { if (isWebSocket()) { super.sendRelayedMessage(header, payload, broadcast); } else { // queue the message for long poller to retrieve later if (!commsLogIgnore(header.structId)) { commsLog("%s [M] ~] Message:%d %s (to %s:%d)", this, header.structId, getNameFor(header), TO_TYPES[header.toType], header.toId); } final LongPollQueue messages = LongPollQueue.getQueue(getTheirEntityId()); // FIXME: Need a sensible way to protect against memory gobbling if this queue isn't cleared fast enough messages.add(toJSON(header, payload, ENVELOPE_MESSAGE)); //logger.debug("{} Queued {} messages for longPoller {}", this, messages.size(), messages.getEntityId()); } } private boolean floodCheck(long now, RequestHeader header) { int reqs; long newFloodPeriod = now / FLOOD_TIME_PERIOD; if (newFloodPeriod != floodPeriod) { // race condition between read and write of floodPeriod. but is benign as it means we reset // request count to 0 an extra time floodPeriod = newFloodPeriod; requestCount.set(0); reqs = 0; } else { reqs = requestCount.incrementAndGet(); } if (reqs > FLOOD_KILL) { logger.warn("{} flood killing {}/{}", this, header.contractId, header.structId); close(); return true; } if (reqs > FLOOD_IGNORE) { // do nothing, send no response logger.warn("{} flood ignoring {}/{}", this, header.contractId, header.structId); return true; } if (reqs > FLOOD_WARN) { // respond with error so client can slow down logger.warn("{} flood warning {}/{}", this, header.contractId, header.structId); sendResponse(new Error(ERROR_FLOOD), header.requestId); return true; } return false; } }
package gov.nih.nci.calab.service.common; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.HibernateDataAccess; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Aliquot; import gov.nih.nci.calab.domain.Instrument; import gov.nih.nci.calab.domain.MeasureType; import gov.nih.nci.calab.domain.MeasureUnit; import gov.nih.nci.calab.domain.Protocol; import gov.nih.nci.calab.domain.ProtocolFile; import gov.nih.nci.calab.domain.Sample; import gov.nih.nci.calab.domain.SampleContainer; import gov.nih.nci.calab.domain.StorageElement; import gov.nih.nci.calab.dto.characterization.CharacterizationTypeBean; import gov.nih.nci.calab.dto.common.InstrumentBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.ProtocolBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.inventory.AliquotBean; import gov.nih.nci.calab.dto.inventory.ContainerBean; import gov.nih.nci.calab.dto.inventory.ContainerInfoBean; import gov.nih.nci.calab.dto.inventory.SampleBean; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabComparators; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.StringUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import org.apache.log4j.Logger; import org.apache.struts.util.LabelValueBean; import org.hibernate.Hibernate; import org.hibernate.SQLQuery; import org.hibernate.collection.PersistentSet; /** * The service to return prepopulated data that are shared across different * views. * * @author zengje * */ /* CVS $Id: LookupService.java,v 1.126 2007-07-19 21:19:57 pansu Exp $ */ public class LookupService { private static Logger logger = Logger.getLogger(LookupService.class); /** * Retrieving all unmasked aliquots for use in views create run, use aliquot * and create aliquot. * * @return a Map between sample name and its associated unmasked aliquots * @throws Exception */ public Map<String, SortedSet<AliquotBean>> getUnmaskedSampleAliquots() throws Exception { SortedSet<AliquotBean> aliquots = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<AliquotBean>> sampleAliquots = new HashMap<String, SortedSet<AliquotBean>>(); try { ida.open(); String hqlString = "select aliquot.id, aliquot.name, aliquot.sample.name from Aliquot aliquot where aliquot.dataStatus is null order by aliquot.name"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; AliquotBean aliquot = new AliquotBean(StringUtils .convertToString(info[0]), StringUtils .convertToString(info[1]), CaNanoLabConstants.ACTIVE_STATUS); String sampleName = (String) info[2]; if (sampleAliquots.get(sampleName) != null) { aliquots = (SortedSet<AliquotBean>) sampleAliquots .get(sampleName); } else { aliquots = new TreeSet<AliquotBean>( new CaNanoLabComparators.AliquotBeanComparator()); sampleAliquots.put(sampleName, aliquots); } aliquots.add(aliquot); } } catch (Exception e) { logger.error("Error in retrieving all aliquot Ids and names", e); throw new RuntimeException( "Error in retrieving all aliquot Ids and names"); } finally { ida.close(); } return sampleAliquots; } /** * * @return a map between sample name and its sample containers * @throws Exception */ public Map<String, SortedSet<ContainerBean>> getAllSampleContainers() throws Exception { SortedSet<ContainerBean> containers = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<ContainerBean>> sampleContainers = new HashMap<String, SortedSet<ContainerBean>>(); try { ida.open(); String hqlString = "select container, container.sample.name from SampleContainer container"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; if (!(info[0] instanceof Aliquot)) { ContainerBean container = new ContainerBean( (SampleContainer) info[0]); String sampleName = (String) info[1]; if (sampleContainers.get(sampleName) != null) { containers = (SortedSet<ContainerBean>) sampleContainers .get(sampleName); } else { containers = new TreeSet<ContainerBean>( new CaNanoLabComparators.ContainerBeanComparator()); sampleContainers.put(sampleName, containers); } containers.add(container); } } } catch (Exception e) { logger.error("Error in retrieving all containers", e); throw new RuntimeException("Error in retrieving all containers"); } finally { ida.close(); } return sampleContainers; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getSampleContainerInfo() throws Exception { Map<String, SortedSet<String>> allUnits = getAllMeasureUnits(); List<StorageElement> storageElements = getAllStorageElements(); SortedSet<String> quantityUnits = (allUnits.get("Quantity") == null) ? new TreeSet<String>() : allUnits.get("Quantity"); SortedSet<String> concentrationUnits = (allUnits.get("Concentration") == null) ? new TreeSet<String>() : allUnits.get("Concentration"); SortedSet<String> volumeUnits = (allUnits.get("Volume") == null) ? new TreeSet<String>() : allUnits.get("Volume"); SortedSet<String> rooms = new TreeSet<String>(); SortedSet<String> freezers = new TreeSet<String>(); SortedSet<String> shelves = new TreeSet<String>(); SortedSet<String> boxes = new TreeSet<String>(); for (StorageElement storageElement : storageElements) { if (storageElement.getType().equalsIgnoreCase("Room") && !rooms.contains(storageElement.getLocation())) { rooms.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Freezer") && !freezers.contains(storageElement.getLocation())) { freezers.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Shelf") && !shelves.contains(storageElement.getLocation())) { shelves.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Box") && !boxes.contains(storageElement.getLocation())) { boxes.add((storageElement.getLocation())); } } // set labs and racks to null for now ContainerInfoBean containerInfo = new ContainerInfoBean(quantityUnits, concentrationUnits, volumeUnits, null, rooms, freezers, shelves, boxes); return containerInfo; } public SortedSet<String> getAllSampleContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct container.containerType from SampleContainer container order by container.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample container types", e); throw new RuntimeException( "Error in retrieving all sample container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); return containerTypes; } public SortedSet<String> getAllAliquotContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.containerType from Aliquot aliquot order by aliquot.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all aliquot container types", e); throw new RuntimeException( "Error in retrieving all aliquot container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); return containerTypes; } public Map<String, SortedSet<String>> getAllMeasureUnits() throws Exception { Map<String, SortedSet<String>> unitMap = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from MeasureUnit unit order by unit.name"; List results = ida.search(hqlString); SortedSet<String> units = null; for (Object obj : results) { MeasureUnit unit = (MeasureUnit) obj; String type = unit.getType(); if (unitMap.get(type) != null) { units = unitMap.get(type); } else { units = new TreeSet<String>(); unitMap.put(type, units); } units.add(unit.getName()); } } catch (Exception e) { logger.error("Error in retrieving all measure units", e); throw new RuntimeException("Error in retrieving all measure units."); } finally { ida.close(); } return unitMap; } private List<StorageElement> getAllStorageElements() throws Exception { List<StorageElement> storageElements = new ArrayList<StorageElement>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from StorageElement where type in ('Room', 'Freezer', 'Shelf', 'Box') and location!='Other'"; List results = ida.search(hqlString); for (Object obj : results) { storageElements.add((StorageElement) obj); } } catch (Exception e) { logger.error("Error in retrieving all rooms and freezers", e); throw new RuntimeException( "Error in retrieving all rooms and freezers."); } finally { ida.close(); } return storageElements; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getAliquotContainerInfo() throws Exception { return getSampleContainerInfo(); } /** * Get all samples in the database * * @return a list of SampleBean containing sample Ids and names DELETE */ public List<SampleBean> getAllSamples() throws Exception { List<SampleBean> samples = new ArrayList<SampleBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sample.id, sample.name from Sample sample"; List results = ida.search(hqlString); for (Object obj : results) { Object[] sampleInfo = (Object[]) obj; samples.add(new SampleBean(StringUtils .convertToString(sampleInfo[0]), StringUtils .convertToString(sampleInfo[1]))); } } catch (Exception e) { logger.error("Error in retrieving all sample IDs and names", e); throw new RuntimeException( "Error in retrieving all sample IDs and names"); } finally { ida.close(); } Collections.sort(samples, new CaNanoLabComparators.SampleBeanComparator()); return samples; } /** * Retrieve all Assay Types from the system * * @return A list of all assay type */ public List getAllAssayTypes() throws Exception { List<String> assayTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assayType.name from AssayType assayType order by assayType.executeOrder"; List results = ida.search(hqlString); for (Object obj : results) { assayTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all assay types", e); throw new RuntimeException("Error in retrieving all assay types"); } finally { ida.close(); } return assayTypes; } /** * * @return a map between assay type and its assays * @throws Exception */ public Map<String, SortedSet<AssayBean>> getAllAssayTypeAssays() throws Exception { Map<String, SortedSet<AssayBean>> assayTypeAssays = new HashMap<String, SortedSet<AssayBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assay.id, assay.name, assay.assayType from Assay assay"; List results = ida.search(hqlString); SortedSet<AssayBean> assays = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; AssayBean assay = new AssayBean( ((Long) objArray[0]).toString(), (String) objArray[1], (String) objArray[2]); if (assayTypeAssays.get(assay.getAssayType()) != null) { assays = (SortedSet<AssayBean>) assayTypeAssays.get(assay .getAssayType()); } else { assays = new TreeSet<AssayBean>( new CaNanoLabComparators.AssayBeanComparator()); assayTypeAssays.put(assay.getAssayType(), assays); } assays.add(assay); } } catch (Exception e) { // TODO: temp for debuging use. remove later e.printStackTrace(); logger.error("Error in retrieving all assay beans. ", e); throw new RuntimeException("Error in retrieving all assays beans. "); } finally { ida.close(); } return assayTypeAssays; } /** * * @return all sample sources */ public SortedSet<String> getAllSampleSources() throws Exception { SortedSet<String> sampleSources = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select source.organizationName from Source source order by source.organizationName"; List results = ida.search(hqlString); for (Object obj : results) { sampleSources.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return sampleSources; } /** * * @return a map between sample source and samples with unmasked aliquots * @throws Exception */ public Map<String, SortedSet<SampleBean>> getSampleSourceSamplesWithUnmaskedAliquots() throws Exception { Map<String, SortedSet<SampleBean>> sampleSourceSamples = new HashMap<String, SortedSet<SampleBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.sample from Aliquot aliquot where aliquot.dataStatus is null"; List results = ida.search(hqlString); SortedSet<SampleBean> samples = null; for (Object obj : results) { SampleBean sample = new SampleBean((Sample) obj); if (sampleSourceSamples.get(sample.getSampleSource()) != null) { // TODO need to make sample source a required field if (sample.getSampleSource().length() > 0) { samples = (SortedSet<SampleBean>) sampleSourceSamples .get(sample.getSampleSource()); } } else { samples = new TreeSet<SampleBean>( new CaNanoLabComparators.SampleBeanComparator()); if (sample.getSampleSource().length() > 0) { sampleSourceSamples.put(sample.getSampleSource(), samples); } } samples.add(sample); } } catch (Exception e) { logger.error( "Error in retrieving sample beans with unmasked aliquots ", e); throw new RuntimeException( "Error in retrieving all sample beans with unmasked aliquots. "); } finally { ida.close(); } return sampleSourceSamples; } public List<String> getAllSampleSOPs() throws Exception { List<String> sampleSOPs = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleSOP.name from SampleSOP sampleSOP where sampleSOP.description='sample creation'"; List results = ida.search(hqlString); for (Object obj : results) { sampleSOPs.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Sample SOPs."); throw new RuntimeException("Problem to retrieve all Sample SOPs. "); } finally { ida.close(); } return sampleSOPs; } /** * * @return all methods for creating aliquots */ public List<LabelValueBean> getAliquotCreateMethods() throws Exception { List<LabelValueBean> createMethods = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sop.name, file.uri from SampleSOP sop join sop.sampleSOPFileCollection file where sop.description='aliquot creation'"; List results = ida.search(hqlString); for (Object obj : results) { String sopName = (String) ((Object[]) obj)[0]; String sopURI = (String) ((Object[]) obj)[1]; String sopURL = (sopURI == null) ? "" : sopURI; createMethods.add(new LabelValueBean(sopName, sopURL)); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return createMethods; } /** * * @return all source sample IDs */ public List<String> getAllSourceSampleIds() throws Exception { List<String> sourceSampleIds = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct sample.sourceSampleId from Sample sample order by sample.sourceSampleId"; List results = ida.search(hqlString); for (Object obj : results) { sourceSampleIds.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all source sample IDs", e); throw new RuntimeException( "Error in retrieving all source sample IDs"); } finally { ida.close(); } return sourceSampleIds; } public Map<String, SortedSet<String>> getAllParticleTypeParticles() throws Exception { // TODO fill in actual database query. Map<String, SortedSet<String>> particleTypeParticles = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); try { ida.open(); // String hqlString = "select particle.type, particle.name from // Nanoparticle particle"; String hqlString = "select particle.type, particle.name from Nanoparticle particle where size(particle.characterizationCollection) = 0"; List results = ida.search(hqlString); SortedSet<String> particleNames = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; String particleType = (String) objArray[0]; String particleName = (String) objArray[1]; if (particleType != null) { // check if the particle already has visibility group // assigned, if yes, do NOT add to the list List<String> groups = userService.getAccessibleGroups( particleName, CaNanoLabConstants.CSM_READ_ROLE); if (groups.size() == 0) { if (particleTypeParticles.get(particleType) != null) { particleNames = (SortedSet<String>) particleTypeParticles .get(particleType); } else { particleNames = new TreeSet<String>( new CaNanoLabComparators.SortableNameComparator()); particleTypeParticles.put(particleType, particleNames); } particleNames.add(particleName); } } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return particleTypeParticles; } public SortedSet<String> getAllDendrimerCores() { SortedSet<String> cores = new TreeSet<String>(); cores.add("Diamine"); cores.add("Ethyline"); return cores; } public SortedSet<String> getAllDendrimerSurfaceGroupNames() throws Exception { SortedSet<String> names = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct name from SurfaceGroupType"; List results = ida.search(hqlString); for (Object obj : results) { names.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Surface Group name."); throw new RuntimeException( "Problem to retrieve all Surface Group name. "); } finally { ida.close(); } return names; } public SortedSet<String> getAllDendrimerBranches() throws Exception { SortedSet<String> branches = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.branch from DendrimerComposition dendrimer where dendrimer.branch is not null"; List results = ida.search(hqlString); for (Object obj : results) { branches.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Branches."); throw new RuntimeException( "Problem to retrieve all Dendrimer Branches. "); } finally { ida.close(); } branches.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_BRANCHES)); return branches; } public SortedSet<String> getAllDendrimerGenerations() throws Exception { SortedSet<String> generations = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.generation from DendrimerComposition dendrimer where dendrimer.generation is not null "; List results = ida.search(hqlString); for (Object obj : results) { generations.add(obj.toString()); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Generations."); throw new RuntimeException( "Problem to retrieve all Dendrimer Generations. "); } finally { ida.close(); } generations.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_GENERATIONS)); return generations; } public String[] getAllMetalCompositions() { String[] compositions = new String[] { "Gold", "Sliver", "Iron oxide" }; return compositions; } public SortedSet<String> getAllPolymerInitiators() throws Exception { SortedSet<String> initiators = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct polymer.initiator from PolymerComposition polymer where polymer.initiator is not null "; List results = ida.search(hqlString); for (Object obj : results) { initiators.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Polymer Initiator."); throw new RuntimeException( "Problem to retrieve all Polymer Initiator. "); } finally { ida.close(); } initiators.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_POLYMER_INITIATORS)); return initiators; } public SortedSet<String> getAllParticleSources() throws Exception { // TODO fill in db code return getAllSampleSources(); } public String getParticleClassification(String particleType) { String classification = CaNanoLabConstants.PARTICLE_CLASSIFICATION_MAP .get(particleType); return classification; } /** * * @return a map between a characterization type and its child * characterizations. */ public Map<String, List<String>> getCharacterizationTypeCharacterizations() throws Exception { Map<String, List<String>> charTypeChars = new HashMap<String, List<String>>(); HibernateDataAccess hda = HibernateDataAccess.getInstance(); try { hda.open(); List<String> chars = null; String query = "select distinct a.category, a.name from def_characterization_category a " + "where a.name not in (select distinct b.category from def_characterization_category b) " + "order by a.category, a.name"; SQLQuery queryObj = hda.getNativeQuery(query); queryObj.addScalar("CATEGORY", Hibernate.STRING); queryObj.addScalar("NAME", Hibernate.STRING); List results = queryObj.list(); for (Object obj : results) { Object[] objarr = (Object[]) obj; String type = objarr[0].toString(); String name = objarr[1].toString(); if (charTypeChars.get(type) != null) { chars = (List<String>) charTypeChars.get(type); } else { chars = new ArrayList<String>(); charTypeChars.put(type, chars); } chars.add(name); } } catch (Exception e) { logger .error("Problem to retrieve all characterization type characterizations. " + e); throw new RuntimeException( "Problem to retrieve all characteriztaion type characterizations. "); } finally { hda.close(); } return charTypeChars; } public List<LabelValueBean> getAllInstrumentTypeAbbrs() throws Exception { List<LabelValueBean> instrumentTypeAbbrs = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, instrumentType.abbreviation from InstrumentType instrumentType where instrumentType.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { if (obj != null) { Object[] objs = (Object[]) obj; String label = ""; if (objs[1] != null) { label = (String) objs[0] + "(" + objs[1] + ")"; } else { label = (String) objs[0]; } instrumentTypeAbbrs.add(new LabelValueBean(label, (String) objs[0])); } } } catch (Exception e) { logger.error("Problem to retrieve all instrumentTypes. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } return instrumentTypeAbbrs; } public Map<String, SortedSet<String>> getAllInstrumentManufacturers() throws Exception { Map<String, SortedSet<String>> instrumentManufacturers = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, manufacturer.name from InstrumentType instrumentType join instrumentType.manufacturerCollection manufacturer "; List results = ida.search(hqlString); SortedSet<String> manufacturers = null; for (Object obj : results) { String instrumentType = ((Object[]) obj)[0].toString(); String manufacturer = ((Object[]) obj)[1].toString(); if (instrumentManufacturers.get(instrumentType) != null) { manufacturers = (SortedSet<String>) instrumentManufacturers .get(instrumentType); } else { manufacturers = new TreeSet<String>(); instrumentManufacturers.put(instrumentType, manufacturers); } manufacturers.add(manufacturer); } List allResult = ida .search("select manufacturer.name from Manufacturer manufacturer where manufacturer.name is not null"); SortedSet<String> allManufacturers = null; allManufacturers = new TreeSet<String>(); for (Object obj : allResult) { String name = (String) obj; allManufacturers.add(name); } } catch (Exception e) { logger .error("Problem to retrieve manufacturers for intrument types " + e); throw new RuntimeException( "Problem to retrieve manufacturers for intrument types."); } finally { ida.close(); } return instrumentManufacturers; } public SortedSet<String> getAllLookupTypes(String lookupType) throws Exception { SortedSet<String> types = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct name from " + lookupType; List results = ida.search(hqlString); for (Object obj : results) { types.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all " + lookupType + " types."); throw new RuntimeException("Problem to retrieve all " + lookupType + " types."); } finally { ida.close(); } return types; } public Map<ProtocolBean, List<ProtocolFileBean>> getAllProtocolNameVersionByType( String type) throws Exception { Map<ProtocolBean, List<ProtocolFileBean>> nameVersions = new HashMap<ProtocolBean, List<ProtocolFileBean>>(); Map<Protocol, ProtocolBean> keyMap = new HashMap<Protocol, ProtocolBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select protocolFile, protocolFile.protocol from ProtocolFile protocolFile" + " where protocolFile.protocol.type = '" + type + "'"; List results = ida.search(hqlString); for (Object obj : results) { Object[] array = (Object[]) obj; Object key = null; Object value = null; for (int i = 0; i < array.length; i++) { if (array[i] instanceof Protocol) { key = array[i]; } else if (array[i] instanceof ProtocolFile) { value = array[i]; } } if (keyMap.containsKey((Protocol) key)) { ProtocolBean pb = keyMap.get((Protocol) key); List<ProtocolFileBean> localList = nameVersions.get(pb); ProtocolFileBean fb = new ProtocolFileBean(); fb.setVersion(((ProtocolFile) value).getVersion()); fb.setId(((ProtocolFile) value).getId().toString()); localList.add(fb); } else { List<ProtocolFileBean> localList = new ArrayList<ProtocolFileBean>(); ProtocolFileBean fb = new ProtocolFileBean(); fb.setVersion(((ProtocolFile) value).getVersion()); fb.setId(((ProtocolFile) value).getId().toString()); localList.add(fb); ProtocolBean protocolBean = new ProtocolBean(); Protocol protocol = (Protocol) key; protocolBean.setId(protocol.getId().toString()); protocolBean.setName(protocol.getName()); protocolBean.setType(protocol.getType()); nameVersions.put(protocolBean, localList); keyMap.put((Protocol) key, protocolBean); } } } catch (Exception e) { logger .error("Problem to retrieve all protocol names and their versions by type " + type); throw new RuntimeException( "Problem to retrieve all protocol names and their versions by type " + type); } finally { ida.close(); } return nameVersions; } public SortedSet<String> getAllProtocolTypes() throws Exception { SortedSet<String> protocolTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct protocol.type from Protocol protocol where protocol.type is not null"; List results = ida.search(hqlString); for (Object obj : results) { protocolTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all protocol types."); throw new RuntimeException( "Problem to retrieve all protocol types."); } finally { ida.close(); } return protocolTypes; } public SortedSet<ProtocolBean> getAllProtocols(UserBean user) throws Exception { SortedSet<ProtocolBean> protocolBeans = new TreeSet<ProtocolBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from Protocol as protocol left join fetch protocol.protocolFileCollection"; List results = ida.search(hqlString); for (Object obj : results) { Protocol p = (Protocol) obj; ProtocolBean pb = new ProtocolBean(); pb.setId(p.getId().toString()); pb.setName(p.getName()); pb.setType(p.getType()); PersistentSet set = (PersistentSet) p .getProtocolFileCollection(); // HashSet hashSet = set. if (!set.isEmpty()) { List<ProtocolFileBean> list = new ArrayList<ProtocolFileBean>(); for (Iterator it = set.iterator(); it.hasNext();) { ProtocolFile pf = (ProtocolFile) it.next(); ProtocolFileBean pfb = new ProtocolFileBean(); pfb.setId(pf.getId().toString()); pfb.setVersion(pf.getVersion()); list.add(pfb); } pb.setFileBeanList(filterProtocols(list, user)); } if (!pb.getFileBeanList().isEmpty()) protocolBeans.add(pb); } } catch (Exception e) { logger.error("Problem to retrieve all protocol names and types."); throw new RuntimeException( "Problem to retrieve all protocol names and types."); } finally { ida.close(); } return protocolBeans; } private List<ProtocolFileBean> filterProtocols( List<ProtocolFileBean> protocolFiles, UserBean user) throws Exception { UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); List<LabFileBean> tempList = new ArrayList<LabFileBean>(); for (ProtocolFileBean pfb : protocolFiles) { tempList.add((LabFileBean) pfb); } List<LabFileBean> filteredProtocols = userService.getFilteredFiles( user, tempList); protocolFiles.clear(); if (filteredProtocols == null || filteredProtocols.isEmpty()) return protocolFiles; for (LabFileBean lfb : filteredProtocols) { protocolFiles.add((ProtocolFileBean) lfb); } return protocolFiles; } public Map<String, String[]> getAllAgentTypes() { Map<String, String[]> agentTypes = new HashMap<String, String[]>(); String[] therapeuticsAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Therapeutic", therapeuticsAgentTypes); String[] targetingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Targeting", targetingAgentTypes); String[] imagingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Imaging", imagingAgentTypes); String[] reportingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Reporting", reportingAgentTypes); return agentTypes; } public String[] getAllAgentTargetTypes() { String[] targetTypes = new String[] { "Receptor", "Antigen", "Other" }; return targetTypes; } public String[] getAllActivationMethods() { String[] activationMethods = new String[] { "NMR", "MRI", "Radiation", "Ultrasound", "Ultraviolet Light" }; return activationMethods; } public List<LabelValueBean> getAllSpecies() throws Exception { List<LabelValueBean> species = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); species.add(new LabelValueBean("", "")); try { for (int i = 0; i < CaNanoLabConstants.SPECIES_COMMON.length; i++) { String specie = CaNanoLabConstants.SPECIES_COMMON[i]; species.add(new LabelValueBean(specie, specie)); } } catch (Exception e) { logger.error("Problem to retrieve all species. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } return species; } public String[] getAllReportTypes() { String[] allReportTypes = new String[] { CaNanoLabConstants.REPORT, CaNanoLabConstants.ASSOCIATED_FILE }; return allReportTypes; } /** * Get other particles from the given particle source * * @param particleSource * @param particleName * @param user * @return * @throws Exception */ public SortedSet<String> getOtherParticles(String particleSource, String particleName, UserBean user) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); SortedSet<String> otherParticleNames = new TreeSet<String>(); try { ida.open(); String hqlString = "select particle.name from Nanoparticle particle where particle.source.organizationName='" + particleSource + "' and particle.name !='" + particleName + "'"; List results = ida.search(hqlString); for (Object obj : results) { String otherParticleName = (String) obj; // check if user can see the particle boolean status = userService.checkReadPermission(user, otherParticleName); if (status) { otherParticleNames.add(otherParticleName); } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return otherParticleNames; } public List<InstrumentBean> getAllInstruments() throws Exception { List<InstrumentBean> instruments = new ArrayList<InstrumentBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from Instrument instrument where instrument.type is not null order by instrument.type"; List results = ida.search(hqlString); for (Object obj : results) { Instrument instrument = (Instrument) obj; instruments.add(new InstrumentBean(instrument)); } } catch (Exception e) { logger.error("Problem to retrieve all instruments. " + e); throw new RuntimeException("Problem to retrieve all intruments. "); } finally { ida.close(); } return instruments; } public SortedSet<String> getAllCharacterizationFileTypes() throws Exception { SortedSet<String> fileTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct fileType.name from CharacterizationFileType fileType order by fileType.name"; List results = ida.search(hqlString); for (Object obj : results) { String type = (String) obj; fileTypes.add(type); } } catch (Exception e) { logger .error("Problem to retrieve all characterization file types. " + e); throw new RuntimeException( "Problem to retrieve all characterization file types. "); } finally { ida.close(); } return fileTypes; } public List<CharacterizationTypeBean> getAllCharacterizationTypes() throws Exception { List<CharacterizationTypeBean> charTypes = new ArrayList<CharacterizationTypeBean>(); HibernateDataAccess hda = HibernateDataAccess.getInstance(); try { hda.open(); String query = "select distinct category, has_action, indent_level, category_order from def_characterization_category order by category_order"; SQLQuery queryObj = hda.getNativeQuery(query); queryObj.addScalar("CATEGORY", Hibernate.STRING); queryObj.addScalar("HAS_ACTION", Hibernate.INTEGER); queryObj.addScalar("INDENT_LEVEL", Hibernate.INTEGER); queryObj.addScalar("CATEGORY_ORDER", Hibernate.INTEGER); List results = queryObj.list(); for (Object obj : results) { Object[] objarr = (Object[]) obj; String type = objarr[0].toString(); boolean hasAction = ((Integer) objarr[1] == 0) ? false : true; int indentLevel = (Integer) objarr[2]; CharacterizationTypeBean charType = new CharacterizationTypeBean( type, indentLevel, hasAction); charTypes.add(charType); } } catch (Exception e) { logger .error("Problem to retrieve all characterization types. " + e); throw new RuntimeException( "Problem to retrieve all characteriztaion types. "); } finally { hda.close(); } return charTypes; } public Map<String, SortedSet<String>> getDerivedDataCategoryMap( String characterizationName) throws Exception { Map<String, SortedSet<String>> categoryMap = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select category.name, datumName.name from DerivedBioAssayDataCategory category left join category.datumNameCollection datumName where datumName.datumParsed=false and category.characterizationName='" + characterizationName + "'"; List results = ida.search(hqlString); SortedSet<String> datumNames = null; for (Object obj : results) { String categoryName = ((Object[]) obj)[0].toString(); String datumName = ((Object[]) obj)[1].toString(); if (categoryMap.get(categoryName) != null) { datumNames = categoryMap.get(categoryName); } else { datumNames = new TreeSet<String>(); categoryMap.put(categoryName, datumNames); } datumNames.add(datumName); } } catch (Exception e) { logger .error("Problem to retrieve all derived bioassay data categories. " + e); throw new RuntimeException( "Problem to retrieve all derived bioassay data categories."); } finally { ida.close(); } return categoryMap; } public SortedSet<String> getDerivedDatumNames(String characterizationName) throws Exception { SortedSet<String> datumNames = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct name from DatumName where datumParsed=false and characterizationName='" + characterizationName + "'"; List results = ida.search(hqlString); for (Object obj : results) { String datumName = obj.toString(); datumNames.add(datumName); } } catch (Exception e) { logger .error("Problem to retrieve all derived bioassay datum names. " + e); throw new RuntimeException( "Problem to retrieve all derived bioassay datum names."); } finally { ida.close(); } return datumNames; } public SortedSet<String> getDerivedDataCategories( String characterizationName) throws Exception { SortedSet<String> categories = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct name from DerivedBioAssayDataCategory where characterizationName='" + characterizationName + "'"; List results = ida.search(hqlString); for (Object obj : results) { String category = obj.toString(); categories.add(category); } } catch (Exception e) { e.printStackTrace(); logger .error("Problem to retrieve all derived bioassay data categories. " + e); throw new RuntimeException( "Problem to retrieve all derived bioassay data categories."); } finally { ida.close(); } return categories; } public SortedSet<String> getAllCharacterizationSources() throws Exception { SortedSet<String> sources = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct char.source from Characterization char where char.source is not null"; List results = ida.search(hqlString); for (Object obj : results) { sources.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Characterization Sources."); throw new RuntimeException( "Problem to retrieve all Characterization Sources. "); } finally { ida.close(); } sources.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CHARACTERIZATION_SOURCES)); return sources; } public SortedSet<String> getAllManufacturers() throws Exception { SortedSet<String> manufacturers = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrument.manufacturer from Instrument instrument"; List results = ida.search(hqlString); for (Object obj : results) { String manufacturer = (String) obj; manufacturers.add(manufacturer); } } catch (Exception e) { logger.error("Problem to retrieve all manufacturers. " + e); throw new RuntimeException( "Problem to retrieve all manufacturers. "); } finally { ida.close(); } return manufacturers; } }
package com.ibm.sk.ff.gui.client; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class Client { private final String URL; public Client() { URL = "http://" + Config.HOSTNAME + ":" + Config.PORT + "/"; } public boolean postMessage(String url, String message) { boolean ret = true; try { CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(URL + url); StringEntity se = new StringEntity(message); httpPost.setEntity(se); CloseableHttpResponse response = client.execute(httpPost); if (response.getStatusLine().getStatusCode() != 200) { ret = false; } client.close(); } catch (Exception e) { e.printStackTrace(); ret = false; System.exit(-1); } return ret; } public String getMessage(String url) { String responseString = ""; try { CloseableHttpClient client = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(URL + url); CloseableHttpResponse response = client.execute(httpGet); if (response.getStatusLine().getStatusCode() != 200) { responseString = null;; } else { responseString = EntityUtils.toString(response.getEntity()); } client.close(); } catch (Exception e) { e.printStackTrace(); System.exit(-1); } return responseString; } }
package gov.nih.nci.calab.service.common; import gov.nih.nci.calab.db.DataAccessProxy; import gov.nih.nci.calab.db.IDataAccess; import gov.nih.nci.calab.domain.Aliquot; import gov.nih.nci.calab.domain.Instrument; import gov.nih.nci.calab.domain.MeasureUnit; import gov.nih.nci.calab.domain.Sample; import gov.nih.nci.calab.domain.SampleContainer; import gov.nih.nci.calab.domain.StorageElement; import gov.nih.nci.calab.dto.common.InstrumentBean; import gov.nih.nci.calab.dto.common.LabFileBean; import gov.nih.nci.calab.dto.common.ProtocolBean; import gov.nih.nci.calab.dto.common.ProtocolFileBean; import gov.nih.nci.calab.dto.common.UserBean; import gov.nih.nci.calab.dto.inventory.AliquotBean; import gov.nih.nci.calab.dto.inventory.ContainerBean; import gov.nih.nci.calab.dto.inventory.ContainerInfoBean; import gov.nih.nci.calab.dto.inventory.SampleBean; import gov.nih.nci.calab.dto.workflow.AssayBean; import gov.nih.nci.calab.service.security.UserService; import gov.nih.nci.calab.service.util.CaNanoLabConstants; import gov.nih.nci.calab.service.util.CaNanoLabComparators; import gov.nih.nci.calab.service.util.StringUtils; import gov.nih.nci.calab.domain.ProtocolFile; import gov.nih.nci.calab.domain.Protocol; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.HashSet; import java.util.TreeSet; import java.util.Iterator; import org.hibernate.collection.PersistentSet; import org.apache.log4j.Logger; import org.apache.struts.util.LabelValueBean; /** * The service to return prepopulated data that are shared across different * views. * * @author zengje * */ /* CVS $Id: LookupService.java,v 1.104 2007-06-01 21:22:40 pansu Exp $ */ public class LookupService { private static Logger logger = Logger.getLogger(LookupService.class); /** * Retrieving all unmasked aliquots for use in views create run, use aliquot * and create aliquot. * * @return a Map between sample name and its associated unmasked aliquots * @throws Exception */ public Map<String, SortedSet<AliquotBean>> getUnmaskedSampleAliquots() throws Exception { SortedSet<AliquotBean> aliquots = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<AliquotBean>> sampleAliquots = new HashMap<String, SortedSet<AliquotBean>>(); try { ida.open(); String hqlString = "select aliquot.id, aliquot.name, aliquot.sample.name from Aliquot aliquot where aliquot.dataStatus is null order by aliquot.name"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; AliquotBean aliquot = new AliquotBean(StringUtils .convertToString(info[0]), StringUtils .convertToString(info[1]), CaNanoLabConstants.ACTIVE_STATUS); String sampleName = (String) info[2]; if (sampleAliquots.get(sampleName) != null) { aliquots = (SortedSet<AliquotBean>) sampleAliquots .get(sampleName); } else { aliquots = new TreeSet<AliquotBean>( new CaNanoLabComparators.AliquotBeanComparator()); sampleAliquots.put(sampleName, aliquots); } aliquots.add(aliquot); } } catch (Exception e) { logger.error("Error in retrieving all aliquot Ids and names", e); throw new RuntimeException( "Error in retrieving all aliquot Ids and names"); } finally { ida.close(); } return sampleAliquots; } /** * * @return a map between sample name and its sample containers * @throws Exception */ public Map<String, SortedSet<ContainerBean>> getAllSampleContainers() throws Exception { SortedSet<ContainerBean> containers = null; IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); Map<String, SortedSet<ContainerBean>> sampleContainers = new HashMap<String, SortedSet<ContainerBean>>(); try { ida.open(); String hqlString = "select container, container.sample.name from SampleContainer container"; List results = ida.search(hqlString); for (Object obj : results) { Object[] info = (Object[]) obj; if (!(info[0] instanceof Aliquot)) { ContainerBean container = new ContainerBean( (SampleContainer) info[0]); String sampleName = (String) info[1]; if (sampleContainers.get(sampleName) != null) { containers = (SortedSet<ContainerBean>) sampleContainers .get(sampleName); } else { containers = new TreeSet<ContainerBean>( new CaNanoLabComparators.ContainerBeanComparator()); sampleContainers.put(sampleName, containers); } containers.add(container); } } } catch (Exception e) { logger.error("Error in retrieving all containers", e); throw new RuntimeException("Error in retrieving all containers"); } finally { ida.close(); } return sampleContainers; } /** * Retrieving all sample types. * * @return a list of all sample types */ public List<String> getAllSampleTypes() throws Exception { // Detail here // Retrieve data from Sample_Type table List<String> sampleTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleType.name from SampleType sampleType order by sampleType.name"; List results = ida.search(hqlString); for (Object obj : results) { sampleTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample types", e); throw new RuntimeException("Error in retrieving all sample types"); } finally { ida.close(); } return sampleTypes; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getSampleContainerInfo() throws Exception { List<MeasureUnit> units = getAllMeasureUnits(); List<StorageElement> storageElements = getAllStorageElements(); List<String> quantityUnits = new ArrayList<String>(); List<String> concentrationUnits = new ArrayList<String>(); List<String> volumeUnits = new ArrayList<String>(); List<String> rooms = new ArrayList<String>(); List<String> freezers = new ArrayList<String>(); List<String> shelves = new ArrayList<String>(); List<String> boxes = new ArrayList<String>(); for (MeasureUnit unit : units) { if (unit.getType().equalsIgnoreCase("Quantity")) { quantityUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Volume")) { volumeUnits.add(unit.getName()); } else if (unit.getType().equalsIgnoreCase("Concentration")) { concentrationUnits.add(unit.getName()); } } for (StorageElement storageElement : storageElements) { if (storageElement.getType().equalsIgnoreCase("Room") && !rooms.contains(storageElement.getLocation())) { rooms.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Freezer") && !freezers.contains(storageElement.getLocation())) { freezers.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Shelf") && !shelves.contains(storageElement.getLocation())) { shelves.add((storageElement.getLocation())); } else if (storageElement.getType().equalsIgnoreCase("Box") && !boxes.contains(storageElement.getLocation())) { boxes.add((storageElement.getLocation())); } } // set labs and racks to null for now ContainerInfoBean containerInfo = new ContainerInfoBean(quantityUnits, concentrationUnits, volumeUnits, null, rooms, freezers, shelves, boxes); return containerInfo; } public List<String> getAllSampleContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct container.containerType from SampleContainer container order by container.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample container types", e); throw new RuntimeException( "Error in retrieving all sample container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } public List<String> getAllAliquotContainerTypes() throws Exception { SortedSet<String> containerTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.containerType from Aliquot aliquot order by aliquot.containerType"; List results = ida.search(hqlString); for (Object obj : results) { containerTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all aliquot container types", e); throw new RuntimeException( "Error in retrieving all aliquot container types."); } finally { ida.close(); } containerTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_CONTAINER_TYPES)); List<String> containerTypeList = new ArrayList<String>(containerTypes); return containerTypeList; } private List<MeasureUnit> getAllMeasureUnits() throws Exception { List<MeasureUnit> units = new ArrayList<MeasureUnit>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from MeasureUnit"; List results = ida.search(hqlString); for (Object obj : results) { units.add((MeasureUnit) obj); } } catch (Exception e) { logger.error("Error in retrieving all measure units", e); throw new RuntimeException("Error in retrieving all measure units."); } finally { ida.close(); } return units; } private List<StorageElement> getAllStorageElements() throws Exception { List<StorageElement> storageElements = new ArrayList<StorageElement>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from StorageElement where type in ('Room', 'Freezer', 'Shelf', 'Box') and location!='Other'"; List results = ida.search(hqlString); for (Object obj : results) { storageElements.add((StorageElement) obj); } } catch (Exception e) { logger.error("Error in retrieving all rooms and freezers", e); throw new RuntimeException( "Error in retrieving all rooms and freezers."); } finally { ida.close(); } return storageElements; } /** * * @return the default sample container information in a form of * ContainerInfoBean */ public ContainerInfoBean getAliquotContainerInfo() throws Exception { return getSampleContainerInfo(); } /** * Get all samples in the database * * @return a list of SampleBean containing sample Ids and names DELETE */ public List<SampleBean> getAllSamples() throws Exception { List<SampleBean> samples = new ArrayList<SampleBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sample.id, sample.name from Sample sample"; List results = ida.search(hqlString); for (Object obj : results) { Object[] sampleInfo = (Object[]) obj; samples.add(new SampleBean(StringUtils .convertToString(sampleInfo[0]), StringUtils .convertToString(sampleInfo[1]))); } } catch (Exception e) { logger.error("Error in retrieving all sample IDs and names", e); throw new RuntimeException( "Error in retrieving all sample IDs and names"); } finally { ida.close(); } Collections.sort(samples, new CaNanoLabComparators.SampleBeanComparator()); return samples; } /** * Retrieve all Assay Types from the system * * @return A list of all assay type */ public List getAllAssayTypes() throws Exception { List<String> assayTypes = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assayType.name from AssayType assayType order by assayType.executeOrder"; List results = ida.search(hqlString); for (Object obj : results) { assayTypes.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all assay types", e); throw new RuntimeException("Error in retrieving all assay types"); } finally { ida.close(); } return assayTypes; } /** * * @return a map between assay type and its assays * @throws Exception */ public Map<String, SortedSet<AssayBean>> getAllAssayTypeAssays() throws Exception { Map<String, SortedSet<AssayBean>> assayTypeAssays = new HashMap<String, SortedSet<AssayBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select assay.id, assay.name, assay.assayType from Assay assay"; List results = ida.search(hqlString); SortedSet<AssayBean> assays = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; AssayBean assay = new AssayBean( ((Long) objArray[0]).toString(), (String) objArray[1], (String) objArray[2]); if (assayTypeAssays.get(assay.getAssayType()) != null) { assays = (SortedSet<AssayBean>) assayTypeAssays.get(assay .getAssayType()); } else { assays = new TreeSet<AssayBean>( new CaNanoLabComparators.AssayBeanComparator()); assayTypeAssays.put(assay.getAssayType(), assays); } assays.add(assay); } } catch (Exception e) { // TODO: temp for debuging use. remove later e.printStackTrace(); logger.error("Error in retrieving all assay beans. ", e); throw new RuntimeException("Error in retrieving all assays beans. "); } finally { ida.close(); } return assayTypeAssays; } /** * * @return all sample sources */ public List<String> getAllSampleSources() throws Exception { List<String> sampleSources = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select source.organizationName from Source source order by source.organizationName"; List results = ida.search(hqlString); for (Object obj : results) { sampleSources.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return sampleSources; } /** * * @return a map between sample source and samples with unmasked aliquots * @throws Exception */ public Map<String, SortedSet<SampleBean>> getSampleSourceSamplesWithUnmaskedAliquots() throws Exception { Map<String, SortedSet<SampleBean>> sampleSourceSamples = new HashMap<String, SortedSet<SampleBean>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct aliquot.sample from Aliquot aliquot where aliquot.dataStatus is null"; List results = ida.search(hqlString); SortedSet<SampleBean> samples = null; for (Object obj : results) { SampleBean sample = new SampleBean((Sample) obj); if (sampleSourceSamples.get(sample.getSampleSource()) != null) { // TODO need to make sample source a required field if (sample.getSampleSource().length() > 0) { samples = (SortedSet<SampleBean>) sampleSourceSamples .get(sample.getSampleSource()); } } else { samples = new TreeSet<SampleBean>( new CaNanoLabComparators.SampleBeanComparator()); if (sample.getSampleSource().length() > 0) { sampleSourceSamples.put(sample.getSampleSource(), samples); } } samples.add(sample); } } catch (Exception e) { logger.error( "Error in retrieving sample beans with unmasked aliquots ", e); throw new RuntimeException( "Error in retrieving all sample beans with unmasked aliquots. "); } finally { ida.close(); } return sampleSourceSamples; } public List<String> getAllSampleSOPs() throws Exception { List<String> sampleSOPs = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sampleSOP.name from SampleSOP sampleSOP where sampleSOP.description='sample creation'"; List results = ida.search(hqlString); for (Object obj : results) { sampleSOPs.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Sample SOPs."); throw new RuntimeException("Problem to retrieve all Sample SOPs. "); } finally { ida.close(); } return sampleSOPs; } /** * * @return all methods for creating aliquots */ public List<LabelValueBean> getAliquotCreateMethods() throws Exception { List<LabelValueBean> createMethods = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select sop.name, file.path from SampleSOP sop join sop.sampleSOPFileCollection file where sop.description='aliquot creation'"; List results = ida.search(hqlString); for (Object obj : results) { String sopName = (String) ((Object[]) obj)[0]; String sopURI = (String) ((Object[]) obj)[1]; String sopURL = (sopURI == null) ? "" : sopURI; createMethods.add(new LabelValueBean(sopName, sopURL)); } } catch (Exception e) { logger.error("Error in retrieving all sample sources", e); throw new RuntimeException("Error in retrieving all sample sources"); } finally { ida.close(); } return createMethods; } /** * * @return all source sample IDs */ public List<String> getAllSourceSampleIds() throws Exception { List<String> sourceSampleIds = new ArrayList<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct sample.sourceSampleId from Sample sample order by sample.sourceSampleId"; List results = ida.search(hqlString); for (Object obj : results) { sourceSampleIds.add((String) obj); } } catch (Exception e) { logger.error("Error in retrieving all source sample IDs", e); throw new RuntimeException( "Error in retrieving all source sample IDs"); } finally { ida.close(); } return sourceSampleIds; } public Map<String, SortedSet<String>> getAllParticleTypeParticles() throws Exception { // TODO fill in actual database query. Map<String, SortedSet<String>> particleTypeParticles = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); try { ida.open(); // String hqlString = "select particle.type, particle.name from // Nanoparticle particle"; String hqlString = "select particle.type, particle.name from Nanoparticle particle where size(particle.characterizationCollection) = 0"; List results = ida.search(hqlString); SortedSet<String> particleNames = null; for (Object obj : results) { Object[] objArray = (Object[]) obj; String particleType = (String) objArray[0]; String particleName = (String) objArray[1]; if (particleType != null) { // check if the particle already has visibility group // assigned, if yes, do NOT add to the list List<String> groups = userService.getAccessibleGroups( particleName, CaNanoLabConstants.CSM_READ_ROLE); if (groups.size() == 0) { if (particleTypeParticles.get(particleType) != null) { particleNames = (SortedSet<String>) particleTypeParticles .get(particleType); } else { particleNames = new TreeSet<String>( new CaNanoLabComparators.SortableNameComparator()); particleTypeParticles.put(particleType, particleNames); } particleNames.add(particleName); } } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return particleTypeParticles; } /* * public String[] getAllParticleFunctions() { String[] functions = new * String[] { "Therapeutic", "Targeting", "Diagnostic Imaging", "Diagnostic * Reporting" }; return functions; } */ public Map<String, String> getAllParticleFunctions() { Map<String, String> functionsMap = new HashMap<String, String>(); functionsMap.put("Therapeutic", "Therapeutic"); functionsMap.put("Targeting", "Targeting"); functionsMap.put("Diagnostic Imaging", "Imaging"); functionsMap.put("Diagnostic Reporting", "Reporting"); return functionsMap; } public String[] getAllCharacterizationTypes() { String[] charTypes = new String[] { "Physical Characterization", "In Vitro Characterization", "In Vivo Characterization" }; return charTypes; } public String[] getAllDendrimerCores() { String[] cores = new String[] { "Diamine", "Ethyline" }; return cores; } public String[] getAllDendrimerSurfaceGroupNames() throws Exception { SortedSet<String> names = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct surfaceGroup.name from SurfaceGroup surfaceGroup where surfaceGroup.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { names.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Surface Group name."); throw new RuntimeException( "Problem to retrieve all Surface Group name. "); } finally { ida.close(); } names.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_SURFACE_GROUP_NAMES)); names.add(CaNanoLabConstants.OTHER); return (String[]) names.toArray(new String[0]); } public String[] getAllDendrimerBranches() throws Exception { SortedSet<String> branches = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.branch from DendrimerComposition dendrimer where dendrimer.branch is not null"; List results = ida.search(hqlString); for (Object obj : results) { branches.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Branches."); throw new RuntimeException( "Problem to retrieve all Dendrimer Branches. "); } finally { ida.close(); } branches.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_BRANCHES)); branches.add(CaNanoLabConstants.OTHER); return (String[]) branches.toArray(new String[0]); } public String[] getAllDendrimerGenerations() throws Exception { SortedSet<String> generations = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct dendrimer.generation from DendrimerComposition dendrimer where dendrimer.generation is not null "; List results = ida.search(hqlString); for (Object obj : results) { generations.add(obj.toString()); } } catch (Exception e) { logger.error("Problem to retrieve all Dendrimer Generations."); throw new RuntimeException( "Problem to retrieve all Dendrimer Generations. "); } finally { ida.close(); } generations.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_DENDRIMER_GENERATIONS)); generations.add(CaNanoLabConstants.OTHER); return (String[]) generations.toArray(new String[0]); } public String[] getAllMetalCompositions() { String[] compositions = new String[] { "Gold", "Sliver", "Iron oxide" }; return compositions; } public String[] getAllPolymerInitiators() throws Exception { SortedSet<String> initiators = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct polymer.initiator from PolymerComposition polymer where polymer.initiator is not null "; List results = ida.search(hqlString); for (Object obj : results) { initiators.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all Polymer Initiator."); throw new RuntimeException( "Problem to retrieve all Polymer Initiator. "); } finally { ida.close(); } initiators.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_POLYMER_INITIATORS)); initiators.add(CaNanoLabConstants.OTHER); return (String[]) initiators.toArray(new String[0]); } public List<String> getAllParticleSources() throws Exception { // TODO fill in db code return getAllSampleSources(); } public String getParticleClassification(String particleType) { String classification = CaNanoLabConstants.PARTICLE_CLASSIFICATION_MAP .get(particleType); return classification; } /** * * @return a map between a characterization type and its child * characterizations. */ public Map<String, String[]> getCharacterizationTypeCharacterizations() { Map<String, String[]> charTypeChars = new HashMap<String, String[]>(); String[] physicalChars = new String[] { CaNanoLabConstants.PHYSICAL_COMPOSITION, CaNanoLabConstants.PHYSICAL_SIZE, CaNanoLabConstants.PHYSICAL_MOLECULAR_WEIGHT, CaNanoLabConstants.PHYSICAL_MORPHOLOGY, CaNanoLabConstants.PHYSICAL_SOLUBILITY, CaNanoLabConstants.PHYSICAL_SURFACE, CaNanoLabConstants.PHYSICAL_PURITY, // CaNanoLabConstants.PHYSICAL_STABILITY, // CaNanoLabConstants.PHYSICAL_FUNCTIONAL, CaNanoLabConstants.PHYSICAL_SHAPE }; charTypeChars.put("physical", physicalChars); String[] toxChars = new String[] { CaNanoLabConstants.TOXICITY_OXIDATIVE_STRESS, CaNanoLabConstants.TOXICITY_ENZYME_FUNCTION }; charTypeChars.put("toxicity", toxChars); String[] cytoToxChars = new String[] { CaNanoLabConstants.CYTOTOXICITY_CELL_VIABILITY, CaNanoLabConstants.CYTOTOXICITY_CASPASE3_ACTIVIATION }; charTypeChars.put("cytoTox", cytoToxChars); String[] bloodContactChars = new String[] { CaNanoLabConstants.BLOODCONTACTTOX_PLATE_AGGREGATION, CaNanoLabConstants.BLOODCONTACTTOX_HEMOLYSIS, CaNanoLabConstants.BLOODCONTACTTOX_PLASMA_PROTEIN_BINDING, CaNanoLabConstants.BLOODCONTACTTOX_COAGULATION }; charTypeChars.put("bloodContactTox", bloodContactChars); String[] immuneCellFuncChars = new String[] { CaNanoLabConstants.IMMUNOCELLFUNCTOX_OXIDATIVE_BURST, CaNanoLabConstants.IMMUNOCELLFUNCTOX_CHEMOTAXIS, CaNanoLabConstants.IMMUNOCELLFUNCTOX_LEUKOCYTE_PROLIFERATION, CaNanoLabConstants.IMMUNOCELLFUNCTOX_PHAGOCYTOSIS, CaNanoLabConstants.IMMUNOCELLFUNCTOX_CYTOKINE_INDUCTION, CaNanoLabConstants.IMMUNOCELLFUNCTOX_CFU_GM, CaNanoLabConstants.IMMUNOCELLFUNCTOX_COMPLEMENT_ACTIVATION, CaNanoLabConstants.IMMUNOCELLFUNCTOX_NKCELL_CYTOTOXIC_ACTIVITY }; charTypeChars.put("immuneCellFuncTox", immuneCellFuncChars); // String[] metabolicChars = new String[] { // CaNanoLabConstants.METABOLIC_STABILITY_CYP450, // CaNanoLabConstants.METABOLIC_STABILITY_GLUCURONIDATION_SULPHATION, // CaNanoLabConstants.METABOLIC_STABILITY_ROS }; // charTypeChars.put("metabolicStabilityTox", metabolicChars); return charTypeChars; } public List<LabelValueBean> getAllInstrumentTypeAbbrs() throws Exception { List<LabelValueBean> instrumentTypeAbbrs = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, instrumentType.abbreviation from InstrumentType instrumentType where instrumentType.name is not null"; List results = ida.search(hqlString); for (Object obj : results) { if (obj != null) { Object[] objs = (Object[]) obj; String label = ""; if (objs[1] != null) { label = (String) objs[0] + "(" + objs[1] + ")"; } else { label = (String) objs[0]; } instrumentTypeAbbrs.add(new LabelValueBean(label, (String) objs[0])); } } } catch (Exception e) { logger.error("Problem to retrieve all instrumentTypes. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } instrumentTypeAbbrs.add(new LabelValueBean(CaNanoLabConstants.OTHER, CaNanoLabConstants.OTHER)); return instrumentTypeAbbrs; } public Map<String, SortedSet<String>> getAllInstrumentManufacturers() throws Exception { Map<String, SortedSet<String>> instrumentManufacturers = new HashMap<String, SortedSet<String>>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct instrumentType.name, manufacturer.name from InstrumentType instrumentType join instrumentType.manufacturerCollection manufacturer "; List results = ida.search(hqlString); SortedSet<String> manufacturers = null; for (Object obj : results) { String instrumentType = ((Object[]) obj)[0].toString(); String manufacturer = ((Object[]) obj)[1].toString(); if (instrumentManufacturers.get(instrumentType) != null) { manufacturers = (SortedSet<String>) instrumentManufacturers .get(instrumentType); } else { manufacturers = new TreeSet<String>(); instrumentManufacturers.put(instrumentType, manufacturers); } manufacturers.add(manufacturer); } List allResult = ida .search("select manufacturer.name from Manufacturer manufacturer where manufacturer.name is not null"); SortedSet<String> allManufacturers = null; allManufacturers = new TreeSet<String>(); for (Object obj : allResult) { String name = (String) obj; allManufacturers.add(name); } instrumentManufacturers.put(CaNanoLabConstants.OTHER, allManufacturers); } catch (Exception e) { logger .error("Problem to retrieve manufacturers for intrument types " + e); throw new RuntimeException( "Problem to retrieve manufacturers for intrument types."); } finally { ida.close(); } return instrumentManufacturers; } public String[] getSizeDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Volume", "Intensity", "Number" }; return graphTypes; } public String[] getMolecularWeightDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Volume", "Mass", "Number" }; return graphTypes; } public String[] getMorphologyDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getShapeDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getStabilityDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getPurityDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getSolubilityDistributionGraphTypes() { // TODO query from database or properties file String[] graphTypes = new String[] { "Image", "Graph" }; return graphTypes; } public String[] getAllMorphologyTypes() throws Exception { SortedSet<String> morphologyTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct morphology.type from Morphology morphology"; List results = ida.search(hqlString); for (Object obj : results) { morphologyTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all morphology types."); throw new RuntimeException( "Problem to retrieve all morphology types."); } finally { ida.close(); } morphologyTypes.addAll(Arrays .asList(CaNanoLabConstants.DEFAULT_MORPHOLOGY_TYPES)); morphologyTypes.add(CaNanoLabConstants.OTHER); return (String[]) morphologyTypes.toArray(new String[0]); } public String[] getAllShapeTypes() throws Exception { SortedSet<String> shapeTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct shape.type from Shape shape where shape.type is not null"; List results = ida.search(hqlString); for (Object obj : results) { shapeTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all shape types."); throw new RuntimeException("Problem to retrieve all shape types."); } finally { ida.close(); } shapeTypes .addAll(Arrays.asList(CaNanoLabConstants.DEFAULT_SHAPE_TYPES)); shapeTypes.add(CaNanoLabConstants.OTHER); return (String[]) shapeTypes.toArray(new String[0]); } public Map<ProtocolBean, List<ProtocolFileBean>> getAllProtocolNameVersionByType( String type) throws Exception { Map<ProtocolBean, List<ProtocolFileBean>> nameVersions = new HashMap<ProtocolBean, List<ProtocolFileBean>>(); Map<Protocol, ProtocolBean> keyMap = new HashMap<Protocol, ProtocolBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select protocolFile, protocolFile.protocol from ProtocolFile protocolFile" + " where protocolFile.protocol.type = '" + type + "'"; List results = ida.search(hqlString); for (Object obj : results) { Object[] array = (Object[]) obj; Object key = null; Object value = null; for (int i = 0; i < array.length; i++) { if (array[i] instanceof Protocol) { key = array[i]; } else if (array[i] instanceof ProtocolFile) { value = array[i]; } } if (keyMap.containsKey((Protocol) key)) { ProtocolBean pb = keyMap.get((Protocol) key); List<ProtocolFileBean> localList = nameVersions.get(pb); ProtocolFileBean fb = new ProtocolFileBean(); fb.setVersion(((ProtocolFile) value).getVersion()); fb.setId(((ProtocolFile) value).getId().toString()); localList.add(fb); } else { List<ProtocolFileBean> localList = new ArrayList<ProtocolFileBean>(); ProtocolFileBean fb = new ProtocolFileBean(); fb.setVersion(((ProtocolFile) value).getVersion()); fb.setId(((ProtocolFile) value).getId().toString()); localList.add(fb); ProtocolBean protocolBean = new ProtocolBean(); Protocol protocol = (Protocol) key; protocolBean.setId(protocol.getId().toString()); protocolBean.setName(protocol.getName()); protocolBean.setType(protocol.getType()); nameVersions.put(protocolBean, localList); keyMap.put((Protocol) key, protocolBean); } } } catch (Exception e) { logger .error("Problem to retrieve all protocol names and their versions by type " + type); throw new RuntimeException( "Problem to retrieve all protocol names and their versions by type " + type); } finally { ida.close(); } return nameVersions; } public SortedSet<String> getAllProtocolTypes() throws Exception { SortedSet<String> protocolTypes = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct protocol.type from Protocol protocol where protocol.type is not null"; List results = ida.search(hqlString); for (Object obj : results) { protocolTypes.add((String) obj); } } catch (Exception e) { logger.error("Problem to retrieve all protocol types."); throw new RuntimeException( "Problem to retrieve all protocol types."); } finally { ida.close(); } return protocolTypes; } public SortedSet<ProtocolBean> getAllProtocols(UserBean user) throws Exception { SortedSet<ProtocolBean> protocolBeans = new TreeSet<ProtocolBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from Protocol as protocol left join fetch protocol.protocolFileCollection"; List results = ida.search(hqlString); for (Object obj : results) { Protocol p = (Protocol) obj; ProtocolBean pb = new ProtocolBean(); pb.setId(p.getId().toString()); pb.setName(p.getName()); pb.setType(p.getType()); PersistentSet set = (PersistentSet) p .getProtocolFileCollection(); // HashSet hashSet = set. if (!set.isEmpty()) { List<ProtocolFileBean> list = new ArrayList<ProtocolFileBean>(); for (Iterator it = set.iterator(); it.hasNext();) { ProtocolFile pf = (ProtocolFile) it.next(); ProtocolFileBean pfb = new ProtocolFileBean(); pfb.setId(pf.getId().toString()); pfb.setVersion(pf.getVersion()); list.add(pfb); } pb.setFileBeanList(filterProtocols(list, user)); } if (!pb.getFileBeanList().isEmpty()) protocolBeans.add(pb); } } catch (Exception e) { logger.error("Problem to retrieve all protocol names and types."); throw new RuntimeException( "Problem to retrieve all protocol names and types."); } finally { ida.close(); } return protocolBeans; } private List<ProtocolFileBean> filterProtocols( List<ProtocolFileBean> protocolFiles, UserBean user) throws Exception { UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); List<LabFileBean> tempList = new ArrayList<LabFileBean>(); for (ProtocolFileBean pfb : protocolFiles) { tempList.add((LabFileBean) pfb); } List<LabFileBean> filteredProtocols = userService.getFilteredFiles( user, tempList); protocolFiles.clear(); if (filteredProtocols == null || filteredProtocols.isEmpty()) return protocolFiles; for (LabFileBean lfb : filteredProtocols) { protocolFiles.add((ProtocolFileBean) lfb); } return protocolFiles; } public String[] getAllStressorTypes() { String[] stressorTypes = new String[] { "Thermal", "PH", "Freeze thaw", "Photo", "Centrifugation", "Lyophilization", "Chemical", "Other" }; return stressorTypes; } public String[] getAllAreaMeasureUnits() { String[] areaUnit = new String[] { "sq nm" }; return areaUnit; } public String[] getAllChargeMeasureUnits() { String[] chargeUnit = new String[] { "a.u", "aC", "Ah", "C", "esu", "Fr", "statC" }; return chargeUnit; } public String[] getAllDensityMeasureUnits() { String[] densityUnits = new String[] { "kg/L" }; return densityUnits; } public String[] getAllControlTypes() { String[] controlTypes = new String[] { " ", "Positive", "Negative" }; return controlTypes; } public String[] getAllConditionTypes() { String[] conditionTypes = new String[] { "Particle Concentration", "Temperature", "Time" }; return conditionTypes; } public Map<String, String[]> getAllAgentTypes() { Map<String, String[]> agentTypes = new HashMap<String, String[]>(); String[] therapeuticsAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Therapeutic", therapeuticsAgentTypes); String[] targetingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Targeting", targetingAgentTypes); String[] imagingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Imaging", imagingAgentTypes); String[] reportingAgentTypes = new String[] { "Peptide", "Small Molecule", "Antibody", "DNA", "Probe", "Image Contrast Agent", "Other" }; agentTypes.put("Reporting", reportingAgentTypes); return agentTypes; } public Map<String, String[]> getAllAgentTargetTypes() { Map<String, String[]> agentTargetTypes = new HashMap<String, String[]>(); String[] targetTypes = new String[] { "Receptor", "Antigen", "Other" }; String[] targetTypes1 = new String[] { "Receptor", "Other" }; String[] targetTypes2 = new String[] { "Other" }; agentTargetTypes.put("Small Molecule", targetTypes2); agentTargetTypes.put("Peptide", targetTypes1); agentTargetTypes.put("Antibody", targetTypes); agentTargetTypes.put("DNA", targetTypes1); agentTargetTypes.put("Probe", targetTypes1); agentTargetTypes.put("Other", targetTypes2); agentTargetTypes.put("Image Contrast Agent", targetTypes2); return agentTargetTypes; } public String[] getAllTimeUnits() { String[] timeUnits = new String[] { "hours", "days", "months" }; return timeUnits; } public String[] getAllTemperatureUnits() { String[] temperatureUnits = new String[] { "degrees celsius", "degrees fahrenhiet" }; return temperatureUnits; } public String[] getAllConcentrationUnits() { String[] concentrationUnits = new String[] { "g/ml", "mg/ml", "pg/ml", "ug/ml", "ug/ul" }; return concentrationUnits; } public Map<String, String[]> getAllConditionUnits() { Map<String, String[]> conditionTypeUnits = new HashMap<String, String[]>(); String[] concentrationUnits = new String[] { "g/ml", "mg/ml", "pg/ml", "ug/ml", "ug/ul", }; String[] temperatureUnits = new String[] { "degrees celsius", "degrees fahrenhiet" }; String[] timeUnits = new String[] { "hours", "days", "months" }; conditionTypeUnits.put("Particle Concentration", concentrationUnits); conditionTypeUnits.put("Time", timeUnits); conditionTypeUnits.put("Temperature", temperatureUnits); return conditionTypeUnits; } public String[] getAllCellLines() throws Exception { SortedSet<String> cellLines = new TreeSet<String>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "select distinct cellViability.cellLine, caspase.cellLine from CellViability cellViability, Caspase3Activation caspase"; List results = ida.search(hqlString); for (Object obj : results) { // cellLines.add((String) obj); Object[] objects = (Object[]) obj; for (Object object : objects) { if (object != null) { cellLines.add((String) object); } } } } catch (Exception e) { logger.error("Problem to retrieve all Cell lines."); throw new RuntimeException("Problem to retrieve all Cell lines."); } finally { ida.close(); } cellLines.addAll(Arrays.asList(CaNanoLabConstants.DEFAULT_CELLLINES)); cellLines.add(CaNanoLabConstants.OTHER); return (String[]) cellLines.toArray(new String[0]); } public String[] getAllActivationMethods() { String[] activationMethods = new String[] { "NMR", "MRI", "Radiation", "Ultrasound", "Ultraviolet Light" }; return activationMethods; } public List<LabelValueBean> getAllSpecies() throws Exception { List<LabelValueBean> species = new ArrayList<LabelValueBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); species.add(new LabelValueBean("", "")); try { for (int i = 0; i < CaNanoLabConstants.SPECIES_COMMON.length; i++) { String specie = CaNanoLabConstants.SPECIES_COMMON[i]; species.add(new LabelValueBean(specie, specie)); } } catch (Exception e) { logger.error("Problem to retrieve all species. " + e); throw new RuntimeException( "Problem to retrieve all intrument types. "); } finally { ida.close(); } return species; } public String[] getAllReportTypes() { String[] allReportTypes = new String[] { CaNanoLabConstants.REPORT, CaNanoLabConstants.ASSOCIATED_FILE }; return allReportTypes; } /** * Get other particles from the given particle source * * @param particleSource * @param particleName * @param user * @return * @throws Exception */ public SortedSet<String> getOtherParticles(String particleSource, String particleName, UserBean user) throws Exception { IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); UserService userService = new UserService( CaNanoLabConstants.CSM_APP_NAME); SortedSet<String> otherParticleNames = new TreeSet<String>(); try { ida.open(); String hqlString = "select particle.name from Nanoparticle particle where particle.source.organizationName='" + particleSource + "' and particle.name !='" + particleName + "'"; List results = ida.search(hqlString); for (Object obj : results) { String otherParticleName = (String) obj; // check if user can see the particle boolean status = userService.checkReadPermission(user, otherParticleName); if (status) { otherParticleNames.add(otherParticleName); } } } catch (Exception e) { logger .error("Error in retrieving all particle type particles. ", e); throw new RuntimeException( "Error in retrieving all particle type particles. "); } finally { ida.close(); } return otherParticleNames; } public List<InstrumentBean> getAllInstruments() throws Exception { List<InstrumentBean> instruments = new ArrayList<InstrumentBean>(); IDataAccess ida = (new DataAccessProxy()) .getInstance(IDataAccess.HIBERNATE); try { ida.open(); String hqlString = "from Instrument instrument where instrument.type is not null and instrument.manufacturer is not null"; List results = ida.search(hqlString); for (Object obj : results) { Instrument instrument = (Instrument) obj; instruments.add(new InstrumentBean(instrument)); } } catch (Exception e) { logger.error("Problem to retrieve all instruments. " + e); throw new RuntimeException("Problem to retrieve all intruments. "); } finally { ida.close(); } return instruments; } }
package org.spoofax.terms.io.binary; import static org.spoofax.interpreter.terms.IStrategoTerm.APPL; import static org.spoofax.interpreter.terms.IStrategoTerm.INT; import static org.spoofax.interpreter.terms.IStrategoTerm.LIST; import static org.spoofax.interpreter.terms.IStrategoTerm.REAL; import static org.spoofax.interpreter.terms.IStrategoTerm.STRING; import static org.spoofax.interpreter.terms.IStrategoTerm.TUPLE; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.FileChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoInt; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoReal; import org.spoofax.interpreter.terms.IStrategoString; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.IStrategoTuple; import org.spoofax.terms.io.TermWriter; import org.spoofax.terms.util.TermUtils; /** * Writes a term in the binary Streamable ATerm Format (SAF). */ public final class SAFWriter implements TermWriter { /** * Writes the given ATerm to a (streamable) binary format. Supply the * constructor of this class with a ATerm and keep calling the serialize method * until the finished() method returns true.<br /> * <br /> * For example (yes I know this code is crappy, but it's simple):<blockquote> * * <pre> * ByteBuffer buffer = ByteBuffer.allocate(8192); * BinaryWriter bw = new BinaryWriter(aterm); * while (!bw.isFinished()) { * buffer.clear(); * bw.serialize(buffer); * while (buffer.hasRemaining()) * channel.write(buffer); // Write the chunk of data to a channel * } * </pre> * * </blockquote> * * @author Arnold Lankamp * @author Nathan Bruning (ported to use IStrategoTerm) */ private final static class SAFWriterInternal { private final static int ISSHAREDFLAG = 0x00000080; private final static int ANNOSFLAG = 0x00000010; private final static int ISFUNSHARED = 0x00000040; private final static int APPLQUOTED = 0x00000020; private final static int STACKSIZE = 256; private final static int MINIMUMFREESPACE = 10; private final Map<IStrategoTerm, Integer> sharedTerms; private int currentKey; private final Map<Object, Integer> applSignatures; private int sigKey; private ATermMapping[] stack; private int stackPosition; private IStrategoTerm currentTerm; private int indexInTerm; private byte[] tempNameWriteBuffer; private ByteBuffer currentBuffer; /** * Constructor. * * @param root * The ATerm that needs to be serialized. */ private SAFWriterInternal(IStrategoTerm root) { super(); sharedTerms = new HashMap<IStrategoTerm, Integer>(); currentKey = 0; applSignatures = new HashMap<Object, Integer>(); sigKey = 0; stack = new ATermMapping[STACKSIZE]; stackPosition = 0; ATermMapping tm = new ATermMapping(); tm.term = root; stack[stackPosition] = tm; currentTerm = root; indexInTerm = 0; tempNameWriteBuffer = null; } /** * Serializes the term from the position where it left of the last time this * method was called. Note that the buffer will be flipped before returned. * * @param buffer * The buffer that will be filled with data. */ public void serialize(ByteBuffer buffer) { currentBuffer = buffer; while (currentTerm != null) { if (buffer.remaining() < MINIMUMFREESPACE) break; Integer id = sharedTerms.get(currentTerm); if (id != null) { buffer.put((byte) ISSHAREDFLAG); writeInt(id.intValue()); stackPosition--; // Pop the term from the stack, since it's // subtree is shared. } else { visit(currentTerm); if (TermUtils.isList(currentTerm)) stack[stackPosition].nextPartOfList = (IStrategoList) currentTerm; // for // ATermList->next // optimizaton. // Don't add the term to the shared list until we are completely // done with it. if (indexInTerm == 0) sharedTerms.put(currentTerm, new Integer(currentKey++)); else break; } currentTerm = getNextTerm(); } buffer.flip(); } /** * nathan: added */ protected void visit(IStrategoTerm term) { switch (term.getTermType()) { case APPL: voidVisitAppl((IStrategoAppl) term); break; case INT: voidVisitInt((IStrategoInt) term); break; case LIST: voidVisitList((IStrategoList) term); break; case REAL: voidVisitReal((IStrategoReal) term); break; case STRING: voidVisitString((IStrategoString) term); break; case TUPLE: voidVisitTuple((IStrategoTuple) term); break; default: throw new RuntimeException("Could not serializate term of type " + term.getClass().getName() + " to SAF format."); } } private void voidVisitTuple(IStrategoTuple term) { writeAppl(term, term.getSubtermCount(), "", false); } private void voidVisitString(IStrategoString term) { writeAppl(term, term.stringValue(), term.stringValue(), true); } /** * Checks if we are done serializing. * * @return true when we are done serializing; false otherwise. */ public boolean isFinished() { return (currentTerm == null); } /** * Finds the next term we are going to serialize, based on the current state * of the stack. * * @return The next term we are going to serialize. */ private IStrategoTerm getNextTerm() { IStrategoTerm next = null; // Make sure the stack remains large enough ensureStackCapacity(); while (next == null && stackPosition > -1) { ATermMapping current = stack[stackPosition]; IStrategoTerm term = current.term; final boolean hasRemainigSubterms = current.subTermsAfter > 0 || term.getSubtermCount() > current.subTermIndex + 1; if (hasRemainigSubterms) { if (!TermUtils.isList(term)) { next = term.getSubterm(++current.subTermIndex); } else { IStrategoList nextList = current.nextPartOfList; next = nextList.head(); current.nextPartOfList = nextList.tail(); current.subTermIndex++; current.subTermsAfter } ATermMapping child = new ATermMapping(); child.term = next; if (TermUtils.isList(next)) { child.subTermsAfter = next.getSubtermCount(); } stack[++stackPosition] = child; } else if (!current.annosDone && !term.getAnnotations().isEmpty()) { next = term.getAnnotations(); ATermMapping annos = new ATermMapping(); annos.term = next; stack[++stackPosition] = annos; current.annosDone = true; } else { stackPosition } } return next; } /** * Resizes the stack when needed. When we're running low on stack space the * capacity will be doubled. */ private void ensureStackCapacity() { int stackSize = stack.length; if (stackPosition + 1 == stackSize) { ATermMapping[] newStack = new ATermMapping[(stackSize << 1)]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; } } /** * Returns a header for the given term. * * @param term * The term we are requesting a header for. * @return The constructed header. */ private byte getHeader(IStrategoTerm term) { byte header = (byte) ATermConstants.ATermTypeForTerm(term); if (!term.getAnnotations().isEmpty()) header = (byte) (header | ANNOSFLAG); return header; } /** * Structure that holds information about the state of the contained term. * * @author Arnold Lankamp */ protected static class ATermMapping { public IStrategoTerm term; public int subTermIndex = -1; public int subTermsAfter = -1; public boolean annosDone = false; public IStrategoList nextPartOfList = null; // This is for a ATermList // 'nextTerm' optimalization // only. } /** * Write appl or string or tuple. * * @param term * the term * @param fun * the constructor key, can be a IStrategoConstructor (for * applications), a IStrategoString (for strings) or an integer, * for tuples * @param name the constructor name, or string value, or empty string for a tuple * @param isString true if the term is a string */ protected void writeAppl(IStrategoTerm term, Object fun, String name, boolean isString) { if (indexInTerm == 0) { byte header = getHeader(term); Integer key = applSignatures.get(fun); if (key == null) { if (isString) header = (byte) (header | APPLQUOTED); currentBuffer.put(header); writeInt(term.getSubtermCount()); byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); int length = nameBytes.length; writeInt(length); int endIndex = length; int remaining = currentBuffer.remaining(); if (remaining < endIndex) endIndex = remaining; currentBuffer.put(nameBytes, 0, endIndex); if (endIndex != length) { indexInTerm = endIndex; tempNameWriteBuffer = nameBytes; } applSignatures.put(fun, new Integer(sigKey++)); } else { header = (byte) (header | ISFUNSHARED); currentBuffer.put(header); writeInt(key.intValue()); } } else { int length = tempNameWriteBuffer.length; int endIndex = length; int remaining = currentBuffer.remaining(); if ((indexInTerm + remaining) < endIndex) endIndex = (indexInTerm + remaining); currentBuffer.put(tempNameWriteBuffer, indexInTerm, (endIndex - indexInTerm)); indexInTerm = endIndex; if (indexInTerm == length) { indexInTerm = 0; tempNameWriteBuffer = null; } } } /** * Serializes the given appl. The function name of the appl can be * serialized in chunks. * */ public void voidVisitAppl(IStrategoAppl arg) { writeAppl(arg, arg.getConstructor(), arg.getConstructor().getName(), false); } /** * Serializes the given int. Ints will always be serialized in one piece. */ public void voidVisitInt(IStrategoInt arg) { currentBuffer.put(getHeader(arg)); writeInt(arg.intValue()); } /** * Serializes the given list. List information will always be serialized in * one piece. * */ public void voidVisitList(IStrategoList arg) { byte header = getHeader(arg); currentBuffer.put(header); writeInt(arg.size()); } /** * Serializes the given real. Reals will always be serialized in one peice. */ public void voidVisitReal(IStrategoReal arg) { currentBuffer.put(getHeader(arg)); writeDouble(arg.realValue()); } private final static int SEVENBITS = 0x0000007f; private final static int SIGNBIT = 0x00000080; private final static int LONGBITS = 8; /** * Splits the given integer in separate bytes and writes it to the buffer. * It will occupy the smallest amount of bytes possible. This is done in the * following way: the sign bit will be used to indicate that more bytes * coming, if this is set to 0 we know we are done. Since we are mostly * writing small values, this will save a considerable amount of space. On * the other hand a large number will occupy 5 bytes instead of the regular * 4. * * @param value * The integer that needs to be split and written. */ private void writeInt(int value) { int intValue = value; if ((intValue & 0xffffff80) == 0) { currentBuffer.put((byte) (intValue & SEVENBITS)); return; } currentBuffer.put((byte) ((intValue & SEVENBITS) | SIGNBIT)); if ((intValue & 0xffffc000) == 0) { currentBuffer.put((byte) ((intValue >>> 7) & SEVENBITS)); return; } currentBuffer.put((byte) (((intValue >>> 7) & SEVENBITS) | SIGNBIT)); if ((intValue & 0xffe00000) == 0) { currentBuffer.put((byte) ((intValue >>> 14) & SEVENBITS)); return; } currentBuffer.put((byte) (((intValue >>> 14) & SEVENBITS) | SIGNBIT)); if ((intValue & 0xf0000000) == 0) { currentBuffer.put((byte) ((intValue >>> 21) & SEVENBITS)); return; } currentBuffer.put((byte) (((intValue >>> 21) & SEVENBITS) | SIGNBIT)); currentBuffer.put((byte) ((intValue >>> 28) & SEVENBITS)); } /** * Splits the given double in separate bytes and writes it to the buffer. * Doubles will always occupy 8 bytes, since the convertion of a floating * point number to a long will always cause the high order bits to be * occupied. * * @param value * The integer that needs to be split and written. */ private void writeDouble(double value) { long longValue = Double.doubleToLongBits(value); writeLong(longValue); } private void writeLong(long value) { for (int i = 0; i < LONGBITS; i++) { currentBuffer.put((byte) (value >>> (i * 8))); } } } @Override public void write(IStrategoTerm term, OutputStream outputStream) throws IOException { SAFWriterInternal binaryWriter = new SAFWriterInternal(term); ByteBuffer byteBuffer = ByteBuffer.allocate(65536); WritableByteChannel channel = Channels.newChannel(outputStream); outputStream.write((byte)'?'); do { byteBuffer.clear(); binaryWriter.serialize(byteBuffer); int blockSize = byteBuffer.limit(); outputStream.write((byte)(blockSize & 0x000000ff)); outputStream.write((byte)((blockSize >>> 8) & 0x000000ff)); channel.write(byteBuffer); } while(!binaryWriter.isFinished()); // Do not close the channel, doing so will also close the backing // stream. } /** * @deprecated Use {@code new SAFWriter().writeToFile(term, file)} instead. */ @Deprecated public static void writeTermToSAFFile(IStrategoTerm term, File file) throws IOException { SAFWriter writer = new SAFWriter(); writer.writeToFile(term, file); } /** * @deprecated Use {@code new SAFWriter().writeToBytes(term)} instead. */ @Deprecated public static byte[] writeTermToSAFString(IStrategoTerm term) { SAFWriter writer = new SAFWriter(); return writer.writeToBytes(term); } /** * @deprecated Use {@code new SAFWriter().write(term, outputStream)} instead. */ @Deprecated public static void writeTermToSAFStream(IStrategoTerm term, OutputStream outputStream) throws IOException { SAFWriter writer = new SAFWriter(); writer.write(term, outputStream); } }
package io.core9.commerce.checkout; import io.core9.commerce.cart.Cart; import io.core9.commerce.cart.LineItem; import io.core9.plugin.database.repository.AbstractCrudEntity; import io.core9.plugin.database.repository.Collection; import io.core9.plugin.database.repository.CrudEntity; import java.util.Map; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) @Collection("core.orders") public class OrderImpl extends AbstractCrudEntity implements CrudEntity, Order { private Address billing; private Address shipping; private String paymentmethod; private Map<String,Object> paymentData; private Cart cart; private LineItem shippingCost; private boolean finalized; private String remark; public Address getBilling() { return billing; } public void setBilling(Address billing) { this.billing = billing; } public Address getShipping() { return shipping; } public void setShipping(Address shipping) { this.shipping = shipping; } public String getPaymentmethod() { return paymentmethod; } public void setPaymentmethod(String paymentmethod) { this.paymentmethod = paymentmethod; } @Override public Cart getCart() { return cart; } @Override public void setCart(Cart cart) { this.cart = cart; } @Override public LineItem getShippingCost() { return shippingCost; } @Override public void setShippingCost(LineItem shippingCost) { this.shippingCost = shippingCost; } @Override public Map<String, Object> getPaymentData() { return paymentData; } @Override public void setPaymentData(Map<String, Object> data) { this.paymentData = data; } @Override public boolean isFinalized() { return this.finalized; } @Override public void setFinalized(boolean finalized) { this.finalized = finalized; } @Override public int getTotal() { if(shippingCost != null) { return cart.getTotal() + shippingCost.getPrice(); } return cart.getTotal(); } @Override public String getRemark() { return remark; } @Override public void setRemark(String remark) { this.remark = remark; } }
package info.justaway.fragment.profile; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import info.justaway.EditProfileActivity; import info.justaway.JustawayApplication; import info.justaway.R; import info.justaway.ScaleImageActivity; import info.justaway.task.FollowTask; import info.justaway.task.UnfollowTask; import twitter4j.Relationship; import twitter4j.User; public class SummaryFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_profile_summary, container, false); JustawayApplication application = JustawayApplication.getApplication(); final User user = (User) getArguments().getSerializable("user"); Relationship relationship = (Relationship) getArguments().getSerializable("relationship"); ImageView icon = (ImageView) v.findViewById(R.id.icon); TextView name = (TextView) v.findViewById(R.id.name); TextView screenName = (TextView) v.findViewById(R.id.screenName); TextView followedBy = (TextView) v.findViewById(R.id.followedBy); TextView follow = (TextView) v.findViewById(R.id.follow); String iconUrl = user.getBiggerProfileImageURL(); application.displayRoundedImage(iconUrl, icon); icon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), ScaleImageActivity.class); intent.putExtra("url", user.getOriginalProfileImageURL()); startActivity(intent); } }); name.setText(user.getName()); screenName.setText("@" + user.getScreenName()); if (relationship.isSourceFollowedByTarget()) { followedBy.setText(""); } else { followedBy.setText(""); } User me = application.getUser(); if (me == null) { follow.setVisibility(View.GONE); return v; } follow.setVisibility(View.VISIBLE); if (user.getId() == me.getId()) { follow.setText(""); follow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), EditProfileActivity.class); startActivity(intent); } }); } else if (relationship.isSourceFollowingTarget()) { follow.setText(""); follow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new UnfollowTask().execute(user.getId()); } }); } else { follow.setText(""); follow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new FollowTask().execute(user.getId()); } }); } return v; } }
package info.tregmine.listeners; import java.util.Map; import java.util.HashMap; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.Queue; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.SkullType; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.Skull; import org.bukkit.entity.Item; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.player.PlayerCommandPreprocessEvent; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerKickEvent; import org.bukkit.event.player.PlayerLoginEvent.Result; import org.bukkit.event.player.PlayerLoginEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Score; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.ScoreboardManager; import org.kitteh.tag.PlayerReceiveNameTagEvent; import info.tregmine.Tregmine; import info.tregmine.api.PlayerReport; import info.tregmine.api.TregminePlayer; import info.tregmine.api.Rank; import info.tregmine.api.PlayerBannedException; import info.tregmine.api.lore.Created; import info.tregmine.api.util.ScoreboardClearTask; import info.tregmine.database.DAOException; import info.tregmine.database.IContext; import info.tregmine.database.IInventoryDAO; import info.tregmine.database.IMotdDAO; import info.tregmine.database.ILogDAO; import info.tregmine.database.IPlayerDAO; import info.tregmine.database.IPlayerReportDAO; import info.tregmine.database.IWalletDAO; import info.tregmine.database.IMentorLogDAO; import info.tregmine.commands.MentorCommand; import static info.tregmine.database.IInventoryDAO.InventoryType; public class TregminePlayerListener implements Listener { private static class RankComparator implements Comparator<TregminePlayer> { private int order; public RankComparator() { this.order = 1; } public RankComparator(boolean reverseOrder) { this.order = reverseOrder ? -1 : 1; } @Override public int compare(TregminePlayer a, TregminePlayer b) { return order * (a.getGuardianRank() - b.getGuardianRank()); } } private final static String[] quitMessages = new String[] { ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " deserted from the battlefield with a hearty good bye!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " stole the cookies and ran!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was eaten by a teenage mutant ninja platypus!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " parachuted of the plane and into the unknown!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was eaten by a teenage mutant ninja creeper!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " jumped off the plane with a cobble stone parachute!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " built Rome in one day and now deserves a break!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " will come back soon because Tregmine is awesome!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " leaves the light and enter darkness.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " disconnects from a better life.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " already miss the best friends in the world!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " will build something epic next time.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " is not banned... yet!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " has left our world!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " went to browse Tregmine's forums instead!", ChatColor.DARK_GRAY + "Quit - %s" + "'s" + ChatColor.DARK_GRAY + " CPU was killed by the Rendermen!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " logged out by accident!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found the IRL warp!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " left the game due to IRL chunk error issues!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " left the Matrix. Say hi to Morpheus!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " disconnected? What is this!? Impossibru!", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found a lose cable and ate it.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found the true END of minecraft.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " found love elswhere.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " rage quit the server.", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was not accidently banned by " + ChatColor.DARK_RED + "BlackX", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " got " + ChatColor.WHITE + "TROLLED by " + ChatColor.DARK_RED + "TheScavenger101", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " lost an epic rap battle with " + ChatColor.DARK_RED + "einand", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was bored to death by " + ChatColor.DARK_RED + "knipil", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " went squid fishing with " + ChatColor.DARK_RED + "GeorgeBombadil", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " shouldn't have joined a spelling bee with " + ChatColor.DARK_RED + "mejjad", ChatColor.DARK_GRAY + "Quit - %s" + ChatColor.DARK_GRAY + " was paralyzed by a gaze from " + ChatColor.DARK_RED + "mksen", }; private Tregmine plugin; private Map<Item, TregminePlayer> droppedItems; public TregminePlayerListener(Tregmine instance) { this.plugin = instance; droppedItems = new HashMap<Item, TregminePlayer>(); } @EventHandler public void onPlayerClick(PlayerInteractEvent event) { if (event.getAction() != Action.RIGHT_CLICK_BLOCK) { return; } Player player = event.getPlayer(); BlockState block = event.getClickedBlock().getState(); if (block instanceof Skull) { Skull skull = (Skull) block; if (!skull.getSkullType().equals(SkullType.PLAYER)) { return; } String owner = skull.getOwner(); TregminePlayer skullowner = plugin.getPlayerOffline(owner); if (skullowner != null){ ChatColor C = skullowner.getNameColor(); player.sendMessage(ChatColor.AQUA + "This is " + C + owner + "'s " + ChatColor.AQUA + "head!"); }else{ player.sendMessage(ChatColor.AQUA + "This is " + ChatColor.WHITE + owner + ChatColor.AQUA + "'s head!"); } } } @EventHandler public void onPlayerItemHeld(InventoryCloseEvent event) { Player player = (Player) event.getPlayer(); if (player.getGameMode() == GameMode.CREATIVE) { for (ItemStack item : player.getInventory().getContents()) { if (item != null) { ItemMeta meta = item.getItemMeta(); List<String> lore = new ArrayList<String>(); lore.add(Created.CREATIVE.toColorString()); TregminePlayer p = this.plugin.getPlayer(player); lore.add(ChatColor.WHITE + "by: " + p.getChatName()); lore.add(ChatColor.WHITE + "Value: " + ChatColor.MAGIC + "0000" + ChatColor.RESET + ChatColor.WHITE + " Treg"); meta.setLore(lore); item.setItemMeta(meta); } } } } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { Player player = event.getPlayer(); Block block = event.getClickedBlock(); Location loc = block.getLocation(); if (player.getItemInHand().getType() == Material.BOOK) { player.sendMessage(ChatColor.DARK_AQUA + "Type: " + ChatColor.AQUA + block.getType().toString() + " (" + ChatColor.BLUE + block.getType().getId() + ChatColor.DARK_AQUA + ")"); player.sendMessage(ChatColor.DARK_AQUA + "Data: " + ChatColor.AQUA + (int) block.getData()); player.sendMessage(ChatColor.RED + "X" + ChatColor.WHITE + ", " + ChatColor.GREEN + "Y" + ChatColor.WHITE + ", " + ChatColor.BLUE + "Z" + ChatColor.WHITE + ": " + ChatColor.RED + loc.getBlockX() + ChatColor.WHITE + ", " + ChatColor.GREEN + loc.getBlockY() + ChatColor.WHITE + ", " + ChatColor.BLUE + loc.getBlockZ()); try { player.sendMessage(ChatColor.DARK_AQUA + "Biome: " + ChatColor.AQUA + block.getBiome().toString()); } catch (Exception e) { player.sendMessage(ChatColor.DARK_AQUA + "Biome: " + ChatColor.AQUA + "NULL"); } Tregmine.LOGGER.info("POS: " + loc.getBlockX() + ", " + loc.getBlockY() + ", " + loc.getBlockZ()); } } } @EventHandler public void onPreCommand(PlayerCommandPreprocessEvent event) { // Tregmine.LOGGER.info("COMMAND: " + event.getPlayer().getName() + "::" // + event.getMessage()); } @EventHandler public void onPlayerLogin(PlayerLoginEvent event) { TregminePlayer player; try { player = plugin.addPlayer(event.getPlayer(), event.getAddress()); if (player == null) { event.disallow(Result.KICK_OTHER, "Something went wrong"); return; } } catch (PlayerBannedException e) { event.disallow(Result.KICK_BANNED, e.getMessage()); return; } if (player.getRank() == Rank.UNVERIFIED) { player.setChatState(TregminePlayer.ChatState.SETUP); } if (player.getLocation().getWorld().getName().matches("world_the_end")) { player.teleport(this.plugin.getServer().getWorld("world") .getSpawnLocation()); } if (player.getKeyword() != null) { String keyword = player.getKeyword() + ".mc.tregmine.info:25565".toLowerCase(); Tregmine.LOGGER.warning("host: " + event.getHostname()); Tregmine.LOGGER.warning("keyword:" + keyword); if (keyword.equals(event.getHostname().toLowerCase()) || keyword.matches("mc.tregmine.info")) { Tregmine.LOGGER.warning(player.getName() + " keyword :: success"); } else { Tregmine.LOGGER.warning(player.getName() + " keyword :: faild"); event.disallow(Result.KICK_BANNED, "Wrong keyword!"); } } else { Tregmine.LOGGER.warning(player.getName() + " keyword :: notset"); } if (player.getRank() == Rank.GUARDIAN) { player.setGuardianState(TregminePlayer.GuardianState.QUEUED); } } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { event.setJoinMessage(null); TregminePlayer player = plugin.getPlayer(event.getPlayer()); if (player == null) { event.getPlayer().kickPlayer("error loading profile!"); return; } Rank rank = player.getRank(); // Handle invisibility, if set List<TregminePlayer> players = plugin.getOnlinePlayers(); if (player.hasFlag(TregminePlayer.Flags.INVISIBLE)) { player.sendMessage(ChatColor.YELLOW + "You are now invisible!"); // Hide the new player from all existing players for (TregminePlayer current : players) { if (!current.getRank().canVanish()) { current.hidePlayer(player); } else { current.showPlayer(player); } } } else { for (TregminePlayer current : players) { current.showPlayer(player); } } // Hide currently invisible players from the player that just signed on for (TregminePlayer current : players) { if (current.hasFlag(TregminePlayer.Flags.INVISIBLE)) { player.hidePlayer(current); } else { player.showPlayer(current); } if (player.getRank().canVanish()) { player.showPlayer(current); } } // Set applicable game mode if (rank == Rank.BUILDER) { player.setGameMode(GameMode.CREATIVE); } else if (!rank.canUseCreative()) { player.setGameMode(GameMode.SURVIVAL); } // Try to find a mentor for new players if (rank == Rank.UNVERIFIED) { return; } // Check if the player is allowed to fly if (player.hasFlag(TregminePlayer.Flags.HARDWARNED)) { player.sendMessage("You are hardwarned and are not allowed to fly."); player.setAllowFlight(false); } else if (rank.canFly()) { if (player.hasFlag(TregminePlayer.Flags.FLY_ENABLED)) { player.sendMessage("Flying: Allowed and Enabled! Toggle flying with /fly"); player.setAllowFlight(true); } else { player.sendMessage("Flying: Allowed but Disabled! Toggle flying with /fly"); player.setAllowFlight(false); } } else { player.sendMessage("no-z-cheat"); player.sendMessage("You are NOT allowed to fly"); player.setAllowFlight(false); } try (IContext ctx = plugin.createContext()) { if (player.getPlayTime() > 10 * 3600 && rank == Rank.SETTLER) { player.setRank(Rank.RESIDENT); rank = Rank.RESIDENT; IPlayerDAO playerDAO = ctx.getPlayerDAO(); playerDAO.updatePlayer(player); playerDAO.updatePlayerInfo(player); player.sendMessage(ChatColor.DARK_GREEN + "Congratulations! " + "You are now a resident on Tregmine!"); } // Load inventory from DB - disabled until we know it's reliable /*PlayerInventory inv = (PlayerInventory) player.getInventory(); DBInventoryDAO invDAO = new DBInventoryDAO(conn); int invId = invDAO.getInventoryId(player.getId(), InventoryType.PLAYER); if (invId != -1) { Tregmine.LOGGER.info("Loaded inventory from DB"); inv.setContents(invDAO.getStacks(invId, inv.getSize())); } int armorId = invDAO.getInventoryId(player.getId(), InventoryType.PLAYER_ARMOR); if (armorId != -1) { Tregmine.LOGGER.info("Loaded armor from DB"); inv.setArmorContents(invDAO.getStacks(armorId, 4)); }*/ // Load motd IMotdDAO motdDAO = ctx.getMotdDAO(); String message = motdDAO.getMotd(); if (message != null) { String[] lines = message.split("\n"); for (String line : lines) { player.sendMessage(ChatColor.GOLD + "" + ChatColor.BOLD + line); } } } catch (DAOException e) { throw new RuntimeException(e); } // Show a score board if (player.isOnline()) { ScoreboardManager manager = Bukkit.getScoreboardManager(); Scoreboard board = manager.getNewScoreboard(); Objective objective = board.registerNewObjective("1", "2"); objective.setDisplaySlot(DisplaySlot.SIDEBAR); objective.setDisplayName("" + ChatColor.DARK_RED + "" + ChatColor.BOLD + "Welcome to Tregmine!"); try (IContext ctx = plugin.createContext()) { IWalletDAO walletDAO = ctx.getWalletDAO(); // Get a fake offline player String desc = ChatColor.BLACK + "Your Balance:"; Score score = objective.getScore(Bukkit.getOfflinePlayer(desc)); score.setScore((int)walletDAO.balance(player)); } catch (DAOException e) { throw new RuntimeException(e); } try { player.setScoreboard(board); ScoreboardClearTask.start(plugin, player); } catch (IllegalStateException e) { // ignore } } // Recalculate guardians activateGuardians(); if (rank == Rank.TOURIST) { // Try to find a mentor for tourists that rejoin MentorCommand.findMentor(plugin, player); } else if (player.canMentor()) { Queue<TregminePlayer> students = plugin.getStudentQueue(); if (students.size() > 0) { player.sendMessage(ChatColor.YELLOW + "Mentors are needed! " + "Type /mentor to offer your services!"); } } if (player.getKeyword() == null && player.getRank().mustUseKeyword()) { player.sendMessage(ChatColor.RED + "You have not set a keyword! DO SO NOW."); } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event) { TregminePlayer player = plugin.getPlayer(event.getPlayer()); if (player == null) { Tregmine.LOGGER.info(event.getPlayer().getName() + " was not found " + "in players map when quitting."); return; } event.setQuitMessage(null); if (!player.isOp()) { String message = null; if (player.getQuitMessage() != null) { message = player.getChatName() + " quit: " + ChatColor.YELLOW + player.getQuitMessage(); } else { Random rand = new Random(); int msgIndex = rand.nextInt(quitMessages.length); message = String.format(quitMessages[msgIndex], player.getChatName()); } plugin.getServer().broadcastMessage(message); } // Look if there are any students being mentored by the exiting player if (player.getStudent() != null) { TregminePlayer student = player.getStudent(); try (IContext ctx = plugin.createContext()) { IMentorLogDAO mentorLogDAO = ctx.getMentorLogDAO(); int mentorLogId = mentorLogDAO.getMentorLogId(student, player); mentorLogDAO.updateMentorLogEvent(mentorLogId, IMentorLogDAO.MentoringEvent.CANCELLED); } catch (DAOException e) { throw new RuntimeException(e); } student.setMentor(null); player.setStudent(null); student.sendMessage(ChatColor.RED + "Your mentor left. We'll try " + "to find a new one for you as quickly as possible."); MentorCommand.findMentor(plugin, student); } else if (player.getMentor() != null) { TregminePlayer mentor = player.getMentor(); try (IContext ctx = plugin.createContext()) { IMentorLogDAO mentorLogDAO = ctx.getMentorLogDAO(); int mentorLogId = mentorLogDAO.getMentorLogId(player, mentor); mentorLogDAO.updateMentorLogEvent(mentorLogId, IMentorLogDAO.MentoringEvent.CANCELLED); } catch (DAOException e) { throw new RuntimeException(e); } mentor.setStudent(null); player.setMentor(null); mentor.sendMessage(ChatColor.RED + "Your student left. :("); } plugin.removePlayer(player); Tregmine.LOGGER.info("Unloaded settings for " + player.getName() + "."); activateGuardians(); } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { TregminePlayer player = this.plugin.getPlayer(event.getPlayer()); if (player == null) { event.getPlayer().kickPlayer("error loading profile!"); } } @EventHandler public void onPlayerPickupItem(PlayerPickupItemEvent event) { TregminePlayer player = this.plugin.getPlayer(event.getPlayer()); if (player.getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } if (!player.getRank().arePickupsLogged()) { return; } if (!player.getRank().canPickup()) { event.setCancelled(true); return; } try (IContext ctx = plugin.createContext()) { Item item = event.getItem(); TregminePlayer droppedBy = droppedItems.get(item); if (droppedBy != null && droppedBy.getId() != player.getId()) { ItemStack stack = item.getItemStack(); ILogDAO logDAO = ctx.getLogDAO(); logDAO.insertGiveLog(droppedBy, player, stack); player.sendMessage(ChatColor.YELLOW + "You got " + stack.getAmount() + " " + stack.getType() + " from " + droppedBy.getName() + "."); if (droppedBy.isOnline()) { droppedBy.sendMessage(ChatColor.YELLOW + "You gave " + stack.getAmount() + " " + stack.getType() + " to " + player.getName() + "."); } } droppedItems.remove(item); } catch (DAOException e) { throw new RuntimeException(e); } } @EventHandler public void onPlayerDropItem(PlayerDropItemEvent event) { TregminePlayer player = this.plugin.getPlayer(event.getPlayer()); if (player.getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } if (!player.getRank().arePickupsLogged()) { return; } if (!player.getRank().canPickup()) { event.setCancelled(true); return; } Item item = event.getItemDrop(); droppedItems.put(item, player); } @EventHandler public void onPlayerKick(PlayerKickEvent event) { event.setLeaveMessage(null); } @EventHandler public void onNameTag(PlayerReceiveNameTagEvent event) { TregminePlayer player = plugin.getPlayer(event.getPlayer()); if (player == null) { return; } event.setTag(player.getChatName()); } private void activateGuardians() { // Identify all guardians and categorize them based on their current // state Player[] players = plugin.getServer().getOnlinePlayers(); Set<TregminePlayer> guardians = new HashSet<TregminePlayer>(); List<TregminePlayer> activeGuardians = new ArrayList<TregminePlayer>(); List<TregminePlayer> inactiveGuardians = new ArrayList<TregminePlayer>(); List<TregminePlayer> queuedGuardians = new ArrayList<TregminePlayer>(); for (Player srvPlayer : players) { TregminePlayer guardian = plugin.getPlayer(srvPlayer.getName()); if (guardian == null || guardian.getRank() != Rank.GUARDIAN) { continue; } TregminePlayer.GuardianState state = guardian.getGuardianState(); if (state == null) { state = TregminePlayer.GuardianState.QUEUED; } switch (state) { case ACTIVE: activeGuardians.add(guardian); break; case INACTIVE: inactiveGuardians.add(guardian); break; case QUEUED: queuedGuardians.add(guardian); break; } guardian.setGuardianState(TregminePlayer.GuardianState.QUEUED); guardians.add(guardian); } Collections.sort(activeGuardians, new RankComparator()); Collections.sort(inactiveGuardians, new RankComparator(true)); Collections.sort(queuedGuardians, new RankComparator()); int idealCount = (int) Math.ceil(Math.sqrt(players.length) / 2); // There are not enough guardians active, we need to activate a few more if (activeGuardians.size() <= idealCount) { // Make a pool of every "willing" guardian currently online List<TregminePlayer> activationList = new ArrayList<TregminePlayer>(); activationList.addAll(activeGuardians); activationList.addAll(queuedGuardians); // If the pool isn't large enough to satisfy demand, we add the // guardians // that have made themselves inactive as well. if (activationList.size() < idealCount) { int diff = idealCount - activationList.size(); // If there aren't enough of these to satisfy demand, we add all // of them if (diff >= inactiveGuardians.size()) { activationList.addAll(inactiveGuardians); } // Otherwise we just add the lowest ranked of the inactive else { activationList.addAll(inactiveGuardians.subList(0, diff)); } } // If there are more than necessarry guardians online, only activate // the most highly ranked. Set<TregminePlayer> activationSet; if (activationList.size() > idealCount) { Collections.sort(activationList, new RankComparator()); activationSet = new HashSet<TregminePlayer>(activationList.subList(0, idealCount)); } else { activationSet = new HashSet<TregminePlayer>(activationList); } // Perform activation StringBuffer globalMessage = new StringBuffer(); String delim = ""; for (TregminePlayer guardian : activationSet) { guardian.setGuardianState(TregminePlayer.GuardianState.ACTIVE); globalMessage.append(delim); globalMessage.append(guardian.getName()); delim = ", "; } Set<TregminePlayer> oldActiveGuardians = new HashSet<TregminePlayer>(activeGuardians); if (!activationSet.containsAll(oldActiveGuardians) || activationSet.size() != oldActiveGuardians.size()) { plugin.getServer() .broadcastMessage( ChatColor.BLUE + "Active guardians are: " + globalMessage + ". Please contact any of them if you need help."); // Notify previously active guardian of their state change for (TregminePlayer guardian : activeGuardians) { if (!activationSet.contains(guardian)) { guardian.sendMessage(ChatColor.BLUE + "You are no longer on active duty, and should not respond to help requests, unless asked by an admin or active guardian."); } } // Notify previously inactive guardians of their state change for (TregminePlayer guardian : inactiveGuardians) { if (activationSet.contains(guardian)) { guardian.sendMessage(ChatColor.BLUE + "You have been restored to active duty and should respond to help requests."); } } // Notify previously queued guardians of their state change for (TregminePlayer guardian : queuedGuardians) { if (activationSet.contains(guardian)) { guardian.sendMessage(ChatColor.BLUE + "You are now on active duty and should respond to help requests."); } } } } } }
package com.couchbase.lite; import com.couchbase.lite.util.Log; import com.couchbase.lite.util.TextUtils; import junit.framework.Assert; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class ApiTest extends LiteTestCase { private int changeCount = 0; //SERVER & DOCUMENTS public void testAPIManager() throws Exception { Manager manager = this.manager; Assert.assertTrue(manager != null); for(String dbName : manager.getAllDatabaseNames()){ Database db = manager.getDatabase(dbName); Log.i(TAG, "Database '" + dbName + "':" + db.getDocumentCount() + " documents"); } ManagerOptions options= new ManagerOptions(); options.setReadOnly(true); Manager roManager=new Manager(new LiteTestContext(), options); Assert.assertTrue(roManager!=null); Database db =roManager.getDatabase("foo"); Assert.assertNull(db); List<String> dbNames=manager.getAllDatabaseNames(); Assert.assertFalse(dbNames.contains("foo")); Assert.assertTrue(dbNames.contains(DEFAULT_TEST_DB)); } public void testCreateDocument() throws CouchbaseLiteException { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateDocument"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); String docID=doc.getId(); assertTrue("Invalid doc ID: " + docID, docID.length() > 10); String currentRevisionID=doc.getCurrentRevisionId(); assertTrue("Invalid doc revision: " + docID, currentRevisionID.length() > 10); assertEquals(doc.getUserProperties(), properties); assertEquals(db.getDocument(docID), doc); db.clearDocumentCache();// so we can load fresh copies Document doc2 = db.getExistingDocument(docID); assertEquals(doc2.getId(), docID); assertEquals(doc2.getCurrentRevisionId(), currentRevisionID); assertNull(db.getExistingDocument("b0gus")); } public void testDeleteDatabase() throws Exception { Database deleteme = manager.getDatabase("deleteme"); assertTrue(deleteme.exists()); String dbPath =deleteme.getPath(); assertTrue(new File(dbPath).exists()); assertTrue(new File(dbPath.substring(0, dbPath.lastIndexOf('.'))).exists()); deleteme.delete(); assertFalse(deleteme.exists()); assertFalse(new File(dbPath).exists()); assertFalse(new File(dbPath + "-journal").exists()); assertFalse(new File(dbPath.substring(0, dbPath.lastIndexOf('.'))).exists()); deleteme.delete(); // delete again, even though already deleted Database deletemeFetched = manager.getExistingDatabase("deleteme"); assertNull(deletemeFetched); } public void testDatabaseCompaction() throws Exception{ Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testDatabaseCompaction"); properties.put("tag", 1337); Document doc=createDocumentWithProperties(database, properties); SavedRevision rev1 = doc.getCurrentRevision(); Map<String,Object> properties2 = new HashMap<String,Object>(properties); properties2.put("tag", 4567); SavedRevision rev2 = rev1.createRevision(properties2); database.compact(); Document fetchedDoc = database.getDocument(doc.getId()); List<SavedRevision> revisions = fetchedDoc.getRevisionHistory(); for (SavedRevision revision : revisions) { if (revision.getId().equals(rev1)) { assertFalse(revision.arePropertiesAvailable()); } if (revision.getId().equals(rev2)) { assertTrue(revision.arePropertiesAvailable()); } } } public void testDocumentCache() throws Exception{ Database db = startDatabase(); Document doc = db.createDocument(); UnsavedRevision rev1 = doc.createRevision(); Map<String, Object> rev1Properties = new HashMap<String, Object>(); rev1Properties.put("foo", "bar"); rev1.setUserProperties(rev1Properties); SavedRevision savedRev1 = rev1.save(); String documentId = savedRev1.getDocument().getId(); // getting the document puts it in cache Document docRev1 = db.getExistingDocument(documentId); UnsavedRevision rev2 = docRev1.createRevision(); Map<String, Object> rev2Properties = rev2.getProperties(); rev2Properties.put("foo", "baz"); rev2.setUserProperties(rev2Properties); rev2.save(); Document docRev2 = db.getExistingDocument(documentId); assertEquals("baz", docRev2.getProperty("foo")); } public void testCreateRevisions() throws Exception{ Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateRevisions"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); assertFalse(doc.isDeleted()); SavedRevision rev1 = doc.getCurrentRevision(); assertTrue(rev1.getId().startsWith("1-")); assertEquals(1, rev1.getSequence()); assertEquals(0, rev1.getAttachments().size()); // Test -createRevisionWithProperties: Map<String,Object> properties2 = new HashMap<String,Object>(properties); properties2.put("tag", 4567); SavedRevision rev2 = rev1.createRevision(properties2); assertNotNull("Put failed", rev2); assertTrue("Document revision ID is still " + doc.getCurrentRevisionId(), doc.getCurrentRevisionId().startsWith("2-")); assertEquals(rev2.getId(), doc.getCurrentRevisionId()); assertNotNull(rev2.arePropertiesAvailable()); assertEquals(rev2.getUserProperties(), properties2); assertEquals(rev2.getDocument(), doc); assertEquals(rev2.getProperty("_id"), doc.getId()); assertEquals(rev2.getProperty("_rev"), rev2.getId()); // Test -createRevision: UnsavedRevision newRev = rev2.createRevision(); assertNull(newRev.getId()); assertEquals(newRev.getParent(), rev2); assertEquals(newRev.getParentId(), rev2.getId()); assertEquals(doc.getCurrentRevision(), rev2); assertFalse(doc.isDeleted()); List<SavedRevision> listRevs=new ArrayList<SavedRevision>(); listRevs.add(rev1); listRevs.add(rev2); assertEquals(newRev.getRevisionHistory(), listRevs); assertEquals(newRev.getProperties(), rev2.getProperties()); assertEquals(newRev.getUserProperties(), rev2.getUserProperties()); Map<String,Object> userProperties=new HashMap<String, Object>(); userProperties.put("because", "NoSQL"); newRev.setUserProperties(userProperties); assertEquals(newRev.getUserProperties(), userProperties); Map<String,Object> expectProperties=new HashMap<String, Object>(); expectProperties.put("because", "NoSQL"); expectProperties.put("_id", doc.getId()); expectProperties.put("_rev", rev2.getId()); assertEquals(newRev.getProperties(),expectProperties); SavedRevision rev3 = newRev.save(); assertNotNull(rev3); assertEquals(rev3.getUserProperties(), newRev.getUserProperties()); } public void testCreateNewRevisions() throws Exception{ Map<String,Object> properties = new HashMap<String,Object>(); properties.put("testName", "testCreateRevisions"); properties.put("tag", 1337); Database db = startDatabase(); Document doc=db.createDocument(); UnsavedRevision newRev =doc.createRevision(); Document newRevDocument = newRev.getDocument(); assertEquals(doc, newRevDocument); assertEquals(db, newRev.getDatabase()); assertNull(newRev.getParentId()); assertNull(newRev.getParent()); Map<String,Object> expectProperties=new HashMap<String, Object>(); expectProperties.put("_id", doc.getId()); assertEquals(expectProperties, newRev.getProperties()); assertTrue(!newRev.isDeletion()); assertEquals(newRev.getSequence(), 0); //ios support another approach to set properties:: //newRev.([@"testName"] = @"testCreateRevisions"; //newRev[@"tag"] = @1337; newRev.setUserProperties(properties); assertEquals(newRev.getUserProperties(), properties); SavedRevision rev1 = newRev.save(); assertNotNull("Save 1 failed", rev1); assertEquals(doc.getCurrentRevision(), rev1); assertNotNull(rev1.getId().startsWith("1-")); assertEquals(1, rev1.getSequence()); assertNull(rev1.getParentId()); assertNull(rev1.getParent()); newRev = rev1.createRevision(); newRevDocument = newRev.getDocument(); assertEquals(doc, newRevDocument); assertEquals(db, newRev.getDatabase()); assertEquals(rev1.getId(), newRev.getParentId()); assertEquals(rev1, newRev.getParent()); assertEquals(rev1.getProperties(), newRev.getProperties()); assertEquals(rev1.getUserProperties(), newRev.getUserProperties()); assertNotNull(!newRev.isDeletion()); // we can't add/modify one property as on ios. need to add separate method? // newRev[@"tag"] = @4567; properties.put("tag", 4567); newRev.setUserProperties(properties); SavedRevision rev2 = newRev.save(); assertNotNull( "Save 2 failed", rev2); assertEquals(doc.getCurrentRevision(), rev2); assertNotNull(rev2.getId().startsWith("2-")); assertEquals(2, rev2.getSequence()); assertEquals(rev1.getId(), rev2.getParentId()); assertEquals(rev1, rev2.getParent()); assertNotNull("Document revision ID is still " + doc.getCurrentRevisionId(), doc.getCurrentRevisionId().startsWith("2-")); // Add a deletion/tombstone revision: newRev = doc.createRevision(); assertEquals(rev2.getId(), newRev.getParentId()); assertEquals(rev2, newRev.getParent()); newRev.setIsDeletion(true); SavedRevision rev3 = newRev.save(); assertNotNull("Save 3 failed", rev3); assertNotNull("Unexpected revID " + rev3.getId(), rev3.getId().startsWith("3-")); assertEquals(3, rev3.getSequence()); assertTrue(rev3.isDeletion()); assertTrue(doc.isDeleted()); assertNull(doc.getCurrentRevision()); List<SavedRevision> leafRevs = new ArrayList<SavedRevision>(); leafRevs.add(rev3); assertEquals(doc.getLeafRevisions(), leafRevs); db.getDocumentCount(); Document doc2 = db.getDocument(doc.getId()); assertEquals(doc, doc2); assertNull(db.getExistingDocument(doc.getId())); } //API_SaveMultipleDocuments on IOS //API_SaveMultipleUnsavedDocuments on IOS //API_DeleteMultipleDocuments commented on IOS public void testDeleteDocument() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testDeleteDocument"); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); assertTrue(!doc.isDeleted()); assertTrue(!doc.getCurrentRevision().isDeletion()); assertTrue(doc.delete()); assertTrue(doc.isDeleted()); assertNull(doc.getCurrentRevision()); } public void testPurgeDocument() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testPurgeDocument"); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); assertNotNull(doc); assertNotNull(doc.purge()); Document redoc = db.getCachedDocument(doc.getId()); assertNull(redoc); } public void testDeleteDocumentViaTombstoneRevision() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "testDeleteDocument"); Database db = startDatabase(); Document doc=createDocumentWithProperties(db, properties); assertTrue(!doc.isDeleted()); assertTrue(!doc.getCurrentRevision().isDeletion()); Map<String, Object> props = new HashMap<String, Object>(doc.getProperties()); props.put("_deleted", true); doc.putProperties(props); assertTrue(doc.isDeleted()); assertNotNull(doc.getCurrentRevision().isDeletion()); } public void testAllDocuments() throws Exception{ Database db = startDatabase(); int kNDocs = 5; createDocuments(db, kNDocs); // clear the cache so all documents/revisions will be re-fetched: db.clearDocumentCache(); Log.i(TAG, " Query query = db.createAllDocumentsQuery(); //query.prefetch = YES; Log.i(TAG, "Getting all documents: " + query); QueryEnumerator rows = query.run(); assertEquals(rows.getCount(), kNDocs); int n = 0; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); Log.i(TAG, " --> " + row); Document doc = row.getDocument(); assertNotNull("Couldn't get doc from query", doc ); assertNotNull("QueryRow should have preloaded revision contents", doc.getCurrentRevision().arePropertiesAvailable()); Log.i(TAG, " Properties =" + doc.getProperties()); assertNotNull("Couldn't get doc properties", doc.getProperties()); assertEquals(doc.getProperty("testName"), "testDatabase"); n++; } assertEquals(n, kNDocs); } public void testLocalDocs() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("foo", "bar"); Database db = startDatabase(); Map<String,Object> props = db.getExistingLocalDocument("dock"); assertNull(props); assertNotNull("Couldn't put new local doc", db.putLocalDocument("dock", properties)); props = db.getExistingLocalDocument("dock"); assertEquals(props.get("foo"), "bar"); Map<String,Object> newProperties = new HashMap<String, Object>(); newProperties.put("FOOO", "BARRR"); assertNotNull("Couldn't update local doc", db.putLocalDocument("dock", newProperties)); props = db.getExistingLocalDocument("dock"); assertNull(props.get("foo")); assertEquals(props.get("FOOO"), "BARRR"); assertNotNull("Couldn't delete local doc", db.deleteLocalDocument("dock")); props = db.getExistingLocalDocument("dock"); assertNull(props); assertNotNull("Second delete should have failed", !db.deleteLocalDocument("dock")); //TODO issue: deleteLocalDocument should return error.code( see ios) } // HISTORY public void testHistory() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); properties.put("testName", "test06_History"); properties.put("tag", 1); Database db = startDatabase(); Document doc = createDocumentWithProperties(db, properties); String rev1ID = doc.getCurrentRevisionId(); Log.i(TAG, "1st revision: "+ rev1ID); assertNotNull("1st revision looks wrong: " + rev1ID, rev1ID.startsWith("1-")); assertEquals(doc.getUserProperties(), properties); properties = new HashMap<String, Object>(); properties.putAll(doc.getProperties()); properties.put("tag", 2); assertNotNull(!properties.equals(doc.getProperties())); assertNotNull(doc.putProperties(properties)); String rev2ID = doc.getCurrentRevisionId(); Log.i(TAG, "rev2ID" + rev2ID); assertNotNull("2nd revision looks wrong:" + rev2ID, rev2ID.startsWith("2-")); List<SavedRevision> revisions = doc.getRevisionHistory(); Log.i(TAG, "Revisions = " + revisions); assertEquals(revisions.size(), 2); SavedRevision rev1 = revisions.get(0); assertEquals(rev1.getId(), rev1ID); Map<String,Object> gotProperties = rev1.getProperties(); assertEquals(1, gotProperties.get("tag")); SavedRevision rev2 = revisions.get(1); assertEquals(rev2.getId(), rev2ID); assertEquals(rev2, doc.getCurrentRevision()); gotProperties = rev2.getProperties(); assertEquals(2, gotProperties.get("tag")); List<SavedRevision> tmp = new ArrayList<SavedRevision>(); tmp.add(rev2); assertEquals(doc.getConflictingRevisions(), tmp); assertEquals(doc.getLeafRevisions(), tmp); } public void testHistoryAfterDocDeletion() throws Exception{ Map<String,Object> properties = new HashMap<String, Object>(); String docId = "testHistoryAfterDocDeletion"; properties.put("tag", 1); Database db = startDatabase(); Document doc = db.getDocument(docId); assertEquals(docId, doc.getId()); doc.putProperties(properties); String revID = doc.getCurrentRevisionId(); for(int i=2; i<6; i++){ properties.put("tag", i); properties.put("_rev", revID ); doc.putProperties(properties); revID = doc.getCurrentRevisionId(); Log.i(TAG, i + " revision: " + revID); assertTrue("revision is not correct:" + revID + ", should be with prefix " + i +"-", revID.startsWith(String.valueOf(i) +"-")); assertEquals("Doc Id is not correct ", docId, doc.getId()); } // now delete the doc and clear it from the cache so we // make sure we are reading a fresh copy doc.delete(); database.clearDocumentCache(); // get doc from db with same ID as before, and the current rev should be null since the // last update was a deletion Document docPostDelete = db.getDocument(docId); assertNull(docPostDelete.getCurrentRevision()); // save a new revision properties = new HashMap<String, Object>(); properties.put("tag", 6); UnsavedRevision newRevision = docPostDelete.createRevision(); newRevision.setProperties(properties); SavedRevision newSavedRevision = newRevision.save(); // make sure the current revision of doc matches the rev we just saved assertEquals(newSavedRevision, docPostDelete.getCurrentRevision()); // make sure the rev id is 7- assertTrue(docPostDelete.getCurrentRevisionId().startsWith("7-")); } public void testConflict() throws Exception{ Map<String,Object> prop = new HashMap<String, Object>(); prop.put("foo", "bar"); Database db = startDatabase(); Document doc = createDocumentWithProperties(db, prop); SavedRevision rev1 = doc.getCurrentRevision(); Map<String,Object> properties = new HashMap<String, Object>(); properties.putAll(doc.getProperties()); properties.put("tag", 2); SavedRevision rev2a = doc.putProperties(properties); properties = new HashMap<String, Object>(); properties.putAll(rev1.getProperties()); properties.put("tag", 3); UnsavedRevision newRev = rev1.createRevision(); newRev.setProperties(properties); boolean allowConflict = true; SavedRevision rev2b = newRev.save(allowConflict); assertNotNull("Failed to create a a conflict", rev2b); List<SavedRevision> confRevs = new ArrayList<SavedRevision>(); confRevs.add(rev2b); confRevs.add(rev2a); assertEquals(doc.getConflictingRevisions(), confRevs); assertEquals(doc.getLeafRevisions(), confRevs); SavedRevision defaultRev, otherRev; if (rev2a.getId().compareTo(rev2b.getId()) > 0) { defaultRev = rev2a; otherRev = rev2b; } else { defaultRev = rev2b; otherRev = rev2a; } assertEquals(doc.getCurrentRevision(), defaultRev); Query query = db.createAllDocumentsQuery(); query.setAllDocsMode(Query.AllDocsMode.SHOW_CONFLICTS); QueryEnumerator rows = query.run(); assertEquals(rows.getCount(), 1); QueryRow row = rows.getRow(0); List<SavedRevision> revs = row.getConflictingRevisions(); assertEquals(revs.size(), 2); assertEquals(revs.get(0), defaultRev); assertEquals(revs.get(1), otherRev); } //ATTACHMENTS public void testAttachments() throws Exception, IOException { String attachmentName = "index.html"; String content = "This is a test attachment!"; Document doc = createDocWithAttachment(database, attachmentName, content); UnsavedRevision newRev = doc.getCurrentRevision().createRevision(); newRev.removeAttachment(attachmentName); SavedRevision rev4 = newRev.save(); assertNotNull(rev4); assertEquals(0, rev4.getAttachmentNames().size()); } public void testUpdateDocWithAttachments() throws Exception, IOException { String attachmentName = "index.html"; String content = "This is a test attachment!"; Document doc = createDocWithAttachment(database, attachmentName, content); SavedRevision latestRevision = doc.getCurrentRevision(); Map<String,Object> propertiesUpdated = new HashMap<String, Object>(); propertiesUpdated.put("propertiesUpdated", "testUpdateDocWithAttachments"); UnsavedRevision newUnsavedRevision = latestRevision.createRevision(); newUnsavedRevision.setUserProperties(propertiesUpdated); SavedRevision newSavedRevision = newUnsavedRevision.save(); assertNotNull(newSavedRevision); assertEquals(1, newSavedRevision.getAttachmentNames().size()); Attachment fetched = doc.getCurrentRevision().getAttachment(attachmentName); InputStream is = fetched.getContent(); byte[] attachmentBytes = TextUtils.read(is); assertEquals(content, new String(attachmentBytes)); assertNotNull(fetched); } //CHANGE TRACKING public void testChangeTracking() throws Exception{ final CountDownLatch doneSignal = new CountDownLatch(1); Database db = startDatabase(); db.addChangeListener(new Database.ChangeListener() { @Override public void changed(Database.ChangeEvent event) { doneSignal.countDown(); } }); createDocumentsAsync(db, 5); // We expect that the changes reported by the server won't be notified, because those revisions // are already cached in memory. boolean success = doneSignal.await(300, TimeUnit.SECONDS); assertTrue(success); assertEquals(5, db.getLastSequenceNumber()); } //VIEWS public void testCreateView() throws Exception{ Database db = startDatabase(); View view = db.getView("vu"); assertNotNull(view); assertEquals(db, view.getDatabase()); assertEquals("vu", view.getName()); assertNull(view.getMap()); assertNull(view.getReduce()); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); assertNotNull(view.getMap() != null); int kNDocs = 50; createDocuments(db, kNDocs); Query query = view.createQuery(); assertEquals(db, query.getDatabase()); query.setStartKey(23); query.setEndKey(33); QueryEnumerator rows = query.run(); assertNotNull(rows); assertEquals(11, rows.getCount()); int expectedKey = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(expectedKey, row.getKey()); assertEquals(expectedKey+1, row.getSequenceNumber()); ++expectedKey; } } //API_RunSlowView commented on IOS public void testValidation() throws Exception{ Database db = startDatabase(); db.setValidation("uncool", new Validator() { @Override public void validate(Revision newRevision, ValidationContext context) { { if (newRevision.getProperty("groovy") ==null) { context.reject("uncool"); } } } }); Map<String,Object> properties = new HashMap<String,Object>(); properties.put("groovy", "right on"); properties.put( "foo", "bar"); Document doc = db.createDocument(); assertNotNull(doc.putProperties(properties)); properties = new HashMap<String,Object>(); properties.put( "foo", "bar"); doc = db.createDocument(); try{ assertNull(doc.putProperties(properties)); } catch (CouchbaseLiteException e){ //TODO assertEquals(e.getCBLStatus().getCode(), Status.FORBIDDEN); // assertEquals(e.getLocalizedMessage(), "forbidden: uncool"); //TODO: Not hooked up yet } } public void testViewWithLinkedDocs() throws Exception{ Database db = startDatabase(); int kNDocs = 50; Document[] docs = new Document[50]; String lastDocID = ""; for (int i=0; i<kNDocs; i++) { Map<String,Object> properties = new HashMap<String,Object>(); properties.put("sequence", i); properties.put("prev", lastDocID); Document doc = createDocumentWithProperties(db, properties); docs[i]=doc; lastDocID = doc.getId(); } Query query = db.slowQuery(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), new Object[]{"_id", document.get("prev")}); } }); query.setStartKey(23); query.setEndKey(33); query.setPrefetch(true); QueryEnumerator rows = query.run(); assertNotNull(rows); assertEquals(rows.getCount(), 11); int rowNumber = 23; for (Iterator<QueryRow> it = rows; it.hasNext();) { QueryRow row = it.next(); assertEquals(row.getKey(), rowNumber); Document prevDoc = docs[rowNumber]; assertEquals(row.getDocumentId(), prevDoc.getId()); assertEquals(row.getDocument(), prevDoc); ++rowNumber; } } public void testLiveQueryRun() throws Exception { runLiveQuery("run"); } public void testLiveQueryStart() throws Exception { runLiveQuery("start"); } public void testLiveQueryStartWaitForRows() throws Exception { runLiveQuery("startWaitForRows"); } public void testLiveQueryStop() throws Exception { final int kNDocs = 100; final CountDownLatch doneSignal = new CountDownLatch(1); final Database db = startDatabase(); // run a live query View view = db.getView("vu"); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); final LiveQuery query = view.createQuery().toLiveQuery(); final AtomicInteger atomicInteger = new AtomicInteger(0); // install a change listener which decrements countdown latch when it sees a new // key from the list of expected keys final LiveQuery.ChangeListener changeListener = new LiveQuery.ChangeListener() { @Override public void changed(LiveQuery.ChangeEvent event) { Log.d(TAG, "changed called, atomicInteger.incrementAndGet"); atomicInteger.incrementAndGet(); assertNull(event.getError()); if (event.getRows().getCount() == kNDocs) { doneSignal.countDown(); } } }; query.addChangeListener(changeListener); // create the docs that will cause the above change listener to decrement countdown latch Log.d(Database.TAG, "testLiveQueryStop: createDocumentsAsync()"); createDocumentsAsync(db, kNDocs); Log.d(Database.TAG, "testLiveQueryStop: calling query.start()"); query.start(); // wait until the livequery is called back with kNDocs docs Log.d(Database.TAG, "testLiveQueryStop: waiting for doneSignal"); boolean success = doneSignal.await(45, TimeUnit.SECONDS); assertTrue(success); Log.d(Database.TAG, "testLiveQueryStop: waiting for query.stop()"); query.stop(); // after stopping the query, we should not get any more livequery callbacks, even // if we add more docs to the database and pause (to give time for potential callbacks) int numTimesCallbackCalled = atomicInteger.get(); Log.d(Database.TAG, "testLiveQueryStop: numTimesCallbackCalled is: " + numTimesCallbackCalled + ". Now adding docs"); for (int i=0; i<10; i++) { createDocuments(db, 1); Log.d(Database.TAG, "testLiveQueryStop: add a document. atomicInteger.get(): " + atomicInteger.get()); assertEquals(numTimesCallbackCalled, atomicInteger.get()); Thread.sleep(200); } assertEquals(numTimesCallbackCalled, atomicInteger.get()); } public void testLiveQueryRestart() throws Exception { // kick something off that will s } public void runLiveQuery(String methodNameToCall) throws Exception { final Database db = startDatabase(); final CountDownLatch doneSignal = new CountDownLatch(11); // 11 corresponds to startKey=23; endKey=33 // run a live query View view = db.getView("vu"); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); final LiveQuery query = view.createQuery().toLiveQuery(); query.setStartKey(23); query.setEndKey(33); Log.i(TAG, "Created " + query); // these are the keys that we expect to see in the livequery change listener callback final Set<Integer> expectedKeys = new HashSet<Integer>(); for (int i=23; i<34; i++) { expectedKeys.add(i); } // install a change listener which decrements countdown latch when it sees a new // key from the list of expected keys final LiveQuery.ChangeListener changeListener = new LiveQuery.ChangeListener() { @Override public void changed(LiveQuery.ChangeEvent event) { QueryEnumerator rows = event.getRows(); for (Iterator<QueryRow> it = rows; it.hasNext(); ) { QueryRow row = it.next(); if (expectedKeys.contains(row.getKey())) { expectedKeys.remove(row.getKey()); doneSignal.countDown(); } } } }; query.addChangeListener(changeListener); // create the docs that will cause the above change listener to decrement countdown latch int kNDocs = 50; createDocumentsAsync(db, kNDocs); if (methodNameToCall.equals("start")) { // start the livequery running asynchronously query.start(); } else if (methodNameToCall.equals("startWaitForRows")) { query.start(); query.waitForRows(); } else { assertNull(query.getRows()); query.run(); // this will block until the query completes assertNotNull(query.getRows()); } // wait for the doneSignal to be finished boolean success = doneSignal.await(300, TimeUnit.SECONDS); assertTrue("Done signal timed out, live query never ran", success); // stop the livequery since we are done with it query.removeChangeListener(changeListener); query.stop(); } public void testAsyncViewQuery() throws Exception { final CountDownLatch doneSignal = new CountDownLatch(1); final Database db = startDatabase(); View view = db.getView("vu"); view.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { emitter.emit(document.get("sequence"), null); } }, "1"); int kNDocs = 50; createDocuments(db, kNDocs); Query query = view.createQuery(); query.setStartKey(23); query.setEndKey(33); query.runAsync(new Query.QueryCompleteListener() { @Override public void completed(QueryEnumerator rows, Throwable error) { Log.i(TAG, "Async query finished!"); assertNotNull(rows); assertNull(error); assertEquals(rows.getCount(), 11); int expectedKey = 23; for (Iterator<QueryRow> it = rows; it.hasNext(); ) { QueryRow row = it.next(); assertEquals(row.getDocument().getDatabase(), db); assertEquals(row.getKey(), expectedKey); ++expectedKey; } doneSignal.countDown(); } }); Log.i(TAG, "Waiting for async query to finish..."); boolean success = doneSignal.await(300, TimeUnit.SECONDS); assertTrue("Done signal timed out, async query never ran", success); } /** * Make sure that a database's map/reduce functions are shared with the shadow database instance * running in the background server. */ public void testSharedMapBlocks() throws Exception { Manager mgr = new Manager(new LiteTestContext("API_SharedMapBlocks"), Manager.DEFAULT_OPTIONS); Database db = mgr.getDatabase("db"); db.open(); db.setFilter("phil", new ReplicationFilter() { @Override public boolean filter(SavedRevision revision, Map<String, Object> params) { return true; } }); db.setValidation("val", new Validator() { @Override public void validate(Revision newRevision, ValidationContext context) { } }); View view = db.getView("view"); boolean ok = view.setMapReduce(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { } }, new Reducer() { @Override public Object reduce(List<Object> keys, List<Object> values, boolean rereduce) { return null; } }, "1" ); assertNotNull("Couldn't set map/reduce", ok); final Mapper map = view.getMap(); final Reducer reduce = view.getReduce(); final ReplicationFilter filter = db.getFilter("phil"); final Validator validation = db.getValidation("val"); Future result = mgr.runAsync("db", new AsyncTask() { @Override public void run(Database database) { assertNotNull(database); View serverView = database.getExistingView("view"); assertNotNull(serverView); assertEquals(database.getFilter("phil"), filter); assertEquals(database.getValidation("val"), validation); assertEquals(serverView.getMap(), map); assertEquals(serverView.getReduce(), reduce); } }); result.get(); // blocks until async task has run db.close(); mgr.close(); } public void testChangeUUID() throws Exception{ Manager mgr = new Manager(new LiteTestContext("ChangeUUID"), Manager.DEFAULT_OPTIONS); Database db = mgr.getDatabase("db"); db.open(); String pub = db.publicUUID(); String priv = db.privateUUID(); assertTrue(pub.length() > 10); assertTrue(priv.length() > 10); assertTrue("replaceUUIDs failed", db.replaceUUIDs()); assertFalse(pub.equals(db.publicUUID())); assertFalse(priv.equals(db.privateUUID())); mgr.close(); } public void testMultiDocumentUpdate() throws Exception { final int numberOfDocuments = 10; final int numberOfUpdates = 10; final Document[] docs = new Document[numberOfDocuments]; for (int j = 0; j < numberOfDocuments; j++) { Map<String,Object> prop = new HashMap<String, Object>(); prop.put("foo", "bar"); prop.put("toogle", true); Document document = createDocumentWithProperties(database, prop); docs[j] = document; } final AtomicInteger numDocsUpdated = new AtomicInteger(0); final AtomicInteger numExceptions = new AtomicInteger(0); for (int j = 0; j < numberOfDocuments; j++) { Document doc = docs[j]; for(int k=0; k < numberOfUpdates; k++) { Map<String, Object> contents = new HashMap(doc.getProperties()); Boolean wasChecked = (Boolean) contents.get("toogle"); //toggle value of check property contents.put("toogle",!wasChecked); try { doc.putProperties(contents); numDocsUpdated.incrementAndGet(); } catch (CouchbaseLiteException cblex) { Log.e(TAG, "Document update failed", cblex); numExceptions.incrementAndGet(); } } } assertEquals(numberOfDocuments * numberOfUpdates, numDocsUpdated.get()); assertEquals(0, numExceptions.get()); } public void failingTestMultiDocumentUpdateInTransaction() throws Exception { final int numberOfDocuments = 10; final int numberOfUpdates = 10; final Document[] docs = new Document[numberOfDocuments]; database.runInTransaction(new TransactionalTask() { @Override public boolean run() { for (int j = 0; j < numberOfDocuments; j++) { Map<String,Object> prop = new HashMap<String, Object>(); prop.put("foo", "bar"); prop.put("toogle", true); Document document = createDocumentWithProperties(database, prop); docs[j] = document; } return true; } }); final AtomicInteger numDocsUpdated = new AtomicInteger(0); final AtomicInteger numExceptions = new AtomicInteger(0); database.runInTransaction(new TransactionalTask() { @Override public boolean run() { for (int j = 0; j < numberOfDocuments; j++) { Document doc = docs[j]; SavedRevision lastSavedRevision = null; for(int k=0; k < numberOfUpdates; k++) { if (lastSavedRevision != null) { assertEquals(lastSavedRevision.getId(), doc.getCurrentRevisionId()); } Map<String, Object> contents = new HashMap(doc.getProperties()); Document docLatest = database.getDocument(doc.getId()); Boolean wasChecked = (Boolean) contents.get("toogle"); //toggle value of check property contents.put("toogle",!wasChecked); try { lastSavedRevision = doc.putProperties(contents); numDocsUpdated.incrementAndGet(); } catch (CouchbaseLiteException cblex) { Log.e(TAG, "Document update failed", cblex); numExceptions.incrementAndGet(); } } } return true; } }); assertEquals(numberOfDocuments * numberOfUpdates, numDocsUpdated.get()); assertEquals(0, numExceptions.get()); } }
package cornell.eickleapp; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.LayerDrawable; import android.os.Bundle; import android.os.Vibrator; import android.preference.PreferenceManager; import android.text.InputType; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; public class DrinkCounter extends Activity { private int drink_count = 0; private DatabaseHandler db; private double bac; private Vibrator click_vibe; private int face_color; private int face_icon; private boolean clicked; private Date start_date; private final Double CALORIES_PER_DRINK = 120.0; private final Double CALORIES_HOT_DOG = 250.0; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.drink_tracker); click_vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE); clicked=false; db = new DatabaseHandler(this); start(); updateFace(); SharedPreferences getPrefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); Boolean checkSurveyed = getPrefs.getBoolean("hints", true); if (checkSurveyed) { Intent openTutorial = new Intent(this, DrinkCounterTutorial.class); startActivity(openTutorial); } } @Override protected void onResume() { super.onResume(); start(); recalculateBac(); updateFace(); clicked = false; } @Override protected void onStop() { db.close(); super.onStop(); finish(); } private void start(){ Date date = DatabaseStore.getDelayedDate(); ArrayList<DatabaseStore> drink_count_vals = (ArrayList<DatabaseStore>) db .getVarValuesDelay("drink_count", date); if(drink_count_vals != null){ drink_count_vals = DatabaseStore.sortByTime(drink_count_vals); start_date = drink_count_vals.get(0).date; drink_count = Integer.parseInt(drink_count_vals.get( drink_count_vals.size()-1).value); }else{ start_date = date; bac = calculateBac(start_date, date, drink_count); } } public void removeLast() { drink_count Date date = new Date(); ArrayList<DatabaseStore> drink_count_vals = (ArrayList<DatabaseStore>) db .getVarValuesDelay("drink_count", date); drink_count_vals = DatabaseStore.sortByTime(drink_count_vals); ArrayList<String> variables = new ArrayList<String>(); variables.add(drink_count_vals.get( drink_count_vals.size() - 1).variable); variables.add("bac"); variables.add("bac_color"); variables.add("hotdog"); ArrayList<DatabaseStore> hd_val = ((ArrayList<DatabaseStore>)db .getVarValuesForDay("hotdog",date)); if(hd_val!=null){ if(hd_val.size() ==1){ if(Integer.valueOf(hd_val.get(0).value) >0){ db.updateOrAdd("hotdog", Integer.valueOf(hd_val.get(0).value) - 1); } } } if (drink_count_vals.size() == 1) { ArrayList<String> vals = new ArrayList<String>(); vals.add("drank_last_night"); vals.add("tracked"); db.deleteValuesTomorrow(vals); variables.add("drank"); } db.deleteVaribles(variables, drink_count_vals.get(drink_count_vals.size() - 1)); recalculateBac(); updateFace(); Toast.makeText(getApplicationContext(), "Your last drink has been removed", Toast.LENGTH_SHORT).show(); } public static int getBacColor(double bac_value) { if (bac_value < 0.06) { return Color.rgb(112,191, 65); } else if (bac_value < 0.15) { return Color.rgb(245, 211,40); } else if (bac_value < 0.24) { return Color.rgb(236, 93, 87); } else { return Color.DKGRAY; } } public void setFaceIcon(double bac_value){ if (bac_value < 0.06) { face_icon = R.drawable.ic_tracker_smile; } else if (bac_value < 0.15) { face_icon = R.drawable.ic_tracker_neutral; } else if (bac_value < 0.24) { face_icon = R.drawable.ic_tracker_frown; } else { face_icon = R.drawable.ic_tracker_dead; } } private void updateFace(){ setContentView(R.layout.drink_tracker); face_color = getBacColor(bac); setFaceIcon(bac); ImageView face = (ImageView)findViewById(R.id.drink_smile); //Update the face color ((GradientDrawable)((LayerDrawable) face.getDrawable()).getDrawable(0) ).setColor(face_color); //Update the face icon Drawable to_replace = getResources().getDrawable(face_icon); ((LayerDrawable) face.getDrawable()).setDrawableByLayerId( R.id.face_icon, to_replace); face.invalidate(); face.refreshDrawableState(); } private void recalculateBac(){ Date date = DatabaseStore.getDelayedDate(); bac = calculateBac(start_date, date, drink_count); } private double calculateBac(Date start, Date end, int number_drinks) { if(number_drinks <= 0){ return 0.0; } if(start == null){ start(); } long time_elapsed = (end.getTime()-start.getTime()) / (1000 * 60 * 60); // get the users gender ArrayList<DatabaseStore> stored_gender = (ArrayList<DatabaseStore>) db .getAllVarValue("gender"); // If user did not set gender use "Female" as default String gender = "Female"; if (stored_gender != null) { gender = stored_gender.get(0).value; } // fetch the users weight ArrayList<DatabaseStore> stored_weight = (ArrayList<DatabaseStore>) db .getAllVarValue("weight"); Integer weight_lbs = 120; if (stored_weight != null) { weight_lbs = Integer.parseInt(stored_weight.get(0).value); } double metabolism_constant = 0; double gender_constant = 0; double weight_kilograms = weight_lbs * 0.453592; if (gender.equals("Male")) { metabolism_constant = 0.015; gender_constant = 0.58; } else { metabolism_constant = 0.017; gender_constant = 0.49; } double bac_update = ((0.806 * number_drinks * 1.2) / (gender_constant * weight_kilograms)) - (metabolism_constant * time_elapsed); return bac_update; } @SuppressLint("NewApi") public void hadDrink(View view) { clicked=true; drink_count++; if (drink_count == 1) { db.addValueTomorrow("drank_last_night", "True"); db.updateOrAdd("drank", "True"); } db.addDelayValue("drink_count", drink_count); recalculateBac(); start(); updateFace(); db.addDelayValue("bac", String.valueOf(bac)); db.addDelayValue("bac_color", String.valueOf(face_color)); // calculate number of hot dogs that equate the number of calories Double drink_cals = drink_count * CALORIES_PER_DRINK; int number_hot_dogs = (int) Math.ceil(drink_cals/ CALORIES_HOT_DOG); db.updateOrAdd("hot_dogs", number_hot_dogs); } private void injectDrink(int minutesDelay){ drink_count++; Date date = new Date(); //get the existing values from the DB ArrayList<DatabaseStore> counts_recent = (ArrayList<DatabaseStore>)db.getVarValuesDelay( "drink_count", date); ArrayList<DatabaseStore> bac_recent = (ArrayList<DatabaseStore>)db.getVarValuesDelay( "bac", date); ArrayList<DatabaseStore> colors_recent = (ArrayList<DatabaseStore>)db.getVarValuesDelay( "bac_color", date); //Construct the time where we want to inject GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); gc.add(Calendar.HOUR_OF_DAY, -6); gc.add(Calendar.MINUTE, minutesDelay*-1); date = gc.getTime(); int value_inject = 0; double bac_inject =0.0; int color_inject = 0; if(counts_recent != null){ //Sort all values by date counts_recent = DatabaseStore.sortByTime(counts_recent); bac_recent = DatabaseStore.sortByTime(bac_recent); colors_recent = DatabaseStore.sortByTime(colors_recent); assert(bac_recent.size()== counts_recent.size()); assert(colors_recent.size() == counts_recent.size()); boolean placed = false; Iterator<DatabaseStore> iterator = counts_recent.iterator(); Date start_date = counts_recent.get(0).date; int index_val = 0; while (iterator.hasNext()){ DatabaseStore ds = iterator.next(); if(ds.date.after(date)){ if (!placed){ value_inject = Integer.parseInt(ds.value); bac_inject = calculateBac(start_date, date, Integer.parseInt( ds.value)); color_inject = getBacColor(bac_inject); placed=true; } //update drink count Integer new_count_val = Integer.parseInt(ds.value) + 1; ds.value = new_count_val.toString(); db.updateQuestion(ds); //update bac double new_bac = calculateBac(start_date, ds.date, new_count_val); DatabaseStore d = bac_recent.get(index_val); d.value = String.valueOf(new_bac); db.updateQuestion(d); //update Bac Color int new_bac_color = getBacColor(new_bac); d = colors_recent.get(index_val); d.value =String.valueOf(new_bac_color); db.updateQuestion(d); } index_val += 1; } }else{ value_inject = 1; bac_inject = calculateBac(start_date, date, 1); color_inject = getBacColor(bac_inject); } //Add the injected question DatabaseStore data_store = DatabaseStore.DatabaseIntegerStore("drink_count", String.valueOf(value_inject), date); db.addQuestion(data_store); data_store = DatabaseStore.DatabaseIntegerStore("bac", String.valueOf(bac_inject), date); db.addQuestion(data_store); data_store = DatabaseStore.DatabaseIntegerStore("bac_color", String.valueOf(color_inject), date); db.addQuestion(data_store); recalculateBac(); updateFace(); } public void addDrinkHandler(View view){ click_vibe.vibrate(75); Toast t = Toast.makeText(getApplicationContext(), "Adding a drink." , Toast.LENGTH_SHORT); t.setGravity(Gravity.TOP, 0, 100); t.show(); updateFace(); hadDrink(view); } public void removeLastHandler(View view){ click_vibe.vibrate(20); if (clicked == true){ new AlertDialog.Builder(this) .setTitle("Remove Last Drink") .setMessage("Are you sure you would like to remove your last recorded drink?") .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { clicked=false; removeLast(); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); }else{ new AlertDialog.Builder(this) .setTitle("Remove Last Drink") .setMessage("Your last drink was already removed or you did not record any drinks recently.") .setPositiveButton(android.R.string.yes, null).show(); } } public void injectDrinkHandler(View view){ click_vibe.vibrate(20); final String options[] = new String[] {"3 Hours Ago", "2.5 Hours Ago", "2 Hours Ago", "1.5 Hours Ago", "1 Hour Ago", "45 Minutes Ago", "30 Minutes Ago", "15 Minutes Ago"}; final int values[] = new int[] {180, 150, 120, 90, 60, 45, 30, 15}; final Context context = this; new AlertDialog.Builder(this) .setTitle("Record a Drink I had: ") .setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { final int v = values[which]; new AlertDialog.Builder(context) .setTitle("Add Drink in Past") .setMessage("Are you sure you would like to record a drink you had "+options[which] +"?") .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { injectDrink(v); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } }) .setNegativeButton(android.R.string.no, null).show(); } public void trackMoney(View view){ click_vibe.vibrate(20); final EditText input = new EditText(this); input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL); new AlertDialog.Builder(this).setTitle("Enter Amount you spent on Alcohol").setView( input).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { double value = Double.parseDouble(input.getText().toString()); DecimalFormat formatter = new DecimalFormat(" db.addDelayValue("money", formatter.format(value)); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } }
package org.voovan.http.server; import org.voovan.http.message.Request; import org.voovan.http.message.Response; import org.voovan.http.server.WebSocketDispatcher.WebSocketEvent; import org.voovan.http.server.context.WebContext; import org.voovan.http.server.context.WebServerConfig; import org.voovan.http.websocket.WebSocketFrame; import org.voovan.http.websocket.WebSocketFrame.Opcode; import org.voovan.http.websocket.WebSocketTools; import org.voovan.network.IoHandler; import org.voovan.network.IoSession; import org.voovan.network.messagesplitter.HttpMessageSplitter; import org.voovan.tools.TEnv; import org.voovan.tools.TObject; import org.voovan.tools.log.Logger; import java.nio.ByteBuffer; import java.nio.channels.InterruptedByTimeoutException; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.Vector; public class WebServerHandler implements IoHandler { private HttpDispatcher httpDispatcher; private WebSocketDispatcher webSocketDispatcher; private WebServerConfig webConfig; private Timer keepAliveTimer; private List<IoSession> keepAliveSessionList; public WebServerHandler(WebServerConfig webConfig, HttpDispatcher httpDispatcher, WebSocketDispatcher webSocketDispatcher) { this.httpDispatcher = httpDispatcher; this.webSocketDispatcher = webSocketDispatcher; this.webConfig = webConfig; keepAliveSessionList = new Vector<IoSession>(); keepAliveTimer = new Timer("VOOVAN_WEB@KEEP_ALIVER_TIMER"); initKeepAliveTimer(); } /** * * @return */ private long getTimeoutValue(){ int keepAliveTimeout = webConfig.getKeepAliveTimeout(); return System.currentTimeMillis()+keepAliveTimeout*1000; } /** * Timer */ public void initKeepAliveTimer(){ TimerTask keepAliveTask = new TimerTask() { @Override public void run() { long currentTimeValue = System.currentTimeMillis(); // session for(int i=0; i<keepAliveSessionList.size(); i++){ IoSession session = keepAliveSessionList.get(i); long timeOutValue = (long) session.getAttribute("TimeOutValue"); if(timeOutValue < currentTimeValue){ session.close(); keepAliveSessionList.remove(session); i } } } }; keepAliveTimer.schedule(keepAliveTask, 1 , 1000); } @Override public Object onConnect(IoSession session) { return null; } @Override public void onDisconnect(IoSession session) { if ("WebSocket".equals(session.getAttribute("Type"))) { // WebSocket Close webSocketDispatcher.fireCloseEvent(session); } // IoSession keepAliveSessionList.remove(session); } @Override public Object onReceive(IoSession session, Object obj) { String defaultCharacterSet = webConfig.getCharacterSet(); // Http if (obj instanceof Request) { Request request = TObject.cast(obj); Response response = new Response(); if(webConfig.isGzip() && request.header().contain("Accept-Encoding") && request.header().get("Accept-Encoding").contains("gzip")) { response.setCompress(true); } // Http / HttpRequest httpRequest = new HttpRequest(request, defaultCharacterSet); HttpResponse httpResponse = new HttpResponse(response, defaultCharacterSet); session.setAttribute("HttpRequest",httpRequest); session.setAttribute("HttpResponse",httpResponse); httpRequest.setRemoteAddres(session.remoteAddress()); httpRequest.setRemotePort(session.remotePort()); // WebSocket if (WebSocketTools.isWebSocketUpgrade(request)) { return disposeUpgrade(session, httpRequest, httpResponse); } // Http 1.1 else { return disposeHttp(session, httpRequest, httpResponse); } } // WEBSocket else if (obj instanceof WebSocketFrame) { return disposeWebSocket(session, (WebSocketFrame)obj); } session.close(); return null; } /** * Http * * @param session HTTP-Session * @param httpRequest HTTP * @param httpResponse HTTP * @return HTTP */ public HttpResponse disposeHttp(IoSession session, HttpRequest httpRequest, HttpResponse httpResponse) { session.setAttribute("Type", "HTTP"); httpDispatcher.process(httpRequest, httpResponse); if (httpRequest.header().contain("Connection") && httpRequest.header().get("Connection").toLowerCase().contains("keep-alive")) { session.setAttribute("IsKeepAlive", true); httpResponse.header().put("Connection", httpRequest.header().get("Connection")); } httpResponse.header().put("Server", WebContext.getVERSION()); return httpResponse; } /** * Http * * @param session HTTP-Session * @param httpRequest HTTP * @param httpResponse HTTP * @return HTTP */ public HttpResponse disposeUpgrade(IoSession session, HttpRequest httpRequest, HttpResponse httpResponse) { session.setAttribute("Type", "Upgrade"); session.setAttribute("IsKeepAlive", true); httpResponse.protocol().setStatus(101); httpResponse.protocol().setStatusCode("Switching Protocols"); httpResponse.header().put("Connection", "Upgrade"); if(httpRequest.header()!=null && "websocket".equalsIgnoreCase(httpRequest.header().get("Upgrade"))){ httpResponse.header().put("Upgrade", "websocket"); String webSocketKey = WebSocketTools.generateSecKey(httpRequest.header().get("Sec-WebSocket-Key")); httpResponse.header().put("Sec-WebSocket-Accept", webSocketKey); } else if(httpRequest.header()!=null && "h2c".equalsIgnoreCase(httpRequest.header().get("Upgrade"))){ httpResponse.header().put("Upgrade", "h2c"); // HTTP2, } return httpResponse; } /** * WebSocket * * @param session HTTP-Session * @param webSocketFrame WebSocket * @return WebSocket */ public WebSocketFrame disposeWebSocket(IoSession session, WebSocketFrame webSocketFrame) { session.setAttribute("Type" , "WebSocket"); session.setAttribute("IsKeepAlive" , true); HttpRequest reqWebSocket = TObject.cast(session.getAttribute("HttpRequest")); // WS_CLOSE if (webSocketFrame.getOpcode() == Opcode.CLOSING) { return WebSocketFrame.newInstance(true, Opcode.CLOSING, false, webSocketFrame.getFrameData()); } // WS_PING ping pong else if (webSocketFrame.getOpcode() == Opcode.PING) { return WebSocketFrame.newInstance(true, Opcode.PONG, false, webSocketFrame.getFrameData()); } // WS_PING pong ping else if (webSocketFrame.getOpcode() == Opcode.PONG) { TEnv.sleep(1000); return WebSocketFrame.newInstance(true, Opcode.PING, false, null); } // WS_RECIVE Recived else if (webSocketFrame.getOpcode() == Opcode.TEXT || webSocketFrame.getOpcode() == Opcode.BINARY) { WebSocketFrame respWebSocketFrame = null; if(webSocketFrame.getErrorCode()==0){ respWebSocketFrame = webSocketDispatcher.process(WebSocketEvent.RECIVED, session, reqWebSocket, webSocketFrame); }else{ respWebSocketFrame = WebSocketFrame.newInstance(true, Opcode.CLOSING, false, ByteBuffer.wrap(WebSocketTools.intToByteArray(webSocketFrame.getErrorCode(), 2))); } return respWebSocketFrame; } return null; } @Override public void onSent(IoSession session, Object obj) { HttpRequest request = TObject.cast(session.getAttribute("HttpRequest")); HttpResponse response = TObject.cast(session.getAttribute("HttpResponse")); if(HttpMessageSplitter.isWebSocketFrame((ByteBuffer) obj) != -1){ WebSocketFrame webSocketFrame = WebSocketFrame.parse((ByteBuffer)obj); if(webSocketFrame.getOpcode() != Opcode.PING && webSocketFrame.getOpcode() != Opcode.PONG && webSocketFrame.getOpcode() != Opcode.CLOSING) { webSocketDispatcher.process(WebSocketEvent.SENT, session, request, webSocketFrame); } } // WebSocket if("Upgrade".equals(session.getAttribute("Type"))){ session.setAttribute("Type", "WebSocket"); WebSocketFrame webSocketFrame = webSocketDispatcher.process(WebSocketEvent.OPEN, session, request, null); if(webSocketFrame!=null) { // onOpen ByteBuffer byteBuffer = webSocketFrame.toByteBuffer(); //syncSend onSent , session.send(byteBuffer); byteBuffer.rewind(); // onSent onSent(session, byteBuffer); } // ping WebSocketFrame ping = WebSocketFrame.newInstance(true, Opcode.PING, false, null); session.send(ping.toByteBuffer()); } if (session.containAttribute("IsKeepAlive") && (boolean) session.getAttribute("IsKeepAlive") && webConfig.getKeepAliveTimeout() > 0) { if(!keepAliveSessionList.contains(session)){ keepAliveSessionList.add(session); } session.setAttribute("TimeOutValue", getTimeoutValue()); }else { if(keepAliveSessionList.contains(session)){ keepAliveSessionList.remove(session); } session.close(); } } @Override public void onException(IoSession session, Exception e) { if(!(e instanceof InterruptedByTimeoutException)){ Logger.error("Http Server Error",e); } session.close(); } }
/* @header@ */ package org.pcmm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.umu.cops.prpdp.COPSPdpException; import org.umu.cops.stack.*; import java.io.IOException; import java.net.Socket; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; /** * Class for managing an provisioning connection at the PDP side. */ public class PCMMPdpConnection implements Runnable { public final static Logger logger = LoggerFactory.getLogger(PCMMPdpConnection.class); /** Socket connected to PEP */ private Socket _sock; /** PEP identifier */ private COPSPepId _pepId; /** Time of the latest keep-alive sent */ private Date _lastKa; /** Opcode of the latest message sent */ private byte _lastmessage; /** * Time of the latest keep-alive received */ protected Date _lastRecKa; /** Maps a Client Handle to a Handler */ protected Hashtable _managerMap; // map < String(COPSHandle), COPSPdpHandler> HandlerMap; /** * PDP policy data processor class */ protected PCMMPdpDataProcess _process; /** Accounting timer value (secs) */ protected short _acctTimer; /** Keep-alive timer value (secs) */ protected short _kaTimer; /** COPS error returned by PEP */ protected COPSError _error; /** * Creates a new PDP connection * * @param pepId PEP-ID of the connected PEP * @param sock Socket connected to PEP * @param process Object for processing policy data */ public PCMMPdpConnection(COPSPepId pepId, Socket sock, PCMMPdpDataProcess process) { _sock = sock; _pepId = pepId; _lastKa = new Date(); _lastmessage = COPSHeader.COPS_OP_OPN; _managerMap = new Hashtable(20); _kaTimer = 120; _process = process; } /** * Gets the time of that latest keep-alive sent * @return Time of that latest keep-alive sent */ public Date getLastKAlive() { return _lastKa; } /** * Sets the keep-alive timer value * @param kaTimer Keep-alive timer value (secs) */ public void setKaTimer(short kaTimer) { _kaTimer = kaTimer; } /** * Gets the keep-alive timer value * @return Keep-alive timer value (secs) */ public short getKaTimer() { return _kaTimer; } /** * Sets the accounting timer value * @param acctTimer Accounting timer value (secs) */ public void setAccTimer(short acctTimer) { _acctTimer = acctTimer; } /** * Gets the accounting timer value * @return Accounting timer value (secs) */ public short getAcctTimer() { return _acctTimer; } /** * Gets the latest COPS message * @return Code of the latest message sent */ public byte getLastMessage() { return _lastmessage; } /** * Gets active handles * @return An <tt>Enumeration</tt> holding all active handles */ public Enumeration getHandles() { return _managerMap.keys(); } /** * Gets the handle map * @return A <tt>Hashtable</tt> holding the handle map */ public Hashtable getReqStateMans() { return _managerMap; } /** * Gets the PEP-ID * @return The ID of the PEP, as a <tt>String</tt> */ public String getPepId() { return _pepId.getData().str(); } /** * Checks whether the socket to the PEP is closed or not * @return <tt>true</tt> if closed, <tt>false</tt> otherwise */ public boolean isClosed() { return _sock.isClosed(); } /** * Closes the socket to the PEP * @throws IOException */ protected void close() throws IOException { _sock.close(); } /** * Gets the socket to the PEP * @return Socket connected to the PEP */ public Socket getSocket() { return _sock; } /** * Main loop */ public void run () { Date _lastSendKa = new Date(); _lastRecKa = new Date(); try { while (!_sock.isClosed()) { if (_sock.getInputStream().available() != 0) { _lastmessage = processMessage(_sock); _lastRecKa = new Date(); } // Keep Alive if (_kaTimer > 0) { // Timeout at PDP int _startTime = (int) (_lastRecKa.getTime()); int cTime = (int) (new Date().getTime()); if ((int)(cTime - _startTime) > _kaTimer*1000) { _sock.close(); // Notify all Request State Managers notifyNoKAAllReqStateMan(); } // Send to PEP _startTime = (int) (_lastSendKa.getTime()); cTime = (int) (new Date().getTime()); if ((cTime - _startTime) > ((_kaTimer * 3/4) * 1000)) { COPSHeader hdr = new COPSHeader(COPSHeader.COPS_OP_KA); COPSKAMsg msg = new COPSKAMsg(); msg.add(hdr); COPSTransceiver.sendMsg(msg, _sock); _lastSendKa = new Date(); } } try { Thread.sleep(500); } catch (Exception e) { logger.error("Unexpected exception while sleeping", e); } } } catch (Exception e) { logger.error("Error reading messages from socket", e); } // connection closed by server // COPSDebug.out(getClass().getName(),"Connection closed by client"); try { _sock.close(); } catch (IOException e) { logger.error("Error closing socket", e); } // Notify all Request State Managers try { notifyCloseAllReqStateMan(); } catch (COPSPdpException e) { logger.error("Error closing state managers", e); } } /** * Gets a COPS message from the socket and processes it * @param conn Socket connected to the PEP * @return Type of COPS message */ private byte processMessage(Socket conn) throws COPSPdpException, COPSException, IOException { COPSMsg msg = COPSTransceiver.receiveMsg(conn); if (msg.getHeader().isAClientClose()) { handleClientCloseMsg(conn, msg); return COPSHeader.COPS_OP_CC; } else if (msg.getHeader().isAKeepAlive()) { handleKeepAliveMsg(conn, msg); return COPSHeader.COPS_OP_KA; } else if (msg.getHeader().isARequest()) { handleRequestMsg(conn, msg); return COPSHeader.COPS_OP_REQ; } else if (msg.getHeader().isAReport()) { handleReportMsg(conn, msg); return COPSHeader.COPS_OP_RPT; } else if (msg.getHeader().isADeleteReq()) { handleDeleteRequestMsg(conn, msg); return COPSHeader.COPS_OP_DRQ; } else if (msg.getHeader().isASyncComplete()) { handleSyncComplete(conn, msg); return COPSHeader.COPS_OP_SSC; } else { throw new COPSPdpException("Message not expected (" + msg.getHeader().getOpCode() + ")."); } } /** * Handle Client Close Message, close the passed connection * * @param conn a Socket * @param msg a COPSMsg * * * <Client-Close> ::= <Common Header> * <Error> * [<Integrity>] * * Not support [<Integrity>] * */ private void handleClientCloseMsg(Socket conn, COPSMsg msg) { COPSClientCloseMsg cMsg = (COPSClientCloseMsg) msg; _error = cMsg.getError(); // COPSDebug.out(getClass().getName(),"Got close request, closing connection " + // conn.getInetAddress() + ":" + conn.getPort() + ":[Error " + _error.getDescription() + "]"); try { // Support if (cMsg.getIntegrity() != null) { logger.error("Unsupported objects (Integrity) to connection " + conn.getInetAddress()); } conn.close(); } catch (Exception unae) { logger.error("Unexpected exception closing connection", unae); } } /** * Gets the occurred COPS Error * @return <tt>COPSError</tt> object */ protected COPSError getError() { return _error; } /** * Handle Keep Alive Message * * <Keep-Alive> ::= <Common Header> * [<Integrity>] * * Not support [<Integrity>] * * @param conn a Socket * @param msg a COPSMsg * */ private void handleKeepAliveMsg(Socket conn, COPSMsg msg) { COPSKAMsg cMsg = (COPSKAMsg) msg; COPSKAMsg kaMsg = (COPSKAMsg) msg; try { // Support if (cMsg.getIntegrity() != null) { logger.error("Unsupported objects (Integrity) to connection " + conn.getInetAddress()); } kaMsg.writeData(conn); } catch (Exception unae) { logger.error("Unexpected exception while writing keep-alive message", unae); } } /** * Handle Delete Request Message * * <Delete Request> ::= <Common Header> * <Client Handle> * <Reason> * [<Integrity>] * * Not support [<Integrity>] * * @param conn a Socket * @param msg a COPSMsg * */ private void handleDeleteRequestMsg(Socket conn, COPSMsg msg) throws COPSPdpException { COPSDeleteMsg cMsg = (COPSDeleteMsg) msg; // COPSDebug.out(getClass().getName(),"Removing ClientHandle for " + // conn.getInetAddress() + ":" + conn.getPort() + ":[Reason " + cMsg.getReason().getDescription() + "]"); // Support if (cMsg.getIntegrity() != null) { logger.error("Unsupported objects (Integrity) to connection " + conn.getInetAddress()); } // Delete clientHandler if (_managerMap.remove(cMsg.getClientHandle().getId().str()) == null) { // COPSDebug.out(getClass().getName(),"Missing for ClientHandle " + // cMsg.getClientHandle().getId().getData()); } PCMMPdpReqStateMan man = (PCMMPdpReqStateMan) _managerMap.get(cMsg.getClientHandle().getId().str()); if (man == null) { logger.warn("State manager not found"); } else { man.processDeleteRequestState(cMsg); } } /** * Handle Request Message * * <Request> ::= <Common Header> * <Client Handle> * <Context> * *(<Named ClientSI>) * [<Integrity>] * <Named ClientSI> ::= <*(<PRID> <EPD>)> * * Not support [<Integrity>] * * @param conn a Socket * @param msg a COPSMsg * */ private void handleRequestMsg(Socket conn, COPSMsg msg) throws COPSPdpException { COPSReqMsg reqMsg = (COPSReqMsg) msg; COPSContext cntxt = reqMsg.getContext(); COPSHeader header = reqMsg.getHeader(); //short reqType = cntxt.getRequestType(); short cType = header.getClientType(); // Support if (reqMsg.getIntegrity() != null) { logger.error("Unsupported objects (Integrity) to connection " + conn.getInetAddress()); } PCMMPdpReqStateMan man; man = (PCMMPdpReqStateMan) _managerMap.get(reqMsg.getClientHandle().getId().str()); if (man == null) { man = new PCMMPdpReqStateMan(cType, reqMsg.getClientHandle().getId().str()); _managerMap.put(reqMsg.getClientHandle().getId().str(),man); man.setDataProcess(_process); man.initRequestState(_sock); // COPSDebug.out(getClass().getName(),"createHandler called, clientType=" + // header.getClientType() + " msgType=" + // cntxt.getMessageType() + ", connId=" + conn.toString()); } man.processRequest(reqMsg); } /** * Handle Report Message * * <Report State> ::= <Common Header> * <Client Handle> * <Report Type> * *(<Named ClientSI>) * [<Integrity>] * * Not support [<Integrity>] * * @param conn a Socket * @param msg a COPSMsg * */ private void handleReportMsg(Socket conn, COPSMsg msg) throws COPSPdpException { COPSReportMsg repMsg = (COPSReportMsg) msg; // COPSHandle handle = repMsg.getClientHandle(); // COPSHeader header = repMsg.getHeader(); // Support if (repMsg.getIntegrity() != null) { logger.error("Unsupported objects (Integrity) to connection " + conn.getInetAddress()); } PCMMPdpReqStateMan man = (PCMMPdpReqStateMan) _managerMap.get(repMsg.getClientHandle().getId().str()); if (man == null) { logger.warn("State manager not found"); } else { man.processReport(repMsg); } } /** * Method handleSyncComplete * * @param conn a Socket * @param msg a COPSMsg * */ private void handleSyncComplete(Socket conn, COPSMsg msg) throws COPSPdpException { COPSSyncStateMsg cMsg = (COPSSyncStateMsg) msg; // COPSHandle handle = cMsg.getClientHandle(); // COPSHeader header = cMsg.getHeader(); // Support if (cMsg.getIntegrity() != null) { logger.error("Unsupported objects (Integrity) to connection " + conn.getInetAddress()); } PCMMPdpReqStateMan man = (PCMMPdpReqStateMan) _managerMap.get(cMsg.getClientHandle().getId().str()); if (man == null) { logger.warn("State manager not found"); } else { man.processSyncComplete(cMsg); } } /** * Requests a COPS sync from the PEP * @throws COPSException * @throws COPSPdpException */ protected void syncAllRequestState() throws COPSException, COPSPdpException { if (_managerMap.size() > 0) { for (Enumeration e = _managerMap.keys() ; e.hasMoreElements() ;) { String handle = (String) e.nextElement(); PCMMPdpReqStateMan man = (PCMMPdpReqStateMan) _managerMap.get(handle); man.syncRequestState(); } } } private void notifyCloseAllReqStateMan() throws COPSPdpException { if (_managerMap.size() > 0) { for (Enumeration e = _managerMap.keys() ; e.hasMoreElements() ;) { String handle = (String) e.nextElement(); PCMMPdpReqStateMan man = (PCMMPdpReqStateMan) _managerMap.get(handle); man.processClosedConnection(_error); } } } private void notifyNoKAAllReqStateMan() throws COPSPdpException { if (_managerMap.size() > 0) { for (Enumeration e = _managerMap.keys() ; e.hasMoreElements() ;) { String handle = (String) e.nextElement(); PCMMPdpReqStateMan man = (PCMMPdpReqStateMan) _managerMap.get(handle); man.processNoKAConnection(); } } } }
package org.pitest.maven; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; import java.util.logging.Logger; import java.util.stream.Collectors; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.pitest.coverage.CoverageSummary; import org.pitest.mutationtest.config.PluginServices; import org.pitest.mutationtest.config.ReportOptions; import org.pitest.mutationtest.statistics.MutationStatistics; import org.pitest.mutationtest.tooling.CombinedStatistics; import org.pitest.plugin.ClientClasspathPlugin; import org.pitest.plugin.ToolClasspathPlugin; import org.slf4j.bridge.SLF4JBridgeHandler; import uk.org.lidalia.sysoutslf4j.context.SysOutOverSLF4J; public class AbstractPitMojo extends AbstractMojo { private final Predicate<MavenProject> notEmptyProject; private final Predicate<Artifact> filter; private final PluginServices plugins; // Concrete List types declared for all fields to work around maven 2 bug /** * Test plugin to use */ @Parameter(property = "testPlugin", defaultValue = "") private String testPlugin; /** * Classes to include in mutation test */ @Parameter(property = "targetClasses") private ArrayList<String> targetClasses; /** * Tests to run */ @Parameter(property = "targetTests") private ArrayList<String> targetTests; /** * Methods not to mutate */ @Parameter(property = "excludedMethods") private ArrayList<String> excludedMethods; /** * Classes not to mutate */ @Parameter(property = "excludedClasses") private ArrayList<String> excludedClasses; /** * Classes not to run tests from */ @Parameter(property = "excludedTestClasses") private ArrayList<String> excludedTestClasses; @Parameter(property = "avoidCallsTo") private ArrayList<String> avoidCallsTo; /** * Base directory where all reports are written to. */ @Parameter(defaultValue = "${project.build.directory}/pit-reports", property = "reportsDirectory") private File reportsDirectory; /** * File to write history information to for incremental analysis */ @Parameter(property = "historyOutputFile") private File historyOutputFile; /** * File to read history from for incremental analysis (can be same as output * file) */ @Parameter(property = "historyInputFile") private File historyInputFile; /** * Convenience flag to read and write history to a local temp file. * * Setting this flag is the equivalent to calling maven with -DhistoryInputFile=file -DhistoryOutputFile=file * * Where file is a file named [groupid][artifactid][version]_pitest_history.bin in the temp directory * */ @Parameter(defaultValue = "false", property = "withHistory") private boolean withHistory; /** * Maximum distance to look from test to class. Relevant when mutating static * initializers * */ @Parameter(defaultValue = "-1", property = "maxDependencyDistance") private int maxDependencyDistance; /** * Number of threads to use */ @Parameter(defaultValue = "1", property = "threads") private int threads; /** * Mutate static initializers */ @Parameter(defaultValue = "false", property = "mutateStaticInitializers") private boolean mutateStaticInitializers; /** * Detect inlined code */ @Parameter(defaultValue = "true", property = "detectInlinedCode") private boolean detectInlinedCode; /** * Mutation operators to apply */ @Parameter(property = "mutators") private ArrayList<String> mutators; /** * Mutation operators to apply */ @Parameter(property = "features") private ArrayList<String> features; /** * Weighting to allow for timeouts */ @Parameter(defaultValue = "1.25", property = "timeoutFactor") private float timeoutFactor; /** * Constant factor to allow for timeouts */ @Parameter(defaultValue = "3000", property = "timeoutConstant") private long timeoutConstant; /** * Maximum number of mutations to allow per class */ @Parameter(defaultValue = "-1", property = "maxMutationsPerClass") private int maxMutationsPerClass; /** * Arguments to pass to child processes */ @Parameter private ArrayList<String> jvmArgs; /** * Formats to output during analysis phase */ @Parameter(property = "outputFormats") private ArrayList<String> outputFormats; /** * Output verbose logging */ @Parameter(defaultValue = "false", property = "verbose") private boolean verbose; /** * Throw error if no mutations found */ @Parameter(defaultValue = "true", property = "failWhenNoMutations") private boolean failWhenNoMutations; /** * Create timestamped subdirectory for report */ @Parameter(defaultValue = "true", property = "timestampedReports") private boolean timestampedReports; /** * TestNG Groups/JUnit Categories to exclude */ @Parameter(property = "excludedGroups") private ArrayList<String> excludedGroups; /** * TestNG Groups/JUnit Categories to include */ @Parameter(property = "includedGroups") private ArrayList<String> includedGroups; /** * Test methods that should be included for challenging the mutants */ @Parameter(property = "includedTestMethods") private ArrayList<String> includedTestMethods; /** * Whether to create a full mutation matrix. * * If set to true all tests covering a mutation will be executed, * if set to false the test execution will stop after the first killing test. */ @Parameter(property = "fullMutationMatrix", defaultValue = "false") private boolean fullMutationMatrix; /** * Maximum number of mutations to include in a single analysis unit. * * If set to 1 will analyse very slowly, but with strong (jvm per mutant) * isolation. * */ @Parameter(property = "mutationUnitSize") private int mutationUnitSize; /** * Export line coverage data */ @Parameter(defaultValue = "false", property = "exportLineCoverage") private boolean exportLineCoverage; /** * Mutation score threshold at which to fail build */ @Parameter(defaultValue = "0", property = "mutationThreshold") private int mutationThreshold; /** * Maximum surviving mutants to allow */ @Parameter(defaultValue = "-1", property = "maxSurviving") private int maxSurviving = -1; /** * Line coverage threshold at which to fail build */ @Parameter(defaultValue = "0", property = "coverageThreshold") private int coverageThreshold; /** * Path to java executable to use when running tests. Will default to * executable in JAVA_HOME if none set. */ @Parameter private String jvm; /** * Engine to use when generating mutations. */ @Parameter(defaultValue = "gregor", property = "mutationEngine") private String mutationEngine; /** * List of additional classpath entries to use when looking for tests and * mutable code. These will be used in addition to the classpath with which * PIT is launched. */ @Parameter(property = "additionalClasspathElements") private ArrayList<String> additionalClasspathElements; /** * List of classpath entries, formatted as "groupId:artifactId", which should * not be included in the classpath when running mutation tests. Modelled * after the corresponding Surefire/Failsafe property. */ @Parameter(property = "classpathDependencyExcludes") private ArrayList<String> classpathDependencyExcludes; @Parameter(property = "excludedRunners") private ArrayList<String> excludedRunners; /** * When set indicates that analysis of this project should be skipped */ @Parameter(property = "skipPitest", defaultValue = "false") private boolean skip; /** * When set will try and create settings based on surefire configuration. This * may not give the desired result in some circumstances */ @Parameter(defaultValue = "true") private boolean parseSurefireConfig; /** * honours common skipTests flag in a maven run */ @Parameter(defaultValue = "false") private boolean skipTests; /** * When set will ignore failing tests when computing coverage. Otherwise, the * run will fail. If parseSurefireConfig is true, will be overridden from * surefire configuration property testFailureIgnore */ @Parameter(defaultValue = "false") private boolean skipFailingTests; /** * Use slf4j for logging */ @Parameter(defaultValue = "false", property = "useSlf4j") private boolean useSlf4j; /** * Configuration properties. * * Value pairs may be used by pitest plugins. * */ @Parameter private Map<String, String> pluginConfiguration; /** * environment configuration * * Value pairs may be used by pitest plugins. */ @Parameter private Map<String, String> environmentVariables = new HashMap<>(); /** * <i>Internal</i>: Project to interact with. * */ @Parameter(property = "project", readonly = true, required = true) private MavenProject project; /** * <i>Internal</i>: Map of plugin artifacts. */ @Parameter(property = "plugin.artifactMap", readonly = true, required = true) private Map<String, Artifact> pluginArtifactMap; /** * Communicate the classpath using a temporary jar with a classpath * manifest. This allows support of very large classpaths but may cause * issues with certian libraries. */ @Parameter(property = "useClasspathJar", defaultValue = "false") private boolean useClasspathJar; private final GoalStrategy goalStrategy; public AbstractPitMojo() { this(new RunPitStrategy(), new DependencyFilter(new PluginServices( AbstractPitMojo.class.getClassLoader())), new PluginServices( AbstractPitMojo.class.getClassLoader()), new NonEmptyProjectCheck()); } public AbstractPitMojo(final GoalStrategy strategy, final Predicate<Artifact> filter, final PluginServices plugins, final Predicate<MavenProject> emptyProjectCheck) { this.goalStrategy = strategy; this.filter = filter; this.plugins = plugins; this.notEmptyProject = emptyProjectCheck; } @Override public final void execute() throws MojoExecutionException, MojoFailureException { switchLogging(); RunDecision shouldRun = shouldRun(); if (shouldRun.shouldRun()) { for (final ToolClasspathPlugin each : this.plugins .findToolClasspathPlugins()) { this.getLog().info("Found plugin : " + each.description()); } for (final ClientClasspathPlugin each : this.plugins .findClientClasspathPlugins()) { this.getLog().info( "Found shared classpath plugin : " + each.description()); } final Optional<CombinedStatistics> result = analyse(); if (result.isPresent()) { throwErrorIfScoreBelowThreshold(result.get().getMutationStatistics()); throwErrorIfMoreThanMaximumSurvivors(result.get().getMutationStatistics()); throwErrorIfCoverageBelowThreshold(result.get().getCoverageSummary()); } } else { this.getLog().info("Skipping project because:"); for (String reason : shouldRun.getReasons()) { this.getLog().info(" - " + reason); } } } private void switchLogging() { if (this.useSlf4j) { SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); Logger.getLogger("PIT").addHandler(new SLF4JBridgeHandler()); SysOutOverSLF4J.sendSystemOutAndErrToSLF4J(); } } private void throwErrorIfCoverageBelowThreshold( final CoverageSummary coverageSummary) throws MojoFailureException { if ((this.coverageThreshold != 0) && (coverageSummary.getCoverage() < this.coverageThreshold)) { throw new MojoFailureException("Line coverage of " + coverageSummary.getCoverage() + "(" + coverageSummary.getNumberOfCoveredLines() + "/" + coverageSummary.getNumberOfLines() + ") is below threshold of " + this.coverageThreshold); } } private void throwErrorIfScoreBelowThreshold(final MutationStatistics result) throws MojoFailureException { if ((this.mutationThreshold != 0) && (result.getPercentageDetected() < this.mutationThreshold)) { throw new MojoFailureException("Mutation score of " + result.getPercentageDetected() + " is below threshold of " + this.mutationThreshold); } } private void throwErrorIfMoreThanMaximumSurvivors(final MutationStatistics result) throws MojoFailureException { if ((this.maxSurviving >= 0) && (result.getTotalSurvivingMutations() > this.maxSurviving)) { throw new MojoFailureException("Had " + result.getTotalSurvivingMutations() + " surviving mutants, but only " + this.maxSurviving + " survivors allowed"); } } protected Optional<CombinedStatistics> analyse() throws MojoExecutionException { final ReportOptions data = new MojoToReportOptionsConverter(this, new SurefireConfigConverter(), this.filter).convert(); return Optional.ofNullable(this.goalStrategy.execute(detectBaseDir(), data, this.plugins, this.environmentVariables)); } protected File detectBaseDir() { // execution project doesn't seem to always be available. // possibily a maven 2 vs maven 3 issue? final MavenProject executionProject = this.project.getExecutionProject(); if (executionProject == null) { return null; } return executionProject.getBasedir(); } protected Predicate<Artifact> getFilter() { return filter; } protected GoalStrategy getGoalStrategy() { return goalStrategy; } protected PluginServices getPlugins() { return plugins; } public List<String> getTargetClasses() { return withoutNulls(this.targetClasses); } public void setTargetClasses(ArrayList<String> targetClasses) { this.targetClasses = targetClasses; } public List<String> getTargetTests() { return withoutNulls(this.targetTests); } public void setTargetTests(ArrayList<String> targetTests) { this.targetTests = targetTests; } public List<String> getExcludedMethods() { return withoutNulls(this.excludedMethods); } public List<String> getExcludedClasses() { return withoutNulls(this.excludedClasses); } public List<String> getAvoidCallsTo() { return withoutNulls(this.avoidCallsTo); } public File getReportsDirectory() { return this.reportsDirectory; } public int getMaxDependencyDistance() { return this.maxDependencyDistance; } public int getThreads() { return this.threads; } public boolean isMutateStaticInitializers() { return this.mutateStaticInitializers; } public List<String> getMutators() { return withoutNulls(this.mutators); } public float getTimeoutFactor() { return this.timeoutFactor; } public long getTimeoutConstant() { return this.timeoutConstant; } public ArrayList<String> getExcludedTestClasses() { return withoutNulls(excludedTestClasses); } public int getMaxMutationsPerClass() { return this.maxMutationsPerClass; } public List<String> getJvmArgs() { return withoutNulls(this.jvmArgs); } public List<String> getOutputFormats() { return withoutNulls(this.outputFormats); } public boolean isVerbose() { return this.verbose; } public MavenProject getProject() { return this.project; } public Map<String, Artifact> getPluginArtifactMap() { return this.pluginArtifactMap; } public boolean isFailWhenNoMutations() { return this.failWhenNoMutations; } public List<String> getExcludedGroups() { return withoutNulls(this.excludedGroups); } public List<String> getIncludedGroups() { return withoutNulls(this.includedGroups); } public List<String> getIncludedTestMethods() { return withoutNulls(this.includedTestMethods); } public boolean isFullMutationMatrix() { return fullMutationMatrix; } public void setFullMutationMatrix(boolean fullMutationMatrix) { this.fullMutationMatrix = fullMutationMatrix; } public int getMutationUnitSize() { return this.mutationUnitSize; } public boolean isTimestampedReports() { return this.timestampedReports; } public boolean isDetectInlinedCode() { return this.detectInlinedCode; } public void setTimestampedReports(final boolean timestampedReports) { this.timestampedReports = timestampedReports; } public File getHistoryOutputFile() { return this.historyOutputFile; } public File getHistoryInputFile() { return this.historyInputFile; } public boolean isExportLineCoverage() { return this.exportLineCoverage; } protected RunDecision shouldRun() { RunDecision decision = new RunDecision(); if (this.skip) { decision.addReason("Execution of PIT should be skipped."); } if (this.skipTests) { decision.addReason("Test execution should be skipped (-DskipTests)."); } if ("pom".equalsIgnoreCase(this.project.getPackaging())) { decision.addReason("Packaging is POM."); } if (!notEmptyProject.test(project)) { decision.addReason("Project has no tests, it is empty."); } return decision; } public String getMutationEngine() { return this.mutationEngine; } public String getJavaExecutable() { return this.jvm; } public void setJavaExecutable(final String javaExecutable) { this.jvm = javaExecutable; } public List<String> getAdditionalClasspathElements() { return withoutNulls(this.additionalClasspathElements); } public List<String> getClasspathDependencyExcludes() { return withoutNulls(this.classpathDependencyExcludes); } public boolean isParseSurefireConfig() { return this.parseSurefireConfig; } public boolean skipFailingTests() { return this.skipFailingTests; } public Map<String, String> getPluginProperties() { return pluginConfiguration; } public Map<String, String> getEnvironmentVariables() { return environmentVariables; } public boolean useHistory() { return this.withHistory; } public ArrayList<String> getExcludedRunners() { return withoutNulls(excludedRunners); } public ArrayList<String> getFeatures() { return withoutNulls(features); } public String getTestPlugin() { return testPlugin; } public boolean isUseClasspathJar() { return this.useClasspathJar; } static class RunDecision { private List<String> reasons = new ArrayList<>(4); boolean shouldRun() { return reasons.isEmpty(); } public void addReason(String reason) { reasons.add(reason); } public List<String> getReasons() { return Collections.unmodifiableList(reasons); } } private <X> ArrayList<X> withoutNulls(List<X> originalList) { if (originalList == null) { return null; } return originalList.stream() .filter(Objects::nonNull) .collect(Collectors.toCollection(ArrayList::new)); } }
package org.headsupdev.agile.api.rest; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; import com.google.gson.GsonBuilder; import org.apache.wicket.PageParameters; import org.apache.wicket.model.IModel; /** * The base class for HeadsUp Agile REST API classes. This allows for simple API creation by exposing objects * through wicket models. * <p/> * Created: 09/02/2013 * * @author Andrew Williams * @since 2.0 */ public abstract class Api extends org.innobuilt.wicket.rest.JsonWebServicePage { protected Api( PageParameters params ) { super( params ); setupBuilder(); } protected Api( PageParameters params, Class clazz ) { super( params, clazz ); setupBuilder(); } private void setupBuilder() { GsonBuilder builder = getBuilder(); builder.setDateFormat( "yyyy-MM-dd'T'HH:mmZ" ); // ISO 8601 date/time format if ( respectPublishAnnotation() ) { // Prefer to only expose the fields I have annotated builder.setExclusionStrategies( new MissingPublishExclusionStrategy() ); } setupJson( builder ); } public boolean respectPublishAnnotation() { return true; } public void setModel( IModel model ) { super.setDefaultModel( model ); } public void setupJson( GsonBuilder builder ) { // for extension purposes } public abstract void doGet( PageParameters pageParameters ); public void doPost( PageParameters pageParameters ) { // override this to handle POST method } public void doPut( PageParameters pageParameters ) { // override this to handle PUT method } public void doDelete( PageParameters pageParameters ) { // override this to handle DELETE method } private static class MissingPublishExclusionStrategy implements ExclusionStrategy { public boolean shouldSkipField( FieldAttributes fieldAttributes ) { return fieldAttributes.getAnnotation( Publish.class ) == null; } public boolean shouldSkipClass( Class<?> aClass ) { return false; } } }
package com.reactlibrary; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import org.tensorflow.Graph; import org.tensorflow.Operation; import org.tensorflow.contrib.android.TensorFlowInferenceInterface; public class RNTensorflowModule extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; private TensorFlowInferenceInterface inference; public RNTensorflowModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "RNTensorflow"; } @ReactMethod public void instantiateTensorflow(String modelFilePath) { this.inference = new TensorFlowInferenceInterface(reactContext.getAssets(), modelFilePath); } @ReactMethod public void feed(String inputName, double[] src, long[] dims) { this.inference.feed(inputName, src, dims); } @ReactMethod public void feed(String inputName, double[] src) { this.inference.feed(inputName, src); } @ReactMethod public void run(String[] outputNames) { this.inference.run(outputNames); } @ReactMethod public void run(String[] outputNames, boolean enableStats) { this.inference.run(outputNames, enableStats); } @ReactMethod public double[] fetch(String outputName, int outputSize) { double[] dst = new double[outputSize]; this.inference.fetch(outputName, dst); return dst; } @ReactMethod public Graph graph() { return this.inference.graph(); } @ReactMethod public Operation graphOperation(String operationName) { return this.inference.graphOperation(operationName); } @ReactMethod public String stats() { return this.inference.getStatString(); } @ReactMethod public void close() { this.inference.close(); } }
package com.rnziparchive; import android.content.res.AssetFileDescriptor; import android.util.Log; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.DeviceEventManagerModule; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import net.lingala.zip4j.exception.ZipException; import net.lingala.zip4j.model.FileHeader; import net.lingala.zip4j.progress.ProgressMonitor; import net.lingala.zip4j.model.ZipParameters; import net.lingala.zip4j.util.Zip4jConstants; public class RNZipArchiveModule extends ReactContextBaseJavaModule { private static final String TAG = RNZipArchiveModule.class.getSimpleName(); private static final int BUFFER_SIZE = 4096; private static final String PROGRESS_EVENT_NAME = "zipArchiveProgressEvent"; private static final String EVENT_KEY_FILENAME = "filePath"; private static final String EVENT_KEY_PROGRESS = "progress"; public RNZipArchiveModule(ReactApplicationContext reactContext) { super(reactContext); } @Override public String getName() { return "RNZipArchive"; } @ReactMethod public void isPasswordProtected(final String zipFilePath, final Promise promise) { try { net.lingala.zip4j.core.ZipFile zipFile = new net.lingala.zip4j.core.ZipFile(zipFilePath); promise.resolve(zipFile.isEncrypted()); } catch (ZipException ex) { promise.reject(null, String.format("Unable to check for encryption due to: %s", getStackTrace(ex))); } } @ReactMethod public void unzipWithPassword(final String zipFilePath, final String destDirectory, final String password, final Promise promise) { new Thread(new Runnable() { @Override public void run() { try { net.lingala.zip4j.core.ZipFile zipFile = new net.lingala.zip4j.core.ZipFile(zipFilePath); if (zipFile.isEncrypted()) { zipFile.setPassword(password); } else { promise.reject(null, String.format("Zip file: %s is not password protected", zipFilePath)); } List fileHeaderList = zipFile.getFileHeaders(); List extractedFileNames = new ArrayList<>(); int totalFiles = fileHeaderList.size(); updateProgress(0, 1, zipFilePath); // force 0% for (int i = 0; i < totalFiles; i++) { FileHeader fileHeader = (FileHeader) fileHeaderList.get(i); zipFile.extractFile(fileHeader, destDirectory); if (!fileHeader.isDirectory()) { extractedFileNames.add(fileHeader.getFileName()); } updateProgress(i + 1, totalFiles, zipFilePath); } promise.resolve(Arguments.fromList(extractedFileNames)); } catch (ZipException ex) { updateProgress(0, 1, zipFilePath); // force 0% promise.reject(null, String.format("Failed to unzip file, due to: %s", getStackTrace(ex))); } } }).start(); } @ReactMethod public void unzip(final String zipFilePath, final String destDirectory, final Promise promise) { new Thread(new Runnable() { @Override public void run() { // Check the file exists FileInputStream inputStream = null; try { inputStream = new FileInputStream(zipFilePath); new File(zipFilePath); } catch (FileNotFoundException | NullPointerException e) { if (inputStream != null) { try { inputStream.close(); } catch (IOException ignored) { } } promise.reject(null, "Couldn't open file " + zipFilePath + ". "); return; } try { // Find the total uncompressed size of every file in the zip, so we can // get an accurate progress measurement final long totalUncompressedBytes = getUncompressedSize(zipFilePath); File destDir = new File(destDirectory); if (!destDir.exists()) { //noinspection ResultOfMethodCallIgnored destDir.mkdirs(); } updateProgress(0, 1, zipFilePath); // force 0% // We use arrays here so we can update values // from inside the callback final long[] extractedBytes = {0}; final int[] lastPercentage = {0}; final ZipFile zipFile = new ZipFile(zipFilePath); final Enumeration<? extends ZipEntry> entries = zipFile.entries(); Log.d(TAG, "Zip has " + zipFile.size() + " entries"); while (entries.hasMoreElements()) { final ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) continue; StreamUtil.ProgressCallback cb = new StreamUtil.ProgressCallback() { @Override public void onCopyProgress(long bytesRead) { extractedBytes[0] += bytesRead; int lastTime = lastPercentage[0]; int percentDone = (int) ((double) extractedBytes[0] * 100 / (double) totalUncompressedBytes); // update at most once per percent. if (percentDone > lastTime) { lastPercentage[0] = percentDone; updateProgress(extractedBytes[0], totalUncompressedBytes, zipFilePath); } } }; File fout = new File(destDirectory, entry.getName()); if (!fout.exists()) { //noinspection ResultOfMethodCallIgnored (new File(fout.getParent())).mkdirs(); } InputStream in = null; BufferedOutputStream Bout = null; try { in = zipFile.getInputStream(entry); Bout = new BufferedOutputStream(new FileOutputStream(fout)); StreamUtil.copy(in, Bout, cb); Bout.close(); in.close(); } catch (IOException ex) { if (in != null) { try { in.close(); } catch (Exception ignored) { } } if (Bout != null) { try { Bout.close(); } catch (Exception ignored) { } } } } zipFile.close(); updateProgress(1, 1, zipFilePath); // force 100% promise.resolve(destDirectory); } catch (Exception ex) { updateProgress(0, 1, zipFilePath); // force 0% promise.reject(null, "Failed to extract file " + ex.getLocalizedMessage()); } } }).start(); } /** * Extract a zip held in the assets directory. * <p> * Note that the progress value isn't as accurate as when unzipping * from a file. When reading a zip from a stream, we can't * get accurate uncompressed sizes for files (ZipEntry#getCompressedSize() returns -1). * <p> * Instead, we compare the number of bytes extracted to the size of the compressed zip file. * In most cases this means the progress 'stays on' 100% for a little bit (compressedSize < uncompressed size) */ @ReactMethod public void unzipAssets(final String assetsPath, final String destDirectory, final Promise promise) { new Thread(new Runnable() { @Override public void run() { InputStream assetsInputStream; final long size; try { assetsInputStream = getReactApplicationContext().getAssets().open(assetsPath); AssetFileDescriptor fileDescriptor = getReactApplicationContext().getAssets().openFd(assetsPath); size = fileDescriptor.getLength(); } catch (IOException e) { promise.reject(null, String.format("Asset file `%s` could not be opened", assetsPath)); return; } try { try { File destDir = new File(destDirectory); if (!destDir.exists()) { //noinspection ResultOfMethodCallIgnored destDir.mkdirs(); } ZipInputStream zipIn = new ZipInputStream(assetsInputStream); BufferedInputStream bin = new BufferedInputStream(zipIn); ZipEntry entry; final long[] extractedBytes = {0}; final int[] lastPercentage = {0}; updateProgress(0, 1, assetsPath); // force 0% File fout; while ((entry = zipIn.getNextEntry()) != null) { if (entry.isDirectory()) continue; fout = new File(destDirectory, entry.getName()); if (!fout.exists()) { //noinspection ResultOfMethodCallIgnored (new File(fout.getParent())).mkdirs(); } final ZipEntry finalEntry = entry; StreamUtil.ProgressCallback cb = new StreamUtil.ProgressCallback() { @Override public void onCopyProgress(long bytesRead) { extractedBytes[0] += bytesRead; int lastTime = lastPercentage[0]; int percentDone = (int) ((double) extractedBytes[0] * 100 / (double) size); // update at most once per percent. if (percentDone > lastTime) { lastPercentage[0] = percentDone; updateProgress(extractedBytes[0], size, finalEntry.getName()); } } }; FileOutputStream out = new FileOutputStream(fout); BufferedOutputStream Bout = new BufferedOutputStream(out); StreamUtil.copy(bin, Bout, cb); Bout.close(); out.close(); } updateProgress(1, 1, assetsPath); // force 100% bin.close(); zipIn.close(); } catch (Exception ex) { ex.printStackTrace(); updateProgress(0, 1, assetsPath); // force 0% throw new Exception(String.format("Couldn't extract %s", assetsPath)); } } catch (Exception ex) { promise.reject(null, ex.getMessage()); return; } promise.resolve(destDirectory); } }).start(); } @ReactMethod public void zip(String fileOrDirectory, String destDirectory, Promise promise) { List<String> filePaths = new ArrayList<>(); String fromDirectory; try { File tmp = new File(fileOrDirectory); if (tmp.exists()) { if (tmp.isDirectory()) { fromDirectory = fileOrDirectory; List<File> files = getSubFiles(tmp, true); for (int i = 0; i < files.size(); i++) { filePaths.add(files.get(i).getAbsolutePath()); } } else { fromDirectory = fileOrDirectory.substring(0, fileOrDirectory.lastIndexOf("/")); filePaths.add(fileOrDirectory); } } else { throw new FileNotFoundException(fileOrDirectory); } } catch (FileNotFoundException | NullPointerException e) { promise.reject(null, "Couldn't open file/directory " + fileOrDirectory + "."); return; } try { String[] filePathArray = filePaths.toArray(new String[filePaths.size()]); new ZipTask(filePathArray, destDirectory, fromDirectory, promise, this).zip(); } catch (Exception ex) { promise.reject(null, ex.getMessage()); return; } } @ReactMethod public void zipWithPassword(final String fileOrDirectory, final String destDirectory, final String password, final String encyptionMethod, final Promise promise) { new Thread(new Runnable() { @Override public void run() { try { net.lingala.zip4j.core.ZipFile zipFile = new net.lingala.zip4j.core.ZipFile(destDirectory); ZipParameters parameters = new ZipParameters(); parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); String encParts[] = encyptionMethod.split("-"); if (password != null && !password.isEmpty()) { parameters.setEncryptFiles(true); if (encParts[0].equals("AES")) { parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES); if (encParts[1].equals("128")) { parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_128); } else if (encParts[1].equals("256")) { parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256); } else { parameters.setAesKeyStrength(Zip4jConstants.ENC_METHOD_STANDARD); } } else if (encyptionMethod.equals("STANDARD")) { parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); Log.d(TAG, "Standard Encryption"); } else { parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); Log.d(TAG, "Encryption type not supported default to Standard Encryption"); } parameters.setPassword(password); } else { promise.reject(null, "Password is empty"); } updateProgress(0, 100, destDirectory); File f = new File(fileOrDirectory); int totalFiles = 0; int fileCounter = 0; if (f.exists()) { if (f.isDirectory()) { zipFile.addFolder(f.getAbsolutePath(), parameters); fileCounter += 1; List<File> files = getSubFiles(f, true); totalFiles = files.size() + 1; updateProgress(fileCounter, totalFiles, destDirectory); for (int i = 0; i < files.size(); i++) { if (files.get(i).isDirectory()) { zipFile.addFolder(f.getAbsolutePath(), parameters); fileCounter += 1; updateProgress(fileCounter, totalFiles, destDirectory); } else { zipFile.addFile(files.get(i), parameters); fileCounter += 1; updateProgress(fileCounter, totalFiles, destDirectory); } } } else { totalFiles = 1; zipFile.addFile(f, parameters); fileCounter += 1; updateProgress(fileCounter, totalFiles, destDirectory); } } else { promise.reject(null, "File or folder does not exist"); } updateProgress(1, 1, destDirectory); // force 100% promise.resolve(destDirectory); } catch (Exception ex) { promise.reject(null, ex.getMessage()); return; } } }).start(); } private List<File> getSubFiles(File baseDir, boolean isContainFolder) { List<File> fileList = new ArrayList<>(); File[] tmpList = baseDir.listFiles(); for (File file : tmpList) { if (file.isFile()) { fileList.add(file); } if (file.isDirectory()) { if (isContainFolder) { fileList.add(file); //key code } fileList.addAll(getSubFiles(file, isContainFolder)); } } return fileList; } protected void updateProgress(long extractedBytes, long totalSize, String zipFilePath) { // Ensure progress can't overflow 1 double progress = Math.min((double) extractedBytes / (double) totalSize, 1); Log.d(TAG, String.format("updateProgress: %.0f%%", progress * 100)); WritableMap map = Arguments.createMap(); map.putString(EVENT_KEY_FILENAME, zipFilePath); map.putDouble(EVENT_KEY_PROGRESS, progress); getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(PROGRESS_EVENT_NAME, map); } /** * Return the uncompressed size of the ZipFile (only works for files on disk, not in assets) * * @return -1 on failure */ private long getUncompressedSize(String zipFilePath) { long totalSize = 0; try { ZipFile zipFile = new ZipFile(zipFilePath); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); long size = entry.getSize(); if (size != -1) { totalSize += size; } } zipFile.close(); } catch (IOException ignored) { return -1; } return totalSize; } /** * Returns the exception stack trace as a string */ private String getStackTrace(Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); return sw.toString(); } }
package dog.craftz.sqlite_2; import com.facebook.react.bridge.NativeArray; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableType; import com.facebook.react.bridge.WritableNativeArray; import android.content.Context; import android.util.Log; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import android.os.Handler; import android.os.HandlerThread; import org.json.JSONArray; import org.json.JSONException; import java.io.File; import java.util.HashMap; import java.util.Map; public class RNSqlite2Module extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; private static final boolean DEBUG_MODE = false; private static final String TAG = RNSqlite2Module.class.getSimpleName(); private static final Object[][] EMPTY_ROWS = new Object[][]{}; private static final String[] EMPTY_COLUMNS = new String[]{}; private static final SQLitePLuginResult EMPTY_RESULT = new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, null); private static final Map<String, SQLiteDatabase> DATABASES = new HashMap<String, SQLiteDatabase>(); private final Handler writeHandler = createBackgroundHandler("WRITE"); private final Handler readHandler = createBackgroundHandler("READ"); /** * Linked activity */ protected Context context = null; public RNSqlite2Module(ReactApplicationContext reactContext) { super(reactContext); this.context = reactContext.getApplicationContext(); this.reactContext = reactContext; } @Override public String getName() { return "RNSqlite2"; } private Handler createBackgroundHandler(final String name) { HandlerThread thread = new HandlerThread("SQLitePlugin BG Handler for " + name); thread.start(); return new Handler(thread.getLooper()); } @ReactMethod public void exec(final String dbName, final ReadableArray queries, final Boolean readOnly, final Promise promise) { debug("exec called: %s", dbName); final int numQueries = queries.size(); boolean isAllSelectQuery = true; for (int i = 0; i < numQueries; i++) { ReadableArray sqlQuery = queries.getArray(i); String sql = sqlQuery.getString(0); if (!isSelect(sql)) { isAllSelectQuery = false; break; } } if (isAllSelectQuery) { readHandler.post(getQueryRunnable(true, dbName, queries, readOnly, promise)); } else { writeHandler.post(getQueryRunnable(false, dbName, queries, readOnly, promise)); } } private Runnable getQueryRunnable(final boolean isSelectOnly, final String dbName, final ReadableArray queries, final Boolean readOnly, final Promise promise) { return new Runnable() { @Override public void run() { try { final int numQueries = queries.size(); SQLitePLuginResult[] results = new SQLitePLuginResult[numQueries]; SQLiteDatabase db = getDatabase(dbName, isSelectOnly); for (int i = 0; i < numQueries; i++) { ReadableArray sqlQuery = queries.getArray(i); String sql = sqlQuery.getString(0); ReadableArray queryArgs = sqlQuery.getArray(1); try { if (isSelect(sql)) { results[i] = doSelectInBackgroundAndPossiblyThrow(sql, queryArgs, db); } else { // update/insert/delete if (readOnly) { results[i] = new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, new ReadOnlyException()); } else { results[i] = doUpdateInBackgroundAndPossiblyThrow(sql, queryArgs, db); } } } catch (Throwable e) { if (DEBUG_MODE) { e.printStackTrace(); } results[i] = new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, 0, 0, e); } } NativeArray data = pluginResultsToPrimitiveData(results); promise.resolve(data); } catch (Exception e) { promise.reject("SQLiteError", e); } } }; } // do a update/delete/insert operation private SQLitePLuginResult doUpdateInBackgroundAndPossiblyThrow(String sql, ReadableArray queryArgs, SQLiteDatabase db) throws IllegalArgumentException { debug("\"run\" query: %s", sql); SQLiteStatement statement = null; try { statement = db.compileStatement(sql); debug("compiled statement"); // Bind all of the arguments for (int i = 0; i < queryArgs.size(); i++) { ReadableType type = queryArgs.getType(i); switch (type) { case Null: statement.bindNull(i + 1); break; case Boolean: final long b = queryArgs.getBoolean(i) ? 1 : 0; statement.bindLong(i + 1, b); break; case Number: final double f = queryArgs.getDouble(i); statement.bindDouble(i + 1, f); break; case String: statement.bindString(i + 1, unescapeBlob(queryArgs.getString(i))); break; default: throw new IllegalArgumentException("Unexpected data type given"); } } debug("bound args"); if (isInsert(sql)) { debug("type: insert"); long insertId = statement.executeInsert(); int rowsAffected = insertId >= 0 ? 1 : 0; return new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, insertId, null); } else if (isDelete(sql) || isUpdate(sql)) { debug("type: update/delete"); int rowsAffected = statement.executeUpdateDelete(); return new SQLitePLuginResult(EMPTY_ROWS, EMPTY_COLUMNS, rowsAffected, 0, null); } else { // in this case, we don't need rowsAffected or insertId, so we can have a slight // perf boost by just executing the query debug("type: drop/create/etc."); statement.execute(); return EMPTY_RESULT; } } finally { if (statement != null) { statement.close(); } } } // do a select operation private SQLitePLuginResult doSelectInBackgroundAndPossiblyThrow(String sql, ReadableArray queryArgs, SQLiteDatabase db) { debug("\"all\" query: %s", sql); Cursor cursor = null; try { String[] bindArgs = convertParamsToStringArray(queryArgs); cursor = db.rawQuery(sql, bindArgs); int numRows = cursor.getCount(); if (numRows == 0) { return EMPTY_RESULT; } int numColumns = cursor.getColumnCount(); Object[][] rows = new Object[numRows][]; String[] columnNames = cursor.getColumnNames(); for (int i = 0; cursor.moveToNext(); i++) { Object[] row = new Object[numColumns]; for (int j = 0; j < numColumns; j++) { row[j] = getValueFromCursor(cursor, j, cursor.getType(j)); } rows[i] = row; } debug("returning %d rows", numRows); return new SQLitePLuginResult(rows, columnNames, 0, 0, null); } finally { if (cursor != null) { cursor.close(); } } } private Object getValueFromCursor(Cursor cursor, int index, int columnType) { switch (columnType) { case Cursor.FIELD_TYPE_FLOAT: return cursor.getDouble(index); case Cursor.FIELD_TYPE_INTEGER: return cursor.getLong(index); case Cursor.FIELD_TYPE_BLOB: // convert byte[] to binary string; it's good enough, because // WebSQL doesn't support blobs anyway return new String(cursor.getBlob(index)); case Cursor.FIELD_TYPE_STRING: return cursor.getString(index); } return null; } private SQLiteDatabase getDatabase(String name, final boolean isReadOnly) { final String accessTypeName = isReadOnly ? "-read" : "-write"; SQLiteDatabase database = DATABASES.get(name + accessTypeName); if (database == null) { if (":memory:".equals(name)) { database = SQLiteDatabase.openOrCreateDatabase(name, null); } else { File file = new File(this.context.getFilesDir(), name); database = SQLiteDatabase.openOrCreateDatabase(file, null); } DATABASES.put(name + accessTypeName, database); } return database; } private static void debug(String line, Object... format) { if (DEBUG_MODE) { Log.d(TAG, String.format(line, format)); } } private static NativeArray pluginResultsToPrimitiveData(SQLitePLuginResult[] results) { WritableNativeArray list = new WritableNativeArray(); for (int i = 0; i < results.length; i++) { SQLitePLuginResult result = results[i]; WritableNativeArray arr = convertPluginResultToArray(result); list.pushArray(arr); } return list; } private static WritableNativeArray convertPluginResultToArray(SQLitePLuginResult result) { WritableNativeArray data = new WritableNativeArray(); if (result.error != null) { data.pushString(result.error.getMessage()); } else { data.pushNull(); } data.pushInt((int) result.insertId); data.pushInt(result.rowsAffected); // column names WritableNativeArray columnNames = new WritableNativeArray(); for (int i = 0; i < result.columns.length; i++) { columnNames.pushString(result.columns[i]); } data.pushArray(columnNames); // rows WritableNativeArray rows = new WritableNativeArray(); for (int i = 0; i < result.rows.length; i++) { Object[] values = result.rows[i]; // row content WritableNativeArray rowContent = new WritableNativeArray(); for (int j = 0; j < values.length; j++) { Object value = values[j]; if (value == null) { rowContent.pushNull(); } else if (value instanceof String) { rowContent.pushString((String)value); } else if (value instanceof Boolean) { rowContent.pushBoolean((Boolean)value); } else { Number v = (Number)value; rowContent.pushDouble(v.doubleValue()); } } rows.pushArray(rowContent); } data.pushArray(rows); return data; } private static boolean isSelect(String str) { return startsWithCaseInsensitive(str, "select"); } private static boolean isInsert(String str) { return startsWithCaseInsensitive(str, "insert"); } private static boolean isUpdate(String str) { return startsWithCaseInsensitive(str, "update"); } private static boolean isDelete(String str) { return startsWithCaseInsensitive(str, "delete"); } // identify an "insert"/"select" query more efficiently than with a Pattern private static boolean startsWithCaseInsensitive(String str, String substr) { int i = -1; int len = str.length(); while (++i < len) { char ch = str.charAt(i); if (!Character.isWhitespace(ch)) { break; } } int j = -1; int substrLen = substr.length(); while (++j < substrLen) { if (j + i >= len) { return false; } char ch = str.charAt(j + i); if (Character.toLowerCase(ch) != substr.charAt(j)) { return false; } } return true; } private static String[] jsonArrayToStringArray(String jsonArray) throws JSONException { JSONArray array = new JSONArray(jsonArray); int len = array.length(); String[] res = new String[len]; for (int i = 0; i < len; i++) { res[i] = array.getString(i); } return res; } private static String[] convertParamsToStringArray(ReadableArray paramArray) { int len = paramArray.size(); String[] res = new String[len]; for (int i = 0; i < len; i++) { ReadableType type = paramArray.getType(i); if (type == ReadableType.String) { String unescaped = unescapeBlob(paramArray.getString(i)); res[i] = unescaped; } else if (type == ReadableType.Boolean) { res[i] = paramArray.getBoolean(i) ? "0" : "1"; } else if (type == ReadableType.Null) { res[i] = "NULL"; } else if (type == ReadableType.Number) { res[i] = Double.toString(paramArray.getDouble(i)); } } return res; } private static String unescapeBlob(String str) { return str.replaceAll("\u0001\u0001", "\u0000") .replaceAll("\u0001\u0002", "\u0001") .replaceAll("\u0002\u0002", "\u0002"); } private static class SQLitePLuginResult { public final Object[][] rows; public final String[] columns; public final int rowsAffected; public final long insertId; public final Throwable error; public SQLitePLuginResult(Object[][] rows, String[] columns, int rowsAffected, long insertId, Throwable error) { this.rows = rows; this.columns = columns; this.rowsAffected = rowsAffected; this.insertId = insertId; this.error = error; } } private static class ReadOnlyException extends Exception { public ReadOnlyException() { super("could not prepare statement (23 not authorized)"); } } }
package rtdc.android.impl; import android.content.Intent; import rtdc.android.AdminActivity; import rtdc.android.Rtdc; import rtdc.android.presenter.ActionPlanActivity; import rtdc.android.presenter.CreateUnitActivity; import rtdc.android.presenter.CreateActionActivity; import rtdc.android.presenter.LoginActivity; import rtdc.core.impl.Dispatcher; public class AndroidDispatcher implements Dispatcher { @Override public void goToLogin() { Intent intent = new Intent(Rtdc.getAppContext(), LoginActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Rtdc.getAppContext().startActivity(intent); } @Override public void goToAllUnits() { Intent intent = new Intent(Rtdc.getAppContext(), AdminActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Rtdc.getAppContext().startActivity(intent); } @Override public void goToActionPlan() { Intent intent = new Intent(Rtdc.getAppContext(), ActionPlanActivity.class); Rtdc.getAppContext().startActivity(intent); } @Override public void goToUnitInfo() { Intent intent = new Intent(Rtdc.getAppContext(), CreateUnitActivity.class); Rtdc.getAppContext().startActivity(intent); } @Override public void goToEditAction() { Intent intent = new Intent(Rtdc.getAppContext(), CreateActionActivity.class); Rtdc.getAppContext().startActivity(intent); } }
package nl.weeaboo.styledtext.layout; import java.text.Bidi; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import nl.weeaboo.styledtext.ETextAttribute; import nl.weeaboo.styledtext.StyledText; import nl.weeaboo.styledtext.TextStyle; public final class LayoutUtil { private static final float EPSILON = .001f; private static final char NON_BREAKING_SPACE = 0x00A0; private static final char FIGURE_SPACE = 0x2007; private static final char NARROW_NO_BREAK_SPACE = 0x202F; private static final char WORD_JOINER = 0x2060; private static final char ZERO_WIDTH_NO_BREAK_SPACE = 0xFEFF; private LayoutUtil() { } /** * @param c A Unicode codepoint * @return {@code true} if the codepoint represents non-breaking whitespace */ public static boolean isNonBreakingSpace(int c) { return c == NON_BREAKING_SPACE || c == FIGURE_SPACE || c == NARROW_NO_BREAK_SPACE || c == WORD_JOINER || c == ZERO_WIDTH_NO_BREAK_SPACE; } public static boolean hasMultipleStyles(StyledText stext) { if (stext.length() <= 1) { // Text isn't long enough to be able to contain multiple styles return false; } TextStyle ref = stext.getStyle(0); for (int n = 1; n < stext.length(); n++) { TextStyle ts = stext.getStyle(n); if (ref != ts && (ref == null || !ref.equals(ts))) { return true; } } return false; } public static ITextLayout layout(IFontStore fontStore, StyledText stext, LayoutParameters params) { TextLayoutAlgorithm algo = new TextLayoutAlgorithm(fontStore); return algo.layout(stext, params); } /** * @param pos Number of currently visible glyphs. The fractional part of the number represents partial * visibility of the next glyph. * @param inc Increase the visible glyphs by this amount. * @return The new number of visible glyphs. */ public static float increaseVisibleCharacters(IGlyphSequence glyphs, float pos, float inc) { pos = Math.max(0, pos); while (pos < glyphs.getGlyphCount() && inc > EPSILON) { int ipos = (int)pos; float fracLeft = (ipos + 1) - pos; float glyphDuration = getDuration(glyphs.getGlyphStyle(ipos)); if (fracLeft >= 1f && inc >= glyphDuration) { // Fast case: move ahead a full glyph from an integer pos pos = ipos + 1; inc -= glyphDuration; } else { // Move ahead a partial glyph pos += Math.min(fracLeft, inc / glyphDuration); inc -= fracLeft * glyphDuration; } } return pos; } private static float getDuration(TextStyle style) { if (style == null || !style.hasProperty(ETextAttribute.SPEED)) { return 1f; } return 1f / style.getSpeed(); } static float getKerningOffset(ILayoutElement a, ILayoutElement b) { if (!(a instanceof ITextElement) || !(b instanceof IGlyphSequence)) { return 0f; } ITextElement textA = (ITextElement)a; IGlyphSequence textB = (IGlyphSequence)b; if (textB.getGlyphCount() == 0) { return 0f; } return textA.getKerning(textB.getGlyphId(0)); } static int getGlyphCount(ILayoutElement elem) { if (elem instanceof IGlyphSequence) { IGlyphSequence seq = (IGlyphSequence)elem; return seq.getGlyphCount(); } return 0; } static List<ILayoutElement> visualSortedCopy(List<ILayoutElement> elems) { ILayoutElement[] elemsArray = new ILayoutElement[elems.size()]; byte[] bidiLevels = new byte[elemsArray.length]; int t = 0; for (ILayoutElement elem : elems) { elemsArray[t] = elem; bidiLevels[t] = 0; if (elem instanceof ITextElement) { ITextElement textElem = (ITextElement)elem; bidiLevels[t] = (byte)textElem.getBidiLevel(); } t++; } Bidi.reorderVisually(bidiLevels, 0, elemsArray, 0, elemsArray.length); return Arrays.asList(elemsArray); } /** Filters layout elements by type */ static <T extends ILayoutElement> List<T> getLayoutElements(List<ILayoutElement> elems, Class<T> type) { List<T> result = new ArrayList<T>(elems.size()); for (ILayoutElement elem : elems) { if (type.isInstance(elem)) { result.add(type.cast(elem)); } } return result; } public static boolean isRightToLeftLevel(int bidiLevel) { return (bidiLevel & 1) != 0; } public static int getVisibleLines(ITextLayout layout, int startLine, float maxHeight) { final int lineCount = layout.getLineCount(); if (maxHeight <= 0) { return lineCount; } startLine = Math.max(0, Math.min(lineCount, startLine)); int endLine = startLine; while (endLine < lineCount && layout.getTextHeight(startLine, endLine + 1) <= maxHeight) { endLine++; } // Always show at least one line (prevents text from disappearing if its bounds are too small) return Math.max(1, endLine - startLine); } }
/* GodotIO.java */ /* This file is part of: */ /* GODOT ENGINE */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* included in all copies or substantial portions of the Software. */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.godotengine.godot; import org.godotengine.godot.input.*; import android.app.Activity; import android.content.*; import android.content.pm.ActivityInfo; import android.content.res.AssetManager; import android.graphics.Point; import android.net.Uri; import android.os.*; import android.util.DisplayMetrics; import android.util.Log; import android.util.SparseArray; import android.view.Display; import android.view.DisplayCutout; import android.view.WindowInsets; import java.io.IOException; import java.io.InputStream; import java.util.Locale; // Wrapper for native library public class GodotIO { AssetManager am; final Activity activity; GodotEditText edit; final int SCREEN_LANDSCAPE = 0; final int SCREEN_PORTRAIT = 1; final int SCREEN_REVERSE_LANDSCAPE = 2; final int SCREEN_REVERSE_PORTRAIT = 3; final int SCREEN_SENSOR_LANDSCAPE = 4; final int SCREEN_SENSOR_PORTRAIT = 5; final int SCREEN_SENSOR = 6; /// FILES public int last_file_id = 1; static class AssetData { public boolean eof = false; public String path; public InputStream is; public int len; public int pos; } SparseArray<AssetData> streams; public int file_open(String path, boolean write) { //System.out.printf("file_open: Attempt to Open %s\n",path); //Log.v("MyApp", "TRYING TO OPEN FILE: " + path); if (write) return -1; AssetData ad = new AssetData(); try { ad.is = am.open(path); } catch (Exception e) { //System.out.printf("Exception on file_open: %s\n",path); return -1; } try { ad.len = ad.is.available(); } catch (Exception e) { System.out.printf("Exception availabling on file_open: %s\n", path); return -1; } ad.path = path; ad.pos = 0; ++last_file_id; streams.put(last_file_id, ad); return last_file_id; } public int file_get_size(int id) { if (streams.get(id) == null) { System.out.printf("file_get_size: Invalid file id: %d\n", id); return -1; } return streams.get(id).len; } public void file_seek(int id, int bytes) { if (streams.get(id) == null) { System.out.printf("file_get_size: Invalid file id: %d\n", id); return; } //seek sucks AssetData ad = streams.get(id); if (bytes > ad.len) bytes = ad.len; if (bytes < 0) bytes = 0; try { if (bytes > (int)ad.pos) { int todo = bytes - (int)ad.pos; while (todo > 0) { todo -= ad.is.skip(todo); } ad.pos = bytes; } else if (bytes < (int)ad.pos) { ad.is = am.open(ad.path); ad.pos = bytes; int todo = bytes; while (todo > 0) { todo -= ad.is.skip(todo); } } ad.eof = false; } catch (IOException e) { System.out.printf("Exception on file_seek: %s\n", e); return; } } public int file_tell(int id) { if (streams.get(id) == null) { System.out.printf("file_read: Can't tell eof for invalid file id: %d\n", id); return 0; } AssetData ad = streams.get(id); return ad.pos; } public boolean file_eof(int id) { if (streams.get(id) == null) { System.out.printf("file_read: Can't check eof for invalid file id: %d\n", id); return false; } AssetData ad = streams.get(id); return ad.eof; } public byte[] file_read(int id, int bytes) { if (streams.get(id) == null) { System.out.printf("file_read: Can't read invalid file id: %d\n", id); return new byte[0]; } AssetData ad = streams.get(id); if (ad.pos + bytes > ad.len) { bytes = ad.len - ad.pos; ad.eof = true; } if (bytes == 0) { return new byte[0]; } byte[] buf1 = new byte[bytes]; int r = 0; try { r = ad.is.read(buf1); } catch (IOException e) { System.out.printf("Exception on file_read: %s\n", e); return new byte[bytes]; } if (r == 0) { return new byte[0]; } ad.pos += r; if (r < bytes) { byte[] buf2 = new byte[r]; for (int i = 0; i < r; i++) buf2[i] = buf1[i]; return buf2; } else { return buf1; } } public void file_close(int id) { if (streams.get(id) == null) { System.out.printf("file_close: Can't close invalid file id: %d\n", id); return; } streams.remove(id); } /// DIRECTORIES static class AssetDir { public String[] files; public int current; public String path; } public int last_dir_id = 1; SparseArray<AssetDir> dirs; public int dir_open(String path) { AssetDir ad = new AssetDir(); ad.current = 0; ad.path = path; try { ad.files = am.list(path); // no way to find path is directory or file exactly. // but if ad.files.length==0, then it's an empty directory or file. if (ad.files.length == 0) { return -1; } } catch (IOException e) { System.out.printf("Exception on dir_open: %s\n", e); return -1; } //System.out.printf("Opened dir: %s\n",path); ++last_dir_id; dirs.put(last_dir_id, ad); return last_dir_id; } public boolean dir_is_dir(int id) { if (dirs.get(id) == null) { System.out.printf("dir_next: invalid dir id: %d\n", id); return false; } AssetDir ad = dirs.get(id); //System.out.printf("go next: %d,%d\n",ad.current,ad.files.length); int idx = ad.current; if (idx > 0) idx if (idx >= ad.files.length) return false; String fname = ad.files[idx]; try { if (ad.path.equals("")) am.open(fname); else am.open(ad.path + "/" + fname); return false; } catch (Exception e) { return true; } } public String dir_next(int id) { if (dirs.get(id) == null) { System.out.printf("dir_next: invalid dir id: %d\n", id); return ""; } AssetDir ad = dirs.get(id); //System.out.printf("go next: %d,%d\n",ad.current,ad.files.length); if (ad.current >= ad.files.length) { ad.current++; return ""; } String r = ad.files[ad.current]; ad.current++; return r; } public void dir_close(int id) { if (dirs.get(id) == null) { System.out.printf("dir_close: invalid dir id: %d\n", id); return; } dirs.remove(id); } GodotIO(Activity p_activity) { am = p_activity.getAssets(); activity = p_activity; //streams = new HashMap<Integer, AssetData>(); streams = new SparseArray<>(); dirs = new SparseArray<>(); } // MISCELLANEOUS OS IO public int openURI(String p_uri) { try { Log.v("MyApp", "TRYING TO OPEN URI: " + p_uri); String path = p_uri; String type = ""; if (path.startsWith("/")) { //absolute path to filesystem, prepend file:// path = "file://" + path; if (p_uri.endsWith(".png") || p_uri.endsWith(".jpg") || p_uri.endsWith(".gif") || p_uri.endsWith(".webp")) {
package org.xins.server; import org.apache.log4j.Logger; import org.xins.util.MandatoryArgumentChecker; import org.xins.util.text.FastStringBuffer; /** * Base class for function implementation classes. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ public abstract class Function extends Object implements DefaultResultCodes { // Class fields // Class functions /** * Checks if the specified value is <code>null</code> or an empty string. * Only if it is then <code>true</code> is returned. * * @param value * the value to check. * * @return * <code>true</code> if and only if <code>value == null || * value.length() == 0</code>. */ protected static final boolean isMissing(String value) { return value == null || value.length() == 0; } // Constructors protected Function(API api, String name, String version) throws IllegalArgumentException { // Check argument MandatoryArgumentChecker.check("api", api, "name", name, "version", version); _log = Logger.getLogger(getClass().getName()); _api = api; _name = name; _version = version; _api.functionAdded(this); } // Fields /** * The logger used by this function. This field is initialized by the * constructor and set to a non-<code>null</code> value. */ private final Logger _log; /** * The API implementation this function is part of. */ private final API _api; /** * The name of this function. */ private final String _name; /** * The version of the specification this function implements. */ private final String _version; /** * Lock object for <code>_callCount</code>. */ private final Object _callCountLock = new Object(); /** * The total number of calls executed up until now. */ private int _callCount; /** * Statistics object linked to this function. */ private final Statistics _statistics = new Statistics(); /** * Lock object for a successful call. */ private final Object _successfulCallLock = new Object(); /** * Lock object for an unsuccessful call. */ private final Object _unsuccessfulCallLock = new Object(); /** * Buffer for log messages for successful calls. This field is * initialized at construction time and cannot be <code>null</code>. */ private final FastStringBuffer _successfulCallStringBuffer = new FastStringBuffer(256); /** * Buffer for log messages for unsuccessful calls. This field is * initialized at construction time and cannot be <code>null</code>. */ private final FastStringBuffer _unsuccessfulCallStringBuffer = new FastStringBuffer(256); /** * The number of successful calls executed up until now. */ private int _successfulCalls; /** * The number of unsuccessful calls executed up until now. */ private int _unsuccessfulCalls; /** * The start time of the most recent successful call. */ private long _lastSuccessfulStart; /** * The start time of the most recent unsuccessful call. */ private long _lastUnsuccessfulStart; /** * The duration of the most recent successful call. */ private long _lastSuccessfulDuration; /** * The duration of the most recent unsuccessful call. */ private long _lastUnsuccessfulDuration; /** * The total duration of all successful calls up until now. */ private long _successfulDuration; /** * The total duration of all unsuccessful calls up until now. */ private long _unsuccessfulDuration; /** * The minimum time a successful call took. */ private long _successfulMin = Long.MAX_VALUE; /** * The minimum time an unsuccessful call took. */ private long _unsuccessfulMin = Long.MAX_VALUE; /** * The maximum time a successful call took. */ private long _successfulMax; /** * The maximum time an unsuccessful call took. */ private long _unsuccessfulMax; // Methods /** * Returns the logger associated with this function. * * @return * the associated logger, constant, and cannot be <code>null</code>. */ final Logger getLogger() { return _log; } /** * Returns the name of this function. * * @return * the name, not <code>null</code>. */ final String getName() { return _name; } /** * Returns the specification version for this function. * * @return * the version, not <code>null</code>. */ final String getVersion() { return _version; } /** * Returns the call statistics for this function. * * @return * the statistics, never <code>null</code>. */ final Statistics getStatistics() { return _statistics; } /** * Assigns a new call ID for the caller. Every call to this method will * return an increasing number. * * @return * the assigned call ID, &gt;= 0. */ final int assignCallID() { synchronized (_callCountLock) { return _callCount++; } } /** * Handles a call to this function. * * @param context * the context for this call, never <code>null</code>. * * @throws Throwable * if anything goes wrong. */ protected abstract void handleCall(CallContext context) throws Throwable; /** * Callback method that may be called after a call to this function. This * method will store statistics-related information. * * <p />This method does not <em>have</em> to be called. If statistics * gathering is disabled, then this method should not be called. * * @param context * the used call context, not <code>null</code>. * * @param success * indication if the call was successful. * * @param code * the function result code, or <code>null</code>. * * @deprecated * Deprecated since XINS 0.32. Use * {@link #performedCall(CallContext,ResultCode)} instead. */ final void performedCall(CallContext context, boolean success, String code) { long start = context.getStart(); long duration = System.currentTimeMillis() - start; boolean debugEnabled = context.isDebugEnabled(); String message = null; if (success) { if (debugEnabled) { synchronized (_successfulCallStringBuffer) { _successfulCallStringBuffer.clear(); _successfulCallStringBuffer.append("Call succeeded. Duration: "); _successfulCallStringBuffer.append(String.valueOf(duration)); _successfulCallStringBuffer.append(" ms."); if (code != null) { _successfulCallStringBuffer.append(" Code: \""); _successfulCallStringBuffer.append(code); _successfulCallStringBuffer.append("\"."); } message = _successfulCallStringBuffer.toString(); } } synchronized (_successfulCallLock) { _lastSuccessfulStart = start; _lastSuccessfulDuration = duration; _successfulCalls++; _successfulDuration += duration; _successfulMin = _successfulMin > duration ? duration : _successfulMin; _successfulMax = _successfulMax < duration ? duration : _successfulMax; } } else { if (debugEnabled) { synchronized (_unsuccessfulCallStringBuffer) { _unsuccessfulCallStringBuffer.clear(); _unsuccessfulCallStringBuffer.append("Call failed. Duration: "); _unsuccessfulCallStringBuffer.append(String.valueOf(duration)); _unsuccessfulCallStringBuffer.append(" ms."); if (code != null) { _unsuccessfulCallStringBuffer.append(" Code: \""); _unsuccessfulCallStringBuffer.append(code); _unsuccessfulCallStringBuffer.append("\"."); } message = _unsuccessfulCallStringBuffer.toString(); } } synchronized (_unsuccessfulCallLock) { _lastUnsuccessfulStart = start; _lastUnsuccessfulDuration = duration; _unsuccessfulCalls++; _unsuccessfulDuration += duration; _unsuccessfulMin = _unsuccessfulMin > duration ? duration : _unsuccessfulMin; _unsuccessfulMax = _unsuccessfulMax < duration ? duration : _unsuccessfulMax; } } if (debugEnabled) { context.debug(message); } } /** * Callback method that may be called after a call to this function. This * method will store statistics-related information. * * <p />This method does not <em>have</em> to be called. If statistics * gathering is disabled, then this method should not be called. * * @param context * the used call context, not <code>null</code>. * * @param code * the function result code, or <code>null</code>. * * @since XINS 0.32 */ final void performedCall(CallContext context, ResultCode code) { if (code == null) { performedCall(context, true, null); } else { performedCall(context, code.getSuccess(), code.getValue()); } } // Inner classes /** * Call statistics pertaining to a certain function. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:znerd@FreeBSD.org">znerd@FreeBSD.org</a>) */ final class Statistics extends Object { // Constructors /** * Constructs a new <code>Statistics</code> object. */ private Statistics() { // empty } // Fields // Methods /** * Returns the number of successful calls executed up until now. * * @return * the number of successful calls executed up until now. */ public int getSuccessfulCalls() { return _successfulCalls; } /** * Returns the number of unsuccessful calls executed up until now. * * @return * the number of unsuccessful calls executed up until now. */ public int getUnsuccessfulCalls() { return _unsuccessfulCalls; } /** * Returns the start time of the most recent successful call. * * @return * the start time of the most recent successful call. */ public long getLastSuccessfulStart() { return _lastSuccessfulStart; } /** * Returns the start time of the most recent unsuccessful call. * * @return * the start time of the most recent unsuccessful call. */ public long getLastUnsuccessfulStart() { return _lastUnsuccessfulStart; } /** * Returns the duration of the most recent successful call. * * @return * the duration of the most recent successful call. */ public long getLastSuccessfulDuration() { return _lastSuccessfulDuration; } /** * Returns the duration of the most recent unsuccessful call. * * @return * the duration of the most recent unsuccessful call. */ public long getLastUnsuccessfulDuration() { return _unsuccessfulDuration; } /** * Returns the total duration of all successful calls up until now. * * @return * the total duration of all successful calls up until now. */ public long getSuccessfulDuration() { return _successfulDuration; } /** * Returns the total duration of all unsuccessful calls up until now. * * @return * the total duration of all unsuccessful calls up until now. */ public long getUnsuccessfulDuration() { return _unsuccessfulDuration; } /** * Returns the minimum time a successful call took. * * @return * the minimum time a successful call took. */ public long getSuccessfulMin() { return _successfulMin; } /** * Returns the minimum time an unsuccessful call took. * * @return * the minimum time an unsuccessful call took. */ public long getUnsuccessfulMin() { return _unsuccessfulMin; } /** * Returns the maximum time a successful call took. * * @return * the maximum time a successful call took. */ public long getSuccessfulMax() { return _successfulMax; } /** * Returns the maximum time an unsuccessful call took. * * @return * the maximum time an unsuccessful call took. */ public long getUnsuccessfulMax() { return _unsuccessfulMax; } } }
package com.intellij.ui.jcef; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.LightEditActionFactory; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SystemInfo; import com.intellij.ui.JBColor; import com.jetbrains.cef.JCefAppConfig; import com.jetbrains.cef.JCefVersionDetails; import org.cef.CefClient; import org.cef.browser.CefBrowser; import org.cef.browser.CefFrame; import org.cef.callback.CefContextMenuParams; import org.cef.callback.CefMenuModel; import org.cef.handler.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import static com.intellij.ui.jcef.JBCefEventUtils.convertCefKeyEvent; import static com.intellij.ui.jcef.JBCefEventUtils.isUpDownKeyEvent; import static org.cef.callback.CefMenuModel.MenuId.MENU_ID_USER_LAST; /** * A wrapper over {@link CefBrowser}. * <p> * Use {@link #getComponent()} as the browser's UI component. * <p> * Use {@link #loadURL(String)} or {@link #loadHTML(String)} for loading. * <p> * Use {@link JBCefOsrHandlerBrowser} to render offscreen via a custom {@link CefRenderHandler}. * * @see JBCefOsrHandlerBrowser * @author tav */ @SuppressWarnings("unused") public class JBCefBrowser extends JBCefBrowserBase { /** * Defines whether the browser component should take focus on navigation (loading a new URL). * <p></p> * Accepts {@link Boolean} values. The default value is {@link Boolean#FALSE}. * * @see #setProperty(String, Object) */ @NotNull public static final String FOCUS_ON_NAVIGATION = "JBCefBrowser.focusOnNavigation"; /** * Defines whether the browser component should take focus on show. * <p></p> * Accepts {@link Boolean} values. The default value is {@link Boolean#FALSE}. * * @see #setProperty(String, Object) */ @NotNull public static final String FOCUS_ON_SHOW = "JBCefBrowser.focusOnShow"; private static final @NotNull List<Consumer<? super JBCefBrowser>> ourOnBrowserMoveResizeCallbacks = Collections.synchronizedList(new ArrayList<>(1)); private static final @NotNull Dimension DEF_PREF_SIZE = new Dimension(800, 600); private static final class ShortcutProvider { // Since these CefFrame::* methods are available only with JCEF API 1.1 and higher, we are adding no shortcuts for older JCEF private static final List<Pair<String, AnAction>> ourActions = isSupportedByJCefApi() ? List.of( createAction("$Cut", CefFrame::cut), createAction("$Copy", CefFrame::copy), createAction("$Paste", CefFrame::paste), createAction("$Delete", CefFrame::delete), createAction("$SelectAll", CefFrame::selectAll), createAction("$Undo", CefFrame::undo), createAction("$Redo", CefFrame::redo) ) : List.of(); // This method may be deleted when JCEF API version check is included into JBCefApp#isSupported private static boolean isSupportedByJCefApi() { try { /* getVersionDetails() was introduced alongside JCEF API versioning with first version of 1.1, which also added these necessary * for shortcuts to work CefFrame methods. Therefore successful call to getVersionDetails() means our JCEF API is at least 1.1 */ JCefAppConfig.getVersionDetails(); return true; } catch (NoSuchMethodError | JCefVersionDetails.VersionUnavailableException e) { Logger.getInstance(ShortcutProvider.class).warn("JCEF shortcuts are unavailable (incompatible API)", e); return false; } } private static Pair<String, AnAction> createAction(String shortcut, Consumer<? super CefFrame> action) { return Pair.create( shortcut, LightEditActionFactory.create(event -> { Component component = event.getData(PlatformDataKeys.CONTEXT_COMPONENT); if (component == null) return; Component parentComponent = component.getParent(); if (!(parentComponent instanceof JComponent)) return; Object browser = ((JComponent)parentComponent).getClientProperty(JBCEFBROWSER_INSTANCE_PROP); if (!(browser instanceof JBCefBrowser)) return; action.accept(((JBCefBrowser) browser).getCefBrowser().getFocusedFrame()); }) ); } private static void registerShortcuts(JComponent uiComp, JBCefBrowser jbCefBrowser) { ActionManager actionManager = ActionManager.getInstance(); for (Pair<String, AnAction> action : ourActions) { action.second.registerCustomShortcutSet(actionManager.getAction(action.first).getShortcutSet(), uiComp, jbCefBrowser); } } } private final @NotNull JPanel myComponent; private final @NotNull CefFocusHandler myCefFocusHandler; private final @NotNull CefKeyboardHandler myKeyboardHandler; private JDialog myDevtoolsFrame = null; protected CefContextMenuHandler myDefaultContextMenuHandler; private volatile boolean myFirstShow = true; /** * Creates a browser with the provided {@code JBCefClient} and initial URL. The client's lifecycle is the responsibility of the caller. */ public JBCefBrowser(@NotNull JBCefClient client, @Nullable String url) { this(client, false, url); } public JBCefBrowser(@NotNull CefBrowser cefBrowser, @NotNull JBCefClient client) { this(cefBrowser, client, false, null); } private JBCefBrowser(@NotNull JBCefClient client, boolean isDefaultClient, @Nullable String url) { this(null, client, isDefaultClient, url); } private JBCefBrowser(@Nullable CefBrowser cefBrowser, @NotNull JBCefClient client, boolean isDefaultClient, @Nullable String url) { super(client, createBrowser(cefBrowser, client.getCefClient(), url), cefBrowser == null, isDefaultClient); if (client.isDisposed()) { throw new IllegalArgumentException("JBCefClient is disposed"); } myComponent = createComponent(); myCefClient.addFocusHandler(myCefFocusHandler = new CefFocusHandlerAdapter() { @Override public boolean onSetFocus(CefBrowser browser, FocusSource source) { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); boolean componentFocused = focusOwner == getComponent() || focusOwner == getCefBrowser().getUIComponent(); boolean focusOnNavigation = (myFirstShow && Boolean.TRUE.equals(getProperty(FOCUS_ON_SHOW))) || Boolean.TRUE.equals(getProperty(FOCUS_ON_NAVIGATION)) || componentFocused; myFirstShow = false; if (source == FocusSource.FOCUS_SOURCE_NAVIGATION && !focusOnNavigation) { if (SystemInfo.isWindows) { myCefBrowser.setFocus(false); } return true; // suppress focusing the browser on navigation events } if (!browser.getUIComponent().hasFocus()) { if (SystemInfo.isLinux) { browser.getUIComponent().requestFocus(); } else { browser.getUIComponent().requestFocusInWindow(); } } return false; } }, myCefBrowser); myCefClient.addKeyboardHandler(myKeyboardHandler = new CefKeyboardHandlerAdapter() { @Override public boolean onKeyEvent(CefBrowser browser, CefKeyEvent cefKeyEvent) { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); boolean consume = focusOwner != browser.getUIComponent(); if (consume && SystemInfo.isMac && isUpDownKeyEvent(cefKeyEvent)) return true; // consume Window focusedWindow = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); if (focusedWindow == null) { return true; // consume } KeyEvent javaKeyEvent = convertCefKeyEvent(cefKeyEvent, focusedWindow); Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(javaKeyEvent); return consume; } }, myCefBrowser); myDefaultContextMenuHandler = createDefaultContextMenuHandler(); myCefClient.addContextMenuHandler(myDefaultContextMenuHandler, this.getCefBrowser()); } // New API is not available in JBR yet @SuppressWarnings("deprecation") private static @NotNull CefBrowser createBrowser(@Nullable CefBrowser cefBrowser, @NotNull CefClient client, @Nullable String url) { // Uncomment when new JBR would arrive // CefRendering mode = JBCefApp.isOffScreenRenderingMode() ? CefRendering.OFFSCREEN : CefRendering.DEFAULT; boolean mode = JBCefApp.isOffScreenRenderingMode(); return cefBrowser != null ? cefBrowser : client.createBrowser(url != null ? url : BLANK_URI, mode, false, null); } protected DefaultCefContextMenuHandler createDefaultContextMenuHandler() { boolean isInternal = ApplicationManager.getApplication().isInternal(); return new DefaultCefContextMenuHandler(isInternal); } private @NotNull JPanel createComponent() { Component uiComp = getCefBrowser().getUIComponent(); JPanel resultPanel = new JPanel(new BorderLayout()) { { enableEvents(AWTEvent.MOUSE_WHEEL_EVENT_MASK); } @Override public void setBackground(Color bg) { uiComp.setBackground(bg); super.setBackground(bg); } @Override public void removeNotify() { if (SystemInfo.isWindows) { if (myCefBrowser.getUIComponent().hasFocus()) { // pass focus before removal myCefBrowser.setFocus(false); } } myFirstShow = true; super.removeNotify(); } @Override public Dimension getPreferredSize() { // Preferred size should not be zero, otherwise the content loading is not triggered Dimension size = super.getPreferredSize(); return size.width > 0 && size.height > 0 ? size : DEF_PREF_SIZE; } @Override protected void processFocusEvent(FocusEvent e) { super.processFocusEvent(e); if (e.getID() == FocusEvent.FOCUS_GAINED) { uiComp.requestFocusInWindow(); } } }; resultPanel.setBackground(JBColor.background()); resultPanel.putClientProperty(JBCEFBROWSER_INSTANCE_PROP, this); if (SystemInfo.isMac) { ShortcutProvider.registerShortcuts(resultPanel, this); } resultPanel.add(uiComp, BorderLayout.CENTER); if (SystemInfo.isWindows) { myCefBrowser.getUIComponent().addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (myCefBrowser.getUIComponent().isFocusable()) { getCefBrowser().setFocus(true); } } }); } resultPanel.setFocusCycleRoot(true); resultPanel.setFocusTraversalPolicyProvider(true); resultPanel.setFocusTraversalPolicy(new MyFTP()); resultPanel.addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent e) { ourOnBrowserMoveResizeCallbacks.forEach(callback -> callback.accept(JBCefBrowser.this)); } @Override public void componentMoved(ComponentEvent e) { ourOnBrowserMoveResizeCallbacks.forEach(callback -> callback.accept(JBCefBrowser.this)); } @Override public void componentShown(ComponentEvent e) { ourOnBrowserMoveResizeCallbacks.forEach(callback -> callback.accept(JBCefBrowser.this)); } @Override public void componentHidden(ComponentEvent e) { ourOnBrowserMoveResizeCallbacks.forEach(callback -> callback.accept(JBCefBrowser.this)); } }); return resultPanel; } /** * For internal usage. */ public static void addOnBrowserMoveResizeCallback(@NotNull Consumer<? super JBCefBrowser> callback) { ourOnBrowserMoveResizeCallbacks.add(callback); } /** * For internal usage. */ public static void removeOnBrowserMoveResizeCallback(@NotNull Consumer<? super JBCefBrowser> callback) { ourOnBrowserMoveResizeCallbacks.remove(callback); } /** * Creates a browser with default {@link JBCefClient}. The default client is disposed with this browser and may not be used with other browsers. */ @SuppressWarnings("unused") public JBCefBrowser() { this(JBCefApp.getInstance().createClient(), true, null); } /** * @see #JBCefBrowser() * @param url initial url */ @SuppressWarnings("unused") public JBCefBrowser(@NotNull String url) { this(JBCefApp.getInstance().createClient(), true, url); } public @NotNull JComponent getComponent() { return myComponent; } @Override public void setProperty(@NotNull String name, @Nullable Object value) { if (FOCUS_ON_NAVIGATION.equals(name) && !(value instanceof Boolean)) { throw new IllegalArgumentException("JBCefBrowserBase.FOCUS_ON_NAVIGATION should be java.lang.Boolean"); } super.setProperty(name, value); } private static @Nullable Window getActiveFrame() { for (Frame frame : Frame.getFrames()) { if (frame.isActive()) return frame; } return null; } public void openDevtools() { if (myDevtoolsFrame != null) { myDevtoolsFrame.toFront(); return; } Window activeFrame = getActiveFrame(); if (activeFrame == null) return; Rectangle bounds = activeFrame.getGraphicsConfiguration().getBounds(); myDevtoolsFrame = new JDialog(activeFrame); myDevtoolsFrame.setTitle("JCEF DevTools"); myDevtoolsFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); myDevtoolsFrame.setBounds(bounds.width / 4 + 100, bounds.height / 4 + 100, bounds.width / 2, bounds.height / 2); myDevtoolsFrame.setLayout(new BorderLayout()); JBCefBrowser devTools = new JBCefBrowser(myCefBrowser.getDevTools(), myCefClient); myDevtoolsFrame.add(devTools.getComponent(), BorderLayout.CENTER); myDevtoolsFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosed(WindowEvent e) { myDevtoolsFrame = null; Disposer.dispose(devTools); } }); myDevtoolsFrame.setVisible(true); } @Override public void dispose() { super.dispose(() -> { myCefClient.removeFocusHandler(myCefFocusHandler, myCefBrowser); myCefClient.removeKeyboardHandler(myKeyboardHandler, myCefBrowser); }); } protected class DefaultCefContextMenuHandler extends CefContextMenuHandlerAdapter { protected static final int DEBUG_COMMAND_ID = MENU_ID_USER_LAST; private final boolean isInternal; public DefaultCefContextMenuHandler(boolean isInternal) { this.isInternal = isInternal; } @Override public void onBeforeContextMenu(CefBrowser browser, CefFrame frame, CefContextMenuParams params, CefMenuModel model) { if (isInternal) { model.addItem(DEBUG_COMMAND_ID, "Open DevTools"); } } @Override public boolean onContextMenuCommand(CefBrowser browser, CefFrame frame, CefContextMenuParams params, int commandId, int eventFlags) { if (commandId == DEBUG_COMMAND_ID) { openDevtools(); return true; } return false; } } private class MyFTP extends FocusTraversalPolicy { @Override public Component getComponentAfter(Container aContainer, Component aComponent) { return myCefBrowser.getUIComponent(); } @Override public Component getComponentBefore(Container aContainer, Component aComponent) { return myCefBrowser.getUIComponent(); } @Override public Component getFirstComponent(Container aContainer) { return myCefBrowser.getUIComponent(); } @Override public Component getLastComponent(Container aContainer) { return myCefBrowser.getUIComponent(); } @Override public Component getDefaultComponent(Container aContainer) { return myCefBrowser.getUIComponent(); } } }
package com.intellij.ui.jcef; import com.intellij.openapi.util.Disposer; import org.cef.CefClient; import org.cef.browser.CefBrowser; import org.cef.browser.CefFrame; import org.cef.browser.CefMessageRouter; import org.cef.callback.CefQueryCallback; import org.cef.handler.CefMessageRouterHandler; import org.cef.handler.CefMessageRouterHandlerAdapter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Function; /** * A JS query callback. * * @author tav */ public final class JBCefJSQuery implements JBCefDisposable { @NotNull private final JSQueryFunc myFunc; @NotNull private final CefClient myCefClient; @NotNull private final DisposeHelper myDisposeHelper = new DisposeHelper(); @NotNull private final Map<Function<? super String, ? extends Response>, CefMessageRouterHandler> myHandlerMap = Collections.synchronizedMap(new HashMap<>()); private JBCefJSQuery(@NotNull JBCefBrowserBase browser, @NotNull JBCefJSQuery.JSQueryFunc func) { myFunc = func; myCefClient = browser.getJBCefClient().getCefClient(); Disposer.register(browser.getJBCefClient(), this); } /** * @return name of the global function JS must call to send query to Java */ @NotNull public final String getFuncName() { return myFunc.myFuncName; } /** * Creates a unique JS query. * * @see JBCefClient#JBCEFCLIENT_JSQUERY_POOL_SIZE_PROP * @param browser the associated cef browser */ public static JBCefJSQuery create(@NotNull JBCefBrowserBase browser) { Function<Void, JBCefJSQuery> create = (v) -> { return new JBCefJSQuery(browser, new JSQueryFunc(browser.getJBCefClient())); }; if (!browser.isCefBrowserCreated()) { return create.apply(null); } JBCefClient.JSQueryPool pool = browser.getJBCefClient().getJSQueryPool(); JSQueryFunc slot; if (pool != null && (slot = pool.getFreeSlot()) != null) { return new JBCefJSQuery(browser, slot); } // this query will produce en error in JS debug console return create.apply(null); } /** * @deprecated use {@link #create(JBCefBrowserBase)} */ @Deprecated public static JBCefJSQuery create(@NotNull JBCefBrowser browser) { return create((JBCefBrowserBase)browser); } /** * Returns the query callback to inject into JS code * * @param queryResult the result (JS variable name, or JS value in single quotes) that will be passed to the java handler {@link #addHandler(Function)} */ public String inject(@Nullable String queryResult) { return inject(queryResult, "function(response) {}", "function(error_code, error_message) {}"); } /** * Returns the query callback to inject into JS code * * @param queryResult the result (JS variable name, or JS value in single quotes) that will be passed to the java handler {@link #addHandler(Function)} * @param onSuccessCallback JS callback in format: function(response) {} * @param onFailureCallback JS callback in format: function(error_code, error_message) {} */ public String inject(@Nullable String queryResult, @NotNull String onSuccessCallback, @NotNull String onFailureCallback) { if (queryResult != null && queryResult.isEmpty()) queryResult = "''"; return "window." + myFunc.myFuncName + "({request: '' + " + queryResult + "," + "onSuccess: " + onSuccessCallback + "," + "onFailure: " + onFailureCallback + "});"; } public void addHandler(@NotNull Function<? super String, ? extends Response> handler) { CefMessageRouterHandler cefHandler; myFunc.myRouter.addHandler(cefHandler = new CefMessageRouterHandlerAdapter() { @Override public boolean onQuery(CefBrowser browser, CefFrame frame, long query_id, String request, boolean persistent, CefQueryCallback callback) { Response response = handler.apply(request); if (callback != null && response != null) { if (response.isSuccess() && response.hasResponse()) { callback.success(response.response()); } else { callback.failure(response.errCode(), response.errMsg()); } } else if (callback != null) { callback.success(""); } return true; } }, false); myHandlerMap.put(handler, cefHandler); } public void removeHandler(@NotNull Function<? super String, ? extends Response> handler) { CefMessageRouterHandler cefHandler = myHandlerMap.remove(handler); if (cefHandler != null) { myFunc.myRouter.removeHandler(cefHandler); } } @Override public void dispose() { myDisposeHelper.dispose(() -> { myCefClient.removeMessageRouter(myFunc.myRouter); myFunc.myRouter.dispose(); myHandlerMap.clear(); }); } @Override public boolean isDisposed() { return myDisposeHelper.isDisposed(); } /** * A JS handler response to a query. */ public static class Response { public static final int ERR_CODE_SUCCESS = 0; @Nullable private final String myResponse; private final int myErrCode; @Nullable private final String myErrMsg; public Response(@Nullable String response) { this(response, ERR_CODE_SUCCESS, null); } public Response(@Nullable String response, int errCode, @Nullable String errMsg) { myResponse = response; myErrCode = errCode; myErrMsg = errMsg; } @Nullable public String response() { return myResponse; } public int errCode() { return myErrCode; } @Nullable public String errMsg() { return myErrMsg; } public boolean isSuccess() { return myErrCode == ERR_CODE_SUCCESS; } public boolean hasResponse() { return myResponse != null; } } static class JSQueryFunc { final CefMessageRouter myRouter; final String myFuncName; JSQueryFunc(@NotNull JBCefClient client) { this(client, client.nextJSQueryIndex(), false); } JSQueryFunc(@NotNull JBCefClient client, int index, boolean isSlot) { String postfix = client.hashCode() + "_" + (isSlot ? "slot_" : "") + index; myFuncName = "cefQuery_" + postfix; CefMessageRouter.CefMessageRouterConfig config = new CefMessageRouter.CefMessageRouterConfig(); config.jsQueryFunction = myFuncName; config.jsCancelFunction = "cefQuery_cancel_" + postfix; myRouter = CefMessageRouter.create(config); client.getCefClient().addMessageRouter(myRouter); } } }
package example; //-*- mode:java; encoding:utf-8 -*- // vim:set fileencoding=utf-8: //@homepage@ import java.awt.*; import java.awt.event.*; import javax.swing.*; // import javax.swing.event.*; import javax.swing.table.*; // import java.util.*; public final class MainPanel extends JPanel { private final String[] columnNames = {"String", "Integer", "Boolean"}; private final Object[][] data = { {"aaa", 12, true}, {"bbb", 5, false}, {"CCC", 92, true}, {"DDD", 0, false} }; private final DefaultTableModel model = new DefaultTableModel(data, columnNames) { @Override public Class<?> getColumnClass(int column) { // ArrayIndexOutOfBoundsException: 0 >= 0 // Bug ID: JDK-6967479 JTable sorter fires even if the model is empty //return getValueAt(0, column).getClass(); switch (column) { case 0: return String.class; case 1: return Number.class; case 2: return Boolean.class; default: return super.getColumnClass(column); } } }; private final JTable table = new JTable(model) { private final Color evenColor = new Color(245, 245, 245); @Override public Component prepareRenderer(TableCellRenderer tcr, int row, int column) { Component c = super.prepareRenderer(tcr, row, column); if (isRowSelected(row)) { c.setForeground(getSelectionForeground()); c.setBackground(getSelectionBackground()); } else { c.setForeground(getForeground()); c.setBackground(row % 2 == 0 ? evenColor : getBackground()); } return c; } }; public MainPanel() { super(new BorderLayout()); JScrollPane scroll = new JScrollPane(table); scroll.setBackground(Color.RED); scroll.getViewport().setBackground(Color.GREEN); //table.setBackground(Color.BLUE); //table.setOpaque(false); //table.setBackground(scroll.getBackground()); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setComponentPopupMenu(new TablePopupMenu()); //scroll.getViewport().setComponentPopupMenu(makePop()); //scroll.setComponentPopupMenu(makePop()); table.setRowSorter(new TableRowSorter<>(model)); add(makeToolBox(table), BorderLayout.NORTH); add(makeColorBox(table), BorderLayout.SOUTH); add(scroll); setPreferredSize(new Dimension(320, 240)); } private static JComponent makeToolBox(JTable table) { JCheckBox check = new JCheckBox("FillsViewportHeight"); check.addActionListener(e -> table.setFillsViewportHeight(((JCheckBox) e.getSource()).isSelected())); JButton button = new JButton("clearSelection"); button.addActionListener(e -> table.clearSelection()); Box box = Box.createHorizontalBox(); box.add(check); box.add(button); return box; } private static JComponent makeColorBox(final JTable table) { JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT)); final JRadioButton r1 = new JRadioButton("WHITE"); final JRadioButton r2 = new JRadioButton("BLUE"); ButtonGroup bg = new ButtonGroup(); ActionListener al = e -> table.setBackground(r1.isSelected() ? Color.WHITE : Color.BLUE); p.add(new JLabel("table.setBackground: ")); bg.add(r1); p.add(r1); r1.addActionListener(al); bg.add(r2); p.add(r2); r2.addActionListener(al); r1.setSelected(true); return p; } public static void main(String... args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } public static void createAndShowGUI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("@title@"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.getContentPane().add(new MainPanel()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } } class TablePopupMenu extends JPopupMenu { private final Action deleteAction = new AbstractAction("delete") { @Override public void actionPerformed(ActionEvent e) { JTable table = (JTable) getInvoker(); DefaultTableModel model = (DefaultTableModel) table.getModel(); int[] selection = table.getSelectedRows(); for (int i = selection.length - 1; i >= 0; i model.removeRow(table.convertRowIndexToModel(selection[i])); } } }; private final Action addAction = new AbstractAction("add") { @Override public void actionPerformed(ActionEvent e) { JTable table = (JTable) getInvoker(); DefaultTableModel model = (DefaultTableModel) table.getModel(); model.addRow(new Object[] {"example", model.getRowCount(), false}); } }; protected TablePopupMenu() { super(); add(addAction); addSeparator(); add(deleteAction); } @Override public void show(Component c, int x, int y) { if (c instanceof JTable) { deleteAction.setEnabled(((JTable) c).getSelectedRowCount() > 0); super.show(c, x, y); } } }
package org.apache.log4j.spi; import java.io.Writer; import java.io.PrintWriter; import java.util.Vector; public class ThrowableInformation implements java.io.Serializable { static final long serialVersionUID = -4748765566864322735L; private transient Throwable throwable; private String[] rep; public ThrowableInformation(Throwable throwable) { this.throwable = throwable; } public Throwable getThrowable() { return throwable; } public String[] getThrowableStrRep() { if(rep != null) { return (String[]) rep.clone(); } else { VectorWriter vw = new VectorWriter(); throwable.printStackTrace(vw); rep = vw.toStringArray(); vw.clear(); return rep; } } } class VectorWriter extends PrintWriter { private Vector v; VectorWriter() { super(new NullWriter()); v = new Vector(); } public void println(Object o) { v.addElement(o.toString()); } // JDK 1.1.x apprenly uses this form of println while in // printStackTrace() public void println(char[] s) { v.addElement(new String(s)); } public void println(String s) { v.addElement(s); } public String[] toStringArray() { int len = v.size(); String[] sa = new String[len]; for(int i = 0; i < len; i++) { sa[i] = (String) v.elementAt(i); } return sa; } public void clear() { v.setSize(0); } } class NullWriter extends Writer { public void close() { } public void flush() { } public void write(char[] cbuf, int off, int len) { } }
package org.apache.velocity.runtime.directive; import java.util.Map; import java.io.Writer; import java.io.IOException; import org.apache.velocity.Context; import org.apache.velocity.util.ClassUtils; import org.apache.velocity.runtime.parser.Node; import org.apache.velocity.runtime.parser.Token; import org.apache.velocity.runtime.parser.ASTReference; import org.apache.velocity.runtime.parser.ParserTreeConstants; public class Set implements Directive { protected String property; public String getName() { return "set"; } public int getType() { return LINE; } public int getArgs() { return 1; } public void render(Context context, Writer writer, Node node) throws IOException { Object value = null; Node right = node.jjtGetChild(0).jjtGetChild(0).jjtGetChild(0) .jjtGetChild(1).jjtGetChild(0); value = right.value(context); ASTReference left = (ASTReference) node.jjtGetChild(0).jjtGetChild(0) .jjtGetChild(0).jjtGetChild(0); if (left.jjtGetNumChildren() == 0) context.put(left.getFirstToken().image.substring(1), value); else left.setValue(context, value); } }
package org.jivesoftware.spark.ui; import org.jivesoftware.spark.component.tabbedPane.SparkTab; import org.jivesoftware.spark.ui.rooms.ChatRoomImpl; import org.jivesoftware.spark.PresenceManager; import org.jivesoftware.smack.packet.Presence; import org.jivesoftware.resource.SparkRes; import java.awt.Component; import java.awt.Color; /** * Allows users to control the decoration of a <code>SparkTab</code> component within the <code>ChatContainer</code>. */ public abstract class SparkTabHandler { public abstract boolean isTabHandled(SparkTab tab, Component component, boolean isSelectedTab, boolean chatFrameFocused); /** * Updates the SparkTab to show it is in a stale state. * * @param tab the SparkTab. * @param chatRoom the ChatRoom of the SparkTab. */ protected void decorateStaleTab(SparkTab tab, ChatRoom chatRoom) { tab.setTitleColor(Color.gray); tab.setTabFont(tab.getDefaultFont()); String jid = ((ChatRoomImpl)chatRoom).getParticipantJID(); Presence presence = PresenceManager.getPresence(jid); if (!presence.isAvailable()) { tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_UNAVAILABLE_STALE_IMAGE)); } else { Presence.Mode mode = presence.getMode(); if (mode == Presence.Mode.available || mode == null) { tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_AVAILABLE_STALE_IMAGE)); } else if (mode == Presence.Mode.away) { tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_AWAY_STALE_IMAGE)); } else if (mode == Presence.Mode.chat) { tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_FREE_CHAT_STALE_IMAGE)); } else if (mode == Presence.Mode.dnd) { tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_DND_STALE_IMAGE)); } else if (mode == Presence.Mode.xa) { tab.setIcon(SparkRes.getImageIcon(SparkRes.IM_DND_STALE_IMAGE)); } } tab.validateTab(); } }
package org.neo4j.impl.cache; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Logger; public class AdaptiveCacheManager { private static final Logger log = Logger .getLogger( AdaptiveCacheManager.class.getName() ); private float decreaseRatio = 1.15f; private float increaseRatio = 1.1f; private final List<AdaptiveCacheElement> caches = new LinkedList<AdaptiveCacheElement>(); private AdaptiveCacheWorker workerThread; public synchronized void registerCache( Cache<?,?> cache, float ratio, int minSize ) { if ( cache == null || ratio >= 1 || ratio <= 0 || minSize < 0 ) { throw new IllegalArgumentException( " cache=" + cache + " ratio =" + ratio + " minSize=" + minSize ); } for ( AdaptiveCacheElement element : caches ) { if ( element.getCache() == cache ) { log.fine( "Cache[" + cache.getName() + "] already registered." ); return; } } AdaptiveCacheElement element = new AdaptiveCacheElement( cache, ratio, minSize ); caches.add( element ); cache.setAdaptiveStatus( true ); log.fine( "Cache[" + cache.getName() + "] threshold=" + ratio + "minSize=" + minSize + " registered." ); } public synchronized void unregisterCache( Cache<?,?> cache ) { if ( cache == null ) { throw new IllegalArgumentException( "Null cache" ); } Iterator<AdaptiveCacheElement> itr = caches.iterator(); while ( itr.hasNext() ) { AdaptiveCacheElement element = itr.next(); if ( element.getCache() == cache ) { itr.remove(); break; } } log.fine( "Cache[" + cache.getName() + "] removed." ); } synchronized AdaptiveCacheElement getAdaptiveCacheElementIndex( Cache<?,?> cache ) { for ( AdaptiveCacheElement element : caches ) { if ( element.getCache() == cache ) { return element; } } return null; } private void parseParams( Map<Object,Object> params ) { if ( params.containsKey( "adaptive_cache_worker_sleep_time" ) ) { Object value = params.get( "adaptive_cache_worker_sleep_time" ); int sleepTime = 3000; try { sleepTime = Integer.parseInt( (String) value ); } catch ( NumberFormatException e ) { log.warning( "Unable to parse apdaptive_cache_worker_sleep_time " + value ); } workerThread.setSleepTime( sleepTime ); } if ( params.containsKey( "adaptive_cache_manager_decrease_ratio" ) ) { Object value = params.get( "adaptive_cache_manager_decrease_ratio" ); try { decreaseRatio = Float.parseFloat( (String) value ); } catch ( NumberFormatException e ) { log.warning( "Unable to parse adaptive_cache_manager_decrease_ratio " + value ); } if ( decreaseRatio < 1 ) { decreaseRatio = 1.0f; } } if ( params.containsKey( "adaptive_cache_manager_increase_ratio" ) ) { Object value = params.get( "adaptive_cache_manager_increase_ratio" ); try { increaseRatio = Float.parseFloat( (String) value ); } catch ( NumberFormatException e ) { log.warning( "Unable to parse adaptive_cache_manager_increase_ratio " + value ); } if ( increaseRatio < 1 ) { increaseRatio = 1.0f; } } } public void start( Map<Object,Object> params ) { workerThread = new AdaptiveCacheWorker(); parseParams( params ); workerThread.start(); } public void stop() { workerThread.markDone(); workerThread = null; } Collection<AdaptiveCacheElement> getCaches() { return caches; } private class AdaptiveCacheWorker extends Thread { private boolean done = false; private int sleepTime = 3000; AdaptiveCacheWorker() { super( "AdaptiveCacheWorker" ); } void setSleepTime( int sleepTime ) { this.sleepTime = sleepTime; } public void run() { while ( !done ) { try { adaptCaches(); Thread.sleep( sleepTime ); } catch ( InterruptedException e ) { } } } void markDone() { done = true; } } public void adaptCaches() { List<AdaptiveCacheElement> copy = new LinkedList<AdaptiveCacheElement>(); synchronized ( this ) { copy.addAll( caches ); } for ( AdaptiveCacheElement element : copy ) { adaptCache( element ); } } public void adaptCache( Cache<?,?> cache ) { if ( cache == null ) { throw new IllegalArgumentException( "Null cache" ); } AdaptiveCacheElement element = getAdaptiveCacheElementIndex( cache ); if ( element != null ) { adaptCache( element ); } } private void adaptCache( AdaptiveCacheElement element ) { long max = Runtime.getRuntime().maxMemory(); long total = Runtime.getRuntime().totalMemory(); long free = Runtime.getRuntime().freeMemory(); float ratio = (float) (max - free) / max; float allocationRatio = (float) total / max; if ( allocationRatio < element.getRatio() ) { // allocation ratio < 1 means JVM can still increase heap size // we won't decrease caches until element ratio is less // then allocationRatio ratio = 0; } // System.out.println( "max= " + max + " total=" + total + // " ratio= " + ratio + " ... free=" + free ); if ( ratio > element.getRatio() ) { // decrease cache size // after decrease we resize again with +1000 to avoid // spam of this method Cache<?,?> cache = element.getCache(); int newCacheSize = (int) ( cache.maxSize() / decreaseRatio / (1 + (ratio - element.getRatio())) ); int minSize = element.minSize(); if ( newCacheSize < minSize ) { log.fine( "Cache[" + cache.getName() + "] cannot decrease under " + minSize + " (allocation ratio=" + allocationRatio + " threshold status=" + ratio + ")" ); cache.resize( minSize ); cache.resize( minSize + 1000 ); return; } if ( newCacheSize + 1200 > cache.size() ) { if ( cache.size() - 1200 >= minSize ) { newCacheSize = cache.size() - 1200; } else { newCacheSize = minSize; } } log.fine( "Cache[" + cache.getName() + "] decreasing from " + cache.size() + " to " + newCacheSize + " (allocation ratio=" + allocationRatio + " threshold status=" + ratio + ")" ); if ( newCacheSize <= 1000 ) { cache.clear(); } else { cache.resize( newCacheSize ); } cache.resize( newCacheSize + 1000 ); } else { // increase cache size Cache<?,?> cache = element.getCache(); if ( cache.size() / (float) cache.maxSize() < 0.9f ) { return; } int newCacheSize = (int) (cache.maxSize() * increaseRatio); log.fine( "Cache[" + cache.getName() + "] increasing from " + cache.size() + " to " + newCacheSize + " (allocation ratio=" + allocationRatio + " threshold status=" + ratio + ")" ); cache.resize( newCacheSize ); } } private static class AdaptiveCacheElement { private final Cache<?,?> cache; private final float ratio; private final int minSize; AdaptiveCacheElement( Cache<?,?> cache, float ratio, int minSize ) { this.cache = cache; this.ratio = ratio; this.minSize = minSize; } String getName() { return cache.getName(); } Cache<?,?> getCache() { return cache; } float getRatio() { return ratio; } int minSize() { return minSize; } } }
package org.ngsutils.support.io; import java.io.IOException; import java.io.InputStream; /** * Will assume that there are suffixLen bytes of suffix at the end of the proper inputstream. * This class will pass everything read everything from the parent inputstream *except* * the last suffixLen bytes of suffix. * * This is useful for reading a variable length stream with a fixed length suffix block, such * as a stream with an MD5/SHA1 hash digest of a stream appended to the stream itself. * * @author mbreese */ public class SuffixInputStream extends InputStream { public static final int DEFAULT_BUFFERSIZE = 8192; private InputStream parent; private int suffixLen; private boolean closed = false; private byte[] buffer = null; private byte[] bufferSuffix = null; private int pos=0; private int buflen=0; public SuffixInputStream(InputStream parent, int suffixLen, int bufferSize) throws IOException { if (suffixLen >= bufferSize) { throw new IOException("The buffer size must be bigger than the suffix length!"); } this.parent = parent; this.suffixLen = suffixLen; this.buffer = new byte[bufferSize+suffixLen]; this.bufferSuffix = new byte[suffixLen]; int total = 0; int count = 0; // read a full buffer length first - we want to read only in bufferSize blocks while (total < bufferSize && (count = parent.read(buffer, total, bufferSize-total)) != -1) { total += count; } if (total == -1 || total < suffixLen) { throw new IOException("Stream is exhausted before suffix!"); } // copy the suffixLen bytes from the end of the buffer. for (int i=0; i<suffixLen; i++) { bufferSuffix[i] = buffer[total - suffixLen + i]; } buflen = total - suffixLen; pos = 0; // System.err.println("bufferHash: "+ StringUtils.join(" ", bufferHash)); } public SuffixInputStream(InputStream parent, int suffixLen) throws IOException { this(parent, suffixLen, DEFAULT_BUFFERSIZE); } @Override public int read() throws IOException { if (closed) { throw new IOException("Attempted to read from closed stream!"); } if (pos >= buflen) { // fill the end of the buffer // System.err.println("buffer0 : "+ StringUtils.join(" ", buffer)); buflen = parent.read(buffer, suffixLen, buffer.length - suffixLen); // System.err.println("buffer1 : "+ StringUtils.join(" ", buffer)); if (buflen == -1) { return -1; } // System.err.println("bufferHash: "+ StringUtils.join(" ", bufferHash)); // copy the hash buffer to the main buffer (prefix) for (int i=0; i<bufferSuffix.length; i++) { buffer[i] = bufferSuffix[i]; } // System.err.println("buffer2 : "+ StringUtils.join(" ", buffer)); // copy the end of the buffer to the hash buffer for (int i=0; i<suffixLen; i++) { bufferSuffix[i] = buffer[buflen + i]; buffer[buflen+i] = -1; } // System.err.println("buffer3 : "+ StringUtils.join(" ", buffer)); // System.err.println("bufferHash: "+ StringUtils.join(" ", bufferHash)); pos = 0; } // System.err.println("["+pos+"] "+String.format("%02X", buffer[pos])); return buffer[pos++] & 0xff; } public void close() throws IOException { if (closed) { return; } parent.close(); closed = true; } public byte[] getSuffix() throws IOException { if (closed) { return bufferSuffix; } throw new IOException("Stream hasn't been closed yet"); } }
package org.smoothbuild.testing; import static com.google.common.base.Preconditions.checkArgument; import static org.smoothbuild.fs.base.PathUtils.isValid; import static org.smoothbuild.fs.base.PathUtils.toCanonical; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import org.smoothbuild.fs.base.PathUtils; import org.smoothbuild.fs.mem.InMemoryFileSystem; import com.google.common.io.LineReader; public class TestingFileSystem extends InMemoryFileSystem { /** * Creates textual file that contains its path. */ public void createFile(String root, String path) throws IOException { String fullPath = fullPath(root, path); OutputStreamWriter writer = new OutputStreamWriter(createOutputStream(fullPath)); writer.write(path); writer.close(); } public void createEmptyFile(String path) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(createOutputStream(path)); writer.close(); } public void assertContentHasFilePath(String root, String path) throws IOException, FileNotFoundException { String fullPath = fullPath(root, path); try (InputStreamReader readable = new InputStreamReader(this.createInputStream(fullPath));) { LineReader reader = new LineReader(readable); String actual = reader.readLine(); if (!actual.equals(path)) { throw new AssertionError("File content is incorrect. Expected '" + path + "' but was '" + actual + "'."); } } } private static String fullPath(String root, String path) { checkArgument(isValid(root)); checkArgument(isValid(path)); return PathUtils.append(toCanonical(root), toCanonical(path)); } }
package coordinates; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.util.Collections; import java.util.Vector; public class CoordinateImage extends BufferedImage { private Vector<Coordinate> coordinates = null; private int height; private double difference; private int verticalFactor; private Color xColor = Color.blue; private Color yColor = Color.green; private Color zColor = Color.orange; private BasicStroke pointWidth; private BasicStroke lineWidth; public CoordinateImage() { super(1, 1, BufferedImage.TYPE_INT_RGB); } public CoordinateImage(int width, int height, Vector<Coordinate> coordinates, int verticalFactor) { super((width * verticalFactor) + 10, height, BufferedImage.TYPE_INT_RGB); this.verticalFactor = verticalFactor; this.height = height; this.coordinates = coordinates; createImage(); } public Vector<Coordinate> getCoordinates() { return coordinates; } public int getVericalFactor() { return verticalFactor; } private void createImage() { Vector<Double> x = new Vector<Double>(); Vector<Double> y = new Vector<Double>(); Vector<Double> z = new Vector<Double>(); separateCoordinates(x, y, z); double[] xStats = getStats(x); double[] yStats = getStats(y); double[] zStats = getStats(z); difference = Math.max(xStats[2], Math.max(yStats[2], zStats[2])); Graphics2D g2 = (Graphics2D) this.getGraphics(); g2.setColor(Color.white); g2.setStroke(new BasicStroke(1)); double zero = calculatePoint(0, xStats, (height - 10) / difference); Line2D l = new Line2D.Double(0, zero, coordinates.size() * verticalFactor, zero); g2.draw(l); drawAxis(x, xStats, xColor); drawAxis(y, yStats, yColor); drawAxis(z, zStats, zColor); } private void drawAxis(Vector<Double> points, double[] stats, Color color) { double factor = (height - 10) / difference; Graphics2D g2 = (Graphics2D) this.getGraphics(); g2.setColor(color); Point2D previous = new Point2D.Double(0, calculatePoint(points.elementAt(0), stats, factor)); for(int i = 1; i< points.size(); i++) { Point2D p = new Point2D.Double(i* verticalFactor, calculatePoint(points.elementAt(i), stats, factor)); Line2D l = new Line2D.Double(p, previous); g2.draw(l); previous = p; } } private double calculatePoint(double point, double[] stats, double factor) { return height - ((point - stats[0]) * factor + 5); } private void separateCoordinates(Vector<Double> x, Vector<Double> y, Vector<Double> z) { for(int i = 0; i < coordinates.size(); i++) { Coordinate c = coordinates.elementAt(i); x.add(c.getX()); y.add(c.getY()); z.add(c.getZ()); } } /** * * @param points * @return min, max, diff */ private double[] getStats(Vector<Double> points) { double[] stats = new double[3]; stats[0] = Collections.min(points); stats[1] = Collections.max(points); stats[2] = Math.abs(stats[1] - stats[0]); return stats; } }
package org.tensorics.core.tensor; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; /** * Default Implementation of {@link Tensor}. * <p> * By constraint of creation it holds a set of {@link Position} of type C and values of type T, such that ALL Positions * contains the same number and type of coordinates. Number and type of coordinates can be accessed and explored via * {@link Shape}. * <p> * There is a special type of Tensor that has ZERO dimensiality. Can be obtained via factory method. * <p> * {@link ImmutableTensor} is immutable. * * @author agorzaws, kfuchsbe * @param <T> type of values in Tensor. */ @SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.TooManyMethods" }) public class ImmutableTensor<T> implements Tensor<T> { private final Map<Position, Tensor.Entry<T>> entries; // NOSONAR private final Shape shape; // NOSONAR private final Context context; /** * Private constructor to be called from builder * * @param builder to be used when {@link ImmutableTensor} is created. */ ImmutableTensor(AbstractTensorBuilder<T> builder) { this.entries = builder.createEntries(); this.shape = Shape.viewOf(builder.getDimensions(), this.entries.keySet()); this.context = builder.getContext(); } /** * Returns a builder for an {@link ImmutableTensor}. As argument it takes set of class of coordinates which * represent the dimensions of the tensor. * * @param dimensions a set of classes that can later be used as coordinates for the tensor entries. * @return a builder for {@link ImmutableTensor} * @param <T> type of values in Tensor. */ public static final <T> Builder<T> builder(Set<? extends Class<?>> dimensions) { return new Builder<T>(dimensions); } /** * Returns a builder for an {@link ImmutableTensor}. The dimensions (classes of coordinates) of the future tensor * have to be given as arguments here. * * @param dimensions the dimensions of the tensor to create * @return a builder for an immutable tensor * @param <T> the type of values of the tensor */ public static final <T> Builder<T> builder(Class<?>... dimensions) { return builder(ImmutableSet.copyOf(dimensions)); } /** * Creates a tensor from the given map, where the map has to contain the positions as keys and the values as values. * * @param dimensions the desired dimensions of the tensor. This has to be consistent with the position - keys in the * map. * @param map the map from which to construct a tensor * @return a new immutable tensor */ public static final <T> Tensor<T> fromMap(Set<? extends Class<?>> dimensions, Map<Position, T> map) { Builder<T> builder = builder(dimensions); for (Map.Entry<Position, T> entry : map.entrySet()) { builder.at(entry.getKey()).put(entry.getValue()); } return builder.build(); } /** * Returns the builder that can create special tensor of dimension size equal ZERO. * * @param value to be used. * @return a builder for {@link ImmutableTensor} * @param <T> type of values in Tensor. */ public static final <T> Tensor<T> zeroDimensionalOf(T value) { Builder<T> builder = builder(Collections.<Class<?>> emptySet()); builder.at(Position.empty()).put(value); return builder.build(); } /** * Creates an immutable copy of the given tensor. * * @param tensor the tensor whose element to copy * @return new immutable Tensor */ public static final <T> Tensor<T> copyOf(Tensor<T> tensor) { Builder<T> builder = builder(tensor.shape().dimensionSet()); builder.putAll(tensor.entrySet()); builder.setTensorContext(tensor.context()); return builder.build(); } @Override public T get(Position position) { return findEntryOrThrow(position).getValue(); } @Override public Context context() { return context; } @Override public Set<Tensor.Entry<T>> entrySet() { return new HashSet<>(this.entries.values()); } @Override @SafeVarargs public final T get(Object... coordinates) { return get(Position.of(coordinates)); } @Override public Shape shape() { return this.shape; } private Tensor.Entry<T> findEntryOrThrow(Position position) { Tensor.Entry<T> entry = findEntryOrNull(position); if (entry == null) { throw new NoSuchElementException("Entry for position '" + position + "' is not contained in this tensor."); } return entry; } private Tensor.Entry<T> findEntryOrNull(Position position) { return this.entries.get(position); } /** * A builder for an immutable tensor. * * @author kfuchsbe * @param <S> the type of the values to be added */ public static final class Builder<S> extends AbstractTensorBuilder<S> { Builder(Set<? extends Class<?>> dimensions) { super(dimensions); } /** * Builds an {@link ImmutableTensor} from all elements put before. * * @return an {@link ImmutableTensor}. */ public ImmutableTensor<S> build() { return new ImmutableTensor<S>(this); } } @Override public String toString() { StringBuffer buffer = new StringBuffer(); for (Position position : this.shape.positionSet()) { buffer.append(position + "=" + get(position) + "; "); } if (buffer.length() > 1) { buffer.setLength(buffer.length() - 2); } return "{" + buffer + "}"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((context == null) ? 0 : context.hashCode()); result = prime * result + ((entries == null) ? 0 : entries.hashCode()); result = prime * result + ((shape == null) ? 0 : shape.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } ImmutableTensor<?> other = (ImmutableTensor<?>) obj; if (context == null) { if (other.context != null) { return false; } } else if (!context.equals(other.context)) { return false; } if (entries == null) { if (other.entries != null) { return false; } } else if (!entries.equals(other.entries)) { return false; } if (shape == null) { if (other.shape != null) { return false; } } else if (!shape.equals(other.shape)) { return false; } return true; } }
package org.lockss.plugin.atypon; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.lockss.config.TdbAu; import org.lockss.daemon.ConfigParamDescr; import org.lockss.extractor.ArticleMetadata; import org.lockss.extractor.MetadataField; import org.lockss.plugin.ArchivalUnit; import org.lockss.plugin.CachedUrl; import org.lockss.util.Logger; import org.lockss.util.TypedEntryMap; /** * This class contains useful routines to allow a metadata extractor to verify * the contents of an ArticleMetadata against the current AU's TDB information. * This might be used to avoid emitting an article that is likely due to an * overcrawl - currently used by BaseAtypon * @author alexohlson * */ public class BaseAtyponMetadataUtil { static Logger log = Logger.getLogger(BaseAtyponMetadataUtil.class); /** * html "dc.*" information may not contain publication title and volume * ris information usually does. * If the volume is available, check against the TDB information * If the volume wasn't available but the year was, try that * If we're still valid and the publication title is available, check * a normalized version of that against a normalized version of tdb pub title * @param au * @param am * @return true if the metadata matches the TDB information */ public static boolean metadataMatchesTdb(ArchivalUnit au, ArticleMetadata am) { boolean isInAu = true; // Use the journalTitle and volume name from the ArticleMetadata String foundJournalTitle = am.get(MetadataField.FIELD_PUBLICATION_TITLE); String foundVolume = am.get(MetadataField.FIELD_VOLUME); String foundDate = am.get(MetadataField.FIELD_DATE); // If we got nothing, just return, we can't validate if (StringUtils.isEmpty(foundVolume) && StringUtils.isEmpty(foundDate) && StringUtils.isEmpty(foundDate)) { return isInAu; //return true, we have no way of knowing } // Check VOLUME/YEAR if (!(StringUtils.isEmpty(foundVolume) || StringUtils.isEmpty(foundDate))) { // Get the AU's volume name from the AU properties. This must be set TypedEntryMap tfProps = au.getProperties(); String AU_volume = tfProps.getString(ConfigParamDescr.VOLUME_NAME.getKey()); // Do Volume comparison first, it's simpler if (isInAu && !(StringUtils.isEmpty(foundVolume))) { isInAu = ( (AU_volume != null) && (AU_volume.equals(foundVolume))); log.debug3("After volume check, isInAu :" + isInAu); } // Add in doing year comparison if FIELD_DATE is set // this is more complicated because date format is variable } TdbAu tdbau = au.getTdbAu(); String AU_journal_title = (tdbau == null) ? null : tdbau.getPublicationTitle(); // Now check journalTitle with some flexibility for string differences if (isInAu && !(StringUtils.isEmpty(foundJournalTitle) || StringUtils.isEmpty(AU_journal_title)) ) { // normalize titles to catch unimportant differences log.debug3("pre-normalized title from AU is : " + AU_journal_title); log.debug3("pre-normalized title from metadata is : " + foundJournalTitle); String normAuTitle = normalizeTitle(AU_journal_title); String normFoundTitle = normalizeTitle(foundJournalTitle); log.debug3("normalized title from AU is : " + normAuTitle); log.debug3("normalized title from metadata is : " + normFoundTitle); // If the titles are a subset of each other or are equal after normalization isInAu = ( ( (StringUtils.contains(normAuTitle,normFoundTitle)) || (StringUtils.contains(normFoundTitle,normAuTitle))) ); // last chance... cover weird cases, such as when the publisher mistakenly // converts multi-byte in to ? in their text output if (!isInAu) { log.debug3("one last attempt to match"); String rawTextAuTitle = generateRawTitle(normAuTitle); String rawTextFoundTitle = generateRawTitle(normFoundTitle); log.debug3("raw AuTitle: " + rawTextAuTitle); log.debug3("raw foundTitle: " + rawTextFoundTitle); isInAu =( ( (StringUtils.contains(normAuTitle,normFoundTitle)) || (StringUtils.contains(normFoundTitle,normAuTitle))) ); } } log.debug3("After metadata check, isInAu is " + isInAu); return isInAu; } /* Because we compare a title from metadata with the title in the AU * (as set in the tdb file) to make sure the item belongs in this AU, * we need to minimize potential for mismatch by normalizing the titles * Remove any apostrophes - eg "T'ang" becomes "Tang"; "Freddy's" ==> "Freddys" */ static private final Map<String, String> AtyponNormalizeMap = new HashMap<String,String>(); static { AtyponNormalizeMap.put("&", "and"); AtyponNormalizeMap.put("\u2013", "-"); //en-dash to hyphen AtyponNormalizeMap.put("\u2014", "-"); //em-dash to hyphen AtyponNormalizeMap.put("\u201c", "\""); //ldquo to basic quote AtyponNormalizeMap.put("\u201d", "\""); //rdquo to basic quote AtyponNormalizeMap.put("'", ""); //apostrophe to nothing - remove AtyponNormalizeMap.put("\u2018", ""); //single left quote to nothing - remove AtyponNormalizeMap.put("\u2019", ""); //single right quote (apostrophe alternative) to nothing - remove } /* To maximize the chance of finding matching titles normalize out stylistic * differences as much as possible, eg * make lower case, * remove leading and trailing spaces * remove a leading "the " in the title * map control variations on standard chars (en-dash --> hyphen) * and & to "and" * */ public static String normalizeTitle(String inTitle) { String outTitle; if (inTitle == null) return null; outTitle = inTitle.toLowerCase(); outTitle = outTitle.trim(); //Remove a leading "the " in the title if (outTitle.startsWith("the ")) { outTitle = outTitle.substring(4);// get over the "the " } //reduce interior multiple space characters to only one outTitle = outTitle.replaceAll("\\s+", " "); // Using the normalization map, substitute characters for (Map.Entry<String, String> norm_entry : AtyponNormalizeMap.entrySet()) { log.debug3("normalizing title by replacing " + norm_entry.getKey() + " with " + norm_entry.getValue()); // StringUtils.replace is MUCH faster than String.replace outTitle = StringUtils.replace(outTitle, norm_entry.getKey(), norm_entry.getValue()); } return outTitle; } /* * A last ditch effort to avoid false negatives due to odd characters * It is assumed it will already have gone through normalizeTitle which lets us make * assumptions * remove spaces * remove ?,-,:," * 'this is a text:title-for "questions"?' in to * 'thisisatextitleforquestions' * */ public static String generateRawTitle(String inTitle) { String outTitle; if (inTitle == null) return null; //reduce interior multiple space characters to only one //outTitle = inTitle.replaceAll("(\\s|\"|\\?|-|:)", ""); outTitle = inTitle.replaceAll("\\W", ""); return outTitle; } /* * We can do a little additional cleanup * 1. if the DOI wasn't there, get it from the URL * 2. if the Publisher wasn't set, get it from the TDB * 3. If the Publication Title wasn't set, get it from the TDB * 4. if the access.url is set, make sure it's in the AU */ public static void completeMetadata(CachedUrl cu, ArticleMetadata am) { // if the doi isn't in the metadata, we can still get it from the filename if (am.get(MetadataField.FIELD_DOI) == null) { /*matches() is anchored so must create complete pattern or else use .finds() */ /* URL is "<base>/doi/(abs|full)/<doi1st>/<doi2nd> */ String base_url = cu.getArchivalUnit().getConfiguration().get(ConfigParamDescr.BASE_URL.getKey()); String patternString = "^" + base_url + "doi/[^/]+/([^/]+)/([^?&]+)$"; Pattern METADATA_PATTERN = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); String url = cu.getUrl(); Matcher mat = METADATA_PATTERN.matcher(url); if (mat.matches()) { log.debug3("Pull DOI from URL " + mat.group(1) + "." + mat.group(2)); am.put(MetadataField.FIELD_DOI, mat.group(1) + "/" + mat.group(2)); } } // Pick up some information from the TDB if not in the cooked data TdbAu tdbau = cu.getArchivalUnit().getTdbAu(); // returns null if titleConfig is null if (tdbau != null) { if (am.get(MetadataField.FIELD_PUBLISHER) == null) { // We can try to get the publishger from the tdb file. This would be the most accurate String publisher = tdbau.getPublisherName(); if (publisher != null) { am.put(MetadataField.FIELD_PUBLISHER, publisher); } } if (am.get(MetadataField.FIELD_PUBLICATION_TITLE) == null) { String journal_title = tdbau.getPublicationTitle(); if (journal_title != null) { am.put(MetadataField.FIELD_PUBLICATION_TITLE, journal_title); } } } // Finally, check the access.url and MAKE SURE that it is in the AU // or put it to a value that is String potential_access_url; if ((potential_access_url = am.get(MetadataField.FIELD_ACCESS_URL)) != null) { CachedUrl potential_cu = cu.getArchivalUnit().makeCachedUrl(potential_access_url); if ( (potential_cu == null) || (!potential_cu.hasContent()) ){ //Not in this AU; remove this value; allow for fullTextCu to get set later am.replace(MetadataField.FIELD_ACCESS_URL, null); } } } }
package henfredemars; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Calendar; import java.util.List; import java.util.zip.GZIPOutputStream; import java.util.HashSet; //Parse and compile data samples into a single file //Input files must be in text form (i.e. not compressed) public class DataCompiler { public static void main(String[] args) { File directory = new File(args[0]); File outputFile = new File(args[1]); File[] files = directory.listFiles(); long numberOfGoodRecords = 0; long numberOfBadRecords = 0; long totalNumberOfRecords = 0; long filesProcessed = 0; HashSet<String> stationSet = new HashSet<String>(); //Prepare output file FileOutputStream fOutStream = null; GZIPOutputStream goos = null; ObjectOutputStream oos = null; try { fOutStream = new FileOutputStream(outputFile); } catch (FileNotFoundException e1) { System.out.println("DataCompiler - error writing file"); e1.printStackTrace(); } try { goos = new GZIPOutputStream(fOutStream); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } try { oos = new ObjectOutputStream(goos); } catch (IOException e1) { System.out.println("DataCompiler - error writing file"); e1.printStackTrace(); } //Process files for (File file: files) { filesProcessed++; System.out.println("Processing file: " + file.getName()); List<String> lines = null; try { lines = Files.readAllLines(file.toPath(),StandardCharsets.UTF_8); } catch (IOException e) { System.out.println("DataCompiler - failed to read file lines"); e.printStackTrace(); } for (String line: lines) { if (line.contains("WBAN")) { continue; } totalNumberOfRecords++; DataSample ds = new DataSample(); String[] elements = line.split(" +"); if (elements.length<26) { numberOfBadRecords++; continue; } ds.setStationId(elements[0]); Calendar date = Calendar.getInstance(); String dateStr = elements[2]; if (dateStr.length()<12) { numberOfBadRecords++; continue; } date.set(Calendar.YEAR, Integer.valueOf(dateStr.substring(0,4))); date.set(Calendar.MONTH, Integer.valueOf(dateStr.substring(4,6))-1); date.set(Calendar.DAY_OF_MONTH, Integer.valueOf(dateStr.substring(6,8))); date.set(Calendar.HOUR_OF_DAY, Integer.valueOf(dateStr.substring(8,10))); date.set(Calendar.MINUTE, Integer.valueOf(dateStr.substring(10,12))); ds.setDate(date); try { ds.setRainfall(Float.valueOf(elements[28].replace('T','1'))); ds.setWindSpeed(Float.valueOf(elements[4])); ds.setTemperature(Float.valueOf(elements[21])); ds.setHumidity(Float.valueOf(elements[22])); ds.setPressure(Float.valueOf(elements[25])); } catch (NumberFormatException e) { numberOfBadRecords++; if (totalNumberOfRecords % 100000!=0) continue; System.out.println("Line missing required data."); System.out.println(line); continue; //Bad measurement } if (ds.checkSample()==DataStatus.ALL_GOOD) { try { numberOfGoodRecords++; oos.writeObject(ds); stationSet.add(ds.getStationId()); if (numberOfGoodRecords % 1000==0) { oos.reset(); } } catch (IOException e) { System.out.println("DataCompiler - error writing object"); e.printStackTrace(); } } else { numberOfBadRecords++; if (totalNumberOfRecords % 100000!=0) continue; System.out.println("Bad measurement discarded DS: " + ds.checkSample()); } } if (filesProcessed%25==0) { System.out.println("GoodRecords: " + numberOfGoodRecords); System.out.println("BadRecords: " + numberOfBadRecords); System.out.println("TotalRecords: " + totalNumberOfRecords); System.out.println("Stations: " + stationSet.size()); System.out.println("FilesProcessed: " + filesProcessed); } } System.out.println("GoodRecords: " + numberOfGoodRecords); System.out.println("BadRecords: " + numberOfBadRecords); System.out.println("TotalRecords: " + totalNumberOfRecords); System.out.println("Stations: " + stationSet.size()); System.out.println("FilesProcessed: " + filesProcessed); try { oos.close(); } catch (IOException e) { //Do nothing } } }
package lombok.eclipse; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import lombok.Lombok; import lombok.core.AST; import lombok.core.LombokImmutableList; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.ImportReference; import org.eclipse.jdt.internal.compiler.ast.Initializer; import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; import org.eclipse.jdt.internal.compiler.ast.Statement; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; /** * Wraps around Eclipse's internal AST view to add useful features as well as the ability to visit parents from children, * something Eclipse own AST system does not offer. */ public class EclipseAST extends AST<EclipseAST, EclipseNode, ASTNode> { /** * Creates a new EclipseAST of the provided Compilation Unit. * * @param ast The compilation unit, which serves as the top level node in the tree to be built. */ public EclipseAST(CompilationUnitDeclaration ast) { super(toFileName(ast), packageDeclaration(ast), new EclipseImportList(ast)); this.compilationUnitDeclaration = ast; setTop(buildCompilationUnit(ast)); this.completeParse = isComplete(ast); clearChanged(); } public URI getAbsoluteFileLocation() { return ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(getFileName())).getLocationURI(); } private static String packageDeclaration(CompilationUnitDeclaration cud) { ImportReference pkg = cud.currentPackage; return pkg == null ? null : Eclipse.toQualifiedName(pkg.getImportName()); } @Override public int getSourceVersion() { long sl = compilationUnitDeclaration.problemReporter.options.sourceLevel; long cl = compilationUnitDeclaration.problemReporter.options.complianceLevel; sl >>= 16; cl >>= 16; if (sl == 0) sl = cl; if (cl == 0) cl = sl; return Math.min((int)(sl - 44), (int)(cl - 44)); } @Override public int getLatestJavaSpecSupported() { return Eclipse.getEcjCompilerVersion(); } /** * Runs through the entire AST, starting at the compilation unit, calling the provided visitor's visit methods * for each node, depth first. */ public void traverse(EclipseASTVisitor visitor) { top().traverse(visitor); } void traverseChildren(EclipseASTVisitor visitor, EclipseNode node) { LombokImmutableList<EclipseNode> children = node.down(); int len = children.size(); for (int i = 0; i < len; i++) { children.get(i).traverse(visitor); } } /** * Eclipse starts off with a 'diet' parse which leaves method bodies blank, amongst other shortcuts. * * For such diet parses, this method returns false, otherwise it returns true. Any lombok processor * that needs the contents of methods should just do nothing (and return false so it gets another shot later!) * when this is false. */ public boolean isCompleteParse() { return completeParse; } class ParseProblem { final boolean isWarning; final String message; final int sourceStart; final int sourceEnd; ParseProblem(boolean isWarning, String message, int sourceStart, int sourceEnd) { this.isWarning = isWarning; this.message = message; this.sourceStart = sourceStart; this.sourceEnd = sourceEnd; } void addToCompilationResult() { CompilationUnitDeclaration cud = (CompilationUnitDeclaration) top().get(); addProblemToCompilationResult(cud.getFileName(), cud.compilationResult, isWarning, message, sourceStart, sourceEnd); } } private void propagateProblems() { if (queuedProblems.isEmpty()) return; CompilationUnitDeclaration cud = (CompilationUnitDeclaration) top().get(); if (cud.compilationResult == null) return; for (ParseProblem problem : queuedProblems) problem.addToCompilationResult(); queuedProblems.clear(); } private final List<ParseProblem> queuedProblems = new ArrayList<ParseProblem>(); void addProblem(ParseProblem problem) { queuedProblems.add(problem); propagateProblems(); } /** * Adds a problem to the provided CompilationResult object so that it will show up * in the Problems/Warnings view. */ public static void addProblemToCompilationResult(char[] fileNameArray, CompilationResult result, boolean isWarning, String message, int sourceStart, int sourceEnd) { try { EcjReflectionCheck.addProblemToCompilationResult.invoke(null, fileNameArray, result, isWarning, message, sourceStart, sourceEnd); } catch (NoClassDefFoundError e) { //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } catch (IllegalAccessException e) { throw Lombok.sneakyThrow(e); } catch (InvocationTargetException e) { throw Lombok.sneakyThrow(e); } catch (NullPointerException e) { if (!"false".equals(System.getProperty("lombok.debug.reflection", "false"))) { e.initCause(EcjReflectionCheck.problem); throw e; } //ignore, we don't have access to the correct ECJ classes, so lombok can't possibly //do anything useful here. } } private final CompilationUnitDeclaration compilationUnitDeclaration; private boolean completeParse; private static String toFileName(CompilationUnitDeclaration ast) { return ast.compilationResult.fileName == null ? null : new String(ast.compilationResult.fileName); } /** * Call this method to move an EclipseAST generated for a diet parse to rebuild itself for the full parse - * with filled in method bodies and such. Also propagates problems and errors, which in diet parse * mode can't be reliably added to the problems/warnings view. */ public void rebuild(boolean force) { propagateProblems(); if (completeParse && !force) return; boolean changed = isChanged(); boolean newCompleteParse = isComplete(compilationUnitDeclaration); if (!newCompleteParse && !force) return; top().rebuild(); this.completeParse = newCompleteParse; if (!changed) clearChanged(); } private static boolean isComplete(CompilationUnitDeclaration unit) { return (unit.bits & ASTNode.HasAllMethodBodies) != 0; } /** {@inheritDoc} */ @Override protected EclipseNode buildTree(ASTNode node, Kind kind) { switch (kind) { case COMPILATION_UNIT: return buildCompilationUnit((CompilationUnitDeclaration) node); case TYPE: return buildType((TypeDeclaration) node); case FIELD: return buildField((FieldDeclaration) node); case INITIALIZER: return buildInitializer((Initializer) node); case METHOD: return buildMethod((AbstractMethodDeclaration) node); case ARGUMENT: return buildLocal((Argument) node, kind); case LOCAL: return buildLocal((LocalDeclaration) node, kind); case STATEMENT: return buildStatement((Statement) node); case ANNOTATION: return buildAnnotation((Annotation) node, false); default: throw new AssertionError("Did not expect to arrive here: " + kind); } } private EclipseNode buildCompilationUnit(CompilationUnitDeclaration top) { if (setAndGetAsHandled(top)) return null; List<EclipseNode> children = buildTypes(top.types); return putInMap(new EclipseNode(this, top, children, Kind.COMPILATION_UNIT)); } private void addIfNotNull(Collection<EclipseNode> collection, EclipseNode n) { if (n != null) collection.add(n); } private List<EclipseNode> buildTypes(TypeDeclaration[] children) { List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); if (children != null) for (TypeDeclaration type : children) addIfNotNull(childNodes, buildType(type)); return childNodes; } private EclipseNode buildType(TypeDeclaration type) { if (setAndGetAsHandled(type)) return null; List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); childNodes.addAll(buildFields(type.fields)); childNodes.addAll(buildTypes(type.memberTypes)); childNodes.addAll(buildMethods(type.methods)); childNodes.addAll(buildAnnotations(type.annotations, false)); return putInMap(new EclipseNode(this, type, childNodes, Kind.TYPE)); } private Collection<EclipseNode> buildFields(FieldDeclaration[] children) { List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); if (children != null) for (FieldDeclaration child : children) addIfNotNull(childNodes, buildField(child)); return childNodes; } private static <T> List<T> singleton(T item) { List<T> list = new ArrayList<T>(); if (item != null) list.add(item); return list; } private EclipseNode buildField(FieldDeclaration field) { if (field instanceof Initializer) return buildInitializer((Initializer)field); if (setAndGetAsHandled(field)) return null; List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); addIfNotNull(childNodes, buildStatement(field.initialization)); childNodes.addAll(buildAnnotations(field.annotations, true)); return putInMap(new EclipseNode(this, field, childNodes, Kind.FIELD)); } private EclipseNode buildInitializer(Initializer initializer) { if (setAndGetAsHandled(initializer)) return null; return putInMap(new EclipseNode(this, initializer, singleton(buildStatement(initializer.block)), Kind.INITIALIZER)); } private Collection<EclipseNode> buildMethods(AbstractMethodDeclaration[] children) { List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); if (children != null) for (AbstractMethodDeclaration method : children) addIfNotNull(childNodes, buildMethod(method)); return childNodes; } private EclipseNode buildMethod(AbstractMethodDeclaration method) { if (setAndGetAsHandled(method)) return null; List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); childNodes.addAll(buildArguments(method.arguments)); if (method instanceof ConstructorDeclaration) { ConstructorDeclaration constructor = (ConstructorDeclaration) method; addIfNotNull(childNodes, buildStatement(constructor.constructorCall)); } childNodes.addAll(buildStatements(method.statements)); childNodes.addAll(buildAnnotations(method.annotations, false)); return putInMap(new EclipseNode(this, method, childNodes, Kind.METHOD)); } //Arguments are a kind of LocalDeclaration. They can definitely contain lombok annotations, so we care about them. private Collection<EclipseNode> buildArguments(Argument[] children) { List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); if (children != null) for (LocalDeclaration local : children) { addIfNotNull(childNodes, buildLocal(local, Kind.ARGUMENT)); } return childNodes; } private EclipseNode buildLocal(LocalDeclaration local, Kind kind) { if (setAndGetAsHandled(local)) return null; List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); addIfNotNull(childNodes, buildStatement(local.initialization)); childNodes.addAll(buildAnnotations(local.annotations, true)); return putInMap(new EclipseNode(this, local, childNodes, kind)); } private Collection<EclipseNode> buildAnnotations(Annotation[] annotations, boolean varDecl) { List<EclipseNode> elements = new ArrayList<EclipseNode>(); if (annotations != null) for (Annotation an : annotations) addIfNotNull(elements, buildAnnotation(an, varDecl)); return elements; } private EclipseNode buildAnnotation(Annotation annotation, boolean field) { if (annotation == null) return null; boolean handled = setAndGetAsHandled(annotation); if (!field && handled) { // @Foo int x, y; is handled in eclipse by putting the same annotation node on 2 FieldDeclarations. return null; } return putInMap(new EclipseNode(this, annotation, null, Kind.ANNOTATION)); } private Collection<EclipseNode> buildStatements(Statement[] children) { List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); if (children != null) for (Statement child : children) addIfNotNull(childNodes, buildStatement(child)); return childNodes; } private EclipseNode buildStatement(Statement child) { if (child == null) return null; if (child instanceof TypeDeclaration) return buildType((TypeDeclaration)child); if (child instanceof LocalDeclaration) return buildLocal((LocalDeclaration)child, Kind.LOCAL); if (setAndGetAsHandled(child)) return null; return drill(child); } private EclipseNode drill(Statement statement) { List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); for (FieldAccess fa : fieldsOf(statement.getClass())) childNodes.addAll(buildWithField(EclipseNode.class, statement, fa)); return putInMap(new EclipseNode(this, statement, childNodes, Kind.STATEMENT)); } /** For Eclipse, only Statement counts, as Expression is a subclass of it, even though this isn't * entirely correct according to the JLS spec (only some expressions can be used as statements, not all of them). */ @Override protected Collection<Class<? extends ASTNode>> getStatementTypes() { return Collections.<Class<? extends ASTNode>>singleton(Statement.class); } private static class EcjReflectionCheck { private static final String COMPILATIONRESULT_TYPE = "org.eclipse.jdt.internal.compiler.CompilationResult"; public static Method addProblemToCompilationResult; public static final Throwable problem; static { Throwable problem_ = null; Method m = null; try { m = EclipseAstProblemView.class.getMethod("addProblemToCompilationResult", char[].class, Class.forName(COMPILATIONRESULT_TYPE), boolean.class, String.class, int.class, int.class); } catch (Throwable t) { // That's problematic, but as long as no local classes are used we don't actually need it. // Better fail on local classes than crash altogether. problem_ = t; } addProblemToCompilationResult = m; problem = problem_; } } }
package rgms.infrastructure; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.*; import rgms.model.User; /** * * @author Tyler 2 */ public class AuthenticationManager { public static Session LoadCurrentSession() { return null; } public static Session Login(String username, String password, boolean rememberMe) { Session userSession = null; try { JDBCConnection conn = new JDBCConnection(); String query = "SELECT * FROM Users WHERE Username='" + username + "' AND Passphrase='" + password + "'" ; try { conn.getConnection(); ResultSet rs = conn.executeQuery(query); /** * Since usernames are unique, there should only be at most * one set returned by the query */ if (rs != null && rs.next()) { userSession = createSession(rs); } conn.setDone(); } catch (Exception e) { Logger.getLogger(AuthenticationManager.class.getName()).log(Level.SEVERE, null, e); } } catch (Exception ex) { Logger.getLogger(AuthenticationManager.class.getName()).log(Level.SEVERE, null, ex); } return userSession; } private static Session createSession(ResultSet rs) throws SQLException { String rsUsername = rs.getString("Username"); String rsPassword = rs.getString("Passphrase"); int rsUserId = Integer.parseInt(rs.getString("Id")); String rsFirstName = rs.getString("Firstname"); String rsLastName = rs.getString("Lastname"); String rsImageReference = rs.getString("ImageReference"); User thisUser = new User(rsUserId, rsFirstName, rsLastName, rsUsername, rsPassword, rsImageReference); Session session = new Session(false, rsUserId, thisUser); return session; } }
package org.helioviewer.jhv.base; import java.net.Authenticator; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.net.Proxy; import org.helioviewer.jhv.Settings; public class ProxySettings { public static final Proxy proxy; static { String[] httpVars = { "http.proxyHost", "http.proxyPort", "http.proxyUser", "http.proxyPassword" }; String[] socksVars = { "socksProxyHost", "socksProxyPort", "java.net.socks.username", "java.net.socks.password" }; Proxy _proxy = detectProxy(httpVars[0], httpVars[1], Proxy.Type.HTTP); if (_proxy == null) _proxy = detectProxy(socksVars[0], socksVars[1], Proxy.Type.SOCKS); if (_proxy == null) _proxy = Proxy.NO_PROXY; proxy = _proxy; if (proxy != Proxy.NO_PROXY) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == RequestorType.PROXY) { String[] vars = proxy.type().equals(Proxy.Type.HTTP) ? httpVars : socksVars; String host = System.getProperty(vars[0]); String port = System.getProperty(vars[1]); String user = System.getProperty(vars[2]); String pass = System.getProperty(vars[3]); if (user == null || pass == null) { user = Settings.getSingletonInstance().getProperty("default.proxyUsername"); pass = Settings.getSingletonInstance().getProperty("default.proxyPassword"); } if (user != null && pass != null && getRequestingHost().equalsIgnoreCase(host) && Integer.toString(getRequestingPort()).equals(port)) { return new PasswordAuthentication(user, pass.toCharArray()); } } return null; } }); } } private static Proxy detectProxy(String host, String port, Proxy.Type type) { String proxyHost = System.getProperty(host); if (proxyHost != null) { try { int proxyPort = Integer.parseInt(System.getProperty(port)); return new Proxy(type, InetSocketAddress.createUnresolved(proxyHost, proxyPort)); } catch (Exception ignore) { } } return null; } public static void init() {} }
package org.helioviewer.jhv.layers; import java.awt.EventQueue; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Date; import javax.swing.JOptionPane; import javax.swing.table.AbstractTableModel; import org.helioviewer.jhv.gui.ImageViewerGui; import org.helioviewer.jhv.gui.components.MoviePanel; import org.helioviewer.jhv.gui.dialogs.MetaDataDialog; import org.helioviewer.jhv.io.FileDownloader; import org.helioviewer.viewmodel.view.ImageInfoView; import org.helioviewer.viewmodel.view.LayeredView; import org.helioviewer.viewmodel.view.View; import org.helioviewer.viewmodel.view.jp2view.JHVJP2View; import org.helioviewer.viewmodel.view.jp2view.JHVJPXView; import org.helioviewer.viewmodel.view.jp2view.datetime.ImmutableDateTime; /** * This class is a (redundant) representation of the LayeredView + ViewChain * state, and, in addition to this, introduces the concept of an "activeLayer", * which is the Layer that is currently operated on by the user/GUI. * * This class is mainly used by the LayerTable(Model) as an abstraction to the * ViewChain. * * Future development plans still have to show if it is worth to keep this * class, or if the abstraction should be avoided and direct access to the * viewChain/layeredView should be used in all GUI classes. * * @author Malte Nuhn */ public class LayersModel extends AbstractTableModel { private static final LayersModel layersModel = new LayersModel(); private int activeLayer = -1; private final ArrayList<LayersListener> layerListeners = new ArrayList<LayersListener>(); private static final LayeredView layeredView = new LayeredView(); /** * Method returns the sole instance of this class. * * @return the only instance of this class. * */ public static LayersModel getSingletonInstance() { if (!EventQueue.isDispatchThread()) { System.out.println(">>> You have been naughty: " + Thread.currentThread().getName()); Thread.dumpStack(); System.exit(1); } return layersModel; } private LayersModel() { } public LayeredView getLayeredView() { return layeredView; } /* <LayerTableModel> */ /** * {@inheritDoc} */ @Override public int getRowCount() { return layeredView.getNumLayers(); } /** * {@inheritDoc} Hardcoded value of columns. This value is dependent on the * actual design of the LayerTable */ @Override public int getColumnCount() { return 4; } /** * Return the LayerDescriptor for the given row of the table, regardless * which column is requested. */ @Override public Object getValueAt(int idx, int col) { return layeredView.getLayerDescriptor(getLayer(idx)); } /* </LayerTableModel> */ /** * Return the view associated with the active Layer * * @return View associated with the active Layer */ public JHVJP2View getActiveView() { return getLayer(activeLayer); } /** * @return Index of the currently active Layer */ public int getActiveLayer() { return activeLayer; } /** * @param idx * - Index of the layer to be retrieved * @return View associated with the given index */ private JHVJP2View getLayer(int idx) { idx = invertIndex(idx); if (idx >= 0 && idx < getNumLayers()) { return layeredView.getLayer(idx); } return null; } /** * Set the activeLayer to the Layer associated with the given index * * @param idx * - index of the layer to be set as active Layer */ public void setActiveLayer(int idx) { View view = getLayer(idx); if (view == null && idx != -1) { return; } activeLayer = idx; fireActiveLayerChanged(view); } /** * Return the timestamp of the first available image data of the layer in * question * * @param view * - View that can be associated with the layer in question * @return timestamp of the first available image data, null if no * information available */ public ImmutableDateTime getStartDate(JHVJP2View view) { ImmutableDateTime result = null; if (view instanceof JHVJPXView) { result = ((JHVJPXView) view).getFrameDateTime(0); } else { result = view.getMetaData().getDateTime(); } return result; } /** * Return the timestamp of the first available image data of the layer in * question * * @param idx * - index of the layer in question * @return timestamp of the first available image data, null if no * information available */ public ImmutableDateTime getStartDate(int idx) { return getStartDate(getLayer(idx)); } /** * Return the timestamp of the first available image data * * @return timestamp of the first available image data, null if no * information available */ public Date getFirstDate() { ImmutableDateTime earliest = null; for (int idx = 0; idx < getNumLayers(); idx++) { ImmutableDateTime start = getStartDate(idx); if (start == null) { continue; } if (earliest == null || start.compareTo(earliest) < 0) { earliest = start; } } return earliest == null ? null : earliest.getTime(); } /** * Return the timestamp of the last available image data of the layer in * question * * @param view * - View that can be associated with the layer in question * @return timestamp of the last available image data, null if no * information available */ public ImmutableDateTime getEndDate(JHVJP2View view) { ImmutableDateTime result = null; if (view instanceof JHVJPXView) { JHVJPXView tmv = (JHVJPXView) view; int lastFrame = tmv.getMaximumFrameNumber(); result = tmv.getFrameDateTime(lastFrame); } else { result = view.getMetaData().getDateTime(); } return result; } /** * Return the timestamp of the last available image data * * @return timestamp of the last available image data, null if no * information available */ public Date getLastDate() { ImmutableDateTime latest = null; for (int idx = 0; idx < getNumLayers(); idx++) { ImmutableDateTime end = getEndDate(idx); if (end == null) { continue; } if (latest == null || end.compareTo(latest) > 0) { latest = end; } } return latest == null ? null : latest.getTime(); } /** * Return the timestamp of the last available image data of the layer in * question * * @param idx * - index of the layer in question * @return timestamp of the last available image data, null if no * information available */ public ImmutableDateTime getEndDate(int idx) { return getEndDate(getLayer(idx)); } /** * Find the index of the layer that can be associated with the given view * * @param view * - View that can be associated with the layer in question * @return index of the layer that can be associated with the given view */ public int findView(JHVJP2View view) { int idx = -1; if (view != null) { idx = layeredView.getLayerLevel(view); } return invertIndex(idx); } /** * Important internal method to convert between LayersModel indexing and * LayeredView indexing. Calling it twice should form the identity * operation. * * LayersModel indices go from 0 .. (LayerCount - 1), with 0 being the * uppermost layer * * whereas * * LayeredView indies go from (LayerCount - 1) .. 0, with 0 being the layer * at the bottom. * * @param idx * to be converted from LayersModel to LayeredView or the other * direction. * @return the inverted index */ private int invertIndex(int idx) { int num = this.getNumLayers(); // invert indices if (idx >= 0 && num > 0) { idx = num - 1 - idx; } return idx; } /** * Important internal method to convert between LayersModel indexing and * LayeredView indexing. * * Since this index transformation involves the number of layers, this * transformation has to pay respect to situation where the number of layers * has changed. * * @param idx * to be converted from LayersModel to LayeredView or the other * direction after a layer has been deleted * @return inverted index */ private int invertIndexDeleted(int idx) { int num = this.getNumLayers(); if (idx >= 0) { idx = num - idx; } return idx; } /** * Return the number of layers currently available * * @return number of layers */ public int getNumLayers() { return layeredView.getNumLayers(); } /** * Change the visibility of the layer in question, and automatically * (un)link + play/pause the layer * * @param view * - View that can be associated with the layer in question */ public void toggleVisibility(JHVJP2View view) { layeredView.toggleVisibility(view); ImageViewerGui.getSingletonInstance().getMoviePanelContainer().layerVisibilityChanged(view); int idx = findView(view); fireTableRowsUpdated(idx, idx); boolean visible = layeredView.isVisible(view); setLink(view, visible); if (!visible && view instanceof JHVJPXView) { ((JHVJPXView) view).pauseMovie(); } } public void toggleVisibility(int idx) { toggleVisibility(getLayer(idx)); } /** * Get the visibility of the layer in question * * @param view * - View that can be associated with the layer in question * * @return true if the layer is visible */ public boolean isVisible(JHVJP2View view) { return layeredView.isVisible(view); } /** * Check if the given index is valid, given the current state of the * LayeredView/ViewChain * * @param idx * - index of the layer in question * @return true if the index is valid */ private boolean isValidIndex(int idx) { if (idx >= 0 && idx < getNumLayers()) { return true; } return false; } /** * Calulate a new activeLayer after the old Layer has been deleted * * @param oldActiveLayerIdx * - index of old active, but deleted, layer * @return the index of the new active layer to choose, or -1 if no suitable * new layer can be found */ private int determineNewActiveLayer(int oldActiveLayerIdx) { int candidate = oldActiveLayerIdx; if (!isValidIndex(candidate)) { candidate = getNumLayers() - 1; } return candidate; } /** * Trigger downloading the layer in question * * @param view * - View that can be associated with the layer in question */ public void downloadLayer(JHVJP2View view) { if (view == null) { return; } Thread downloadThread = new Thread(new Runnable() { private ImageInfoView theInfoView; @Override public void run() { downloadFromJPIP(theInfoView); } public Runnable init(ImageInfoView theInfoView) { this.theInfoView = theInfoView; return this; } }.init(view), "DownloadFromJPIPThread"); downloadThread.start(); } /** * Downloads the complete image from the JPIP server. * * Changes the source of the ImageInfoView afterwards, since a local file is * always faster. */ private void downloadFromJPIP(ImageInfoView infoView) { FileDownloader fileDownloader = new FileDownloader(); URI downloadUri = infoView.getDownloadURI(); URI uri = infoView.getUri(); // the http server to download the file from is unknown if (downloadUri.equals(uri) && !downloadUri.toString().contains("delphi.nascom.nasa.gov")) { String inputValue = JOptionPane.showInputDialog("To download this file, please specify a concurrent HTTP server address to the JPIP server: ", uri); if (inputValue != null) { try { downloadUri = new URI(inputValue); } catch (URISyntaxException e) { } } } File downloadDestination = fileDownloader.getDefaultDownloadLocation(uri); try { if (!fileDownloader.get(downloadUri, downloadDestination, "Downloading " + infoView.getName())) { return; } } catch (IOException e) { e.printStackTrace(); return; } } /** * Trigger showing a dialog displaying the meta data of the layer in * question. * * @param view * - View that can be associated with the layer in question * * @see org.helioviewer.jhv.gui.dialogs.MetaDataDialog */ public void showMetaInfo(JHVJP2View view) { if (view == null) { return; } MetaDataDialog dialog = new MetaDataDialog(); dialog.setMetaData(view); dialog.showDialog(); } public void addLayer(JHVJP2View view) { if (view == null) { return; } int newIndex = invertIndex(layeredView.addLayer(view)); // wtf while (view.getSubimageData() == null) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } ImageViewerGui ivg = ImageViewerGui.getSingletonInstance(); // If MoviewView, add MoviePanel if (view instanceof JHVJPXView) { MoviePanel moviePanel = new MoviePanel((JHVJPXView) view); if (isTimed(view)) { setLink(view, true); } ivg.getMoviePanelContainer().addLayer(view, moviePanel); } else { MoviePanel moviePanel = new MoviePanel(null); ivg.getMoviePanelContainer().addLayer(view, moviePanel); } fireLayerAdded(newIndex); fireTableRowsInserted(newIndex, newIndex); setActiveLayer(newIndex); } /** * Remove the layer in question * * @param view * - View that can be associated with the layer in question */ public void removeLayer(JHVJP2View view) { if (view == null) { return; } if (view instanceof JHVJPXView) { MoviePanel moviePanel = MoviePanel.getMoviePanel((JHVJPXView) view); if (moviePanel != null) { moviePanel.remove(); } } int oldIndex = invertIndexDeleted(layeredView.removeLayer(view)); fireLayerRemoved(oldIndex); fireTableRowsDeleted(oldIndex, oldIndex); int newIndex = determineNewActiveLayer(oldIndex); setActiveLayer(newIndex); } public void removeLayer(int idx) { removeLayer(getLayer(idx)); } /** * Set the link-state of the layer in question * * @param view * - View that can be associated with the layer in question * @param link * - true if the layer in question should be linked */ private void setLink(JHVJP2View view, boolean link) { if (view == null) { return; } if (view instanceof JHVJPXView) { MoviePanel moviePanel = MoviePanel.getMoviePanel((JHVJPXView) view); if (moviePanel != null) { moviePanel.setMovieLink(link); } } } /** * Check whether the layer in question has timing information * * @param idx * - index of the layer in question * @return true if the layer in question has timing information */ public boolean isTimed(int idx) { return isTimed(getLayer(idx)); } /** * Check whether the layer in question has timing information * * @param view * - View that can be associated with the layer in question * @return true if the layer in question has timing information */ private boolean isTimed(JHVJP2View view) { if (view == null) return false; return layeredView.getLayerDescriptor(view).isTimed; } /** * Move the layer in question up * * @param view * - View that can be associated with the layer in question */ private void moveLayerUp(JHVJP2View view) { if (view == null) { return; } // Operates on the (inverted) LayeredView indices int level = layeredView.getLayerLevel(view); if (level < layeredView.getNumLayers() - 1) { level++; } layeredView.moveView(view, level); setActiveLayer(invertIndex(level)); } public void moveLayerUp(int idx) { moveLayerUp(getLayer(idx)); } /** * Move the layer in question down * * @param view * - View that can be associated with the layer in question */ private void moveLayerDown(JHVJP2View view) { if (view == null) { return; } // Operates on the (inverted) LayeredView indices int level = layeredView.getLayerLevel(view); if (level > 0) { level } layeredView.moveView(view, level); setActiveLayer(invertIndex(level)); } public void moveLayerDown(int idx) { moveLayerDown(getLayer(idx)); } /** * Return the current framerate for the layer in question * * @param view * - View that can be associated with the layer in question * @return the current framerate or 0 if the movie is not playing, or if * an error occurs */ public int getFPS(JHVJP2View view) { int result = 0; if (view instanceof JHVJPXView) { result = (int) (Math.round(((JHVJPXView) view).getActualFramerate() * 100) / 100); } return result; } /** * Check whether the layer in question is a Remote View * * @param view * - View that can be associated with the layer in question * @return true if the layer in question is a remote view */ public boolean isRemote(JHVJP2View view) { if (view != null) { return view.isRemote(); } else { return false; } } /** * Check whether the layer in question is connected to a JPIP server * * @param view * - View that can be associated with the layer in question * @return true if the layer is connected to a JPIP server */ public boolean isConnectedToJPIP(JHVJP2View view) { if (view != null) { return view.isConnectedToJPIP(); } else { return false; } } /** * Return a representation of the layer in question * * @param view * - View that can be associated with the layer in question * @return LayerDescriptor of the current state of the layer in question */ public LayerDescriptor getDescriptor(JHVJP2View view) { return layeredView.getLayerDescriptor(view); } private void fireLayerRemoved(int oldIndex) { for (LayersListener ll : layerListeners) { ll.layerRemoved(oldIndex); } } private void fireLayerAdded(int newIndex) { for (LayersListener ll : layerListeners) { ll.layerAdded(newIndex); } } private void fireActiveLayerChanged(View view) { for (LayersListener ll : layerListeners) { ll.activeLayerChanged(view); } } public void addLayersListener(LayersListener layerListener) { layerListeners.add(layerListener); } public void removeLayersListener(LayersListener layerListener) { layerListeners.remove(layerListener); } }
package cs201.gui.transit; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Stack; import javax.imageio.ImageIO; import javax.swing.JOptionPane; import cs201.gui.CityPanel; import cs201.gui.CityPanel.DrivingDirection; import cs201.gui.CityPanel.WalkingDirection; import cs201.gui.Gui; import cs201.roles.transit.PassengerRole; import cs201.structures.Structure; public class PassengerGui implements Gui { class MyPoint extends Point { MyPoint prev; WalkingDirection move; public MyPoint(int i, int j, MyPoint previous,WalkingDirection moveDir) { super(i,j); prev = previous; move = moveDir; } public boolean equals(MyPoint p) { return p.x == x && p.y == y; } } public static ArrayList<BufferedImage> movementSprites; private PassengerRole pass; private Structure destination; private int destX,destY; private int x, y; private boolean fired; private boolean present; private CityPanel city; private WalkingDirection currentDirection; private Stack<WalkingDirection> moves; public PassengerGui(PassengerRole pass,CityPanel city) { this(pass,city,pass.getCurrentLocation()); } public PassengerGui(PassengerRole pass,CityPanel city, int x, int y) { this.pass = pass; this.city = city; this.x = x; this.y = y; destX = x; destY = y; fired = true; present = false; currentDirection = WalkingDirection.None; movementSprites = new ArrayList<BufferedImage>(); try { movementSprites.add(null); movementSprites.add(WalkingDirection.North.ordinal(),ImageIO.read(new File("data/TransitSprites/Walk_North.png"))); movementSprites.add(WalkingDirection.South.ordinal(),ImageIO.read(new File("data/TransitSprites/Walk_South.png"))); movementSprites.add(WalkingDirection.East.ordinal(),ImageIO.read(new File("data/TransitSprites/Walk_East.png"))); movementSprites.add(WalkingDirection.West.ordinal(),ImageIO.read(new File("data/TransitSprites/Walk_West.png"))); } catch(Exception e) { System.out.println("ERROR"); e.printStackTrace(); } } public PassengerGui(PassengerRole pass,CityPanel city, Structure s) { this(pass,city,(int)s.x,(int)s.y); } public void setPresent(boolean present) { this.present = present; } public void doGoToLocation(Structure structure) { destination = structure; destX = (int)structure.getEntranceLocation().x; destY = (int)structure.getEntranceLocation().y; fired = false; present = true; findPath(); } private void findPath() { WalkingDirection[][] map = city.getWalkingMap(); moves = new Stack<WalkingDirection>(); Queue<MyPoint> location = new LinkedList<MyPoint>(); ArrayList<MyPoint> visitedPoints = new ArrayList<MyPoint>(); MyPoint startLoc = new MyPoint(x/CityPanel.GRID_SIZE,y/CityPanel.GRID_SIZE,null,WalkingDirection.None); MyPoint destination = new MyPoint(destX/CityPanel.GRID_SIZE,destY/CityPanel.GRID_SIZE,null,WalkingDirection.None); location.add(startLoc); visitedPoints.add(startLoc); //run a BFS while(!location.isEmpty()) { MyPoint p = location.remove(); if(p.equals(destination)) { MyPoint head = p; while(head != null) { moves.add(head.move); head = head.prev; } break; } WalkingDirection currentDirection = map[p.y][p.x]; if(currentDirection == WalkingDirection.Turn) { List<WalkingDirection> validDirections = getJunctionDirections(map,p.x,p.y); for(WalkingDirection dir : validDirections) { MyPoint nextPoint = getPointFromDirection(p,dir); if(!visitedPoints.contains(nextPoint)) { visitedPoints.add(nextPoint); location.add(nextPoint); } } } else { MyPoint nextPoint = getPointFromDirection(p,currentDirection); if(!visitedPoints.contains(nextPoint)) { visitedPoints.add(nextPoint); location.add(nextPoint); } } } if(moves.isEmpty()) { JOptionPane.showMessageDialog(null,""+pass.getName()+": I cannot find a path."); } else { //clear first element moves.pop(); } } private MyPoint getPointFromDirection(MyPoint p, WalkingDirection dir) { switch(dir) { case East: return new MyPoint(p.x+1,p.y,p,dir); case North: return new MyPoint(p.x,p.y-1,p,dir); case South: return new MyPoint(p.x,p.y+1,p,dir); case West: return new MyPoint(p.x-1,p.y,p,dir); default: return new MyPoint(p.x,p.y-1,p,WalkingDirection.North); } } //Make me abstract for subclasses! public void draw(Graphics2D g) { g.setColor(Color.RED); g.drawImage (movementSprites.get(currentDirection.ordinal()),x,y,CityPanel.GRID_SIZE,CityPanel.GRID_SIZE,null); g.setColor(Color.BLACK); g.drawString(""+destination, x,y); g.drawString(""+pass.getName(), x,y+CityPanel.GRID_SIZE); //g.fillRect(x,y,CityPanel.GRID_SIZE,CityPanel.GRID_SIZE); } @Override public void updatePosition() { if(!fired) { if(x == destX && y == destY) { fired = true; pass.msgAnimationFinished (); return; } switch(currentDirection) { case East: x++; break; case North: y break; case South: y++; break; case West: x break; default: break; } if(x % CityPanel.GRID_SIZE == 0 && y % CityPanel.GRID_SIZE == 0 && !moves.isEmpty()) { currentDirection = moves.pop(); return; } } } private void junction(WalkingDirection[][] map, int x2, int y2) { List<WalkingDirection> validDirections = getJunctionDirections(map,x2,y2); if(validDirections.size() == 1) { currentDirection = validDirections.get(0); return; } else if(validDirections.size() == 3) { if(x != destX) { for(WalkingDirection dir : validDirections) { currentDirection = dir; return; } } else { for(int i = 0; i < validDirections.size(); i++) { WalkingDirection dir = validDirections.get(i); if(dir == WalkingDirection.West || dir == WalkingDirection.East) { validDirections.remove(dir); } } } } if(validDirections.size() == 2) { if(WalkingDirection.opposites(validDirections.get(0),validDirections.get(1))) { if(validDirections.get(0).isHorizontal()) { if(x > destX) { currentDirection = WalkingDirection.West; return; } else { currentDirection = WalkingDirection.East; return; } } else { if(y > destY) { currentDirection = WalkingDirection.North; return; } else { currentDirection = WalkingDirection.South; return; } } } else { int dX = destX - x; int dY = destY - y; WalkingDirection towardsX = dX > 0?WalkingDirection.East:WalkingDirection.West; WalkingDirection towardsY = dY > 0?WalkingDirection.South:WalkingDirection.North; if(x == destX) { WalkingDirection dir = WalkingDirection.None; WalkingDirection toRemove = WalkingDirection.None; for(WalkingDirection d : validDirections) { if(!d.isHorizontal() && d == towardsY) { dir = d; } else if(!d.isHorizontal() && d != towardsY) { toRemove = d; } } if(toRemove != WalkingDirection.None) { validDirections.remove(toRemove); dir = validDirections.get(0); } if(dir != WalkingDirection.None) { currentDirection = dir; return; } } else if(y == destY) { WalkingDirection dir = WalkingDirection.None; WalkingDirection toRemove = WalkingDirection.None; for(WalkingDirection d : validDirections) { if(!d.isVertical() && d == towardsX) { dir = d; } else if(!d.isVertical() && d != towardsX) { toRemove = d; } } if(toRemove != WalkingDirection.None) { validDirections.remove(toRemove); dir = validDirections.get(0); } if(dir != WalkingDirection.None) { currentDirection = dir; return; } } else { WalkingDirection dir = WalkingDirection.None; WalkingDirection toRemove = WalkingDirection.None; for(WalkingDirection d : validDirections) { if(d.isVertical() && d == towardsY) { dir = d; } else if(d.isVertical() && d != towardsY) { toRemove = d; } } if(toRemove != WalkingDirection.None) { validDirections.remove(toRemove); dir = validDirections.get(0); } if(dir != WalkingDirection.None) { currentDirection = dir; return; } else { currentDirection = WalkingDirection.North; } } } } } private List<WalkingDirection> getJunctionDirections(WalkingDirection[][] map,int x2, int y2) { List<WalkingDirection> validDirections = new ArrayList<WalkingDirection>(); int leftX = x2-1; int rightX = x2+1; int upY = y2 - 1; int downY = y2 + 1; if(inBounds(map,leftX,y2) && getDirection(map,leftX,y2) == WalkingDirection.West) { validDirections.add(WalkingDirection.West); } if(inBounds(map,rightX,y2) && getDirection(map,rightX,y2) == WalkingDirection.East) { validDirections.add(WalkingDirection.East); } if(inBounds(map,x2,upY) && getDirection(map,x2,upY) == WalkingDirection.North) { validDirections.add(WalkingDirection.North); } if(inBounds(map,x2,downY) && getDirection(map,x2,downY) == WalkingDirection.South) { validDirections.add(WalkingDirection.South); } return validDirections; } private WalkingDirection getDirection(WalkingDirection[][] map, int x, int y) { return map[y][x]; } private boolean inBounds(WalkingDirection[][] map, int x2, int y2) { return y2 < map.length && y2 >= 0 && x2 >= 0 && x2 < map[y2].length; } @Override public boolean isPresent() { return present; } public void setLocation(int x, int y) { this.x = x; this.y = y; } }
package backend; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.util.ArrayList; import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class Preferences { /** * The purposes of this class is to read, write, and hold application preferences. * Essentially, anything that needs to be loaded from disk at runtime and passed * into any of the core components for configuration purposes is done by this class. * Currently, it's primary tasks include: * - providing the location of the derby database * - keeping track of which seed file was used to create the derby database * - remembering which genre codes file users selected (optional) * * NOTE: Although not explicitly supported within the program, you can bypass the * default pagemaps/ directory by editing the configuration file that Preferences * loads and adding a pagemapdir= field. Otherwise, Preferences will stick with * the internal default (defined here, NOT IN PAGEMAPPER). */ private final File prefsFile; public final static String DEFAULT_PREF_FILE = "genrebrowser.ini"; private String derbyDir = null, genreCodes = null, pageMapDir = "pagemaps/"; private String source; private String[][] generalCodes, pageCodes; public Preferences(String filename) { /** * This constructor allows for alternate preference profiles. To use just the * default file (as PrimaryWindow does), call it as: * Preferences p = new Preferences(Preferences.DEFAULT_PREF_FILE). * */ prefsFile = new File(filename); while(derbyDir == null) { if (prefsFile.exists()) { try { readPrefs(); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Problem reading file. Please try again.\nExiting.","Loading Error",JOptionPane.ERROR_MESSAGE); } } else { // If the filename passed into the constructor isn't found, assume that // this is a first-time run and run configuration sequence. System.out.println(filename + " does not exist. Creating new workspace."); firstTimeConfig(); } } } private void readPrefs() throws IOException { /** * Reads the selected preferences file from disk and parses its contents, setting * the internal configuration variables to match the fields it finds. Line input * is parsed using a simple regex split and a String switch. */ ArrayList<String> rawtext = new ArrayList<String>(); String line; BufferedReader lines = new BufferedReader(new FileReader(prefsFile)); while((line = lines.readLine()) != null){ rawtext.add(line.trim()); } lines.close(); for (int i=0;i<rawtext.size();i++) { if(rawtext.get(i) == "#PREFS") { continue; } else if (rawtext.get(i).length() > 1 && rawtext.get(i).indexOf("=") > 0) { String[] parts = rawtext.get(i).split("="); // Right now there are only four possible fields, but you could add more // by expanding this switch statement. if ("databasedir".equals(parts[0])) derbyDir = parts[1]; else if ("sourcefile".equals(parts[0])) source = parts[1]; else if ("genrecodes".equals(parts[0])) genreCodes = parts[1]; else if ("pagemapdir".equals(parts[0])) pageMapDir = parts[1]; } } System.out.println("Preferences loaded."); if(genreCodes != null) { // If users selected a genre codes file during a past session, retrieve it! System.out.println("Trying to load genre codes file."); readCodes(); } } private void firstTimeConfig() { /** * This method is a series of pop-up dialogs that ask users to configure the * browser. Right now, it only asks for a seed file and for a directory name * for the local derby database. */ JOptionPane.showMessageDialog(null, "Please specify a seed file for the browser's database.","First Time Configuration",JOptionPane.OK_OPTION); JFileChooser seed = new JFileChooser(System.getProperty("user.dir")); if (seed.showOpenDialog(null) == JFileChooser.CANCEL_OPTION) System.exit(1); source = seed.getSelectedFile().getAbsolutePath(); derbyDir = (String)JOptionPane.showInputDialog(null,"Choose a name for the browser's database:","First Time Configuration",JOptionPane.PLAIN_MESSAGE,null,null,null); derbyDir = new File(derbyDir).getAbsolutePath(); } public void writePrefs() { /** * Writes configuration settings to disk. It will write to the same file that it * read from initially, or in the case of a first-run to the filename passed into * the constructor at creation. */ try { BufferedWriter output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(prefsFile.getAbsolutePath()),"UTF-8")); output.write("#PREFS\n"); output.write("databasedir=" + derbyDir + "\n"); output.write("sourcefile=" + source + "\n"); // If the pagemapdir was overrided by the current configuration file, remember it. if (!pageMapDir.equals("pagemaps/")) { output.write("pagemapdir=" + pageMapDir + "\n"); } // If users selected a genre codes file, remember it. if (genreCodes != null) { output.write("genrecodes=" + genreCodes + "\n"); } output.close(); System.out.println("Preferences written to disk."); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Problem writing file. Please ensure you have the necessary privledges.","Write Error",JOptionPane.ERROR_MESSAGE); } } // The following block of codes are just private variables that require public // request methods so that they are effectively read only outside of this class. // This is standard OOP practice. public String getDerbyDir() { return derbyDir; } public String getSource() { return source; } public boolean exists() { return new File(derbyDir).isDirectory(); } public String[][] getGeneralCodes() { return generalCodes; } public String[][] getPageCodes() { return pageCodes; } public String getMapDir() { return pageMapDir; } public void setGenreCodes(String filename) { /** * Public interface method for genre code files. The code reader is private and * internal. This sets the internal filename and then loads the internal code reader. */ genreCodes = filename; readCodes(); } private void readCodes () { /** * Reads the genre codes file from disk and parses codes into two categories: * general codes that reflect volume and page level data and those that could * reflect only page level data. There's no real reason to keep them separate right * now other than to display them as distinct categories to users. */ String line; // ArrayLists are used for their Python-like functionally. They are converted to // fixed length arrays at the end of this method. ArrayList<String[]> all, page; all = new ArrayList<String[]>(); page = new ArrayList<String[]>(); boolean both = true; try { InputStream codesIn = new FileInputStream(new File(genreCodes)); BufferedReader inLines = new BufferedReader(new InputStreamReader(codesIn,Charset.forName("UTF-8"))); while ((line = inLines.readLine()) != null) { if (line.trim().length() > 0) { if(line.contains("#GENERAL")) { both = true; } else if (line.contains("#PAGES")) { both = false; } else { if (both) { all.add(line.trim().split("\\t",2)); } else { page.add(line.trim().split("\\t",2)); } } } } inLines.close(); generalCodes = all.toArray(new String[all.size()][2]); pageCodes = page.toArray(new String[page.size()][2]); } catch (IOException e) { JOptionPane.showMessageDialog(null, "Could not load Genre Codes from " + genreCodes + ".\nPlease ensure file exists.","Load Error.",JOptionPane.ERROR_MESSAGE); genreCodes = null; } } public boolean hasGenreCodes() { /** * Simple check to see if a genre code file has been selected (either at load-time * from the configuration file or during run-time by the user when starting the * PageMapper). */ if (genreCodes == null) { return false; } else { return true; } } }
package jorgediazest.util.modelquery; import com.liferay.portal.kernel.concurrent.ConcurrentHashSet; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.model.Portlet; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import jorgediazest.util.data.DataComparator; import jorgediazest.util.data.DataModelComparator; import jorgediazest.util.model.Model; import jorgediazest.util.model.ModelFactory; public class ModelQueryFactory { public ModelQueryFactory(ModelFactory modelFactory) throws Exception { this(modelFactory, null); } public ModelQueryFactory( ModelFactory modelFactory, ModelQueryClassFactory mqClassFactory) throws Exception { if (modelFactory == null) { throw new Exception("modelFactory cannot be null"); } this.modelFactory = modelFactory; if (mqClassFactory != null) { this.mqClassFactory = mqClassFactory; } } public DataComparatorFactory getDataComparatorFactory() { return dataComparatorFactory; } public ModelQuery getModelQueryObject(Class<?> clazz) { return getModelQueryObject(clazz.getName()); } public ModelQuery getModelQueryObject(Model model) { if ((model == null) || Validator.isNull(model.getClassName())) { return null; } if (cacheNullModelObject.contains(model.getClassName())) { return null; } ModelQuery modelQuery = cacheModelObject.get(model); if (modelQuery != null) { return modelQuery; } modelQuery = getModelQueryObjectNoCached(model); if (modelQuery == null) { cacheNullModelObject.add(model.getClassName()); return null; } cacheModelObject.put(model, modelQuery); return modelQuery; } public ModelQuery getModelQueryObject(String className) { Model model = modelFactory.getModelObject(className); if (model == null) { return null; } return this.getModelQueryObject(model); } public void setDataComparatorFactory( DataComparatorFactory dataComparatorFactory) { this.dataComparatorFactory = dataComparatorFactory; } public interface DataComparatorFactory { public DataComparator getDataComparator(ModelQuery query); } public interface ModelQueryClassFactory { public Class<? extends ModelQuery> getModelQueryClass(String className); } protected ModelQuery getModelQueryObjectNoCached(Model model) { String className = model.getClassName(); Class<? extends ModelQuery> modelClass = null; ModelQuery modelQuery = null; try { modelClass = mqClassFactory.getModelQueryClass(className); if (modelClass == null) { return null; } modelQuery = (ModelQuery)modelClass.newInstance(); modelQuery.setModelQueryFactory(this); modelQuery.init(model, dataComparatorFactory); } catch (Exception e) { if (_log.isWarnEnabled()) { _log.warn( "getModelObject(" + className + ") EXCEPTION " + e.getClass().getName() + ": " + e.getMessage()); } modelQuery = null; } return modelQuery; } protected Map<Model, ModelQuery> cacheModelObject = new ConcurrentHashMap<Model, ModelQuery>(); protected Set<String> cacheNullModelObject = new ConcurrentHashSet<String>(); protected DataComparatorFactory dataComparatorFactory = new DataComparatorFactory() { protected DataComparator dataComparator = new DataModelComparator( new String[] { "createDate", "status", "version", "name", "title", "description", "size" }); @Override public DataComparator getDataComparator(ModelQuery query) { return dataComparator; } }; protected Map<String, Set<Portlet>> handlerPortletMap = new HashMap<String, Set<Portlet>>(); protected ModelFactory modelFactory = null; protected ModelQueryClassFactory mqClassFactory = new ModelQueryClassFactory() { @Override public Class<? extends ModelQuery> getModelQueryClass( String className) { return DefaultModelQuery.class; } }; private static Log _log = LogFactoryUtil.getLog(ModelQueryFactory.class); }
/* * $Log: Adapter.java,v $ * Revision 1.17 2005-08-16 12:33:30 europe\L190409 * added NDC with correlationId * * Revision 1.16 2005/07/05 12:27:52 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * added possibility to end processing with an exception * * Revision 1.15 2005/01/13 08:55:15 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * Make threadContext-attributes available in PipeLineSession * * Revision 1.14 2004/09/08 14:14:41 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * adjusted error logging * * Revision 1.13 2004/08/19 07:16:21 unknown <unknown@ibissource.org> * Resolved problem of hanging adapter if stopRunning was called just after the * adapter was set to started * * Revision 1.12 2004/07/06 07:00:44 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * configure now throws less exceptions * * Revision 1.11 2004/06/30 10:02:23 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * improved error reporting * * Revision 1.10 2004/06/16 13:08:11 Johan Verrips <johan.verrips@ibissource.org> * Added configuration error when no pipeline was configured * * Revision 1.9 2004/06/16 12:34:46 Johan Verrips <johan.verrips@ibissource.org> * Added AutoStart functionality on Adapter * * Revision 1.8 2004/04/28 08:31:41 Johan Verrips <johan.verrips@ibissource.org> * Added getRunStateAsString function * * Revision 1.7 2004/04/13 11:37:13 Johan Verrips <johan.verrips@ibissource.org> * When the Adapter was in state "ERROR", it could not be stopped anymore. Fixed it. * * Revision 1.6 2004/04/06 14:52:52 Johan Verrips <johan.verrips@ibissource.org> * Updated handling of errors in receiver.configure() * * Revision 1.5 2004/03/30 07:29:53 Gerrit van Brakel <gerrit.van.brakel@ibissource.org> * updated javadoc * * Revision 1.4 2004/03/26 10:42:45 Johan Verrips <johan.verrips@ibissource.org> * added @version tag in javadoc * */ package nl.nn.adapterframework.core; import nl.nn.adapterframework.configuration.ConfigurationException; import nl.nn.adapterframework.errormessageformatters.ErrorMessageFormatter; import nl.nn.adapterframework.jms.JNDIBase; import nl.nn.adapterframework.jms.JmsRealm; import nl.nn.adapterframework.util.DateUtils; import nl.nn.adapterframework.util.JtaUtil; import nl.nn.adapterframework.util.MessageKeeper; import nl.nn.adapterframework.util.RunStateEnum; import nl.nn.adapterframework.util.RunStateManager; import nl.nn.adapterframework.util.StatisticsKeeper; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import java.util.Date; import java.util.Hashtable; import java.util.Iterator; import java.util.Vector; import javax.transaction.SystemException; import javax.transaction.UserTransaction; /** * The Adapter is the central manager in the IBIS Adapterframework, that has knowledge * and uses {@link IReceiver IReceivers} and a {@link PipeLine}. * * <b>responsibility</b><br/> * <ul> * <li>keeping and gathering statistics</li> * <li>processing messages, retrieved from IReceivers</li> * <li>starting and stoppping IReceivers</li> * <li>delivering error messages in a specified format</li> * </ul> * All messages from IReceivers pass through the adapter (multi threaded). * Multiple receivers may be attached to one adapter.<br/> * <br/> * The actual processing of messages is delegated to the {@link PipeLine} * object, which returns a {@link PipeLineResult}. If an error occurs during * the pipeline execution, the state in the <code>PipeLineResult</code> is set * to the state specified by <code>setErrorState</code>, which defaults to "ERROR". * * @version Id * @author Johan Verrips * @see nl.nn.adapterframework.core.IReceiver * @see nl.nn.adapterframework.core.PipeLine * @see nl.nn.adapterframework.util.StatisticsKeeper * @see nl.nn.adapterframework.util.DateUtils * @see nl.nn.adapterframework.util.MessageKeeper * @see nl.nn.adapterframework.core.PipeLineResult * */ public class Adapter extends JNDIBase implements Runnable, IAdapter { public static final String version = "$RCSfile: Adapter.java,v $ $Revision: 1.17 $ $Date: 2005-08-16 12:33:30 $"; private Vector receivers = new Vector(); private long lastMessageDate = 0; private PipeLine pipeline; private String name; private Logger log = Logger.getLogger(this.getClass()); private long numOfMessagesProcessed = 0; private long numOfMessagesInError = 0; private StatisticsKeeper statsMessageProcessingDuration = null; private long statsUpSince = System.currentTimeMillis(); private IErrorMessageFormatter errorMessageFormatter; private RunStateManager runState = new RunStateManager(); private boolean configurationSucceeded = false; private String description; private MessageKeeper messageKeeper; //instantiated in configure() private int messageKeeperSize = 10; //default length private boolean autoStart = true; /** * AutoStart indicates that the adapter should be started when the configuration * is started. * @param autoStart defaults to TRUE * @since 4.1.1 */ public void setAutoStart(boolean autoStart) { this.autoStart = autoStart; } /** * AutoStart indicates that the adapter should be started when the configuration * is started. AutoStart defaults to TRUE * @since 4.1.1 */ public boolean isAutoStart() { return autoStart; } // state to put in PipeLineResult when a PipeRunException occurs; private String errorState = "ERROR"; private String userTransactionUrl = "java:comp/UserTransaction"; /** * The nummer of message currently in process */ private int numOfMessagesInProcess = 0; public boolean configurationSucceeded() { return configurationSucceeded; } /* * This function is called by Configuration.registerAdapter, * to make configuration information available to the Adapter. <br/><br/> * This method also performs * a <code>Pipeline.configurePipes()</code>, as to configure the individual pipes. * @see nl.nn.adapterframework.core.Pipeline#configurePipes */ public void configure() throws ConfigurationException { configurationSucceeded = false; log.debug("configuring adapter [" + getName() + "]"); MessageKeeper messageKeeper = getMessageKeeper(); statsMessageProcessingDuration = new StatisticsKeeper(getName()); if (pipeline == null) { String msg = "No pipeline configured for adapter [" + getName() + "]"; messageKeeper.add(msg); throw new ConfigurationException(msg); } try { pipeline.setAdapter(this); pipeline.configurePipes(); messageKeeper.add("pipeline successfully configured"); Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); log.info("Adapter [" + name + "] is initializing receiver [" + receiver.getName() + "]"); receiver.setAdapter(this); try { receiver.configure(); messageKeeper.add("receiver [" + receiver.getName() + "] successfully configured"); } catch (ConfigurationException e) { String msg = "Adapter [" + getName() + "] got error initializing receiver [" + receiver.getName() + "]"; log.error(msg, e); messageKeeper.add(msg + ": " + e.getMessage()); } } configurationSucceeded = true; } catch (ConfigurationException e) { String msg = "Adapter [" + getName() + "] got error initializing pipeline"; messageKeeper.add(msg + ": " + e.getMessage()); log.error(msg, e); } } /** * Decrease the number of messages in process */ private synchronized void decNumOfMessagesInProcess(long duration) { synchronized (statsMessageProcessingDuration) { numOfMessagesInProcess numOfMessagesProcessed++; statsMessageProcessingDuration.addValue(duration); notifyAll(); } } public synchronized String formatErrorMessage( String errorMessage, Throwable t, String originalMessage, String messageID, INamedObject objectInError, long receivedTime) { if (errorMessageFormatter == null) { errorMessageFormatter = new ErrorMessageFormatter(); } // you never can trust an implementation, so try/catch! try { return errorMessageFormatter.format( errorMessage, t, objectInError, originalMessage, messageID, receivedTime); } catch (Exception e) { String msg = "got error while formatting errormessage, original errorMessage [" + errorMessage + "]"; msg = msg + " from [" + (objectInError == null ? "unknown-null" : objectInError.getName()) + "]"; log.error(msg, e); getMessageKeeper().add(msg + ": " + e.getMessage()); return errorMessage; } } /** * @return some functional description of the <code>Adapter</code> */ public String getDescription() { return this.description; } public java.lang.String getErrorState() { return errorState; } /** * retrieve the date and time of the last message */ public String getLastMessageDate() { String result = ""; if (lastMessageDate != 0) result = DateUtils.format(new Date(lastMessageDate), DateUtils.FORMAT_GENERICDATETIME); else result = "-"; return result; } /** * the MessageKeeper is for keeping the last <code>messageKeeperSize</code> * messages available, for instance for displaying it in the webcontrol * @see nl.nn.adapterframework.util.MessageKeeper */ public MessageKeeper getMessageKeeper() { if (messageKeeper == null) messageKeeper = new MessageKeeper(messageKeeperSize < 1 ? 1 : messageKeeperSize); return messageKeeper; } /** * the functional name of this adapter * @return the name of the adapter */ public String getName() { return name; } public UserTransaction getUserTransaction() throws TransactionException { try { return JtaUtil.getUserTransaction(getContext(), getUserTransactionUrl()); } catch (Exception e) { throw new TransactionException( "[" + name + "] could not obtain UserTransaction from URL [" + getUserTransactionUrl() + "]", e); } } /* protected TransactionManager getTransactionManager() throws TransactionException { if (tm == null) { try { Class c = Class.forName(getTransactionManagerFactoryClassName()); tm = (TransactionManager) c.getMethod(getTransactionManagerFactoryMethod(), null).invoke(null, null); } catch (Exception e) { throw new TransactionException("["+name+"] could not obtain TransactionManager",e); } } return tm; } */ public boolean inTransaction() throws TransactionException { try { return JtaUtil.inTransaction(getUserTransaction()); } catch (SystemException e) { throw new TransactionException("[" + name + "] could not obtain transaction status", e); } } /* public boolean inTransaction() throws TransactionException { try { Transaction tx = getTransaction(); return tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION; } catch (SystemException e) { throw new TransactionException("["+name+"] could not obtain transaction status",e); } } */ /* public Transaction createTransaction() throws TransactionException { TransactionManager tm = getTransactionManager(); try { log.debug("starting transaction, status before="+JtaUtil.displayTransactionStatus(tm)); tm.begin(); log.debug("started transaction, status after="+JtaUtil.displayTransactionStatus(tm)); } catch (Exception e) { log.debug("exception in starting transaction, status after="+JtaUtil.displayTransactionStatus(tm)); throw new TransactionException("["+name+"] could not start transaction",e); } return getTransaction(); } public Transaction getTransaction() throws TransactionException { TransactionManager tm = getTransactionManager(); try { log.debug("getting transaction, status before="+JtaUtil.displayTransactionStatus(tm)); return tm.getTransaction(); } catch (SystemException e) { throw new TransactionException("["+name+"] could not obtain transaction",e); } } */ /** * The number of messages for which processing ended unsuccessfully. */ public long getNumOfMessagesInError() { synchronized (statsMessageProcessingDuration) { return numOfMessagesInError; } } public int getNumOfMessagesInProcess() { synchronized (statsMessageProcessingDuration) { return numOfMessagesInProcess; } } public long getNumOfMessagesProcessed() { synchronized (statsMessageProcessingDuration) { return numOfMessagesProcessed; } } public Hashtable getPipeLineStatistics() { return pipeline.getPipeStatistics(); } public IReceiver getReceiverByName(String receiverName) { Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); if (receiver.getName().equalsIgnoreCase(receiverName)) { return receiver; } } return null; } public Iterator getReceiverIterator() { return receivers.iterator(); } public RunStateEnum getRunState() { return runState.getRunState(); } public String getRunStateAsString() { return runState.getRunState().toString(); } /** * Return the total processing duration as a StatisticsKeeper * @see nl.nn.adapterframework.util.StatisticsKeeper * @return nl.nn.adapterframework.util.StatisticsKeeper */ public StatisticsKeeper getStatsMessageProcessingDuration() { return statsMessageProcessingDuration; } public String getStatsUpSince() { return DateUtils.format(new Date(statsUpSince), DateUtils.FORMAT_GENERICDATETIME); } /** * Retrieve the waiting statistics as a <code>Hashtable</code> */ public Hashtable getWaitingStatistics() { return pipeline.getPipeWaitingStatistics(); } /** * The number of messages for which processing ended unsuccessfully. */ private void incNumOfMessagesInError() { synchronized (statsMessageProcessingDuration) { numOfMessagesInError++; } } /** * Increase the number of messages in process */ private void incNumOfMessagesInProcess(long startTime) { synchronized (statsMessageProcessingDuration) { numOfMessagesInProcess++; lastMessageDate = startTime; } } /** * * Process the receiving of a message * After all Pipes have been run in the PipeLineProcessor, the Object.toString() function * is called. The result is returned to the Receiver. * */ public PipeLineResult processMessage(String messageId, String message) { return processMessage(messageId, message, null); } public PipeLineResult processMessage(String messageId, String message, PipeLineSession pipeLineSession) { long startTime = System.currentTimeMillis(); try { return processMessageWithExceptions(messageId, message, pipeLineSession); } catch (Throwable t) { PipeLineResult result = new PipeLineResult(); result.setState(getErrorState()); String msg = "Illegal exception ["+t.getClass().getName()+"]"; INamedObject objectInError = null; if (t instanceof ListenerException) { Throwable cause = ((ListenerException) t).getCause(); if (cause instanceof PipeRunException) { PipeRunException pre = (PipeRunException) cause; msg = "error during pipeline processing"; objectInError = pre.getPipeInError(); } else if (cause instanceof ManagedStateException) { msg = "illegal state"; objectInError = this; } } result.setResult(formatErrorMessage(msg, t, message, messageId, objectInError, startTime)); return result; } } public PipeLineResult processMessageWithExceptions(String messageId, String message, PipeLineSession pipeLineSession) throws ListenerException { PipeLineResult result = new PipeLineResult(); long startTime = System.currentTimeMillis(); // prevent executing a stopped adapter // the receivers should implement this, but you never now.... RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STARTED) && !currentRunState.equals(RunStateEnum.STOPPING)) { String msgAdapterNotOpen = "Adapter [" + getName() + "] in state [" + currentRunState + "], cannot process message"; throw new ListenerException(new ManagedStateException(msgAdapterNotOpen)); } incNumOfMessagesInProcess(startTime); NDC.push(messageId); if (log.isDebugEnabled()) { // for performance reasons log.debug("Adapter [" + name + "] received message [" + message + "] with messageId [" + messageId + "]"); } else { log.info("Adapter [" + name + "] received message with messageId [" + messageId + "]"); } try { result = pipeline.process(messageId, message,pipeLineSession); if (log.isDebugEnabled()) { log.debug("Adapter [" + getName() + "] messageId[" + messageId + "] got exit-state [" + result.getState() + "] and result [" + result.toString() + "] from PipeLine"); } return result; } catch (Throwable t) { ListenerException e; if (t instanceof ListenerException) { e = (ListenerException) t; } else { e = new ListenerException(t); } incNumOfMessagesInError(); getMessageKeeper().add("error processing message with messageId [" + messageId+"]: " + e.getMessage()); log.error("Adapter: [" + getName() + "] caught exception message with messageId [" + messageId+"]",e); throw e; } finally { long endTime = System.currentTimeMillis(); long duration = endTime - startTime; //reset the InProcess fields, and increase processedMessagesCount decNumOfMessagesInProcess(duration); if (log.isDebugEnabled()) { // for performance reasons log.debug("Adapter: [" + getName() + "] STAT: Finished processing message with messageId [" + messageId + "] exit-state [" + result.getState() + "] started " + DateUtils.format(new Date(startTime), DateUtils.FORMAT_GENERICDATETIME) + " finished " + DateUtils.format(new Date(endTime), DateUtils.FORMAT_GENERICDATETIME) + " total duration: " + duration + " msecs"); } else { log.info("Adapter completed message with messageId [" + messageId + "] with exit-state [" + result.getState() + "]"); } NDC.pop(); } } /** * Register a PipeLine at this adapter. On registering, the adapter performs * a <code>Pipeline.configurePipes()</code>, as to configure the individual pipes. * @param pipeline * @throws ConfigurationException * @see PipeLine */ public void registerPipeLine(PipeLine pipeline) throws ConfigurationException { this.pipeline = pipeline; pipeline.setAdapter(this); log.debug("Adapter [" + name + "] registered pipeline [" + pipeline.toString() + "]"); } /** * Register a receiver for this Adapter * @param receiver * @see IReceiver */ public void registerReceiver(IReceiver receiver) { receivers.add(receiver); log.debug( "Adapter [" + name + "] registered receiver [" + receiver.getName() + "] with properties [" + receiver.toString() + "]"); } /** * do not call this method! start an adapter by the <code>start()</code> * method. This method starts the adapter, synchronizing the adapter itself. * This is done to prevent simultaenous starting and stopping of the adapter * by the web-application. */ public void run() { try { if (!configurationSucceeded) { log.error( "configuration of adapter [" + getName() + "] did not succeed, therefore starting the adapter is not possible"); getMessageKeeper().add("configuration did not succeed. Starting the adapter is not possible"); runState.setRunState(RunStateEnum.ERROR); return; } synchronized (runState) { RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STOPPED)) { String msg = "Adapter [" + getName() + "] is currently in state [" + currentRunState + "], ignoring start() command"; log.warn(msg); getMessageKeeper().add(msg); return; } // start the pipeline runState.setRunState(RunStateEnum.STARTING); } try { log.debug("Adapter [" + getName() + "] is starting pipeline"); pipeline.start(); } catch (PipeStartException pre) { log.error(pre); getMessageKeeper().add("Adapter [" + getName() + "] got error starting PipeLine: " + pre.getMessage()); runState.setRunState(RunStateEnum.ERROR); return; } // as from version 3.0 the adapter is started, // regardless of receivers are correctly started. runState.setRunState(RunStateEnum.STARTED); getMessageKeeper().add("Adapter up and running"); log.info("Adapter [" + getName() + "] up and running"); // starting receivers Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); if (receiver.getRunState() != RunStateEnum.ERROR) { log.info("Adapter [" + getName() + "] is starting receiver [" + receiver.getName() + "]"); receiver.startRunning(); } else log.warn("Adapter [" + getName() + "] will NOT start receiver [" + receiver.getName() + "] as it is in state ERROR"); } //while // wait until the stopRunning is called waitForRunState(RunStateEnum.STOPPING); // stop the adapter log.debug("***stopping adapter"); it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); receiver.waitForRunState(RunStateEnum.STOPPED); log.info("Adapter [" + getName() + "] stopped [" + receiver.getName() + "]"); } int currentNumOfMessagesInProcess = getNumOfMessagesInProcess(); if (currentNumOfMessagesInProcess > 0) { String msg = "Adapter [" + name + "] is being stopped while still processing " + currentNumOfMessagesInProcess + " messages, waiting for them to finish"; log.warn(msg); getMessageKeeper().add(msg); } waitForNoMessagesInProcess(); log.debug("Adapter [" + name + "] is stopping pipeline"); pipeline.stop(); runState.setRunState(RunStateEnum.STOPPED); getMessageKeeper().add("Adapter stopped"); } catch (Throwable e) { log.error("error running adapter [" + getName() + "] [" + ToStringBuilder.reflectionToString(e) + "]", e); runState.setRunState(RunStateEnum.ERROR); } } /** * some functional description of the <code>Adapter</code> */ public void setDescription(String description) { this.description = description; } /** * Register a <code>ErrorMessageFormatter</code> as the formatter * for this <code>adapter</code> * @param errorMessageFormatter * @see IErrorMessageFormatter */ public void setErrorMessageFormatter(IErrorMessageFormatter errorMessageFormatter) { this.errorMessageFormatter = errorMessageFormatter; } public void setErrorState(java.lang.String newErrorState) { errorState = newErrorState; } /** * Set the number of messages that are kept on the screen. * @param size * @see nl.nn.adapterframework.util.MessageKeeper */ public void setMessageKeeperSize(int size) { this.messageKeeperSize = size; } /** * the functional name of this adapter */ public void setName(String name) { this.name = name; } /** * Start the adapter. The thread-name will be set tot the adapter's name. * The run method, called by t.start(), will call the startRunning method * of the IReceiver. The Adapter will be a new thread, as this interface * extends the <code>Runnable</code> interface. The actual starting is done * in the <code>run</code> method. * @see IReceiver#startRunning() * @see Adapter#run */ public void startRunning() { Thread t = new Thread(this, getName()); t.start(); } /** * Stop the <code>Adapter</code> and close all elements like receivers, * Pipeline, pipes etc. * The adapter * will call the <code>IReceiver</code> to <code>stopListening</code> * <p>Also the <code>PipeLine.close()</code> method will be called, * closing alle registered pipes. </p> * @see IReceiver#stopRunning * @see PipeLine#stop */ public void stopRunning() { synchronized (runState) { RunStateEnum currentRunState = getRunState(); if (!currentRunState.equals(RunStateEnum.STARTED) && (!currentRunState.equals(RunStateEnum.ERROR))) { String msg = "Adapter [" + name + "] in state [" + currentRunState + "] while stopAdapter() command is issued, ignoring command"; log.warn(msg); getMessageKeeper().add(msg); return; } if (currentRunState.equals(RunStateEnum.ERROR)) { runState.setRunState(RunStateEnum.STOPPED); return; } log.debug("Adapter [" + name + "] is stopping receivers"); Iterator it = receivers.iterator(); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); try { receiver.stopRunning(); log.info("Adapter [" + name + "] successfully stopped receiver [" + receiver.getName() + "]"); } catch (Exception e) { log.error("Adapter [" + name + "] received error while stopping, ignoring this, so watch out.", e); getMessageKeeper().add( "received error stopping receiver [" + receiver.getName() + "] : " + e.getMessage()); } } runState.setRunState(RunStateEnum.STOPPING); } } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[name=" + name + "]"); sb.append("[version=" + version + "]"); Iterator it = receivers.iterator(); sb.append("[receivers="); while (it.hasNext()) { IReceiver receiver = (IReceiver) it.next(); sb.append(" " + receiver.getName()); } sb.append("]"); sb.append( "[pipeLine=" + ((pipeline != null) ? pipeline.toString() : "none registered") + "]" + "[started=" + getRunState() + "]"); return sb.toString(); } public void waitForNoMessagesInProcess() throws InterruptedException { synchronized (statsMessageProcessingDuration) { while (getNumOfMessagesInProcess() > 0) { wait(); } } } public void waitForRunState(RunStateEnum requestedRunState) throws InterruptedException { runState.waitForRunState(requestedRunState); } public boolean waitForRunState(RunStateEnum requestedRunState, long maxWait) throws InterruptedException { return runState.waitForRunState(requestedRunState, maxWait); } /** * loads TransactionManager properties from a JmsRealm * @see JmsRealm */ public void setJmsRealm(String jmsRealmName) { JmsRealm.copyRealm(this, jmsRealmName); } /** * The JNDI-key under which the UserTransaction can be retrieved */ public String getUserTransactionUrl() { return userTransactionUrl; } /** * The JNDI-key under which the UserTransaction can be retrieved */ public void setUserTransactionUrl(String userTransactionUrl) { this.userTransactionUrl = userTransactionUrl; } }
package de.jungblut.graph.search; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import de.jungblut.graph.Graph; import de.jungblut.graph.vertex.CostVertex; /** * A* algorithm for fast and heuristic search of the shortest paths in a graph. * * @author thomas.jungblut * */ public final class AStar { private static final DistanceMeasurer<CostVertex> DEFAULT_MEASURER = new DefaultDistanceMeasurer(); /** * Executes an A* search in a graph. It needs a graph, the start and end * vertex. The heuristic distance measurer is based on the average edge weight * of start and end node. */ public static WeightedEdgeContainer<CostVertex> startAStarSearch( Graph<CostVertex> g, CostVertex start, CostVertex goal) { return startAStarSearch(g, start, goal, DEFAULT_MEASURER); } /** * Executes an A* search in a graph. It needs a graph, the start and end * vertex as well as a heuristic distance measurer. */ public static WeightedEdgeContainer<CostVertex> startAStarSearch( Graph<CostVertex> g, CostVertex start, CostVertex goal, DistanceMeasurer<CostVertex> measurer) { HashSet<CostVertex> closedSet = new HashSet<>(); HashSet<CostVertex> openSet = new HashSet<>(); HashMap<CostVertex, CostVertex> cameFrom = new HashMap<>(); // distance from the start from start along optimal path HashMap<CostVertex, Integer> g_score = new HashMap<>(); // distance from start to goal plus heuristic estimate HashMap<CostVertex, Double> f_score = new HashMap<>(); // heuristic score HashMap<CostVertex, Double> h_score = new HashMap<>(); g_score.put(start, 0); h_score.put(start, measurer.measureDistance(g, start, goal)); f_score.put(start, h_score.get(start)); // create a deep copy for (CostVertex v : g.getVertexSet()) openSet.add(v); while (!openSet.isEmpty()) { CostVertex v = findLowest(openSet, f_score); if (v.equals(goal)) { return new WeightedEdgeContainer<CostVertex>(g_score, cameFrom); } else { openSet.remove(v); closedSet.add(v); for (CostVertex y : g.getAdjacentVertices(v.getVertexId())) { boolean tentativeIsBetter = false; if (closedSet.contains(y)) continue; int tentativeGScore = g_score.get(v) + y.getCost(); Integer gScore = g_score.get(y); if (!openSet.contains(y)) { openSet.add(y); tentativeIsBetter = true; } else if (gScore == null || tentativeGScore < gScore) { tentativeIsBetter = true; } else { tentativeIsBetter = false; } if (tentativeIsBetter) { cameFrom.put(y, v); g_score.put(y, tentativeGScore); double dist = measurer.measureDistance(g, y, goal); h_score.put(y, dist); f_score.put(y, tentativeGScore + dist); } } } } return new WeightedEdgeContainer<>(g_score, cameFrom); } private static CostVertex findLowest(HashSet<CostVertex> openSet, HashMap<CostVertex, Double> scoredMap) { CostVertex low = null; double lowest = Double.MAX_VALUE; for (CostVertex v : openSet) { Double current = scoredMap.get(v); if (low == null && current != null) { low = v; lowest = current; } else { if (current != null && lowest > current) { low = v; lowest = current; } } } return low; } /** * That does not make so much sense, but works for small graphs because it * never over estimates the cost. * * @author thomas.jungblut * */ private static class DefaultDistanceMeasurer implements DistanceMeasurer<CostVertex> { @Override public double measureDistance(Graph<CostVertex> g, CostVertex start, CostVertex goal) { double startWeight = averageEdgeWeights(g, start); double goalWeight = averageEdgeWeights(g, goal); // pow the result by 2 double c = Math.pow((startWeight - goalWeight), 2); // absolute the distance return Math.abs(c - startWeight); } private double averageEdgeWeights(Graph<CostVertex> g, CostVertex vertex) { int sum = 0; int count = 0; Set<CostVertex> adjacents = g.getAdjacentVertices(vertex); if (adjacents == null) return 0; for (CostVertex e : adjacents) { sum += e.getCost(); count++; } if (count == 0) return 0; else return sum / count; } }; }
package de.onyxbits.raccoon; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; /** * A container for putting search results in. * * @author patrick * */ public class SearchView extends JPanel implements ActionListener, ChangeListener, Runnable { private static final long serialVersionUID = 1L; protected Archive archive; private static final String CARDRESULTS = "results"; private static final String CARDPROGRESS = "progress"; private static final String CARDMESSAGE = "message"; private JTextField query; private JSpinner page; private JScrollPane results; private JProgressBar progress; private JLabel message; private JPanel main; private CardLayout cardLayout; private MainActivity mainActivity; private SearchView(MainActivity mainActivity, Archive archive) { this.archive = archive; this.mainActivity = mainActivity; setLayout(new BorderLayout()); query = new JTextField(); query.setToolTipText("Keywords or packagename"); page = new JSpinner(new SpinnerNumberModel(1, 1, 10000, 1)); page.setToolTipText("Result page"); results = new JScrollPane(); cardLayout = new CardLayout(); message = new JLabel(); progress = new JProgressBar(); progress.setIndeterminate(true); progress.setString("Searching"); progress.setStringPainted(true); GridBagConstraints center = new GridBagConstraints(); center.anchor = GridBagConstraints.CENTER; center.fill = GridBagConstraints.NONE; main = new JPanel(); main.setLayout(cardLayout); JPanel container = new JPanel(); container.setLayout(new GridBagLayout()); container.add(message,center); main.add(container, CARDMESSAGE); main.add(results, CARDRESULTS); container = new JPanel(); container.setLayout(new GridBagLayout()); container.add(progress,center); main.add(container, CARDPROGRESS); container = new JPanel(); container.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS)); container.add(query); container.add(page); add(container, BorderLayout.NORTH); add(main, BorderLayout.CENTER); } public static SearchView create(MainActivity mainActivity, Archive archive) { SearchView ret = new SearchView(mainActivity, archive); ret.query.addActionListener(ret); ret.page.addChangeListener(ret); return ret; } public void actionPerformed(ActionEvent event) { if (event.getSource() == query) { page.setValue(1); doSearch(); } } public void stateChanged(ChangeEvent event) { if (event.getSource() == page) { doSearch(); } // Slightly ugly: a searchview is meant to sit in a JTabbedPane and // registered as it's ChangeListener, so the query can get focus whenever // the user switches to this view. In fact, we consider the query field to // be so important that we always focus it, no matter what. query.requestFocusInWindow(); } /** * After adding this view to a JTabbedPane, post it to the EDT via * SwingUtils.invokeLater() to ensure the query gets the inputfocus. */ public void run() { query.requestFocusInWindow(); } protected void doSearch() { if (query.getText().length() == 0) { doMessage("Enter keywords, app name, vendor name, app id or a Google Play url"); } else { query.setEnabled(false); page.setEnabled(false); cardLayout.show(main, CARDPROGRESS); int offset = (Integer) page.getValue(); offset = (offset - 1) * 10; new SearchWorker(archive, query.getText(), this).withOffset(offset).withLimit(offset + 10) .execute(); } } protected void doMessage(String status) { query.setEnabled(true); page.setEnabled(true); cardLayout.show(main, CARDMESSAGE); message.setText(status); } protected void doResultList(JPanel listing) { query.setEnabled(true); page.setEnabled(true); cardLayout.show(main, CARDRESULTS); results.setViewportView(listing); } protected void doDownload(DownloadView d) { if (d.isDownloaded()) { int result = JOptionPane.showConfirmDialog(getRootPane(), "Overwrite file?", "File exists", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); if (result == JOptionPane.YES_OPTION) { mainActivity.doDownload(d); } } else { mainActivity.doDownload(d); } } public Archive getArchive() { return archive; } }
// Administrator of the National Aeronautics and Space Administration // This software is distributed under the NASA Open Source Agreement // (NOSA), version 1.3. The NOSA has been approved by the Open Source // Initiative. See the file NOSA-1.3-JPF at the top of the distribution // directory tree for the complete NOSA document. // KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT // SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR // DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. package gov.nasa.jpf.jvm.bytecode; import gov.nasa.jpf.jvm.*; /** * common root for MONITORENTER/EXIT */ public abstract class LockInstruction extends Instruction { int lastLockRef = -1; /** * only useful post-execution (in an instructionExecuted() notification) */ public int getLastLockRef () { return lastLockRef; } /** * If the current thread already owns the lock, then the current thread can go on. * For example, this is a recursive acquisition. */ protected boolean isLockOwner(ThreadInfo ti, ElementInfo ei) { return ei.getLockingThread() == ti; } /** * If the object will still be owned, then the current thread can go on. * For example, all but the last monitorexit for the object. */ protected boolean isLastUnlock(ElementInfo ei) { return ei.getLockCount() == 0; } /** * If the object isn't shared, then the current thread can go on. * For example, this object isn't reachable by other threads. */ protected boolean isShared(ThreadInfo ti, ElementInfo ei) { if (!ti.skipLocalSync()) { return true; } return ei.isShared(); } public void accept(InstructionVisitor insVisitor) { insVisitor.visit(this); } }
package org.voovan.http.server; import org.voovan.Global; import org.voovan.http.client.HttpClient; import org.voovan.http.message.HttpStatic; import org.voovan.http.server.context.HttpModuleConfig; import org.voovan.http.server.context.HttpRouterConfig; import org.voovan.http.server.context.WebContext; import org.voovan.http.server.context.WebServerConfig; import org.voovan.http.server.router.OptionsRouter; import org.voovan.http.websocket.WebSocketRouter; import org.voovan.http.websocket.WebSocketSession; import org.voovan.http.websocket.filter.StringFilter; import org.voovan.network.SSLManager; import org.voovan.network.SocketContext; import org.voovan.network.messagesplitter.HttpMessageSplitter; import org.voovan.network.tcp.TcpServerSocket; import org.voovan.tools.*; import org.voovan.tools.threadpool.ThreadPool; import org.voovan.tools.weave.Weave; import org.voovan.tools.hotswap.Hotswaper; import org.voovan.tools.json.JSON; import org.voovan.tools.log.Logger; import org.voovan.tools.reflect.TReflect; import java.io.File; import java.io.IOException; import java.net.URL; import java.nio.channels.ShutdownChannelGroupException; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; public class WebServer { private SocketContext serverSocket; private HttpDispatcher httpDispatcher; private WebSocketDispatcher webSocketDispatcher; private SessionManager sessionManager; private WebServerConfig config; private WebServerLifeCycle webServerLifeCycle; /** * * * @param config WEB * */ public WebServer(WebServerConfig config) { this.config = config; initAop(); initHotSwap(); initWebServer(config); } /** * Session * @return Session */ public SessionManager getSessionManager(){ return this.sessionManager; } private void initHotSwap() { if(config.getHotSwapInterval() > 0) { try { Hotswaper hotSwaper = Hotswaper.get(); hotSwaper.autoReload(config.getHotSwapInterval()); } catch (Exception e) { Logger.error("Init hotswap failed: " + e.getMessage()); } } } private void initAop() { if(config.getWeaveConfig()!=null) { try { Weave.init(config.getWeaveConfig()); } catch (Exception e) { Logger.error("Init aop failed: " + e.getMessage()); } } } private void initWebServer(WebServerConfig config) { //[HTTP] SessionManage this.sessionManager = SessionManager.newInstance(config); //[HTTP] this.httpDispatcher = new HttpDispatcher(config, sessionManager); this.webSocketDispatcher = new WebSocketDispatcher(config, sessionManager); } private void initSocketServer(WebServerConfig config) throws IOException{ //[Socket] socket serverSocket = new TcpServerSocket(config.getHost(), config.getPort(), config.getReadTimeout()*1000, config.getSendTimeout()*1000, 0); // Web serverSocket.setAcceptEventRunnerGroup(SocketContext.createEventRunnerGroup("Web", SocketContext.ACCEPT_THREAD_SIZE, true)); serverSocket.setIoEventRunnerGroup(SocketContext.createEventRunnerGroup("Web", SocketContext.IO_THREAD_SIZE, false)); //[Socket] HTTPS if(config.isHttps()) { SSLManager sslManager = new SSLManager("TLS", false); sslManager.loadKey(System.getProperty("user.dir") + config.getHttps().getCertificateFile(), config.getHttps().getCertificatePassword(), config.getHttps().getKeyPassword()); serverSocket.setSSLManager(sslManager); } serverSocket.handler(new WebServerHandler(config, httpDispatcher, webSocketDispatcher)); serverSocket.filterChain().add(new WebServerFilter()); serverSocket.messageSplitter(new HttpMessageSplitter()); } /** * Router WebServer */ private void initRouter(){ for(HttpRouterConfig httpRouterConfig : config.getRouterConfigs()){ String method = httpRouterConfig.getMethod(); String route = httpRouterConfig.getRoute(); String className = httpRouterConfig.getClassName(); if(!method.equals("WEBSOCKET")) { otherMethod(method, route, httpRouterConfig.getHttpRouterInstance()); }else{ socket(route, httpRouterConfig.getWebSocketRouterInstance()); } } } public void initModule() { for (HttpModuleConfig httpModuleConfig : config.getModuleConfigs()) { HttpModule httpModule = httpModuleConfig.getHttpModuleInstance(this); if(httpModule!=null){ httpModule.lifeCycleInit(); httpModule.install(); } } } public void unInitModule() { for (HttpModuleConfig moduleConfig : this.config.getModuleConfigs().toArray(new HttpModuleConfig[0])) { HttpModule httpModule = moduleConfig.getHttpModuleInstance(this); httpModule.lifeCycleDestory(); httpModule.unInstall(); Logger.simple("[HTTP] Module ["+moduleConfig.getName()+"] uninstall"); } } /** * Http * @return Http */ public WebServerConfig getWebServerConfig() { return config; } public HttpDispatcher getHttpDispatcher() { return httpDispatcher; } public WebSocketDispatcher getWebSocketDispatcher() { return webSocketDispatcher; } public SocketContext getServerSocket() { return serverSocket; } public WebServerLifeCycle getWebServerLifeCycle() { return webServerLifeCycle; } /** * HTTP */ /** * GET * @param routeRegexPath * @param router HTTP * @return WebServer */ public WebServer get(String routeRegexPath, HttpRouter router) { httpDispatcher.addRouter(HttpStatic.GET_STRING, routeRegexPath, router); return this; } /** * POST * @param routeRegexPath * @param router HTTP * @return WebServer */ public WebServer post(String routeRegexPath, HttpRouter router) { httpDispatcher.addRouter(HttpStatic.POST_STRING, routeRegexPath, router); return this; } /** * GET POST * @param routeRegexPath * @param router HTTP * @return WebServer */ public WebServer getAndPost(String routeRegexPath, HttpRouter router) { get(routeRegexPath, router); post(routeRegexPath, router); return this; } /** * HEAD * @param routeRegexPath * @param router HTTP * @return WebServer */ public WebServer head(String routeRegexPath, HttpRouter router) { httpDispatcher.addRouter(HttpStatic.HEAD_STRING, routeRegexPath, router); return this; } /** * PUT * @param routeRegexPath * @param router HTTP * @return WebServer */ public WebServer put(String routeRegexPath, HttpRouter router) { httpDispatcher.addRouter(HttpStatic.PUT_STRING, routeRegexPath, router); return this; } /** * DELETE * @param routeRegexPath * @param router HTTP * @return WebServer */ public WebServer delete(String routeRegexPath, HttpRouter router) { httpDispatcher.addRouter(HttpStatic.DELETE_STRING, routeRegexPath, router); return this; } /** * TRACE * @param routeRegexPath * @param router HTTP * @return WebServer */ public WebServer trace(String routeRegexPath, HttpRouter router) { httpDispatcher.addRouter(HttpStatic.TRACE_STRING, routeRegexPath, router); return this; } /** * CONNECT * @param routeRegexPath * @param router HTTP * @return WebServer */ public WebServer connect(String routeRegexPath, HttpRouter router) { httpDispatcher.addRouter(HttpStatic.CONNECTION_STRING, routeRegexPath, router); return this; } /** * OPTIONS * @param routeRegexPath * @param router HTTP * @return WebServer */ public WebServer options(String routeRegexPath, HttpRouter router) { httpDispatcher.addRouter(HttpStatic.OPTIONS_STRING, routeRegexPath, router); return this; } /** * * @param method * @param routeRegexPath * @param router HTTP * @return WebServer */ public WebServer otherMethod(String method, String routeRegexPath, HttpRouter router) { httpDispatcher.addRouteMethod(method); httpDispatcher.addRouter(method, routeRegexPath, router); return this; } /** * WebSocket * @param routeRegexPath * @param router WebSocket * @return WebServer */ public WebServer socket(String routeRegexPath, WebSocketRouter router) { webSocketDispatcher.addRouteHandler(routeRegexPath, router); return this; } /** * WebServer, * @param config WebServer * @return WebServer */ public static WebServer newInstance(WebServerConfig config) { if(config!=null) { return new WebServer(config); }else{ Logger.error("Create WebServer failed: WebServerConfig object is null."); } return null; } /** * WebServer,JSON * * @param json WebServerJSON * @return WebServer */ public static WebServer newInstance(String json) { if(json!=null) { return new WebServer(WebContext.buildConfigFromJSON(json)); }else{ Logger.error("Create WebServer failed: WebServerConfig object is null."); } return null; } /** * WebServer, * * @param configFile WebServer * @return WebServer */ public static WebServer newInstance(File configFile) { try { if(configFile!=null && configFile.exists()) { return new WebServer(WebContext.buildConfigFromFile(configFile.getCanonicalPath())); }else{ Logger.error("Create WebServer failed: WebServerConfig object is null."); } } catch (IOException e) { Logger.error("Create WebServer failed",e); } return null; } /** * WebServer, * @param port HTTP * @return WebServer */ public static WebServer newInstance(int port) { WebServerConfig config = WebContext.getWebServerConfig(); config.setPort(port); return newInstance(config); } /** * WebServer, * * @return WebServer */ public static WebServer newInstance() { return newInstance(WebContext.getWebServerConfig()); } private void commonServe() throws IOException { WebContext.getAuthToken(); WebContext.logo(); // Class WebServerInit(this); WebContext.initWebServerPluginConfig(true); initRouter(); initModule(); InitManagerRouter(); initSocketServer(this.config); WebContext.welcome(); // PID Long pid = TEnv.getCurrentPID(); File pidFile = new File("logs" + File.separator + ".pid"); TFile.mkdir(pidFile.getPath()); TFile.writeFile(pidFile, false, pid.toString().getBytes()); System.out.println(" Pid: \t\t"+ pid.toString()); String serviceUrl = "http" + (config.isHttps()?"s":"") + ": + (config.getHost().equals("0.0.0.0") ? "127.0.0.1" : config.getHost()) + ":"+config.getPort(); Logger.simplef(" Listen: \t{}", serviceUrl); Logger.simplef(" Time: \t{}", TDateTime.now()); Logger.simplef(" Elapsed: \t{} ms", TPerformance.getRuningTime()); Logger.simple("=================================================================================================================================================="); } /** * WebConfig * @param reloadInfoJson WebConfig */ public void reload(String reloadInfoJson){ if(reloadInfoJson!=null) { WebServerConfig config = this.config; Map<String, Object> reloadInfo = (Map<String, Object>) JSON.parse(reloadInfoJson); if ("FILE".equals(reloadInfo.get("Type"))) { config = WebContext.buildConfigFromFile(reloadInfo.get("Content").toString()); } if ("HTTP".equals(reloadInfo.get("Type"))) { config = WebContext.buildConfigFromRemote(reloadInfo.get("Content").toString()); } if ("JSON".equals(reloadInfo.get("Type"))) { config = WebContext.buildConfigFromJSON(reloadInfo.get("Content").toString()); } this.config = config; } WebContext.PAUSE = true; TEnv.sleep(1000); unInitModule(); this.httpDispatcher = new HttpDispatcher(config,sessionManager); this.webSocketDispatcher = new WebSocketDispatcher(config, sessionManager); // WebServer http websocket serverSocket.handler(new WebServerHandler(config, httpDispatcher,webSocketDispatcher)); WebContext.welcome(); WebContext.initWebServerPluginConfig(false); initRouter(); initModule(); InitManagerRouter(); WebContext.PAUSE = false; } /** * * @param webServer WebServer */ private void WebServerInit(WebServer webServer){ String lifeCycleClass = WebContext.getWebServerConfig().getLifeCycleClass(); if(lifeCycleClass==null) { Logger.info("None WebServer lifeCycle class to load."); return; } if(lifeCycleClass.isEmpty()){ Logger.info("None WebServer lifeCycle class to load."); return; } try { Class clazz = Class.forName(lifeCycleClass); if(TReflect.isImp(clazz, WebServerLifeCycle.class)){ webServerLifeCycle = (WebServerLifeCycle)TReflect.newInstance(clazz); webServerLifeCycle.init(webServer); }else{ Logger.warn("The WebServer lifeCycle class " + lifeCycleClass + " is not a class implement by " + WebServerLifeCycle.class.getName()); } } catch (Exception e) { Logger.error("Initialize WebServer lifeCycle class error: ", e); } } /** * * @param webServer WebServer */ private void WebServerDestory(WebServer webServer){ if(webServerLifeCycle!=null) { try { webServerLifeCycle.destory(webServer); } catch (Exception e) { Logger.error("Initialize WebServer destory lifeCycle error: ", e); } } } public void InitManagerRouter(){ WebServer webServer = this; //Http Status otherMethod("ADMIN", "/voovan/admin/status", new HttpRouter() { @Override public void process(HttpRequest request, HttpResponse response) throws Exception { String status = "RUNNING"; String authToken = request.header().get("AUTH-TOKEN"); if(authToken!=null && authToken.equals(WebContext.AUTH_TOKEN)) { if(WebContext.PAUSE){ status = "PAUSE"; } response.write(status); } else { request.getSession().close(); } } }); //WebSocket socket("/voovan/admin", new WebSocketRouter() { String tips = TString.tokenReplace("{}:# ", WebContext.getWebServerConfig().getServerName()); @Override public Object onOpen(WebSocketSession session) { if(!TPerformance.getLocalIpAddrs().contains(session.getRemoteAddress())){ session.close(); } session.setAttribute("authed", false); return tips; } @Override public Object onRecived(WebSocketSession session, Object obj) { String[] cmds = ((String)obj).split(" "); String response = ""; switch (cmds[0]) { case "auth" : { // AUTH_TOKEN if(cmds.length<1 || TString.isNullOrEmpty(cmds[1])) { response = "(error) Need token for Authentication"; } // AUTH_TOKEN if(!WebContext.AUTH_TOKEN.equals(cmds[1])) { response = "(error) Token is invalide"; } session.setAttribute("authed", true); response = "Authentication success"; break; } case "exit" : { response = "Bye, see you later"; Global.getHashWheelTimer().addTask(()->{ session.close(); }, 1); return null; } default: { if (!((Boolean) session.getAttribute("authed"))) { response = "(error) Authentication required"; } else { switch (cmds[0]) { case "status": { String status = "RUNNING"; if (WebContext.PAUSE) { status = "PAUSE"; } response = "Web server is " + status; break; } case "shutdown": { webServer.stop(); response = "Web server is stoped"; break; } case "pause": { WebContext.PAUSE = true; response = "Web server is paused"; break; } case "unpause": { WebContext.PAUSE = false; response = "Web server is running"; break; } case "reload": { String config = (cmds.length == 1 || TString.isNullOrEmpty(cmds[1])) ? null : cmds[1]; reload(config); response = "Web server reload success"; break; } case "config": { response = "\r\n" + JSON.formatJson(JSON.toJSON(webServer.config)); break; } // Token case "changeToken": { // AUTH_TOKEN if (cmds.length < 1 || TString.isNullOrEmpty(cmds[1])) { response = "(error) Token is invalide"; } WebContext.AUTH_TOKEN = cmds[1]; File tokenFile = new File("logs" + File.separator + ".token"); TFile.writeFile(tokenFile, false, WebContext.AUTH_TOKEN.getBytes()); response = "Token is changed"; break; } } } } } response = response.length()==0 ? "" : TString.tokenReplace("{}\r\n", response); return TString.tokenReplace("{}{}",response, tips); } @Override public void onSent(WebSocketSession session, Object obj) { } @Override public void onClose(WebSocketSession session) { } }.addFilterChain(new StringFilter())); } /** * * * * @return WebServer */ public WebServer serve() { // SIGTERM final WebServer innerWebServer = this; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { innerWebServer.stop(); } }); try { commonServe(); serverSocket.start(); } catch (IOException e) { Logger.error("Start HTTP server error",e); TEnv.sleep(1000); System.exit(0); } return this; } /** * * * @return WebServer */ public WebServer syncServe() { try { commonServe(); serverSocket.syncStart(); } catch (IOException e) { Logger.error("Start HTTP server error",e); } return this; } /** * Http * @return */ public Map<String, Map<String, RouterWrap<HttpRouter>>> getHttpRouters(){ return httpDispatcher.getRoutes(); } /** * WebSocket * @return */ public Map<String, RouterWrap<WebSocketRouter>> getWebSocketRouters(){ return webSocketDispatcher.getRouters(); } /** * * @return true: , false: */ public boolean isServing(){ return serverSocket.isConnected(); } public void pause(){ WebContext.PAUSE = true; } public void unPause(){ WebContext.PAUSE = false; } /** * WebServer * @param args */ public static void main(String[] args) { WebServer webServer = newInstance(args); webServer.serve(); } /** * * @param args * @return WebServer */ public static WebServer newInstance(String[] args) { //, framework.properties for(int i=0;i<args.length;i++){ if(args[i].equals("--env") || args[i].equals("-e")){ i++; TEnv.setEnvName(args[i]); break; } else { continue; } } WebServerConfig config = WebContext.getWebServerConfig(); if(args.length>0){ for(int i=0;i<args.length;i++){ if(args[i].equals("--config")){ i++; config = WebContext.buildConfigFromFile(args[i]); } if(args[i].equals("--remoteConfig")){ i++; config = WebContext.buildConfigFromRemote(args[i]); } if(args[i].equals("--cli")){ Logger.setEnable(false); AtomicReference<WebSocketSession> sessionRef = new AtomicReference<WebSocketSession>(); try { String url = args[i + 1].trim(); String path = url.substring(url.indexOf("/", 8)); HttpClient client = HttpClient.newInstance(url, 60); client.webSocket(path, new WebSocketRouter() { @Override public Object onOpen(WebSocketSession session) { System.out.println("[" + TDateTime.now() + "] connect to " + url.toString() + "\r\n\r\n"); sessionRef.set(session); return null; } @Override public Object onRecived(WebSocketSession session, Object obj) { System.out.print(obj); return null; } @Override public void onSent(WebSocketSession session, Object obj) { } @Override public void onClose(WebSocketSession session) { } }.addFilterChain(new StringFilter())); TEnv.wait(()->client.isConnect() && sessionRef.get()==null); WebSocketSession webSocketSession = sessionRef.get(); while(client.isConnect()) { int size = System.in.available(); if(size>0) { byte[] commandBytes = new byte[size]; System.in.read(commandBytes); String command = new String(commandBytes).trim(); webSocketSession.send(command); } TEnv.sleep(500); } } catch (Exception e) { System.out.println(args); e.printStackTrace(); } System.exit(1); } if(args[i].equals("-h")){ config = config==null?WebContext.getWebServerConfig():config; i++; config.setHost(args[i]); } if(args[i].equals("-p")){ config = config==null?WebContext.getWebServerConfig():config; i++; config.setPort(Integer.parseInt(args[i])); } if(args[i].equals("-rto")){ config = config==null?WebContext.getWebServerConfig():config; i++; config.setReadTimeout(Integer.parseInt(args[i])); } if(args[i].equals("-sto")){ config = config==null?WebContext.getWebServerConfig():config; i++; config.setReadTimeout(Integer.parseInt(args[i])); } if(args[i].equals("-r")){ config = config==null?WebContext.getWebServerConfig():config; i++; config.setContextPath(args[i]); } //,index.htm,index.html,default.htm,default.htm if(args[i].equals("-i")){ config = config==null?WebContext.getWebServerConfig():config; i++; config.setIndexFiles(args[i]); } //, false if(args[i].equals("-mri")){ config = config==null?WebContext.getWebServerConfig():config; config.setMatchRouteIgnoreCase(true); } //, UTF-8 if(args[i].equals("--charset")){ config = config==null?WebContext.getWebServerConfig():config; i++; config.setCharacterSet(args[i]); } //Gzip, true if(args[i].equals("--noGzip")){ config = config==null?WebContext.getWebServerConfig():config; config.setGzip(false); } //access.log, true if(args[i].equals("--noAccessLog")){ config = config==null?WebContext.getWebServerConfig():config; config.setAccessLog(false); } //HTTPS if(args[i].equals("--https.CertificateFile")){ config = config==null?WebContext.getWebServerConfig():config; i++; config.getHttps().setCertificateFile(args[i]); } if(args[i].equals("--https.CertificatePassword")){ config = config==null?WebContext.getWebServerConfig():config; i++; config.getHttps().setCertificatePassword(args[i]); } //Key if(args[i].equals("--https.KeyPassword")){ config = config==null?WebContext.getWebServerConfig():config; i++; config.getHttps().setKeyPassword(args[i]); } if(args[i].equals("-v")){ Logger.simple("Version:"+WebContext.VERSION); return null; } if(args[i].equals("--help") || args[i].equals("-?")){ Logger.simple("Usage: java -jar voovan-framework.jar [Options]"); Logger.simple(""); Logger.simple("Start voovan webserver"); Logger.simple(""); Logger.simple("Options:"); Logger.simple(TString.rightPad(" -h", 35, ' ') + "Webserver bind host ip address"); Logger.simple(TString.rightPad(" -p", 35, ' ') + "Webserver bind port number"); Logger.simple(TString.rightPad(" --env", 35, ' ') + "Webserver environment name"); Logger.simple(TString.rightPad(" -rto", 35, ' ') + "Socket readFromChannel timeout"); Logger.simple(TString.rightPad(" -sto", 35, ' ') + "Socket writeToChannel timeout"); Logger.simple(TString.rightPad(" -r", 35, ' ') + "Context root path, contain webserver static file"); Logger.simple(TString.rightPad(" -i", 35, ' ') + "index file for client access to webserver"); Logger.simple(TString.rightPad(" -mri", 35, ' ') + "Match route ignore case"); Logger.simple(TString.rightPad(" --config", 35, ' ') + "Webserver config file"); Logger.simple(TString.rightPad(" --remoteConfig", 35, ' ') + "Remote Webserver config with a HTTP URL address"); Logger.simple(TString.rightPad(" --charset", 35, ' ') + "set default charset"); Logger.simple(TString.rightPad(" --noGzip", 35, ' ') + "Do not use gzip for client"); Logger.simple(TString.rightPad(" --noAccessLog", 35, ' ') + "Do not write access log to access.log"); Logger.simple(TString.rightPad(" --https.CertificateFile", 35, ' ') + "Certificate file for https"); Logger.simple(TString.rightPad(" --https.CertificatePassword", 35, ' ')+ "Certificate passwork for https"); Logger.simple(TString.rightPad(" --https.KeyPassword", 35, ' ') + "Certificate key for https"); Logger.simple(TString.rightPad(" --help, -?", 35, ' ') + "how to use this command"); Logger.simple(TString.rightPad(" -v", 35, ' ') + "Show the version information"); Logger.simple(""); Logger.simple("This WebServer based on VoovanFramework."); Logger.simple("WebSite: http: Logger.simple("Author: helyho"); Logger.simple("E-mail: helyho@gmail.com"); Logger.simple(""); System.exit(1); return null; } } } if(config.getHotSwapInterval() >0 || config.getWeaveConfig()!=null) { if(TEnv.JDK_VERSION > 8 && !"true".equals(System.getProperty("jdk.attach.allowAttachSelf"))){ System.out.println("Your are working on: JDK-" +TEnv.JDK_VERSION+". " + "You should add java command arguments: " + "-Djdk.attach.allowAttachSelf=true"); System.exit(0); } } WebServer webServer = WebServer.newInstance(config); return webServer; } /** * WebServer */ public void stop(){ try { System.out.println("============================================================================================="); System.out.println("[" + TDateTime.now() + "] Try to stop WebServer...."); if(serverSocket!=null) { serverSocket.close(); } System.out.println("[" + TDateTime.now() + "] Socket closed"); if(serverSocket.getAcceptEventRunnerGroup()!=null) { ThreadPool.gracefulShutdown(serverSocket.getAcceptEventRunnerGroup().getThreadPool()); } if(serverSocket.getIoEventRunnerGroup()!=null) { ThreadPool.gracefulShutdown(serverSocket.getIoEventRunnerGroup().getThreadPool()); } SocketContext.gracefulShutdown(); ThreadPool.gracefulShutdown(Global.getThreadPool()); System.out.println("[" + TDateTime.now() + "] Thread pool is shutdown."); //LifeCycle.destory unInitModule(); this.WebServerDestory(this); System.out.println("[" + TDateTime.now() + "] Now webServer is fully stoped."); TEnv.sleep(1000); }catch(ShutdownChannelGroupException e){ return; } } }
package act.db.morphia.util; import act.Act; import act.app.App; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import org.mongodb.morphia.converters.SimpleValueConverter; import org.mongodb.morphia.converters.TypeConverter; import org.mongodb.morphia.mapping.MappedField; import org.mongodb.morphia.utils.IterHelper; import org.osgl.util.KVStore; import org.osgl.util.S; import org.osgl.util.ValueObject; import javax.inject.Inject; import java.util.HashMap; import java.util.Map; public class KVStoreConverter extends TypeConverter implements SimpleValueConverter { public static final String KEY = "k"; public static final String VALUE = "v"; public static final String UDF_TYPE = "t"; private ValueObjectConverter valueObjectConverter; private boolean persistAsList; public KVStoreConverter() { setSupportedTypes(new Class[] {KVStore.class}); this.valueObjectConverter = new ValueObjectConverter(); Object o = App.instance().config().get("morphia.kvstore.persist.structure"); if (null != o) { persistAsList = S.eq(S.string(o), "list", S.IGNORECASE); } } @Override public Object decode(Class<?> aClass, Object fromDB, MappedField mappedField) { final KVStore store = new KVStore(); boolean isStore = aClass.isInstance(store); if (null == fromDB) { return isStore ? store : Act.app().getInstance(aClass); } if (fromDB instanceof BasicDBList) { BasicDBList dbList = (BasicDBList) fromDB; int sz = dbList.size(); for (int i = 0; i < sz; ++i) { BasicDBObject dbObj = (BasicDBObject) dbList.get(i); String key = dbObj.getString(KEY); Object val = dbObj.get(VALUE); store.putValue(key, valueObjectConverter.decode(ValueObject.class, val)); } } else if (fromDB instanceof BasicDBObject) { new IterHelper<Object, Object>().loopMap(fromDB, new IterHelper.MapIterCallback<Object, Object>() { @Override public void eval(final Object k, final Object val) { final String key = S.string(k); store.putValue(key, valueObjectConverter.decode(ValueObject.class, val)); } }); } if (isStore) { return store; } Map retVal = (Map) Act.app().getInstance(aClass); retVal.putAll(store.toMap()); return retVal; } @Override public Object encode(Object value, MappedField optionalExtraInfo) { if (null == value) { return null; } Map<String, ?> store = (Map) value; boolean persistAsList = (this.persistAsList || optionalExtraInfo.hasAnnotation(PersistAsList.class)) && !optionalExtraInfo.hasAnnotation(PersistAsMap.class); if (persistAsList) { BasicDBList list = new BasicDBList(); for (String key : store.keySet()) { ValueObject vo = ValueObject.of(store.get(key)); BasicDBObject dbObject = new BasicDBObject(); dbObject.put(KEY, key); dbObject.put(VALUE, valueObjectConverter.encode(vo, optionalExtraInfo)); list.add(dbObject); } return list; } else { final Map mapForDb = new HashMap(); for (final Map.Entry<String, ?> entry : store.entrySet()) { mapForDb.put(entry.getKey(), valueObjectConverter.encode(ValueObject.of(entry.getValue()), optionalExtraInfo)); } return mapForDb; } } }
package au.com.southsky.jfreesane; import java.io.IOException; import java.nio.charset.Charset; import java.util.EnumSet; import java.util.List; import java.util.Set; import au.com.southsky.jfreesane.SaneSession.SaneInputStream; import au.com.southsky.jfreesane.SaneSession.SaneOutputStream; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Sets; public class SaneOption { private static Group currentGroup = null; private enum OptionAction implements SaneEnum { GET_VALUE(0), SET_VALUE(1), SET_AUTO(2); private int actionNo; OptionAction(int actionNo) { this.actionNo = actionNo; } @Override public int getWireValue() { return actionNo; } } public enum OptionValueType implements SaneEnum { BOOLEAN(0), INT(1), FIXED(2), STRING(3), BUTTON(4), GROUP(5); private int typeNo; OptionValueType(int typeNo) { this.typeNo = typeNo; } public int typeNo() { return typeNo; } @Override public int getWireValue() { return typeNo; } }; public enum OptionUnits implements SaneEnum { UNIT_NONE(0), UNIT_PIXEL(1), UNIT_BIT(2), UNIT_MM(3), UNIT_DPI(4), UNIT_PERCENT(5), UNIT_MICROSECOND( 6); private final int wireValue; OptionUnits(int wireValue) { this.wireValue = wireValue; } @Override public int getWireValue() { return wireValue; } }; public enum OptionCapability implements SaneEnum { SOFT_SELECT(1, "Option value may be set by software"), HARD_SELECT(2, "Option value may be set by user intervention at the scanner"), SOFT_DETECT(4, "Option value may be read by software"), EMULATED(8, "Option value may be detected by software"), AUTOMATIC(16, "Capability is emulated by driver"), INACTIVE(32, "Capability not currently active"), ADVANCED( 64, "Advanced user option"); private int capBit; private String description; OptionCapability(int capBit, String description) { this.capBit = capBit; this.description = description; } public String description() { return description; } @Override public int getWireValue() { return capBit; } } /** * Represents the information that the SANE daemon returns about the effect of modifying an * option. */ public enum OptionWriteInfo implements SaneEnum { /** * The value passed to SANE was accepted, but the SANE daemon has chosen a slightly different * value than the one specified. */ INEXACT(1), /** * Setting the option may have resulted in changes to other options and the client should * re-read options whose values it needs. */ RELOAD_OPTIONS(2), /** * Setting the option may have caused a parameter set by the user to have changed. */ RELOAD_PARAMETERS(4); private final int wireValue; OptionWriteInfo(int wireValue) { this.wireValue = wireValue; } @Override public int getWireValue() { return wireValue; } } public enum OptionValueConstraintType implements SaneEnum { NO_CONSTRAINT(0, "No constraint"), RANGE_CONSTRAINT(1, ""), VALUE_LIST_CONSTRAINT(2, ""), STRING_LIST_CONSTRAINT( 3, ""); private final int wireValue; private final String description; OptionValueConstraintType(int wireValue, String description) { this.wireValue = wireValue; this.description = description; } public String description() { return description; } @Override public int getWireValue() { return wireValue; } } public static abstract class RangeConstraint { protected final int min; protected final int max; protected final int quantum; RangeConstraint(int min, int max, int quantum) { this.min = min; this.max = max; this.quantum = quantum; } } public static class IntegerRangeContraint extends RangeConstraint { IntegerRangeContraint(int min, int max, int quantum) { super(min, max, quantum); } public int getMin() { return min; } public int getMax() { return max; } public int getQuantum() { return quantum; } } public static class FixedRangeConstraint extends RangeConstraint { private static final float DIVISOR = 65536.0f; FixedRangeConstraint(int min, int max, int quantum) { super(min, max, quantum); } public float getMin() { return min / DIVISOR; } public float getMax() { return max / DIVISOR; } public float getQuantum() { return quantum / DIVISOR; } } private final SaneDevice device; private final int optionNumber; private final String name; private final String title; private final String description; private final Group group; private final OptionValueType valueType; private final OptionUnits units; private final int size; private final Set<OptionCapability> optionCapabilities; private final OptionValueConstraintType constraintType; private final RangeConstraint rangeConstraints; private final List<String> stringContraints; // TODO: wrong level of abstraction private final List<Integer> wordConstraints; public SaneOption(SaneDevice device, int optionNumber, String name, String title, String description, Group group, OptionValueType type, OptionUnits units, int size, int capabilityWord, OptionValueConstraintType constraintType, RangeConstraint rangeConstraints, List<String> stringContraints, List<Integer> wordConstraints) { super(); this.device = device; this.optionNumber = optionNumber; this.name = name; this.title = title; this.description = description; this.group = group; this.valueType = type; this.units = units; this.size = size; this.optionCapabilities = SaneEnums.enumSet(OptionCapability.class, capabilityWord); this.constraintType = constraintType; this.rangeConstraints = rangeConstraints; this.stringContraints = stringContraints; this.wordConstraints = wordConstraints; } public static List<SaneOption> optionsFor(SaneDevice device) throws IOException { Preconditions.checkState(device.isOpen(), "you must open() the device first"); List<SaneOption> options = Lists.newArrayList(); SaneSession session = device.getSession(); SaneInputStream inputStream = session.getInputStream(); SaneOutputStream outputStream = session.getOutputStream(); // initialise the current group currentGroup = null; // send RPC 4 outputStream.write(SaneWord.forInt(4)); // select device outputStream.write(device.getHandle().getHandle()); // first word of response in number of option entries int length = inputStream.readWord().integerValue() - 1; if (length <= 0) { return ImmutableList.of(); } for (int i = 0; i <= length; i++) { SaneOption option = SaneOption.fromStream(inputStream, device, i); // We expect the first option to have an empty name. Subsequent options with empty names are // invalid if (option == null || (i > 0 && Strings.isNullOrEmpty(option.getName()))) { continue; } options.add(option); } return options; } private static SaneOption fromStream(SaneInputStream inputStream, SaneDevice device, int optionNumber) throws IOException { SaneOption option = null; // discard pointer inputStream.readWord(); String optionName = inputStream.readString(); String optionTitle = inputStream.readString(); String optionDescription = inputStream.readString(); int typeInt = inputStream.readWord().integerValue(); // TODO: range check here OptionValueType valueType = SaneEnums.valueOf(OptionValueType.class, typeInt); int unitsInt = inputStream.readWord().integerValue(); // TODO: range check here OptionUnits units = SaneEnums.valueOf(OptionUnits.class, unitsInt); int size = inputStream.readWord().integerValue(); // constraint type int capabilityWord = inputStream.readWord().integerValue(); int constraintTypeInt = inputStream.readWord().integerValue(); // TODO: range check here OptionValueConstraintType constraintType = SaneEnums.valueOf(OptionValueConstraintType.class, constraintTypeInt); // decode the constraint List<String> stringConstraints = null; List<Integer> valueConstraints = null; RangeConstraint rangeConstraint = null; switch (constraintType) { case NO_CONSTRAINT: // inputStream.readWord(); // discard empty list break; case STRING_LIST_CONSTRAINT: stringConstraints = Lists.newArrayList(); int n = inputStream.readWord().integerValue(); for (int i = 0; i < n; i++) { stringConstraints.add(inputStream.readString()); } // inputStream.readWord(); break; case VALUE_LIST_CONSTRAINT: valueConstraints = Lists.newArrayList(); n = inputStream.readWord().integerValue(); for (int i = 0; i < n; i++) { valueConstraints.add(inputStream.readWord().integerValue()); } // inputStream.readWord(); // TODO: Is this necessary? break; case RANGE_CONSTRAINT: // TODO: still don't understand the 6 values int w0 = inputStream.readWord().integerValue(); int w1 = inputStream.readWord().integerValue(); int w2 = inputStream.readWord().integerValue(); int w3 = inputStream.readWord().integerValue(); // int w4 = inputStream.readWord().integerValue(); switch (valueType) { case INT: rangeConstraint = new IntegerRangeContraint(w1, w2, w3); break; case FIXED: rangeConstraint = new FixedRangeConstraint(w1, w2, w3); break; default: throw new IllegalStateException("Integer or Fixed type expected for range constraint"); } break; default: throw new IllegalStateException("Unknow constrint type"); } // handle a change of group if (valueType == OptionValueType.GROUP) { currentGroup = new Group(optionTitle, valueType); } else { // TODO: lots option = new SaneOption(device, optionNumber, optionName, optionTitle, optionDescription, currentGroup, valueType, units, size, capabilityWord, constraintType, rangeConstraint, stringConstraints, valueConstraints); } return option; } public static class Group { private final String title; private final OptionValueType valueType; public Group(String title, OptionValueType valueType) { super(); this.title = title; this.valueType = valueType; } public String getTitle() { return title; } public OptionValueType getValueType() { return valueType; } } public SaneDevice getDevice() { return device; } public String getName() { return name; } public String getTitle() { return title; } public String getDescription() { return description; } public Group getGroup() { return group; } public OptionValueType getType() { return valueType; } public OptionUnits getUnits() { return units; } public int getSize() { return size; } public int getValueCount() { switch (valueType) { case BOOLEAN: case STRING: return 1; case INT: case FIXED: return size / SaneWord.SIZE_IN_BYTES; case BUTTON: case GROUP: throw new IllegalStateException("Option type '" + valueType + "' has no value count"); default: throw new IllegalStateException("Option type '" + valueType + "' unknown"); } } public Set<OptionCapability> getCapabilities() { return EnumSet.copyOf(optionCapabilities); } public OptionValueConstraintType getConstraintType() { return constraintType; } public RangeConstraint getRangeConstraints() { return rangeConstraints; } public List<String> getStringContraints() { return stringContraints; } public List<Integer> getWordConstraints() { return wordConstraints; } public String toString() { return String .format("Option: %s, %s, value type: %s, units: %s", name, title, valueType, units); } /** * Reads the current boolean value option. This option must be of type * {@link OptionValueType#BOOLEAN}. * * @throws IOException * if a problem occurred while talking to SANE */ public boolean getBooleanValue() throws IOException { Preconditions.checkState(valueType == OptionValueType.BOOLEAN, "option is not a boolean"); Preconditions.checkState(getValueCount() == 1, "option is a boolean array, not boolean"); ControlOptionResult result = readOption(); return SaneWord.fromBytes(result.getValue()).integerValue() != 0; } /** * Reads the current Integer value option. We do not cache value from previous get or set * operations so each get involves a round trip to the server. * * TODO: consider caching the returned value for "fast read" later * * @return the value of the option * @throws IOException * if a problem occurred while talking to SANE */ public int getIntegerValue() throws IOException { // check for type agreement Preconditions.checkState(valueType == OptionValueType.INT, "option is not an integer"); Preconditions.checkState(getValueCount() == 1, "option is an integer array, not integer"); // Send RCP corresponding to: // SANE_Status sane_control_option (SANE_Handle h, SANE_Int n, // SANE_Action a, void *v, // SANE_Int * i); ControlOptionResult result = readOption(); Preconditions.checkState(result.getType() == OptionValueType.INT); Preconditions.checkState(result.getValueSize() == SaneWord.SIZE_IN_BYTES, "unexpected value size " + result.getValueSize() + ", expecting " + SaneWord.SIZE_IN_BYTES); // TODO: handle resource authorisation // TODO: check status -- may have to reload options!! return SaneWord.fromBytes(result.getValue()).integerValue(); // the // value } public String getStringValue(Charset encoding) throws IOException { Preconditions.checkState(valueType == OptionValueType.STRING, "option is not a string"); ControlOptionResult result = readOption(); byte[] value = result.getValue(); // string is null terminated int length; for (length = 0; length < value.length && value[length] != 0; length++) ; // trim the trailing null character return new String(result.getValue(), 0, length, encoding); } public double getFixedValue() throws IOException { Preconditions.checkState(valueType == OptionValueType.FIXED, "option is not of fixed precision type"); ControlOptionResult result = readOption(); return SaneWord.fromBytes(result.getValue()).fixedPrecisionValue(); } private ControlOptionResult readOption() throws IOException { // check that this option is readable Preconditions.checkState(isReadable(), "option is not readable"); Preconditions.checkState(isActive(), "option is not active"); SaneOutputStream out = device.getSession().getOutputStream(); out.write(SaneWord.forInt(5)); out.write(device.getHandle().getHandle()); out.write(SaneWord.forInt(optionNumber)); out.write(OptionAction.GET_VALUE); out.write(valueType); out.write(SaneWord.forInt(size)); int elementCount; switch (valueType) { case BOOLEAN: case FIXED: case INT: elementCount = 1; break; case STRING: elementCount = size; break; default: throw new IllegalStateException("Unsupported type " + valueType); } out.write(SaneWord.forInt(elementCount)); for (int i = 0; i < size; i++) { out.write(0);// why do we need to provide a value // buffer in an RPC call ??? } // read result ControlOptionResult result = ControlOptionResult.fromStream(device.getSession() .getInputStream()); return result; } /** * Sets the value of the current option to the supplied boolean value. Option value must be of * boolean type. SANE may ignore your preference, so if you need to ensure the value has been set * correctly, you should examine the return value of this method. * * @return the value that the option now has according to SANE */ public boolean setBooleanValue(boolean value) throws IOException { ControlOptionResult result = writeOption(SaneWord.forInt(value ? 1 : 0)); Preconditions.checkState(result.getType() == OptionValueType.BOOLEAN); return SaneWord.fromBytes(result.getValue()).integerValue() != 0; } /** * Sets the value of the current option to the supplied fixed-precision value. Option value must * be of fixed-precision type. */ public double setFixedValue(double value) throws IOException { Preconditions.checkArgument(value >= -32768 && value <= 32767.9999, "value " + value + " is out of range"); SaneWord wordValue = SaneWord.forFixedPrecision(value); ControlOptionResult result = writeOption(wordValue); Preconditions.checkState(result.getType() == OptionValueType.FIXED); return SaneWord.fromBytes(result.getValue()).fixedPrecisionValue(); } public String setStringValue(String newValue) throws IOException { // check for type agreement Preconditions.checkState(valueType == OptionValueType.STRING); Preconditions.checkState(getValueCount() == 1); Preconditions.checkState(isWriteable()); // new value must be STRICTLY less than size(), as SANE includes the // trailing null // that we will add later in its size Preconditions.checkState(newValue.length() < getSize()); ControlOptionResult result = writeOption(newValue); Preconditions.checkState(result.getType() == OptionValueType.STRING); // TODO(sjr): maybe this should go somewhere common? String optionValueFromServer = new String(result.getValue(), 0, result.getValueSize() - 1); Preconditions .checkState( result.getInfo().contains(OptionWriteInfo.INEXACT) ^ newValue.equals(optionValueFromServer), "new option value does not match when it should"); return optionValueFromServer; } /** * Set the value of the current option to the supplied value. Option value must be of integer type * * TODO: consider caching the returned value for "fast read" later * * @param newValue * for the option * @return the value actually set * @throws IOException */ public int setIntegerValue(int newValue) throws IOException { // check for type agreement Preconditions.checkState(valueType == OptionValueType.INT); Preconditions.checkState(getValueCount() == 1, "option is an integer array"); // check that this option is readable Preconditions.checkState(isWriteable()); // Send RPC corresponding to: // SANE_Status sane_control_option (SANE_Handle h, SANE_Int n, // SANE_Action a, void *v, // SANE_Int * i); ControlOptionResult result = writeOption(newValue); Preconditions.checkState(result.getType() == OptionValueType.INT); Preconditions.checkState(result.getValueSize() == SaneWord.SIZE_IN_BYTES); return SaneWord.fromBytes(result.getValue()).integerValue(); } private ControlOptionResult writeOption(SaneWord value) throws IOException { Preconditions.checkState(isWriteable(), "option is not writeable"); Preconditions.checkState(isActive(), "option is not active"); SaneOutputStream out = device.getSession().getOutputStream(); out.write(SaneWord.forInt(5)); out.write(device.getHandle().getHandle()); out.write(SaneWord.forInt(optionNumber)); out.write(SaneWord.forInt(OptionAction.SET_VALUE.getWireValue())); out.write(valueType); out.write(SaneWord.forInt(SaneWord.SIZE_IN_BYTES)); // Write the pointer to the word out.write(SaneWord.forInt(1)); // and the word itself out.write(value); ControlOptionResult result = handleWriteResponse(); if (result.getInfo().contains(OptionWriteInfo.RELOAD_OPTIONS) || result.getInfo().contains(OptionWriteInfo.RELOAD_PARAMETERS)) { device.invalidateOptions(); device.listOptions(); } return result; } private ControlOptionResult writeOption(String value) throws IOException { Preconditions.checkState(valueType == OptionValueType.STRING); SaneOutputStream out = device.getSession().getOutputStream(); out.write(SaneWord.forInt(5) /* rpc #5 */); out.write(SaneWord.forInt(device.getHandle().getHandle().integerValue())); out.write(SaneWord.forInt(this.optionNumber)); out.write(SaneWord.forInt(OptionAction.SET_VALUE.getWireValue())); out.write(valueType); // even if the string is empty, we still write out at least 1 byte (null // terminator) out.write(SaneWord.forInt(value.length() + 1)); // write(String) takes care of writing the size for us out.write(value); return handleWriteResponse(); } private ControlOptionResult writeOption(int value) throws IOException { Preconditions.checkState(valueType == OptionValueType.INT); SaneOutputStream out = device.getSession().getOutputStream(); out.write(SaneWord.forInt(5) /* rpc #5 */); out.write(device.getHandle().getHandle()); out.write(SaneWord.forInt(this.optionNumber)); out.write(OptionAction.SET_VALUE); out.write(valueType); out.write(SaneWord.forInt(size)); out.write(SaneWord.forInt(1)); // only one value follows out.write(SaneWord.forInt(value)); return handleWriteResponse(); } private ControlOptionResult handleWriteResponse() throws IOException { ControlOptionResult result = ControlOptionResult.fromStream(device.getSession() .getInputStream()); if (result.getInfo().contains(OptionWriteInfo.RELOAD_OPTIONS)) { device.invalidateOptions(); } return result; } public boolean isActive() { return !optionCapabilities.contains(OptionCapability.INACTIVE); } public boolean isReadable() { return optionCapabilities.contains(OptionCapability.SOFT_DETECT); } public boolean isWriteable() { return optionCapabilities.contains(OptionCapability.SOFT_SELECT); } /** * Represents the result of calling {@code SANE_NET_CONTROL_OPTION} (RPC code 5). */ private static class ControlOptionResult { private final int status; private final Set<OptionWriteInfo> info; private final OptionValueType type; private final int valueSize; private final byte[] value; private final String resource; private ControlOptionResult(int status, int info, OptionValueType type, int valueSize, byte[] value, String resource) { this.status = status; this.info = SaneEnums.enumSet(OptionWriteInfo.class, info); this.type = type; this.valueSize = valueSize; this.value = value; this.resource = resource; } public static ControlOptionResult fromStream(SaneInputStream stream) throws IOException { int status = stream.readWord().integerValue(); if (status != 0) { SaneStatus statusEnum = SaneStatus.fromWireValue(status); throw new IOException(String.format("unexpected status %d%s", status, statusEnum != null ? " (" + statusEnum + ")" : "")); } int info = stream.readWord().integerValue(); OptionValueType type = SaneEnums.valueOf(OptionValueType.class, stream.readWord() .integerValue()); int valueSize = stream.readWord().integerValue(); // read the pointer int pointer = stream.readWord().integerValue(); byte[] value = null; if (pointer == 0) { // there is no value } else { value = new byte[valueSize]; if (stream.read(value) != valueSize) { throw new IOException("truncated read while getting value"); } } String resource = stream.readString(); return new ControlOptionResult(status, info, type, valueSize, value, resource); } public int getStatus() { return status; } public Set<OptionWriteInfo> getInfo() { return Sets.immutableEnumSet(info); } public OptionValueType getType() { return type; } public int getValueSize() { return valueSize; } public byte[] getValue() { return value; } public String getResource() { return resource; } } }
package authzserver; import authzserver.mock.MockShibbolethFilter; import authzserver.shibboleth.ShibbolethPreAuthenticatedProcessingFilter; import authzserver.shibboleth.ShibbolethUserDetailService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.embedded.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider; @Configuration @EnableWebSecurity public class ShibbolethSecurityConfig extends WebSecurityConfigurerAdapter { private static final Logger LOG = LoggerFactory.getLogger(ShibbolethSecurityConfig.class); @Bean @Profile("dev") public FilterRegistrationBean mockShibbolethFilter() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new MockShibbolethFilter()); filterRegistrationBean.addUrlPatterns("/oauth/authorize"); return filterRegistrationBean; } @Override public void configure(WebSecurity web) throws Exception { web. ignoring()
package ca.krasnay.panelized; import java.util.List; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.form.DropDownChoice; import org.apache.wicket.markup.html.form.IChoiceRenderer; import org.apache.wicket.model.IComponentAssignedModel; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; /** * Control that encapsulates a DropDownChoice component. * * @author <a href="mailto:john@krasnay.ca">John Krasnay</a> */ public class DropDownControl<T> extends AbstractControl<T> { private DropDownChoice<T> dropDownChoice; private boolean required; private IModel<String> nullOptionText; public DropDownControl(String id) { this(id, (List<T>) null); } public DropDownControl(String id, IModel<List<T>> choices) { this(id, null, choices); } public DropDownControl(String id, IModel<T> model, IModel<List<T>> choices) { super(id, model); dropDownChoice = new DropDownChoice<T>("component", new DelegateModel<T>(this), choices) { @Override protected CharSequence getDefaultChoice(final String selected) { if (nullOptionText == null) { return super.getDefaultChoice(selected); } else { boolean noSelection = selected == null || selected.equals(""); if (isNullValid() || noSelection) { StringBuilder sb = new StringBuilder(); sb.append("\n<option"); if (noSelection) { sb.append(" selected=\"selected\""); } sb.append(" value=\"\">").append(nullOptionText.getObject()).append("</option>"); return sb; } else { return ""; } } } @Override public boolean isEnabled() { return isEnabledInternal(); }; @Override public boolean isRequired() { return DropDownControl.this.isRequired(); } @Override protected void onComponentTag(ComponentTag tag) { super.onComponentTag(tag); onDropDownComponentTag(tag); } }; add(dropDownChoice); } public DropDownControl(String id, IModel<T> model, List<T> choices) { this(id, model, Model.ofList(choices)); } public DropDownControl(String id, List<T> choices) { this(id, null, Model.ofList(choices)); } @Override public DropDownChoice<T> getFormComponent() { return dropDownChoice; } public DropDownChoice<T> getDropDownChoice() { return dropDownChoice; } @Override public boolean isRequired() { return required; } // public DropDownControl<T> onChange(final AjaxAction action) { // getFormComponent().add(new AjaxFormComponentUpdatingBehavior("onchange") { // @Override // protected void onUpdate(AjaxRequestTarget target) { // action.invoke(target); // return this; /** * Calls the provided action when the dropdown changes. Note that the model * object is updated when changed, as per Wicket's * AjaxFormComponentUpdatingBehavior. This means that action code can find * out the new value for this dropdown by inspecting the model object; * however, it means that even if the form is cancelled the model object * will have the new value. */ public DropDownControl<T> onChange(final AjaxAction action) { dropDownChoice.add(new AjaxFormComponentUpdatingBehavior("onchange") { @Override protected void onUpdate(AjaxRequestTarget target) { action.invoke(target); } }); return this; } /** * Callback method called from the onComponentTag field of the DropDownControl. * Here we can do last-minute changes to the tag. * * <p>This is called at the end of onComponentTag after the parent * implementations have been invoked, so this method can override those * tag changes. * * <p>The default implementation does nothing. */ protected void onDropDownComponentTag(ComponentTag tag) { } public DropDownControl<T> setChoiceRenderer(IChoiceRenderer<T> renderer) { getDropDownChoice().setChoiceRenderer(renderer); return this; } public DropDownControl<T> setChoices(IModel<? extends List<? extends T>> choices) { getDropDownChoice().setChoices(choices); return this; } public DropDownControl<T> setChoices(List<? extends T> choices) { return setChoices(Model.ofList(choices)); } public DropDownControl<T> setNullOptionText(IModel<String> nullOptionText) { if (nullOptionText instanceof IComponentAssignedModel) { this.nullOptionText = ((IComponentAssignedModel<String>) nullOptionText).wrapOnAssignment(this); } else { this.nullOptionText = nullOptionText; } return this; } public DropDownControl<T> setNullValid(boolean nullValid) { getDropDownChoice().setNullValid(nullValid); return this; } @Override public DropDownControl<T> setRequired(boolean required) { this.required = required; return this; } }
package com.akiban.ais.pt; import com.akiban.ais.AISCloner; import com.akiban.ais.model.*; import com.akiban.ais.util.TableChange; import com.akiban.message.MessageRequiredServices; import com.akiban.server.api.DDLFunctions; import com.akiban.server.error.InvalidAlterException; import com.akiban.server.service.session.Session; import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import java.util.*; /** Hook for <code>RenameTableRequest</code>. * The single statement <code>RENAME TABLE xxx TO _xxx_old, _xxx_new TO xxx</code> * arrives from the adapter as two requests. For simplicity, and since * rename is cheap, the first is allowed to proceed, but the target name is noted. * The second is where all the work this has been leading up to happens: the * alter is performed on <code>xxx</code> and new is renamed to old. * In this way, at the end of the atomic rename, the client sees the tables that * it expects with the shape that it expects. But not arrived at in * the way it orchestrated. */ public class OSCRenameTableHook { private final MessageRequiredServices requiredServices; public OSCRenameTableHook(MessageRequiredServices requiredServices) { this.requiredServices = requiredServices; } public boolean before(Session session, TableName oldName, TableName newName) { if ((newName.getTableName().charAt(0) == '_') && newName.getTableName().endsWith("_old") && newName.getSchemaName().equals(oldName.getSchemaName())) { return beforeOld(session, oldName, newName); } else if ((oldName.getTableName().charAt(0) == '_') && oldName.getTableName().endsWith("_new") & oldName.getSchemaName().equals(newName.getSchemaName())) { return beforeNew(session, oldName, newName); } return true; // Allow rename to continue. } /** Handle first rename. * We are being told to rename <code>xxx</code> to <code>_xxx_old</code>. * If this is OSC, there is an <code>_xxx_new</code> that points to <code>xxx</code>. * Except that either one of those _ names might have multiple _'s for uniqueness. */ protected boolean beforeOld(Session session, TableName oldName, TableName newName) { AkibanInformationSchema ais = ais(session); String schemaName = oldName.getSchemaName(); String tableName = oldName.getTableName(); // Easy case first. UserTable table = ais.getUserTable(schemaName, "_" + tableName + "_new"); if ((table != null) && (table.getPendingOSC() != null) && (table.getPendingOSC().getOriginalName().equals(tableName))) { table.getPendingOSC().setCurrentName(newName.getTableName()); return true; } // Try harder. for (Map.Entry<String,UserTable> entry : ais.getSchema(schemaName).getUserTables().entrySet()) { if (entry.getKey().contains(tableName) && (table.getPendingOSC() != null) && (table.getPendingOSC().getOriginalName().equals(tableName))) { table.getPendingOSC().setCurrentName(newName.getTableName()); return true; } } return true; } /** Handle second rename. * Undo the first rename. So far that is the only change to real data that has * been made. If we fail now because of grouping constraints, we are in as good * shape as is possible under those circumstances. * Then do the alter on the original table. * Then rename the temp table to the name that OSC will DROP. */ protected boolean beforeNew(Session session, TableName oldName, TableName newName) { AkibanInformationSchema ais = ais(session); UserTable tempTable = ais.getUserTable(oldName); if (tempTable == null) return true; PendingOSC osc = tempTable.getPendingOSC(); if ((osc == null) || (osc.getCurrentName() == null)) return true; TableName currentName = new TableName(oldName.getSchemaName(), osc.getCurrentName()); if (ais.getUserTable(currentName) == null) return true; TableName origName = new TableName(oldName.getSchemaName(), osc.getOriginalName()); ddl().renameTable(session, currentName, origName); doAlter(session, origName, oldName, osc); ddl().renameTable(session, oldName, currentName); return false; } /** Do the actual alter, corresponding to what was done previously * on a temporary copy of the table. Because we have this copy as * a template, not very much information needs to be remembered * about the earlier alter. */ protected void doAlter(Session session, TableName origName, TableName tempName, PendingOSC changes) { AkibanInformationSchema ais = ais(session); UserTable origTable = ais.getUserTable(origName); UserTable tempTable = ais.getUserTable(tempName); Set<Column> droppedColumns = new HashSet<Column>(); BiMap<Column,Column> modifiedColumns = HashBiMap.<Column,Column>create(); Set<Column> addedColumns = new HashSet<Column>(); getColumnChanges(origTable, tempTable, changes.getColumnChanges(), droppedColumns, modifiedColumns, addedColumns); Set<TableIndex> droppedIndexes = new HashSet<TableIndex>(); BiMap<TableIndex,TableIndex> modifiedIndexes = HashBiMap.<TableIndex,TableIndex>create(); Set<TableIndex> addedIndexes = new HashSet<TableIndex>(); getIndexChanges(origTable, tempTable, changes.getIndexChanges(), droppedIndexes, modifiedIndexes, addedIndexes); AkibanInformationSchema aisCopy = AISCloner.clone(ais, new GroupSelector(origTable.getGroup())); UserTable copyTable = aisCopy.getUserTable(origName); rebuildColumns(origTable, copyTable, droppedColumns, modifiedColumns, addedColumns); rebuildIndexes(origTable, copyTable, droppedIndexes, modifiedIndexes, addedIndexes); rebuildGroup(aisCopy, copyTable); copyTable.endTable(); ddl().alterTable(session, origName, copyTable, changes.getColumnChanges(), changes.getIndexChanges(), null); } private void getColumnChanges(UserTable origTable, UserTable tempTable, Collection<TableChange> changes, Set<Column> droppedColumns, Map<Column,Column> modifiedColumns, Set<Column> addedColumns) { for (TableChange columnChange : changes) { switch (columnChange.getChangeType()) { case DROP: { Column oldColumn = origTable.getColumn(columnChange.getOldName()); if (oldColumn == null) throw new InvalidAlterException(origTable.getName(), "Could not find dropped column " + columnChange); droppedColumns.add(oldColumn); } break; case MODIFY: { Column oldColumn = origTable.getColumn(columnChange.getOldName()); Column newColumn = tempTable.getColumn(columnChange.getNewName()); if ((oldColumn == null) || (newColumn == null)) throw new InvalidAlterException(origTable.getName(), "Could not find modified column " + columnChange); modifiedColumns.put(oldColumn, newColumn); } break; case ADD: { Column newColumn = tempTable.getColumn(columnChange.getNewName()); if (newColumn == null) throw new InvalidAlterException(origTable.getName(), "Could not find added column " + columnChange); addedColumns.add(newColumn); } break; } } } private void rebuildColumns(UserTable origTable, UserTable copyTable, Set<Column> droppedColumns, Map<Column,Column> modifiedColumns, Set<Column> addedColumns) { copyTable.dropColumns(); int colpos = 0; for (Column origColumn : origTable.getColumns()) { if (droppedColumns.contains(origColumn)) continue; Column fromColumn = origColumn; Column newColumn = modifiedColumns.get(origColumn); if (newColumn != null) fromColumn = newColumn; // Note that dropping columns can still cause otherwise // unchanged ones to move. Column.create(copyTable, fromColumn, null, colpos++); } for (Column newColumn : addedColumns) { Column.create(copyTable, newColumn, null, colpos++); } } private void getIndexChanges(UserTable origTable, UserTable tempTable, Collection<TableChange> changes, Set<TableIndex> droppedIndexes, Map<TableIndex,TableIndex> modifiedIndexes, Set<TableIndex> addedIndexes) { for (TableChange indexChange : changes) { switch (indexChange.getChangeType()) { case DROP: { TableIndex oldIndex = origTable.getIndex(indexChange.getOldName()); if (oldIndex == null) throw new InvalidAlterException(origTable.getName(), "Could not find dropped index " + indexChange); droppedIndexes.add(oldIndex); } break; case MODIFY: { TableIndex oldIndex = origTable.getIndex(indexChange.getOldName()); TableIndex newIndex = tempTable.getIndex(indexChange.getNewName()); if ((oldIndex == null) || (newIndex == null)) throw new InvalidAlterException(origTable.getName(), "Could not find modified index " + indexChange); modifiedIndexes.put(oldIndex, newIndex); } break; case ADD: { TableIndex newIndex = tempTable.getIndex(indexChange.getNewName()); if (newIndex == null) throw new InvalidAlterException(origTable.getName(), "Could not find added index " + indexChange); addedIndexes.add(newIndex); } break; } } } private void rebuildIndexes(UserTable origTable, UserTable copyTable, Set<TableIndex> droppedIndexes, Map<TableIndex,TableIndex> modifiedIndexes, Set<TableIndex> addedIndexes) { copyTable.removeIndexes(copyTable.getIndexesIncludingInternal()); for (TableIndex origIndex : origTable.getIndexes()) { if (droppedIndexes.contains(origIndex)) continue; TableIndex fromIndex = origIndex; TableIndex newIndex = modifiedIndexes.get(origIndex); if (newIndex != null) fromIndex = newIndex; rebuildIndex(origTable, copyTable, fromIndex); } for (TableIndex newIndex : addedIndexes) { rebuildIndex(origTable, copyTable, newIndex); } } private void rebuildIndex(UserTable origTable, UserTable copyTable, TableIndex fromIndex) { TableIndex copyIndex = TableIndex.create(copyTable, fromIndex); int idxpos = 0; for (IndexColumn indexColumn : fromIndex.getKeyColumns()) { Column copyColumn = copyTable.getColumn(indexColumn.getColumn().getName()); if (copyColumn == null) // This assumes that index implicitly dropped by // removing all its columns was included in // indexChanges passed from adapter. throw new InvalidAlterException(origTable.getName(), "Could not find index column " + indexColumn); IndexColumn.create(copyIndex, copyColumn, indexColumn, idxpos++); } } // This assumes that OSC was not used to deliberately affect the group, by changing // grouping constraints, say, since the group structure is not on the master. // So it only deals with unintended consequences. private void rebuildGroup(AkibanInformationSchema ais, UserTable table) { rebuildGroupIndexes(ais, table); Join parentJoin = table.getParentJoin(); if (parentJoin != null) { table.removeCandidateParentJoin(parentJoin); if (joinStillValid(parentJoin, table, false)) { parentJoin = rebuildJoin(ais, parentJoin, table, false); table.addCandidateParentJoin(parentJoin); } } for (Join childJoin : table.getChildJoins()) { table.removeCandidateChildJoin(parentJoin); if (joinStillValid(childJoin, table, true)) { childJoin = rebuildJoin(ais, childJoin, table, true); table.addCandidateChildJoin(childJoin); } } } private void rebuildGroupIndexes(AkibanInformationSchema ais, UserTable table) { Group group = table.getGroup(); List<GroupIndex> dropIndexes = new ArrayList<GroupIndex>(); List<GroupIndex> copyIndexes = new ArrayList<GroupIndex>(); for (GroupIndex groupIndex : group.getIndexes()) { boolean found = false, drop = false; for (IndexColumn indexColumn : groupIndex.getKeyColumns()) { if (indexColumn.getColumn().getTable() == table) { found = true; if (table.getColumn(indexColumn.getColumn().getName()) == null) { drop = true; } } } if (found) { if (drop) dropIndexes.add(groupIndex); else copyIndexes.add(groupIndex); } } group.removeIndexes(dropIndexes); group.removeIndexes(copyIndexes); for (GroupIndex oldIndex : copyIndexes) { GroupIndex newIndex = GroupIndex.create(ais, group, oldIndex); int idxpos = 0; for (IndexColumn indexColumn : oldIndex.getKeyColumns()) { Column column = indexColumn.getColumn(); if (column.getTable() == table) column = table.getColumn(column.getName()); IndexColumn.create(newIndex, column, indexColumn, idxpos++); } } } private boolean joinStillValid(Join join, UserTable table, boolean asParent) { for (JoinColumn joinColumn : join.getJoinColumns()) { Column column = (asParent) ? joinColumn.getParent() : joinColumn.getChild(); assert (column.getTable() == table); if (table.getColumn(column.getName()) == null) return false; } return true; } private Join rebuildJoin(AkibanInformationSchema ais, Join oldJoin, UserTable table, boolean asParent) { Join newJoin = Join.create(ais, oldJoin.getName(), oldJoin.getParent(), oldJoin.getChild()); for (JoinColumn joinColumn : oldJoin.getJoinColumns()) { Column parent = joinColumn.getParent(); Column child = joinColumn.getChild(); if (asParent) parent = table.getColumn(parent.getName()); else child = table.getColumn(child.getName()); newJoin.addJoinColumn(parent, child); } return newJoin; } private static class GroupSelector extends com.akiban.ais.protobuf.ProtobufWriter.TableSelector { private final Group group; public GroupSelector(Group group) { this.group = group; } @Override public boolean isSelected(Columnar columnar) { return columnar.isTable() && ((Table)columnar).getGroup() == group; } } private AkibanInformationSchema ais(Session session) { return requiredServices.schemaManager().getAis(session); } private DDLFunctions ddl() { return requiredServices.dxl().ddlFunctions(); } }
package com.comandante.creeper.player; import com.comandante.creeper.entity.CreeperEntity; import com.comandante.creeper.managers.GameManager; import com.comandante.creeper.spells.Effect; import com.comandante.creeper.stat.Stats; import com.comandante.creeper.world.Room; import com.google.common.base.Optional; import org.apache.commons.codec.binary.Base64; import org.jboss.netty.channel.Channel; public class Player extends CreeperEntity { private String playerName; private Channel channel; private Optional<String> returnDirection = Optional.absent(); private final GameManager gameManager; private Room currentRoom; public Player(String playerName, GameManager gameManager) { this.playerName = playerName; this.gameManager = gameManager; } public String getPlayerName() { return playerName; } public String getPlayerId() { return new String(Base64.encodeBase64(playerName.getBytes())); } public Channel getChannel() { return channel; } public void setChannel(Channel channel) { this.channel = channel; } public void setPlayerName(String playerName) { this.playerName = playerName; } public Optional<String> getReturnDirection() { return returnDirection; } public void setReturnDirection(Optional<String> returnDirection) { this.returnDirection = returnDirection; } public Room getCurrentRoom() { return currentRoom; } public void setCurrentRoom(Room currentRoom) { this.currentRoom = currentRoom; } @Override public void run() { PlayerMetadata playerMetadata = gameManager.getPlayerManager().getPlayerMetadata(this.getPlayerId()); Stats stats = gameManager.getStatsModifierFactory().getStatsModifier(this); if (playerMetadata.getStats().getCurrentHealth() < stats.getMaxHealth()) { gameManager.addHealth(this, (int) (playerMetadata.getStats().getMaxHealth() * .05)); } if (playerMetadata.getStats().getCurrentMana() < stats.getMaxMana()) { gameManager.addMana(this, (int) (playerMetadata.getStats().getMaxMana() * .03)); } for (String effectId: playerMetadata.getEffects()) { Effect effect = gameManager.getEntityManager().getEffect(effectId); gameManager.getEffectsManager().applyEffectStatsOnTick(effect, playerMetadata); effect.setTicks(effect.getTicks() + 1); if (effect.getTicks() >= effect.getLifeSpanTicks()) { gameManager.getEffectsManager().removeDurationStats(effect, playerMetadata); gameManager.getEntityManager().removeEffect(effect); } else { gameManager.getEntityManager().saveEffect(effect); } } } }
package com.conveyal.r5.analyst; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClient; import com.amazonaws.services.sqs.model.MessageAttributeValue; import com.amazonaws.services.sqs.model.SendMessageRequest; import com.conveyal.r5.analyst.cluster.GridRequest; import com.conveyal.r5.analyst.cluster.Origin; import com.conveyal.r5.api.util.LegMode; import com.conveyal.r5.profile.FastRaptorWorker; import com.conveyal.r5.profile.PerTargetPropagater; import com.conveyal.r5.profile.StreetMode; import com.conveyal.r5.streets.LinkedPointSet; import com.conveyal.r5.streets.StreetRouter; import com.conveyal.r5.transit.TransportNetwork; import gnu.trove.iterator.TIntIntIterator; import gnu.trove.list.TIntList; import gnu.trove.list.array.TIntArrayList; import gnu.trove.map.TIntIntMap; import org.apache.commons.math3.random.MersenneTwister; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Base64; import java.util.stream.DoubleStream; public class GridComputer { private static final Logger LOG = LoggerFactory.getLogger(GridComputer.class); /** The number of bootstrap replications used to bootstrap the sampling distribution of the percentiles */ public static final int N_BOOTSTRAP_REPLICATIONS = 1000; /** SQS client. TODO: async? */ private static final AmazonSQS sqs = new AmazonSQSClient(); private static final Base64.Encoder base64 = Base64.getEncoder(); private final GridCache gridCache; public final GridRequest request; private static WebMercatorGridPointSetCache pointSetCache = new WebMercatorGridPointSetCache(); public final TransportNetwork network; public GridComputer(GridRequest request, GridCache gridCache, TransportNetwork network) { this.request = request; this.gridCache = gridCache; this.network = network; } public void run() throws IOException { final Grid grid = gridCache.get(request.grid); // ensure they both have the same zoom level if (request.zoom != grid.zoom) throw new IllegalArgumentException("grid zooms do not match!"); // use the middle of the grid cell request.request.fromLat = Grid.pixelToCenterLat(request.north + request.y, request.zoom); request.request.fromLon = Grid.pixelToCenterLon(request.west + request.x, request.zoom); // Run the raptor algorithm to get times at each destination for each iteration // first, find the access stops StreetMode mode; if (request.request.accessModes.contains(LegMode.CAR)) mode = StreetMode.CAR; else if (request.request.accessModes.contains(LegMode.BICYCLE)) mode = StreetMode.BICYCLE; else mode = StreetMode.WALK; LOG.info("Maximum number of rides: {}", request.request.maxRides); LOG.info("Maximum trip duration: {}", request.request.maxTripDurationMinutes); // Use the extent of the opportunity density grid as the destinations; this avoids having to convert between // coordinate systems, and avoids including thousands of extra points in the weeds where there happens to be a // transit stop. It also means that all data will be included in the analysis even if the user is only analyzing // a small part of the city. WebMercatorGridPointSet destinations = pointSetCache.get(grid); // TODO recast using egress mode final LinkedPointSet linkedDestinations = destinations.link(network.streetLayer, mode); StreetRouter sr = new StreetRouter(network.streetLayer); sr.distanceLimitMeters = 2000; sr.setOrigin(request.request.fromLat, request.request.fromLon); sr.dominanceVariable = StreetRouter.State.RoutingVariable.DISTANCE_MILLIMETERS; sr.route(); TIntIntMap reachedStops = sr.getReachedStops(); // convert millimeters to seconds int millimetersPerSecond = (int) (request.request.walkSpeed * 1000); for (TIntIntIterator it = reachedStops.iterator(); it.hasNext();) { it.advance(); it.setValue(it.value() / millimetersPerSecond); } FastRaptorWorker router = new FastRaptorWorker(network.transitLayer, request.request, reachedStops); // Run the raptor algorithm int[][] timesAtStopsEachIteration = router.route(); // compute bootstrap weights, see comments in Javadoc detailing how we compute the weights we're using // the Mersenne Twister is a fast, high-quality RNG well-suited to Monte Carlo situations MersenneTwister twister = new MersenneTwister(); // This stores the number of times each Monte Carlo draw is included in each bootstrap sample, which could be // 0, 1 or more. We store the weights on each iteration rather than a list of iterations because it allows // us to easily construct the weights s.t. they sum to the original number of MC draws. int[][] bootstrapWeights = new int[N_BOOTSTRAP_REPLICATIONS + 1][router.nMinutes * router.monteCarloDrawsPerMinute]; Arrays.fill(bootstrapWeights[0], 1); // equal weight to all observations for first sample for (int bootstrap = 1; bootstrap < bootstrapWeights.length; bootstrap++) { for (int minute = 0; minute < router.nMinutes; minute++) { for (int draw = 0; draw < router.monteCarloDrawsPerMinute; draw++) { bootstrapWeights[bootstrap][twister.nextInt(router.monteCarloDrawsPerMinute)]++; } } } // Do propagation of travel times from transit stops to the destinations int[] nonTransferTravelTimesToStops = linkedDestinations.eval(sr::getTravelTimeToVertex).travelTimes; PerTargetPropagater propagater = new PerTargetPropagater(timesAtStopsEachIteration, nonTransferTravelTimesToStops, linkedDestinations, request.request, request.cutoffMinutes * 60); // store the accessibility results for each bootstrap replication double[] bootstrapReplications = new double[N_BOOTSTRAP_REPLICATIONS + 1]; // The lambda will be called with a boolean array of whether the target is reachable within the cutoff at each // Monte Carlo draw. These are then bootstrapped to create the sampling distribution. propagater.propagate((target, reachable) -> { int gridx = target % grid.width; int gridy = target / grid.width; double opportunityCountAtTarget = grid.grid[gridx][gridy]; // as an optimization, don't even bother to compute the sampling distribution at cells that contain no // opportunities. if (opportunityCountAtTarget < 1e-6) return; // index the Monte Carlo iterations in which the destination was reached within the travel time cutoff, // so we can skip over the non-reachable ones in bootstrap computations. // this improves computation speed (verified) TIntList reachableInIterationsList = new TIntArrayList(); for (int i = 0; i < reachable.length; i++) { if (reachable[i]) reachableInIterationsList.add(i); } int[] reachableInIterations = reachableInIterationsList.toArray(); boolean isAlwaysReachableWithinTravelTimeCutoff = reachableInIterations.length == timesAtStopsEachIteration.length; boolean isNeverReachableWithinTravelTimeCutoff = reachableInIterations.length == 0; // Optimization: only bootstrap if some of the travel times are above the cutoff and some below. // If a destination is always reachable, it will perforce be reachable always in every bootstrap // sample, so there is no need to compute the bootstraps, and similarly if it is never reachable. if (isAlwaysReachableWithinTravelTimeCutoff) { // this destination is always reachable and will be included in all bootstrap samples, no need to do the // bootstrapping // possible optimization: have a variable that persists between calls to this lambda and increment // that single value, then add that value to each replication at the end; reduces the number of additions. for (int i = 0; i < bootstrapReplications.length; i++) bootstrapReplications[i] += grid.grid[gridx][gridy]; } else if (isNeverReachableWithinTravelTimeCutoff) { // do nothing, never reachable, does not impact accessibility } else { // This origin is sometimes reachable within the time window, do bootstrapping to determine // the distribution of how often for (int bootstrap = 0; bootstrap < N_BOOTSTRAP_REPLICATIONS + 1; bootstrap++) { int count = 0; for (int iteration : reachableInIterations) { count += bootstrapWeights[bootstrap][iteration]; } // TODO sigmoidal rolloff here, to avoid artifacts from large destinations that jump a few seconds // in or out of the cutoff. if (count > timesAtStopsEachIteration.length / 2) { bootstrapReplications[bootstrap] += opportunityCountAtTarget; } } } }); // round (not cast/floor) these all to ints. int[] intReplications = DoubleStream.of(bootstrapReplications).mapToInt(d -> (int) Math.round(d)).toArray(); // now construct the output // these things are tiny, no problem storing in memory ByteArrayOutputStream baos = new ByteArrayOutputStream(); new Origin(request, intReplications).write(baos); // send this origin to an SQS queue as a binary payload; it will be consumed by GridResultConsumer // and GridResultAssembler SendMessageRequest smr = new SendMessageRequest(request.outputQueue, base64.encodeToString(baos.toByteArray())); smr = smr.addMessageAttributesEntry("jobId", new MessageAttributeValue().withDataType("String").withStringValue(request.jobId)); sqs.sendMessage(smr); } }
package com.crystalcraftmc.pvpstorm; import net.md_5.bungee.api.ChatColor; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; public class PvPStorm extends JavaPlugin { // TODO Implement mob boss health bar - perhaps in listener? NEEDS RESEARCH. public void onEnable() { getLogger().info(ChatColor.AQUA + "PvP Storm has been initialized!"); getServer().getPluginManager().registerEvents(gameStart, this); getServer().getPluginManager().registerEvents(gameEnd, this); } public void onDisable() { getLogger().info(ChatColor.RED + "PvP Storm has been stopped by the server."); } public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (cmd.getName().equalsIgnoreCase("storm")) { if (args.length == 1) { return false; } else if (args.length > 1) { if (args[0].equalsIgnoreCase("start")) { Bukkit.broadcastMessage(ChatColor.DARK_RED + getConfig().getString("start-message")); // TODO Change weather to thunder + lightning? // TODO Implement a timer countdown? // TODO Alert the listener to begin counting who hits the Stormer, in order to give prizes at end return true; } else if (args[0].equalsIgnoreCase("stop")) { Bukkit.broadcastMessage(ChatColor.AQUA + getConfig().getString("end-message")); // TODO Reset weather to sun? // TODO Alert listener to stop counting and give out awards return true; } else if (args[0].equalsIgnoreCase("power")) { // TODO Block console from running these commands! if (args.length < 2) { // TODO Output a list of all possible powers to the user return true; } else if (args[1].equalsIgnoreCase("flare")) { // TODO Damage players in radius, temporarily lower health return true; } else if (args[1].equalsIgnoreCase("vanish")) { // TODO Make user invisible at expense of health return true; } else if (args[1].equalsIgnoreCase("timewarp")) { // TODO Instantly move the user backwards about 10 blocks, but add slowness for a few seconds return true; } } else { return false; } } } } private GameStartListener gameStart = new GameStartListener(this); private GameEndListener gameEnd = new GameEndListener(this); }
package com.faforever.api.config; import com.faforever.api.config.elide.ElideConfig; import com.faforever.api.data.domain.Achievement; import com.faforever.api.data.domain.Avatar; import com.faforever.api.data.domain.AvatarAssignment; import com.faforever.api.data.domain.Clan; import com.faforever.api.data.domain.CoopResult; import com.faforever.api.data.domain.Event; import com.faforever.api.data.domain.FeaturedMod; import com.faforever.api.data.domain.Leaderboard; import com.faforever.api.data.domain.LeaderboardRating; import com.faforever.api.data.domain.Map; import com.faforever.api.data.domain.MapStatistics; import com.faforever.api.data.domain.MapVersion; import com.faforever.api.data.domain.Mod; import com.faforever.api.data.domain.ModVersion; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.caffeine.CaffeineCache; import org.springframework.cache.interceptor.AbstractCacheResolver; import org.springframework.cache.interceptor.CacheOperationInvocationContext; import org.springframework.cache.interceptor.CacheResolver; import org.springframework.cache.support.SimpleCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.web.servlet.HandlerMapping; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.Collection; import java.util.List; import static com.faforever.api.challonge.ChallongeController.CHALLONGE_READ_CACHE_NAME; import static com.faforever.api.featuredmods.FeaturedModService.FEATURED_MOD_FILES_CACHE_NAME; import static com.faforever.api.leaderboard.LeaderboardService.LEADERBOARD_GLOBAL_CACHE_NAME; import static com.faforever.api.leaderboard.LeaderboardService.LEADERBOARD_RANKED_1V1_CACHE_NAME; import static com.faforever.api.security.OAuthClientDetailsService.CLIENTS_CACHE_NAME; import static com.github.benmanes.caffeine.cache.Caffeine.newBuilder; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; @EnableCaching(proxyTargetClass = true) @Configuration @Profile(ApplicationProfile.PRODUCTION) public class CacheConfig { @Bean public CacheManager cacheManager() { SimpleCacheManager cacheManager = new SimpleCacheManager(); cacheManager.setCaches(Arrays.asList( // Elide entity caches new CaffeineCache(ElideConfig.DEFAULT_CACHE_NAME, newBuilder().maximumSize(0).build()), new CaffeineCache(Avatar.TYPE_NAME, newBuilder().expireAfterWrite(5, MINUTES).build()), new CaffeineCache(AvatarAssignment.TYPE_NAME, newBuilder().expireAfterWrite(5, MINUTES).build()), new CaffeineCache(Achievement.TYPE_NAME, newBuilder().expireAfterWrite(60, MINUTES).build()), new CaffeineCache(Clan.TYPE_NAME, newBuilder().expireAfterWrite(5, MINUTES).build()), new CaffeineCache(CoopResult.TYPE_NAME, newBuilder().expireAfterWrite(5, MINUTES).build()), new CaffeineCache(Event.TYPE_NAME, newBuilder().expireAfterWrite(60, MINUTES).build()), new CaffeineCache(FeaturedMod.TYPE_NAME, newBuilder().expireAfterWrite(60, MINUTES).build()), new CaffeineCache(Map.TYPE_NAME, newBuilder().expireAfterWrite(60, MINUTES).build()), new CaffeineCache(MapVersion.TYPE_NAME, newBuilder().expireAfterWrite(60, MINUTES).build()), new CaffeineCache(MapStatistics.TYPE_NAME, newBuilder().expireAfterWrite(1, MINUTES).build()), new CaffeineCache(Mod.TYPE_NAME, newBuilder().expireAfterWrite(60, MINUTES).build()), new CaffeineCache(ModVersion.TYPE_NAME, newBuilder().expireAfterWrite(60, MINUTES).build()), // Other caches new CaffeineCache(CHALLONGE_READ_CACHE_NAME, newBuilder().expireAfterWrite(5, MINUTES).build()), new CaffeineCache(LEADERBOARD_RANKED_1V1_CACHE_NAME, newBuilder().expireAfterWrite(5, MINUTES).build()), new CaffeineCache(LEADERBOARD_GLOBAL_CACHE_NAME, newBuilder().expireAfterWrite(5, MINUTES).build()), new CaffeineCache(FEATURED_MOD_FILES_CACHE_NAME, newBuilder().expireAfterWrite(5, MINUTES).build()), new CaffeineCache(CLIENTS_CACHE_NAME, newBuilder().expireAfterWrite(5, SECONDS).build()), new CaffeineCache(Leaderboard.TYPE_NAME, newBuilder().expireAfterWrite(1, MINUTES).build()), new CaffeineCache(LeaderboardRating.TYPE_NAME, newBuilder().expireAfterWrite(1, MINUTES).build()) )); return cacheManager; } /** * Returns a cache resolver that resolves cache names by JSON API type names. For instance, the type "map" will be * resolved to a cache named "map". If no dedicated cache config is available, the "default" config will be applied. */ @Bean public CacheResolver elideCacheResolver(CacheManager cacheManager) { return new AbstractCacheResolver(cacheManager) { @Override protected Collection<String> getCacheNames(CacheOperationInvocationContext<?> context) { String entity = getEntity((HttpServletRequest) context.getArgs()[1]); if (!cacheManager.getCacheNames().contains(entity)) { return List.of(ElideConfig.DEFAULT_CACHE_NAME); } return List.of(entity); } }; } @SuppressWarnings("unchecked") private String getEntity(HttpServletRequest request) { return (String) ((java.util.Map<String, Object>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE)).get("entity"); } }
package com.rabduck.mutter; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import javax.swing.Icon; import javax.swing.JFileChooser; import javax.swing.filechooser.FileSystemView; public class FileItem implements Item { private Path path; private Icon icon; private final boolean bIconCached = false; public FileItem(String fullPath) { super(); setItemPath(fullPath); } public FileItem(Path fullPath) { super(); setItemPath(fullPath); } @Override public String toString() { return getItemName(); } @Override public String getItemPath() { // TODO Auto-generated method stub return path.toAbsolutePath().toString(); } @Override public String getItemName() { // TODO Auto-generated method stub return path.getFileName().toString(); } @Override public void setItemPath(String fullPath) { // TODO Auto-generated method stub setItemPath(Paths.get(fullPath)); } public void setItemPath(Path fullPath) { // TODO Auto-generated method stub this.path = fullPath; if(bIconCached){ icon = FileSystemView.getFileSystemView().getSystemIcon(new File(getItemPath())); } } @Override public boolean execute(String option) throws ExecException { try { Desktop.getDesktop().open(new File(getItemPath())); } catch (IOException e) { e.printStackTrace(); throw new ExecException(e); } return false; } @Override public Icon getIcon() { if(icon != null){ return icon; } // reference: // How do I get a file's icon in Java? - Stack Overflow return FileSystemView.getFileSystemView().getSystemIcon(new File(getItemPath())); // for OS X ? // JFileChooser jfc = new JFileChooser(); // return jfc.getUI().getFileView(jfc).getIcon(new File(getItemPath())); } }
package com.filestack.transforms; import com.filestack.FileLink; import com.filestack.StorageOptions; import com.filestack.errors.InternalException; import com.filestack.errors.InvalidArgumentException; import com.filestack.errors.InvalidParameterException; import com.filestack.errors.PolicySignatureException; import com.filestack.errors.ResourceNotFoundException; import com.filestack.transforms.tasks.AvTransformOptions; import com.filestack.util.Util; import com.google.gson.JsonObject; import io.reactivex.Single; import io.reactivex.schedulers.Schedulers; import java.io.IOException; import java.util.concurrent.Callable; /** * {@link Transform Transform} subclass for audio and video transformations. */ public class AvTransform extends Transform { /** * Constructs a new instance. * * @param fileLink must point to an existing audio or video resource * @param storeOpts sets how the resulting file(s) are stored, uses defaults if null * @param avOps sets conversion options */ public AvTransform(FileLink fileLink, StorageOptions storeOpts, AvTransformOptions avOps) { super(fileLink); if (avOps == null) { throw new InvalidArgumentException("AvTransform can't be created without options"); } if (storeOpts != null) { tasks.add(TransformTask.merge("video_convert", storeOpts.getAsTask(), avOps)); } else { tasks.add(avOps); } } /** * Gets converted content as a new {@link FileLink}. Starts processing on first call. * Returns null if still processing. Poll this method or use {@link #getFileLinkAsync()}. * If you need other data, such as thumbnails, use {@link Transform#getContentJson()}. * * @return null if processing, new {@link FileLink} if complete * @throws IOException if request fails because of network or other IO issue * @throws PolicySignatureException if security is missing or invalid or tagging isn't enabled * @throws ResourceNotFoundException if handle isn't found * @throws InvalidParameterException if handle is malformed * @throws InternalException if unexpected error occurs */ public FileLink getFileLink() throws IOException, PolicySignatureException, ResourceNotFoundException, InvalidParameterException, InternalException { JsonObject json = getContentJson(); String status = json.get("status").getAsString(); switch (status) { case "started": case "pending": return null; case "completed": JsonObject data = json.get("data").getAsJsonObject(); String url = data.get("url").getAsString(); // Correcting for error where status is "completed" but fields are empty if (url.equals("")) { return null; } String handle = url.split("/")[3]; return new FileLink(apiKey, handle, security); default: throw new InternalException(); } } // Async method wrappers /** * Asynchronously gets converted content as a new {@link FileLink}. * Uses default 10 second polling. Use {@link #getFileLinkAsync(int)} to adjust interval. * * @see #getFileLink() */ public Single<FileLink> getFileLinkAsync() { return getFileLinkAsync(10); } /** * Asynchronously gets converted content as a new {@link FileLink}. * * @param pollInterval how frequently to poll (in seconds) * @see #getFileLink() */ public Single<FileLink> getFileLinkAsync(final int pollInterval) { return Single.fromCallable(new Callable<FileLink>() { @Override public FileLink call() throws Exception { FileLink fileLink = null; while (fileLink == null) { fileLink = getFileLink(); if (!Util.isUnitTest()) { Thread.sleep(pollInterval * 1000); } } return fileLink; } }) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.single()); } }
package com.github.arteam.jdit; import org.skife.jdbi.v2.Handle; /** * A component that responsible for migrating data in the DB */ class DataMigration { private final Handle handle; DataMigration(Handle handle) { this.handle = handle; } /** * Execute a script a from a classpath location * * @param scriptLocation script location (without leading slash). * If one exists, it's trimmed */ public void executeScript(String scriptLocation) { String correctLocation = !scriptLocation.startsWith("/") ? scriptLocation : scriptLocation.substring(1); handle.createScript(correctLocation).executeAsSeparateStatements(); } /** * Sweep data from DB, but don't drop the schema. * Also restart sequences, so tests can rely on its predictability */ public void sweepData() { handle.execute("TRUNCATE SCHEMA public RESTART IDENTITY AND COMMIT"); } }