answer
stringlengths
17
10.2M
package org.safehaus.subutai.impl.template.manager; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.Sets; import java.nio.file.Paths; import java.util.*; import java.util.concurrent.TimeUnit; import org.safehaus.subutai.api.commandrunner.AgentResult; import org.safehaus.subutai.api.commandrunner.Command; import org.safehaus.subutai.api.commandrunner.RequestBuilder; import org.safehaus.subutai.api.templateregistry.Template; import org.safehaus.subutai.shared.protocol.Agent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TemplateManagerImpl extends TemplateManagerBase { private static final Logger logger = LoggerFactory.getLogger(TemplateManagerImpl.class); @Override public String getMasterTemplateName() { return "master"; } @Override public boolean setup(String hostName) { Agent a = agentManager.getAgentByHostname(hostName); return scriptExecutor.execute(a, ActionType.SETUP, 15, TimeUnit.MINUTES); } @Override public boolean clone(String hostName, String templateName, String cloneName) { Agent a = agentManager.getAgentByHostname(hostName); List<Template> parents = templateRegistry.getParentTemplates(templateName); for(Template p : parents) { boolean temp_exists = scriptExecutor.execute(a, ActionType.LIST_TEMPLATES, p.getTemplateName()); if(!temp_exists) { boolean b = scriptExecutor.execute(a, ActionType.IMPORT, p.getTemplateName()); if(!b) { logger.error("Failed to install parent templates: " + p.getTemplateName()); return false; } } } return scriptExecutor.execute(a, ActionType.CLONE, templateName, cloneName, " &"); // TODO: script does not return w/o redirecting outputs!!! // for now, script is run in background } @Override public boolean cloneDestroy(String hostName, String cloneName) { Agent a = agentManager.getAgentByHostname(hostName); return scriptExecutor.execute(a, ActionType.DESTROY, cloneName); } @Override public boolean clonesDestroy(String hostName, Set<String> cloneNames) { Preconditions.checkArgument(!Strings.isNullOrEmpty(hostName), "Host server name is null or empty"); Preconditions.checkArgument(cloneNames != null && !cloneNames.isEmpty(), "Clone names is null or empty"); Agent a = agentManager.getAgentByHostname(hostName); StringBuilder cmdBuilder = new StringBuilder(); int i = 0; for(String cloneName : cloneNames) { cmdBuilder.append("/usr/bin/subutai destroy ").append(cloneName); if(++i < cloneNames.size()) cmdBuilder.append(" & "); } Command cmd = getCommandRunner() .createCommand(new RequestBuilder(cmdBuilder.toString()).withTimeout(180), Sets.newHashSet(a)); getCommandRunner().runCommand(cmd); return cmd.hasSucceeded(); } @Override public boolean clone(String hostName, String templateName, Set<String> cloneNames) { Agent a = agentManager.getAgentByHostname(hostName); List<Template> parents = templateRegistry.getParentTemplates(templateName); for(Template p : parents) { boolean temp_exists = scriptExecutor.execute(a, ActionType.LIST_TEMPLATES, p.getTemplateName()); if(!temp_exists) { boolean b = scriptExecutor.execute(a, ActionType.IMPORT, p.getTemplateName()); if(!b) { logger.error("Failed to install parent templates: " + p.getTemplateName()); return false; } } } boolean result = true; for(String cloneName : cloneNames) { String command = String.format("/usr/bin/subutai clone %s %s &", templateName, cloneName); Command cmd = getCommandRunner() .createCommand(new RequestBuilder(command).withTimeout(180), Sets.newHashSet(a)); getCommandRunner().runCommand(cmd); result &= cmd.hasSucceeded(); } return result; } @Override public boolean cloneRename(String hostName, String oldName, String newName) { Agent a = agentManager.getAgentByHostname(hostName); return scriptExecutor.execute(a, ActionType.RENAME, oldName, newName); } @Override public boolean promoteClone(String hostName, String cloneName) { Agent a = agentManager.getAgentByHostname(hostName); return scriptExecutor.execute(a, ActionType.PROMOTE, cloneName); } @Override public boolean promoteClone(String hostName, String cloneName, String newName, boolean copyit) { List<String> args = new ArrayList<>(); if(newName != null && newName.length() > 0) args.add("-n " + newName); if(copyit) args.add("-c"); args.add(cloneName); String[] arr = args.toArray(new String[args.size()]); Agent a = agentManager.getAgentByHostname(hostName); return scriptExecutor.execute(a, ActionType.PROMOTE, arr); } @Override public boolean importTemplate(String hostName, String templateName) { Agent a = agentManager.getAgentByHostname(hostName); // check parents first List<Template> parents = templateRegistry.getParentTemplates(templateName); for(Template p : parents) { boolean temp_exists = scriptExecutor.execute(a, ActionType.LIST_TEMPLATES, p.getTemplateName()); if(!temp_exists) { boolean installed = scriptExecutor.execute(a, ActionType.IMPORT, p.getTemplateName()); if(!installed) { logger.error("Failed to install parent templates: " + p.getTemplateName()); return false; } } } return scriptExecutor.execute(a, ActionType.IMPORT, templateName); } @Override public String exportTemplate(String hostName, String templateName) { Agent a = agentManager.getAgentByHostname(hostName); boolean b = scriptExecutor.execute(a, ActionType.EXPORT, templateName); if(b) return getExportedPackageFilePath(a, templateName); return null; } private String getExportedPackageFilePath(Agent a, String templateName) { Set<Agent> set = new HashSet<>(Arrays.asList(a)); Command cmd = commandRunner.createCommand(new RequestBuilder("echo $SUBUTAI_TMPDIR"), set); commandRunner.runCommand(cmd); AgentResult res = cmd.getResults().get(a.getUuid()); if(res.getExitCode() != null && res.getExitCode() == 0) { String dir = res.getStdOut(); String s = ActionType.GET_PACKAGE_NAME.buildCommand(templateName); cmd = commandRunner.createCommand(new RequestBuilder(s), set); commandRunner.runCommand(cmd); if(cmd.hasSucceeded()) { res = cmd.getResults().get(a.getUuid()); return Paths.get(dir, res.getStdOut()).toString(); } else { // TODO: to be removed templateName = templateName + "-subutai-template.deb"; return Paths.get(dir, templateName).toString(); } } return null; } }
package owltools.cli; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.semanticweb.owlapi.model.IRI; import org.semanticweb.owlapi.model.OWLClass; import org.semanticweb.owlapi.model.OWLException; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLOntology; import owltools.cli.tools.CLIMethod; import owltools.gaf.GafDocument; import owltools.gaf.GafObjectsBuilder; import owltools.gaf.GeneAnnotation; import owltools.gaf.inference.AnnotationPredictor; import owltools.gaf.inference.CompositionalClassPredictor; import owltools.gaf.inference.Prediction; import owltools.gaf.io.PseudoRdfXmlWriter; import owltools.gaf.io.XgmmlWriter; import owltools.gaf.owl.GAFOWLBridge; import owltools.gaf.rules.AnnotationRuleViolation; import owltools.gaf.rules.AnnotationRulesEngine; import owltools.gaf.rules.AnnotationRulesEngine.AnnotationRuleCheckException; import owltools.gaf.rules.AnnotationRulesFactory; import owltools.gaf.rules.go.GoAnnotationRulesFactoryImpl; import owltools.io.OWLPrettyPrinter; /** * GAF tools for command-line, includes validation of GAF files. * * TODO implement a filtering mechanism for GAF files */ public class GafCommandRunner extends CommandRunner { public GafDocument gafdoc = null; private String gafReportFile = null; /** * Used for loading GAFs into memory * * @param opts * @throws Exception */ @CLIMethod("--gaf") public void gaf(Opts opts) throws Exception { opts.info("GAF-FILE", "parses GAF and makes this the current GAF document"); GafObjectsBuilder builder = new GafObjectsBuilder(); gafdoc = builder.buildDocument(opts.nextOpt()); } @CLIMethod("--gaf2owl") public void gaf2Owl(Opts opts) throws OWLException { opts.info("[-n TARGET-IRI] [-o FILE]", "translates previously loaded GAF document into OWL"); GAFOWLBridge bridge; String iri = null; String out = null; boolean isSkipIndividuals = false; while (opts.hasOpts()) { if (opts.nextEq("-n")) iri = opts.nextOpt(); else if (opts.nextEq("-o")) { out = opts.nextOpt(); } else if (opts.nextEq("-c") || opts.nextEq("--skip-individuals")) { isSkipIndividuals = true; } else break; } if (iri != null) { if (!iri.startsWith("http:")) { iri = "http://purl.obolibrary.org/obo/"+iri; if (!iri.endsWith(".owl")) iri = iri + ".owl"; } // todo - save tgtOnt OWLOntology tgtOnt = g.getManager().createOntology(IRI.create(iri)); bridge = new GAFOWLBridge(g, tgtOnt); } else { // adds gaf axioms back into main ontology bridge = new GAFOWLBridge(g); } bridge.setGenerateIndividuals(!isSkipIndividuals); bridge.translate(gafdoc); if (out != null) { pw.saveOWL(bridge.getTargetOntology(),out,g); } } @CLIMethod("--gaf-xp-predict") public void gafXpPredict(Opts opts) { owlpp = new OWLPrettyPrinter(g); if (gafdoc == null) { System.err.println("No gaf document (use '--gaf GAF-FILE') "); exit(1); } AnnotationPredictor ap = new CompositionalClassPredictor(gafdoc, g); Set<Prediction> predictions = ap.getAllPredictions(); System.out.println("Predictions:"+predictions.size()); for (Prediction p : predictions) { System.out.println(p.render(owlpp)); } } @CLIMethod("--gaf-term-IC-values") public void gafTermICValues(Opts opts) { // TODO - ensure has_part and other relations are excluded owlpp = new OWLPrettyPrinter(g); Map<OWLObject,Set<String>> aMap = new HashMap<OWLObject,Set<String>>(); double corpusSize = gafdoc.getBioentities().size(); for (GeneAnnotation a : gafdoc.getGeneAnnotations()) { OWLObject c = g.getOWLObjectByIdentifier(a.getCls()); for (OWLObject x : g.getAncestorsReflexive(c)) { if (!aMap.containsKey(x)) aMap.put(x, new HashSet<String>()); aMap.get(x).add(a.getBioentity()); } } for (OWLObject c : g.getAllOWLObjects()) { if (c instanceof OWLClass) { if (g.isObsolete(c)) continue; if (!aMap.containsKey(c)) continue; int n = aMap.get(c).size(); double ic = - (Math.log( n / corpusSize) / Math.log(2)); System.out.println(g.getIdentifier(c)+"\t"+g.getLabel(c)+"\t"+ ic); } } } @CLIMethod("--gaf-term-counts") public void gafTermCounts(Opts opts) { // TODO - ensure has_part and other relations are excluded owlpp = new OWLPrettyPrinter(g); Map<OWLObject,Set<String>> aMap = new HashMap<OWLObject,Set<String>>(); for (GeneAnnotation a : gafdoc.getGeneAnnotations()) { OWLObject c = g.getOWLObjectByIdentifier(a.getCls()); for (OWLObject x : g.getAncestorsReflexive(c)) { if (!aMap.containsKey(x)) aMap.put(x, new HashSet<String>()); aMap.get(x).add(a.getBioentity()); } } for (OWLObject c : g.getAllOWLObjects()) { if (c instanceof OWLClass) { if (g.isObsolete(c)) continue; System.out.println(g.getIdentifier(c)+"\t"+g.getLabel(c)+"\t"+ (aMap.containsKey(c) ? aMap.get(c).size() : "0")); } } } @CLIMethod("--gaf-query") public void gafQuery(Opts opts) { opts.info("LABEL", "extracts lines from a GAF file where the ontology term is a reflexive descendant of the query"); OWLObject obj = resolveEntity(opts); Set<OWLObject> descs = g.getDescendantsReflexive(obj); for (GeneAnnotation a : gafdoc.getGeneAnnotations()) { OWLObject c = g.getOWLObjectByIdentifier(a.getCls()); if (descs.contains(c)) { System.out.println(g.getIdentifier(c)+"\t"+a.getBioentityObject()+"\t"+a.getBioentityObject().getSymbol()); } } } @CLIMethod("--gaf-run-checks") public void runGAFChecks(Opts opts) throws AnnotationRuleCheckException, IOException { if (g != null && gafdoc != null && gafReportFile != null) { AnnotationRulesFactory rulesFactory = new GoAnnotationRulesFactoryImpl(g); AnnotationRulesEngine ruleEngine = new AnnotationRulesEngine(-1, rulesFactory ); Map<String, List<AnnotationRuleViolation>> allViolations = ruleEngine.validateAnnotations(gafdoc); File reportFile = new File(gafReportFile); // no violations found, delete previous error file (if it exists) if (allViolations.isEmpty()) { System.out.println("No violations found for gaf."); FileUtils.deleteQuietly(reportFile); return; } // write violations PrintWriter writer = null; try { // TODO make this a more detailed report int allViolationsCount = 0; writer = new PrintWriter(reportFile); writer.println(" List<String> ruleIds = new ArrayList<String>(allViolations.keySet()); Collections.sort(ruleIds); for (String ruleId : ruleIds) { List<AnnotationRuleViolation> violationList = allViolations.get(ruleId); writer.println(ruleId + " count: "+ violationList.size()); for (AnnotationRuleViolation violation : violationList) { writer.print("Line "); writer.print(violation.getLineNumber()); writer.print(": "); writer.println(violation.getMessage()); allViolationsCount++; } writer.println(" } System.err.println(allViolationsCount+" GAF violations found, reportfile: "+gafReportFile); } finally { IOUtils.closeQuietly(writer); } exit(-1); // end with an error code to indicate to Jenkins, that it was not successful } } @CLIMethod("--gaf-report-file") public void setGAFReportFile(Opts opts) { if (opts.hasArgs()) { gafReportFile = opts.nextOpt(); } } @CLIMethod("--pseudo-rdf-xml") public void createRdfXml(Opts opts) throws IOException { opts.info("OUTPUTFILE", "create an RDF XML file in legacy format."); if (g == null) { System.err.println("ERROR: No ontology available."); exit(-1); return; } if(gafdoc == null) { System.err.println("ERROR: No GAF available."); exit(-1); return; } if (!opts.hasArgs()) { System.err.println("ERROR: No output file available."); exit(-1); return; } String outputFileName = opts.nextOpt(); PseudoRdfXmlWriter w = new PseudoRdfXmlWriter(); OutputStream stream = new FileOutputStream(new File(outputFileName)); w.write(stream, g, Arrays.asList(gafdoc)); stream.close(); } @CLIMethod("--write-xgmml") public void writeXgmml(Opts opts) throws IOException { opts.info("OUTPUTFILE", "create an XGMML file in legacy format."); if (g == null) { System.err.println("ERROR: No ontology available."); exit(-1); return; } if (!opts.hasArgs()) { System.err.println("ERROR: No output file available."); exit(-1); return; } String outputFileName = opts.nextOpt(); XgmmlWriter w = new XgmmlWriter(); OutputStream stream = new FileOutputStream(new File(outputFileName)); w.write(stream, g, Arrays.asList(gafdoc)); stream.close(); } }
package edu.umd.cs.findbugs.detect; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import org.apache.bcel.classfile.Method; import org.apache.bcel.generic.BranchInstruction; import org.apache.bcel.generic.GotoInstruction; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.LOOKUPSWITCH; import org.apache.bcel.generic.TABLESWITCH; import org.apache.bcel.util.ByteSequence; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.Detector; import edu.umd.cs.findbugs.StatelessDetector; import edu.umd.cs.findbugs.ba.BasicBlock; import edu.umd.cs.findbugs.ba.CFG; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.Edge; import edu.umd.cs.findbugs.ba.EdgeTypes; import edu.umd.cs.findbugs.visitclass.Constants2; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; public class DuplicateBranches extends PreorderVisitor implements Detector, StatelessDetector, Constants2 { private ClassContext classContext; private BugReporter bugReporter; public DuplicateBranches(BugReporter bugReporter) { this.bugReporter = bugReporter; } public Object clone() throws CloneNotSupportedException { return super.clone(); } public void visitClassContext(ClassContext classContext) { this.classContext = classContext; classContext.getJavaClass().accept(this); } public void visitMethod(Method method) { try { if (method.getCode() == null) return; CFG cfg = classContext.getCFG(method); Iterator<BasicBlock> bbi = cfg.blockIterator(); while (bbi.hasNext()) { BasicBlock bb = bbi.next(); int numOutgoing = cfg.getNumOutgoingEdges(bb); if (numOutgoing == 2) findIfElseDuplicates(cfg, method, bb); else if (numOutgoing > 2) findSwitchDuplicates(cfg, method, bb); } } catch (Exception e) { bugReporter.logError("Failure examining basic blocks in Duplicate Branches detector", e); } } private void findIfElseDuplicates(CFG cfg, Method method, BasicBlock bb) { BasicBlock thenBB = null, elseBB = null; Iterator<Edge> iei = cfg.outgoingEdgeIterator(bb); while (iei.hasNext()) { Edge e = iei.next(); if (e.getType() == EdgeTypes.IFCMP_EDGE) { elseBB = e.getTarget(); } else if (e.getType() == EdgeTypes.FALL_THROUGH_EDGE) { thenBB = e.getTarget(); } } if ((thenBB == null) || (elseBB == null) || (thenBB.getFirstInstruction() == null) || (elseBB.getFirstInstruction() == null)) return; int thenStartPos = thenBB.getFirstInstruction().getPosition(); int elseStartPos = elseBB.getFirstInstruction().getPosition(); BasicBlock thenFinishBlock = findThenFinish(cfg, thenBB, elseStartPos); if (thenFinishBlock == null) return; Instruction lastFinishIns = thenFinishBlock.getLastInstruction().getInstruction(); if (!(lastFinishIns instanceof GotoInstruction)) return; int thenFinishPos = thenFinishBlock.getLastInstruction().getPosition(); int elseFinishPos = ((GotoInstruction) lastFinishIns).getTarget().getPosition(); if (thenFinishPos >= elseStartPos) return; if ((thenFinishPos - thenStartPos) != (elseFinishPos - elseStartPos)) return; byte[] thenBytes = getCodeBytes(method, thenStartPos, thenFinishPos); byte[] elseBytes = getCodeBytes(method, elseStartPos, elseFinishPos); if (!Arrays.equals(thenBytes, elseBytes)) return; bugReporter.reportBug(new BugInstance(this, "DB_DUPLICATE_BRANCHES", LOW_PRIORITY) .addClass(classContext.getJavaClass()) .addMethod(classContext.getJavaClass(), method) .addSourceLineRange(this.classContext, this, thenBB.getFirstInstruction().getPosition(), thenBB.getLastInstruction().getPosition()) .addSourceLineRange(this.classContext, this, elseBB.getFirstInstruction().getPosition(), elseBB.getLastInstruction().getPosition())); } private void findSwitchDuplicates(CFG cfg, Method method, BasicBlock bb) { Iterator<Edge> iei = cfg.outgoingEdgeIterator(bb); int[] switchPos = new int[cfg.getNumOutgoingEdges(bb)+1]; int idx = 0; while (iei.hasNext()) { Edge e = iei.next(); if (EdgeTypes.SWITCH_EDGE == e.getType()) { BasicBlock target = e.getTarget(); InstructionHandle firstIns = target.getFirstInstruction(); if (firstIns == null) return; switchPos[idx++] = firstIns.getPosition(); } else if (EdgeTypes.SWITCH_DEFAULT_EDGE == e.getType()) { BasicBlock target = e.getTarget(); InstructionHandle firstIns = target.getFirstInstruction(); if (firstIns == null) return; switchPos[idx++] = firstIns.getPosition(); } else return; } Arrays.sort(switchPos); if (switchPos.length < 2) return; for (int i = 0; i < switchPos.length-2; i++) { int s1Length = switchPos[i+1] - switchPos[i]; if (s1Length == 0) continue; byte[] s1Bytes = null; for (int j = i+1; j < switchPos.length-1; j++) { int s2Length = switchPos[j+1] - switchPos[j]; if (s2Length == 0) continue; if (s1Length != s2Length) continue; if (s1Bytes == null) s1Bytes = getCodeBytes(method, switchPos[i], switchPos[i+1]); byte[] s2Bytes = getCodeBytes(method, switchPos[j], switchPos[j+1]); if (!Arrays.equals(s1Bytes, s2Bytes)) continue; bugReporter.reportBug(new BugInstance(this, "DB_DUPLICATE_BRANCHES", LOW_PRIORITY) .addClass(classContext.getJavaClass()) .addMethod(classContext.getJavaClass(), method) .addSourceLineRange(this.classContext, this, switchPos[i], switchPos[i+1]-1) .addSourceLineRange(this.classContext, this, switchPos[j], switchPos[j+1]-1)); j = switchPos.length; } } } private byte[] getCodeBytes(Method m, int start, int end) { byte[] code = m.getCode().getCode(); byte[] bytes = new byte[end-start]; System.arraycopy( code, start, bytes, 0, end - start); try { ByteSequence sequence = new ByteSequence(code); while ((sequence.available() > 0) && (sequence.getIndex() < start)) { Instruction.readInstruction(sequence); } int pos; while (sequence.available() > 0 && ((pos = sequence.getIndex()) < end)) { Instruction ins = Instruction.readInstruction(sequence); if ((ins instanceof BranchInstruction) && !(ins instanceof TABLESWITCH) && !(ins instanceof LOOKUPSWITCH)) { BranchInstruction bi = (BranchInstruction)ins; int offset = bi.getIndex(); if ((offset + pos) >= end) { bytes[pos+bi.getLength()-1 - start] = 0; } } } } catch (IOException ioe) { } return bytes; } private BasicBlock findThenFinish(CFG cfg, BasicBlock thenBB, int elsePos) { //Follow fall thru links until we find a goto link past the else Iterator<Edge> ie = cfg.outgoingEdgeIterator(thenBB); while (ie.hasNext()) { Edge e = ie.next(); if (e.getType() == EdgeTypes.GOTO_EDGE) { InstructionHandle firstInsH = e.getTarget().getFirstInstruction(); if (firstInsH != null) { int targetPos = firstInsH.getPosition(); if (targetPos > elsePos) return e.getSource(); } } } ie = cfg.outgoingEdgeIterator(thenBB); while (ie.hasNext()) { Edge e = ie.next(); if (e.getType() == EdgeTypes.FALL_THROUGH_EDGE) { BasicBlock target = e.getTarget(); if (target.getFirstInstruction() == null) return findThenFinish(cfg, target, elsePos); int targetPos = target.getFirstInstruction().getPosition(); if (targetPos < elsePos) return findThenFinish(cfg, target, elsePos); } } return null; } public void report() { } }
package com.ibm.streamsx.topology.function; import java.net.MalformedURLException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import com.ibm.streams.operator.ProcessingElement; /** * Context for a function executing in a IBM Streams application. */ public interface FunctionContext { /** * Get the processing element hosting a function * @return ProcessingElement hosting a function. */ ProcessingElement getPE(); ScheduledExecutorService getScheduledExecutorService(); /** * Return a ThreadFactory that can be used by the function with the thread context * class loader set correctly. Functions should utilize * the returned factory to create Threads. * <P> * Threads returned by the ThreadFactory have not been started * and are set as daemon threads. Functions may set the threads * as non-daemon before starting them. The SPL runtime will wait * for non-daemon threads before terminating a processing * element in standalone mode. * </P> * <P> * Any uncaught exception thrown by the {@code Runnable} passed * to the {@code ThreadFactory.newThread(Runnable)} will cause * the processing element containing the function to terminate. * </P> * <P> * The ThreadFactory will be shutdown when the processing element is to be shutdown. * Once the ThreadFactory * is shutdown a call to <code>newThread()</code> will return null. * </P> * * @return A ThreadFactory that can be used by the function. */ ThreadFactory getThreadFactory(); /** * Get the index of the parallel channel the function is on. * <P> * If the function is in a parallel region, this method returns a value from * 0 to N-1, where N is the {@link #getMaxChannels() number of channels in the parallel region}; * otherwise it returns -1. * </P> * * @return the index of the parallel channel if the * function is executing in a parallel region, or -1 if the function * is not executing in a parallel region. * */ int getChannel(); /** * Get the total number of parallel channels for the parallel region that * the function is in. If the function is not in a parallel region, this * method returns 0. * * @return the number of parallel channels for the parallel region that this * function is in, or 0 if the function is not in a parallel region. */ int getMaxChannels(); * If a file path ends with {@code /* } then it is assumed to * be a directory and all jar files in the directory * with the extension {@code .jar} or {@code .JAR} are * added to the function class loader. * </P> * * @param libraries String representations of URLs and file paths to be * added into the functional class loader. If {@code null} then no libraries * are added to the class loader. * */ void addClassLibraries(String[] libraries) throws MalformedURLException; }
package org.jboss.as.messaging; import org.hornetq.api.core.TransportConfiguration; import org.jboss.staxmapper.XMLExtendedStreamReader; import javax.xml.stream.XMLStreamException; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; /** * @author scott.stark@jboss.org * @version $Revision:$ */ public class ElementUtils { static Logger log = Logger.getLogger("org.jboss.as.messaging"); enum StaxEvent { START_ELEMENT(1), END_ELEMENT(2), PROCESSING_INSTRUCTION(3), CHARACTERS(4), COMMENT(5), SPACE(6), START_DOCUMENT(7), END_DOCUMENT(8), ENTITY_REFERENCE(9), ATTRIBUTE(10), DTD(11), CDATA(12), NAMESPACE(13), NOTATION_DECLARATION(14), ENTITY_DECLARATION(15); /** Stash the values for use as an array indexed by StaxEvent.tag-1 */ private static StaxEvent[] EVENTS = values(); private final int tag; StaxEvent(int tag) { this.tag = tag; } static StaxEvent tagToEvent(int tag) { return EVENTS[tag - 1]; } } static XMLStreamException unexpectedAttribute(final XMLExtendedStreamReader reader, final int index) { return new XMLStreamException("Unexpected attribute '" + reader.getAttributeName(index) + "' encountered", reader.getLocation()); } static XMLStreamException unexpectedElement(final XMLExtendedStreamReader reader) { return new XMLStreamException("Unexpected element '" + reader.getName() + "' encountered", reader.getLocation()); } static TransportConfiguration parseTransportConfiguration(final XMLExtendedStreamReader reader, String name, Element parentElement) throws XMLStreamException { Map<String, Object> params = new HashMap<String, Object>(); int tag = reader.getEventType(); String localName = null; String clazz = null; do { tag = reader.nextTag(); localName = reader.getLocalName(); Element element = Element.forName(localName); if(localName.equals(parentElement.getLocalName()) == true) break; switch(element) { case FACTORY_CLASS: clazz = reader.getElementText(); break; case PARAM: int count = reader.getAttributeCount(); String key = null, value = null; for(int n = 0; n < count; n ++) { String attrName = reader.getAttributeLocalName(n); Attribute attribute = Attribute.forName(attrName); switch (attribute) { case KEY: key = reader.getAttributeValue(n); break; case VALUE: value = reader.getAttributeValue(n); break; default: throw unexpectedAttribute(reader, n); } } reader.discardRemainder(); params.put(key, value); break; } // Scan to element end } while(reader.hasNext()); return new TransportConfiguration(clazz, params, name); } }
package com.enseirb.telecom.s9; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; //test // The Java class will be hosted at the URI path "/myresource" @Path("/app/friends") public class FriendInterface { // TODO: update the class to suit your needs // The Java method will process HTTP GET requests // The Java method will produce content identified by the MIME Media // type "text/plain" @GET @Path("{username}") @Produces(MediaType.APPLICATION_XML) public Response getFriend() { // need to create return Response.status(Status.SERVICE_UNAVAILABLE).build(); } @POST @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response postFriend(Friend friend) { // add a friend return Response.status(Status.SERVICE_UNAVAILABLE).build(); } @PUT @Path("{username}") @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response putFriend(Friend friend) { // need to verify the friend // and after this modifies the friend return Response.status(Status.SERVICE_UNAVAILABLE).build(); } @DELETE @Path("{username}") @Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response deleteFriend(Friend friend) { // need to verify the user // and after this delete the user return Response.status(Status.SERVICE_UNAVAILABLE).build(); } }
package ch.openech.client.ewk; import java.util.ArrayList; import java.util.List; import ch.openech.client.ewk.event.ExportAllAction; import ch.openech.client.ewk.event.KeyDeliveryAction; import ch.openech.client.ewk.event.moveIn.MoveInWizard; import ch.openech.datagenerator.GeneratePersonAction; import ch.openech.dm.person.Person; import ch.openech.dm.person.PlaceOfOrigin; import ch.openech.dm.person.Relation; import ch.openech.mj.application.WindowConfig; import ch.openech.mj.edit.EditorPage; import ch.openech.mj.edit.EditorPageAction; import ch.openech.mj.page.ActionGroup; import ch.openech.mj.page.Page; import ch.openech.mj.page.PageAction; import ch.openech.mj.page.PageContext; import ch.openech.mj.resources.Resources; import ch.openech.mj.util.BusinessRule; import ch.openech.mj.util.StringUtils; import ch.openech.server.EchServer; import ch.openech.xml.write.EchNamespaceContext; public class WindowConfigEwk implements WindowConfig { private final EchNamespaceContext echNamespaceContext; public WindowConfigEwk (EchNamespaceContext echNamespaceContext) { this.echNamespaceContext = echNamespaceContext; } @Override public String getTitle() { return Resources.getString("Application.title") + " - Schema: " + echNamespaceContext.getVersion(); } @Override public void fillActionGroup(PageContext pageContext, ActionGroup actionGroup) { ActionGroup create = actionGroup.getOrCreateActionGroup(ActionGroup.NEW); create.add(new EditorPageAction(MoveInWizard.class, echNamespaceContext.getVersion())); create.add(new PageAction(BirthPage.class, echNamespaceContext.getVersion())); ActionGroup admin = actionGroup.getOrCreateActionGroup("admin"); ActionGroup export = admin.getOrCreateActionGroup("export"); export.add(new ExportAllAction(echNamespaceContext)); if (echNamespaceContext.keyDeliveryPossible()) { export.add(new KeyDeliveryAction(echNamespaceContext)); } ActionGroup imprt = admin.getOrCreateActionGroup("imprt"); imprt.add(new EditorPageAction(BaseDeliveryEditor.class, echNamespaceContext.getVersion())); // TODO updateBaseDeliveryPageMenuVisibility(); imprt.add(new GeneratePersonAction(echNamespaceContext)); // TODO updateGenerateDataVisibility(); } // private void updateBaseDeliveryPageMenuVisibility() { // boolean visible = preferences.getBoolean("menuBaseDelivery", false); // menuItemBaseDeliveryPage.setVisible(visible); // private void updateGenerateDataVisibility() { // boolean visible = preferences.getBoolean("generateData", true); // menuItemGenerateData.setVisible(visible); @Override public Class<?>[] getSearchClasses() { return new Class<?>[]{SearchPersonPage.class}; } public static class BirthPage extends EditorPage { public BirthPage(PageContext context, String version) { super(context, new BirthCreator(context, EchNamespaceContext.getNamespaceContext(20, version))); } @Override public void setPreviousPage(Page page) { if (page instanceof PersonViewPage) { PersonViewPage personPage = (PersonViewPage) page; getFormVisual().setObject(calculatePresets(personPage.getObject())); } } private static Person calculatePresets(Person parentPerson) { Person person = new Person(); Person mother = null; Person father = null; if (parentPerson.isMale()) father = parentPerson; else mother = parentPerson; Relation partnerRelation = parentPerson.getPartner(); if (partnerRelation != null && partnerRelation.partner != null && partnerRelation.partner.vn != null) { Person partnerOfVisiblePerson = EchServer.getInstance().getPersistence().person().getByVn(partnerRelation.partner.vn); if (partnerOfVisiblePerson != null) { if (partnerOfVisiblePerson.isMale()) father = partnerOfVisiblePerson; else mother = partnerOfVisiblePerson; } } if (mother != null) { addRelation(person, mother); } if (father != null) { addRelation(person, father); } presetOfficialName(person, father, mother); presetReligion(person, father, mother); presetNationality(person, father, mother); presetPlaceOfOrigin(person, father, mother); // presetContact(person, father, mother); PreferenceData preferenceData = PreferenceData.load(); person.placeOfBirth.setMunicipalityIdentification(preferenceData.preferencesDefaultsData.residence); return person; } private static void addRelation(Person person, Person parent) { Relation relation = new Relation(); relation.partner = parent.personIdentification; if (parent.isMale()) { relation.typeOfRelationship = "4"; } else if (parent.isFemale()) { relation.typeOfRelationship = "3"; } relation.care = "1"; person.relation.add(relation); } @BusinessRule("Bei Geburt wird offizieller Name von Vater übernommen, wenn nicht vorhanden von Mutter") private static void presetOfficialName(Person person, Person father, Person mother) { if (father != null) { person.personIdentification.officialName = father.personIdentification.officialName; } else if (mother != null) { person.personIdentification.officialName = mother.personIdentification.officialName; } } // private void presetContact(Person person, Person father, Person mother) { // if (mother != null) { // person.dwellingAddress = mother.dwellingAddress; // person.contactPerson = mother.contactPerson; // person.contactPerson.address = mother.contactAddress; // } else if (father != null) { // person.dwellingAddress = father.dwellingAddress; // person.contactPerson = father.contactPerson; // person.contactPerson.address = father.contactAddress; @BusinessRule("Bei Geburt wird Religion von Vater übernommen, wenn nicht vorhanden von Mutter") private static void presetReligion(Person person, Person father, Person mother) { if (father != null && !StringUtils.isEmpty(father.religion)) { person.religion = father.religion; } else if (mother != null && !StringUtils.isEmpty(mother.religion)) { person.religion = mother.religion; } } @BusinessRule("Bei Geburt wird Staatsangehörigkeit von Vater übernommen, wenn nicht vorhanden von Mutter") private static void presetNationality(Person person, Person father, Person mother) { if (father != null && "2".equals(father.nationality.nationalityStatus)) { father.nationality.copyTo(person.nationality); } else if (mother != null && "2".equals(mother.nationality.nationalityStatus)) { mother.nationality.copyTo(person.nationality); } } @BusinessRule("Bei Geburt wird Heimatort von Vater übernommen, wenn nicht vorhanden oder ausländisch von Mutter") private static void presetPlaceOfOrigin(Person person, Person father, Person mother) { if (father != null && father.isSwiss()) { person.placeOfOrigin.addAll(convertToAbstammung(father.placeOfOrigin)); } else if (mother != null && mother.isSwiss()) { person.placeOfOrigin.addAll(convertToAbstammung(mother.placeOfOrigin)); } } private static List<PlaceOfOrigin> convertToAbstammung(List<PlaceOfOrigin> placeOfOrigins) { List<PlaceOfOrigin> result = new ArrayList<PlaceOfOrigin>(); for (PlaceOfOrigin placeOfOrigin : placeOfOrigins) { // placeOfOriginAddOn // auch gar nicht zu PlaceOfOrigin newPlaceOfOrigin = new PlaceOfOrigin(); newPlaceOfOrigin.originName = placeOfOrigin.originName; newPlaceOfOrigin.canton = placeOfOrigin.canton; result.add(newPlaceOfOrigin); } return result; } } }
package edu.umd.cs.findbugs.detect; import edu.umd.cs.findbugs.*; import java.util.*; import org.apache.bcel.classfile.Code; public class FindFloatEquality extends BytecodeScanningDetector implements StatelessDetector { private static final int SAW_NOTHING = 0; private static final int SAW_COMP = 1; private BugReporter bugReporter; private OpcodeStack opStack = new OpcodeStack(); private int state; public FindFloatEquality(BugReporter bugReporter) { this.bugReporter = bugReporter; } Collection<SourceLineAnnotation> found = new LinkedList<SourceLineAnnotation>(); @Override public void visit(Code obj) { found.clear(); opStack.resetForMethodEntry(this); state = SAW_NOTHING; super.visit(obj); if (!found.isEmpty()) { BugInstance bug = new BugInstance(this, "FE_FLOATING_POINT_EQUALITY", NORMAL_PRIORITY) .addClassAndMethod(this); for(SourceLineAnnotation s : found) bug.add(s); bugReporter.reportBug(bug); found.clear(); } } public boolean okValueToCompareAgainst(Number n) { if (n == null) return false; double v = n.doubleValue(); v = v - Math.floor(v); return v == 0.0; } @Override public void sawOpcode(int seen) { if (false) System.out.println(OPCODE_NAMES[seen] + " " + state); opStack.mergeJumps(this); try { switch ( seen ) { case FCMPG: case FCMPL: case DCMPG: case DCMPL: if (opStack.getStackDepth() >= 2) { OpcodeStack.Item first = opStack.getStackItem(0); OpcodeStack.Item second = opStack.getStackItem(1); state = SAW_NOTHING; Number n1 = (Number)first.getConstant(); Number n2 = (Number)second.getConstant(); if (okValueToCompareAgainst(n1)) return; if (okValueToCompareAgainst(n2)) return; } state = SAW_COMP; break; case IFEQ: case IFNE: if (state == SAW_COMP) { SourceLineAnnotation sourceLineAnnotation = SourceLineAnnotation.fromVisitedInstruction(getClassContext(), this, getPC()); if (sourceLineAnnotation != null) found.add(sourceLineAnnotation); } state = SAW_NOTHING; break; default: state = SAW_NOTHING; break; } } finally { opStack.sawOpcode(this, seen); } } }
package com.etsy.conjecture.model; import com.etsy.conjecture.data.LazyVector; import com.etsy.conjecture.Utilities; import static com.google.common.base.Preconditions.checkArgument; import com.etsy.conjecture.data.Label; import com.etsy.conjecture.data.LabeledInstance; import com.etsy.conjecture.data.StringKeyedVector; import java.util.Collection; /** * Builds the weight updates as a function * of learning rate and regularization schedule for SGD learning. * * Default learning rate and regularization are: * LR: Exponentially decreasing * REG: Lazily applied L1 and L2 regularization * Subclasses overwrite LR and REG functions as necessary */ public abstract class SGDOptimizer<L extends Label> implements LazyVector.UpdateFunction { private static final long serialVersionUID = 9153480933266800474L; double laplace = 0.0; double gaussian = 0.0; double initialLearningRate = 0.01; transient UpdateableLinearModel model; double examplesPerEpoch = 10000; boolean useExponentialLearningRate = false; double exponentialLearningRateBase = 0.99; public SGDOptimizer() {} public SGDOptimizer(double g, double l) { gaussian = g; laplace = l; } /** * Do minibatch gradient descent */ public StringKeyedVector getUpdates(Collection<LabeledInstance<L>> minibatch) { StringKeyedVector updateVec = new StringKeyedVector(); for (LabeledInstance<L> instance : minibatch) { updateVec.add(getUpdate(instance)); // accumulate gradient model.truncate(instance); model.epoch++; } updateVec.mul(1.0/minibatch.size()); // do a single update, scaling weights by the // average gradient over the minibatch return updateVec; } /** * Get the update to the param vector using a chosen * learning rate / regularization schedule. * Returns a StringKeyedVector of updates for each * parameter. */ public abstract StringKeyedVector getUpdate(LabeledInstance<L> instance); public void teardown() { } /** * Implements lazy updating of regularization when the regularization * updates aren't sparse (e.g. elastic net l1 and l2, adagrad l1). * * When regularization can be done on just the non-zero elements of * the sample instance (e.g. FTRL proximal, HandsFree), the lazyUpdate * function does nothing (i.e. just returns the unscaled param). */ public double lazyUpdate(String feature, double param, long start, long end) { if (Utilities.floatingPointEquals(laplace, 0.0d) && Utilities.floatingPointEquals(gaussian, 0.0d)) { return param; } for (long iter = start + 1; iter <= end; iter++) { if (Utilities.floatingPointEquals(param, 0.0d)) { return 0.0d; } double eta = getDecreasingLearningRate(iter); /** * TODO: patch so that param cannot cross 0.0 during gaussian update */ param -= eta * gaussian * param; if (param > 0.0) { param = Math.max(0.0, param - eta * laplace); } else { param = Math.min(0.0, param + eta * laplace); } } return param; } /** * Computes a linearly or exponentially decreasing * learning rate as a function of the current epoch. * Even when we have per feature learning rates, it's * necessary to keep track of a decreasing learning rate * for things like truncation. */ public double getDecreasingLearningRate(long t){ double epoch_fudged = Math.max(1.0, (t + 1) / examplesPerEpoch); if (useExponentialLearningRate) { return Math.max( 0d, this.initialLearningRate * Math.pow(this.exponentialLearningRateBase, epoch_fudged)); } else { return Math.max(0d, this.initialLearningRate / epoch_fudged); } } public SGDOptimizer<L> setInitialLearningRate(double rate) { checkArgument(rate > 0, "Initial learning rate must be greater than 0. Given: %s", rate); this.initialLearningRate = rate; return this; } public SGDOptimizer<L> setExamplesPerEpoch(double examples) { checkArgument(examples > 0, "examples per epoch must be positive, given %f", examples); this.examplesPerEpoch = examples; return this; } public SGDOptimizer<L> setUseExponentialLearningRate(boolean useExponentialLearningRate) { this.useExponentialLearningRate = useExponentialLearningRate; return this; } public SGDOptimizer<L> setExponentialLearningRateBase(double base) { checkArgument(base > 0, "exponential learning rate base must be positive, given: %f", base); checkArgument( base <= 1.0, "exponential learning rate base must be at most 1.0, given: %f", base); this.exponentialLearningRateBase = base; return this; } public SGDOptimizer<L> setGaussianRegularizationWeight(double gaussian) { checkArgument(gaussian >= 0.0, "gaussian regularization weight must be positive, given: %f", gaussian); this.gaussian = gaussian; return this; } public SGDOptimizer<L> setLaplaceRegularizationWeight(double laplace) { checkArgument(laplace >= 0.0, "laplace regularization weight must be positive, given: %f", laplace); this.laplace = laplace; return this; } }
package org.gemoc.execution.engine.api_implementations.utils; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Path; import org.eclipse.emf.ecore.EObject; import org.gemoc.execution.engine.Activator; import org.gemoc.gemoc_language_workbench.api.utils.LanguageInitializer; public class Kermeta2LanguageInitializer implements LanguageInitializer { String jarDependenciesFolderPath; String jarDsaFolderPath; public Kermeta2LanguageInitializer(String jarDependenciesFolderPath, String jarDsaFolderPath) { this.jarDependenciesFolderPath = jarDependenciesFolderPath; this.jarDsaFolderPath = jarDsaFolderPath; } @Override public void initialize() { Activator.getMessagingSystem().info("Initializing Kermeta2 Language with...", Activator.PLUGIN_ID); Activator.getMessagingSystem().info("\tFolder containing jar dependencies: " + jarDependenciesFolderPath, Activator.PLUGIN_ID); Activator.getMessagingSystem().info("\tFolder containing jar DSA: " + jarDsaFolderPath, Activator.PLUGIN_ID); Activator.getMessagingSystem().debug( "Adding all the JAR files from folder " + jarDependenciesFolderPath + " and " + jarDsaFolderPath + " to the current ClassLoader", Activator.PLUGIN_ID); ClassLoader customizedClassLoader = this.customizeClassLoader(jarDsaFolderPath, jarDependenciesFolderPath); this.initializeKermeta2(customizedClassLoader); } private void initializeKermeta2(ClassLoader classLoader) { if (classLoader == null) { throw new NullPointerException("The given ClassLoader is null"); } // Parsing the "main.properties" file. Properties prop = new Properties(); InputStream in = classLoader.getResourceAsStream("main.properties"); try { prop.load(in); Class<?> init; init = classLoader.loadClass(prop.get("mainRunner").toString()); Activator.getMessagingSystem().debug( "Calling method init4eclipse : " + init.getDeclaredMethod("init4eclipse").toString(), Activator.PLUGIN_ID); init.getDeclaredMethod("init4eclipse").invoke(null, (Object[]) null); in.close(); } catch (IOException e) { String errorMessage = "IOException while initializing the Kermeta2 language"; Activator.getMessagingSystem().error(errorMessage, Activator.PLUGIN_ID); Activator.error(errorMessage, e); } catch (ClassNotFoundException e) { String errorMessage = "ClassNotFoundException while initializing the Kermeta2 language"; Activator.getMessagingSystem().error(errorMessage, Activator.PLUGIN_ID); Activator.error(errorMessage, e); } catch (IllegalAccessException e) { String errorMessage = "IllegalAccessException while initializing the Kermeta2 language"; Activator.getMessagingSystem().error(errorMessage, Activator.PLUGIN_ID); Activator.error(errorMessage, e); } catch (IllegalArgumentException e) { String errorMessage = "IllegalArgumentException while initializing the Kermeta2 language"; Activator.getMessagingSystem().error(errorMessage, Activator.PLUGIN_ID); Activator.error(errorMessage, e); } catch (InvocationTargetException e) { String errorMessage = "InvocationTargetException while initializing the Kermeta2 language"; Activator.getMessagingSystem().error(errorMessage, Activator.PLUGIN_ID); Activator.error(errorMessage, e); Activator.error(e.getCause().getMessage(), e.getCause()); } catch (NoSuchMethodException e) { String errorMessage = "NoSuchMethodException while initializing the Kermeta2 language"; Activator.getMessagingSystem().error(errorMessage, Activator.PLUGIN_ID); Activator.error(errorMessage, e); } catch (SecurityException e) { String errorMessage = "SecurityException while initializing the Kermeta2 language"; Activator.getMessagingSystem().error(errorMessage, Activator.PLUGIN_ID); Activator.error(errorMessage, e); } } private ClassLoader customizeClassLoader(String jarDsaFolderPath, String jarDependenciesFolderPath) { List<URL> urls = new ArrayList<URL>(); try { urls.addAll(this.getJarUrlsFromFolder(jarDependenciesFolderPath)); urls.addAll(this.getJarUrlsFromFolder(jarDsaFolderPath)); } catch (CoreException e) { String errorMessage = "CoreException while customizing the ClassLoader"; Activator.getMessagingSystem().error(errorMessage, Activator.PLUGIN_ID); Activator.error(errorMessage, e); } catch (MalformedURLException e) { String errorMessage = "MalformedURLException while customizing the ClassLoader"; Activator.getMessagingSystem().error(errorMessage, Activator.PLUGIN_ID); Activator.error(errorMessage, e); } URL[] turls = (URL[]) urls.toArray(new URL[urls.size()]); ClassLoader res = new URLClassLoader(turls, Activator.class.getClassLoader()); return res; } private List<URL> getJarUrlsFromFolder(String folderPath) throws MalformedURLException, CoreException { List<URL> urls = new ArrayList<URL>(); IFolder folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(new Path(folderPath)); for (IResource resource : folder.members()) { if (resource instanceof IFile) { IFile file = (IFile) resource; if (file.getFileExtension().equals("jar")) { urls.add(file.getLocationURI().toURL()); } } } return urls; } }
package edu.uw.zookeeper.common; import static com.google.common.base.Preconditions.checkNotNull; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.base.Objects; import com.google.common.collect.ImmutableBiMap; import edu.uw.zookeeper.data.Serializes; public final class TimeValue implements Comparable<TimeValue> { public static TimeValue milliseconds(long value) { return new TimeValue(value, TimeUnit.MILLISECONDS); } public static TimeValue seconds(long value) { return new TimeValue(value, TimeUnit.SECONDS); } public static TimeValue create(long value, String unitText) { checkNotNull(unitText); TimeUnit unit = null; try { unit = TimeUnit.valueOf(unitText.toUpperCase()); } catch (IllegalArgumentException e) { unit = SHORT_UNIT_NAMES.inverse().get(unitText.toLowerCase()); } if (unit == null) { throw new IllegalArgumentException(String.valueOf(unitText)); } return new TimeValue(value, unit); } public static TimeValue create(long value, TimeUnit unit) { return new TimeValue(value, unit); } @Serializes(from=String.class, to=TimeValue.class) public static TimeValue fromString(String text) { Matcher m = PATTERN.matcher(text); if (! m.matches()) { throw new IllegalArgumentException(text); } long value = Long.parseLong(m.group(1)); String unit = m.group(2); return create(value, unit); } public static final ImmutableBiMap<TimeUnit, String> SHORT_UNIT_NAMES = ImmutableBiMap.<TimeUnit, String>builder() .put(TimeUnit.DAYS, "d") .put(TimeUnit.HOURS, "h") .put(TimeUnit.MINUTES, "m") .put(TimeUnit.SECONDS, "s") .put(TimeUnit.MILLISECONDS, "ms") .put(TimeUnit.MICROSECONDS, "us") .put(TimeUnit.NANOSECONDS, "ns") .build(); protected static String FORMAT = "%d %s"; protected static Pattern PATTERN = Pattern.compile("(\\d+)[ \t]*([a-zA-Z]+)"); private final long value; private final TimeUnit unit; public TimeValue(long value, TimeUnit unit) { this.value = value; this.unit = checkNotNull(unit); } public long value() { return value; } public TimeUnit unit() { return unit; } public long value(TimeUnit to) { return to.convert(value, unit); } public TimeValue convert(TimeUnit to) { return new TimeValue(value(to), to); } public TimeValue difference(TimeValue other) { Long diff = value - other.value(unit); return new TimeValue(diff, unit); } @Override public int compareTo(TimeValue other) { long diff = value - other.value(unit); return (int) diff; } @Override public String toString() { return String.format(FORMAT, value, SHORT_UNIT_NAMES.get(unit)); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (! (obj instanceof TimeValue)) { return false; } TimeValue other = (TimeValue) obj; return Objects.equal(value, other.value) && Objects.equal(unit, other.unit); } @Override public int hashCode() { return Objects.hashCode(value); } }
package com.accenture.multibank.dao; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; import com.accenture.multibank.accounts.AccountModifiable; import com.accenture.multibank.generator.AccountNumberGenerator; import org.junit.Before; import org.junit.Test; import com.accenture.multibank.accounts.SavingAccount; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class TestHashMapAccountDao { AbstractDAO<Integer, AccountModifiable> accDao; int accNr; @Mock AccountNumberGenerator generator; @Before public void setup() { accDao = new HashMapAccountDAO(); accNr = 1; when(generator.generateAccountNumber()).thenReturn(++accNr); } @Test public void safeAndFindAccount() { AccountModifiable actual = new SavingAccount(accNr, 100); accDao.save(actual); AccountModifiable expected = accDao.find(actual.getAccountNumber()); assertEquals(expected, actual); } @Test(expected = NullPointerException.class) public void safeNullAccount() { AccountModifiable actual = null; accDao.save(actual); } @Test() public void findAccountThatDoesNotExist() { AccountModifiable actual = accDao.find(0); assertEquals(null, actual); } @Test public void deleteAccountThatDoesNotExist() { AccountModifiable accountReadable = accDao.delete(0); assertEquals(null, accountReadable); } @Test public void updateAccountThatDoesNotExist() { AccountModifiable tmp = new SavingAccount(generator.generateAccountNumber(), 0); accDao.update(tmp); AccountModifiable actual = accDao.find(accNr); assertEquals(null, actual); } }
package steamcondenser.steam.community.tf2; import org.w3c.dom.Element; /** * The TF2ClassFactory is used to created instances of TF2Class based on the * XML input data * @author Sebastian Staudt */ abstract class TF2ClassFactory { /** * Creates a new instance of TF2Class storing the statistics for a Team * Fortress 2 class with the assigned XML data * @param classData * @return An instance of TF2Class or its subclasses TF2Engineer, TF2Medic, * TF2Sniper or TF2Spy depending on the given XML data */ public static TF2Class getTF2Class(Element classData) { String className = classData.getElementsByTagName("className").item(0).getTextContent(); if(className.equals("Engineer")) { return new TF2Engineer(classData); } else if(className.equals("Medic")) { return new TF2Medic(classData); } else if(className.equals("Sniper")) { return new TF2Sniper(classData); } else if(className.equals("Spy")) { return new TF2Spy(classData); } else { return new TF2Class(classData); } } }
package com.exalttech.trex.ui.models; import javafx.beans.property.*; public class PortModel { private StringProperty portDriver = new SimpleStringProperty(); private StringProperty rxFilterMode = new SimpleStringProperty(); private BooleanProperty multicast = new SimpleBooleanProperty(); private BooleanProperty promiscuousMode = new SimpleBooleanProperty(); private StringProperty owner = new SimpleStringProperty(); private StringProperty portSpeed = new SimpleStringProperty(); private StringProperty portStatus = new SimpleStringProperty(); private StringProperty capturingMode = new SimpleStringProperty(); private BooleanProperty linkStatus = new SimpleBooleanProperty(); private BooleanProperty ledStatus = new SimpleBooleanProperty(); private StringProperty numaMode = new SimpleStringProperty(); private StringProperty pciAddress = new SimpleStringProperty(); private StringProperty rxQueueing = new SimpleStringProperty(); private StringProperty gratARP = new SimpleStringProperty(); private ObjectProperty<FlowControl> flowControl = new SimpleObjectProperty<>(FlowControl.NONE); private PortModel() {} public static PortModel createModelFrom(Port port) { PortModel model = new PortModel(); model.portDriver.setValue(port.getDriver()); model.rxFilterMode.setValue(port.getAttr().getRx_filter_mode()); model.multicast.setValue(port.getAttr().getMulticast().getEnabled()); model.promiscuousMode.setValue(port.getAttr().getPromiscuous().getEnabled()); model.owner.setValue(port.getOwner()); model.portSpeed.setValue(String.valueOf(port.getSpeed())); model.portStatus.setValue(port.getStatus()); model.capturingMode.setValue(port.getCaptureStatus()); model.linkStatus.setValue(port.getLink()); model.ledStatus.setValue(port.getLed()); model.numaMode.set(String.valueOf(port.getNuma())); model.pciAddress.setValue(port.getPci_addr()); model.rxQueueing.setValue(port.getRx_info().getQueue().isIs_active() ? "On" : "Off"); model.gratARP.setValue(port.getRx_info().getGrat_arp().isIs_active() ? "On" : "Off"); model.flowControl.setValue(port.getFlowControl()); return model; } public String getPortDriver() { return portDriver.get(); } public StringProperty portDriverProperty() { return portDriver; } public String getRxFilterMode() { return rxFilterMode.get(); } public StringProperty rxFilterModeProperty() { return rxFilterMode; } public boolean getMulticast() { return multicast.get(); } public BooleanProperty multicastProperty() { return multicast; } public boolean getPromiscuousMode() { return promiscuousMode.get(); } public BooleanProperty promiscuousModeProperty() { return promiscuousMode; } public String getOwner() { return owner.get(); } public StringProperty ownerProperty() { return owner; } public String getPortSpeed() { return portSpeed.get(); } public StringProperty portSpeedProperty() { return portSpeed; } public String getPortStatus() { return portStatus.get(); } public StringProperty portStatusProperty() { return portStatus; } public String getCapturingMode() { return capturingMode.get(); } public StringProperty capturingModeProperty() { return capturingMode; } public boolean getLinkStatus() { return linkStatus.get(); } public BooleanProperty linkStatusProperty() { return linkStatus; } public boolean getLedStatus() { return ledStatus.get(); } public BooleanProperty ledStatusProperty() { return ledStatus; } public String getNumaMode() { return numaMode.get(); } public StringProperty numaModeProperty() { return numaMode; } public String getPciAddress() { return pciAddress.get(); } public StringProperty pciAddressProperty() { return pciAddress; } public String getRxQueueing() { return rxQueueing.get(); } public StringProperty rxQueueingProperty() { return rxQueueing; } public String getGratARP() { return gratARP.get(); } public StringProperty gratARPProperty() { return gratARP; } public FlowControl getFlowControl() { return flowControl.get(); } public ObjectProperty<FlowControl> flowControlProperty() { return flowControl; } }
package org.eclipse.che.ide.extension.machine.client.actions; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import com.google.web.bindery.event.shared.EventBus; import org.eclipse.che.api.machine.gwt.client.MachineServiceClient; import org.eclipse.che.api.machine.gwt.client.events.ExtServerStateEvent; import org.eclipse.che.api.machine.gwt.client.events.ExtServerStateHandler; import org.eclipse.che.api.machine.shared.dto.CommandDto; import org.eclipse.che.api.machine.shared.dto.MachineDto; import org.eclipse.che.api.promises.client.Function; import org.eclipse.che.api.promises.client.FunctionException; import org.eclipse.che.api.promises.client.Operation; import org.eclipse.che.api.promises.client.OperationException; import org.eclipse.che.api.workspace.gwt.client.WorkspaceServiceClient; import org.eclipse.che.commons.annotation.Nullable; import org.eclipse.che.ide.api.action.AbstractPerspectiveAction; import org.eclipse.che.ide.api.action.Action; import org.eclipse.che.ide.api.action.ActionEvent; import org.eclipse.che.ide.api.action.ActionManager; import org.eclipse.che.ide.api.action.CustomComponentAction; import org.eclipse.che.ide.api.action.DefaultActionGroup; import org.eclipse.che.ide.api.action.Presentation; import org.eclipse.che.ide.api.app.AppContext; import org.eclipse.che.ide.api.event.project.CloseCurrentProjectEvent; import org.eclipse.che.ide.api.event.project.CloseCurrentProjectHandler; import org.eclipse.che.ide.extension.machine.client.MachineLocalizationConstant; import org.eclipse.che.ide.extension.machine.client.MachineResources; import org.eclipse.che.ide.extension.machine.client.command.CommandConfiguration; import org.eclipse.che.ide.extension.machine.client.command.CommandType; import org.eclipse.che.ide.extension.machine.client.command.CommandTypeRegistry; import org.eclipse.che.ide.extension.machine.client.command.edit.EditCommandsPresenter; import org.eclipse.che.ide.ui.dropdown.DropDownHeaderWidget; import org.eclipse.che.ide.ui.dropdown.DropDownListFactory; import org.vectomatic.dom.svg.ui.SVGImage; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import static org.eclipse.che.ide.extension.machine.client.MachineExtension.GROUP_COMMANDS_LIST; import static org.eclipse.che.ide.workspace.perspectives.project.ProjectPerspective.PROJECT_PERSPECTIVE_ID; /** * Action that allows user to select command from list of all commands. * * @author Artem Zatsarynnyy */ @Singleton public class SelectCommandComboBoxReady extends AbstractPerspectiveAction implements CustomComponentAction, EditCommandsPresenter.ConfigurationChangedListener, CloseCurrentProjectHandler, ExtServerStateHandler { public static final String GROUP_COMMANDS = "CommandsGroup"; private static final Comparator<CommandConfiguration> commandsComparator = new CommandsComparator(); private final MachineLocalizationConstant locale; private final DropDownHeaderWidget dropDownHeaderWidget; private final HTML devMachineLabelWidget; private final DropDownListFactory dropDownListFactory; private final AppContext appContext; private final String workspaceId; private final ActionManager actionManager; private final WorkspaceServiceClient workspaceServiceClient; private final MachineServiceClient machineServiceClient; private final CommandTypeRegistry commandTypeRegistry; private final MachineResources resources; private List<CommandConfiguration> commands; private DefaultActionGroup commandActions; private String lastDevMachineId; @Inject public SelectCommandComboBoxReady(MachineLocalizationConstant locale, MachineResources resources, ActionManager actionManager, EventBus eventBus, DropDownListFactory dropDownListFactory, WorkspaceServiceClient workspaceServiceClient, MachineServiceClient machineServiceClient, CommandTypeRegistry commandTypeRegistry, EditCommandsPresenter editCommandsPresenter, AppContext appContext, @Named("workspaceId") String workspaceId) { super(Collections.singletonList(PROJECT_PERSPECTIVE_ID), locale.selectCommandControlTitle(), locale.selectCommandControlDescription(), null, null); this.locale = locale; this.resources = resources; this.actionManager = actionManager; this.workspaceServiceClient = workspaceServiceClient; this.machineServiceClient = machineServiceClient; this.commandTypeRegistry = commandTypeRegistry; this.dropDownListFactory = dropDownListFactory; this.appContext = appContext; this.workspaceId = workspaceId; this.dropDownHeaderWidget = dropDownListFactory.createList(GROUP_COMMANDS_LIST); this.devMachineLabelWidget = new HTML(locale.selectCommandEmptyCurrentDevMachineText()); commands = new LinkedList<>(); eventBus.addHandler(ExtServerStateEvent.TYPE, this); editCommandsPresenter.addConfigurationsChangedListener(this); commandActions = new DefaultActionGroup(GROUP_COMMANDS, false, actionManager); actionManager.registerAction(GROUP_COMMANDS, commandActions); lastDevMachineId = null; } @Override public void updateInPerspective(@NotNull ActionEvent event) { final String currentDevMachineId = appContext.getDevMachineId(); if (currentDevMachineId == null) { return; } if (lastDevMachineId == null || !currentDevMachineId.equals(lastDevMachineId)) { //Gets DevMachine name by ID. machineServiceClient.getMachine(currentDevMachineId).then(new Operation<MachineDto>() { @Override public void apply(MachineDto arg) throws OperationException { devMachineLabelWidget.setText(arg.getName()); } }); lastDevMachineId = currentDevMachineId; } } @Override public void actionPerformed(ActionEvent e) { } @Override public Widget createCustomComponent(Presentation presentation) { // Create widgets for custom component 'select command'. FlowPanel customComponentHeader = new FlowPanel(); FlowPanel devMachineIconPanel = new FlowPanel(); FlowPanel commandIconPanel = new FlowPanel(); customComponentHeader.setStyleName(resources.getCss().selectCommandBox()); devMachineIconPanel.setStyleName(resources.getCss().selectCommandBoxIconPanel()); devMachineIconPanel.add(new SVGImage(resources.devMachine())); customComponentHeader.add(devMachineIconPanel); customComponentHeader.add(this.devMachineLabelWidget); commandIconPanel.setStyleName(resources.getCss().selectCommandBoxIconPanel()); commandIconPanel.add(new SVGImage(resources.cmdIcon())); customComponentHeader.add(commandIconPanel); customComponentHeader.add((Widget)dropDownHeaderWidget); return customComponentHeader; } /** Returns selected command. */ @Nullable public CommandConfiguration getSelectedCommand() { if (commands.isEmpty()) { return null; } final String selectedCommandName = dropDownHeaderWidget.getSelectedElementName(); for (CommandConfiguration configuration : commands) { if (configuration.getName().equals(selectedCommandName)) { return configuration; } } return null; } public void setSelectedCommand(CommandConfiguration command) { dropDownHeaderWidget.selectElement(command.getName()); } @Override public void onCloseCurrentProject(CloseCurrentProjectEvent event) { setCommandConfigurations(Collections.<CommandConfiguration>emptyList(), null); } /** * Load all saved commands. * * @param commandToSelect * command that should be selected after loading all commands */ private void loadCommands(@Nullable final CommandConfiguration commandToSelect) { workspaceServiceClient.getCommands(workspaceId).then(new Function<List<CommandDto>, List<CommandConfiguration>>() { @Override public List<CommandConfiguration> apply(List<CommandDto> arg) throws FunctionException { final List<CommandConfiguration> configurationList = new ArrayList<>(); for (CommandDto command : arg) { final CommandType type = commandTypeRegistry.getCommandTypeById(command.getType()); // skip command if it's type isn't registered if (type != null) { configurationList.add(type.getConfigurationFactory().createFromDto(command)); } } return configurationList; } }).then(new Operation<List<CommandConfiguration>>() { @Override public void apply(List<CommandConfiguration> commandConfigurations) throws OperationException { setCommandConfigurations(commandConfigurations, commandToSelect); } }); } /** * Sets command configurations to the list. * * @param commandConfigurations * collection of command configurations to set * @param commandToSelect * command that should be selected or {@code null} if none */ private void setCommandConfigurations(@NotNull List<CommandConfiguration> commandConfigurations, @Nullable CommandConfiguration commandToSelect) { final DefaultActionGroup commandsList = (DefaultActionGroup)actionManager.getAction(GROUP_COMMANDS_LIST); commands.clear(); clearCommandActions(commandsList); commandActions.removeAll(); Collections.sort(commandConfigurations, commandsComparator); CommandConfiguration prevCommand = null; for (CommandConfiguration configuration : commandConfigurations) { if (prevCommand != null && !configuration.getType().getId().equals(prevCommand.getType().getId())) { commandActions.addSeparator(); } commandActions.add(dropDownListFactory.createElement(configuration.getName(), configuration.getType().getIcon(), dropDownHeaderWidget)); prevCommand = configuration; } commandsList.addAll(commandActions); commands.addAll(commandConfigurations); if (commandToSelect != null) { setSelectedCommand(commandToSelect); } else { selectLastUsedCommand(); } } private void clearCommandActions(@NotNull DefaultActionGroup commandsList) { for (Action action : commandActions.getChildActionsOrStubs()) { commandsList.remove(action); } } /** Selects last used command. */ private void selectLastUsedCommand() { if (commands.isEmpty()) { setEmptyCommand(); } else { // TODO: consider to saving last used command ID somewhere // for now, we always select first command final CommandConfiguration command = commands.get(0); dropDownHeaderWidget.selectElement(command.getName()); } } /** Clears the selected element in the 'Select Command' menu. */ private void setEmptyCommand() { dropDownHeaderWidget.selectElement(this.locale.selectCommandEmptyCurrentCommandText()); } @Override public void onConfigurationAdded(CommandConfiguration command) { loadCommands(command); } @Override public void onConfigurationRemoved(CommandConfiguration command) { loadCommands(null); } @Override public void onConfigurationsUpdated(CommandConfiguration command) { loadCommands(command); } @Override public void onExtServerStarted(ExtServerStateEvent event) { loadCommands(null); } @Override public void onExtServerStopped(ExtServerStateEvent event) { } private static class CommandsComparator implements Comparator<CommandConfiguration> { @Override public int compare(CommandConfiguration o1, CommandConfiguration o2) { return o1.getType().getId().compareTo(o2.getType().getId()); } } }
package com.facebook.litho.widget; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.OrientationHelper; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.OnScrollListener; import com.facebook.litho.Component; import com.facebook.litho.ComponentContext; import com.facebook.litho.ComponentInfo; import com.facebook.litho.ComponentTree; import com.facebook.litho.LayoutHandler; import com.facebook.litho.Size; import com.facebook.litho.SizeSpec; import com.facebook.litho.testing.testrunner.ComponentsTestRunner; import junit.framework.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RuntimeEnvironment; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Tests for {@link RecyclerBinder} */ @RunWith(ComponentsTestRunner.class) @PrepareForTest(ComponentTreeHolder.class) @PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"}) public class RecyclerBinderTest { @Rule public PowerMockRule mPowerMockRule = new PowerMockRule(); private static final float RANGE_RATIO = 2.0f; private static final int RANGE_SIZE = 3; private final Map<Component, TestComponentTreeHolder> mHoldersForComponents = new HashMap<>(); private RecyclerBinder mRecyclerBinder; private LayoutInfo mLayoutInfo; private ComponentContext mComponentContext; private final Answer<ComponentTreeHolder> mComponentTreeHolderAnswer = new Answer<ComponentTreeHolder>() { @Override public ComponentTreeHolder answer(InvocationOnMock invocation) throws Throwable { final ComponentInfo componentInfo = (ComponentInfo) invocation.getArguments()[0]; final TestComponentTreeHolder holder = new TestComponentTreeHolder(componentInfo); mHoldersForComponents.put(componentInfo.getComponent(), holder); return holder; } }; @Before public void setup() { mComponentContext = new ComponentContext(RuntimeEnvironment.application); PowerMockito.mockStatic(ComponentTreeHolder.class); PowerMockito.when(ComponentTreeHolder.acquire( any(ComponentInfo.class), any(LayoutHandler.class))) .thenAnswer(mComponentTreeHolderAnswer); mLayoutInfo = mock(LayoutInfo.class); setupBaseLayoutInfoMock(); mRecyclerBinder = new RecyclerBinder(mComponentContext, RANGE_RATIO, mLayoutInfo); } private void setupBaseLayoutInfoMock() { Mockito.when(mLayoutInfo.getScrollDirection()).thenReturn(OrientationHelper.VERTICAL); Mockito.when(mLayoutInfo.getLayoutManager()) .thenReturn(new LinearLayoutManager(mComponentContext)); Mockito.when(mLayoutInfo.approximateRangeSize(anyInt(), anyInt(), anyInt(), anyInt())) .thenReturn(RANGE_SIZE); Mockito.when(mLayoutInfo.getChildHeightSpec(anyInt())) .thenReturn(SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); Mockito.when(mLayoutInfo.getChildWidthSpec(anyInt())) .thenReturn(SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY)); } @Test public void testComponentTreeHolderCreation() { final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(0, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } } @Test public void testOnMeasureAfterAddingItems() { final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } final Size size = new Size(); final int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.AT_MOST); final int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); TestComponentTreeHolder componentTreeHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); int rangeTotal = RANGE_SIZE + (int) (RANGE_SIZE * RANGE_RATIO); for (int i = 1; i <= rangeTotal; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } for (int k = rangeTotal + 1; k < components.size(); k++) { componentTreeHolder = mHoldersForComponents.get(components.get(k).getComponent()); assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } Assert.assertEquals(100, size.width); } @Test public void onBoundsDefined() { final List<ComponentInfo> components = prepareLoadedBinder(); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); holder.mLayoutAsyncCalled = false; holder.mLayoutSyncCalled = false; } mRecyclerBinder.setSize(200, 200); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(holder.mLayoutAsyncCalled); assertFalse(holder.mLayoutSyncCalled); } } @Test public void onBoundsDefinedWithDifferentSize() { final List<ComponentInfo> components = prepareLoadedBinder(); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); holder.mLayoutAsyncCalled = false; holder.mLayoutSyncCalled = false; } mRecyclerBinder.setSize(300, 200); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutSyncCalled); for (int i = 1; i <= rangeTotal; i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutAsyncCalled); } for (int i = rangeTotal + 1; i < components.size(); i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(holder.isTreeValid()); assertFalse(holder.mLayoutAsyncCalled); assertFalse(holder.mLayoutSyncCalled); } } @Test public void testMount() { RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); } @Test public void testMountGrid() { when(mLayoutInfo.getSpanCount()).thenReturn(2); GridLayoutManager gridLayoutManager = mock(GridLayoutManager.class); when(mLayoutInfo.getLayoutManager()).thenReturn(gridLayoutManager); RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(gridLayoutManager).setSpanSizeLookup(any(GridLayoutManager.SpanSizeLookup.class)); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); } @Test public void testMountWithStaleView() { RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); RecyclerView secondRecyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(secondRecyclerView); verify(recyclerView).setLayoutManager(null); verify(recyclerView).setAdapter(null); verify(recyclerView).removeOnScrollListener(any(OnScrollListener.class)); verify(secondRecyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(secondRecyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(secondRecyclerView).addOnScrollListener(any(OnScrollListener.class)); } @Test public void testUnmount() { RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); mRecyclerBinder.unmount(recyclerView); verify(recyclerView).setLayoutManager(null); verify(recyclerView).setAdapter(null); verify(recyclerView).removeOnScrollListener(any(OnScrollListener.class)); } @Test public void testUnmountGrid() { when(mLayoutInfo.getSpanCount()).thenReturn(2); GridLayoutManager gridLayoutManager = mock(GridLayoutManager.class); when(mLayoutInfo.getLayoutManager()).thenReturn(gridLayoutManager); RecyclerView recyclerView = mock(RecyclerView.class); mRecyclerBinder.mount(recyclerView); verify(recyclerView).setLayoutManager(mLayoutInfo.getLayoutManager()); verify(gridLayoutManager).setSpanSizeLookup(any(GridLayoutManager.SpanSizeLookup.class)); verify(recyclerView).setAdapter(any(RecyclerView.Adapter.class)); verify(recyclerView).addOnScrollListener(any(OnScrollListener.class)); mRecyclerBinder.unmount(recyclerView); verify(recyclerView).setLayoutManager(null); verify(gridLayoutManager).setSpanSizeLookup(null); verify(recyclerView).setAdapter(null); verify(recyclerView).removeOnScrollListener(any(OnScrollListener.class)); } @Test public void onRemeasureWithDifferentSize() { final List<ComponentInfo> components = prepareLoadedBinder(); for (int i = 0; i < components.size(); i++) { final TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(i).getComponent()); holder.mLayoutAsyncCalled = false; holder.mLayoutSyncCalled = false; } int widthSpec = SizeSpec.makeSizeSpec(100, SizeSpec.EXACTLY); int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(new Size(), widthSpec, heightSpec); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); TestComponentTreeHolder holder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutSyncCalled); for (int i = 1; i <= rangeTotal; i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutAsyncCalled); } for (int i = rangeTotal + 1; i < components.size(); i++) { holder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(holder.isTreeValid()); assertFalse(holder.mLayoutAsyncCalled); assertFalse(holder.mLayoutSyncCalled); } } @Test public void testComponentWithDifferentSpanSize() { Mockito.when(mLayoutInfo.getLayoutManager()) .thenReturn(new GridLayoutManager(mComponentContext, 2)); final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create() .component(mock(Component.class)) .spanSize((i == 0 || i % 3 == 0) ? 2 : 1) .build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } Size size = new Size(); int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); TestComponentTreeHolder componentTreeHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); Assert.assertEquals(200, size.width); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); for (int i = 1; i <= rangeTotal; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); final int expectedWidth = i % 3 == 0 ? 200 : 100; Assert.assertEquals(expectedWidth, componentTreeHolder.mChildWidth); Assert.assertEquals(100, componentTreeHolder.mChildHeight); } } @Test public void testAddItemsAfterMeasuring() { final Size size = new Size(); final int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); final int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); Assert.assertEquals(200, size.width); final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 100; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 100; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } TestComponentTreeHolder componentTreeHolder; int rangeTotal = RANGE_SIZE + (int) (RANGE_SIZE * RANGE_RATIO); for (int i = 0; i < RANGE_SIZE; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); } for (int i = RANGE_SIZE ; i <= rangeTotal; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } for (int i = rangeTotal + 1; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } } @Test public void testRangeBiggerThanContent() { final List<ComponentInfo> components = new ArrayList<>(); for (int i = 0; i < 2; i++) { components.add(ComponentInfo.create().component(mock(Component.class)).build()); mRecyclerBinder.insertItemAt(i, components.get(i)); } for (int i = 0; i < 2; i++) { Assert.assertNotNull(mHoldersForComponents.get(components.get(i).getComponent())); } Size size = new Size(); int widthSpec = SizeSpec.makeSizeSpec(200, SizeSpec.AT_MOST); int heightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY); mRecyclerBinder.measure(size, widthSpec, heightSpec); TestComponentTreeHolder componentTreeHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutSyncCalled); for (int i = 1; i < 2; i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } Assert.assertEquals(100, size.width); } @Test public void testMoveRange() { final List<ComponentInfo> components = prepareLoadedBinder(); final int newRangeStart = 40; final int newRangeEnd = 42; final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); mRecyclerBinder.onNewVisibleRange(newRangeStart, newRangeEnd); TestComponentTreeHolder componentTreeHolder; for (int i = 0; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); if (i >= newRangeStart - (RANGE_RATIO * RANGE_SIZE) && i <= newRangeStart + rangeTotal) { assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } else { assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); if (i <= rangeTotal) { assertTrue(componentTreeHolder.mDidAcquireStateHandler); } else { assertFalse(componentTreeHolder.mDidAcquireStateHandler); } } } } @Test public void testRealRangeOverridesEstimatedRange() { final List<ComponentInfo> components = prepareLoadedBinder(); final int newRangeStart = 40; final int newRangeEnd = 50; int rangeSize = newRangeEnd - newRangeStart; final int rangeTotal = (int) (rangeSize + (RANGE_RATIO * rangeSize)); mRecyclerBinder.onNewVisibleRange(newRangeStart, newRangeEnd); TestComponentTreeHolder componentTreeHolder; for (int i = 0; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); if (i >= newRangeStart - (RANGE_RATIO * rangeSize) && i <= newRangeStart + rangeTotal) { assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } else { assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } } } @Test public void testMoveRangeToEnd() { final List<ComponentInfo> components = prepareLoadedBinder(); final int newRangeStart = 99; final int newRangeEnd = 99; final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); mRecyclerBinder.onNewVisibleRange(newRangeStart, newRangeEnd); TestComponentTreeHolder componentTreeHolder; for (int i = 0; i < components.size(); i++) { componentTreeHolder = mHoldersForComponents.get(components.get(i).getComponent()); if (i >= newRangeStart - (RANGE_RATIO * RANGE_SIZE) && i <= newRangeStart + rangeTotal) { assertTrue(componentTreeHolder.isTreeValid()); assertTrue(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); } else { assertFalse(componentTreeHolder.isTreeValid()); assertFalse(componentTreeHolder.mLayoutAsyncCalled); assertFalse(componentTreeHolder.mLayoutSyncCalled); if (i <= rangeTotal) { assertTrue(componentTreeHolder.mDidAcquireStateHandler); } else { assertFalse(componentTreeHolder.mDidAcquireStateHandler); } } } } @Test public void testMoveItemOutsideFromRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(0, 99); final TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(0).getComponent()); assertFalse(movedHolder.isTreeValid()); assertFalse(movedHolder.mLayoutAsyncCalled); assertFalse(movedHolder.mLayoutSyncCalled); assertTrue(movedHolder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); final TestComponentTreeHolder holderMovedIntoRange = mHoldersForComponents.get(components.get(rangeTotal + 1).getComponent()); assertTrue(holderMovedIntoRange.isTreeValid()); assertTrue(holderMovedIntoRange.mLayoutAsyncCalled); assertFalse(holderMovedIntoRange.mLayoutSyncCalled); } @Test public void testMoveItemInsideRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(99, 4); TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(99).getComponent()); assertTrue(movedHolder.isTreeValid()); assertTrue(movedHolder.mLayoutAsyncCalled); assertFalse(movedHolder.mLayoutSyncCalled); assertFalse(movedHolder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); TestComponentTreeHolder holderMovedOutsideRange = mHoldersForComponents.get(components.get(rangeTotal).getComponent()); assertFalse(holderMovedOutsideRange.isTreeValid()); assertFalse(holderMovedOutsideRange.mLayoutAsyncCalled); assertFalse(holderMovedOutsideRange.mLayoutSyncCalled); } @Test public void testMoveItemInsideVisibleRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(99, 2); final TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(99).getComponent()); assertTrue(movedHolder.isTreeValid()); assertFalse(movedHolder.mLayoutAsyncCalled); assertTrue(movedHolder.mLayoutSyncCalled); assertFalse(movedHolder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); final TestComponentTreeHolder holderMovedOutsideRange = mHoldersForComponents.get(components.get(rangeTotal).getComponent()); assertFalse(holderMovedOutsideRange.isTreeValid()); assertFalse(holderMovedOutsideRange.mLayoutAsyncCalled); assertFalse(holderMovedOutsideRange.mLayoutSyncCalled); assertTrue(holderMovedOutsideRange.mDidAcquireStateHandler); } @Test public void testMoveItemOutsideRange() { final List<ComponentInfo> components = prepareLoadedBinder(); mRecyclerBinder.moveItem(2, 99); final TestComponentTreeHolder movedHolder = mHoldersForComponents.get(components.get(2).getComponent()); assertFalse(movedHolder.isTreeValid()); assertFalse(movedHolder.mLayoutAsyncCalled); assertFalse(movedHolder.mLayoutSyncCalled); assertTrue(movedHolder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); final TestComponentTreeHolder holderMovedInsideRange = mHoldersForComponents.get(components.get(rangeTotal + 1).getComponent()); assertTrue(holderMovedInsideRange.isTreeValid()); assertTrue(holderMovedInsideRange.mLayoutAsyncCalled); assertFalse(holderMovedInsideRange.mLayoutSyncCalled); assertFalse(holderMovedInsideRange.mDidAcquireStateHandler); } @Test public void testMoveWithinRange() { final List<ComponentInfo> components = prepareLoadedBinder(); final TestComponentTreeHolder movedHolderOne = mHoldersForComponents.get(components.get(0).getComponent()); final TestComponentTreeHolder movedHolderTwo = mHoldersForComponents.get(components.get(1).getComponent()); movedHolderOne.mLayoutSyncCalled = false; movedHolderOne.mLayoutAsyncCalled = false; movedHolderOne.mDidAcquireStateHandler = false; movedHolderTwo.mLayoutSyncCalled = false; movedHolderTwo.mLayoutAsyncCalled = false; movedHolderTwo.mDidAcquireStateHandler = false; mRecyclerBinder.moveItem(0, 1); assertTrue(movedHolderOne.isTreeValid()); assertFalse(movedHolderOne.mLayoutAsyncCalled); assertFalse(movedHolderOne.mLayoutSyncCalled); assertFalse(movedHolderOne.mDidAcquireStateHandler); assertTrue(movedHolderTwo.isTreeValid()); assertFalse(movedHolderTwo.mLayoutAsyncCalled); assertFalse(movedHolderTwo.mLayoutSyncCalled); assertFalse(movedHolderTwo.mDidAcquireStateHandler); } @Test public void testInsertInVisibleRange() { final List<ComponentInfo> components = prepareLoadedBinder(); final ComponentInfo newComponentInfo = ComponentInfo.create().component(mock(Component.class)).build(); mRecyclerBinder.insertItemAt(1, newComponentInfo); final TestComponentTreeHolder holder = mHoldersForComponents.get(newComponentInfo.getComponent()); assertTrue(holder.isTreeValid()); assertTrue(holder.mLayoutSyncCalled); assertFalse(holder.mLayoutAsyncCalled); assertFalse(holder.mDidAcquireStateHandler); final int rangeTotal = (int) (RANGE_SIZE + (RANGE_RATIO * RANGE_SIZE)); final TestComponentTreeHolder holderMovedOutsideRange = mHoldersForComponents.get(components.get(rangeTotal).getComponent()); assertFalse(holderMovedOutsideRange.isTreeValid()); assertFalse(holderMovedOutsideRange.mLayoutSyncCalled); assertFalse(holderMovedOutsideRange.mLayoutAsyncCalled); assertTrue(holderMovedOutsideRange.mDidAcquireStateHandler); } @Test public void testInsertInRange() { final List<ComponentInfo> components = prepareLoadedBinder(); final ComponentInfo newComponentInfo = ComponentInfo.create().component(mock(Component.class)).build();
package net.bull.javamelody; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import net.bull.javamelody.Counter.CounterRequestContextComparator; class Collector { // NOPMD private final int periodMillis; private final String application; private final List<Counter> counters; private final Map<String, JRobin> requestJRobinsById = new ConcurrentHashMap<String, JRobin>(); private final Map<String, JRobin> counterJRobins = new LinkedHashMap<String, JRobin>(); private final Map<String, JRobin> otherJRobins = new LinkedHashMap<String, JRobin>(); // globalRequestsByCounter, requestsById, dayCountersByCounter et cpuTimeMillis private final Map<Counter, CounterRequest> globalRequestsByCounter = new HashMap<Counter, CounterRequest>(); private final Map<String, CounterRequest> requestsById = new HashMap<String, CounterRequest>(); private final Map<Counter, Counter> dayCountersByCounter = new LinkedHashMap<Counter, Counter>(); private long cpuTimeMillis; private long gcTimeMillis; private long tomcatBytesReceived; private long tomcatBytesSent; private long lastCollectDuration; private long estimatedMemorySize; private final boolean noDatabase = Parameters.isNoDatabase(); /** * Constructeur. * @param application Code de l'application * @param counters Liste des counters */ Collector(String application, List<Counter> counters) { super(); assert application != null; assert counters != null; this.application = application; this.counters = Collections.unmodifiableList(new ArrayList<Counter>(counters)); for (final Counter counter : counters) { for (final Counter otherCounter : counters) { assert counter == otherCounter || !counter.getName().equals(otherCounter.getName()); } counter.setApplication(application); final Counter dayCounter = new PeriodCounterFactory(counter) .createDayCounterAtDate(new Date()); dayCountersByCounter.put(counter, dayCounter); } periodMillis = Parameters.getResolutionSeconds() * 1000; try { for (final Counter counter : counters) { counter.readFromFile(); } // et seulement ensuite les compteurs du jour for (final Counter counter : counters) { dayCountersByCounter.get(counter).readFromFile(); } LOG.debug("counters data read from files in " + Parameters.getStorageDirectory(application)); } catch (final IOException e) { // (on n'interrompt pas toute l'initialisation juste pour un fichier illisible) LOG.warn( "exception while reading counters data from files in " + Parameters.getStorageDirectory(application), e); } } /** * Retourne le code de l'application. * @return String */ String getApplication() { return application; } /** * @return La liste des counters de ce collector */ List<Counter> getCounters() { return counters; } Counter getCounterByName(String counterName) { for (final Counter counter : counters) { if (counter.getName().equals(counterName)) { return counter; } } return null; } List<CounterRequestContext> getRootCurrentContexts() { final List<CounterRequestContext> rootCurrentContexts = new ArrayList<CounterRequestContext>(); for (final Counter counter : counters) { if (counter.isDisplayed()) { // a priori, les contextes root courants sont dans le compteur http // mais il est possible qu'il y en ait aussi dans ejb ou sql sans parent dans http rootCurrentContexts.addAll(counter.getOrderedRootCurrentContexts()); } } if (rootCurrentContexts.size() > 1) { Collections.sort(rootCurrentContexts, Collections .reverseOrder(new CounterRequestContextComparator(System.currentTimeMillis()))); } return rootCurrentContexts; } long getLastCollectDuration() { return lastCollectDuration; } long getEstimatedMemorySize() { return estimatedMemorySize; } private List<Counter> getRangeCounters(Range range) throws IOException { if (range.getPeriod() == Period.TOUT) { return new ArrayList<Counter>(counters); } final Collection<Counter> currentDayCounters = dayCountersByCounter.values(); final List<Counter> result = new ArrayList<Counter>(currentDayCounters.size()); for (final Counter dayCounter : currentDayCounters) { final Counter counter = getRangeCounter(range, dayCounter); result.add(counter); } return result; } private Counter getRangeCounter(Range range, Counter dayCounter) throws IOException { final PeriodCounterFactory periodCounterFactory = new PeriodCounterFactory(dayCounter); final Counter counter; if (range.getPeriod() == null) { counter = periodCounterFactory.getCustomCounter(range); } else { switch (range.getPeriod()) { case JOUR: counter = periodCounterFactory.getDayCounter(); break; case SEMAINE: counter = periodCounterFactory.getWeekCounter(); break; case MOIS: counter = periodCounterFactory.getMonthCounter(); break; case ANNEE: counter = periodCounterFactory.getYearCounter(); break; case TOUT: throw new IllegalStateException(range.getPeriod().toString()); default: throw new IllegalArgumentException(range.getPeriod().toString()); } } return counter; } List<Counter> getRangeCountersToBeDisplayed(Range range) throws IOException { final List<Counter> result = new ArrayList<Counter>(getRangeCounters(range)); final Iterator<Counter> it = result.iterator(); while (it.hasNext()) { final Counter counter = it.next(); if (!counter.isDisplayed() || counter.isJobCounter()) { it.remove(); } } return Collections.unmodifiableList(result); } Counter getRangeCounter(Range range, String counterName) throws IOException { final Counter counter = getCounterByName(counterName); if (counter == null) { throw new IllegalArgumentException(counterName); } if (range.getPeriod() == Period.TOUT) { return counter; } return getRangeCounter(range, dayCountersByCounter.get(counter)); } void collectLocalContextWithoutErrors() { // ici on n'inclue pas les informations de la bdd et des threads try { final JavaInformations javaInformations = new JavaInformations( Parameters.getServletContext(), false); collectWithoutErrors(Collections.singletonList(javaInformations)); } catch (final Throwable t) { // NOPMD LOG.warn("exception while collecting data", t); } } void collectWithoutErrors(List<JavaInformations> javaInformationsList) { assert javaInformationsList != null; final long start = System.currentTimeMillis(); try { estimatedMemorySize = collect(javaInformationsList); } catch (final Throwable t) { // NOPMD LOG.warn("exception while collecting data", t); } // note : on n'inclue pas "new JavaInformations" de collectLocalContextWithoutErrors lastCollectDuration = Math.max(0, System.currentTimeMillis() - start); } private long collect(List<JavaInformations> javaInformationsList) throws IOException { synchronized (this) { // si pas d'informations, on ne met pas 0 : on ne met rien if (!javaInformationsList.isEmpty()) { collectJavaInformations(javaInformationsList); } long memorySize = 0; for (final Counter counter : counters) { // counter.isDisplayed() peut changer pour spring, ejb, guice ou services selon l'utilisation dayCountersByCounter.get(counter).setDisplayed(counter.isDisplayed()); if (counter.isDisplayed()) { // et pas de persistance de fichiers jrobin ou du compteur memorySize += collectCounterData(counter); } } return memorySize; } } private void collectJavaInformations(List<JavaInformations> javaInformationsList) throws IOException { long usedMemory = 0; long processesCpuTimeMillis = 0; long usedNonHeapMemory = 0; int loadedClassesCount = 0; long garbageCollectionTimeMillis = 0; long usedPhysicalMemorySize = 0; long usedSwapSpaceSize = 0; int availableProcessors = 0; int sessionCount = 0; long sessionAgeSum = 0; int threadCount = 0; int activeThreadCount = 0; int activeConnectionCount = 0; int usedConnectionCount = 0; double systemLoadAverage = 0; long unixOpenFileDescriptorCount = 0; int tomcatBusyThreads = 0; long bytesReceived = 0; long bytesSent = 0; boolean tomcatUsed = false; for (final JavaInformations javaInformations : javaInformationsList) { final MemoryInformations memoryInformations = javaInformations.getMemoryInformations(); usedMemory = add(memoryInformations.getUsedMemory(), usedMemory); sessionCount = add(javaInformations.getSessionCount(), sessionCount); sessionAgeSum = add(javaInformations.getSessionAgeSum(), sessionAgeSum); threadCount = add(javaInformations.getThreadCount(), threadCount); activeThreadCount = add(javaInformations.getActiveThreadCount(), activeThreadCount); activeConnectionCount = add(javaInformations.getActiveConnectionCount(), activeConnectionCount); usedConnectionCount = add(javaInformations.getUsedConnectionCount(), usedConnectionCount); // il y a au moins 1 coeur availableProcessors = add(Math.max(javaInformations.getAvailableProcessors(), 1), availableProcessors); processesCpuTimeMillis = add(javaInformations.getProcessCpuTimeMillis(), processesCpuTimeMillis); usedNonHeapMemory = add(memoryInformations.getUsedNonHeapMemory(), usedNonHeapMemory); loadedClassesCount = add(memoryInformations.getLoadedClassesCount(), loadedClassesCount); usedPhysicalMemorySize = add(memoryInformations.getUsedPhysicalMemorySize(), usedPhysicalMemorySize); usedSwapSpaceSize = add(memoryInformations.getUsedSwapSpaceSize(), usedSwapSpaceSize); garbageCollectionTimeMillis = add(memoryInformations.getGarbageCollectionTimeMillis(), garbageCollectionTimeMillis); systemLoadAverage = add(javaInformations.getSystemLoadAverage(), systemLoadAverage); // que sur linx ou unix unixOpenFileDescriptorCount = add(javaInformations.getUnixOpenFileDescriptorCount(), unixOpenFileDescriptorCount); for (final TomcatInformations tomcatInformations : javaInformations .getTomcatInformationsList()) { tomcatBusyThreads = add(tomcatInformations.getCurrentThreadsBusy(), tomcatBusyThreads); bytesReceived = add(tomcatInformations.getBytesReceived(), bytesReceived); bytesSent = add(tomcatInformations.getBytesSent(), bytesSent); tomcatUsed = true; } } collectJRobinValues(usedMemory, processesCpuTimeMillis, availableProcessors, sessionCount, activeThreadCount, activeConnectionCount, usedConnectionCount); if (tomcatUsed) { // collecte des informations de Tomcat collectTomcatValues(tomcatBusyThreads, bytesReceived, bytesSent); } // collecte du pourcentage de temps en ramasse-miette collectGcTime(garbageCollectionTimeMillis, availableProcessors); collectorOtherJRobinsValues(usedNonHeapMemory, loadedClassesCount, usedPhysicalMemorySize, usedSwapSpaceSize, threadCount, systemLoadAverage, unixOpenFileDescriptorCount); collectSessionsMeanAge(sessionAgeSum, sessionCount); // on pourrait collecter la valeur 100 dans jrobin pour qu'il fasse la moyenne } private static double add(double t1, double t2) { // et positives ie disponibles pour une autre JVM/OS // et dans ce cas, si windows et linux alors on ne somme pas et on garde linux, // si linux et windows alors on garde linux, // si linux et linux alors on somme linux+linux qui est positif if (t1 < 0d && t2 > 0d) { return t2; } else if (t1 > 0d && t2 < 0d) { return t1; } return t1 + t2; } private static long add(long t1, long t2) { if (t1 < 0L && t2 > 0L) { return t2; } else if (t1 > 0L && t2 < 0L) { return t1; } return t1 + t2; } private static int add(int t1, int t2) { if (t1 < 0 && t2 > 0) { return t2; } else if (t1 > 0 && t2 < 0) { return t1; } return t1 + t2; } private void collectJRobinValues(long usedMemory, long processesCpuTimeMillis, int availableProcessors, int sessionCount, int activeThreadCount, int activeConnectionCount, int usedConnectionCount) throws IOException { getCounterJRobin("usedMemory").addValue(usedMemory); // collecte du pourcentage d'utilisation cpu collectCpu(processesCpuTimeMillis, availableProcessors); // collecte du nombre de sessions http if (sessionCount >= 0) { getCounterJRobin("httpSessions").addValue(sessionCount); } // et du nombre de connexions jdbc ouvertes getCounterJRobin("activeThreads").addValue(activeThreadCount); if (!noDatabase) { getCounterJRobin("activeConnections").addValue(activeConnectionCount); getCounterJRobin("usedConnections").addValue(usedConnectionCount); } } private void collectCpu(long processesCpuTimeMillis, int availableProcessors) throws IOException { if (processesCpuTimeMillis >= 0) { // processesCpuTimeMillis est la somme pour tous les serveurs (et pour tous les coeurs) // quel que soit le nombre de serveurs ou de coeurs; final int cpuPercentage = Math.min((int) ((processesCpuTimeMillis - this.cpuTimeMillis) * 100 / periodMillis / availableProcessors), 100); getCounterJRobin("cpu").addValue(cpuPercentage); this.cpuTimeMillis = processesCpuTimeMillis; } } private void collectGcTime(long garbageCollectionTimeMillis, int availableProcessors) throws IOException { if (garbageCollectionTimeMillis >= 0) { final int gcPercentage = Math .min((int) ((garbageCollectionTimeMillis - this.gcTimeMillis) * 100 / periodMillis / availableProcessors), 100); getOtherJRobin("gc").addValue(gcPercentage); this.gcTimeMillis = garbageCollectionTimeMillis; } } private void collectTomcatValues(int tomcatBusyThreads, long bytesReceived, long bytesSent) throws IOException { getOtherJRobin("tomcatBusyThreads").addValue(tomcatBusyThreads); final double periodMinutes = periodMillis / 60000d; getOtherJRobin("tomcatBytesReceived").addValue( (bytesReceived - this.tomcatBytesReceived) / periodMinutes); getOtherJRobin("tomcatBytesSent").addValue( (bytesSent - this.tomcatBytesSent) / periodMinutes); this.tomcatBytesReceived = bytesReceived; this.tomcatBytesSent = bytesSent; } private void collectorOtherJRobinsValues(long usedNonHeapMemory, int loadedClassesCount, long usedPhysicalMemorySize, long usedSwapSpaceSize, int threadCount, double systemLoadAverage, long unixOpenFileDescriptorCount) throws IOException { final Map<String, Double> otherJRobinsValues = new LinkedHashMap<String, Double>(); otherJRobinsValues.put("threadCount", (double) threadCount); otherJRobinsValues.put("loadedClassesCount", (double) loadedClassesCount); otherJRobinsValues.put("usedNonHeapMemory", (double) usedNonHeapMemory); otherJRobinsValues.put("usedPhysicalMemorySize", (double) usedPhysicalMemorySize); otherJRobinsValues.put("usedSwapSpaceSize", (double) usedSwapSpaceSize); otherJRobinsValues.put("systemLoad", systemLoadAverage); otherJRobinsValues.put("fileDescriptors", (double) unixOpenFileDescriptorCount); for (final Map.Entry<String, Double> entry : otherJRobinsValues.entrySet()) { if (entry.getValue() >= 0) { getOtherJRobin(entry.getKey()).addValue(entry.getValue()); } } } private void collectSessionsMeanAge(long sessionAgeSum, int sessionCount) throws IOException { if (sessionCount >= 0) { final long sessionAgeMeanInMinutes; if (sessionCount > 0) { sessionAgeMeanInMinutes = sessionAgeSum / sessionCount / 60000; } else { sessionAgeMeanInMinutes = -1; } getOtherJRobin("httpSessionsMeanAge").addValue(sessionAgeMeanInMinutes); } } private long collectCounterData(Counter counter) throws IOException { // counterName vaut http, sql ou ws par exemple final String counterName = counter.getName(); final List<CounterRequest> requests = counter.getRequests(); if (!counter.isErrorCounter()) { final CounterRequest newGlobalRequest = new CounterRequest(counterName + " global", counterName); for (final CounterRequest request : requests) { newGlobalRequest.addHits(request); } final JRobin hitsJRobin; final JRobin meanTimesJRobin; final JRobin systemErrorsJRobin; if (!counter.isJspOrStrutsCounter()) { hitsJRobin = getCounterJRobin(counterName + "HitsRate"); meanTimesJRobin = getCounterJRobin(counterName + "MeanTimes"); systemErrorsJRobin = getCounterJRobin(counterName + "SystemErrors"); } else { hitsJRobin = getOtherJRobin(counterName + "HitsRate"); meanTimesJRobin = getOtherJRobin(counterName + "MeanTimes"); systemErrorsJRobin = getOtherJRobin(counterName + "SystemErrors"); } final CounterRequest globalRequest = globalRequestsByCounter.get(counter); if (globalRequest != null) { // alors on n'inscrit pas de valeurs car les nouveaux hits final CounterRequest lastPeriodGlobalRequest = newGlobalRequest.clone(); lastPeriodGlobalRequest.removeHits(globalRequest); final long hits = lastPeriodGlobalRequest.getHits(); final long hitsParMinute = hits * 60 * 1000 / periodMillis; hitsJRobin.addValue(hitsParMinute); // s'il n'y a pas eu de hits, alors la moyenne vaut -1 : elle n'a pas de sens if (hits > 0) { // NOPMD meanTimesJRobin.addValue(lastPeriodGlobalRequest.getMean()); systemErrorsJRobin.addValue(lastPeriodGlobalRequest.getSystemErrorPercentage()); counter.writeToFile(); } } // on sauvegarde les nouveaux totaux pour la prochaine fois globalRequestsByCounter.put(counter, newGlobalRequest); } final long dayCounterEstimatedMemorySize = collectCounterRequestsAndErrorsData(counter, requests); return counter.getEstimatedMemorySize() + dayCounterEstimatedMemorySize; } private long collectCounterRequestsAndErrorsData(Counter counter, List<CounterRequest> requests) throws IOException { int size = requests.size(); final Counter dayCounter = getCurrentDayCounter(counter); final int maxRequestsCount = counter.getMaxRequestsCount(); for (final CounterRequest newRequest : requests) { if (size > maxRequestsCount && newRequest.getHits() < 10) { removeRequest(counter, newRequest); size continue; } collectCounterRequestData(dayCounter, newRequest); } while (size > maxRequestsCount && !requests.isEmpty()) { removeRequest(counter, requests.get(0)); size } if (dayCounter.isErrorCounter()) { dayCounter.addErrors(getDeltaOfErrors(counter, dayCounter)); } dayCounter.writeToFile(); return dayCounter.getEstimatedMemorySize(); } private void collectCounterRequestData(Counter dayCounter, CounterRequest newRequest) throws IOException { final String requestStorageId = newRequest.getId(); final JRobin requestJRobin; if (!dayCounter.isJspOrStrutsCounter() && (!dayCounter.isErrorCounter() || dayCounter.isJobCounter())) { requestJRobin = getRequestJRobin(requestStorageId, newRequest.getName()); } else { requestJRobin = null; } final CounterRequest request = requestsById.get(requestStorageId); if (request != null) { // sauf si c'est l'initialisation final CounterRequest lastPeriodRequest = newRequest.clone(); lastPeriodRequest.removeHits(request); if (lastPeriodRequest.getHits() > 0) { if (requestJRobin != null) { // s'il n'y a pas eu de hits, alors la moyenne vaut -1 : elle n'a pas de sens requestJRobin.addValue(lastPeriodRequest.getMean()); } dayCounter.addHits(lastPeriodRequest); } } requestsById.put(requestStorageId, newRequest); } private List<CounterError> getDeltaOfErrors(Counter counter, Counter dayCounter) { final List<CounterError> errors = counter.getErrors(); if (errors.isEmpty()) { return Collections.emptyList(); } final long lastErrorTime; final List<CounterError> dayErrors = dayCounter.getErrors(); if (dayErrors.isEmpty()) { lastErrorTime = dayCounter.getStartDate().getTime(); } else { lastErrorTime = dayErrors.get(dayErrors.size() - 1).getTime(); } final List<CounterError> errorsOfDay = new ArrayList<CounterError>(); for (final CounterError error : errors) { // il peut arriver de manquer une erreur dans l'affichage par jour // mais tant pis et il y a peu de chance que cela arrive if (error.getTime() > lastErrorTime) { errorsOfDay.add(error); } } return errorsOfDay; } private Counter getCurrentDayCounter(Counter counter) throws IOException { Counter dayCounter = dayCountersByCounter.get(counter); final Calendar calendar = Calendar.getInstance(); final int currentDayOfYear = calendar.get(Calendar.DAY_OF_YEAR); calendar.setTime(dayCounter.getStartDate()); if (calendar.get(Calendar.DAY_OF_YEAR) != currentDayOfYear) { dayCounter = new PeriodCounterFactory(dayCounter).buildNewDayCounter(); dayCountersByCounter.put(counter, dayCounter); } return dayCounter; } private void removeRequest(Counter counter, CounterRequest newRequest) { counter.removeRequest(newRequest.getName()); requestsById.remove(newRequest.getId()); final JRobin requestJRobin = requestJRobinsById.remove(newRequest.getId()); if (requestJRobin != null) { requestJRobin.deleteFile(); } } private JRobin getRequestJRobin(String requestId, String requestName) throws IOException { JRobin jrobin = requestJRobinsById.get(requestId); if (jrobin == null) { jrobin = JRobin.createInstance(getApplication(), requestId, requestName); requestJRobinsById.put(requestId, jrobin); } return jrobin; } private JRobin getCounterJRobin(String name) throws IOException { JRobin jrobin = counterJRobins.get(name); if (jrobin == null) { jrobin = JRobin.createInstance(getApplication(), name, null); counterJRobins.put(name, jrobin); } return jrobin; } private JRobin getOtherJRobin(String name) throws IOException { JRobin jrobin = otherJRobins.get(name); if (jrobin == null) { jrobin = JRobin.createInstance(getApplication(), name, null); otherJRobins.put(name, jrobin); } return jrobin; } JRobin getJRobin(String graphName) { JRobin jrobin = counterJRobins.get(graphName); if (jrobin == null) { jrobin = otherJRobins.get(graphName); if (jrobin == null) { jrobin = requestJRobinsById.get(graphName); if (jrobin == null) { // un graph n'est pas toujours de suite dans jrobin return null; } } } return jrobin; } Collection<JRobin> getCounterJRobins() { return Collections.unmodifiableCollection(counterJRobins.values()); } Collection<JRobin> getOtherJRobins() { return Collections.unmodifiableCollection(otherJRobins.values()); } void clearCounter(String counterName) { final Counter counter = getCounterByName(counterName); if (counter != null) { final List<CounterRequest> requests = counter.getRequests(); counter.clear(); globalRequestsByCounter.remove(counter); for (final CounterRequest request : requests) { requestsById.remove(request.getId()); requestJRobinsById.remove(request.getId()); } } } void stop() { try { for (final Counter counter : counters) { counter.writeToFile(); } } catch (final IOException e) { LOG.warn("exception while writing counters data to files", e); } finally { for (final Counter counter : counters) { counter.clear(); } // et on ne fait pas de nettoyage des maps qui servent dans le cas } } static void stopJRobin() { if (Boolean.parseBoolean(System.getProperty(Parameters.PARAMETER_SYSTEM_PREFIX + "jrobinStopDisabled"))) { return; } try { JRobin.stop(); } catch (final Throwable t) { // NOPMD LOG.warn("stopping jrobin failed", t); } } static void detachVirtualMachine() { try { VirtualMachine.detach(); } catch (final Throwable t) { // NOPMD LOG.warn("exception while detaching virtual machine", t); } } /** {@inheritDoc} */ @Override public String toString() { return getClass().getSimpleName() + "[application=" + getApplication() + ", periodMillis=" + periodMillis + ", counters=" + getCounters() + ']'; } }
package com.firebase.geofire.core; import com.firebase.geofire.GeoLocation; import com.firebase.geofire.util.Base32Utils; import com.firebase.geofire.util.Constants; import com.firebase.geofire.util.GeoUtils; import java.util.HashSet; import java.util.Set; public class GeoHashQuery { public static final class Utils { private Utils() { throw new AssertionError("No instances."); } public static double bitsLatitude(double resolution) { return Math.min(Math.log(Constants.EARTH_MERIDIONAL_CIRCUMFERENCE/2/resolution)/Math.log(2), GeoHash.MAX_PRECISION_BITS); } public static double bitsLongitude(double resolution, double latitude) { double degrees = GeoUtils.distanceToLongitudeDegrees(resolution, latitude); return (Math.abs(degrees) > 0) ? Math.max(1, Math.log(360/degrees)/Math.log(2)) : 1; } public static int bitsForBoundingBox(GeoLocation location, double size) { double latitudeDegreesDelta = GeoUtils.distanceToLatitudeDegrees(size); double latitudeNorth = Math.min(90, location.latitude + latitudeDegreesDelta); double latitudeSouth = Math.max(-90, location.latitude - latitudeDegreesDelta); int bitsLatitude = (int)Math.floor(Utils.bitsLatitude(size)) *2; int bitsLongitudeNorth = (int)Math.floor(Utils.bitsLongitude(size, latitudeNorth)) *2 - 1; int bitsLongitudeSouth = (int)Math.floor(Utils.bitsLongitude(size, latitudeSouth)) *2 - 1; return Math.min(bitsLatitude, Math.min(bitsLongitudeNorth, bitsLongitudeSouth)); } } private final String startValue; private final String endValue; public GeoHashQuery(String startValue, String endValue) { this.startValue = startValue; this.endValue = endValue; } public static GeoHashQuery queryForGeoHash(GeoHash geohash, int bits) { String hash = geohash.getGeoHashString(); int precision = (int)Math.ceil((double)bits/Base32Utils.BITS_PER_BASE32_CHAR); if (hash.length() < precision) { return new GeoHashQuery(hash, hash+"~"); } hash = hash.substring(0, precision); String base = hash.substring(0, hash.length() - 1); int lastValue = Base32Utils.base32CharToValue(hash.charAt(hash.length() - 1)); int significantBits = bits - (base.length() * Base32Utils.BITS_PER_BASE32_CHAR); int unusedBits = Base32Utils.BITS_PER_BASE32_CHAR - significantBits; // delete unused bits int startValue = (lastValue >> unusedBits) << unusedBits; int endValue = startValue + (1 << unusedBits); String startHash = base + Base32Utils.valueToBase32Char(startValue); String endHash; if (endValue > 31) { endHash = base + "~"; } else { endHash = base + Base32Utils.valueToBase32Char(endValue); } return new GeoHashQuery(startHash, endHash); } public static Set<GeoHashQuery> queriesAtLocation(GeoLocation location, double radius) { int queryBits = Math.max(1, Utils.bitsForBoundingBox(location, radius)); int geoHashPrecision = (int) Math.ceil((float)queryBits /Base32Utils.BITS_PER_BASE32_CHAR); double latitude = location.latitude; double longitude = location.longitude; double latitudeDegrees = radius/Constants.METERS_PER_DEGREE_LATITUDE; double latitudeNorth = Math.min(90, latitude + latitudeDegrees); double latitudeSouth = Math.max(-90, latitude - latitudeDegrees); double longitudeDeltaNorth = GeoUtils.distanceToLongitudeDegrees(radius, latitudeNorth); double longitudeDeltaSouth = GeoUtils.distanceToLongitudeDegrees(radius, latitudeSouth); double longitudeDelta = Math.max(longitudeDeltaNorth, longitudeDeltaSouth); Set<GeoHashQuery> queries = new HashSet<GeoHashQuery>(); GeoHash geoHash = new GeoHash(latitude, longitude, geoHashPrecision); GeoHash geoHashW = new GeoHash(latitude, GeoUtils.wrapLongitude(longitude - longitudeDelta), geoHashPrecision); GeoHash geoHashE = new GeoHash(latitude, GeoUtils.wrapLongitude(longitude + longitudeDelta), geoHashPrecision); GeoHash geoHashN = new GeoHash(latitudeNorth, longitude, geoHashPrecision); GeoHash geoHashNW = new GeoHash(latitudeNorth, GeoUtils.wrapLongitude(longitude - longitudeDelta), geoHashPrecision); GeoHash geoHashNE = new GeoHash(latitudeNorth, GeoUtils.wrapLongitude(longitude + longitudeDelta), geoHashPrecision); GeoHash geoHashS = new GeoHash(latitudeSouth, longitude, geoHashPrecision); GeoHash geoHashSW = new GeoHash(latitudeSouth, GeoUtils.wrapLongitude(longitude - longitudeDelta), geoHashPrecision); GeoHash geoHashSE = new GeoHash(latitudeSouth, GeoUtils.wrapLongitude(longitude + longitudeDelta), geoHashPrecision); queries.add(queryForGeoHash(geoHash, queryBits)); queries.add(queryForGeoHash(geoHashE, queryBits)); queries.add(queryForGeoHash(geoHashW, queryBits)); queries.add(queryForGeoHash(geoHashN, queryBits)); queries.add(queryForGeoHash(geoHashNE, queryBits)); queries.add(queryForGeoHash(geoHashNW, queryBits)); queries.add(queryForGeoHash(geoHashS, queryBits)); queries.add(queryForGeoHash(geoHashSE, queryBits)); queries.add(queryForGeoHash(geoHashSW, queryBits)); // Join queries boolean didJoin; do { GeoHashQuery query1 = null; GeoHashQuery query2 = null; for (GeoHashQuery query: queries) { for (GeoHashQuery other: queries) { if (query != other && query.canJoinWith(other)) { query1 = query; query2 = other; break; } } } if (query1 != null && query2 != null) { queries.remove(query1); queries.remove(query2); queries.add(query1.joinWith(query2)); didJoin = true; } else { didJoin = false; } } while (didJoin); return queries; } private boolean isPrefix(GeoHashQuery other) { return (other.endValue.compareTo(this.startValue) >= 0) && (other.startValue.compareTo(this.startValue) < 0) && (other.endValue.compareTo(this.endValue) < 0); } private boolean isSuperQuery(GeoHashQuery other) { int startCompare = other.startValue.compareTo(this.startValue); return startCompare <= 0 && other.endValue.compareTo(this.endValue) >= 0; } public boolean canJoinWith(GeoHashQuery other) { return this.isPrefix(other) || other.isPrefix(this) || this.isSuperQuery(other) || other.isSuperQuery(this); } public GeoHashQuery joinWith(GeoHashQuery other) { if (other.isPrefix(this)) { return new GeoHashQuery(this.startValue, other.endValue); } else if (this.isPrefix(other)) { return new GeoHashQuery(other.startValue, this.endValue); } else if (this.isSuperQuery(other)) { return other; } else if (other.isSuperQuery(this)) { return this; } else { throw new IllegalArgumentException("Can't join these 2 queries: " + this + ", " + other); } } public boolean containsGeoHash(GeoHash hash) { String hashStr = hash.getGeoHashString(); return this.startValue.compareTo(hashStr) <= 0 && this.endValue.compareTo(hashStr) > 0; } public String getStartValue() { return this.startValue; } public String getEndValue() { return this.endValue; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GeoHashQuery that = (GeoHashQuery) o; if (!endValue.equals(that.endValue)) return false; if (!startValue.equals(that.startValue)) return false; return true; } @Override public int hashCode() { int result = startValue.hashCode(); result = 31 * result + endValue.hashCode(); return result; } @Override public String toString() { return "GeoHashQuery{" + "startValue='" + startValue + '\'' + ", endValue='" + endValue + '\'' + '}'; } }
package com.b2international.snowowl.snomed.api.impl.validation.domain; import java.util.HashMap; import java.util.Map; import com.b2international.snowowl.snomed.api.domain.browser.ISnomedBrowserDescription; import com.b2international.snowowl.snomed.api.domain.browser.SnomedBrowserDescriptionType; import com.b2international.snowowl.snomed.core.domain.Acceptability; /** * Wrapper for the ISnomedBrowserDescription class */ public class ValidationDescription implements org.ihtsdo.drools.domain.Description { private ISnomedBrowserDescription browserDesciption; private String conceptId; public ValidationDescription(ISnomedBrowserDescription browserDesciption, String conceptId) { this.browserDesciption = browserDesciption; this.conceptId = conceptId; } @Override public String getId() { return browserDesciption.getDescriptionId(); } @Override public boolean isActive() { return browserDesciption.isActive(); } @Override public boolean isPublished() { return browserDesciption.getEffectiveTime() != null; } @Override public String getModuleId() { return browserDesciption.getModuleId(); } @Override public String getLanguageCode() { return browserDesciption.getLang(); } @Override public String getConceptId() { return conceptId; } @Override public String getTypeId() { return browserDesciption.getType().getConceptId(); } @Override public String getCaseSignificanceId() { return browserDesciption.getCaseSignificance().getConceptId(); } @Override public String getTerm() { return browserDesciption.getTerm(); } @Override public boolean isTextDefinition() { return browserDesciption.getType() == SnomedBrowserDescriptionType.TEXT_DEFINITION; } @Override public Map<String, String> getAcceptabilityMap() { Map<String, String> langRefsetIdToAcceptabliltyIdMap = new HashMap<>(); Map<String, Acceptability> acceptabilityMap = browserDesciption.getAcceptabilityMap(); if (acceptabilityMap != null) { for (String langRefsetId : acceptabilityMap.keySet()) { langRefsetIdToAcceptabliltyIdMap.put(langRefsetId, acceptabilityMap.get(langRefsetId).getConceptId()); } } return langRefsetIdToAcceptabliltyIdMap; } }
package com.github.davidmoten.rx.jdbc; import static org.junit.Assert.assertEquals; import java.sql.SQLException; import org.junit.Test; import rx.Observable; import rx.functions.Action1; import rx.observers.TestSubscriber; import com.github.davidmoten.rx.jdbc.annotations.Column; public class DatabaseExampleTest { @Test public void testCreateAndUseAnInMemoryDatabase() throws SQLException { // create an h2 in-memory database that does not get dropped when all // connections closed Database db = Database.from("jdbc:h2:mem:demo1;DB_CLOSE_DELAY=-1"); db.update( "create table person (name varchar(50) primary key, score int not null,dob date, registered timestamp)") .count().toBlocking().single(); assertEquals( 2, db.update("insert into person(name,score) values(?,?)") .parameters("FRED", 21, "JOE", 34).execute()); // use java 8 lambdas if you have them ! db.select("select name, score from person").autoMap(Person.class) .forEach(new Action1<Person>() { @Override public void call(Person person) { System.out.println(person.name() + " has score " + person.score()); } }); db.close(); } static interface Person { @Column String name(); @Column int score(); } @Test public void testParameterOperatorBackpressure() { // use composition to find the first person alphabetically with // a score less than the person with the last name alphabetically // whose name is not XAVIER. Two threads and connections will be used. Database db = DatabaseCreator.db(); TestSubscriber<String> ts = TestSubscriber.create(0); Observable.just("FRED", "FRED").repeat() .lift(db.select("select name from person where name = ?") .parameterOperator().getAs(String.class)) .subscribe(ts); ts.requestMore(1); ts.assertValueCount(1); ts.unsubscribe(); } }
package com.github.anba.es6draft.parser; import static com.github.anba.es6draft.semantics.StaticSemantics.*; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.github.anba.es6draft.ast.AbruptNode.Abrupt; import com.github.anba.es6draft.ast.*; import com.github.anba.es6draft.ast.MethodDefinition.MethodType; import com.github.anba.es6draft.parser.ParserException.ExceptionType; import com.github.anba.es6draft.runtime.internal.CompatibilityOption; import com.github.anba.es6draft.runtime.internal.Messages; import com.github.anba.es6draft.runtime.internal.SmallArrayList; import com.github.anba.es6draft.runtime.objects.FunctionPrototype; /** * Parser for ECMAScript6 source code * <ul> * <li>12 ECMAScript Language: Expressions * <li>13 ECMAScript Language: Statements and Declarations * <li>14 ECMAScript Language: Functions and Classes * <li>15 ECMAScript Language: Scripts and Modules * </ul> */ public class Parser { private static final boolean MODULES_ENABLED = false; private static final boolean DEBUG = false; private static final int MAX_ARGUMENTS = FunctionPrototype.getMaxArguments(); private static final List<Binding> NO_INHERITED_BINDING = Collections.emptyList(); private static final Set<String> EMPTY_LABEL_SET = Collections.emptySet(); private final String sourceFile; private final int sourceLine; private final EnumSet<Option> options; private TokenStream ts; private ParseContext context; private enum StrictMode { Unknown, Strict, NonStrict } private enum StatementType { Iteration, Breakable, Statement } private enum ContextKind { Script, Module, Function, Generator, ArrowFunction, Method } private static class ParseContext { final ParseContext parent; final ContextKind kind; boolean superReference = false; boolean yieldAllowed = false; boolean returnAllowed = false; StrictMode strictMode = StrictMode.Unknown; boolean explicitStrict = false; ParserException strictError = null; List<FunctionNode> deferred = null; ArrayDeque<ObjectLiteral> objectLiterals = null; Map<String, LabelContext> labelSet = null; LabelContext labels = null; ScopeContext scopeContext; final FunctionContext funContext; ParseContext() { this.parent = null; this.kind = null; this.funContext = null; } ParseContext(ParseContext parent, ContextKind kind) { this.parent = parent; this.kind = kind; this.funContext = new FunctionContext(this); this.scopeContext = funContext; this.returnAllowed = isFunction(); if (parent.strictMode == StrictMode.Strict) { this.strictMode = parent.strictMode; } } ParseContext findSuperContext() { ParseContext cx = this; while (cx.kind == ContextKind.ArrowFunction) { cx = cx.parent; } return cx; } void setReferencesSuper() { superReference = true; } boolean hasSuperReference() { return superReference; } final boolean isFunction() { switch (kind) { case ArrowFunction: case Function: case Generator: case Method: return true; case Module: case Script: default: return false; } } int countLiterals() { return (objectLiterals != null ? objectLiterals.size() : 0); } void addLiteral(ObjectLiteral object) { if (objectLiterals == null) { objectLiterals = new ArrayDeque<>(4); } objectLiterals.push(object); } void removeLiteral(ObjectLiteral object) { objectLiterals.removeFirstOccurrence(object); } } // TODO: rename - not used exclusively for functions, also used for scripts and modules private static class FunctionContext extends ScopeContext implements FunctionScope { final ScopeContext enclosing; HashSet<String> parameterNames = null; boolean directEval = false; FunctionContext(ParseContext context) { super(null); this.enclosing = context.parent.scopeContext; } private boolean isStrict() { if (node instanceof FunctionNode) { return IsStrict((FunctionNode) node); } else { assert node instanceof Script; return IsStrict((Script) node); } } @Override public ScopeContext getEnclosingScope() { return enclosing; } @Override public boolean isDynamic() { return directEval && !isStrict(); } @Override public Set<String> parameterNames() { return parameterNames; } @Override public Set<String> lexicallyDeclaredNames() { return lexDeclaredNames; } @Override public List<Declaration> lexicallyScopedDeclarations() { return lexScopedDeclarations; } @Override public Set<String> varDeclaredNames() { return varDeclaredNames; } @Override public List<StatementListItem> varScopedDeclarations() { return varScopedDeclarations; } } private static class BlockContext extends ScopeContext implements BlockScope { final boolean dynamic; BlockContext(ScopeContext parent, boolean dynamic) { super(parent); this.dynamic = dynamic; } @Override public Set<String> lexicallyDeclaredNames() { return lexDeclaredNames; } @Override public List<Declaration> lexicallyScopedDeclarations() { return lexScopedDeclarations; } @Override public boolean isDynamic() { return dynamic; } } private abstract static class ScopeContext implements Scope { final ScopeContext parent; ScopedNode node = null; HashSet<String> varDeclaredNames = null; HashSet<String> lexDeclaredNames = null; List<StatementListItem> varScopedDeclarations = null; List<Declaration> lexScopedDeclarations = null; ScopeContext(ScopeContext parent) { this.parent = parent; } @Override public Scope getParent() { return parent; } @Override public ScopedNode getNode() { return node; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("var: ").append(varDeclaredNames != null ? varDeclaredNames : "<null>"); sb.append("\t"); sb.append("lex: ").append(lexDeclaredNames != null ? lexDeclaredNames : "<null>"); return sb.toString(); } boolean isTopLevel() { return (parent == null); } boolean addVarDeclaredName(String name) { if (varDeclaredNames == null) { varDeclaredNames = new HashSet<>(); } varDeclaredNames.add(name); return (lexDeclaredNames == null || !lexDeclaredNames.contains(name)); } boolean addLexDeclaredName(String name) { if (lexDeclaredNames == null) { lexDeclaredNames = new HashSet<>(); } return lexDeclaredNames.add(name) && (varDeclaredNames == null || !varDeclaredNames.contains(name)); } void addVarScopedDeclaration(StatementListItem decl) { if (varScopedDeclarations == null) { varScopedDeclarations = newSmallList(); } varScopedDeclarations.add(decl); } void addLexScopedDeclaration(Declaration decl) { if (lexScopedDeclarations == null) { lexScopedDeclarations = newSmallList(); } lexScopedDeclarations.add(decl); } } private static class LabelContext { final LabelContext parent; final StatementType type; final Set<String> labelSet; final EnumSet<Abrupt> abrupts = EnumSet.noneOf(Abrupt.class); LabelContext(LabelContext parent, StatementType type, Set<String> labelSet) { this.parent = parent; this.type = type; this.labelSet = labelSet; } void mark(Abrupt abrupt) { abrupts.add(abrupt); } } @SuppressWarnings("serial") private static class RetryGenerator extends RuntimeException { } public enum Option { Strict, FunctionCode, LocalScope, DirectEval, EvalScript, /** B.1.1 Numeric Literals */ LegacyOctalIntegerLiteral, /** B.1.2 String Literals */ OctalEscapeSequence, /** B.1.3 HTML-like Comments */ HTMLComments, /** Moz-Extension: for-each statement */ ForEachStatement, /** Moz-Extension: guarded catch */ GuardedCatch, /** Moz-Extension: expression closure */ ExpressionClosure, /** Moz-Extension: let statement */ LetStatement, /** Moz-Extension: let expression */ LetExpression, /** Moz-Extension: legacy (star-less) generators */ LegacyGenerator, /** Moz-Extension: legacy comprehension forms */ LegacyComprehension; public static EnumSet<Option> from(Set<CompatibilityOption> compatOptions) { EnumSet<Option> options = EnumSet.noneOf(Option.class); if (compatOptions.contains(CompatibilityOption.LegacyOctalIntegerLiteral)) { options.add(Option.LegacyOctalIntegerLiteral); } if (compatOptions.contains(CompatibilityOption.OctalEscapeSequence)) { options.add(Option.OctalEscapeSequence); } if (compatOptions.contains(CompatibilityOption.HTMLComments)) { options.add(Option.HTMLComments); } if (compatOptions.contains(CompatibilityOption.ForEachStatement)) { options.add(Option.ForEachStatement); } if (compatOptions.contains(CompatibilityOption.GuardedCatch)) { options.add(Option.GuardedCatch); } if (compatOptions.contains(CompatibilityOption.ExpressionClosure)) { options.add(Option.ExpressionClosure); } if (compatOptions.contains(CompatibilityOption.LetStatement)) { options.add(Option.LetStatement); } if (compatOptions.contains(CompatibilityOption.LetExpression)) { options.add(Option.LetExpression); } if (compatOptions.contains(CompatibilityOption.LegacyGenerator)) { options.add(Option.LegacyGenerator); } if (compatOptions.contains(CompatibilityOption.LegacyComprehension)) { options.add(Option.LegacyComprehension); } return options; } } public Parser(String sourceFile, int sourceLine, Set<Option> options) { this.sourceFile = sourceFile; this.sourceLine = sourceLine; this.options = EnumSet.copyOf(options); context = new ParseContext(); context.strictMode = this.options.contains(Option.Strict) ? StrictMode.Strict : StrictMode.NonStrict; } String getSourceFile() { return sourceFile; } int getSourceLine() { return sourceLine; } boolean isEnabled(Option option) { return options.contains(option); } private ParseContext newContext(ContextKind kind) { return context = new ParseContext(context, kind); } private ParseContext restoreContext() { if (context.parent.strictError == null) { context.parent.strictError = context.strictError; } return context = context.parent; } private BlockContext enterWithContext() { BlockContext cx = new BlockContext(context.scopeContext, true); context.scopeContext = cx; return cx; } private ScopeContext exitWithContext() { return exitScopeContext(); } private BlockContext enterBlockContext() { BlockContext cx = new BlockContext(context.scopeContext, false); context.scopeContext = cx; return cx; } private BlockContext reenterBlockContext(BlockContext cx) { context.scopeContext = cx; return cx; } private ScopeContext exitBlockContext() { return exitScopeContext(); } private ScopeContext exitScopeContext() { ScopeContext scope = context.scopeContext; ScopeContext parent = scope.parent; assert parent != null : "exitScopeContext() on top-level"; HashSet<String> varDeclaredNames = scope.varDeclaredNames; if (varDeclaredNames != null) { scope.varDeclaredNames = null; for (String name : varDeclaredNames) { addVarDeclaredName(parent, name); } } return context.scopeContext = parent; } private void addFunctionDeclaration(FunctionDeclaration decl) { String name = BoundName(decl.getIdentifier()); ScopeContext parentScope = context.parent.scopeContext; if (parentScope.isTopLevel()) { // top-level function declaration parentScope.addVarScopedDeclaration(decl); if (!parentScope.addVarDeclaredName(name)) { reportSyntaxError(decl, Messages.Key.VariableRedeclaration, name); } } else { // block-scoped function declaration parentScope.addLexScopedDeclaration(decl); if (!parentScope.addLexDeclaredName(name)) { reportSyntaxError(decl, Messages.Key.VariableRedeclaration, name); } } } private void addGeneratorDeclaration(GeneratorDeclaration decl) { String name = BoundName(decl.getIdentifier()); ScopeContext parentScope = context.parent.scopeContext; parentScope.addLexScopedDeclaration(decl); if (!parentScope.addLexDeclaredName(name)) { reportSyntaxError(decl, Messages.Key.VariableRedeclaration, name); } } private void addLexScopedDeclaration(Declaration decl) { context.scopeContext.addLexScopedDeclaration(decl); } private void addVarScopedDeclaration(VariableStatement decl) { context.funContext.addVarScopedDeclaration(decl); } private void addVarDeclaredName(ScopeContext scope, String name) { if (!scope.addVarDeclaredName(name)) { // FIXME: provide correct line/source information reportSyntaxError(Messages.Key.VariableRedeclaration, name); } } private void addVarDeclaredName(ScopeContext scope, Binding binding, String name) { if (!scope.addVarDeclaredName(name)) { reportSyntaxError(binding, Messages.Key.VariableRedeclaration, name); } } private void addLexDeclaredName(ScopeContext scope, Binding binding, String name) { if (!scope.addLexDeclaredName(name)) { reportSyntaxError(binding, Messages.Key.VariableRedeclaration, name); } } /** * <strong>[13.1] Block</strong> * <p> * Static Semantics: Early Errors<br> * <ul> * <li>It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also * occurs in the VarDeclaredNames of StatementList. * </ul> */ @SuppressWarnings("unused") private void addVarDeclaredName(Binding binding) { if (binding instanceof BindingIdentifier) { addVarDeclaredName((BindingIdentifier) binding); } else { assert binding instanceof BindingPattern; addVarDeclaredName((BindingPattern) binding); } } private void addVarDeclaredName(BindingIdentifier bindingIdentifier) { String name = BoundName(bindingIdentifier); addVarDeclaredName(context.scopeContext, bindingIdentifier, name); } private void addVarDeclaredName(BindingPattern bindingPattern) { for (String name : BoundNames(bindingPattern)) { addVarDeclaredName(context.scopeContext, bindingPattern, name); } } /** * <strong>[13.1] Block</strong> * <p> * Static Semantics: Early Errors<br> * <ul> * <li>It is a Syntax Error if the LexicallyDeclaredNames of StatementList contains any * duplicate entries. * <li>It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList also * occurs in the VarDeclaredNames of StatementList. * </ul> */ private void addLexDeclaredName(Binding binding) { if (binding instanceof BindingIdentifier) { addLexDeclaredName((BindingIdentifier) binding); } else { assert binding instanceof BindingPattern; addLexDeclaredName((BindingPattern) binding); } } private void addLexDeclaredName(BindingIdentifier bindingIdentifier) { String name = BoundName(bindingIdentifier); addLexDeclaredName(context.scopeContext, bindingIdentifier, name); } private void addLexDeclaredName(BindingPattern bindingPattern) { for (String name : BoundNames(bindingPattern)) { addLexDeclaredName(context.scopeContext, bindingPattern, name); } } private void addLexDeclaredNames(List<Binding> bindings) { for (Binding binding : bindings) { addLexDeclaredName(binding); } } private void removeLexDeclaredNames(List<Binding> bindings) { for (Binding binding : bindings) { removeLexDeclaredName(binding); } } private void removeLexDeclaredName(Binding binding) { HashSet<String> lexDeclaredNames = context.scopeContext.lexDeclaredNames; if (binding instanceof BindingIdentifier) { BindingIdentifier bindingIdentifier = (BindingIdentifier) binding; String name = BoundName(bindingIdentifier); lexDeclaredNames.remove(name); } else { assert binding instanceof BindingPattern; BindingPattern bindingPattern = (BindingPattern) binding; for (String name : BoundNames(bindingPattern)) { lexDeclaredNames.remove(name); } } } private LabelContext enterLabelled(long sourcePosition, StatementType type, Set<String> labelSet) { LabelContext cx = context.labels = new LabelContext(context.labels, type, labelSet); if (!labelSet.isEmpty() && context.labelSet == null) { context.labelSet = new HashMap<>(); } for (String label : labelSet) { if (context.labelSet.containsKey(label)) { reportSyntaxError(sourcePosition, Messages.Key.DuplicateLabel, label); } context.labelSet.put(label, cx); } return cx; } private LabelContext exitLabelled() { for (String label : context.labels.labelSet) { context.labelSet.remove(label); } return context.labels = context.labels.parent; } private LabelContext enterIteration(long sourcePosition, Set<String> labelSet) { return enterLabelled(sourcePosition, StatementType.Iteration, labelSet); } private void exitIteration() { exitLabelled(); } private LabelContext enterBreakable(long sourcePosition, Set<String> labelSet) { return enterLabelled(sourcePosition, StatementType.Breakable, labelSet); } private void exitBreakable() { exitLabelled(); } private LabelContext findContinueTarget(String label) { for (LabelContext cx = context.labels; cx != null; cx = cx.parent) { if (label == null ? cx.type == StatementType.Iteration : cx.labelSet.contains(label)) { return cx; } } return null; } private LabelContext findBreakTarget(String label) { for (LabelContext cx = context.labels; cx != null; cx = cx.parent) { if (label == null ? cx.type != StatementType.Statement : cx.labelSet.contains(label)) { return cx; } } return null; } private static <T> List<T> newSmallList() { return new SmallArrayList<>(); } private static <T> List<T> newList() { return new SmallArrayList<>(); } private static <T> List<T> merge(List<T> list1, List<T> list2) { if (!(list1.isEmpty() || list2.isEmpty())) { List<T> merged = new ArrayList<>(); merged.addAll(list1); merged.addAll(list2); return merged; } return list1.isEmpty() ? list2 : list1; } private static int toLine(long sourcePosition) { return (int) sourcePosition; } private static int toColumn(long sourcePosition) { return (int) (sourcePosition >>> 32); } private ParserException reportException(ParserException exception) { throw exception; } /** * Report mismatched token error from tokenstream's current position */ private ParserException reportTokenMismatch(Token expected, Token actual) { long sourcePosition = ts.sourcePosition(); int line = toLine(sourcePosition), col = toColumn(sourcePosition); if (actual == Token.EOF) { throw new ParserEOFException(sourceFile, line, col, Messages.Key.UnexpectedToken, actual.toString(), expected.toString()); } throw new ParserException(ExceptionType.SyntaxError, sourceFile, line, col, Messages.Key.UnexpectedToken, actual.toString(), expected.toString()); } /** * Report mismatched token error from tokenstream's current position */ private ParserException reportTokenMismatch(String expected, Token actual) { long sourcePosition = ts.sourcePosition(); int line = toLine(sourcePosition), col = toColumn(sourcePosition); if (actual == Token.EOF) { throw new ParserEOFException(sourceFile, line, col, Messages.Key.UnexpectedToken, actual.toString(), expected); } throw new ParserException(ExceptionType.SyntaxError, sourceFile, line, col, Messages.Key.UnexpectedToken, actual.toString(), expected); } /** * Report parser error with the given type and position */ private ParserException reportError(ExceptionType type, int line, int column, Messages.Key messageKey, String... args) { throw new ParserException(type, sourceFile, line, column, messageKey, args); } /** * Report syntax error from the given position */ private ParserException reportSyntaxError(long sourcePosition, Messages.Key messageKey, String... args) { int line = toLine(sourcePosition), col = toColumn(sourcePosition); throw reportError(ExceptionType.SyntaxError, line, col, messageKey, args); } /** * Report syntax error from the node's source-position */ private ParserException reportSyntaxError(Node node, Messages.Key messageKey, String... args) { throw reportSyntaxError(node.getSourcePosition(), messageKey, args); } /** * Report syntax error from tokenstream's current position */ private ParserException reportSyntaxError(Messages.Key messageKey, String... args) { throw reportSyntaxError(ts.sourcePosition(), messageKey, args); } /** * Report (or store) strict-mode parser error with the given type and position */ private void reportStrictModeError(ExceptionType type, int line, int column, Messages.Key messageKey, String... args) { if (context.strictMode == StrictMode.Unknown) { if (context.strictError == null) { context.strictError = new ParserException(type, sourceFile, line, column, messageKey, args); } } else if (context.strictMode == StrictMode.Strict) { reportError(type, line, column, messageKey, args); } } /** * Report (or store) strict-mode syntax error from the given position */ private void reportStrictModeSyntaxError(long sourcePosition, Messages.Key messageKey, String... args) { int line = toLine(sourcePosition), col = toColumn(sourcePosition); reportStrictModeError(ExceptionType.SyntaxError, line, col, messageKey, args); } /** * Report (or store) strict-mode syntax error from the node's source-position */ private void reportStrictModeSyntaxError(Node node, Messages.Key messageKey, String... args) { reportStrictModeSyntaxError(node.getSourcePosition(), messageKey, args); } /** * Report (or store) strict-mode syntax error from tokenstream's current position */ void reportStrictModeSyntaxError(Messages.Key messageKey, String... args) { reportStrictModeSyntaxError(ts.sourcePosition(), messageKey, args); } /** * Peeks the next token in the token-stream */ private Token peek() { return ts.peekToken(); } /** * Checks whether the next token in the token-stream is equal to the input token */ private boolean LOOKAHEAD(Token token) { return ts.peekToken() == token; } /** * Returns the current token in the token-stream */ private Token token() { return ts.currentToken(); } /** * Consumes the current token in the token-stream and advances the stream to the next token */ private void consume(Token tok) { if (tok != token()) reportTokenMismatch(tok, token()); Token next = ts.nextToken(); if (DEBUG) System.out.printf("consume(%s) -> %s\n", tok, next); } /** * Consumes the current token in the token-stream and advances the stream to the next token */ private void consume(String name) { long sourcePos = ts.sourcePosition(); String string = ts.getString(); consume(Token.NAME); if (!name.equals(string)) reportSyntaxError(sourcePos, Messages.Key.UnexpectedName, string, name); } public Script parseScript(CharSequence source) throws ParserException { if (ts != null) throw new IllegalStateException(); ts = new TokenStream(this, new StringTokenStreamInput(source)); return script(); } public ModuleDeclaration parseModule(CharSequence source) throws ParserException { if (ts != null) throw new IllegalStateException(); newContext(ContextKind.Script); try { applyStrictMode(true); // defaults to strict ModuleDeclaration module; newContext(ContextKind.Module); try { ts = new TokenStream(this, new StringTokenStreamInput(source)).initialise(); String moduleName = sourceFile; // only basename(sourceFile)? List<StatementListItem> body = moduleBody(Token.EOF); FunctionContext scope = context.funContext; module = new ModuleDeclaration(sourceLine, moduleName, body, scope); scope.node = module; } finally { restoreContext(); } createScript(module); return module; } finally { restoreContext(); } } public FunctionDefinition parseFunction(CharSequence formals, CharSequence bodyText) throws ParserException { if (ts != null) throw new IllegalStateException(); newContext(ContextKind.Script); try { applyStrictMode(false); FunctionExpression function; newContext(ContextKind.Function); try { ts = new TokenStream(this, new StringTokenStreamInput(formals)).initialise(); FormalParameterList parameters = formalParameters(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFormalParameterList); } if (ts.position() != formals.length()) { // more input after last token (whitespace, comments), add newlines to handle // last token is single-line comment case formals = "\n" + formals + "\n"; } ts = new TokenStream(this, new StringTokenStreamInput(bodyText)).initialise(); List<StatementListItem> statements = functionBody(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFunctionBody); } String header = String.format("function anonymous (%s) ", formals); String body = String.format("\n%s\n", bodyText); FunctionContext scope = context.funContext; function = new FunctionExpression(sourceLine, scope, "anonymous", parameters, statements, header, body); scope.node = function; function_StaticSemantics(function); function = inheritStrictness(function); } catch (RetryGenerator e) { // don't bother with legacy support here throw reportSyntaxError(Messages.Key.InvalidYieldStatement); } finally { restoreContext(); } createScript(new ExpressionStatement(function)); return function; } finally { restoreContext(); } } public GeneratorDefinition parseGenerator(CharSequence formals, CharSequence bodyText) throws ParserException { if (ts != null) throw new IllegalStateException(); newContext(ContextKind.Script); try { applyStrictMode(false); GeneratorExpression generator; newContext(ContextKind.Generator); try { ts = new TokenStream(this, new StringTokenStreamInput(formals)).initialise(); FormalParameterList parameters = formalParameters(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFormalParameterList); } if (ts.position() != formals.length()) { // more input after last token (whitespace, comments), add newlines to handle // last token is single-line comment case formals = "\n" + formals + "\n"; } ts = new TokenStream(this, new StringTokenStreamInput(bodyText)).initialise(); List<StatementListItem> statements = functionBody(Token.EOF); if (token() != Token.EOF) { reportSyntaxError(Messages.Key.InvalidFunctionBody); } String header = String.format("function* anonymous (%s) ", formals); String body = String.format("\n%s\n", bodyText); FunctionContext scope = context.funContext; generator = new GeneratorExpression(sourceLine, scope, "anonymous", parameters, statements, header, body); scope.node = generator; generator_StaticSemantics(generator); generator = inheritStrictness(generator); } finally { restoreContext(); } createScript(new ExpressionStatement(generator)); return generator; } finally { restoreContext(); } } private Script createScript(StatementListItem statement) { List<StatementListItem> statements = singletonList(statement); boolean strict = (context.strictMode == StrictMode.Strict); FunctionContext scope = context.funContext; Script script = new Script(sourceLine, sourceFile, scope, statements, options, strict); scope.node = script; return script; } /** * <strong>[15.1] Script</strong> * * <pre> * Script : * ScriptBody<sub>opt</sub> * ScriptBody : * OuterStatementList * </pre> */ private Script script() { newContext(ContextKind.Script); try { ts.initialise(); List<StatementListItem> prologue = directivePrologue(); List<StatementListItem> body = outerStatementList(); List<StatementListItem> statements = merge(prologue, body); boolean strict = (context.strictMode == StrictMode.Strict); FunctionContext scope = context.funContext; Script script = new Script(sourceLine, sourceFile, scope, statements, options, strict); scope.node = script; return script; } finally { restoreContext(); } } /** * <strong>[15.1] Script</strong> * * <pre> * OuterStatementList : * OuterItem * OuterStatementList OuterItem * OuterItem : * ModuleDeclaration * ImportDeclaration * StatementListItem * </pre> */ private List<StatementListItem> outerStatementList() { List<StatementListItem> list = newList(); while (token() != Token.EOF) { if (MODULES_ENABLED) { // TODO: implement modules if (token() == Token.IMPORT) { list.add(importDeclaration()); } else if (isName("module") && (peek() == Token.STRING || isIdentifier(peek())) && !ts.hasNextLineTerminator()) { list.add(moduleDeclaration()); } else { list.add(statementListItem()); } } else { list.add(statementListItem()); } } return list; } /** * <strong>[15.3] Modules</strong> * * <pre> * ModuleDeclaration ::= "module" [NoNewline] StringLiteral "{" ModuleBody "}" * | "module" Identifier "from" StringLiteral ";" * </pre> */ private ModuleDeclaration moduleDeclaration() { newContext(ContextKind.Module); try { long sourcePos = ts.sourcePosition(); consume("module"); if (token() == Token.STRING) { String moduleName = stringLiteral(); consume(Token.LC); List<StatementListItem> body = moduleBody(Token.RC); consume(Token.RC); FunctionContext scope = context.funContext; ModuleDeclaration module = new ModuleDeclaration(sourcePos, moduleName, body, scope); scope.node = module; return module; } else { String identifier = identifier(); consume("from"); String moduleName = stringLiteral(); semicolon(); FunctionContext scope = context.funContext; ModuleDeclaration module = new ModuleDeclaration(sourcePos, identifier, moduleName, scope); scope.node = module; return module; } } finally { restoreContext(); } } /** * <strong>[15.3] Modules</strong> * * <pre> * ModuleBody ::= ModuleElement* * ModuleElement ::= ScriptElement * | ExportDeclaration * </pre> */ private List<StatementListItem> moduleBody(Token end) { List<StatementListItem> list = newList(); while (token() != end) { // actually: ExportDeclaration | ImportDeclaration | StatementListItem // TODO: are nested modules (still) allowed? (disabled for now) if (token() == Token.EXPORT) { list.add(exportDeclaration()); } else if (token() == Token.IMPORT) { list.add(importDeclaration()); } else { list.add(statementListItem()); } } return list; } /** * <strong>[15.3] Modules</strong> * * <pre> * ExportDeclaration ::= "export" ExportSpecifierSet ";" * | "export" "default" AssignmentExpression ";" * | "export" VariableDeclaration * | "export" FunctionDeclaration * | "export" ClassDeclaration * </pre> */ private ExportDeclaration exportDeclaration() { long sourcePos = ts.sourcePosition(); consume(Token.EXPORT); switch (token()) { case LC: case MUL: { // "export" ExportSpecifierSet ";" ExportSpecifierSet exportSpecifierSet = exportSpecifierSet(); semicolon(); return new ExportDeclaration(sourcePos, exportSpecifierSet); } case DEFAULT: { // "export" "default" AssignmentExpression ";" consume(Token.DEFAULT); Expression expression = assignmentExpression(true); semicolon(); return new ExportDeclaration(sourcePos, expression); } case VAR: { // "export" VariableDeclaration VariableStatement variableStatement = variableStatement(); return new ExportDeclaration(sourcePos, variableStatement); } case FUNCTION: case CLASS: case LET: case CONST: { // "export" FunctionDeclaration // "export" ClassDeclaration Declaration declaration = declaration(); return new ExportDeclaration(sourcePos, declaration); } default: throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); } } /** * <strong>[15.3] Modules</strong> * * <pre> * ExportSpecifierSet ::= "{" (ExportSpecifier ("," ExportSpecifier)* ","?)? "}" * | "*" ("from" ModuleSpecifier)? * </pre> */ private ExportSpecifierSet exportSpecifierSet() { long sourcePos = ts.sourcePosition(); if (token() == Token.LC) { List<ExportSpecifier> exports = newSmallList(); consume(Token.LC); while (token() != Token.RC) { exports.add(exportSpecifier()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); // FIXME: re-export should also work with named exports String sourceModule = null; if (isName("from")) { consume("from"); sourceModule = moduleSpecifier(); } return new ExportSpecifierSet(sourcePos, exports, sourceModule); } else { consume(Token.MUL); String sourceModule = null; if (isName("from")) { consume("from"); sourceModule = moduleSpecifier(); } return new ExportSpecifierSet(sourcePos, sourceModule); } } /** * <strong>[15.3] Modules</strong> * * <pre> * ExportSpecifier ::= Identifier ("as" IdentifierName)? * </pre> */ private ExportSpecifier exportSpecifier() { long sourcePos = ts.sourcePosition(); String localName = identifier(); String externalName; if (isName("as")) { consume("as"); externalName = identifierName(); } else { externalName = localName; } return new ExportSpecifier(sourcePos, localName, externalName); } /** * <strong>[15.3] Modules</strong> * * <pre> * ModuleSpecifier ::= StringLiteral * </pre> */ private String moduleSpecifier() { return stringLiteral(); } /** * <strong>[15.3] Modules</strong> * * <pre> * ImportDeclaration ::= "import" ImportSpecifierSet "from" ModuleSpecifier ";" * | "import" ModuleSpecifier ";" * </pre> */ private ImportDeclaration importDeclaration() { long sourcePos = ts.sourcePosition(); consume(Token.IMPORT); if (token() == Token.STRING) { String moduleSpecifier = moduleSpecifier(); semicolon(); return new ImportDeclaration(sourcePos, moduleSpecifier); } else { ImportSpecifierSet importSpecifierSet = importSpecifierSet(); consume("from"); String moduleSpecifier = moduleSpecifier(); semicolon(); return new ImportDeclaration(sourcePos, importSpecifierSet, moduleSpecifier); } } /** * <strong>[15.3] Modules</strong> * * <pre> * ImportSpecifierSet ::= Identifier * | "{" (ImportSpecifier ("," ImportSpecifier)* ","?)? "}" * </pre> */ private ImportSpecifierSet importSpecifierSet() { long sourcePos = ts.sourcePosition(); if (isIdentifier(token())) { String defaultImport = identifier(); return new ImportSpecifierSet(sourcePos, defaultImport); } else { List<ImportSpecifier> imports = newSmallList(); consume(Token.LC); while (token() != Token.RC) { imports.add(importSpecifier()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); return new ImportSpecifierSet(sourcePos, imports); } } /** * <strong>[15.3] Modules</strong> * * <pre> * ImportSpecifier ::= Identifier ("as" Identifier)? * | ReservedWord "as" Identifier * </pre> */ private ImportSpecifier importSpecifier() { assert context.strictMode != StrictMode.Unknown : "undefined strict-mode in import specifier"; long sourcePos = ts.sourcePosition(); String externalName, localName; if (!isReservedWord(token())) { externalName = identifier(); if (isName("as")) { consume("as"); localName = identifier(); } else { localName = externalName; } } else { externalName = identifierName(); consume("as"); localName = identifier(); } return new ImportSpecifier(sourcePos, externalName, localName); } /** * <strong>[15.2] Directive Prologues and the Use Strict Directive</strong> * * <pre> * DirectivePrologue : * Directive<sub>opt</sub> * Directive: * StringLiteral ; * Directive StringLiteral ; * </pre> */ private List<StatementListItem> directivePrologue() { List<StatementListItem> statements = newSmallList(); boolean strict = false; directive: while (token() == Token.STRING) { long sourcePos = ts.sourcePosition(); boolean hasEscape = ts.hasEscape(); // peek() may clear hasEscape flag Token next = peek(); switch (next) { case SEMI: case RC: case EOF: break; default: if (ts.hasNextLineTerminator() && !isOperator(next)) { break; } break directive; } // got a directive String string = stringLiteral(); if (!hasEscape && "use strict".equals(string)) { strict = true; } semicolon(); statements.add(new ExpressionStatement(new StringLiteral(sourcePos, string))); } applyStrictMode(strict); return statements; } private static boolean isOperator(Token token) { switch (token) { case DOT: case LB: case LP: case TEMPLATE: case COMMA: case HOOK: case ASSIGN: case ASSIGN_ADD: case ASSIGN_BITAND: case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_MUL: case ASSIGN_SHL: case ASSIGN_SHR: case ASSIGN_SUB: case ASSIGN_USHR: case OR: case AND: case BITAND: case BITOR: case BITXOR: case EQ: case NE: case SHEQ: case SHNE: case LT: case LE: case GT: case GE: case INSTANCEOF: case IN: case SHL: case SHR: case USHR: case ADD: case SUB: case MUL: case DIV: case MOD: return true; default: return false; } } private void applyStrictMode(boolean strict) { if (strict) { context.strictMode = StrictMode.Strict; context.explicitStrict = true; if (context.strictError != null) { reportException(context.strictError); } } else { if (context.strictMode == StrictMode.Unknown) { context.strictMode = context.parent.strictMode; } } } private static FunctionNode.StrictMode toFunctionStrictness(boolean strict, boolean explicit) { if (strict) { if (explicit) { return FunctionNode.StrictMode.ExplicitStrict; } return FunctionNode.StrictMode.ImplicitStrict; } return FunctionNode.StrictMode.NonStrict; } private <FUNCTION extends FunctionNode> FUNCTION inheritStrictness(FUNCTION function) { if (context.strictMode != StrictMode.Unknown) { boolean strict = (context.strictMode == StrictMode.Strict); function.setStrictMode(toFunctionStrictness(strict, context.explicitStrict)); if (context.deferred != null) { for (FunctionNode func : context.deferred) { func.setStrictMode(toFunctionStrictness(strict, false)); } context.deferred = null; } } else { // this case only applies for functions with default parameters assert context.parent.strictMode == StrictMode.Unknown; ParseContext parent = context.parent; if (parent.deferred == null) { parent.deferred = newSmallList(); } parent.deferred.add(function); if (context.deferred != null) { parent.deferred.addAll(context.deferred); context.deferred = null; } } return function; } /** * Special case for {@link Token#YIELD} as {@link BindingIdentifier} in functions and generators */ private BindingIdentifier bindingIdentifierFunctionName() { // FIXME: Preliminary solution to provide SpiderMonkey/V8 compatibility // 'yield' is always a keyword in strict-mode and in generators, but parse function name // in the context of the surrounding environment if (token() == Token.YIELD) { long sourcePos = ts.sourcePosition(); if (isYieldName(context.parent)) { consume(Token.YIELD); return new BindingIdentifier(sourcePos, getName(Token.YIELD)); } reportStrictModeSyntaxError(sourcePos, Messages.Key.StrictModeInvalidIdentifier, getName(Token.YIELD)); reportTokenMismatch("<identifier>", Token.YIELD); } return bindingIdentifier(); } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FunctionDeclaration : * function BindingIdentifier ( FormalParameters ) { FunctionBody } * </pre> */ private FunctionDeclaration functionDeclaration() { newContext(ContextKind.Function); try { long sourcePos = ts.sourcePosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); BindingIdentifier identifier = bindingIdentifierFunctionName(); consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); String header, body; List<StatementListItem> statements; if (token() != Token.LC && isEnabled(Option.ExpressionClosure)) { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int startBody = ts.position(); statements = Collections.<StatementListItem> singletonList(new ReturnStatement(ts .sourcePosition(), assignmentExpression(true))); int endFunction = ts.position(); header = ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; FunctionDeclaration function = new FunctionDeclaration(sourcePos, scope, identifier, parameters, statements, header, body); scope.node = function; function_StaticSemantics(function); addFunctionDeclaration(function); return inheritStrictness(function); } finally { restoreContext(); } } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FunctionExpression : * function BindingIdentifier<sub>opt</sub> ( FormalParameters ) { FunctionBody } * </pre> */ private FunctionExpression functionExpression() { newContext(ContextKind.Function); try { long sourcePos = ts.sourcePosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); BindingIdentifier identifier = null; if (token() != Token.LP) { identifier = bindingIdentifierFunctionName(); } consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); String header, body; List<StatementListItem> statements; if (token() != Token.LC && isEnabled(Option.ExpressionClosure)) { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int startBody = ts.position(); statements = Collections.<StatementListItem> singletonList(new ReturnStatement(ts .sourcePosition(), assignmentExpression(true))); int endFunction = ts.position(); header = ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; FunctionExpression function = new FunctionExpression(sourcePos, scope, identifier, parameters, statements, header, body); scope.node = function; function_StaticSemantics(function); return inheritStrictness(function); } finally { restoreContext(); } } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * StrictFormalParameters : * FormalParameters * </pre> */ private FormalParameterList strictFormalParameters(Token end) { return formalParameters(end); } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FormalParameters : * [empty] * FormalParameterList * </pre> */ private FormalParameterList formalParameters(Token end) { if (token() == end) { long sourcePos = ts.sourcePosition(); return new FormalParameterList(sourcePos, Collections.<FormalParameter> emptyList()); } return formalParameterList(); } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FormalParameterList : * FunctionRestParameter * FormalsList * FormalsList, FunctionRestParameter * FormalsList : * FormalParameter * FormalsList, FormalParameter * FunctionRestParameter : * ... BindingIdentifier * FormalParameter : * BindingElement * </pre> */ private FormalParameterList formalParameterList() { long sourcePos = ts.sourcePosition(); List<FormalParameter> formals = newSmallList(); for (;;) { if (token() == Token.TRIPLE_DOT) { long sourcePosRest = ts.sourcePosition(); consume(Token.TRIPLE_DOT); formals.add(new BindingRestElement(sourcePosRest, bindingIdentifierStrict())); break; } else { formals.add(bindingElement()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } } return new FormalParameterList(sourcePos, formals); } private static <T> T containsAny(Set<T> set, List<T> list) { for (T element : list) { if (set.contains(element)) { return element; } } return null; } private void checkFormalParameterRedeclaration(FunctionNode node, List<String> boundNames, HashSet<String> declaredNames) { if (!(declaredNames == null || declaredNames.isEmpty())) { String redeclared = containsAny(declaredNames, boundNames); if (redeclared != null) { reportSyntaxError(node, Messages.Key.FormalParameterRedeclaration, redeclared); } } } private void function_StaticSemantics(FunctionDefinition function) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = function.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); boolean simple = IsSimpleParameterList(parameters); if (!simple) { checkFormalParameterRedeclaration(function, boundNames, scope.varDeclaredNames); } checkFormalParameterRedeclaration(function, boundNames, scope.lexDeclaredNames); formalParameters_StaticSemantics(function, boundNames, scope.parameterNames, simple); } private void strictFormalParameters_StaticSemantics(FunctionNode node, List<String> boundNames, Set<String> names) { boolean hasDuplicates = (boundNames.size() != names.size()); boolean hasEvalOrArguments = (names.contains("eval") || names.contains("arguments")); if (hasDuplicates) { reportSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } if (hasEvalOrArguments) { reportSyntaxError(node, Messages.Key.StrictModeRestrictedIdentifier); } } private void formalParameters_StaticSemantics(FunctionNode node, List<String> boundNames, Set<String> names, boolean simple) { boolean strict = (context.strictMode != StrictMode.NonStrict); if (!strict && simple) { return; } boolean hasDuplicates = (boundNames.size() != names.size()); boolean hasEvalOrArguments = (names.contains("eval") || names.contains("arguments")); if (!simple) { if (hasDuplicates) { reportSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } if (hasEvalOrArguments) { reportSyntaxError(node, Messages.Key.StrictModeRestrictedIdentifier); } } if (strict) { if (hasDuplicates) { reportStrictModeSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } if (hasEvalOrArguments) { reportStrictModeSyntaxError(node, Messages.Key.StrictModeRestrictedIdentifier); } } } /** * <strong>[14.1] Function Definitions</strong> * * <pre> * FunctionBody : * FunctionStatementList * FunctionStatementList : * StatementList<sub>opt</sub> * </pre> */ private List<StatementListItem> functionBody(Token end) { // enable 'yield' if in generator context.yieldAllowed = (context.kind == ContextKind.Generator); List<StatementListItem> prologue = directivePrologue(); List<StatementListItem> body = statementList(end); return merge(prologue, body); } /** * <strong>[14.2] Arrow Function Definitions</strong> * * <pre> * ArrowFunction : * ArrowParameters => ConciseBody * ArrowParameters : * BindingIdentifier * CoverParenthesisedExpressionAndArrowParameterList * ConciseBody : * [LA &#x2209; { <b>{</b> }] AssignmentExpression * { FunctionBody } * </pre> * * <h2>Supplemental Syntax</h2> * * <pre> * ArrowFormalParameters : * ( StrictFormalParameters ) * </pre> */ private ArrowFunction arrowFunction(boolean allowIn) { newContext(ContextKind.ArrowFunction); try { long sourcePos = ts.sourcePosition(); StringBuilder source = new StringBuilder(); source.append("function anonymous"); FormalParameterList parameters; if (token() == Token.LP) { consume(Token.LP); int start = ts.position() - 1; parameters = strictFormalParameters(Token.RP); consume(Token.RP); source.append(ts.range(start, ts.position())); } else { BindingIdentifier identifier = bindingIdentifierStrict(); FormalParameter parameter = new BindingElement(sourcePos, identifier, null); parameters = new FormalParameterList(sourcePos, singletonList(parameter)); source.append('(').append(identifier.getName()).append(')'); } consume(Token.ARROW); if (token() == Token.LC) { consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = source.toString(); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; ArrowFunction function = new ArrowFunction(sourcePos, scope, parameters, statements, header, body); scope.node = function; arrowFunction_StaticSemantics(function); return inheritStrictness(function); } else { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int startBody = ts.position(); Expression expression = assignmentExpression(allowIn); int endFunction = ts.position(); String header = source.toString(); String body = "return " + ts.range(startBody, endFunction); FunctionContext scope = context.funContext; ArrowFunction function = new ArrowFunction(sourcePos, scope, parameters, expression, header, body); scope.node = function; arrowFunction_StaticSemantics(function); return inheritStrictness(function); } } finally { restoreContext(); } } private void arrowFunction_StaticSemantics(ArrowFunction function) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = function.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); checkFormalParameterRedeclaration(function, boundNames, scope.varDeclaredNames); checkFormalParameterRedeclaration(function, boundNames, scope.lexDeclaredNames); strictFormalParameters_StaticSemantics(function, boundNames, scope.parameterNames); } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * PropertyName ( StrictFormalParameters ) { FunctionBody } * GeneratorMethod * get PropertyName ( ) { FunctionBody } * set PropertyName ( PropertySetParameterList ) { FunctionBody } * </pre> */ private MethodDefinition methodDefinition(boolean alwaysStrict) { switch (methodType()) { case Generator: return generatorMethod(alwaysStrict); case Getter: return getterMethod(alwaysStrict); case Setter: return setterMethod(alwaysStrict); case Function: default: return normalMethod(alwaysStrict); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * PropertyName ( StrictFormalParameters ) { FunctionBody } * </pre> */ private MethodDefinition normalMethod(boolean alwaysStrict) { long sourcePos = ts.sourcePosition(); PropertyName propertyName = propertyName(); return normalMethod(sourcePos, propertyName, alwaysStrict); } private MethodDefinition normalMethod(long sourcePos, PropertyName propertyName, boolean alwaysStrict) { newContext(ContextKind.Method); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = strictFormalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = "function " + ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; MethodType type = MethodType.Function; MethodDefinition method = new MethodDefinition(sourcePos, scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_StaticSemantics(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * get PropertyName ( ) { FunctionBody } * </pre> */ private MethodDefinition getterMethod(boolean alwaysStrict) { long sourcePos = ts.sourcePosition(); consume(Token.NAME); // "get" PropertyName propertyName = propertyName(); newContext(ContextKind.Method); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = new FormalParameterList(ts.sourcePosition(), Collections.<FormalParameter> emptyList()); consume(Token.RP); List<StatementListItem> statements; String header, body; if (token() != Token.LC && isEnabled(Option.ExpressionClosure)) { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int startBody = ts.position(); statements = Collections.<StatementListItem> singletonList(new ReturnStatement(ts .sourcePosition(), assignmentExpression(true))); int endFunction = ts.position(); header = "function " + ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = "function " + ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; MethodType type = MethodType.Getter; MethodDefinition method = new MethodDefinition(sourcePos, scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_StaticSemantics(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * MethodDefinition : * set PropertyName ( PropertySetParameterList ) { FunctionBody } * </pre> */ private MethodDefinition setterMethod(boolean alwaysStrict) { long sourcePos = ts.sourcePosition(); consume(Token.NAME); // "set" PropertyName propertyName = propertyName(); newContext(ContextKind.Method); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = propertySetParameterList(); consume(Token.RP); List<StatementListItem> statements; String header, body; if (token() != Token.LC && isEnabled(Option.ExpressionClosure)) { // need to call manually b/c functionBody() isn't used here applyStrictMode(false); int startBody = ts.position(); statements = Collections.<StatementListItem> singletonList(new ReturnStatement(ts .sourcePosition(), assignmentExpression(true))); int endFunction = ts.position(); header = "function " + ts.range(startFunction, startBody); body = "return " + ts.range(startBody, endFunction); } else { consume(Token.LC); int startBody = ts.position(); statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; header = "function " + ts.range(startFunction, startBody - 1); body = ts.range(startBody, endFunction); } FunctionContext scope = context.funContext; MethodType type = MethodType.Setter; MethodDefinition method = new MethodDefinition(sourcePos, scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_StaticSemantics(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.3] Method Definitions</strong> * * <pre> * PropertySetParameterList : * BindingIdentifier * BindingPattern * </pre> */ private FormalParameterList propertySetParameterList() { long sourcePos = ts.sourcePosition(); FormalParameter setParameter = new BindingElement(sourcePos, binding(), null); return new FormalParameterList(sourcePos, singletonList(setParameter)); } private MethodType methodType() { if (token() == Token.MUL) { return MethodType.Generator; } if (token() == Token.NAME) { String name = getName(Token.NAME); if (("get".equals(name) || "set".equals(name)) && isPropertyName(peek())) { return "get".equals(name) ? MethodType.Getter : MethodType.Setter; } } return MethodType.Function; } private boolean isPropertyName(Token token) { return token == Token.STRING || token == Token.NUMBER || token == Token.LB || isIdentifierName(token); } private void methodDefinition_StaticSemantics(MethodDefinition method) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = method.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); switch (method.getType()) { case Function: case Generator: { checkFormalParameterRedeclaration(method, boundNames, scope.varDeclaredNames); checkFormalParameterRedeclaration(method, boundNames, scope.lexDeclaredNames); strictFormalParameters_StaticSemantics(method, boundNames, scope.parameterNames); return; } case Setter: { boolean simple = IsSimpleParameterList(parameters); if (!simple) { checkFormalParameterRedeclaration(method, boundNames, scope.varDeclaredNames); } checkFormalParameterRedeclaration(method, boundNames, scope.lexDeclaredNames); propertySetParameterList_StaticSemantics(method, boundNames, scope.parameterNames, simple); return; } case Getter: default: return; } } private void propertySetParameterList_StaticSemantics(FunctionNode node, List<String> boundNames, Set<String> names, boolean simple) { boolean strict = (context.strictMode != StrictMode.NonStrict); boolean hasDuplicates = (boundNames.size() != names.size()); boolean hasEvalOrArguments = (names.contains("eval") || names.contains("arguments")); if (!simple) { if (hasDuplicates) { reportSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } if (hasEvalOrArguments) { reportSyntaxError(node, Messages.Key.StrictModeRestrictedIdentifier); } } // FIXME: spec bug - duplicate check done twice if (hasDuplicates) { reportSyntaxError(node, Messages.Key.StrictModeDuplicateFormalParameter); } // FIXME: spec bug - not handled in draft if (strict) { if (hasEvalOrArguments) { reportStrictModeSyntaxError(node, Messages.Key.StrictModeRestrictedIdentifier); } } } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * GeneratorMethod : * * PropertyName ( StrictFormalParameters ) { FunctionBody } * </pre> */ private MethodDefinition generatorMethod(boolean alwaysStrict) { long sourcePos = ts.sourcePosition(); consume(Token.MUL); PropertyName propertyName = propertyName(); newContext(ContextKind.Generator); if (alwaysStrict) { context.strictMode = StrictMode.Strict; } try { consume(Token.LP); int startFunction = ts.position() - 1; FormalParameterList parameters = strictFormalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = "function* " + ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; MethodType type = MethodType.Generator; MethodDefinition method = new MethodDefinition(sourcePos, scope, type, propertyName, parameters, statements, context.hasSuperReference(), header, body); scope.node = method; methodDefinition_StaticSemantics(method); return inheritStrictness(method); } finally { restoreContext(); } } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * GeneratorDeclaration : * function * BindingIdentifier ( FormalParameters ) { FunctionBody } * </pre> */ private GeneratorDeclaration generatorDeclaration(boolean starless) { newContext(ContextKind.Generator); try { long sourcePos = ts.sourcePosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); if (!starless) { consume(Token.MUL); } BindingIdentifier identifier = bindingIdentifierFunctionName(); consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; GeneratorDeclaration generator; if (!starless) { generator = new GeneratorDeclaration(sourcePos, scope, identifier, parameters, statements, header, body); } else { generator = new LegacyGeneratorDeclaration(sourcePos, scope, identifier, parameters, statements, header, body); } scope.node = generator; generator_StaticSemantics(generator); addGeneratorDeclaration(generator); return inheritStrictness(generator); } finally { restoreContext(); } } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * GeneratorExpression : * function * BindingIdentifier<sub>opt</sub> ( FormalParameters ) { FunctionBody } * </pre> */ private GeneratorExpression generatorExpression(boolean starless) { newContext(ContextKind.Generator); try { long sourcePos = ts.sourcePosition(); consume(Token.FUNCTION); int startFunction = ts.position() - "function".length(); if (!starless) { consume(Token.MUL); } BindingIdentifier identifier = null; if (token() != Token.LP) { identifier = bindingIdentifierFunctionName(); } consume(Token.LP); FormalParameterList parameters = formalParameters(Token.RP); consume(Token.RP); consume(Token.LC); int startBody = ts.position(); List<StatementListItem> statements = functionBody(Token.RC); consume(Token.RC); int endFunction = ts.position() - 1; String header = ts.range(startFunction, startBody - 1); String body = ts.range(startBody, endFunction); FunctionContext scope = context.funContext; GeneratorExpression generator; if (!starless) { generator = new GeneratorExpression(sourcePos, scope, identifier, parameters, statements, header, body); } else { generator = new LegacyGeneratorExpression(sourcePos, scope, identifier, parameters, statements, header, body); } scope.node = generator; generator_StaticSemantics(generator); return inheritStrictness(generator); } finally { restoreContext(); } } private void generator_StaticSemantics(GeneratorDefinition generator) { assert context.scopeContext == context.funContext; FunctionContext scope = context.funContext; FormalParameterList parameters = generator.getParameters(); List<String> boundNames = BoundNames(parameters); scope.parameterNames = new HashSet<>(boundNames); boolean simple = IsSimpleParameterList(parameters); if (!simple) { checkFormalParameterRedeclaration(generator, boundNames, scope.varDeclaredNames); } checkFormalParameterRedeclaration(generator, boundNames, scope.lexDeclaredNames); formalParameters_StaticSemantics(generator, boundNames, scope.parameterNames, simple); } /** * <strong>[14.4] Generator Function Definitions</strong> * * <pre> * YieldExpression : * yield YieldDelegator<sub>opt</sub> <font size="-1">[Lexical goal <i>InputElementRegExp</i>]</font> AssignmentExpression * YieldDelegator : * * * </pre> */ private YieldExpression yieldExpression(boolean allowIn) { if (!context.yieldAllowed) { if (context.kind == ContextKind.Function && isEnabled(Option.LegacyGenerator)) { throw new RetryGenerator(); } reportSyntaxError(Messages.Key.InvalidYieldStatement); } long sourcePos = ts.sourcePosition(); consume(Token.YIELD); boolean delegatedYield = false; if (token() == Token.MUL) { consume(Token.MUL); delegatedYield = true; } Expression expr; if (delegatedYield) { expr = assignmentExpression(allowIn); } else if (!isEnabled(Option.LegacyGenerator)) { if (noLineTerminator() && assignmentExpressionFirstSet(token())) { expr = assignmentExpression(allowIn); } else { expr = null; } } else { // slightly different rules for optional AssignmentExpression in legacy generators if (noLineTerminator() && !assignmentExpressionFollowSet(token())) { expr = assignmentExpression(allowIn); } else { expr = null; } } return new YieldExpression(sourcePos, delegatedYield, expr); } private boolean assignmentExpressionFirstSet(Token token) { // returns FIRST(AssignmentExpression) switch (token) { case YIELD: // FIRST(YieldExpression) return true; case DELETE: case VOID: case TYPEOF: case INC: case DEC: case ADD: case SUB: case BITNOT: case NOT: // FIRST(UnaryExpression) return true; case SUPER: case NEW: // FIRST(LeftHandSideExpression) return true; case THIS: case NULL: case FALSE: case TRUE: case NUMBER: case STRING: case LB: case LC: case LP: case FUNCTION: case CLASS: case TEMPLATE: // FIRST(PrimaryExpression) return true; case DIV: case ASSIGN_DIV: // FIRST(RegularExpressionLiteral) return true; case LET: return isEnabled(Option.LetExpression); case NAME: case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: // FIRST(Identifier) return isIdentifier(token); default: return false; } } private boolean assignmentExpressionFollowSet(Token token) { // returns FOLLOW(AssignmentExpression) without { "of", "in", "for", "{" } // NB: not the exact follow set, consider `a = let(x=0)x++ ++`, but not relevant here switch (token) { case COLON: case COMMA: case RB: case RC: case RP: case SEMI: case EOF: return true; default: return false; } } /** * <strong>[14.5] Class Definitions</strong> * * <pre> * ClassDeclaration : * class BindingIdentifier ClassTail * ClassTail : * ClassHeritage<sub>opt</sub> { ClassBody<sub>opt</sub> } * ClassHeritage : * extends AssignmentExpression * </pre> */ private ClassDeclaration classDeclaration() { long sourcePos = ts.sourcePosition(); consume(Token.CLASS); BindingIdentifier name = bindingIdentifierPureStrict(); Expression heritage = null; if (token() == Token.EXTENDS) { consume(Token.EXTENDS); heritage = assignmentExpression(true); } consume(Token.LC); List<MethodDefinition> staticMethods = newList(); List<MethodDefinition> prototypeMethods = newList(); classBody(name, staticMethods, prototypeMethods); consume(Token.RC); ClassDeclaration decl = new ClassDeclaration(sourcePos, name, heritage, staticMethods, prototypeMethods); addLexDeclaredName(name); addLexScopedDeclaration(decl); return decl; } /** * <strong>[14.5] Class Definitions</strong> * * <pre> * ClassExpression : * class BindingIdentifier<sub>opt</sub> ClassTail * ClassTail : * ClassHeritage<sub>opt</sub> { ClassBody<sub>opt</sub> } * ClassHeritage : * extends AssignmentExpression * </pre> */ private ClassExpression classExpression() { long sourcePos = ts.sourcePosition(); consume(Token.CLASS); BindingIdentifier name = null; if (token() != Token.EXTENDS && token() != Token.LC) { name = bindingIdentifierPureStrict(); } Expression heritage = null; if (token() == Token.EXTENDS) { consume(Token.EXTENDS); heritage = assignmentExpression(true); } consume(Token.LC); if (name != null) { enterBlockContext(); addLexDeclaredName(name); } List<MethodDefinition> staticMethods = newList(); List<MethodDefinition> prototypeMethods = newList(); classBody(name, staticMethods, prototypeMethods); if (name != null) { exitBlockContext(); } consume(Token.RC); return new ClassExpression(sourcePos, name, heritage, staticMethods, prototypeMethods); } /** * <strong>[14.5] Class Definitions</strong> * * <pre> * ClassBody : * ClassElementList * ClassElementList : * ClassElement * ClassElementList ClassElement * ClassElement : * MethodDefinition * static MethodDefinition * ; * </pre> */ private void classBody(BindingIdentifier className, List<MethodDefinition> staticMethods, List<MethodDefinition> prototypeMethods) { while (token() != Token.RC) { if (token() == Token.SEMI) { consume(Token.SEMI); } else if (token() == Token.STATIC && !LOOKAHEAD(Token.LP)) { consume(Token.STATIC); staticMethods.add(methodDefinition(true)); } else { prototypeMethods.add(methodDefinition(true)); } } classBody_StaticSemantics(className, staticMethods, true); classBody_StaticSemantics(className, prototypeMethods, false); } private void classBody_StaticSemantics(BindingIdentifier className, List<MethodDefinition> defs, boolean isStatic) { final int VALUE = 0, GETTER = 1, SETTER = 2; Map<String, Integer> values = new HashMap<>(); for (MethodDefinition def : defs) { String key = PropName(def); if (key == null) { assert def.getPropertyName() instanceof ComputedPropertyName; continue; } if (isStatic) { if ("prototype".equals(key)) { reportSyntaxError(def, Messages.Key.InvalidPrototypeMethod); } } else { if ("constructor".equals(key) && SpecialMethod(def)) { reportSyntaxError(def, Messages.Key.InvalidConstructorMethod); } if (className != null) { def.setFunctionName(className.getName()); } } MethodDefinition.MethodType type = def.getType(); final int kind = type == MethodType.Getter ? GETTER : type == MethodType.Setter ? SETTER : VALUE; if (values.containsKey(key)) { int prev = values.get(key); if (kind == VALUE) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == GETTER && prev != SETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == SETTER && prev != GETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } values.put(key, prev | kind); } else { values.put(key, kind); } } } /** * <strong>[13] ECMAScript Language: Statements and Declarations</strong> * * <pre> * Statement : * BlockStatement * VariableStatement * EmptyStatement * ExpressionStatement * IfStatement * BreakableStatement * ContinueStatement * BreakStatement * ReturnStatement * WithStatement * LabelledStatement * ThrowStatement * TryStatement * DebuggerStatement * * BreakableStatement : * IterationStatement * SwitchStatement * </pre> */ private Statement statement() { switch (token()) { case LC: return block(NO_INHERITED_BINDING); case VAR: return variableStatement(); case SEMI: return emptyStatement(); case IF: return ifStatement(); case FOR: return forStatement(EMPTY_LABEL_SET); case WHILE: return whileStatement(EMPTY_LABEL_SET); case DO: return doWhileStatement(EMPTY_LABEL_SET); case CONTINUE: return continueStatement(); case BREAK: return breakStatement(); case RETURN: return returnStatement(); case WITH: return withStatement(); case SWITCH: return switchStatement(EMPTY_LABEL_SET); case THROW: return throwStatement(); case TRY: return tryStatement(); case DEBUGGER: return debuggerStatement(); case LET: if (isEnabled(Option.LetStatement)) { return letStatement(); } break; case YIELD: if (!isYieldName()) { break; } // fall-through case NAME: if (LOOKAHEAD(Token.COLON)) { return labelledStatement(); } default: } return expressionStatement(); } /** * <strong>[13.1] Block</strong> * * <pre> * BlockStatement : * Block * Block : * { StatementList<sub>opt</sub> } * </pre> */ private BlockStatement block(List<Binding> inherited) { long sourcePos = ts.sourcePosition(); consume(Token.LC); BlockContext scope = enterBlockContext(); if (!inherited.isEmpty()) { addLexDeclaredNames(inherited); } List<StatementListItem> list = statementList(Token.RC); if (!inherited.isEmpty()) { removeLexDeclaredNames(inherited); } exitBlockContext(); consume(Token.RC); BlockStatement block = new BlockStatement(sourcePos, scope, list); scope.node = block; return block; } /** * <strong>[13.1] Block</strong> * * <pre> * StatementList : * StatementItem * StatementList StatementListItem * </pre> */ private List<StatementListItem> statementList(Token end) { List<StatementListItem> list = newList(); while (token() != end) { list.add(statementListItem()); } return list; } /** * <strong>[13.1] Block</strong> * * <pre> * StatementListItem : * Statement * Declaration * Declaration : * FunctionDeclaration * GeneratorDeclaration * ClassDeclaration * LexicalDeclaration * </pre> */ private StatementListItem statementListItem() { switch (token()) { case LET: if (LOOKAHEAD(Token.LP) && (isEnabled(Option.LetStatement) || isEnabled(Option.LetExpression))) { return statement(); } case FUNCTION: case CLASS: case CONST: return declaration(); default: return statement(); } } /** * <strong>[13.1] Block</strong> * * <pre> * Declaration : * FunctionDeclaration * GeneratorDeclaration * ClassDeclaration * LexicalDeclaration * </pre> */ private Declaration declaration() { switch (token()) { case FUNCTION: return functionOrGeneratorDeclaration(); case CLASS: return classDeclaration(); case LET: case CONST: return lexicalDeclaration(true); default: throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); } } private Declaration functionOrGeneratorDeclaration() { if (LOOKAHEAD(Token.MUL)) { return generatorDeclaration(false); } else { long position = ts.position(), lineinfo = ts.lineinfo(); try { return functionDeclaration(); } catch (RetryGenerator e) { ts.reset(position, lineinfo); return generatorDeclaration(true); } } } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * LexicalDeclaration : * LetOrConst BindingList ; * LexicalDeclarationNoIn : * LetOrConst BindingListNoIn * LetOrConst : * let * const * </pre> */ private LexicalDeclaration lexicalDeclaration(boolean allowIn) { long sourcePos = ts.sourcePosition(); LexicalDeclaration.Type type; if (token() == Token.LET) { consume(Token.LET); type = LexicalDeclaration.Type.Let; } else { consume(Token.CONST); type = LexicalDeclaration.Type.Const; } List<LexicalBinding> list = bindingList((type == LexicalDeclaration.Type.Const), allowIn); if (allowIn) { semicolon(); } LexicalDeclaration decl = new LexicalDeclaration(sourcePos, type, list); addLexScopedDeclaration(decl); return decl; } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * BindingList : * LexicalBinding * BindingList, LexicalBinding * BindingListNoIn : * LexicalBindingNoIn * BindingListNoIn, LexicalBindingNoIn * </pre> */ private List<LexicalBinding> bindingList(boolean isConst, boolean allowIn) { List<LexicalBinding> list = newSmallList(); list.add(lexicalBinding(isConst, allowIn)); while (token() == Token.COMMA) { consume(Token.COMMA); list.add(lexicalBinding(isConst, allowIn)); } return list; } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * LexicalBinding : * BindingIdentifier Initialiser<sub>opt</sub> * BindingPattern Initialiser * LexicalBindingNoIn : * BindingIdentifier InitialiserNoIn<sub>opt</sub> * BindingPattern InitialiserNoIn * </pre> */ private LexicalBinding lexicalBinding(boolean isConst, boolean allowIn) { long sourcePos = ts.sourcePosition(); Binding binding; Expression initialiser = null; if (token() == Token.LC || token() == Token.LB) { BindingPattern bindingPattern = bindingPattern(); addLexDeclaredName(bindingPattern); if (allowIn) { initialiser = initialiser(allowIn); } else if (token() == Token.ASSIGN) { // make initialiser optional if `allowIn == false` initialiser = initialiser(allowIn); } binding = bindingPattern; } else { BindingIdentifier bindingIdentifier = bindingIdentifier(); addLexDeclaredName(bindingIdentifier); if (token() == Token.ASSIGN) { initialiser = initialiser(allowIn); } else if (isConst && allowIn) { // `allowIn == false` indicates for-loop, cf. validateFor{InOf} reportSyntaxError(bindingIdentifier, Messages.Key.ConstMissingInitialiser); } binding = bindingIdentifier; } return new LexicalBinding(sourcePos, binding, initialiser); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * BindingIdentifier : * Identifier * </pre> */ private BindingIdentifier bindingIdentifier() { long sourcePos = ts.sourcePosition(); String identifier = identifier(); if (context.strictMode != StrictMode.NonStrict) { if ("arguments".equals(identifier) || "eval".equals(identifier)) { reportStrictModeSyntaxError(sourcePos, Messages.Key.StrictModeRestrictedIdentifier); } } return new BindingIdentifier(sourcePos, identifier); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * BindingIdentifier : * Identifier * </pre> */ private BindingIdentifier bindingIdentifierStrict() { long sourcePos = ts.sourcePosition(); String identifier = identifier(); if ("arguments".equals(identifier) || "eval".equals(identifier)) { reportSyntaxError(sourcePos, Messages.Key.StrictModeRestrictedIdentifier); } return new BindingIdentifier(sourcePos, identifier); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * BindingIdentifier : * Identifier * </pre> */ private BindingIdentifier bindingIdentifierPureStrict() { long sourcePos = ts.sourcePosition(); String identifier = strictIdentifier(); if ("arguments".equals(identifier) || "eval".equals(identifier)) { reportSyntaxError(sourcePos, Messages.Key.StrictModeRestrictedIdentifier); } return new BindingIdentifier(sourcePos, identifier); } /** * <strong>[13.2.1] Let and Const Declarations</strong> * * <pre> * Initialiser : * = AssignmentExpression * InitialiserNoIn : * = AssignmentExpressionNoIn * </pre> */ private Expression initialiser(boolean allowIn) { consume(Token.ASSIGN); return assignmentExpression(allowIn); } /** * <strong>[13.2.2] Variable Statement</strong> * * <pre> * VariableStatement : * var VariableDeclarationList ; * </pre> */ private VariableStatement variableStatement() { long sourcePos = ts.sourcePosition(); consume(Token.VAR); List<VariableDeclaration> decls = variableDeclarationList(true); semicolon(); VariableStatement varStmt = new VariableStatement(sourcePos, decls); addVarScopedDeclaration(varStmt); return varStmt; } /** * <strong>[13.2.2] Variable Statement</strong> * * <pre> * VariableDeclarationList : * VariableDeclaration * VariableDeclarationList , VariableDeclaration * VariableDeclarationListNoIn : * VariableDeclarationNoIn * VariableDeclarationListNoIn , VariableDeclarationNoIn * </pre> */ private List<VariableDeclaration> variableDeclarationList(boolean allowIn) { List<VariableDeclaration> list = newSmallList(); list.add(variableDeclaration(allowIn)); while (token() == Token.COMMA) { consume(Token.COMMA); list.add(variableDeclaration(allowIn)); } return list; } /** * <strong>[13.2.2] Variable Statement</strong> * * <pre> * VariableDeclaration : * BindingIdentifier Initialiser<sub>opt</sub> * BindingPattern Initialiser * VariableDeclarationNoIn : * BindingIdentifier InitialiserNoIn<sub>opt</sub> * BindingPattern InitialiserNoIn * </pre> */ private VariableDeclaration variableDeclaration(boolean allowIn) { Binding binding; Expression initialiser = null; if (token() == Token.LC || token() == Token.LB) { BindingPattern bindingPattern = bindingPattern(); addVarDeclaredName(bindingPattern); if (allowIn) { initialiser = initialiser(allowIn); } else if (token() == Token.ASSIGN) { // make initialiser optional if `allowIn == false` initialiser = initialiser(allowIn); } binding = bindingPattern; } else { BindingIdentifier bindingIdentifier = bindingIdentifier(); addVarDeclaredName(bindingIdentifier); if (token() == Token.ASSIGN) { initialiser = initialiser(allowIn); } binding = bindingIdentifier; } return new VariableDeclaration(binding, initialiser); } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingPattern : * ObjectBindingPattern * ArrayBindingPattern * </pre> */ private BindingPattern bindingPattern() { if (token() == Token.LC) { return objectBindingPattern(); } else { return arrayBindingPattern(); } } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * ObjectBindingPattern : * { } * { BindingPropertyList } * { BindingPropertyList , } * BindingPropertyList : * BindingProperty * BindingPropertyList , BindingProperty * BindingProperty : * SingleNameBinding * PropertyName : BindingElement * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * PropertyName : * IdentifierName * StringLiteral * NumericLiteral * </pre> */ private ObjectBindingPattern objectBindingPattern() { long sourcePos = ts.sourcePosition(); List<BindingProperty> list = newSmallList(); consume(Token.LC); while (token() != Token.RC) { list.add(bindingProperty()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); objectBindingPattern_StaticSemantics(list); return new ObjectBindingPattern(sourcePos, list); } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingProperty : * SingleNameBinding * PropertyName : BindingElement * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * BindingIdentifier : * Identifier * </pre> */ private BindingProperty bindingProperty() { if (token() == Token.LB || LOOKAHEAD(Token.COLON)) { PropertyName propertyName = propertyName(); consume(Token.COLON); Binding binding; if (token() == Token.LC) { binding = objectBindingPattern(); } else if (token() == Token.LB) { binding = arrayBindingPattern(); } else { binding = bindingIdentifierStrict(); } Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingProperty(propertyName, binding, initialiser); } else { BindingIdentifier binding = bindingIdentifierStrict(); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingProperty(binding, initialiser); } } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * ArrayBindingPattern : * [ Elision<sub>opt</sub> BindingRestElement<sub>opt</sub> ] * [ BindingElementList ] * [ BindingElementList , Elision<sub>opt</sub> BindingRestElement<sub>opt</sub> ] * BindingElementList : * Elision<sub>opt</sub> BindingElement * BindingElementList , Elision<sub>opt</sub> BindingElement * BindingRestElement : * ... BindingIdentifier * </pre> */ private ArrayBindingPattern arrayBindingPattern() { long sourcePos = ts.sourcePosition(); List<BindingElementItem> list = newSmallList(); consume(Token.LB); boolean needComma = false; Token tok; while ((tok = token()) != Token.RB) { if (needComma) { consume(Token.COMMA); needComma = false; } else if (tok == Token.COMMA) { consume(Token.COMMA); list.add(new BindingElision(0)); } else if (tok == Token.TRIPLE_DOT) { long sourcePosRest = ts.sourcePosition(); consume(Token.TRIPLE_DOT); list.add(new BindingRestElement(sourcePosRest, bindingIdentifierStrict())); break; } else { list.add(bindingElementStrict()); needComma = true; } } consume(Token.RB); arrayBindingPattern_StaticSemantics(list); return new ArrayBindingPattern(sourcePos, list); } /** * <pre> * Binding : * BindingIdentifier * BindingPattern * </pre> */ private Binding binding() { switch (token()) { case LC: return objectBindingPattern(); case LB: return arrayBindingPattern(); default: return bindingIdentifier(); } } /** * <pre> * Binding : * BindingIdentifier * BindingPattern * </pre> */ private Binding bindingStrict() { switch (token()) { case LC: return objectBindingPattern(); case LB: return arrayBindingPattern(); default: return bindingIdentifierStrict(); } } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * </pre> */ private BindingElement bindingElement() { long sourcePos = ts.sourcePosition(); Binding binding = binding(); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingElement(sourcePos, binding, initialiser); } /** * <strong>[13.2.4] Destructuring Binding Patterns</strong> * * <pre> * BindingElement : * SingleNameBinding * BindingPattern Initialiser<sub>opt</sub> * SingleNameBinding : * BindingIdentifier Initialiser<sub>opt</sub> * </pre> */ private BindingElement bindingElementStrict() { long sourcePos = ts.sourcePosition(); Binding binding = bindingStrict(); Expression initialiser = null; if (token() == Token.ASSIGN) { initialiser = initialiser(true); } return new BindingElement(sourcePos, binding, initialiser); } private static String BoundName(BindingIdentifier binding) { return binding.getName(); } private static String BoundName(BindingRestElement element) { return element.getBindingIdentifier().getName(); } private void objectBindingPattern_StaticSemantics(List<BindingProperty> list) { for (BindingProperty property : list) { // BindingProperty : PropertyName ':' BindingElement // BindingProperty : BindingIdentifier Initialiser<opt> Binding binding = property.getBinding(); if (binding instanceof BindingIdentifier) { String name = BoundName(((BindingIdentifier) binding)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(binding, Messages.Key.StrictModeRestrictedIdentifier); } } else { assert binding instanceof BindingPattern; assert property.getPropertyName() != null; // already done implicitly // objectBindingPattern_StaticSemantics(((ObjectBindingPattern) binding).getList()); // arrayBindingPattern_StaticSemantics(((ArrayBindingPattern) // binding).getElements()); } } } private void arrayBindingPattern_StaticSemantics(List<BindingElementItem> list) { for (BindingElementItem element : list) { if (element instanceof BindingElement) { Binding binding = ((BindingElement) element).getBinding(); if (binding instanceof ArrayBindingPattern) { // already done implicitly // arrayBindingPattern_StaticSemantics(((ArrayBindingPattern) binding) // .getElements()); } else if (binding instanceof ObjectBindingPattern) { // already done implicitly // objectBindingPattern_StaticSemantics(((ObjectBindingPattern) // binding).getList()); } else { assert (binding instanceof BindingIdentifier); String name = BoundName(((BindingIdentifier) binding)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(binding, Messages.Key.StrictModeRestrictedIdentifier); } } } else if (element instanceof BindingRestElement) { String name = BoundName(((BindingRestElement) element)); if ("arguments".equals(name) || "eval".equals(name)) { reportSyntaxError(element, Messages.Key.StrictModeRestrictedIdentifier); } } else { assert element instanceof BindingElision; } } } /** * <strong>[13.3] Empty Statement</strong> * * <pre> * EmptyStatement: * ; * </pre> */ private EmptyStatement emptyStatement() { consume(Token.SEMI); return new EmptyStatement(0); } /** * <strong>[13.4] Expression Statement</strong> * * <pre> * ExpressionStatement : * [LA &#x2209; { <b>{, function, class</b> }] Expression ; * </pre> */ private ExpressionStatement expressionStatement() { switch (token()) { case LC: case FUNCTION: case CLASS: reportSyntaxError(Messages.Key.InvalidToken, token().toString()); default: Expression expr = expression(true); semicolon(); return new ExpressionStatement(expr); } } /** * <strong>[13.5] The <code>if</code> Statement</strong> * * <pre> * IfStatement : * if ( Expression ) Statement else Statement * if ( Expression ) Statement * </pre> */ private IfStatement ifStatement() { long sourcePos = ts.sourcePosition(); consume(Token.IF); consume(Token.LP); Expression test = expression(true); consume(Token.RP); Statement then = statement(); Statement otherwise = null; if (token() == Token.ELSE) { consume(Token.ELSE); otherwise = statement(); } return new IfStatement(sourcePos, test, then, otherwise); } /** * <strong>[13.6.1] The <code>do-while</code> Statement</strong> * * <pre> * IterationStatement : * do Statement while ( Expression ) ;<sub>opt</sub> * </pre> */ private DoWhileStatement doWhileStatement(Set<String> labelSet) { long sourcePos = ts.sourcePosition(); consume(Token.DO); LabelContext labelCx = enterIteration(sourcePos, labelSet); Statement stmt = statement(); exitIteration(); consume(Token.WHILE); consume(Token.LP); Expression test = expression(true); consume(Token.RP); if (token() == Token.SEMI) { consume(Token.SEMI); } return new DoWhileStatement(sourcePos, labelCx.abrupts, labelCx.labelSet, test, stmt); } /** * <strong>[13.6.2] The <code>while</code> Statement</strong> * * <pre> * IterationStatement : * while ( Expression ) Statement * </pre> */ private WhileStatement whileStatement(Set<String> labelSet) { long sourcePos = ts.sourcePosition(); consume(Token.WHILE); consume(Token.LP); Expression test = expression(true); consume(Token.RP); LabelContext labelCx = enterIteration(sourcePos, labelSet); Statement stmt = statement(); exitIteration(); return new WhileStatement(sourcePos, labelCx.abrupts, labelCx.labelSet, test, stmt); } /** * <strong>[13.6.3] The <code>for</code> Statement</strong> <br> * <strong>[13.6.4] The <code>for-in</code> and <code>for-of</code> Statements</strong> * * <pre> * IterationStatement : * for ( ExpressionNoIn<sub>opt</sub> ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement * for ( var VariableDeclarationListNoIn ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement * for ( LexicalDeclarationNoIn ; Expression<sub>opt</sub> ; Expression <sub>opt</sub> ) Statement * for ( LeftHandSideExpression in Expression ) Statement * for ( var ForBinding in Expression ) Statement * for ( ForDeclaration in Expression ) Statement * for ( LeftHandSideExpression of Expression ) Statement * for ( var ForBinding of Expression ) Statement * for ( ForDeclaration of Expression ) Statement * ForDeclaration : * LetOrConst ForBinding * ForBinding : * BindingIdentifier * BindingPattern * </pre> */ private IterationStatement forStatement(Set<String> labelSet) { long sourcePos = ts.sourcePosition(); consume(Token.FOR); boolean each = false; if (token() != Token.LP && isName("each") && isEnabled(Option.ForEachStatement)) { consume("each"); each = true; } consume(Token.LP); BlockContext lexBlockContext = null; Node head; switch (token()) { case VAR: long sourcePosVar = ts.sourcePosition(); consume(Token.VAR); VariableStatement varStmt = new VariableStatement(sourcePosVar, variableDeclarationList(false)); addVarScopedDeclaration(varStmt); head = varStmt; break; case LET: case CONST: lexBlockContext = enterBlockContext(); head = lexicalDeclaration(false); break; case SEMI: head = null; break; default: head = expression(false); break; } if (each && token() != Token.IN) { reportTokenMismatch(Token.IN, token()); } if (token() == Token.SEMI) { head = validateFor(head); consume(Token.SEMI); Expression test = null; if (token() != Token.SEMI) { test = expression(true); } consume(Token.SEMI); Expression step = null; if (token() != Token.RP) { step = expression(true); } consume(Token.RP); LabelContext labelCx = enterIteration(sourcePos, labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } ForStatement iteration = new ForStatement(sourcePos, lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, test, step, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } else if (token() == Token.IN) { head = validateForInOf(head); consume(Token.IN); Expression expr; if (lexBlockContext == null) { expr = expression(true); } else { exitBlockContext(); expr = expression(true); reenterBlockContext(lexBlockContext); } consume(Token.RP); LabelContext labelCx = enterIteration(sourcePos, labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } if (each) { ForEachStatement iteration = new ForEachStatement(sourcePos, lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, expr, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } else { ForInStatement iteration = new ForInStatement(sourcePos, lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, expr, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } } else { head = validateForInOf(head); consume("of"); Expression expr; if (lexBlockContext == null) { expr = assignmentExpression(true); } else { exitBlockContext(); expr = assignmentExpression(true); reenterBlockContext(lexBlockContext); } consume(Token.RP); LabelContext labelCx = enterIteration(sourcePos, labelSet); Statement stmt = statement(); exitIteration(); if (lexBlockContext != null) { exitBlockContext(); } ForOfStatement iteration = new ForOfStatement(sourcePos, lexBlockContext, labelCx.abrupts, labelCx.labelSet, head, expr, stmt); if (lexBlockContext != null) { lexBlockContext.node = iteration; } return iteration; } } /** * @see #forStatement(Set) */ private Node validateFor(Node head) { if (head instanceof VariableStatement) { for (VariableDeclaration decl : ((VariableStatement) head).getElements()) { if (decl.getBinding() instanceof BindingPattern && decl.getInitialiser() == null) { reportSyntaxError(head, Messages.Key.DestructuringMissingInitialiser); } } } else if (head instanceof LexicalDeclaration) { boolean isConst = ((LexicalDeclaration) head).getType() == LexicalDeclaration.Type.Const; for (LexicalBinding decl : ((LexicalDeclaration) head).getElements()) { if (decl.getBinding() instanceof BindingPattern && decl.getInitialiser() == null) { reportSyntaxError(head, Messages.Key.DestructuringMissingInitialiser); } if (isConst && decl.getInitialiser() == null) { reportSyntaxError(head, Messages.Key.ConstMissingInitialiser); } } } return head; } /** * @see #forStatement(Set) */ private Node validateForInOf(Node head) { if (head instanceof VariableStatement) { // expected: single variable declaration with no initialiser List<VariableDeclaration> elements = ((VariableStatement) head).getElements(); if (elements.size() == 1 && elements.get(0).getInitialiser() == null) { return head; } } else if (head instanceof LexicalDeclaration) { // expected: single lexical binding with no initialiser List<LexicalBinding> elements = ((LexicalDeclaration) head).getElements(); if (elements.size() == 1 && elements.get(0).getInitialiser() == null) { return head; } } else if (head instanceof Expression) { // expected: left-hand side expression return validateAssignment((Expression) head, ExceptionType.SyntaxError, Messages.Key.InvalidAssignmentTarget); } throw reportSyntaxError(head, Messages.Key.InvalidForInOfHead); } /** * Static Semantics: IsValidSimpleAssignmentTarget */ private LeftHandSideExpression validateSimpleAssignment(Expression lhs, ExceptionType type, Messages.Key messageKey) { if (lhs instanceof Identifier) { if (context.strictMode != StrictMode.NonStrict) { String name = ((Identifier) lhs).getName(); if ("eval".equals(name) || "arguments".equals(name)) { reportStrictModeSyntaxError(lhs, Messages.Key.StrictModeInvalidAssignmentTarget); } } return (Identifier) lhs; } else if (lhs instanceof ElementAccessor) { return (ElementAccessor) lhs; } else if (lhs instanceof PropertyAccessor) { return (PropertyAccessor) lhs; } else if (lhs instanceof SuperExpression) { SuperExpression superExpr = (SuperExpression) lhs; if (superExpr.getExpression() != null || superExpr.getName() != null) { return superExpr; } } // everything else => invalid lhs throw reportError(type, lhs.getLine(), lhs.getColumn(), messageKey); } /** * Static Semantics: IsValidSimpleAssignmentTarget */ private LeftHandSideExpression validateAssignment(Expression lhs, ExceptionType type, Messages.Key messageKey) { // rewrite object/array literal to destructuring form if (lhs instanceof ObjectLiteral) { return toDestructuring((ObjectLiteral) lhs); } else if (lhs instanceof ArrayLiteral) { return toDestructuring((ArrayLiteral) lhs); } return validateSimpleAssignment(lhs, type, messageKey); } private ObjectAssignmentPattern toDestructuring(ObjectLiteral object) { List<AssignmentProperty> list = newSmallList(); for (PropertyDefinition p : object.getProperties()) { AssignmentProperty property; if (p instanceof PropertyValueDefinition) { // AssignmentProperty : PropertyName ':' AssignmentElement // AssignmentElement : DestructuringAssignmentTarget Initialiser{opt} // DestructuringAssignmentTarget : LeftHandSideExpression PropertyValueDefinition def = (PropertyValueDefinition) p; PropertyName propertyName = def.getPropertyName(); Expression propertyValue = def.getPropertyValue(); LeftHandSideExpression target; Expression initialiser; if (propertyValue instanceof AssignmentExpression) { AssignmentExpression assignment = (AssignmentExpression) propertyValue; if (assignment.getOperator() != AssignmentExpression.Operator.ASSIGN) { reportSyntaxError(p, Messages.Key.InvalidDestructuring); } target = destructuringAssignmentTarget(assignment.getLeft()); initialiser = assignment.getRight(); } else { target = destructuringAssignmentTarget(propertyValue); initialiser = null; } property = new AssignmentProperty(p.getSourcePosition(), propertyName, target, initialiser); } else if (p instanceof PropertyNameDefinition) { // AssignmentProperty : Identifier PropertyNameDefinition def = (PropertyNameDefinition) p; property = assignmentProperty(def.getPropertyName(), null); } else if (p instanceof CoverInitialisedName) { // AssignmentProperty : Identifier Initialiser CoverInitialisedName def = (CoverInitialisedName) p; property = assignmentProperty(def.getPropertyName(), def.getInitialiser()); } else { assert p instanceof MethodDefinition; throw reportSyntaxError(p, Messages.Key.InvalidDestructuring); } list.add(property); } context.removeLiteral(object); ObjectAssignmentPattern pattern = new ObjectAssignmentPattern(object.getSourcePosition(), list); if (object.isParenthesised()) { pattern.addParentheses(); } return pattern; } private ArrayAssignmentPattern toDestructuring(ArrayLiteral array) { List<AssignmentElementItem> list = newSmallList(); for (Expression e : array.getElements()) { AssignmentElementItem element; if (e instanceof Elision) { // Elision element = (Elision) e; } else if (e instanceof SpreadElement) { // AssignmentRestElement : ... DestructuringAssignmentTarget // DestructuringAssignmentTarget : LeftHandSideExpression Expression expression = ((SpreadElement) e).getExpression(); LeftHandSideExpression target = destructuringSimpleAssignmentTarget(expression); element = new AssignmentRestElement(e.getSourcePosition(), target); } else { // AssignmentElement : DestructuringAssignmentTarget Initialiser{opt} // DestructuringAssignmentTarget : LeftHandSideExpression LeftHandSideExpression target; Expression initialiser; if (e instanceof AssignmentExpression) { AssignmentExpression assignment = (AssignmentExpression) e; if (assignment.getOperator() != AssignmentExpression.Operator.ASSIGN) { reportSyntaxError(e, Messages.Key.InvalidDestructuring); } target = destructuringAssignmentTarget(assignment.getLeft()); initialiser = assignment.getRight(); } else { target = destructuringAssignmentTarget(e); initialiser = null; } element = new AssignmentElement(e.getSourcePosition(), target, initialiser); } list.add(element); } ArrayAssignmentPattern pattern = new ArrayAssignmentPattern(array.getSourcePosition(), list); if (array.isParenthesised()) { pattern.addParentheses(); } return pattern; } private LeftHandSideExpression destructuringAssignmentTarget(Expression lhs) { return destructuringAssignmentTarget(lhs, true); } private LeftHandSideExpression destructuringSimpleAssignmentTarget(Expression lhs) { return destructuringAssignmentTarget(lhs, false); } private LeftHandSideExpression destructuringAssignmentTarget(Expression lhs, boolean extended) { if (lhs instanceof Identifier) { String name = ((Identifier) lhs).getName(); if ("eval".equals(name) || "arguments".equals(name)) { reportSyntaxError(lhs, Messages.Key.InvalidAssignmentTarget); } return (Identifier) lhs; } else if (lhs instanceof ElementAccessor) { return (ElementAccessor) lhs; } else if (lhs instanceof PropertyAccessor) { return (PropertyAccessor) lhs; } else if (extended && lhs instanceof ObjectAssignmentPattern) { return (ObjectAssignmentPattern) lhs; } else if (extended && lhs instanceof ArrayAssignmentPattern) { return (ArrayAssignmentPattern) lhs; } else if (extended && lhs instanceof ObjectLiteral) { return toDestructuring((ObjectLiteral) lhs); } else if (extended && lhs instanceof ArrayLiteral) { return toDestructuring((ArrayLiteral) lhs); } else if (lhs instanceof SuperExpression) { SuperExpression superExpr = (SuperExpression) lhs; if (superExpr.getExpression() != null || superExpr.getName() != null) { return superExpr; } } // FIXME: spec bug (IsInvalidAssignmentPattern not defined) (Bug 716) // everything else => invalid lhs throw reportSyntaxError(lhs, Messages.Key.InvalidDestructuring); } private AssignmentProperty assignmentProperty(Identifier identifier, Expression initialiser) { switch (identifier.getName()) { case "eval": case "arguments": case "this": case "super": reportSyntaxError(identifier, Messages.Key.InvalidDestructuring); } return new AssignmentProperty(identifier.getSourcePosition(), identifier, initialiser); } /** * <strong>[13.7] The <code>continue</code> Statement</strong> * * <pre> * ContinueStatement : * continue ; * continue [no <i>LineTerminator</i> here] Identifier ; * </pre> */ private ContinueStatement continueStatement() { long sourcePos = ts.sourcePosition(); String label; consume(Token.CONTINUE); if (noLineTerminator() && isIdentifier(token())) { label = identifier(); } else { label = null; } semicolon(); LabelContext target = findContinueTarget(label); if (target == null) { if (label == null) { reportSyntaxError(sourcePos, Messages.Key.InvalidContinueTarget); } else { reportSyntaxError(sourcePos, Messages.Key.LabelTargetNotFound, label); } } if (target.type != StatementType.Iteration) { reportSyntaxError(sourcePos, Messages.Key.InvalidContinueTarget); } target.mark(Abrupt.Continue); return new ContinueStatement(sourcePos, label); } /** * <strong>[13.8] The <code>break</code> Statement</strong> * * <pre> * BreakStatement : * break ; * break [no <i>LineTerminator</i> here] Identifier ; * </pre> */ private BreakStatement breakStatement() { long sourcePos = ts.sourcePosition(); String label; consume(Token.BREAK); if (noLineTerminator() && isIdentifier(token())) { label = identifier(); } else { label = null; } semicolon(); LabelContext target = findBreakTarget(label); if (target == null) { if (label == null) { reportSyntaxError(sourcePos, Messages.Key.InvalidBreakTarget); } else { reportSyntaxError(sourcePos, Messages.Key.LabelTargetNotFound, label); } } target.mark(Abrupt.Break); return new BreakStatement(sourcePos, label); } /** * <strong>[13.9] The <code>return</code> Statement</strong> * * <pre> * ReturnStatement : * return ; * return [no <i>LineTerminator</i> here] Expression ; * </pre> */ private ReturnStatement returnStatement() { if (!context.returnAllowed) { reportSyntaxError(Messages.Key.InvalidReturnStatement); } long sourcePos = ts.sourcePosition(); Expression expr = null; consume(Token.RETURN); if (noLineTerminator() && !(token() == Token.SEMI || token() == Token.RC || token() == Token.EOF)) { expr = expression(true); } semicolon(); return new ReturnStatement(sourcePos, expr); } /** * <strong>[13.10] The <code>with</code> Statement</strong> * * <pre> * WithStatement : * with ( Expression ) Statement * </pre> */ private WithStatement withStatement() { long sourcePos = ts.sourcePosition(); reportStrictModeSyntaxError(sourcePos, Messages.Key.StrictModeWithStatement); consume(Token.WITH); consume(Token.LP); Expression expr = expression(true); consume(Token.RP); BlockContext scope = enterWithContext(); Statement stmt = statement(); exitWithContext(); WithStatement withStatement = new WithStatement(sourcePos, scope, expr, stmt); scope.node = withStatement; return withStatement; } /** * <strong>[13.11] The <code>switch</code> Statement</strong> * * <pre> * SwitchStatement : * switch ( Expression ) CaseBlock * CaseBlock : * { CaseClauses<sub>opt</sub> } * { CaseClauses<sub>opt</sub> DefaultClause CaseClauses<sub>opt</sub> } * CaseClauses : * CaseClause * CaseClauses CaseClause * CaseClause : * case Expression : StatementList<sub>opt</sub> * DefaultClause : * default : StatementList<sub>opt</sub> * </pre> */ private SwitchStatement switchStatement(Set<String> labelSet) { List<SwitchClause> clauses = newList(); long sourcePos = ts.sourcePosition(); consume(Token.SWITCH); consume(Token.LP); Expression expr = expression(true); consume(Token.RP); consume(Token.LC); LabelContext labelCx = enterBreakable(sourcePos, labelSet); BlockContext scope = enterBlockContext(); boolean hasDefault = false; for (;;) { long sourcePosClause = ts.sourcePosition(); Expression caseExpr; Token tok = token(); if (tok == Token.CASE) { consume(Token.CASE); caseExpr = expression(true); consume(Token.COLON); } else if (tok == Token.DEFAULT && !hasDefault) { hasDefault = true; consume(Token.DEFAULT); consume(Token.COLON); caseExpr = null; } else { break; } List<StatementListItem> list = newList(); statementlist: for (;;) { switch (token()) { case CASE: case DEFAULT: case RC: break statementlist; default: list.add(statementListItem()); } } clauses.add(new SwitchClause(sourcePosClause, caseExpr, list)); } exitBlockContext(); exitBreakable(); consume(Token.RC); SwitchStatement switchStatement = new SwitchStatement(sourcePos, scope, labelCx.abrupts, labelCx.labelSet, expr, clauses); scope.node = switchStatement; return switchStatement; } /** * <strong>[13.12] Labelled Statements</strong> * * <pre> * LabelledStatement : * Identifier : Statement * </pre> */ private Statement labelledStatement() { long sourcePos = ts.sourcePosition(); HashSet<String> labelSet = new HashSet<>(4); labels: for (;;) { switch (token()) { case FOR: return forStatement(labelSet); case WHILE: return whileStatement(labelSet); case DO: return doWhileStatement(labelSet); case SWITCH: return switchStatement(labelSet); case YIELD: if (!isYieldName()) { break labels; } // fall-through case NAME: if (LOOKAHEAD(Token.COLON)) { long sourcePosLabel = ts.sourcePosition(); String name = identifier(); consume(Token.COLON); if (!labelSet.add(name)) { reportSyntaxError(sourcePosLabel, Messages.Key.DuplicateLabel, name); } break; } case LC: case VAR: case SEMI: case IF: case CONTINUE: case BREAK: case RETURN: case WITH: case THROW: case TRY: case DEBUGGER: default: break labels; } } assert !labelSet.isEmpty(); LabelContext labelCx = enterLabelled(sourcePos, StatementType.Statement, labelSet); Statement stmt = statement(); exitLabelled(); return new LabelledStatement(sourcePos, labelCx.abrupts, labelCx.labelSet, stmt); } /** * <strong>[13.13] The <code>throw</code> Statement</strong> * * <pre> * ThrowStatement : * throw [no <i>LineTerminator</i> here] Expression ; * </pre> */ private ThrowStatement throwStatement() { long sourcePos = ts.sourcePosition(); consume(Token.THROW); if (!noLineTerminator()) { reportSyntaxError(Messages.Key.UnexpectedEndOfLine); } Expression expr = expression(true); semicolon(); return new ThrowStatement(sourcePos, expr); } /** * <strong>[13.14] The <code>try</code> Statement</strong> * * <pre> * TryStatement : * try Block Catch * try Block Finally * try Block Catch Finally * Catch : * catch ( CatchParameter ) Block * Finally : * finally Block * CatchParameter : * BindingIdentifier * BindingPattern * </pre> */ private TryStatement tryStatement() { BlockStatement tryBlock, finallyBlock = null; CatchNode catchNode = null; List<GuardedCatchNode> guardedCatchNodes = emptyList(); long sourcePos = ts.sourcePosition(); consume(Token.TRY); tryBlock = block(NO_INHERITED_BINDING); Token tok = token(); if (tok == Token.CATCH) { if (isEnabled(Option.GuardedCatch)) { guardedCatchNodes = newSmallList(); while (token() == Token.CATCH && catchNode == null) { long sourcePosCatch = ts.sourcePosition(); consume(Token.CATCH); BlockContext catchScope = enterBlockContext(); consume(Token.LP); Binding catchParameter = binding(); addLexDeclaredName(catchParameter); Expression guard; if (token() == Token.IF) { consume(Token.IF); guard = expression(true); } else { guard = null; } consume(Token.RP); // catch-block receives a blacklist of forbidden lexical declarable names BlockStatement catchBlock = block(singletonList(catchParameter)); exitBlockContext(); if (guard != null) { GuardedCatchNode guardedCatchNode = new GuardedCatchNode(sourcePosCatch, catchScope, catchParameter, guard, catchBlock); catchScope.node = guardedCatchNode; guardedCatchNodes.add(guardedCatchNode); } else { catchNode = new CatchNode(sourcePosCatch, catchScope, catchParameter, catchBlock); catchScope.node = catchNode; } } } else { long sourcePosCatch = ts.sourcePosition(); consume(Token.CATCH); BlockContext catchScope = enterBlockContext(); consume(Token.LP); Binding catchParameter = binding(); addLexDeclaredName(catchParameter); consume(Token.RP); // catch-block receives a blacklist of forbidden lexical declarable names BlockStatement catchBlock = block(singletonList(catchParameter)); exitBlockContext(); catchNode = new CatchNode(sourcePosCatch, catchScope, catchParameter, catchBlock); catchScope.node = catchNode; } if (token() == Token.FINALLY) { consume(Token.FINALLY); finallyBlock = block(NO_INHERITED_BINDING); } } else { consume(Token.FINALLY); finallyBlock = block(NO_INHERITED_BINDING); } return new TryStatement(sourcePos, tryBlock, catchNode, guardedCatchNodes, finallyBlock); } /** * <strong>[13.15] The <code>debugger</code> Statement</strong> * * <pre> * DebuggerStatement : * debugger ; * </pre> */ private DebuggerStatement debuggerStatement() { long sourcePos = ts.sourcePosition(); consume(Token.DEBUGGER); semicolon(); return new DebuggerStatement(sourcePos); } /** * <strong>[Extension] The <code>let</code> Statement</strong> * * <pre> * LetStatement : * let ( BindingList ) BlockStatement * </pre> */ private Statement letStatement() { BlockContext scope = enterBlockContext(); long sourcePos = ts.sourcePosition(); consume(Token.LET); consume(Token.LP); List<LexicalBinding> bindings = bindingList(false, true); consume(Token.RP); if (token() != Token.LC && isEnabled(Option.LetExpression)) { // let expression disguised as let statement - also error in strict mode(!) reportStrictModeSyntaxError(sourcePos, Messages.Key.UnexpectedToken, token().toString()); Expression expression = assignmentExpression(true); exitBlockContext(); LetExpression letExpression = new LetExpression(sourcePos, scope, bindings, expression); scope.node = letExpression; return new ExpressionStatement(letExpression); } else { BlockStatement letBlock = block(toBindings(bindings)); exitBlockContext(); LetStatement block = new LetStatement(sourcePos, scope, bindings, letBlock); scope.node = block; return block; } } private List<Binding> toBindings(List<LexicalBinding> lexicalBindings) { ArrayList<Binding> bindings = new ArrayList<>(lexicalBindings.size()); for (LexicalBinding lexicalBinding : lexicalBindings) { bindings.add(lexicalBinding.getBinding()); } return bindings; } /** * <strong>[12.1] Primary Expressions</strong> * * <pre> * PrimaryExpresion : * this * Identifier * Literal * ArrayInitialiser * ObjectLiteral * FunctionExpression * ClassExpression * GeneratorExpression * GeneratorComprehension * RegularExpressionLiteral * TemplateLiteral * CoverParenthesisedExpressionAndArrowParameterList * Literal : * NullLiteral * ValueLiteral * ValueLiteral : * BooleanLiteral * NumericLiteral * StringLiteral * </pre> */ private Expression primaryExpression() { long sourcePos = ts.sourcePosition(); Token tok = token(); switch (tok) { case THIS: consume(tok); return new ThisExpression(sourcePos); case NULL: consume(tok); return new NullLiteral(sourcePos); case FALSE: case TRUE: consume(tok); return new BooleanLiteral(sourcePos, tok == Token.TRUE); case NUMBER: return new NumericLiteral(sourcePos, numericLiteral()); case STRING: return new StringLiteral(sourcePos, stringLiteral()); case DIV: case ASSIGN_DIV: return regularExpressionLiteral(tok); case LB: return arrayInitialiser(); case LC: return objectLiteral(); case FUNCTION: return functionOrGeneratorExpression(); case CLASS: return classExpression(); case LP: if (LOOKAHEAD(Token.FOR)) { return generatorComprehension(); } else { return coverParenthesisedExpressionAndArrowParameterList(); } case TEMPLATE: return templateLiteral(false); case LET: if (isEnabled(Option.LetExpression)) { return letExpression(); } default: return new Identifier(sourcePos, identifier()); } } private Expression functionOrGeneratorExpression() { if (LOOKAHEAD(Token.MUL)) { return generatorExpression(false); } else { long position = ts.position(), lineinfo = ts.lineinfo(); try { return functionExpression(); } catch (RetryGenerator e) { ts.reset(position, lineinfo); return generatorExpression(true); } } } /** * <strong>[12.1] Primary Expressions</strong> * * <pre> * CoverParenthesisedExpressionAndArrowParameterList : * ( Expression ) * ( ) * ( ... Identifier ) * ( Expression , ... Identifier) * </pre> */ private Expression coverParenthesisedExpressionAndArrowParameterList() { long position = ts.position(), lineinfo = ts.lineinfo(); consume(Token.LP); Expression expr; if (token() == Token.RP) { expr = arrowFunctionEmptyParameters(); } else if (token() == Token.TRIPLE_DOT) { expr = arrowFunctionRestParameter(); } else { // inlined `expression(true)` expr = assignmentExpressionNoValidation(true); if (token() == Token.FOR && isEnabled(Option.LegacyComprehension)) { ts.reset(position, lineinfo); return legacyGeneratorComprehension(); } if (token() == Token.COMMA) { List<Expression> list = new ArrayList<>(); list.add(expr); while (token() == Token.COMMA) { consume(Token.COMMA); if (token() == Token.TRIPLE_DOT) { list.add(arrowFunctionRestParameter()); break; } expr = assignmentExpression(true); list.add(expr); } expr = new CommaExpression(list); } } expr.addParentheses(); consume(Token.RP); return expr; } private EmptyExpression arrowFunctionEmptyParameters() { if (!(token() == Token.RP && LOOKAHEAD(Token.ARROW))) { reportSyntaxError(Messages.Key.EmptyParenthesisedExpression); } return new EmptyExpression(0); } private SpreadElement arrowFunctionRestParameter() { long sourcePos = ts.sourcePosition(); consume(Token.TRIPLE_DOT); SpreadElement spread = new SpreadElement(sourcePos, new Identifier(ts.sourcePosition(), identifier())); if (!(token() == Token.RP && LOOKAHEAD(Token.ARROW))) { reportSyntaxError(spread, Messages.Key.InvalidSpreadExpression); } return spread; } /** * <strong>[12.1.4] Array Initialiser</strong> * * <pre> * ArrayInitialiser : * ArrayLiteral * ArrayComprehension * </pre> */ private ArrayInitialiser arrayInitialiser() { if (LOOKAHEAD(Token.FOR)) { return arrayComprehension(); } else { long sourcePos = ts.sourcePosition(); if (isEnabled(Option.LegacyComprehension)) { switch (peek()) { case RB: case COMMA: case TRIPLE_DOT: break; default: // TODO: report eclipse formatter bug long position = ts.position(), lineinfo = ts.lineinfo(); consume(Token.LB); Expression expression = assignmentExpressionNoValidation(true); if (token() == Token.FOR) { ts.reset(position, lineinfo); return legacyArrayComprehension(); } return arrayLiteral(sourcePos, expression); } } return arrayLiteral(sourcePos, null); } } /** * <strong>[12.1.4] Array Initialiser</strong> * * <pre> * ArrayLiteral : * [ Elision<sub>opt</sub> ] * [ ElementList ] * [ ElementList , Elision<sub>opt</sub> ] * ElementList : * Elision<sub>opt</sub> AssignmentExpression * Elision<sub>opt</sub> SpreadElement * ElementList , Elision<sub>opt</sub> AssignmentExpression * ElementList , Elision<sub>opt</sub> SpreadElement * Elision : * , * Elision , * SpreadElement : * ... AssignmentExpression * </pre> */ private ArrayLiteral arrayLiteral(long sourcePos, Expression expr) { List<Expression> list = newList(); boolean needComma = false; if (expr == null) { consume(Token.LB); } else { list.add(expr); needComma = true; } for (Token tok; (tok = token()) != Token.RB;) { if (needComma) { consume(Token.COMMA); needComma = false; } else if (tok == Token.COMMA) { consume(Token.COMMA); list.add(new Elision(0)); } else if (tok == Token.TRIPLE_DOT) { long sourcePosSpread = ts.sourcePosition(); consume(Token.TRIPLE_DOT); list.add(new SpreadElement(sourcePosSpread, assignmentExpression(true))); needComma = true; } else { list.add(assignmentExpressionNoValidation(true)); needComma = true; } } consume(Token.RB); return new ArrayLiteral(sourcePos, list); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * ArrayComprehension : * [ Comprehension ] * </pre> */ private ArrayComprehension arrayComprehension() { long sourcePos = ts.sourcePosition(); consume(Token.LB); Comprehension comprehension = comprehension(); consume(Token.RB); return new ArrayComprehension(sourcePos, comprehension); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * Comprehension : * ComprehensionFor ComprehensionTail * ComprehensionTail : * AssignmentExpression * ComprehensionFor ComprehensionTail * ComprehensionIf ComprehensionTail * </pre> */ private Comprehension comprehension() { assert token() == Token.FOR; List<ComprehensionQualifier> list = newSmallList(); int scopes = 0; for (;;) { ComprehensionQualifier qualifier; if (token() == Token.FOR) { scopes += 1; qualifier = comprehensionFor(); } else if (token() == Token.IF) { qualifier = comprehensionIf(); } else { break; } list.add(qualifier); } Expression expression = assignmentExpression(true); while (scopes exitBlockContext(); } return new Comprehension(list, expression); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * ComprehensionFor : * for ( ForBinding of AssignmentExpression ) * ForBinding : * BindingIdentifier * BindingPattern * </pre> */ private ComprehensionFor comprehensionFor() { long sourcePos = ts.sourcePosition(); consume(Token.FOR); consume(Token.LP); Binding b = binding(); consume("of"); Expression expression = assignmentExpression(true); consume(Token.RP); BlockContext scope = enterBlockContext(); addLexDeclaredName(b); return new ComprehensionFor(sourcePos, scope, b, expression); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * ComprehensionIf : * if ( AssignmentExpression ) * </pre> */ private ComprehensionIf comprehensionIf() { long sourcePos = ts.sourcePosition(); consume(Token.IF); consume(Token.LP); Expression expression = assignmentExpression(true); consume(Token.RP); return new ComprehensionIf(sourcePos, expression); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * LegacyArrayComprehension : * [ LegacyComprehension ] * </pre> */ private ArrayComprehension legacyArrayComprehension() { long sourcePos = ts.sourcePosition(); consume(Token.LB); LegacyComprehension comprehension = legacyComprehension(); consume(Token.RB); return new ArrayComprehension(sourcePos, comprehension); } /** * <strong>[12.1.4.2] Array Comprehension</strong> * * <pre> * LegacyComprehension : * AssignmentExpression LegacyComprehensionForList LegacyComprehensionIf<sub>opt</sub> * LegacyComprehensionForList : * LegacyComprehensionFor LegacyComprehensionForList<sub>opt</sub> * LegacyComprehensionFor : * for ( ForBinding of Expression ) * for ( ForBinding in Expression ) * for each ( ForBinding in Expression ) * LegacyComprehensionIf : * if ( Expression ) * </pre> */ private LegacyComprehension legacyComprehension() { BlockContext scope = enterBlockContext(); Expression expr = assignmentExpression(true); assert token() == Token.FOR : "empty legacy comprehension"; List<ComprehensionQualifier> list = newSmallList(); while (token() == Token.FOR) { long sourcePos = ts.sourcePosition(); consume(Token.FOR); boolean each = false; if (token() != Token.LP && isName("each")) { consume("each"); each = true; } consume(Token.LP); Binding b = binding(); addLexDeclaredName(b); LegacyComprehensionFor.IterationKind iterationKind; if (each) { consume(Token.IN); iterationKind = LegacyComprehensionFor.IterationKind.EnumerateValues; } else if (token() == Token.IN) { consume(Token.IN); iterationKind = LegacyComprehensionFor.IterationKind.Enumerate; } else { consume("of"); iterationKind = LegacyComprehensionFor.IterationKind.Iterate; } Expression expression = expression(true); consume(Token.RP); list.add(new LegacyComprehensionFor(sourcePos, iterationKind, b, expression)); } if (token() == Token.IF) { long sourcePos = ts.sourcePosition(); consume(Token.IF); consume(Token.LP); Expression expression = expression(true); consume(Token.RP); list.add(new ComprehensionIf(sourcePos, expression)); } exitBlockContext(); return new LegacyComprehension(scope, list, expr); } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * ObjectLiteral : * { } * { PropertyDefinitionList } * { PropertyDefinitionList , } * PropertyDefinitionList : * PropertyDefinition * PropertyDefinitionList , PropertyDefinition * </pre> */ private ObjectLiteral objectLiteral() { long sourcePos = ts.sourcePosition(); List<PropertyDefinition> defs = newList(); consume(Token.LC); while (token() != Token.RC) { defs.add(propertyDefinition()); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } consume(Token.RC); ObjectLiteral object = new ObjectLiteral(sourcePos, defs); context.addLiteral(object); return object; } private void objectLiteral_StaticSemantics(int oldCount) { ArrayDeque<ObjectLiteral> literals = context.objectLiterals; for (int i = oldCount, newCount = literals.size(); i < newCount; ++i) { objectLiteral_StaticSemantics(literals.pop()); } } private void objectLiteral_StaticSemantics(ObjectLiteral object) { final int VALUE = 0, GETTER = 1, SETTER = 2, SPECIAL = 4; Map<String, Integer> values = new HashMap<>(); for (PropertyDefinition def : object.getProperties()) { PropertyName propertyName = def.getPropertyName(); String key = propertyName.getName(); if (key == null) { assert propertyName instanceof ComputedPropertyName; continue; } final int kind; if (def instanceof PropertyValueDefinition) { kind = VALUE; } else if (def instanceof PropertyNameDefinition) { kind = SPECIAL; } else if (def instanceof MethodDefinition) { MethodDefinition method = (MethodDefinition) def; if (method.hasSuperReference()) { reportSyntaxError(def, Messages.Key.SuperOutsideClass); } MethodDefinition.MethodType type = method.getType(); kind = type == MethodType.Getter ? GETTER : type == MethodType.Setter ? SETTER : SPECIAL; } else { assert def instanceof CoverInitialisedName; // Always throw a Syntax Error if this production is present throw reportSyntaxError(def, Messages.Key.MissingColonAfterPropertyId, key); } // It is a Syntax Error if PropertyNameList of PropertyDefinitionList contains any // duplicate entries [...] if (values.containsKey(key)) { int prev = values.get(key); if (kind == VALUE && prev != VALUE) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == VALUE && prev == VALUE) { reportStrictModeSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == GETTER && prev != SETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == SETTER && prev != GETTER) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } if (kind == SPECIAL) { reportSyntaxError(def, Messages.Key.DuplicatePropertyDefinition, key); } values.put(key, prev | kind); } else { values.put(key, kind); } } } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * PropertyDefinition : * IdentifierName * CoverInitialisedName * PropertyName : AssignmentExpression * MethodDefinition * CoverInitialisedName : * IdentifierName Initialiser * </pre> */ private PropertyDefinition propertyDefinition() { long sourcePos = ts.sourcePosition(); if (token() == Token.LB) { // either `PropertyName : AssignmentExpression` or MethodDefinition (normal) PropertyName propertyName = computedPropertyName(); if (token() == Token.COLON) { // it's the `PropertyName : AssignmentExpression` case consume(Token.COLON); Expression propertyValue = assignmentExpressionNoValidation(true); return new PropertyValueDefinition(sourcePos, propertyName, propertyValue); } // otherwise it's MethodDefinition (normal) return normalMethod(sourcePos, propertyName, false); } if (LOOKAHEAD(Token.COLON)) { PropertyName propertyName = literalPropertyName(); consume(Token.COLON); Expression propertyValue = assignmentExpressionNoValidation(true); return new PropertyValueDefinition(sourcePos, propertyName, propertyValue); } if (LOOKAHEAD(Token.COMMA) || LOOKAHEAD(Token.RC)) { // Static Semantics: It is a Syntax Error if IdentifierName is a // ReservedWord. Identifier identifier = new Identifier(sourcePos, identifier()); return new PropertyNameDefinition(sourcePos, identifier); } if (LOOKAHEAD(Token.ASSIGN)) { Identifier identifier = new Identifier(sourcePos, identifier()); consume(Token.ASSIGN); Expression initialiser = assignmentExpression(true); return new CoverInitialisedName(sourcePos, identifier, initialiser); } return methodDefinition(false); } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * PropertyName : * LiteralPropertyName * ComputedPropertyName * </pre> */ private PropertyName propertyName() { if (token() != Token.LB) { return literalPropertyName(); } else { return computedPropertyName(); } } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * PropertyName : * IdentifierName * StringLiteral * NumericLiteral * </pre> */ private PropertyName literalPropertyName() { long sourcePos = ts.sourcePosition(); switch (token()) { case STRING: return new StringLiteral(sourcePos, stringLiteral()); case NUMBER: return new NumericLiteral(sourcePos, numericLiteral()); default: return new Identifier(sourcePos, identifierName()); } } /** * <strong>[12.1.5] Object Initialiser</strong> * * <pre> * ComputedPropertyName : * [ AssignmentExpression ] * </pre> */ private PropertyName computedPropertyName() { long sourcePos = ts.sourcePosition(); consume(Token.LB); Expression expression = assignmentExpression(true); consume(Token.RB); return new ComputedPropertyName(sourcePos, expression); } /** * <strong>[12.1.7] Generator Comprehensions</strong> * * <pre> * GeneratorComprehension : * ( Comprehension ) * </pre> */ private GeneratorComprehension generatorComprehension() { boolean yieldAllowed = context.yieldAllowed; try { context.yieldAllowed = false; long sourcePos = ts.sourcePosition(); consume(Token.LP); Comprehension comprehension = comprehension(); consume(Token.RP); return new GeneratorComprehension(sourcePos, comprehension); } finally { context.yieldAllowed = yieldAllowed; } } /** * <strong>[12.1.7] Generator Comprehensions</strong> * * <pre> * LegacyGeneratorComprehension : * ( LegacyComprehension ) * </pre> */ private GeneratorComprehension legacyGeneratorComprehension() { boolean yieldAllowed = context.yieldAllowed; try { context.yieldAllowed = false; long sourcePos = ts.sourcePosition(); consume(Token.LP); LegacyComprehension comprehension = legacyComprehension(); consume(Token.RP); return new GeneratorComprehension(sourcePos, comprehension); } finally { context.yieldAllowed = yieldAllowed; } } /** * <strong>[12.1.8] Regular Expression Literals</strong> * * <pre> * RegularExpressionLiteral :: * / RegularExpressionBody / RegularExpressionFlags * </pre> */ private Expression regularExpressionLiteral(Token tok) { long sourcePos = ts.sourcePosition(); String[] re = ts.readRegularExpression(tok); regularExpressionLiteral_StaticSemantics(sourcePos, re[0], re[1]); consume(tok); return new RegularExpressionLiteral(sourcePos, re[0], re[1]); } private void regularExpressionLiteral_StaticSemantics(long sourcePos, String p, String f) { // parse to validate regular expression, but ignore actual result RegExpParser.parse(p, f, sourceFile, toLine(sourcePos), toColumn(sourcePos)); } /** * <strong>[12.1.9] Template Literals</strong> * * <pre> * TemplateLiteral : * NoSubstitutionTemplate * TemplateHead Expression [Lexical goal <i>InputElementTemplateTail</i>] TemplateSpans * TemplateSpans : * TemplateTail * TemplateMiddleList [Lexical goal <i>InputElementTemplateTail</i>] TemplateTail * TemplateMiddleList : * TemplateMiddle Expression * TemplateMiddleList [Lexical goal <i>InputElementTemplateTail</i>] TemplateMiddle Expression * </pre> */ private TemplateLiteral templateLiteral(boolean tagged) { List<Expression> elements = newList(); long sourcePosition = ts.sourcePosition(); long sourcePos = sourcePosition; String[] values = ts.readTemplateLiteral(Token.TEMPLATE); elements.add(new TemplateCharacters(sourcePos, values[0], values[1])); while (token() == Token.LC) { consume(Token.LC); elements.add(expression(true)); sourcePos = ts.sourcePosition(); values = ts.readTemplateLiteral(Token.RC); elements.add(new TemplateCharacters(sourcePos, values[0], values[1])); } consume(Token.TEMPLATE); if ((elements.size() / 2) + 1 > MAX_ARGUMENTS) { reportSyntaxError(Messages.Key.FunctionTooManyArguments); } return new TemplateLiteral(sourcePosition, tagged, elements); } /** * <strong>[Extension] The <code>let</code> Expression</strong> * * <pre> * LetExpression : * let ( BindingList ) AssignmentExpression * </pre> */ private LetExpression letExpression() { BlockContext scope = enterBlockContext(); long sourcePos = ts.sourcePosition(); consume(Token.LET); consume(Token.LP); List<LexicalBinding> bindings = bindingList(false, true); consume(Token.RP); Expression expression = assignmentExpression(true); exitBlockContext(); LetExpression letExpression = new LetExpression(sourcePos, scope, bindings, expression); scope.node = letExpression; return letExpression; } /** * <strong>[12.2] Left-Hand-Side Expressions</strong> * * <pre> * MemberExpression : * PrimaryExpression * MemberExpression [ Expression ] * MemberExpression . IdentifierName * MemberExpression QuasiLiteral * super [ Expression ] * super . IdentifierName * new MemberExpression Arguments * NewExpression : * MemberExpression * new NewExpression * CallExpression : * MemberExpression Arguments * super Arguments * CallExpression Arguments * CallExpression [ Expression ] * CallExpression . IdentifierName * CallExpression QuasiLiteral * LeftHandSideExpression : * NewExpression * CallExpression * </pre> */ private Expression leftHandSideExpression(boolean allowCall) { long sourcePos = ts.sourcePosition(); Expression lhs; if (token() == Token.NEW) { consume(Token.NEW); Expression expr = leftHandSideExpression(false); List<Expression> args = null; if (token() == Token.LP) { args = arguments(); } else { args = emptyList(); } lhs = new NewExpression(sourcePos, expr, args); } else if (token() == Token.SUPER) { ParseContext cx = context.findSuperContext(); if (cx.kind == ContextKind.Script && !isEnabled(Option.FunctionCode) || cx.kind == ContextKind.Module) { reportSyntaxError(Messages.Key.InvalidSuperExpression); } cx.setReferencesSuper(); consume(Token.SUPER); switch (token()) { case DOT: consume(Token.DOT); String name = identifierName(); lhs = new SuperExpression(sourcePos, name); break; case LB: consume(Token.LB); Expression expr = expression(true); consume(Token.RB); lhs = new SuperExpression(sourcePos, expr); break; case LP: if (!allowCall) { lhs = new SuperExpression(sourcePos); } else { List<Expression> args = arguments(); lhs = new SuperExpression(sourcePos, args); } break; case TEMPLATE: // handle "new super``" case throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); default: if (!allowCall) { lhs = new SuperExpression(sourcePos); } else { throw reportSyntaxError(Messages.Key.InvalidToken, token().toString()); } break; } } else { lhs = primaryExpression(); } for (;;) { switch (token()) { case DOT: sourcePos = ts.sourcePosition(); consume(Token.DOT); String name = identifierName(); lhs = new PropertyAccessor(sourcePos, lhs, name); break; case LB: sourcePos = ts.sourcePosition(); consume(Token.LB); Expression expr = expression(true); consume(Token.RB); lhs = new ElementAccessor(sourcePos, lhs, expr); break; case LP: if (!allowCall) { return lhs; } if (lhs instanceof Identifier && "eval".equals(((Identifier) lhs).getName())) { context.funContext.directEval = true; } sourcePos = ts.sourcePosition(); List<Expression> args = arguments(); lhs = new CallExpression(sourcePos, lhs, args); break; case TEMPLATE: sourcePos = ts.sourcePosition(); TemplateLiteral templ = templateLiteral(true); lhs = new TemplateCallExpression(sourcePos, lhs, templ); break; default: return lhs; } } } /** * <strong>[12.2] Left-Hand-Side Expressions</strong> * * <pre> * Arguments : * () * ( ArgumentList ) * ArgumentList : * AssignmentExpression * ... AssignmentExpression * ArgumentList , AssignmentExpression * ArgumentList , ... AssignmentExpression * </pre> */ private List<Expression> arguments() { List<Expression> args = newSmallList(); long position = ts.position(), lineinfo = ts.lineinfo(); consume(Token.LP); if (token() != Token.RP) { if (token() != Token.TRIPLE_DOT && isEnabled(Option.LegacyComprehension)) { Expression expr = assignmentExpression(true); if (token() == Token.FOR) { ts.reset(position, lineinfo); args.add(legacyGeneratorComprehension()); return args; } args.add(expr); if (token() == Token.COMMA) { consume(Token.COMMA); } else { consume(Token.RP); return args; } } for (;;) { Expression expr; if (token() == Token.TRIPLE_DOT) { long sourcePos = ts.sourcePosition(); consume(Token.TRIPLE_DOT); expr = new CallSpreadElement(sourcePos, assignmentExpression(true)); } else { expr = assignmentExpression(true); } args.add(expr); if (token() == Token.COMMA) { consume(Token.COMMA); } else { break; } } if (args.size() > MAX_ARGUMENTS) { reportSyntaxError(Messages.Key.FunctionTooManyArguments); } } consume(Token.RP); return args; } /** * <strong>[12.3] Postfix Expressions</strong><br> * <strong>[12.4] Unary Operators</strong> * * <pre> * PostfixExpression : * LeftHandSideExpression * LeftHandSideExpression [no <i>LineTerminator</i> here] ++ * LeftHandSideExpression [no <i>LineTerminator</i> here] -- * UnaryExpression : * PostfixExpression * delete UnaryExpression * void UnaryExpression * typeof UnaryExpression * ++ UnaryExpression * -- UnaryExpression * + UnaryExpression * - UnaryExpression * ~ UnaryExpression * ! UnaryExpression * </pre> */ private Expression unaryExpression() { Token tok = token(); switch (tok) { case DELETE: case VOID: case TYPEOF: case INC: case DEC: case ADD: case SUB: case BITNOT: case NOT: { long sourcePos = ts.sourcePosition(); consume(tok); UnaryExpression unary = new UnaryExpression(sourcePos, unaryOp(tok, false), unaryExpression()); if (tok == Token.INC || tok == Token.DEC) { validateSimpleAssignment(unary.getOperand(), ExceptionType.ReferenceError, Messages.Key.InvalidIncDecTarget); } if (tok == Token.DELETE) { Expression operand = unary.getOperand(); if (operand instanceof Identifier) { reportStrictModeSyntaxError(unary, Messages.Key.StrictModeInvalidDeleteOperand); } } return unary; } default: { Expression lhs = leftHandSideExpression(true); if (noLineTerminator()) { tok = token(); if (tok == Token.INC || tok == Token.DEC) { validateSimpleAssignment(lhs, ExceptionType.ReferenceError, Messages.Key.InvalidIncDecTarget); long sourcePos = ts.sourcePosition(); consume(tok); return new UnaryExpression(sourcePos, unaryOp(tok, true), lhs); } } return lhs; } } } private static UnaryExpression.Operator unaryOp(Token tok, boolean postfix) { switch (tok) { case DELETE: return UnaryExpression.Operator.DELETE; case VOID: return UnaryExpression.Operator.VOID; case TYPEOF: return UnaryExpression.Operator.TYPEOF; case INC: return postfix ? UnaryExpression.Operator.POST_INC : UnaryExpression.Operator.PRE_INC; case DEC: return postfix ? UnaryExpression.Operator.POST_DEC : UnaryExpression.Operator.PRE_DEC; case ADD: return UnaryExpression.Operator.POS; case SUB: return UnaryExpression.Operator.NEG; case BITNOT: return UnaryExpression.Operator.BITNOT; case NOT: return UnaryExpression.Operator.NOT; default: throw new IllegalStateException(); } } private Expression binaryExpression(boolean allowIn) { Expression lhs = unaryExpression(); return binaryExpression(allowIn, lhs, BinaryExpression.Operator.OR.getPrecedence()); } private Expression binaryExpression(boolean allowIn, Expression lhs, int minpred) { // Recursive-descent parsers require multiple levels of recursion to // parse binary expressions, to avoid this we're using precedence // climbing here for (;;) { Token tok = token(); if (tok == Token.IN && !allowIn) { break; } BinaryExpression.Operator op = binaryOp(tok); int pred = (op != null ? op.getPrecedence() : -1); if (pred < minpred) { break; } consume(tok); Expression rhs = unaryExpression(); for (;;) { BinaryExpression.Operator op2 = binaryOp(token()); int pred2 = (op2 != null ? op2.getPrecedence() : -1); if (pred2 <= pred) { break; } rhs = binaryExpression(allowIn, rhs, pred2); } lhs = new BinaryExpression(op, lhs, rhs); } return lhs; } private static BinaryExpression.Operator binaryOp(Token token) { switch (token) { case OR: return BinaryExpression.Operator.OR; case AND: return BinaryExpression.Operator.AND; case BITOR: return BinaryExpression.Operator.BITOR; case BITXOR: return BinaryExpression.Operator.BITXOR; case BITAND: return BinaryExpression.Operator.BITAND; case EQ: return BinaryExpression.Operator.EQ; case NE: return BinaryExpression.Operator.NE; case SHEQ: return BinaryExpression.Operator.SHEQ; case SHNE: return BinaryExpression.Operator.SHNE; case LT: return BinaryExpression.Operator.LT; case LE: return BinaryExpression.Operator.LE; case GT: return BinaryExpression.Operator.GT; case GE: return BinaryExpression.Operator.GE; case IN: return BinaryExpression.Operator.IN; case INSTANCEOF: return BinaryExpression.Operator.INSTANCEOF; case SHL: return BinaryExpression.Operator.SHL; case SHR: return BinaryExpression.Operator.SHR; case USHR: return BinaryExpression.Operator.USHR; case ADD: return BinaryExpression.Operator.ADD; case SUB: return BinaryExpression.Operator.SUB; case MUL: return BinaryExpression.Operator.MUL; case DIV: return BinaryExpression.Operator.DIV; case MOD: return BinaryExpression.Operator.MOD; default: return null; } } /** * <strong>[12.12] Conditional Operator</strong><br> * <strong>[12.13] Assignment Operators</strong> * * <pre> * ConditionalExpression : * LogicalORExpression * LogicalORExpression ? AssignmentExpression : AssignmentExpression * ConditionalExpressionNoIn : * LogicalORExpressionNoIn * LogicalORExpressionNoIn ? AssignmentExpression : AssignmentExpressionNoIn * AssignmentExpression : * ConditionalExpression * YieldExpression * ArrowFunction * LeftHandSideExpression = AssignmentExpression * LeftHandSideExpression AssignmentOperator AssignmentExpression * AssignmentExpressionNoIn : * ConditionalExpressionNoIn * YieldExpression * ArrowFunction * LeftHandSideExpression = AssignmentExpressionNoIn * LeftHandSideExpression AssignmentOperator AssignmentExpressionNoIn * </pre> */ private Expression assignmentExpression(boolean allowIn) { int count = context.countLiterals(); Expression expr = assignmentExpression(allowIn, count); if (count < context.countLiterals()) { objectLiteral_StaticSemantics(count); } return expr; } private Expression assignmentExpressionNoValidation(boolean allowIn) { return assignmentExpression(allowIn, context.countLiterals()); } private Expression assignmentExpression(boolean allowIn, int oldCount) { if (token() == Token.YIELD) { if (context.kind == ContextKind.Generator) { return yieldExpression(allowIn); } else if (context.kind == ContextKind.Function && isEnabled(Option.LegacyGenerator)) { throw new RetryGenerator(); } } long position = ts.position(), lineinfo = ts.lineinfo(); Expression left = binaryExpression(allowIn); Token tok = token(); if (tok == Token.HOOK) { consume(Token.HOOK); Expression then = assignmentExpression(true); consume(Token.COLON); Expression otherwise = assignmentExpression(allowIn); return new ConditionalExpression(left, then, otherwise); } else if (tok == Token.ARROW) { // discard parsed object literals if (oldCount < context.countLiterals()) { ArrayDeque<ObjectLiteral> literals = context.objectLiterals; for (int i = oldCount, newCount = literals.size(); i < newCount; ++i) { literals.pop(); } } ts.reset(position, lineinfo); return arrowFunction(allowIn); } else if (tok == Token.ASSIGN) { LeftHandSideExpression lhs = validateAssignment(left, ExceptionType.ReferenceError, Messages.Key.InvalidAssignmentTarget); consume(Token.ASSIGN); Expression right = assignmentExpression(allowIn); return new AssignmentExpression(assignmentOp(tok), lhs, right); } else if (isAssignmentOperator(tok)) { LeftHandSideExpression lhs = validateSimpleAssignment(left, ExceptionType.ReferenceError, Messages.Key.InvalidAssignmentTarget); consume(tok); Expression right = assignmentExpression(allowIn); return new AssignmentExpression(assignmentOp(tok), lhs, right); } else { return left; } } private static AssignmentExpression.Operator assignmentOp(Token token) { switch (token) { case ASSIGN: return AssignmentExpression.Operator.ASSIGN; case ASSIGN_ADD: return AssignmentExpression.Operator.ASSIGN_ADD; case ASSIGN_SUB: return AssignmentExpression.Operator.ASSIGN_SUB; case ASSIGN_MUL: return AssignmentExpression.Operator.ASSIGN_MUL; case ASSIGN_DIV: return AssignmentExpression.Operator.ASSIGN_DIV; case ASSIGN_MOD: return AssignmentExpression.Operator.ASSIGN_MOD; case ASSIGN_SHL: return AssignmentExpression.Operator.ASSIGN_SHL; case ASSIGN_SHR: return AssignmentExpression.Operator.ASSIGN_SHR; case ASSIGN_USHR: return AssignmentExpression.Operator.ASSIGN_USHR; case ASSIGN_BITAND: return AssignmentExpression.Operator.ASSIGN_BITAND; case ASSIGN_BITOR: return AssignmentExpression.Operator.ASSIGN_BITOR; case ASSIGN_BITXOR: return AssignmentExpression.Operator.ASSIGN_BITXOR; default: throw new IllegalStateException(); } } /** * <strong>[12.13] Assignment Operators</strong> * * <pre> * AssignmentOperator : <b>one of</b> * *= /= %= += -= <<= >>= >>>= &= ^= |= * </pre> */ private boolean isAssignmentOperator(Token tok) { switch (tok) { case ASSIGN_ADD: case ASSIGN_BITAND: case ASSIGN_BITOR: case ASSIGN_BITXOR: case ASSIGN_DIV: case ASSIGN_MOD: case ASSIGN_MUL: case ASSIGN_SHL: case ASSIGN_SHR: case ASSIGN_SUB: case ASSIGN_USHR: return true; default: return false; } } /** * <strong>[12.14] Comma Operator</strong> * * <pre> * Expression : * AssignmentExpression * Expression , AssignmentExpression * ExpressionNoIn : * AssignmentExpressionNoIn * ExpressionNoIn , AssignmentExpressionNoIn * </pre> */ private Expression expression(boolean allowIn) { Expression expr = assignmentExpression(allowIn); if (token() == Token.COMMA) { List<Expression> list = new ArrayList<>(); list.add(expr); while (token() == Token.COMMA) { consume(Token.COMMA); expr = assignmentExpression(allowIn); list.add(expr); } return new CommaExpression(list); } return expr; } /** * <strong>[11.9] Automatic Semicolon Insertion</strong> * * <pre> * </pre> */ private void semicolon() { switch (token()) { case SEMI: consume(Token.SEMI); // fall-through case RC: case EOF: break; default: if (noLineTerminator()) { reportSyntaxError(Messages.Key.MissingSemicolon); } } } /** * Peek next token and check for line-terminator */ private boolean noLineTerminator() { return !ts.hasCurrentLineTerminator(); } /** * Returns <code>true</code> if {@link Token#YIELD} should be treated as {@link Token#NAME} in * the current context */ private boolean isYieldName() { return isYieldName(context); } /** * Returns <code>true</code> if {@link Token#YIELD} should be treated as {@link Token#NAME} in * the supplied context */ private boolean isYieldName(ParseContext context) { // 'yield' is always a keyword in strict-mode and in generators if (context.strictMode == StrictMode.Strict || context.kind == ContextKind.Generator) { return false; } // proactively flag as syntax error if current strict mode is unknown reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(Token.YIELD)); return true; } /** * Returns true if the current token is of type {@link Token#NAME} and its name is {@code name} */ private boolean isName(String name) { Token tok = token(); return (tok == Token.NAME && name.equals(getName(tok))); } /** * Return token name */ private String getName(Token tok) { if (tok == Token.NAME) { return ts.getString(); } return tok.getName(); } /** * <strong>[11.6] Identifier Names and Identifiers</strong> * * <pre> * Identifier :: * IdentifierName but not ReservedWord * ReservedWord :: * Keyword * FutureReservedWord * NullLiteral * BooleanLiteral * </pre> */ private String identifier() { Token tok = token(); if (!isIdentifier(tok)) { reportTokenMismatch("<identifier>", tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[11.6] Identifier Names and Identifiers</strong> * * <pre> * Identifier :: * IdentifierName but not ReservedWord * ReservedWord :: * Keyword * FutureReservedWord * NullLiteral * BooleanLiteral * </pre> */ private String strictIdentifier() { Token tok = token(); if (!isStrictIdentifier(tok)) { reportTokenMismatch("<identifier>", tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[11.6] Identifier Names and Identifiers</strong> */ private boolean isIdentifier(Token tok) { switch (tok) { case NAME: return true; case YIELD: return isYieldName(); case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: if (context.strictMode != StrictMode.NonStrict) { reportStrictModeSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(tok)); } return (context.strictMode != StrictMode.Strict); default: return false; } } /** * <strong>[11.6] Identifier Names and Identifiers</strong> */ private boolean isStrictIdentifier(Token tok) { switch (tok) { case NAME: return true; case YIELD: case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: throw reportSyntaxError(Messages.Key.StrictModeInvalidIdentifier, getName(tok)); default: return false; } } /** * <strong>[11.6] Identifier Names and Identifiers</strong> */ private String identifierName() { Token tok = token(); if (!isIdentifierName(tok)) { reportTokenMismatch("<identifier-name>", tok); } String name = getName(tok); consume(tok); return name; } /** * <strong>[11.6] Identifier Names and Identifiers</strong> */ private static boolean isIdentifierName(Token tok) { switch (tok) { case NAME: // Literals case NULL: case FALSE: case TRUE: // Keywords case BREAK: case CASE: case CATCH: case CLASS: case CONST: case CONTINUE: case DEBUGGER: case DEFAULT: case DELETE: case DO: case ELSE: case EXPORT: case FINALLY: case FOR: case FUNCTION: case IF: case IMPORT: case IN: case INSTANCEOF: case LET: case NEW: case RETURN: case SUPER: case SWITCH: case THIS: case THROW: case TRY: case TYPEOF: case VAR: case VOID: case WHILE: case WITH: // Future Reserved Words case ENUM: case EXTENDS: case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: case YIELD: return true; default: return false; } } /** * <strong>[11.6.1] Reserved Words</strong> */ private boolean isReservedWord(Token tok) { switch (tok) { case FALSE: case NULL: case TRUE: return true; default: return isKeyword(tok) || isFutureReservedWord(tok); } } /** * <strong>[11.6.1.1] Keywords</strong> */ private boolean isKeyword(Token tok) { switch (tok) { case BREAK: case CASE: case CATCH: case CLASS: case CONST: case CONTINUE: case DEBUGGER: case DEFAULT: case DELETE: case DO: case ELSE: case EXPORT: case FINALLY: case FOR: case FUNCTION: case IF: case IMPORT: case IN: case INSTANCEOF: case LET: case NEW: case RETURN: case SUPER: case SWITCH: case THIS: case THROW: case TRY: case TYPEOF: case VAR: case VOID: case WHILE: case WITH: return true; default: return false; } } /** * <strong>[11.6.1.2] Future Reserved Words</strong> */ private boolean isFutureReservedWord(Token tok) { switch (tok) { case ENUM: case EXTENDS: return true; case IMPLEMENTS: case INTERFACE: case PACKAGE: case PRIVATE: case PROTECTED: case PUBLIC: case STATIC: case YIELD: return (context.strictMode != StrictMode.Strict); default: return false; } } /** * <strong>[11.8.3] Numeric Literals</strong> */ private double numericLiteral() { double number = ts.getNumber(); consume(Token.NUMBER); return number; } /** * <strong>[11.8.4] String Literals</strong> */ private String stringLiteral() { String string = ts.getString(); consume(Token.STRING); return string; } }
package com.jdroid.android.ad; import android.app.Activity; import android.text.format.DateUtils; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.ads.AdActivity; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import com.jdroid.android.AbstractApplication; import com.jdroid.android.context.AppContext; public class AdHelper { private ViewGroup adViewContainer; private View customView; private AdView adView; private Boolean displayAds = false; private InterstitialAd interstitial; private Boolean displayInterstitial = false; public void loadAd(final Activity activity, ViewGroup adViewContainer, AdSize adSize, HouseAdBuilder houseAdBuilder, Boolean isInterstitialEnabled) { AppContext applicationContext = AbstractApplication.get().getAppContext(); if (isInterstitialEnabled && applicationContext.areAdsEnabled()) { loadInterstitial(activity); } this.adViewContainer = adViewContainer; if (adViewContainer != null) { if ((adSize == null) || !applicationContext.areAdsEnabled()) { adViewContainer.setVisibility(View.GONE); } else { adView = new AdView(activity); adView.setAdUnitId(applicationContext.getAdUnitId()); adView.setAdSize(adSize); customView = houseAdBuilder != null ? houseAdBuilder.build(activity) : null; if (customView != null) { adViewContainer.addView(customView); adView.setAdListener(new AdListener() { @Override public void onAdLoaded() { super.onAdLoaded(); if (displayAds) { adView.setVisibility(View.VISIBLE); customView.setVisibility(View.GONE); } else { adView.postDelayed(new Runnable() { @Override public void run() { displayAds = true; if ((adView != null) && (customView != null)) { adView.setVisibility(View.VISIBLE); customView.setVisibility(View.GONE); } } }, DateUtils.SECOND_IN_MILLIS * 5); } } @Override public void onAdClosed() { super.onAdClosed(); adView.setVisibility(View.GONE); customView.setVisibility(View.VISIBLE); } @Override public void onAdFailedToLoad(int errorCode) { super.onAdFailedToLoad(errorCode); adView.setVisibility(View.GONE); customView.setVisibility(View.VISIBLE); } }); } AdRequest.Builder builder = createBuilder(applicationContext); adView.loadAd(builder.build()); adViewContainer.addView(adView); } } } private AdRequest.Builder createBuilder(AppContext applicationContext) { final AdRequest.Builder builder = new AdRequest.Builder(); if (!applicationContext.isProductionEnvironment()) { builder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR); for (String deviceId : applicationContext.getTestDevicesIds()) { builder.addTestDevice(deviceId); } } return builder; } private void loadInterstitial(Activity activity) { interstitial = new InterstitialAd(activity); AppContext applicationContext = AbstractApplication.get().getAppContext(); interstitial.setAdUnitId(applicationContext.getAdUnitId()); AdRequest.Builder builder = createBuilder(applicationContext); interstitial.loadAd(builder.build()); interstitial.setAdListener(new AdListener() { @Override public void onAdLoaded() { super.onAdLoaded(); if (displayInterstitial) { displayInterstitial(false); } } @Override public void onAdOpened() { super.onAdOpened(); AbstractApplication.get().getAnalyticsSender().onActivityStart(AdActivity.class, null, null); } }); } public void displayInterstitial(Boolean retryIfNotLoaded) { displayInterstitial = retryIfNotLoaded; if ((interstitial != null) && interstitial.isLoaded()) { interstitial.show(); displayInterstitial = false; } } public void onPause() { if (adView != null) { adView.pause(); } } public void onResume() { if (adView != null) { if (AbstractApplication.get().getAppContext().areAdsEnabled()) { adView.resume(); } else if (adViewContainer != null) { adViewContainer.removeView(adView); adViewContainer.setVisibility(View.GONE); adView = null; adViewContainer = null; } } } public void onDestroy() { if (adView != null) { adView.destroy(); adView = null; adViewContainer = null; } } }
package com.github.anba.es6draft.runtime; import static com.github.anba.es6draft.runtime.AbstractOperations.Get; import static com.github.anba.es6draft.runtime.ExecutionContext.newScriptExecutionContext; import java.text.Collator; import java.text.DecimalFormatSymbols; import java.util.EnumMap; import java.util.EnumSet; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.atomic.AtomicInteger; import com.github.anba.es6draft.runtime.internal.CompatibilityOption; import com.github.anba.es6draft.runtime.internal.Messages; import com.github.anba.es6draft.runtime.internal.ObjectAllocator; import com.github.anba.es6draft.runtime.modules.Loader; import com.github.anba.es6draft.runtime.objects.*; import com.github.anba.es6draft.runtime.objects.NativeErrorConstructor.ErrorType; import com.github.anba.es6draft.runtime.objects.binary.ArrayBufferConstructor; import com.github.anba.es6draft.runtime.objects.binary.ArrayBufferPrototype; import com.github.anba.es6draft.runtime.objects.binary.DataViewConstructor; import com.github.anba.es6draft.runtime.objects.binary.DataViewPrototype; import com.github.anba.es6draft.runtime.objects.binary.ElementType; import com.github.anba.es6draft.runtime.objects.binary.TypedArrayConstructor; import com.github.anba.es6draft.runtime.objects.binary.TypedArrayConstructorPrototype; import com.github.anba.es6draft.runtime.objects.binary.TypedArrayPrototype; import com.github.anba.es6draft.runtime.objects.binary.TypedArrayPrototypePrototype; import com.github.anba.es6draft.runtime.objects.collection.*; import com.github.anba.es6draft.runtime.objects.internal.ListIteratorPrototype; import com.github.anba.es6draft.runtime.objects.intl.CollatorConstructor; import com.github.anba.es6draft.runtime.objects.intl.CollatorPrototype; import com.github.anba.es6draft.runtime.objects.intl.DateTimeFormatConstructor; import com.github.anba.es6draft.runtime.objects.intl.DateTimeFormatPrototype; import com.github.anba.es6draft.runtime.objects.intl.IntlObject; import com.github.anba.es6draft.runtime.objects.intl.NumberFormatConstructor; import com.github.anba.es6draft.runtime.objects.intl.NumberFormatPrototype; import com.github.anba.es6draft.runtime.objects.iteration.GeneratorFunctionConstructor; import com.github.anba.es6draft.runtime.objects.iteration.GeneratorFunctionPrototype; import com.github.anba.es6draft.runtime.objects.iteration.GeneratorPrototype; import com.github.anba.es6draft.runtime.objects.reflect.ProxyConstructor; import com.github.anba.es6draft.runtime.objects.reflect.Reflect; import com.github.anba.es6draft.runtime.types.Callable; import com.github.anba.es6draft.runtime.types.Intrinsics; import com.github.anba.es6draft.runtime.types.ScriptObject; import com.github.anba.es6draft.runtime.types.builtins.OrdinaryFunction; /** * <h1>8 Executable Code and Execution Contexts</h1> * <ul> * <li>8.2 Code Realms * </ul> */ public final class Realm { /** * [[intrinsics]] */ private Map<Intrinsics, ScriptObject> intrinsics = new EnumMap<>(Intrinsics.class); /** * [[globalThis]] */ private GlobalObject globalThis; /** * [[globalEnv]] */ private LexicalEnvironment globalEnv; /** * [[loader]] */ private Loader loader; /** * [[ThrowTypeError]] */ private Callable throwTypeError; private Callable builtinEval; private ExecutionContext defaultContext; private Set<CompatibilityOption> options; private Locale locale = Locale.getDefault(); private TimeZone timezone = TimeZone.getDefault(); private Messages messages = Messages.create(locale); // TODO: move into function source object private Map<String, ScriptObject> templateCallSites = new HashMap<>(); private Realm() { } /** * [[intrinsics]] */ public ScriptObject getIntrinsic(Intrinsics id) { return intrinsics.get(id); } /** * [[globalThis]] */ public GlobalObject getGlobalThis() { return globalThis; } /** * [[globalEnv]] */ public LexicalEnvironment getGlobalEnv() { return globalEnv; } /** * [[loader]] */ public Loader getLoader() { return loader; } /** * [[ThrowTypeError]] */ public Callable getThrowTypeError() { assert throwTypeError != null : "throwTypeError not yet initialised"; return throwTypeError; } /** * Returns the default execution context for this realm */ public ExecutionContext defaultContext() { return defaultContext; } private AtomicInteger evalCounter = new AtomicInteger(0); private AtomicInteger functionCounter = new AtomicInteger(0); /** * Next class name for eval scripts * * @see Eval */ public String nextEvalName() { return "Eval_" + evalCounter.incrementAndGet(); } /** * Next class name for functions * * @see FunctionConstructor * @see GeneratorFunctionConstructor */ public String nextFunctionName() { return "Function_" + functionCounter.incrementAndGet(); } /** * Returns this realm's locale */ public Locale getLocale() { return locale; } /** * Returns this realm's timezone */ public TimeZone getTimezone() { return timezone; } /** * Returns the localised message for {@code key} */ public String message(Messages.Key key) { return messages.getString(key); } /** * Returns a reference to the built-in <code>eval</code> function */ public Callable getBuiltinEval() { return builtinEval; } /** * Returns the compatibility options for this realm instance */ public Set<CompatibilityOption> getOptions() { return options; } /** * Tests whether the requested compatibility option is enabled in this code realm */ public boolean isEnabled(CompatibilityOption option) { return options.contains(option); } /** * Returns the template call-site object for {@code key} */ public ScriptObject getTemplateCallSite(String key) { return templateCallSites.get(key); } /** * Stores the template call-site object */ public void addTemplateCallSite(String key, ScriptObject callSite) { templateCallSites.put(key, callSite); } /** * Returns a {@link Collator} for this realm's locale * * @deprecated No longer used */ @Deprecated public Collator getCollator() { Collator collator = Collator.getInstance(locale); // Use Normalised Form D for comparison (cf. 21.1.3.10, Note 2) collator.setDecomposition(Collator.CANONICAL_DECOMPOSITION); // `"\u0001".localeCompare("\u0002") == -1` should yield true collator.setStrength(Collator.IDENTICAL); return collator; } /** * Returns the locale specific list separator */ public String getListSeparator() { DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(); return symbols.getDecimalSeparator() == ',' ? ";" : ","; } private static final ObjectAllocator<GlobalObject> DEFAULT_GLOBAL_OBJECT = new ObjectAllocator<GlobalObject>() { @Override public GlobalObject newInstance(Realm realm) { return new GlobalObject(realm); } }; /** * Creates a new {@link Realm} object with the default settings */ public static Realm newRealm() { return newRealm(DEFAULT_GLOBAL_OBJECT, CompatibilityOption.WebCompatibility()); } /** * Creates a new {@link Realm} object */ public static Realm newRealm(ObjectAllocator<? extends GlobalObject> allocator, Set<CompatibilityOption> options) { Realm realm = new Realm(); GlobalObject globalThis = allocator.newInstance(realm); ExecutionContext defaultContext = newScriptExecutionContext(realm); GlobalEnvironmentRecord envRec = new GlobalEnvironmentRecord(defaultContext, globalThis); LexicalEnvironment globalEnv = new LexicalEnvironment(defaultContext, envRec); realm.globalThis = globalThis; realm.globalEnv = globalEnv; realm.defaultContext = defaultContext; realm.options = EnumSet.copyOf(options); // intrinsics: 19, 20, 21, 22.1, 24.3 initialiseFundamentalObjects(realm); initialiseStandardObjects(realm); initialiseNativeErrors(realm); initialiseInternalObjects(realm); // intrinsics: 22.2, 23, 24.1, 24.2, 25 initialiseBinaryModule(realm); initialiseCollectionModule(realm); initialiseReflectModule(realm); initialiseIterationModule(realm); // intrinsics: Internationalization API initialiseInternationalisation(realm); // finish initialising global object globalThis.initialise(defaultContext); // store reference to built-in eval realm.builtinEval = (Callable) Get(defaultContext, globalThis, "eval"); return realm; } /** * <h1>19.1 Object Objects - 19.2 Function Objects</h1> * * Fundamental built-in objects which must be initialised early */ private static void initialiseFundamentalObjects(Realm realm) { Map<Intrinsics, ScriptObject> intrinsics = realm.intrinsics; ExecutionContext defaultContext = realm.defaultContext; // allocation phase ObjectConstructor objectConstructor = new ObjectConstructor(realm); ObjectPrototype objectPrototype = new ObjectPrototype(realm); FunctionConstructor functionConstructor = new FunctionConstructor(realm); FunctionPrototype functionPrototype = new FunctionPrototype(realm); // registration phase intrinsics.put(Intrinsics.Object, objectConstructor); intrinsics.put(Intrinsics.ObjectPrototype, objectPrototype); intrinsics.put(Intrinsics.Function, functionConstructor); intrinsics.put(Intrinsics.FunctionPrototype, functionPrototype); // create [[ThrowTypeError]] unique function (needs to be done before init'ing intrinsics) realm.throwTypeError = OrdinaryFunction.createThrowTypeError(defaultContext); // initialisation phase objectConstructor.initialise(defaultContext); objectPrototype.initialise(defaultContext); functionConstructor.initialise(defaultContext); functionPrototype.initialise(defaultContext); // Object.prototype.toString is also an intrinsic Object objectPrototypeToString = Get(defaultContext, objectPrototype, "toString"); intrinsics.put(Intrinsics.ObjProto_toString, (ScriptObject) objectPrototypeToString); } /** * <h1>19.3, 19.4, 20, 21, 22.1, 24.3</h1> * * Standard built-in objects */ private static void initialiseStandardObjects(Realm realm) { Map<Intrinsics, ScriptObject> intrinsics = realm.intrinsics; ExecutionContext defaultContext = realm.defaultContext; // allocation phase ArrayConstructor arrayConstructor = new ArrayConstructor(realm); ArrayPrototype arrayPrototype = new ArrayPrototype(realm); ArrayIteratorPrototype arrayIteratorPrototype = new ArrayIteratorPrototype(realm); StringConstructor stringConstructor = new StringConstructor(realm); StringPrototype stringPrototype = new StringPrototype(realm); BooleanConstructor booleanConstructor = new BooleanConstructor(realm); BooleanPrototype booleanPrototype = new BooleanPrototype(realm); NumberConstructor numberConstructor = new NumberConstructor(realm); NumberPrototype numberPrototype = new NumberPrototype(realm); MathObject mathObject = new MathObject(realm); DateConstructor dateConstructor = new DateConstructor(realm); DatePrototype datePrototype = new DatePrototype(realm); RegExpConstructor regExpConstructor = new RegExpConstructor(realm); RegExpPrototype regExpPrototype = new RegExpPrototype(realm); ErrorConstructor errorConstructor = new ErrorConstructor(realm); ErrorPrototype errorPrototype = new ErrorPrototype(realm); JSONObject jsonObject = new JSONObject(realm); // registration phase intrinsics.put(Intrinsics.Array, arrayConstructor); intrinsics.put(Intrinsics.ArrayPrototype, arrayPrototype); intrinsics.put(Intrinsics.ArrayIteratorPrototype, arrayIteratorPrototype); intrinsics.put(Intrinsics.String, stringConstructor); intrinsics.put(Intrinsics.StringPrototype, stringPrototype); intrinsics.put(Intrinsics.Boolean, booleanConstructor); intrinsics.put(Intrinsics.BooleanPrototype, booleanPrototype); intrinsics.put(Intrinsics.Number, numberConstructor); intrinsics.put(Intrinsics.NumberPrototype, numberPrototype); intrinsics.put(Intrinsics.Math, mathObject); intrinsics.put(Intrinsics.Date, dateConstructor); intrinsics.put(Intrinsics.DatePrototype, datePrototype); intrinsics.put(Intrinsics.RegExp, regExpConstructor); intrinsics.put(Intrinsics.RegExpPrototype, regExpPrototype); intrinsics.put(Intrinsics.Error, errorConstructor); intrinsics.put(Intrinsics.ErrorPrototype, errorPrototype); intrinsics.put(Intrinsics.JSON, jsonObject); // initialisation phase arrayConstructor.initialise(defaultContext); arrayPrototype.initialise(defaultContext); arrayIteratorPrototype.initialise(defaultContext); stringConstructor.initialise(defaultContext); stringPrototype.initialise(defaultContext); booleanConstructor.initialise(defaultContext); booleanPrototype.initialise(defaultContext); numberConstructor.initialise(defaultContext); numberPrototype.initialise(defaultContext); mathObject.initialise(defaultContext); dateConstructor.initialise(defaultContext); datePrototype.initialise(defaultContext); regExpConstructor.initialise(defaultContext); regExpPrototype.initialise(defaultContext); errorConstructor.initialise(defaultContext); errorPrototype.initialise(defaultContext); jsonObject.initialise(defaultContext); } /** * <h1>19.4.5 Native Error Types Used in This Standard</h1> * * Native Error built-in objects */ private static void initialiseNativeErrors(Realm realm) { Map<Intrinsics, ScriptObject> intrinsics = realm.intrinsics; ExecutionContext defaultContext = realm.defaultContext; // allocation phase NativeErrorConstructor evalErrorConstructor = new NativeErrorConstructor(realm, ErrorType.EvalError); NativeErrorPrototype evalErrorPrototype = new NativeErrorPrototype(realm, ErrorType.EvalError); NativeErrorConstructor rangeErrorConstructor = new NativeErrorConstructor(realm, ErrorType.RangeError); NativeErrorPrototype rangeErrorPrototype = new NativeErrorPrototype(realm, ErrorType.RangeError); NativeErrorConstructor referenceErrorConstructor = new NativeErrorConstructor(realm, ErrorType.ReferenceError); NativeErrorPrototype referenceErrorPrototype = new NativeErrorPrototype(realm, ErrorType.ReferenceError); NativeErrorConstructor syntaxErrorConstructor = new NativeErrorConstructor(realm, ErrorType.SyntaxError); NativeErrorPrototype syntaxErrorPrototype = new NativeErrorPrototype(realm, ErrorType.SyntaxError); NativeErrorConstructor typeErrorConstructor = new NativeErrorConstructor(realm, ErrorType.TypeError); NativeErrorPrototype typeErrorPrototype = new NativeErrorPrototype(realm, ErrorType.TypeError); NativeErrorConstructor uriErrorConstructor = new NativeErrorConstructor(realm, ErrorType.URIError); NativeErrorPrototype uriErrorPrototype = new NativeErrorPrototype(realm, ErrorType.URIError); NativeErrorConstructor internalErrorConstructor = new NativeErrorConstructor(realm, ErrorType.InternalError); NativeErrorPrototype internalErrorPrototype = new NativeErrorPrototype(realm, ErrorType.InternalError); // registration phase intrinsics.put(Intrinsics.EvalError, evalErrorConstructor); intrinsics.put(Intrinsics.EvalErrorPrototype, evalErrorPrototype); intrinsics.put(Intrinsics.RangeError, rangeErrorConstructor); intrinsics.put(Intrinsics.RangeErrorPrototype, rangeErrorPrototype); intrinsics.put(Intrinsics.ReferenceError, referenceErrorConstructor); intrinsics.put(Intrinsics.ReferenceErrorPrototype, referenceErrorPrototype); intrinsics.put(Intrinsics.SyntaxError, syntaxErrorConstructor); intrinsics.put(Intrinsics.SyntaxErrorPrototype, syntaxErrorPrototype); intrinsics.put(Intrinsics.TypeError, typeErrorConstructor); intrinsics.put(Intrinsics.TypeErrorPrototype, typeErrorPrototype); intrinsics.put(Intrinsics.URIError, uriErrorConstructor); intrinsics.put(Intrinsics.URIErrorPrototype, uriErrorPrototype); intrinsics.put(Intrinsics.InternalError, internalErrorConstructor); intrinsics.put(Intrinsics.InternalErrorPrototype, internalErrorPrototype); // initialisation phase evalErrorConstructor.initialise(defaultContext); evalErrorPrototype.initialise(defaultContext); rangeErrorConstructor.initialise(defaultContext); rangeErrorPrototype.initialise(defaultContext); referenceErrorConstructor.initialise(defaultContext); referenceErrorPrototype.initialise(defaultContext); syntaxErrorConstructor.initialise(defaultContext); syntaxErrorPrototype.initialise(defaultContext); typeErrorConstructor.initialise(defaultContext); typeErrorPrototype.initialise(defaultContext); uriErrorConstructor.initialise(defaultContext); uriErrorPrototype.initialise(defaultContext); internalErrorConstructor.initialise(defaultContext); internalErrorPrototype.initialise(defaultContext); } /** * Additional internal built-in objects used in this implementation */ private static void initialiseInternalObjects(Realm realm) { Map<Intrinsics, ScriptObject> intrinsics = realm.intrinsics; ExecutionContext defaultContext = realm.defaultContext; // allocation phase ListIteratorPrototype listIteratorPrototype = new ListIteratorPrototype(realm); // registration phase intrinsics.put(Intrinsics.ListIteratorPrototype, listIteratorPrototype); // initialisation phase listIteratorPrototype.initialise(defaultContext); } /** * <h1>23 Keyed Collection</h1> */ private static void initialiseCollectionModule(Realm realm) { Map<Intrinsics, ScriptObject> intrinsics = realm.intrinsics; ExecutionContext defaultContext = realm.defaultContext; // allocation phase MapConstructor mapConstructor = new MapConstructor(realm); MapPrototype mapPrototype = new MapPrototype(realm); MapIteratorPrototype mapIteratorPrototype = new MapIteratorPrototype(realm); WeakMapConstructor weakMapConstructor = new WeakMapConstructor(realm); WeakMapPrototype weakMapPrototype = new WeakMapPrototype(realm); SetConstructor setConstructor = new SetConstructor(realm); SetPrototype setPrototype = new SetPrototype(realm); SetIteratorPrototype setIteratorPrototype = new SetIteratorPrototype(realm); WeakSetConstructor weakSetConstructor = new WeakSetConstructor(realm); WeakSetPrototype weakSetPrototype = new WeakSetPrototype(realm); // registration phase intrinsics.put(Intrinsics.Map, mapConstructor); intrinsics.put(Intrinsics.MapPrototype, mapPrototype); intrinsics.put(Intrinsics.MapIteratorPrototype, mapIteratorPrototype); intrinsics.put(Intrinsics.WeakMap, weakMapConstructor); intrinsics.put(Intrinsics.WeakMapPrototype, weakMapPrototype); intrinsics.put(Intrinsics.Set, setConstructor); intrinsics.put(Intrinsics.SetPrototype, setPrototype); intrinsics.put(Intrinsics.SetIteratorPrototype, setIteratorPrototype); intrinsics.put(Intrinsics.WeakSet, weakSetConstructor); intrinsics.put(Intrinsics.WeakSetPrototype, weakSetPrototype); // initialisation phase mapConstructor.initialise(defaultContext); mapPrototype.initialise(defaultContext); mapIteratorPrototype.initialise(defaultContext); weakMapConstructor.initialise(defaultContext); weakMapPrototype.initialise(defaultContext); setConstructor.initialise(defaultContext); setPrototype.initialise(defaultContext); setIteratorPrototype.initialise(defaultContext); weakSetConstructor.initialise(defaultContext); weakSetPrototype.initialise(defaultContext); } /** * <h1>26 The Reflect Module</h1> */ private static void initialiseReflectModule(Realm realm) { Map<Intrinsics, ScriptObject> intrinsics = realm.intrinsics; ExecutionContext defaultContext = realm.defaultContext; // allocation phase ProxyConstructor proxyConstructor = new ProxyConstructor(realm); Reflect reflect = new Reflect(realm); // registration phase intrinsics.put(Intrinsics.Proxy, proxyConstructor); intrinsics.put(Intrinsics.Reflect, reflect); // initialisation phase proxyConstructor.initialise(defaultContext); reflect.initialise(defaultContext); } /** * <h1>25 The "std:iteration" Module</h1> */ private static void initialiseIterationModule(Realm realm) { Map<Intrinsics, ScriptObject> intrinsics = realm.intrinsics; ExecutionContext defaultContext = realm.defaultContext; // allocation phase GeneratorFunctionConstructor generatorFunctionConstructor = new GeneratorFunctionConstructor( realm); GeneratorPrototype generatorPrototype = new GeneratorPrototype(realm); GeneratorFunctionPrototype generator = new GeneratorFunctionPrototype(realm); // registration phase intrinsics.put(Intrinsics.GeneratorFunction, generatorFunctionConstructor); intrinsics.put(Intrinsics.GeneratorPrototype, generatorPrototype); intrinsics.put(Intrinsics.Generator, generator); // initialisation phase generatorFunctionConstructor.initialise(defaultContext); generatorPrototype.initialise(defaultContext); generator.initialise(defaultContext); } /** * <h1>22.2 TypedArray Objects, 24.1 ArrayBuffer Objects, 24.2 DataView Objects</h1> */ private static void initialiseBinaryModule(Realm realm) { Map<Intrinsics, ScriptObject> intrinsics = realm.intrinsics; ExecutionContext defaultContext = realm.defaultContext; // allocation phase ArrayBufferConstructor arrayBufferConstructor = new ArrayBufferConstructor(realm); ArrayBufferPrototype arrayBufferPrototype = new ArrayBufferPrototype(realm); TypedArrayConstructorPrototype typedArrayConstructor = new TypedArrayConstructorPrototype( realm); TypedArrayPrototypePrototype typedArrayPrototype = new TypedArrayPrototypePrototype(realm); TypedArrayConstructor int8ArrayConstructor = new TypedArrayConstructor(realm, ElementType.Int8); TypedArrayPrototype int8ArrayPrototype = new TypedArrayPrototype(realm, ElementType.Int8); TypedArrayConstructor uint8ArrayConstructor = new TypedArrayConstructor(realm, ElementType.Uint8); TypedArrayPrototype uint8ArrayPrototype = new TypedArrayPrototype(realm, ElementType.Uint8); TypedArrayConstructor uint8CArrayConstructor = new TypedArrayConstructor(realm, ElementType.Uint8C); TypedArrayPrototype uint8CArrayPrototype = new TypedArrayPrototype(realm, ElementType.Uint8C); TypedArrayConstructor int16ArrayConstructor = new TypedArrayConstructor(realm, ElementType.Int16); TypedArrayPrototype int16ArrayPrototype = new TypedArrayPrototype(realm, ElementType.Int16); TypedArrayConstructor uint16ArrayConstructor = new TypedArrayConstructor(realm, ElementType.Uint16); TypedArrayPrototype uint16ArrayPrototype = new TypedArrayPrototype(realm, ElementType.Uint16); TypedArrayConstructor int32ArrayConstructor = new TypedArrayConstructor(realm, ElementType.Int32); TypedArrayPrototype int32ArrayPrototype = new TypedArrayPrototype(realm, ElementType.Int32); TypedArrayConstructor uint32ArrayConstructor = new TypedArrayConstructor(realm, ElementType.Uint32); TypedArrayPrototype uint32ArrayPrototype = new TypedArrayPrototype(realm, ElementType.Uint32); TypedArrayConstructor float32ArrayConstructor = new TypedArrayConstructor(realm, ElementType.Float32); TypedArrayPrototype float32ArrayPrototype = new TypedArrayPrototype(realm, ElementType.Float32); TypedArrayConstructor float64ArrayConstructor = new TypedArrayConstructor(realm, ElementType.Float64); TypedArrayPrototype float64ArrayPrototype = new TypedArrayPrototype(realm, ElementType.Float64); DataViewConstructor dataViewConstructor = new DataViewConstructor(realm); DataViewPrototype dataViewPrototype = new DataViewPrototype(realm); // registration phase intrinsics.put(Intrinsics.ArrayBuffer, arrayBufferConstructor); intrinsics.put(Intrinsics.ArrayBufferPrototype, arrayBufferPrototype); intrinsics.put(Intrinsics.TypedArray, typedArrayConstructor); intrinsics.put(Intrinsics.TypedArrayPrototype, typedArrayPrototype); intrinsics.put(Intrinsics.Int8Array, int8ArrayConstructor); intrinsics.put(Intrinsics.Int8ArrayPrototype, int8ArrayPrototype); intrinsics.put(Intrinsics.Uint8Array, uint8ArrayConstructor); intrinsics.put(Intrinsics.Uint8ArrayPrototype, uint8ArrayPrototype); intrinsics.put(Intrinsics.Uint8ClampedArray, uint8CArrayConstructor); intrinsics.put(Intrinsics.Uint8ClampedArrayPrototype, uint8CArrayPrototype); intrinsics.put(Intrinsics.Int16Array, int16ArrayConstructor); intrinsics.put(Intrinsics.Int16ArrayPrototype, int16ArrayPrototype); intrinsics.put(Intrinsics.Uint16Array, uint16ArrayConstructor); intrinsics.put(Intrinsics.Uint16ArrayPrototype, uint16ArrayPrototype); intrinsics.put(Intrinsics.Int32Array, int32ArrayConstructor); intrinsics.put(Intrinsics.Int32ArrayPrototype, int32ArrayPrototype); intrinsics.put(Intrinsics.Uint32Array, uint32ArrayConstructor); intrinsics.put(Intrinsics.Uint32ArrayPrototype, uint32ArrayPrototype); intrinsics.put(Intrinsics.Float32Array, float32ArrayConstructor); intrinsics.put(Intrinsics.Float32ArrayPrototype, float32ArrayPrototype); intrinsics.put(Intrinsics.Float64Array, float64ArrayConstructor); intrinsics.put(Intrinsics.Float64ArrayPrototype, float64ArrayPrototype); intrinsics.put(Intrinsics.DataView, dataViewConstructor); intrinsics.put(Intrinsics.DataViewPrototype, dataViewPrototype); // initialisation phase arrayBufferConstructor.initialise(defaultContext); arrayBufferPrototype.initialise(defaultContext); typedArrayConstructor.initialise(defaultContext); typedArrayPrototype.initialise(defaultContext); int8ArrayConstructor.initialise(defaultContext); int8ArrayPrototype.initialise(defaultContext); uint8ArrayConstructor.initialise(defaultContext); uint8ArrayPrototype.initialise(defaultContext); uint8CArrayConstructor.initialise(defaultContext); uint8CArrayPrototype.initialise(defaultContext); int16ArrayConstructor.initialise(defaultContext); int16ArrayPrototype.initialise(defaultContext); uint16ArrayConstructor.initialise(defaultContext); uint16ArrayPrototype.initialise(defaultContext); int32ArrayConstructor.initialise(defaultContext); int32ArrayPrototype.initialise(defaultContext); uint32ArrayConstructor.initialise(defaultContext); uint32ArrayPrototype.initialise(defaultContext); float32ArrayConstructor.initialise(defaultContext); float32ArrayPrototype.initialise(defaultContext); float64ArrayConstructor.initialise(defaultContext); float64ArrayPrototype.initialise(defaultContext); dataViewConstructor.initialise(defaultContext); dataViewPrototype.initialise(defaultContext); } /** * <h1>Internationalisation API (ECMA-402)</h1><br> * <h2>8 The Intl Object - 12 DateTimeFormat Objects</h2> * * Additional built-in objects from the Internationalisation API */ private static void initialiseInternationalisation(Realm realm) { Map<Intrinsics, ScriptObject> intrinsics = realm.intrinsics; ExecutionContext defaultContext = realm.defaultContext; // allocation phase IntlObject intlObject = new IntlObject(realm); CollatorConstructor collatorConstructor = new CollatorConstructor(realm); CollatorPrototype collatorPrototype = new CollatorPrototype(realm); NumberFormatConstructor numberFormatConstructor = new NumberFormatConstructor(realm); NumberFormatPrototype numberFormatPrototype = new NumberFormatPrototype(realm); DateTimeFormatConstructor dateTimeFormatConstructor = new DateTimeFormatConstructor(realm); DateTimeFormatPrototype dateTimeFormatPrototype = new DateTimeFormatPrototype(realm); // registration phase intrinsics.put(Intrinsics.Intl, intlObject); intrinsics.put(Intrinsics.Intl_Collator, collatorConstructor); intrinsics.put(Intrinsics.Intl_CollatorPrototype, collatorPrototype); intrinsics.put(Intrinsics.Intl_NumberFormat, numberFormatConstructor); intrinsics.put(Intrinsics.Intl_NumberFormatPrototype, numberFormatPrototype); intrinsics.put(Intrinsics.Intl_DateTimeFormat, dateTimeFormatConstructor); intrinsics.put(Intrinsics.Intl_DateTimeFormatPrototype, dateTimeFormatPrototype); // initialisation phase intlObject.initialise(defaultContext); collatorConstructor.initialise(defaultContext); collatorPrototype.initialise(defaultContext); numberFormatConstructor.initialise(defaultContext); numberFormatPrototype.initialise(defaultContext); dateTimeFormatConstructor.initialise(defaultContext); dateTimeFormatPrototype.initialise(defaultContext); } }
package ASSET.Scenario; import java.beans.PropertyChangeListener; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; import ASSET.NetworkParticipant; import ASSET.ParticipantType; import ASSET.ScenarioType; import ASSET.Models.Detection.DetectionEvent; import ASSET.Models.Environment.EnvironmentType; import ASSET.Models.Environment.SimpleEnvironment; import ASSET.Models.Sensor.Initial.BroadbandSensor; import ASSET.Models.Vessels.SSN; import ASSET.Participants.Status; import ASSET.Scenario.LiveScenario.ISimulation; import ASSET.Util.RandomGenerator; import MWC.GUI.BaseLayer; import MWC.GUI.Layer; import MWC.GenericData.Duration; import MWC.GenericData.WorldLocation; import MWC.GenericData.WorldSpeed; public class CoreScenario implements ScenarioType, ISimulation { // objects /** * The list of participants we maintain */ HashMap<Integer, ParticipantType> _myVisibleParticipants = new HashMap<Integer, ParticipantType>(); /** * The list of monte carlo participants we maintain */ HashMap<Integer, ParticipantType> _myInvisibleParticipants = new HashMap<Integer, ParticipantType>(); /** * the complete list of participants we store */ HashMap<Integer, ParticipantType> _completeParticipantList = new HashMap<Integer, ParticipantType>(); /** * the list of any participants which have been destroyed during a step - they * are only actually removed at the end of the step - we store the index of * any to be destroyed */ private Vector<Integer> _pendingDestruction = new Vector<Integer>(0, 1); /** * the list of any participants which have been created during a step - they * are only actually added at the end of the step - we store the participant * itself */ private Vector<ParticipantType> _pendingCreation = new Vector<ParticipantType>( 0, 1); /** * the name of this scenario */ private String _myName; /** * the case id of this scenario. The case id is used by multiple scenario * generation algorithms to identify which permutation this scenario * represents. */ private String _myCaseId; /** * the step time for this scenario (millis) */ private int _myStepTime = 0; /** * the elapsed time for this scenario (millis) */ long _myTime = 0; /** * the initial value of time for this scenario */ private long _myStartTime = 0; /** * the scenario time step for this scenario (millis) */ int _myScenarioStepTime = 1000; /** * the list of stepping listeners */ private Vector<ScenarioSteppedListener> _stepListeners; /** * the list of participants changed listeners */ private Vector<ParticipantsChangedListener> _participantListeners; /** * the list of running listeners */ private Vector<ScenarioRunningListener> _runningListeners; /** * the timer we are using */ private javax.swing.Timer _myTimer; /** * property change listener support */ private java.beans.PropertyChangeSupport _pSupport; /** * the environment type for our model */ private EnvironmentType _myEnvironment; /** * the system time when we started running (to provide a report on how long it * took.. */ private long _systemStartTime = 0; /** * a seed to set when first starting a scenario (or null to continue with a * random series of randoms */ private Integer _mySeed = null; /** * if we have been stopped, this is the reason why It's also a flag to * indicate that somebody has triggered a scenario stop - note that we only * process the stop at the end of a step */ protected String _stopReason = null; // constructor public CoreScenario() { // initialise the timer _myTimer = new javax.swing.Timer(0, new java.awt.event.ActionListener() { private boolean stepping = false; public void actionPerformed(java.awt.event.ActionEvent e) { if (stepping) System.err.println("STEPPING"); stepping = true; step(); stepping = false; } }); _pSupport = new java.beans.PropertyChangeSupport(this); // create the environment _myEnvironment = createEnvironment(); // give the scenario a random case id _myCaseId = "Case_" + (int) (Math.random() * 2000d); // initialise the display settings _displaySettings = new HashMap<String, String>(); } // methods private EnvironmentType createEnvironment() { return new SimpleEnvironment(1, 1, 1); } /** * Start the scenario auto-stepping through itself. If the step time is set to * zero, it will automatically step after the completion of the previous step. */ public void start() { // store the delay time _myTimer.setDelay(_myStepTime); // initialse the seed (if we have one) if (_mySeed != null) RandomGenerator.seed(_mySeed.intValue()); // store the system start time _systemStartTime = System.currentTimeMillis(); // fire a stepped event to let the recorders store the initial state // No, don't - it's causing the status to go out twice // fireScenarioStepped(this.getTime()); if (!_myTimer.isRunning()) { // get it going _myTimer.start(); } this.fireScenarioStarted(); } /** * find out if the timer is currently auto-stepping * * @return */ public boolean isRunning() { return _myTimer.isRunning(); } /** * let anybody request that the scenario stop, though note that we only * process this at the end of a step. * <p/> * It's the doStop method which actually stops us * * @param reason */ public void stop(String reason) { _stopReason = reason; } /** * pause the automatic execution (but don't assume that the scenario is * complete) */ public void pause() { // is timer running if (_myTimer.isRunning()) _myTimer.stop(); // fire event this.fireScenarioPaused(); } /** * Stop the scenario from auto-stepping */ private void doStop() { // remember the reason String thisReason = _stopReason; // forget our local one, to be sure we aren't called twice _stopReason = null; // and store how long it took long finishTime = System.currentTimeMillis(); // is timer running if (_myTimer.isRunning()) _myTimer.stop(); // work out how long it took long elapsedTime = finishTime - _systemStartTime; // fire event this.fireScenarioStopped(elapsedTime, thisReason); System.out.println("Scenario stopped:" + thisReason); } boolean _firstPass = true; /** * the information we plot as a backdrop * */ private BaseLayer _myBackdrop; private HashMap<String, String> _displaySettings; /** * Move the scenario through a single step */ public void step() { // process a stop, if anybody has asked for it. if (_stopReason != null) { doStop(); // and now drop out return; } long oldTime = _myTime; if (!_firstPass) { // move time forward _myTime += _myScenarioStepTime; } // move the participants forward if (_completeParticipantList != null) { _firstPass = false; // first the decision cycle java.util.Iterator<ParticipantType> iter = _completeParticipantList .values().iterator(); while (iter.hasNext()) { final ParticipantType pt = (ParticipantType) iter.next(); // note: we aren't using the isAlive test to decide whether to do decisions, // since it's the decision that brings it to life pt.doDecision(oldTime, _myTime, this); } // now the movement cycle iter = _completeParticipantList.values().iterator(); while (iter.hasNext()) { final ParticipantType pt = (ParticipantType) iter.next(); if (pt.isAlive()) pt.doMovement(oldTime, _myTime, this); } // now the detection cycle HashMap<Integer, ParticipantType> copiedList = new HashMap<Integer, ParticipantType>( _completeParticipantList); iter = copiedList.values().iterator(); while (iter.hasNext()) { final ParticipantType pt = (ParticipantType) iter.next(); if (pt.isAlive()) pt.doDetection(oldTime, _myTime, this); } } // now add any recently created participants for (int ic = 0; ic < this._pendingCreation.size(); ic++) { final ParticipantType thisPart = (ParticipantType) this._pendingCreation .elementAt(ic); addParticipant(thisPart.getId(), thisPart); } // and clear the list _pendingCreation.clear(); // finally, delete the destroyed participants for (int i = 0; i < this._pendingDestruction.size(); i++) { final Integer thisIndex = (Integer) this._pendingDestruction.elementAt(i); removeParticipant(thisIndex.intValue()); } // and clear the list waiting to be destroyed _pendingDestruction.clear(); // fire messages this.fireScenarioStepped(_myTime); } /** * restart the scenario */ public void restart() { // reset our local time values _myTime = _myStartTime; // clear the 'dead' flag _stopReason = null; // step through the participants // move the participants forward if (_completeParticipantList != null) { final java.util.Iterator<ParticipantType> iter = _completeParticipantList .values().iterator(); while (iter.hasNext()) { final ParticipantType pt = iter.next(); pt.restart(this); } } // reset the observers // reset the listeners if (_participantListeners != null) { Vector<ParticipantsChangedListener> tmpList = new Vector<ParticipantsChangedListener>( _participantListeners); final Iterator<ParticipantsChangedListener> it = tmpList.iterator(); while (it.hasNext()) { final ParticipantsChangedListener pcl = it.next(); pcl.restart(this); } } if (_runningListeners != null) { // work with a copy of the running listeners, to prevent concurrent // changes (since in the restart // a listener may remove then re-insert itself as a listener Vector<ScenarioRunningListener> copyRunningListeners = new Vector<ScenarioRunningListener>( _runningListeners); final Iterator<ScenarioRunningListener> it = copyRunningListeners .iterator(); while (it.hasNext()) { final ScenarioRunningListener prl = it.next(); prl.restart(this); } } if (_stepListeners != null) { final Vector<ScenarioSteppedListener> copyStepListeners = new Vector<ScenarioSteppedListener>( _stepListeners); final Iterator<ScenarioSteppedListener> it = copyStepListeners.iterator(); while (it.hasNext()) { final ScenarioSteppedListener ssl = it.next(); ssl.restart(this); } } } /** * @return the scenario time step */ public int getScenarioStepTime() { return _myScenarioStepTime; } /** * set the scenario time step * * @param step_size * millis to step scenario forward at each step */ public void setScenarioStepTime(final int step_size) { _myScenarioStepTime = step_size; // fire the new value fireNewScenarioStepSize(step_size); } /** * set the scenario time step * * @param step_size * time to step scenario forward at each step */ public void setScenarioStepTime(Duration step_size) { this.setScenarioStepTime((int) step_size.getValueIn(Duration.MILLISECONDS)); } /** * set the size of the time delay (or zero to run to completion) * * @param step_size * time to pause before step (or zero to run) */ public void setStepTime(Duration step_size) { this.setStepTime((int) step_size.getValueIn(Duration.MILLISECONDS)); } /** * @return the step time for auto-stepping (or zero to run on) */ public int getStepTime() { return _myStepTime; } /** * set the size of the time delay (or zero to run to completion) * * @param step_size * millis to pause before step (or zero to run) */ public void setStepTime(final int step_size) { // store the new value _myStepTime = step_size; // update the timer _myTimer.setDelay(step_size); // fire the new value fireNewStepSize(step_size); } /** * get the name of this scenaro */ public String getName() { return _myName; } /** * set the name of this scenario */ public void setName(final String val) { // store old value String oldVal = null; if (_myName != null) oldVal = new String(_myName); // fire the event _pSupport.firePropertyChange(NAME, oldVal, val); // do the update _myName = val; } /** * set the current time of the scenario (millis) */ public long getTime() { return _myTime; } /** * set the initial time of the scenario (millis) */ public void setTime(final long time) { _myTime = time; _myStartTime = time; } /** * set the seed to use for running this scenario */ public void setSeed(Integer seed) { _mySeed = seed; } public String getCaseId() { return _myCaseId; } public void setCaseId(String myCaseId) { this._myCaseId = myCaseId; } /** * get the environment for this model */ public EnvironmentType getEnvironment() { return _myEnvironment; } /** * and set the environment. */ public void setEnvironment(EnvironmentType theEnv) { _myEnvironment = theEnv; } /** * Shut down this scenario. Close the participants, etc */ public void close() { _myEnvironment = null; if (_myBackdrop != null) _myBackdrop.removeAllElements(); if (_myInvisibleParticipants != null) _myInvisibleParticipants.clear(); if (_myVisibleParticipants != null) _myVisibleParticipants.clear(); _myName = "empty"; } // manage our listeners public void addParticipantsChangedListener( final ParticipantsChangedListener list) { if (_participantListeners == null) _participantListeners = new Vector<ParticipantsChangedListener>(1, 2); _participantListeners.add(list); } public void removeParticipantsChangedListener( final ParticipantsChangedListener list) { _participantListeners.remove(list); } public void addPropertyChangeListener(final String property_name, final PropertyChangeListener listener) { if (property_name == null) _pSupport.addPropertyChangeListener(listener); else _pSupport.addPropertyChangeListener(property_name, listener); } public void removePropertyChangeListener(final String property_name, final PropertyChangeListener listener) { try { if (property_name == null) _pSupport.removePropertyChangeListener(listener); else _pSupport.removePropertyChangeListener(property_name, listener); } catch (Exception e) { e.printStackTrace(); } } public void addScenarioRunningListener(final ScenarioRunningListener listener) { if (_runningListeners == null) _runningListeners = new Vector<ScenarioRunningListener>(1, 2); // right, insert the new running listener at the head of the chain. This is // to overcome a problem with // the Loader class - which adds itself as a scenario listener before it's // children. When we STOP // the loader goes in and calls all of the tearDown methods for observers // which it has loaded, so ditching the _myScenario object - even though the // child observer actually // may want to listen out for the Stop event itself in order to output it's // batch (or other) data _runningListeners.add(0, listener); } public void removeScenarioRunningListener( final ScenarioRunningListener listener) { _runningListeners.remove(listener); } public void addScenarioSteppedListener(final ScenarioSteppedListener listener) { if (_stepListeners == null) _stepListeners = new Vector<ScenarioSteppedListener>(1, 2); _stepListeners.add(listener); } public void removeScenarioSteppedListener( final ScenarioSteppedListener listener) { _stepListeners.remove(listener); } private void fireParticipantChanged(final int index, final boolean added) { if (_participantListeners != null) { final Iterator<ParticipantsChangedListener> it = _participantListeners .iterator(); while (it.hasNext()) { final ParticipantsChangedListener pcl = (ParticipantsChangedListener) it .next(); if (added) pcl.newParticipant(index); else pcl.participantRemoved(index); } } } void fireScenarioStepped(final long time) { if (_stepListeners != null) { // take copy of step listeners, in case it gets modified mid-step final Vector<ScenarioSteppedListener> copyStepListeners = new Vector<ScenarioSteppedListener>( _stepListeners); final Iterator<ScenarioSteppedListener> it = copyStepListeners.iterator(); while (it.hasNext()) { final ScenarioSteppedListener pcl = (ScenarioSteppedListener) it.next(); try { pcl.step(this, time); } catch (Exception e) { System.out.println("time:" + time + " pcl was:" + pcl); e.printStackTrace(); // To change body of catch statement use Options // | File Templates. } } } } private void fireScenarioStarted() { if (_runningListeners != null) { final Iterator<ScenarioRunningListener> it = _runningListeners.iterator(); while (it.hasNext()) { final ScenarioRunningListener pcl = (ScenarioRunningListener) it.next(); pcl.started(); } } } /** * pass the message out to the listeners * * @param timeTaken * how long we ran for * @param reason * the reason for stopping */ private void fireScenarioStopped(final long timeTaken, String reason) { if (_runningListeners != null) { // take a deep copy of the running listeners - when we're cycling through // the list there's the chance that // a listener may try and remove itself. bugger Vector<ScenarioRunningListener> copyListeners = new Vector<ScenarioRunningListener>( 0, 1); copyListeners.addAll(_runningListeners); final Iterator<ScenarioRunningListener> it = copyListeners.iterator(); while (it.hasNext()) { final ScenarioRunningListener pcl = it.next(); pcl.finished(timeTaken, reason); } // and ditch our spare copy. copyListeners.removeAllElements(); copyListeners = null; } } /** * pass the message out to the listeners */ private void fireScenarioPaused() { if (_runningListeners != null) { final Iterator<ScenarioRunningListener> it = _runningListeners.iterator(); while (it.hasNext()) { final ScenarioRunningListener pcl = (ScenarioRunningListener) it.next(); pcl.paused(); } } } private void fireNewStepSize(final int val) { if (_runningListeners != null) { final Iterator<ScenarioRunningListener> it = _runningListeners.iterator(); while (it.hasNext()) { final ScenarioRunningListener pcl = (ScenarioRunningListener) it.next(); pcl.newStepTime(val); } } } private void fireNewScenarioStepSize(final int val) { if (_runningListeners != null) { final Iterator<ScenarioRunningListener> it = _runningListeners.iterator(); while (it.hasNext()) { final ScenarioRunningListener pcl = (ScenarioRunningListener) it.next(); pcl.newScenarioStepTime(val); } } } // participant-related /** * Return a particular Participant - so that the Participant can be controlled * directly. Listeners added/removed. Participants added/removed, etc. */ public ParticipantType getThisParticipant(final int id) { ParticipantType res = null; if (_completeParticipantList != null) res = (ParticipantType) _completeParticipantList.get(new Integer(id)); return res; } /** * Provide a list of id numbers of Participant we contain * * @return list of ids of Participant we contain */ public Integer[] getListOfParticipants() { Integer[] res = new Integer[0]; if (_completeParticipantList != null) { final java.util.Collection<Integer> vals = _completeParticipantList .keySet(); res = vals.toArray(res); } return res; } /** * Provide a list of id numbers of Participant we contain * * @return list of ids of Participant we contain */ public Collection<ParticipantType> getListOfVisibleParticipants() { Collection<ParticipantType> res = null; if (_myVisibleParticipants != null) { res = _myVisibleParticipants.values(); } return res; } /** * convenience method for adding a participant to a hashmap */ private void addParticipantToThisList(int index, final ASSET.ParticipantType participant, HashMap<Integer, ParticipantType> map) { // if the index is zero, we will create one if (index == INVALID_ID) { index = ASSET.Util.IdNumber.generateInt(); // put this index into the state, if there is one if (participant.getStatus() != null) participant.getStatus().setId(index); } // do we contain this one already if (map.get(new Integer(index)) != null) System.err.println("DUPLICATE ENTITY BEING ADDED:!" + index); // store it map.put(new Integer(index), participant); } /** * back door, for reloading a scenario from file) */ public void addParticipant(int index, final ASSET.ParticipantType participant) { addParticipantToThisList(index, participant, _myVisibleParticipants); // and the complete list addParticipantToThisList(index, participant, _completeParticipantList); // fire new scenario event this.fireParticipantChanged(index, true); } /** * clear out the participants * */ public void emptyParticipants() { // get their indices Integer[] parts = getListOfParticipants(); for (int i = 0; i < parts.length; i++) { removeParticipant(parts[i]); } } /** * handle inserting a monte carlo participant * * @param index * @param participant */ public void addMonteCarloParticipant(int index, final ASSET.ParticipantType participant) { addParticipantToThisList(index, participant, _myInvisibleParticipants); // and the complete list addParticipantToThisList(index, participant, _completeParticipantList); // fire new scenario event this.fireParticipantChanged(index, true); } /** * remove the indicated participant */ public void removeParticipant(final int index) { final Object found = _completeParticipantList.remove(new Integer(index)); // fire new scenario event if (found != null) { // try to remove it from the other lists _myVisibleParticipants.remove(new Integer(index)); _myInvisibleParticipants.remove(new Integer(index)); // and fire the informant this.fireParticipantChanged(index, false); } } /** * Create a new Participant. The external client can then request the * Participant itself to perform any edits * * @param participant_type * the type of Participant the client wants * @return the id of the new Participant (or INVALID_ID for failure) */ public int createNewParticipant(final String participant_type) { // what we should do, is to create the scenario from the scenario type name, // using the specified scenario_type in the classloader // get the id int id = ASSET.Util.IdNumber.generateInt(); // create the correct type of participant ParticipantType newS = null; if (participant_type.equals(ASSET.Participants.Category.Type.SUBMARINE)) newS = new ASSET.Models.Vessels.SSN(id); else if (participant_type.equals(ASSET.Participants.Category.Type.FRIGATE)) { newS = new ASSET.Models.Vessels.Surface(id); newS.getCategory().setType(ASSET.Participants.Category.Type.FRIGATE); } else if (participant_type .equals(ASSET.Participants.Category.Type.DESTROYER)) { newS = new ASSET.Models.Vessels.Surface(id); newS.getCategory().setType(ASSET.Participants.Category.Type.DESTROYER); } else if (participant_type.equals("SSK")) newS = new ASSET.Models.Vessels.SSK(id); // check it worked if (newS != null) { // give it a default name newS.setName(participant_type + "_" + id); // add it addParticipant(id, newS); } else { MWC.Utilities.Errors.Trace.trace("Vessel type not matched"); id = INVALID_ID; } // return it's index return id; } /** * the detonation event itself * * @param loc * the location of the detonation * @param power * the strength of the detonation */ public void detonationAt(int WeaponID, final WorldLocation loc, double power) { // @@ CREATE EXPLOSION MODEL // see if any participants are within some explosion radius (500 yds) final double EXPLOSION_RADIUS = 500; // move the participants forward if (_completeParticipantList != null) { final java.util.Iterator<ParticipantType> iter = _completeParticipantList .values().iterator(); while (iter.hasNext()) { final NetworkParticipant pt = (NetworkParticipant) iter.next(); // how far away is it? final double rng_degs = pt.getStatus().getLocation().rangeFrom(loc); final double rng_yds = MWC.Algorithms.Conversions.Degs2Yds(rng_degs); if (rng_yds < EXPLOSION_RADIUS) { this._pendingDestruction.add(new Integer(pt.getId())); } } } } /** * method to add a new participant * * @param newPart * the new participant */ public void createParticipant(final ParticipantType newPart) { this._pendingCreation.add(newPart); } // testing for this class public static class ScenarioTest extends junit.framework.TestCase { static public final String TEST_ALL_TEST_TYPE = "UNIT"; public ScenarioTest(final String val) { super(val); } protected int stepCounter = 0; protected long lastTime = 0; protected Boolean lastStartState = null; protected int createdCounter = 0; protected int destroyedCounter = 0; protected class createdListener implements ParticipantsChangedListener { /** * the indicated participant has been added to the scenario */ public void newParticipant(int index) { createdCounter++; } /** * the indicated participant has been removed from the scenario */ public void participantRemoved(int index) { destroyedCounter++; } public void restart(ScenarioType scenario) { } } int newStepTime; protected class startStopListener implements ScenarioRunningListener { public void started() { lastStartState = new Boolean(true); } /** * the scenario has stopped running on auto */ public void paused() { // To change body of implemented methods use File | Settings | File // Templates. } public void finished(long elapsedTime, String reason) { lastStartState = new Boolean(false); } public void newScenarioStepTime(final int val) { newStepTime = val; } public void newStepTime(final int val) { newStepTime = val; } public void restart(ScenarioType scenario) { } } protected class stepListener implements ScenarioSteppedListener { public void step(ScenarioType scenario, final long newTime) { lastTime = newTime; stepCounter++; } public void restart(ScenarioType scenario) { } } public void testScenarioTimes() { final ScenarioType cs = new CoreScenario(); // listener final stepListener sl = new stepListener(); final startStopListener ssl = new startStopListener(); cs.addScenarioSteppedListener(sl); cs.addScenarioRunningListener(ssl); // step times cs.setStepTime(new Duration(5, Duration.SECONDS)); assertEquals("New step time", 5000, cs.getStepTime()); assertEquals("New step time event", 5000, newStepTime); cs.setScenarioStepTime(new Duration(4, Duration.SECONDS)); assertEquals("New scenario step time", 4000, cs.getScenarioStepTime()); assertEquals("New scenario step time event", 4000, newStepTime); cs.setStepTime(500); assertEquals("New step time", 500, cs.getStepTime()); assertEquals("New step time event", 500, newStepTime); cs.setScenarioStepTime(1000); assertEquals("New scenario step time", 1000, cs.getScenarioStepTime()); assertEquals("New scenario step time event", 1000, newStepTime); // current time cs.setTime(100); assertEquals("set time", 100, cs.getTime()); // stepping - firing zero time event first cs.step(); assertEquals("fired at zero time", 100, cs.getTime()); // stepping cs.step(); assertEquals("first step", 1100, cs.getTime()); cs.step(); assertEquals("second step", 2100, cs.getTime()); assertEquals("second step message", 2100, lastTime); assertEquals("step message count", 3, stepCounter); // start // time step interval cs.setStepTime(1000); // reset the step counter stepCounter = 0; // check our listener is prepped assertNull("Start-Stop listener is ready", lastStartState); System.out.println("about to start timed steps"); long tStart = System.currentTimeMillis(); cs.start(); assertTrue("Start message sent", (lastStartState.booleanValue() == true)); while (stepCounter < 3) { try { Thread.sleep(100); } catch (java.lang.InterruptedException e) { e.printStackTrace(); } } long tEnd = System.currentTimeMillis(); System.out.println("finished timed steps"); CoreScenario coreS = (CoreScenario) cs; assertEquals("Stop not pending yet", null, coreS._stopReason); cs.stop("testing"); assertTrue("Stop message sent but not processed", (lastStartState.booleanValue() == true)); assertNotNull("Stop message sent but not processed", coreS._stopReason); // insert a step, so the stop can be processed cs.step(); assertTrue("Stop message sent", (lastStartState.booleanValue() == false)); long tDiff = tEnd - tStart; // check time elapsed assertTrue("timer actually ran: time was:" + tDiff, (tDiff >= 1000)); assertTrue("timer didn't take too long" + tDiff, (tDiff < 2300)); // running on auto! cs.setStepTime(0); cs.setScenarioStepTime(5); cs.setTime(0); tStart = System.currentTimeMillis(); // reset the step counter stepCounter = 0; // check our listener is prepped lastStartState = null; assertNull("Start-Stop listener is ready", lastStartState); // get going cs.start(); assertTrue("Start message sent", (lastStartState.booleanValue() == true)); while (stepCounter < 100) { try { Thread.sleep(1); } catch (java.lang.InterruptedException e) { e.printStackTrace(); } } cs.stop("testing"); tEnd = System.currentTimeMillis(); cs.step(); assertTrue("Stop message sent", (lastStartState.booleanValue() == false)); // how long? tDiff = tEnd - tStart; // check time elapsed // hack: suspect both of these test should allow zero error. // assertEquals("steps got performed", 140, stepCounter, 40); // assertEquals("scenario moved forward", 600, cs.getTime(), 100); // stop // - this has already been tested // reset } public void testScenarioParticipants() { // initialise our test counters createdCounter = 0; destroyedCounter = 0; // create server final ScenarioType srv = new CoreScenario(); // add as listener final createdListener cl = new createdListener(); srv.addParticipantsChangedListener(cl); // create new scenarios // final int s1 = srv.createNewParticipant("SUBMARINE"); final int s2 = srv.createNewParticipant("FRIGATE"); // now stop listening for these events srv.removeParticipantsChangedListener(cl); // add another, which we shouldn't hear about final int s3 = srv.createNewParticipant("DESTROYER"); // check events got fired assertEquals("count of created events (one ignored)", 1, createdCounter); assertEquals("count of destroyed events", destroyedCounter, 0); // get list of scenarios final Integer[] res = srv.getListOfParticipants(); assertEquals("Wrong number of participants", res.length, 2); // get specific scenarios final ParticipantType sc2 = srv.getThisParticipant(s2); assertTrue("participant returned", sc2 != null); if (sc2 == null) return; // make edits sc2.setName("participant 2"); final ParticipantType sc3 = srv.getThisParticipant(s3); sc3.setName("participant 3"); // re-retrieve this scenario to check we're getting the correct one final NetworkParticipant sc2a = srv.getThisParticipant(s2); assertEquals("correct name", sc2a.getName(), "participant 2"); // check we can remove a participant // , but check the length first final int len = srv.getListOfParticipants().length; srv.removeParticipant(s2); // check the length assertEquals("check participant removed", len - 1, srv.getListOfParticipants().length); // check invalid scenario indices NetworkParticipant dd = srv.getThisParticipant(1000); assertEquals("invalid index", dd, null); dd = srv.getThisParticipant(0); assertEquals("invalid index", dd, null); } public void testMonteCarloRunning() { SSN ssn_A = new SSN(12); SSN ssn_B = new SSN(13); SSN ssn_C = new SSN(14); SSN ssn_D = new SSN(15); Status theStat = new Status(12, 0); WorldLocation theLoc = new WorldLocation(1, 1, 1); theStat.setSpeed(new WorldSpeed(12, WorldSpeed.Kts)); theStat.setLocation(theLoc); ssn_A.setStatus(theStat); ssn_B.setStatus(theStat); ssn_C.setStatus(theStat); ssn_D.setStatus(theStat); CoreScenario scen = new CoreScenario(); scen.addParticipant(ssn_A.getId(), ssn_A); scen.addParticipant(ssn_B.getId(), ssn_B); scen.addMonteCarloParticipant(ssn_C.getId(), ssn_C); scen.addMonteCarloParticipant(ssn_D.getId(), ssn_D); final Vector<Integer> aDetections = new Vector<Integer>(0, 1); final Vector<Integer> dDetections = new Vector<Integer>(0, 1); ssn_A.getRadiatedChars().add(EnvironmentType.BROADBAND_PASSIVE, new ASSET.Models.Mediums.BroadbandRadNoise(99)); ssn_B.getRadiatedChars().add(EnvironmentType.BROADBAND_PASSIVE, new ASSET.Models.Mediums.BroadbandRadNoise(99)); ssn_C.getRadiatedChars().add(EnvironmentType.BROADBAND_PASSIVE, new ASSET.Models.Mediums.BroadbandRadNoise(99)); ssn_D.getRadiatedChars().add(EnvironmentType.BROADBAND_PASSIVE, new ASSET.Models.Mediums.BroadbandRadNoise(99)); ssn_A.addSensor(new BroadbandSensor(12) { private static final long serialVersionUID = 1L; // what is the detection strength for this target? protected DetectionEvent detectThis(EnvironmentType environment, ParticipantType host, ParticipantType target, long time, ScenarioType scenario) { aDetections.add(new Integer(target.getId())); return null; } }); ssn_D.addSensor(new BroadbandSensor(19) { private static final long serialVersionUID = 1L; // what is the detection strength for this target? protected DetectionEvent detectThis(EnvironmentType environment, ParticipantType host, ParticipantType target, long time, ScenarioType scenario) { dDetections.add(new Integer(target.getId())); return null; } }); scen.setScenarioStepTime(1000); scen.step(); // ok, check that the correct participants were informed about what's // going on assertEquals("we were only told about B", aDetections.size(), 1); Integer firstEle = (Integer) aDetections.firstElement(); assertEquals("we were only told about B", firstEle.intValue(), 13, 0); // and for the other track assertEquals("we were only told about B", dDetections.size(), 2); Integer firstIndex = new Integer(12); Integer secondIndex = new Integer(13); assertTrue(" we were informed about A", dDetections.contains(firstIndex)); assertTrue(" we were informed about B", dDetections.contains(secondIndex)); } public void testMonteCarloCreation() { CoreScenario scen = new CoreScenario(); SSN ssn_A = new SSN(12); SSN ssn_B = new SSN(13); SSN ssn_C = new SSN(14); SSN ssn_D = new SSN(15); Status theStat = new Status(12, 0); WorldLocation theLoc = new WorldLocation(1, 1, 1); theStat.setSpeed(new WorldSpeed(12, WorldSpeed.Kts)); theStat.setLocation(theLoc); ssn_A.setStatus(theStat); ssn_B.setStatus(theStat); ssn_C.setStatus(theStat); ssn_D.setStatus(theStat); // check empty, etc assertEquals("first list done", 0, scen._completeParticipantList.size()); assertEquals("second list done", 0, scen._myInvisibleParticipants.size()); assertEquals("third list done", 0, scen._myVisibleParticipants.size()); scen.addParticipant(ssn_A.getId(), ssn_A); assertEquals("first list done", 1, scen._completeParticipantList.size()); assertEquals("second list done", 0, scen._myInvisibleParticipants.size()); assertEquals("third list done", 1, scen._myVisibleParticipants.size()); scen.addParticipant(ssn_B.getId(), ssn_B); assertEquals("first list done", 2, scen._completeParticipantList.size()); assertEquals("second list done", 0, scen._myInvisibleParticipants.size()); assertEquals("third list done", 2, scen._myVisibleParticipants.size()); scen.addMonteCarloParticipant(ssn_C.getId(), ssn_C); assertEquals("first list done", 3, scen._completeParticipantList.size()); assertEquals("second list done", 1, scen._myInvisibleParticipants.size()); assertEquals("third list done", 2, scen._myVisibleParticipants.size()); scen.addMonteCarloParticipant(ssn_D.getId(), ssn_D); assertEquals("first list done", 4, scen._completeParticipantList.size()); assertEquals("second list done", 2, scen._myInvisibleParticipants.size()); assertEquals("third list done", 2, scen._myVisibleParticipants.size()); // now try deleting them scen.removeParticipant(13); assertEquals("first list done", 3, scen._completeParticipantList.size()); assertEquals("second list done", 2, scen._myInvisibleParticipants.size()); assertEquals("third list done", 1, scen._myVisibleParticipants.size()); scen.removeParticipant(15); assertEquals("first list done", 2, scen._completeParticipantList.size()); assertEquals("second list done", 1, scen._myInvisibleParticipants.size()); assertEquals("third list done", 1, scen._myVisibleParticipants.size()); } } public static void main(String[] args) { ScenarioTest stt = new ScenarioTest("happy"); stt.testScenarioTimes(); } public Layer getBackdrop() { return _myBackdrop; } public void setBackdrop(BaseLayer layer) { _myBackdrop = layer; } public void stop() { } /** * store the specified display setting * * @param key * @param value */ public void addDisplaySetting(final String key, final String value) { _displaySettings.put(key, value); } public String getDisplaySettingFor(final String key) { return _displaySettings.get(key); } }
package org.openhab.binding.swegonventilation.internal; import java.util.Dictionary; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.xml.bind.DatatypeConverter; import org.apache.commons.lang.StringUtils; import org.openhab.binding.swegonventilation.SwegonVentilationBindingProvider; import org.openhab.binding.swegonventilation.protocol.SwegonVentilationConnector; import org.openhab.binding.swegonventilation.protocol.SwegonVentilationDataParser; import org.openhab.binding.swegonventilation.protocol.SwegonVentilationSerialConnector; import org.openhab.binding.swegonventilation.protocol.SwegonVentilationSimulator; import org.openhab.binding.swegonventilation.protocol.SwegonVentilationUDPConnector; import org.openhab.core.binding.AbstractBinding; import org.openhab.core.events.EventPublisher; import org.openhab.core.items.Item; import org.openhab.core.library.items.NumberItem; import org.openhab.core.library.items.SwitchItem; import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.OnOffType; import org.openhab.core.types.State; import org.openhab.core.types.UnDefType; import org.osgi.service.cm.ConfigurationException; import org.osgi.service.cm.ManagedService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * Binding to receive data from Swegon ventilation system. * * @author Pauli Anttila * @since 1.4.0 */ public class SwegonVentilationBinding extends AbstractBinding<SwegonVentilationBindingProvider> implements ManagedService { private static final Logger logger = LoggerFactory .getLogger(SwegonVentilationBinding.class); /* configuration variables for communication */ private int udpPort = 9998; private String serialPort = null; private boolean simulator = false; /** Thread to handle messages from heat pump */ private MessageListener messageListener = null; public SwegonVentilationBinding() { } public void activate() { logger.debug("Activate"); } public void deactivate() { logger.debug("Deactivate"); if (messageListener != null) { messageListener.setInterrupted(true); } } public void setEventPublisher(EventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } public void unsetEventPublisher(EventPublisher eventPublisher) { this.eventPublisher = null; } /** * @{inheritDoc */ @Override public void updated(Dictionary<String, ?> config) throws ConfigurationException { logger.debug("Configuration updated, config {}", config != null ? true : false); if (config != null) { String portString = (String) config.get("udpPort"); if (StringUtils.isNotBlank(portString)) { udpPort = Integer.parseInt(portString); } serialPort = (String) config.get("serialPort"); String simulateString = (String) config.get("simulate"); if (StringUtils.isNotBlank(simulateString)) { simulator = Boolean.parseBoolean(simulateString); } } if (messageListener != null) { logger.debug("Close previous message listener"); messageListener.setInterrupted(true); try { messageListener.join(); } catch (InterruptedException e) { logger.info("Previous message listener closing interrupted", e); } } messageListener = new MessageListener(); messageListener.start(); } /** * Convert device value to OpenHAB state. * * @param itemType * @param value * * @return a {@link State} */ private State convertDeviceValueToOpenHabState(Class<? extends Item> itemType, Integer value) { State state = UnDefType.UNDEF; try { if (itemType == SwitchItem.class) { state = value == 0 ? OnOffType.OFF : OnOffType.ON; } else if (itemType == NumberItem.class) { state = new DecimalType(value); } } catch (Exception e) { logger.debug("Cannot convert value '{}' to data type {}", value, itemType); } return state; } /** * The MessageListener runs as a separate thread. * * Thread listening message from Swegon ventilation system and send updates * to openHAB bus. * */ private class MessageListener extends Thread { private boolean interrupted = false; MessageListener() { } public void setInterrupted(boolean interrupted) { this.interrupted = interrupted; this.interrupt(); } @Override public void run() { logger.debug("Swegon ventilation system message listener started"); SwegonVentilationConnector connector; if (simulator == true) connector = new SwegonVentilationSimulator(); else if (serialPort != null) connector = new SwegonVentilationSerialConnector(serialPort); else connector = new SwegonVentilationUDPConnector(udpPort); try { connector.connect(); } catch (SwegonVentilationException e) { logger.error( "Error occured when connecting to Swegon ventilation system", e); logger.warn("Closing Swegon ventilation system message listener"); // exit interrupted = true; } // as long as no interrupt is requested, continue running while (!interrupted) { try { // Wait a packet (blocking) byte[] data = connector.receiveDatagram(); logger.trace("Received data (len={}): {}", data.length, DatatypeConverter.printHexBinary(data)); HashMap<SwegonVentilationCommandType, Integer> regValues = SwegonVentilationDataParser .parseData(data); if (regValues != null) { logger.debug("regValues (len={}): {}", regValues.size(), regValues); Set<Map.Entry<SwegonVentilationCommandType, Integer>> set = regValues .entrySet(); for (Entry<SwegonVentilationCommandType, Integer> val : set) { SwegonVentilationCommandType cmdType = val.getKey(); Integer value = val.getValue(); for (SwegonVentilationBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { SwegonVentilationCommandType commandType = provider .getCommandType(itemName); if (commandType.equals(cmdType)) { Class<? extends Item> itemType = provider.getItemType(itemName); org.openhab.core.types.State state = convertDeviceValueToOpenHabState(itemType, value); eventPublisher.postUpdate(itemName, state); } } } } } } catch (SwegonVentilationException e) { logger.error( "Error occured when received data from Swegon ventilation system", e); } } try { connector.disconnect(); } catch (SwegonVentilationException e) { logger.error( "Error occured when disconnecting form Swegon ventilation system", e); } } } }
package examples.performance; import com.vtence.molecule.WebServer; import com.vtence.molecule.middlewares.Compressor; import com.vtence.molecule.middlewares.ConditionalGet; import com.vtence.molecule.middlewares.ContentLengthHeader; import com.vtence.molecule.middlewares.ETag; import com.vtence.molecule.middlewares.FileServer; import com.vtence.molecule.middlewares.StaticAssets; import com.vtence.molecule.templating.JMustacheRenderer; import com.vtence.molecule.templating.Template; import com.vtence.molecule.templating.Templates; import com.vtence.molecule.testing.ResourceLocator; import java.io.File; import java.io.IOException; import java.time.Clock; import static com.vtence.molecule.http.HeaderNames.CACHE_CONTROL; import static com.vtence.molecule.http.HeaderNames.CONTENT_TYPE; import static com.vtence.molecule.http.HeaderNames.LAST_MODIFIED; import static com.vtence.molecule.http.MimeTypes.CSS; import static com.vtence.molecule.http.MimeTypes.HTML; import static com.vtence.molecule.http.MimeTypes.JAVASCRIPT; public class CachingAndCompressionExample { private static final Void NO_CONTEXT = null; private final Clock clock; public CachingAndCompressionExample(Clock clock) { this.clock = clock; } public void run(WebServer server) throws IOException { // We serve files located under the examples/fox directory. File content = ResourceLocator.locateOnClasspath("examples/fox"); // Setup the file server with a cache directive of public; max-age=60 FileServer files = new FileServer(content).header(CACHE_CONTROL, "public; max-age=60"); // For requests paths starting with /css, /js and /images, we serve static assets StaticAssets assets = new StaticAssets(files).serve("/css", "/js", "/images"); // For other requests, we'll serve web pages. // Our web pages are Mustache templates with an .html extension Templates templates = new Templates(new JMustacheRenderer().fromDir(content).extension("html")); // This is our index.html template final Template<Void> index = templates.named("index"); // Add Content-Length header to the response when size of content is known server.add(new ContentLengthHeader()) // Make GET and HEAD requests conditional to freshness of client stored representation. // This is the validation model .add(new ConditionalGet()) // Add an ETag header if response has no freshness information. // This is the case for dynamic content, but static files have a Last-Modified header. .add(new ETag()) // Compress text response bodies (js, css, html but not images) .add(new Compressor().compressibleTypes(JAVASCRIPT, CSS, HTML)) // We serve static assets with freshness information. This is the expiration model. .add(assets) // If client is not requesting a static file, we'll serve our index.html mustache template .start((request, response) -> { response.header(CONTENT_TYPE, HTML); // We add freshness information only when query parameter 'conditional' is present if (request.parameter("conditional") != null) { response.header(LAST_MODIFIED, clock.instant()); } // This will render our index.html template response.done(index.render(NO_CONTEXT)); }); } public static void main(String[] args) throws IOException { CachingAndCompressionExample example = new CachingAndCompressionExample(Clock.systemDefaultZone()); WebServer webServer = WebServer.create(); example.run(webServer); // Try accessing /?conditional then / to get a 304 System.out.println("Access at " + webServer.uri()); } }
package com.google.teampot.api; import java.util.List; import com.google.teampot.api.exception.EntityNotFoundException; import com.google.teampot.api.exception.ProjectExistsException; import com.google.teampot.model.Project; import com.google.teampot.model.User; import com.google.teampot.service.ProjectService; import com.google.teampot.service.UserService; import com.google.api.server.spi.config.ApiMethod; import com.google.api.server.spi.config.ApiMethod.HttpMethod; import com.google.api.server.spi.config.Named; import com.google.api.server.spi.response.UnauthorizedException; import com.google.appengine.api.oauth.OAuthRequestException; public class ProjectEndpoint extends BaseEndpoint{ private static ProjectService projectService = ProjectService.getInstance(); private static UserService userService = UserService.getInstance(); @ApiMethod( name = "project.list", path = "project", httpMethod = HttpMethod.GET ) public List<Project> list(com.google.appengine.api.users.User gUser) throws OAuthRequestException, UnauthorizedException { userService.ensureEnabled(gUser); User user = userService.getUser(gUser); return projectService.listForUser(user); } @ApiMethod( name = "project.listAll", path = "project/all", httpMethod = HttpMethod.GET ) public List<Project> listAll(com.google.appengine.api.users.User gUser) throws OAuthRequestException, UnauthorizedException { userService.ensureEnabled(gUser); return projectService.list(); } @ApiMethod( name = "project.get", path = "project/{id}", httpMethod = HttpMethod.GET ) public Project get(@Named("id") String id, com.google.appengine.api.users.User gUser) throws OAuthRequestException,EntityNotFoundException, UnauthorizedException { userService.ensureEnabled(gUser); Project entity = projectService.get(id); if (entity != null) return entity; else throw new EntityNotFoundException(id); } @ApiMethod( name = "project.save", path = "project", httpMethod = HttpMethod.POST ) public Project save(Project entity, com.google.appengine.api.users.User gUser) throws OAuthRequestException, ProjectExistsException, UnauthorizedException { userService.ensureEnabled(gUser); projectService.save(entity,userService.getUser(gUser)); return entity; } @ApiMethod( name = "project.remove", path = "project/{id}", httpMethod = HttpMethod.DELETE ) public void remove(@Named("id") String id, com.google.appengine.api.users.User gUser) throws OAuthRequestException, UnauthorizedException { userService.ensureEnabled(gUser); projectService.remove(id); } @ApiMethod( name = "project.addMember", path = "project/{id}/addmember/{memberEmail}", httpMethod = HttpMethod.POST ) public User addMember(@Named("id") String id, @Named("memberEmail") String memberEmail, com.google.appengine.api.users.User gUser) throws OAuthRequestException, UnauthorizedException { userService.ensureEnabled(gUser); User member; User user = userService.getUser(gUser); Project entity = projectService.get(id); if (!userService.isUserProvisioned(memberEmail)) { member = new User(memberEmail); UserService.getInstance().provisionProfile(user, member); } else { member = userService.getUser(memberEmail); } projectService.addMember(entity, member, user); return member; } @ApiMethod( name = "project.removeMember", path = "project/{id}/removemember/{memberEmail}", httpMethod = HttpMethod.POST ) public User removeMember(@Named("id") String id, @Named("memberEmail") String memberEmail, com.google.appengine.api.users.User gUser) throws OAuthRequestException, UnauthorizedException { userService.ensureEnabled(gUser); User member = userService.getUser(memberEmail); User user = userService.getUser(gUser); Project entity = projectService.get(id); projectService.removeMember(entity, member, user); return member; } }
package org.bitbucket.nanojava.data; import java.io.ByteArrayOutputStream; import org.bitbucket.nanojava.data.measurement.EndPoints; import org.bitbucket.nanojava.data.measurement.ErrorlessMeasurementValue; import org.bitbucket.nanojava.inchi.NInChIGenerator; import org.bitbucket.nanojava.io.CDKSerializer; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import org.xmlcml.cml.element.CMLMoleculeList; import com.github.jqudt.onto.units.LengthUnit; import nu.xom.Document; import nu.xom.Serializer; public class NanoInChIExamplesTest { @Ignore("Known to fail") @Test public void figureEightLeft() throws Exception { Material material = MaterialBuilder.type("METALOXIDE") .label("silica nanoparticles with gold coating") .componentFromSMILES(1, "[Au]", "SHELL") .componentFromSMILES(2, "O=[Si]=O", "SPHERE") .asMaterial(); String nanoInChI = NInChIGenerator.generator(material); Assert.assertEquals("InChI=1A/Au/msh/s2t-9!O2Si/c1-3-2/msp/s20d-9/k000/y2&1", nanoInChI); CMLMoleculeList cmlMaterial = CDKSerializer.toCML(material); Assert.assertNotNull(cmlMaterial); System.out.println(asIndentedString(cmlMaterial)); } @Test public void simpleGoldParticle() throws Exception { Material material = MaterialBuilder.type("METAL") .componentFromSMILES(1, "[Au]", "SPHERE", new ErrorlessMeasurementValue(EndPoints.DIAMETER, 3.0, LengthUnit.NM)) .asMaterial(); String nanoInChI = NInChIGenerator.generator(material); Assert.assertEquals("InChI=1A/Au/msp/s3d-9/y1", nanoInChI); CMLMoleculeList cmlMaterial = CDKSerializer.toCML(material); Assert.assertNotNull(cmlMaterial); System.out.println(asIndentedString(cmlMaterial)); } private String asIndentedString(CMLMoleculeList cmlMaterial) throws Exception { ByteArrayOutputStream output = new ByteArrayOutputStream(); Serializer xomSerializer = new Serializer(output, "UTF-8"); xomSerializer.setIndent(2); xomSerializer.write(new Document(cmlMaterial)); return output.toString(); } }
package com.hamishrickerby.http_server; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Headers { private static String HEADER_SEPARATOR = ": "; Map<String, String> headers; public Headers() { headers = new HashMap<>(); } public List<String> list() { return headers.keySet().stream() .map(key -> key + HEADER_SEPARATOR + headers.get(key)) .collect(Collectors.toList()); } public void put(String key, String value) { headers.put(key, value); } public void parse(String headerString) { String[] lines = headerString.split("\r\n"); for (String line : Arrays.asList(lines)) { String[] components = line.split(":"); put(components[0].trim(), components[1].trim()); } } public String get(String key) { return headers.getOrDefault(key, ""); } }
package net.cherokeedictionary.lyx; import org.apache.commons.lang3.StringUtils; public class EnglishCherokee implements Comparable<EnglishCherokee>{ private String english; public EnglishCherokee() { } public EnglishCherokee(EnglishCherokee ec) { this.english=ec.english; this.pronounce=ec.pronounce; this.syllabary=ec.syllabary; this.toLabel=ec.toLabel; } public void setEnglish(String english) { this.english = english; } public String getDefinition() { String eng=english; if (eng.endsWith(".")) { eng=StringUtils.left(eng, eng.length()-1); } eng = transform(eng); if (eng.startsWith("(")) { String sub = StringUtils.substringBetween(eng, "(", ")"); eng = StringUtils.substringAfter(eng, "("+sub+")"); eng += " "+"("+sub+")"; } eng=transform(eng); if (eng.endsWith(",")) { eng=StringUtils.left(eng, eng.length()-1); } return eng; } public String syllabary; public String pronounce; public int toLabel; public String getLyxCode(boolean bold) { StringBuilder sb = new StringBuilder(); String eng = StringUtils.strip(getDefinition().replace("\\n", " ")); if (bold) { sb.append("\\begin_layout Standard\n"); sb.append("\\series bold\n"); sb.append(eng); sb.append("\n"); sb.append("\\series default\n"); } else { sb.append("\\begin_layout Standard\n"); sb.append(eng); } sb.append(": "); sb.append(syllabary); sb.append(" ["); sb.append(pronounce); sb.append("]"); sb.append(" (page "); sb.append("\\begin_inset CommandInset ref\n" + "LatexCommand pageref\n" + "reference \""); sb.append(""+toLabel); sb.append("\"\n" + "\\end_inset\n"); sb.append(")\n"); sb.append("\\end_layout\n\n"); return sb.toString(); } private String transform(String eng) { eng = StringUtils.strip(eng); String lc = eng.toLowerCase(); if (lc.startsWith("n.")) { eng = StringUtils.substring(eng, 2); eng = StringUtils.strip(eng); lc = eng.toLowerCase(); } if (lc.startsWith("v. t.")) { eng = StringUtils.substring(eng, 5); eng = StringUtils.strip(eng); lc = eng.toLowerCase(); } if (lc.startsWith("v.t.")) { eng = StringUtils.substring(eng, 4); eng = StringUtils.strip(eng); lc = eng.toLowerCase(); } if (lc.startsWith("v. i.")) { eng = StringUtils.substring(eng, 5); eng = StringUtils.strip(eng); lc = eng.toLowerCase(); } if (lc.startsWith("v.i.")) { eng = StringUtils.substring(eng, 4); eng = StringUtils.strip(eng); lc = eng.toLowerCase(); } if (lc.startsWith("adv.")) { eng = StringUtils.substring(eng, 4); eng = StringUtils.strip(eng); lc = eng.toLowerCase(); } if (lc.startsWith("adj.")) { eng = StringUtils.substring(eng, 4); eng = StringUtils.strip(eng); lc = eng.toLowerCase(); } if (lc.contains(".") && lc.indexOf(".")<4 && !lc.startsWith("1")) { System.err.println("WARNING: BAD DEFINITION! => "+eng); } if (lc.startsWith("becoming ")) { eng = StringUtils.substring(eng, 9)+" (becoming)"; lc = eng.toLowerCase(); } chopper: { if (lc.startsWith("at the ")) { eng = StringUtils.substring(eng, 7)+" (at the)"; break chopper; } if (lc.startsWith("at a ")) { eng = StringUtils.substring(eng, 5)+" (at a)"; break chopper; } if (lc.startsWith("at ")) { eng = StringUtils.substring(eng, 3)+" (at)"; break chopper; } if (lc.startsWith("in the ")) { eng = StringUtils.substring(eng, 7)+" (in the)"; break chopper; } if (lc.startsWith("in a ")) { eng = StringUtils.substring(eng, 5)+" (in a)"; break chopper; } if (lc.startsWith("in ")) { eng = StringUtils.substring(eng, 3)+" (in)"; break chopper; } if (lc.startsWith("on the ")) { eng = StringUtils.substring(eng, 7)+" (on the)"; break chopper; } if (lc.startsWith("on a ")) { eng = StringUtils.substring(eng, 5)+" (on a)"; break chopper; } if (lc.startsWith("on ")) { eng = StringUtils.substring(eng, 3)+" (on)"; break chopper; } if (lc.startsWith("she's ")) { eng = StringUtils.substring(eng, 6); break chopper; } if (lc.startsWith("he/it is ")) { eng = StringUtils.substring(eng, 9); break chopper; } if (lc.startsWith("he, it's ")) { eng = StringUtils.substring(eng, 9); break chopper; } if (lc.startsWith("is ")) { eng = StringUtils.substring(eng, 3); break chopper; } if (lc.startsWith("the ")) { eng = StringUtils.substring(eng, 4); break chopper; } if (lc.startsWith("a ")) { eng = StringUtils.substring(eng, 2); break chopper; } if (lc.startsWith("an ")) { eng = StringUtils.substring(eng, 3); break chopper; } if (lc.startsWith("he's ")) { eng = StringUtils.substring(eng, 5); break chopper; } if (lc.startsWith("he is ")) { eng = StringUtils.substring(eng, 6); break chopper; } if (lc.startsWith("it's ")) { eng = StringUtils.substring(eng, 5); break chopper; } if (lc.startsWith("it is ")) { eng = StringUtils.substring(eng, 6); break chopper; } if (lc.startsWith("his, her")) { if (eng.length()<9) { break chopper; } eng = StringUtils.substring(eng, 8)+" (his/her)"; } if (lc.startsWith("its ")) { eng = StringUtils.substring(eng, 4)+" (its)"; break chopper; } if (lc.startsWith("his ")) { eng = StringUtils.substring(eng, 4)+" (his)"; break chopper; } if (lc.startsWith("her ")) { eng = StringUtils.substring(eng, 4)+" (her)"; break chopper; } if (lc.startsWith("he ")) { eng = StringUtils.substring(eng, 3); break chopper; } if (lc.startsWith("she ")) { eng = StringUtils.substring(eng, 4); break chopper; } if (lc.startsWith("it ")) { eng = StringUtils.substring(eng, 3); break chopper; } } return eng; } @Override public int compareTo(EnglishCherokee arg0) { String e1 = getDefinition(); String e2 = arg0.getDefinition(); int cmp = e1.compareToIgnoreCase(e2); if (cmp!=0) { return cmp; } cmp = e1.compareTo(e2); if (cmp!=0) { return cmp; } cmp = syllabary.compareTo(arg0.syllabary); if (cmp!=0) { return cmp; } cmp = pronounce.compareTo(arg0.pronounce); if (cmp!=0) { return cmp; } return toLabel-arg0.toLabel; } @Override public boolean equals(Object obj) { if (!(obj instanceof EnglishCherokee)) { return false; } return compareTo((EnglishCherokee)obj)==0; } }
package com.orientechnologies.orient.core.storage.impl.local.paginated; import com.orientechnologies.common.io.OFileUtils; import com.orientechnologies.orient.core.config.OGlobalConfiguration; import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import com.orientechnologies.orient.core.id.ORecordId; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OSchema; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery; import com.orientechnologies.orient.core.storage.OPhysicalPosition; import com.orientechnologies.orient.core.storage.OStorage; import com.orientechnologies.orient.server.OServer; import com.orientechnologies.orient.server.OServerMain; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicLong; import static org.assertj.core.api.Assertions.assertThat; /** * @author Andrey Lomakin * @since 6/26/13 */ public class LocalPaginatedStorageSmallCacheBigRecordsCrashRestoreIT { private final AtomicLong idGen = new AtomicLong(); private ODatabaseDocumentTx baseDocumentTx; private ODatabaseDocumentTx testDocumentTx; private File buildDir; private ExecutorService executorService = Executors.newCachedThreadPool(); private Process process; public void spawnServer() throws Exception { String buildDirectory = System.getProperty("buildDirectory", "."); buildDirectory += "/localPaginatedStorageSmallCacheBigRecordsCrashRestore"; buildDir = new File(buildDirectory); if (buildDir.exists()) OFileUtils.deleteFolderIfEmpty(buildDir); buildDir.mkdir(); String javaExec = System.getProperty("java.home") + "/bin/java"; System.setProperty("ORIENTDB_HOME", buildDirectory); ProcessBuilder processBuilder = new ProcessBuilder(javaExec, "-Xmx2048m", "-classpath", System.getProperty("java.class.path"), "-DORIENTDB_HOME=" + buildDirectory, RemoteDBRunner.class.getName()); processBuilder.inheritIO(); process = processBuilder.start(); Thread.sleep(5000); } @After public void tearDown() { testDocumentTx.activateOnCurrentThread(); testDocumentTx.drop(); baseDocumentTx.activateOnCurrentThread(); baseDocumentTx.drop(); OFileUtils.deleteRecursively(buildDir); Assert.assertFalse(buildDir.exists()); } @Before public void setuUp() throws Exception { spawnServer(); baseDocumentTx = new ODatabaseDocumentTx( "plocal:" + buildDir.getAbsolutePath() + "/baseLocalPaginatedStorageSmallCacheBigRecordsCrashRestore"); if (baseDocumentTx.exists()) { baseDocumentTx.open("admin", "admin"); baseDocumentTx.drop(); } baseDocumentTx.create(); testDocumentTx = new ODatabaseDocumentTx("remote:localhost:3500/testLocalPaginatedStorageSmallCacheBigRecordsCrashRestore"); testDocumentTx.open("admin", "admin"); } @Test public void testDocumentCreation() throws Exception { createSchema(baseDocumentTx); createSchema(testDocumentTx); List<Future> futures = new ArrayList<Future>(); for (int i = 0; i < 1; i++) { futures.add(executorService.submit(new DataPropagationTask(baseDocumentTx, testDocumentTx))); } System.out.println("Wait for 5 minutes"); TimeUnit.MINUTES.sleep(1); long lastTs = System.currentTimeMillis(); process.destroy(); process.waitFor(); System.out.println("OrientDB server process was destroyed"); for (Future future : futures) { try { future.get(); } catch (Exception e) { e.printStackTrace(); } } testDocumentTx = new ODatabaseDocumentTx( "plocal:" + buildDir.getAbsolutePath() + "/testLocalPaginatedStorageSmallCacheBigRecordsCrashRestore"); testDocumentTx.open("admin", "admin"); testDocumentTx.close(); testDocumentTx.open("admin", "admin"); compareDocuments(lastTs); } private void createSchema(ODatabaseDocumentTx dbDocumentTx) { ODatabaseRecordThreadLocal.INSTANCE.set(dbDocumentTx); OSchema schema = dbDocumentTx.getMetadata().getSchema(); if (!schema.existsClass("TestClass")) { OClass testClass = schema.createClass("TestClass"); testClass.createProperty("id", OType.LONG); testClass.createProperty("timestamp", OType.LONG); testClass.createProperty("stringValue", OType.STRING); testClass.createProperty("binaryValue", OType.BINARY); testClass.createIndex("idIndex", OClass.INDEX_TYPE.UNIQUE, "id"); schema.save(); } } private void compareDocuments(long lastTs) { long minTs = Long.MAX_VALUE; baseDocumentTx.activateOnCurrentThread(); int clusterId = baseDocumentTx.getClusterIdByName("TestClass"); OStorage baseStorage = baseDocumentTx.getStorage(); OPhysicalPosition[] physicalPositions = baseStorage.ceilingPhysicalPositions(clusterId, new OPhysicalPosition(0)); int recordsRestored = 0; int recordsTested = 0; while (physicalPositions.length > 0) { final ORecordId rid = new ORecordId(clusterId); for (OPhysicalPosition physicalPosition : physicalPositions) { rid.clusterPosition = physicalPosition.clusterPosition; baseDocumentTx.activateOnCurrentThread(); ODocument baseDocument = baseDocumentTx.load(rid); testDocumentTx.activateOnCurrentThread(); List<ODocument> testDocuments = testDocumentTx .query(new OSQLSynchQuery<ODocument>("select from TestClass where id = " + baseDocument.field("id"))); if (testDocuments.size() == 0) { if (((Long) baseDocument.field("timestamp")) < minTs) { minTs = baseDocument.field("timestamp"); } } else { ODocument testDocument = testDocuments.get(0); System.out.println("testing id:: " + testDocument.field("id")); assertThat(testDocument.field("id")).as("id:: %s", testDocument.field("id")).isEqualTo(baseDocument.field("id")); assertThat(testDocument.field("timestamp")).as("documents:: %s - %s", testDocument, baseDocument) .isEqualTo(baseDocument.field("timestamp")); assertThat(testDocument.field("stringValue")).as("id:: %s", testDocument.field("id")) .isEqualTo(baseDocument.field("stringValue")); assertThat(testDocument.field("binaryValue")).as("id:: %s", testDocument.field("id")) .isEqualTo(baseDocument.field("binaryValue")); recordsRestored++; } recordsTested++; if (recordsTested % 10000 == 0) System.out.println(recordsTested + " were tested, " + recordsRestored + " were restored ..."); } physicalPositions = baseStorage.higherPhysicalPositions(clusterId, physicalPositions[physicalPositions.length - 1]); } System.out.println( recordsRestored + " records were restored. Total records " + recordsTested + ". Max interval for lost records " + (lastTs - minTs)); } public static final class RemoteDBRunner { public static void main(String[] args) throws Exception { OGlobalConfiguration.DISK_CACHE_SIZE.setValue(512); OServer server = OServerMain.create(); server.startup(RemoteDBRunner.class .getResourceAsStream("/com/orientechnologies/orient/core/storage/impl/local/paginated/db-create-big-records-config.xml")); server.activate(); } } public class DataPropagationTask implements Callable<Void> { private ODatabaseDocumentTx baseDB; private ODatabaseDocumentTx testDB; public DataPropagationTask(ODatabaseDocumentTx baseDB, ODatabaseDocumentTx testDocumentTx) { this.baseDB = new ODatabaseDocumentTx(baseDB.getURL()); this.testDB = new ODatabaseDocumentTx(testDocumentTx.getURL()); } @Override public Void call() throws Exception { Random random = new Random(); baseDB.open("admin", "admin"); testDB.open("admin", "admin"); try { while (true) { final ODocument document = new ODocument("TestClass"); document.field("id", idGen.getAndIncrement()); document.field("timestamp", System.currentTimeMillis()); document.field("stringValue", "sfe" + random.nextLong()); byte[] binaryValue = new byte[random.nextInt(2 * 65536) + 65537]; random.nextBytes(binaryValue); document.field("binaryValue", binaryValue); saveDoc(document); } } finally { baseDB.activateOnCurrentThread(); baseDB.close(); testDB.activateOnCurrentThread(); testDB.close(); } } private void saveDoc(ODocument document) { baseDB.activateOnCurrentThread(); ODocument testDoc = new ODocument(); document.copyTo(testDoc); document.save(); testDB.activateOnCurrentThread(); testDoc.save(); } } }
package org.mvel.tests.perftests; import junit.framework.TestCase; import org.mvel.ExpressionParser; import static org.mvel.ExpressionParser.compileExpression; import org.mvel.integration.impl.MapVariableResolverFactory; import org.mvel.tests.main.CompiledUnitTest; import org.mvel.tests.main.res.Bar; import org.mvel.tests.main.res.Base; import org.mvel.tests.main.res.Foo; import java.util.HashMap; import java.util.Map; public class CompiledPerformanceTests extends TestCase { protected Foo foo = new Foo(); protected Map<String, Object> map = new HashMap<String, Object>(); protected Base base = new Base(); public CompiledPerformanceTests() { foo.setBar(new Bar()); map.put("foo", foo); map.put("a", null); map.put("b", null); map.put("c", "cat"); map.put("BWAH", ""); map.put("misc", new CompiledUnitTest.MiscTestClass()); map.put("pi", "3.14"); map.put("hour", "60"); map.put("zero", 0); } public void testToListBenchmark() { String text = "misc.toList(foo.bar.name, 'hello', 42, ['key1' : 'value1', c : [ foo.bar.age, 'car', 42 ]], [42, [c : 'value1']] )"; MapVariableResolverFactory variableTable = new MapVariableResolverFactory(map); variableTable.pack(); ExpressionParser ep = new ExpressionParser(); ep.setCompiledStatement(compileExpression(text)); ep.setVariableResolverFactory(variableTable); for (int i = 0; i < 100000000; i++) { ep.executeFast(); } } public void testToListBenchmark2() { testToListBenchmark(); } public void testToListBenchmark3() { testToListBenchmark(); } }
package com.italk2learn.bo; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.RestTemplate; import com.italk2learn.bo.inter.ISpeechRecognitionBO; import com.italk2learn.dao.inter.IAudioStreamDAO; import com.italk2learn.exception.ITalk2LearnException; import com.italk2learn.speech.util.EnginesMap; import com.italk2learn.vo.ASRInstanceVO; import com.italk2learn.vo.AudioRequestVO; import com.italk2learn.vo.AudioResponseVO; import com.italk2learn.vo.SpeechRecognitionRequestVO; import com.italk2learn.vo.SpeechRecognitionResponseVO; @Service("speechRecognitionBO") @Transactional(rollbackFor = { ITalk2LearnException.class, ITalk2LearnException.class }) public class SpeechRecognitionBO implements ISpeechRecognitionBO { private static final Logger logger = LoggerFactory.getLogger(SpeechRecognitionBO.class); private static final int NUM_SECONDS = 30 * 1000; @Autowired private RestTemplate restTemplate; public IAudioStreamDAO audioStreamDAO; private byte[] audio=new byte[0]; //Store all audio in current exercise private byte[] audioExercise=new byte[0]; private EnginesMap em= EnginesMap.getInstance(); private int SEQ=0; //524288 each 5 seconds //12 times per minute private static final int SIZE_AUDIO_2MINUTES = 2 * 12 * 524288; private static final int SIZE_AUDIO_10MINUTES = 10 * 12 * 524288; @Autowired public SpeechRecognitionBO(IAudioStreamDAO audioStreamDAO) { this.audioStreamDAO = audioStreamDAO; } /* * Call http service to init the ASR Engine */ public SpeechRecognitionResponseVO initASREngine(SpeechRecognitionRequestVO request) throws ITalk2LearnException{ logger.info("JLF SpeechRecognitionBO initASREngine()--- Initialising ASREngine instance by user="+request.getHeaderVO().getLoginUser()); cleanAllAudioVariables(); Timer timer = new Timer(); //JLF Testing each 30 seconds if the speech component is sending data to the server, otherwise close the connection timer.scheduleAtFixedRate(new SpeechRecoTask(request), NUM_SECONDS,NUM_SECONDS); SpeechRecognitionResponseVO res=new SpeechRecognitionResponseVO(); try { Map<String, String> vars = new HashMap<String, String>(); //Get an available instance if (em.getInstanceByUser(request.getHeaderVO().getLoginUser())==null){ ASRInstanceVO aux= em.getInstanceEngineAvailable(request.getHeaderVO().getLoginUser()); logger.info("Speech module available for user: "+request.getHeaderVO().getLoginUser()+" with instance: "+aux.getInstance().toString() ); System.out.println("Speech module available for user: "+request.getHeaderVO().getLoginUser()+" with instance: "+aux.getInstance().toString()); vars.put("user", request.getHeaderVO().getLoginUser()); vars.put("instance", aux.getInstance().toString()); vars.put("server", aux.getServer()); vars.put("language", aux.getLanguageCode()); vars.put("model", aux.getModel()); //Call initEngineService of an available instance Boolean resp=this.restTemplate.getForObject(aux.getUrl() + "/initEngine?user={user}&instance={instance}&server={server}&language={language}&model={model}",Boolean.class, vars); res.setOpen(resp); return res; } else { res.setOpen(true); return res; } } catch (Exception e) { em.releaseEngineInstance(request.getHeaderVO().getLoginUser()); logger.error(e.toString()); } return res; } /* * Call http service to close the engine and it receives the final transcription */ public SpeechRecognitionResponseVO closeASREngine(SpeechRecognitionRequestVO request) throws ITalk2LearnException{ logger.info("JLF SpeechRecognitionBO closeASREngine() --- Closing ASREngine instance by user="+request.getHeaderVO().getLoginUser()); cleanAllAudioVariables(); SpeechRecognitionResponseVO res=new SpeechRecognitionResponseVO(); String url=em.getUrlByUser(request.getHeaderVO().getLoginUser()); Integer instanceNum=em.getInstanceByUser(request.getHeaderVO().getLoginUser()); if (instanceNum==null){ System.out.println("Instance already released by user="+ request.getHeaderVO().getLoginUser()+" or never used"); logger.info("closeASREngine()--- Instance already released by user="+ request.getHeaderVO().getLoginUser()+" or never used"); return res; } em.releaseEngineInstance(request.getHeaderVO().getLoginUser()); request.setInstance(instanceNum); try { System.out.println("Speech module released by user: "+request.getHeaderVO().getLoginUser()+" with instance: "+instanceNum.toString()); logger.info("Speech module released by user: "+request.getHeaderVO().getLoginUser()+" with instance: "+instanceNum.toString()); String response=this.restTemplate.getForObject(url + "/closeEngine?instance={instance}",String.class, instanceNum.toString()); res.setResponse(response); return res; } catch (Exception e) { logger.error(e.toString()); } return res; } /* * Call http service to send audio chunks */ public SpeechRecognitionResponseVO sendNewAudioChunk(SpeechRecognitionRequestVO request) throws ITalk2LearnException{ SEQ++; logger.info("JLF SpeechRecognitionBO sendNewAudioChunk()--- Sending new audio chunk by user="+request.getHeaderVO().getLoginUser()); SpeechRecognitionResponseVO res=new SpeechRecognitionResponseVO(); request.setInstance(em.getInstanceByUser(request.getHeaderVO().getLoginUser())); try { res=this.restTemplate.postForObject(em.getUrlByUser(request.getHeaderVO().getLoginUser())+"/sendData", request, SpeechRecognitionResponseVO.class); for (int i=0;i<res.getLiveResponse().size();i++) logger.info("liveResponse word="+ res.getLiveResponse().get(i)); } catch (Exception e) { em.releaseEngineInstance(request.getHeaderVO().getLoginUser()); logger.error(e.toString()); } return res; } public SpeechRecognitionResponseVO saveByteArray(SpeechRecognitionRequestVO request) throws ITalk2LearnException { logger.info("JLF SpeechRecognitionBO saveByteArray()--- Saving sound ByteArray on the database by user="+request.getHeaderVO().getLoginUser()); SpeechRecognitionResponseVO response= new SpeechRecognitionResponseVO(); try { getAudioStreamDAO().saveByteArray(request.getFinalByteArray(), request.getHeaderVO().getIdUser()); } catch (Exception e){ logger.error(e.toString()); } return response; } public AudioResponseVO concatenateAudioStream(AudioRequestVO request) throws ITalk2LearnException { logger.info("JLF --- Concatenating audio chunk which it comes each 5 seconds from the audio component"); AudioResponseVO response= new AudioResponseVO(); try { //JLF:Copying byte array byte[] destination = new byte[request.getAudio().length + getAudio().length]; // copy audio into start of destination (from pos 0, copy audio.length bytes) System.arraycopy(getAudio(), 0, destination, 0, getAudio().length); // copy body into end of destination (from pos audio.length, copy body.length bytes) System.arraycopy(request.getAudio(), 0, destination, getAudio().length, request.getAudio().length); //setAudio(Arrays.copyOfRange(destination, 0, destination.length)); this.audio=destination.clone(); this.audioExercise=destination.clone(); } catch (Exception e){ logger.error(e.toString()); } return response; } // JLF: Get the current stored audio, 2 minutes public AudioResponseVO getCurrentAudioFromPlatform(AudioRequestVO request) throws ITalk2LearnException { logger.info("JLF --- getCurrentAudioFromPlatform-- Get current audio to use on TIS current_audio_length= "+this.audio.length); AudioResponseVO response= new AudioResponseVO(); try { //JLF:The audio should be more than 2 minutes for analysis if (this.audio.length>SIZE_AUDIO_2MINUTES) { int init=this.audio.length-SIZE_AUDIO_2MINUTES; if ((init % 16)!=0) init=init-(init % 16); byte[] destination = Arrays.copyOfRange(this.audio, init, this.audio.length); this.audio=destination.clone(); } response.setAudio(this.audio); } catch (Exception e){ logger.error(e.toString()); } return response; } // JLF: Get whole audio from exercise, 10 minutes public AudioResponseVO getCurrentAudioFromExercise(AudioRequestVO request) throws ITalk2LearnException { logger.info("JLF --- getCurrentAudioFromExercise-- Get current audio to use on SNA current_audio_length= "+this.audioExercise.length); AudioResponseVO response= new AudioResponseVO(); try { if (this.audioExercise.length>SIZE_AUDIO_10MINUTES) { int init=this.audioExercise.length-SIZE_AUDIO_10MINUTES; if ((init % 16)!=0) init=init-(init % 16); byte[] destination = Arrays.copyOfRange(this.audioExercise, init, this.audioExercise.length); this.audioExercise=destination.clone(); } response.setAudioExercise(this.audioExercise); } catch (Exception e){ logger.error(e.toString()); } return response; } public void cleanAllAudioVariables() throws ITalk2LearnException { this.audio=new byte[0]; this.audioExercise=new byte[0]; } public EnginesMap getEm() { return em; } public void setEm(EnginesMap em) { this.em = em; } public IAudioStreamDAO getAudioStreamDAO() { return audioStreamDAO; } public void setAudioStreamDAO(IAudioStreamDAO audioStreamDAO) { this.audioStreamDAO = audioStreamDAO; } public byte[] getAudio() { return audio; } public void setAudio(byte[] audio) { this.audio = audio; } public byte[] getAudioExercise() { return audioExercise; } public void setAudioExercise(byte[] audioExercise) { this.audioExercise = audioExercise; } //JLF: This class check if speech component is sending data to the Speech Reco, if not it closes the instance with the engine and release this class SpeechRecoTask extends TimerTask { private int SEQ_ACK=0; private SpeechRecognitionRequestVO request; public SpeechRecoTask(SpeechRecognitionRequestVO request) { super(); this.request = request; } public void run() { if (SEQ==SEQ_ACK) { try { closeASREngine(request); this.cancel(); } catch (ITalk2LearnException e) { // TODO Auto-generated catch block logger.error(e.toString()); } } else { SEQ_ACK=SEQ; } } } }
package org.xwiki.mail.test.ui; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import javax.mail.internet.MimeMessage; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.openqa.selenium.By; import org.xwiki.administration.test.po.AdministrablePage; import org.xwiki.administration.test.po.AdministrationPage; import org.xwiki.mail.test.po.MailStatusAdministrationSectionPage; import org.xwiki.mail.test.po.SendMailAdministrationSectionPage; import org.xwiki.test.ui.AbstractTest; import org.xwiki.test.ui.SuperAdminAuthenticationRule; import org.xwiki.test.ui.po.LiveTableElement; import org.xwiki.test.ui.po.ViewPage; import com.icegreen.greenmail.util.GreenMail; import com.icegreen.greenmail.util.ServerSetupTest; import static org.junit.Assert.*; /** * UI tests for the Mail application. * * @version $Id$ * @since 6.4M2 */ public class MailTest extends AbstractTest { @Rule public SuperAdminAuthenticationRule authenticationRule = new SuperAdminAuthenticationRule(getUtil()); private GreenMail mail; private List<String> alreadyAssertedMessages = new ArrayList<>(); @Before public void startMail() { this.mail = new GreenMail(ServerSetupTest.SMTP); this.mail.start(); } @After public void stopMail() { if (this.mail != null) { this.mail.stop(); } } @Test public void testMail() throws Exception { // one non-hidden page in the XWiki space getUtil().createPage("XWiki", getTestClassName() + "-" + getTestMethodName(), "", ""); // Step 1: Verify that there are 2 email sections in the Email category AdministrablePage page = new AdministrablePage(); AdministrationPage administrationPage = page.clickAdministerWiki(); Assert.assertTrue(administrationPage.hasSection("Email", "General")); Assert.assertTrue(administrationPage.hasSection("Email", "Mail Sending")); // Step 2: Navigate to each mail section and set the mail sending parameters (SMTP host/port) administrationPage.clickSection("Email", "General"); administrationPage.clickSection("Email", "Mail Sending"); SendMailAdministrationSectionPage sendMailPage = new SendMailAdministrationSectionPage(); sendMailPage.setHost("localhost"); sendMailPage.setPort("3025"); // Make sure we don't wait between email sending in order to speed up the test (and not incur timeouts when // we wait to receive the mails) sendMailPage.setSendWaitTime("0"); // Keep all mail statuses including successful ones (so that we verify this works fine) sendMailPage.setDiscardSuccessStatuses(false); sendMailPage.clickSave(); // Step 3: Verify that there are no admin email sections when administering a space // Select XWiki space administration. AdministrationPage spaceAdministrationPage = administrationPage.selectSpaceToAdminister("XWiki"); // Since clicking on "XWiki" in the Select box will reload the page asynchronously we need to wait for the new // page to be available. For this we wait for the heading to be changed to "Administration:XWiki". getDriver().waitUntilElementIsVisible(By.id("HAdministration:XWiki")); // Also wait till the page is fully loaded to be extra sure... spaceAdministrationPage.waitUntilPageIsLoaded(); // All those sections should not be present Assert.assertTrue(spaceAdministrationPage.hasNotSection("Email", "General")); Assert.assertTrue(spaceAdministrationPage.hasNotSection("Email", "Mail Sending")); // Step 4: Prepare a Template Mail getUtil().deletePage(getTestClassName(), "MailTemplate"); // Create a Wiki page containing a Mail Template (ie a XWiki.Mail object) getUtil().createPage(getTestClassName(), "MailTemplate", "", ""); // Note: We use the following bindings in the Template subject and content so that we ensure that they are // provided by default: // - "$xwiki" // - "$xcontext" // - "$escapetool" // - "$services" // - "$request" // Note: We also use the $name and $doc bindings to show that the user can add new bindings ($doc is not bound // by default since there isn't always a notion of current doc in all places where mail sending is done). String velocityContent = "Hello $name from $escapetool.xml($services.model.resolveDocument(" + "$xcontext.getUser()).getName()) - Served from $request.getRequestURL().toString()"; getUtil().addObject(getTestClassName(), "MailTemplate", "XWiki.Mail", "subject", "#if ($xwiki.exists($doc.documentReference))Status for $name on $doc.fullName#{else}wrong#end", "language", "en", "html", "<strong>" + velocityContent + "</strong>", "text", velocityContent); // We also add an attachment to the Mail Template page to verify that it is sent in the mail ByteArrayInputStream bais = new ByteArrayInputStream("Content of attachment".getBytes()); getUtil().attachFile(getTestClassName(), "MailTemplate", "something.txt", bais, true, new UsernamePasswordCredentials("superadmin", "pass")); // Step 5: Send a template email (with an attachment) to a single email address sendTemplateMailToEmail(); // Step 6: Send a template email to all the users in the XWikiAllGroup Group (we'll create 2 users) + to // two other users (however since they're part of the group they'll receive only one mail each, we thus test // deduplicatio!). sendTemplateMailToUsersAndGroup(); // Step 7: Navigate to the Mail Sending Status Admin page and assert that the Livetable displays the entry for // the sent mails administrationPage = AdministrationPage.gotoPage(); administrationPage.clickSection("Email", "Mail Sending Status"); MailStatusAdministrationSectionPage statusPage = new MailStatusAdministrationSectionPage(); LiveTableElement liveTableElement = statusPage.getLiveTable(); liveTableElement.filterColumn("xwiki-livetable-sendmailstatus-filter-3", "Test"); liveTableElement.filterColumn("xwiki-livetable-sendmailstatus-filter-5", "sent"); liveTableElement.filterColumn("xwiki-livetable-sendmailstatus-filter-6", "xwiki"); // Let's wait till we have at least 3 rows. Note that we wait because we could have received the mails above // but the mail status in the database may not have been updated yet. liveTableElement.waitUntilRowCountGreaterThan(3); liveTableElement.filterColumn("xwiki-livetable-sendmailstatus-filter-4", "john@doe.com"); assertTrue(liveTableElement.getRowCount() > 0); assertTrue(liveTableElement.hasRow("Error", "")); } private void sendTemplateMailToEmail() throws Exception { // Remove existing pages (for pages that we create below) getUtil().deletePage(getTestClassName(), "SendMail"); // Create another page with the Velocity script to send the template email // Note that we didn't need to bind the "$doc" velocity variable because the send is done synchronously and // thus the current XWiki Context is cloned before being passed to the template evaluation, and thus it // already contains the "$doc" binding! String velocity = "{{velocity}}\n" + "#set ($templateReference = $services.model.createDocumentReference('', '" + getTestClassName() + "', 'MailTemplate'))\n" + "#set ($parameters = {'velocityVariables' : { 'name' : 'John' }, 'language' : 'en', " + "'includeTemplateAttachments' : true})\n" + "#set ($message = $services.mailsender.createMessage('template', $templateReference, $parameters))\n" + "#set ($discard = $message.setFrom('localhost@xwiki.org'))\n" + "#set ($discard = $message.addRecipients('to', 'john@doe.com'))\n" + "#set ($discard = $message.setType('Test'))\n" + "#set ($result = $services.mailsender.send([$message], 'database'))\n" + "#if ($services.mailsender.lastError)\n" + " {{error}}$exceptiontool.getStackTrace($services.mailsender.lastError){{/error}}\n" + "#end\n" + "#foreach ($status in $result.statusResult.getByState('FAILED'))\n" + " {{error}}\n" + " $status.messageId - $status.errorSummary\n" + " $status.errorDescription\n" + " {{/error}}\n" + "#end\n" + "{{/velocity}}"; // This will create the page and execute its content and thus send the mail ViewPage vp = getUtil().createPage(getTestClassName(), "SendMail", velocity, ""); // Verify that the page doesn't display any content (unless there's an error!) assertEquals("", vp.getContent()); // Verify that the mail has been received. this.mail.waitForIncomingEmail(10000L, 1); assertEquals(1, this.mail.getReceivedMessages().length); assertReceivedMessages(1, "Subject: Status for John on " + getTestClassName() + ".SendMail", "Hello John from superadmin - Served from http://localhost:8080/xwiki/bin/view/MailTest/SendMail", "<strong>Hello John from superadmin - Served from " + "http://localhost:8080/xwiki/bin/view/MailTest/SendMail</strong>", "X-MailType: Test", "Content-Type: text/plain; name=something.txt", "Content-ID: <something.txt>", "Content-Disposition: attachment; filename=something.txt", "Content of attachment"); } private void sendTemplateMailToUsersAndGroup() throws Exception { // Remove existing pages (for pages that we create below) getUtil().deletePage(getTestClassName(), "SendMailGroupAndUsers"); // Create 2 users getUtil().createUser("user1", "password1", getUtil().getURLToNonExistentPage(), "email", "user1@doe.com"); getUtil().createUser("user2", "password2", getUtil().getURLToNonExistentPage(), "email", "user2@doe.com"); // Create another page with the Velocity script to send the template email // Note: when sending asynchronously the request and response are faked, hence // "$request.getRequestURL().toString()" would return "". // That's why we explicitely pass 'request' as a velocity binding. // OTOH the $xcontext binding is present and has the content of the context at the moment the call to send the // mail asynchronously was done. String velocity = "{{velocity}}\n" + "#set ($templateParameters = " + " {'velocityVariables' : { 'name' : 'John', 'doc' : $doc, 'request' : $request }, " + " 'language' : 'en', 'from' : 'localhost@xwiki.org'})\n" + "#set ($templateReference = $services.model.createDocumentReference('', '" + getTestClassName() + "', 'MailTemplate'))\n" + "#set ($parameters = {'hint' : 'template', 'source' : $templateReference, " + "'parameters' : $templateParameters, 'type' : 'Test'})\n" + "#set ($groupReference = $services.model.createDocumentReference('', 'XWiki', 'XWikiAllGroup'))\n" + "#set ($user1Reference = $services.model.createDocumentReference('', 'XWiki', 'user1'))\n" + "#set ($user2Reference = $services.model.createDocumentReference('', 'XWiki', 'user2'))\n" + "#set ($source = {'groups' : [$groupReference], 'users' : [$user1Reference, $user2Reference]})\n" + "#set ($messages = $services.mailsender.createMessages('usersandgroups', $source, $parameters))\n" + "#set ($result = $services.mailsender.send($messages, 'database'))\n" + "#if ($services.mailsender.lastError)\n" + " {{error}}$exceptiontool.getStackTrace($services.mailsender.lastError){{/error}}\n" + "#end\n" + "#foreach ($status in $result.statusResult.getByState('FAILED'))\n" + " {{error}}\n" + " $status.messageId - $status.errorSummary\n" + " $status.errorDescription\n" + " {{/error}}\n" + "#end\n" + "{{/velocity}}"; // This will create the page and execute its content and thus send the mail ViewPage vp = getUtil().createPage(getTestClassName(), "SendMailGroupAndUsers", velocity, ""); // Verify that the page doesn't display any content (unless there's an error!) assertEquals("", vp.getContent()); // Verify that the mails have been received (first mail above + the 2 mails sent to the group) this.mail.waitForIncomingEmail(10000L, 3); assertEquals(3, this.mail.getReceivedMessages().length); assertReceivedMessages(2, "Subject: Status for John on " + getTestClassName() + ".SendMailGroupAndUsers", "Hello John from superadmin - Served from " + "http://localhost:8080/xwiki/bin/view/MailTest/SendMailGroupAndUsers"); } private void assertReceivedMessages(int expectedMatchingCount, String... expectedLines) throws Exception { StringBuilder builder = new StringBuilder(); int count = 0; for (MimeMessage message : this.mail.getReceivedMessages()) { if (this.alreadyAssertedMessages.contains(message.getMessageID())) { continue; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); message.writeTo(baos); String fullContent = baos.toString(); boolean match = true; for (int i = 0; i < expectedLines.length; i++) { if (!fullContent.contains(expectedLines[i])) { match = false; break; } } if (!match) { builder.append("- Content [" + fullContent + "]").append('\n'); } else { count++; } this.alreadyAssertedMessages.add(message.getMessageID()); } StringBuilder expected = new StringBuilder(); for (int i = 0; i < expectedLines.length; i++) { expected.append("- '" + expectedLines[i] + "'").append('\n'); } assertEquals(String.format("We got [%s] mails matching the expected content instead of [%s]. We were expecting " + "the following content:\n%s\nWe got the following:\n%s", count, expectedMatchingCount, expected.toString(), builder.toString()), expectedMatchingCount, count); } }
package com.legendzero.lzlib.command; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.legendzero.lzlib.lang.LZLibLang; import com.legendzero.lzlib.util.Reflections; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.chat.BaseComponent; import net.md_5.bungee.api.chat.ClickEvent; import net.md_5.bungee.api.chat.ComponentBuilder; import org.bukkit.command.*; import org.bukkit.entity.Player; import org.bukkit.permissions.Permissible; import org.bukkit.permissions.Permission; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.stream.Collectors; public abstract class LZCommand implements TabExecutor, Comparable<LZCommand> { private final Plugin plugin; private final LZCommand parent; private final Map<String, LZCommand> subCommandMap; public LZCommand(Plugin plugin, LZCommand parent) { this.plugin = plugin == null ? Reflections.getProvidingPlugin(this.getClass()) : plugin; this.parent = parent; this.subCommandMap = Maps.newHashMap(); LZLibLang.COMMAND_LOAD.log(this.plugin.getLogger(), Level.INFO, this.getFullName()); if (this.parent == null) { if (this.registerToBukkit()) { LZLibLang.COMMAND_REGISTER_SUCCESS.log(this.plugin.getLogger(), Level.INFO, this.name()); } else { LZLibLang.COMMAND_REGISTER_FAILURE.log(this.plugin.getLogger(), Level.INFO, this.name()); } } } public LZCommand(Plugin plugin) { this(plugin, null); } public LZCommand(LZCommand parent) { this(null, parent); } public LZCommand() { this(null, null); } public final Plugin getPlugin() { return this.plugin; } public final LZCommand getParent() { return this.parent; } public abstract String name(); public String getFullName() { return (this.getParent() == null ? "/" : " ") + this.name(); } public abstract String[] aliases(); public abstract String description(); public abstract String usage(); public abstract Permission permission(); public final Collection<LZCommand> getSubCommands() { return ImmutableSet.copyOf(this.subCommandMap.values()); } public final Collection<LZCommand> getPermissibleSubCommands(Permissible permissible) { return this.subCommandMap.values().stream().filter(cmd -> permissible.hasPermission(cmd.permission())).collect(Collectors.toSet()); } public LZCommand getSubCommand(String alias) { return this.getSubCommand(null, alias); } public LZCommand getSubCommand(Permissible permissible, String alias) { LZCommand command = this.subCommandMap.get(alias.toLowerCase()); if (permissible == null) { return command; } else { if (command != null && permissible.hasPermission(command.permission())) { return command; } else { return null; } } } @Override public boolean onCommand(CommandSender sender, Command cmd, String cmdLabel, String... args) { return this.resolveCommand(sender, Arrays.asList(args)); } @Override public List<String> onTabComplete(CommandSender sender, Command cmd, String cmdLabel, String... args) { return this.resolveTab(sender, Arrays.asList(args)); } @Override public int compareTo(LZCommand other) { return this.name().compareToIgnoreCase(other.name()); } private boolean resolveCommand(CommandSender sender, List<String> args) { if (!args.isEmpty() && this.subCommandMap.containsKey(args.get(0).toLowerCase())) { return this.subCommandMap.get(args.remove(0)).resolveCommand(sender, args); } else { return this.execute(sender, args); } } protected List<String> resolveTab(CommandSender sender, List<String> args) { if (!args.isEmpty() && this.subCommandMap.containsKey(args.get(0).toLowerCase())) { return this.subCommandMap.get(args.remove(0)).resolveTab(sender, args); } else { return this.tabComplete(sender, args); } } protected boolean execute(CommandSender sender, List<String> args) { String fullName = getFullName(); if (sender instanceof Player) { Player.Spigot player = ((Player) sender).spigot(); BaseComponent[] title = new ComponentBuilder( "Command Help: " + fullName + "\n") .color(ChatColor.AQUA).underlined(true).create(); player.sendMessage(title); this.getPermissibleSubCommands(sender).stream().sorted().forEach( command -> player.sendMessage( new ComponentBuilder("> ") .color(ChatColor.YELLOW) .bold(true) .event(new ClickEvent( ClickEvent.Action.RUN_COMMAND, fullName)) .append(fullName) .color(ChatColor.AQUA) .event(new ClickEvent( ClickEvent.Action.SUGGEST_COMMAND, fullName)) .create())); } else { this.getPermissibleSubCommands(sender).stream().sorted().forEach( command -> sender.sendMessage(fullName)); } return true; } protected List<String> tabComplete(CommandSender sender, List<String> args) { return this.getPermissibleSubCommands(sender).stream().map(LZCommand::name).collect(Collectors.toList()); } public void registerSubCommand(LZCommand... commands) { Arrays.stream(commands).forEach(this::registerSubCommand); } public void registerSubCommand(LZCommand command) { this.registerAlias(command.name(), command); Arrays.stream(command.aliases()).forEach(alias -> registerAlias(alias, command)); } public void registerAlias(String alias, LZCommand... commands) { Arrays.stream(commands).forEach(cmd -> this.registerAlias(alias, cmd)); } private void registerAlias(String alias, LZCommand command) { this.subCommandMap.putIfAbsent(alias, command); } public final boolean registerToBukkit() { PluginCommand pluginCommand = this.plugin.getServer().getPluginCommand(this.name()); if (pluginCommand == null) { pluginCommand = this.getPluginCommand(); CommandMap commandMap = this.getCommandMap(); if (pluginCommand == null || commandMap == null) { return false; } commandMap.register(this.plugin.getName().toLowerCase(), pluginCommand); } pluginCommand.setExecutor(this); return true; } private PluginCommand getPluginCommand() { try { Constructor<PluginCommand> c = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class); c.setAccessible(true); return c.newInstance(this.name(), this.getPlugin()); } catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) { this.getPlugin().getLogger().log(Level.SEVERE, "Error creating Bukkit command", e); return null; } } private CommandMap getCommandMap() { PluginManager pluginManager = this.getPlugin().getServer().getPluginManager(); CommandMap cMap = null; try { Field f = pluginManager.getClass().getDeclaredField("commandMap"); f.setAccessible(true); cMap = (CommandMap) f.get(pluginManager); } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { } return cMap; } }
package com.unidev.myip; import com.unidev.platform.web.WebUtils; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; /** * Controller for returning all request headers */ @Controller("/headers") public class HeadersController { @Autowired private HttpServletRequest request; @Autowired private WebUtils webUtils; @RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public JSONObject jsonRequest() { JSONObject jsonObject = new JSONObject(); Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName = (String)headerNames.nextElement(); String headerValue = request.getHeader(headerName); jsonObject.put(headerName, headerValue); } return jsonObject; } }
package cs414.pos.ui; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.DefaultListModel; import javax.swing.DefaultListSelectionModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; /** * * @author Nathan Lighthart */ public class PlaceOrderUI { private UIController controller; private JFrame frame; private JPanel orderPanel; private JPanel optionsPanel; private JComboBox<String> menuComboBox; private JScrollPane menuItemsScrollPane; private JList<String> menuItemsList; private JScrollPane orderScrollPane; private JList<String> orderList; private JLabel totalLabel; private JLabel totalAmount; private JButton addButton; private JButton removeButton; private JButton payCashButton; private JButton payCardButton; public PlaceOrderUI(UIController controller) { this.controller = controller; } public void init() { frame = new JFrame("Place Order"); orderPanel = new JPanel(); optionsPanel = new JPanel(); menuComboBox = new JComboBox<>(); menuItemsScrollPane = new JScrollPane(); menuItemsList = new JList<>(); orderScrollPane = new JScrollPane(); orderList = new JList<>(); totalLabel = new JLabel("Total:"); totalAmount = new JLabel(); addButton = new JButton("Add"); removeButton = new JButton("Remove"); payCashButton = new JButton("Pay Cash"); payCardButton = new JButton("Pay Card"); layoutComponents(); addListeners(); frame.setPreferredSize(new Dimension(800, 600)); frame.pack(); } public void setVisible(boolean visible) { frame.setLocationRelativeTo(null); frame.setVisible(visible); } public void updateMenus() { setMenus(controller.getMenus()); } public void setMenus(Iterable<String> menus) { menuComboBox.removeAllItems(); for(String menu : menus) { menuComboBox.addItem(menu); } } public void setMenuItems(Iterable<String> items) { DefaultListModel<String> model = new DefaultListModel<>(); for(String item : items) { model.addElement(item); } menuItemsList.setModel(model); } private void layoutComponents() { frame.setLayout(new BorderLayout()); frame.add(menuComboBox, BorderLayout.NORTH); frame.add(menuItemsScrollPane, BorderLayout.CENTER); menuItemsScrollPane.setViewportView(menuItemsList); menuItemsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); frame.add(orderPanel, BorderLayout.EAST); orderPanel.setLayout(new BorderLayout()); orderPanel.add(orderScrollPane, BorderLayout.CENTER); orderScrollPane.setViewportView(orderList); orderList.setSelectionModel(new DefaultListSelectionModel() { private static final long serialVersionUID = -2473659851927728063L; @Override public void setSelectionInterval(int index0, int index1) { super.setSelectionInterval(-1, -1); // prevent selection } }); orderList.setModel(new DefaultListModel<String>()); orderPanel.add(optionsPanel, BorderLayout.SOUTH); GridLayout optionsLayout = new GridLayout(3, 2); optionsLayout.setHgap(5); optionsLayout.setVgap(5); optionsPanel.setLayout(optionsLayout); totalLabel.setHorizontalAlignment(SwingConstants.RIGHT); optionsPanel.add(totalLabel); totalAmount.setHorizontalAlignment(SwingConstants.RIGHT); optionsPanel.add(totalAmount); optionsPanel.add(addButton); optionsPanel.add(removeButton); optionsPanel.add(payCashButton); optionsPanel.add(payCardButton); } private void addListeners() { frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { controller.closePlaceOrder(); } }); menuComboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loadItemsAction(); } }); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } }); removeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } }); payCashButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } }); payCardButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } }); } private void loadItemsAction() { if(menuComboBox.getModel().getSize() == 0) { return; // do nothing as nothing to load } String menu = (String) menuComboBox.getSelectedItem(); Iterable<String> menuItems = controller.getFullMenuItems(menu); setMenuItems(menuItems); } // Used to view the interface with nothing working public static void main(String[] args) { final PlaceOrderUI view = new PlaceOrderUI(null); EventQueue.invokeLater(new Runnable() { @Override public void run() { view.init(); view.setVisible(true); view.frame.removeWindowListener(view.frame.getWindowListeners()[0]); view.frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); } }); } }
package com.net2plan.gui.utils; import java.sql.Time; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections15.BidiMap; import org.apache.commons.collections15.bidimap.DualHashBidiMap; import com.net2plan.interfaces.networkDesign.NetPlan; import com.net2plan.interfaces.networkDesign.NetworkLayer; import com.net2plan.utils.Triple; /** * Manages the undo/redo information, tracking the current netPlan and the visualization state */ public class UndoRedoManager { private List<TimelineState> pastInfoVsNewNp; private int pastInfoVsNewNpCursor; private int maxSizeUndoList; private final IVisualizationCallback callback; private TimelineState backupState; public UndoRedoManager(IVisualizationCallback callback, int maxSizeUndoList) { this.pastInfoVsNewNp = new ArrayList<>(); this.pastInfoVsNewNpCursor = -1; this.callback = callback; this.maxSizeUndoList = maxSizeUndoList; } public void addNetPlanChange() { if (this.maxSizeUndoList <= 1) return; // nothing is stored since nothing will be retrieved if (callback.inOnlineSimulationMode()) return; final NetPlan npCopy = callback.getDesign().copy(); final BidiMap<NetworkLayer, Integer> cp_mapLayer2VisualizationOrder = new DualHashBidiMap<>(); for (NetworkLayer cpLayer : npCopy.getNetworkLayers()) { cp_mapLayer2VisualizationOrder.put(cpLayer, callback.getVisualizationState().getCanvasVisualizationOrderNotRemovingNonVisible(callback.getDesign().getNetworkLayer(cpLayer.getIndex()))); } final Map<NetworkLayer, Boolean> cp_layerVisibilityMap = new HashMap<>(); for (NetworkLayer cpLayer : npCopy.getNetworkLayers()) { cp_layerVisibilityMap.put(cpLayer, callback.getVisualizationState().isLayerVisibleInCanvas(callback.getDesign().getNetworkLayer(cpLayer.getIndex()))); } // Removing all changes made after the one at the cursor if (pastInfoVsNewNpCursor != pastInfoVsNewNp.size() - 1) { pastInfoVsNewNp.subList(pastInfoVsNewNpCursor + 1, pastInfoVsNewNp.size()).clear(); } pastInfoVsNewNp.add(new TimelineState(npCopy, cp_mapLayer2VisualizationOrder, cp_layerVisibilityMap)); // Remove the older changes so that the list does not bloat. while (pastInfoVsNewNp.size() > maxSizeUndoList) { pastInfoVsNewNp.remove(0); pastInfoVsNewNpCursor } pastInfoVsNewNpCursor++; } /** * Returns the undo info in the navigation. Returns null if we are already in the first element. The NetPlan object returned is null if * there is no change respect to the current one * * @return see above */ public Triple<NetPlan, BidiMap<NetworkLayer, Integer>, Map<NetworkLayer, Boolean>> getNavigationBackElement() { if (pastInfoVsNewNp.isEmpty()) return null; if (this.maxSizeUndoList <= 1) return null; // nothing is stored since nothing will be retrieved if (callback.inOnlineSimulationMode()) return null; if (pastInfoVsNewNpCursor == 0) return null; this.pastInfoVsNewNpCursor final TimelineState currentState = pastInfoVsNewNp.get(this.pastInfoVsNewNpCursor); this.backupState = currentState; return currentState.getStateDefinition(); } /** * Returns the forward info in the navigation. Returns null if we are already in the head. The NetPlan object returned is null if * there is no change respect to the current one * * @return see above */ public Triple<NetPlan, BidiMap<NetworkLayer, Integer>, Map<NetworkLayer, Boolean>> getNavigationForwardElement() { if (pastInfoVsNewNp.isEmpty()) return null; if (this.maxSizeUndoList <= 1) return null; // nothing is stored since nothing will be retrieved if (callback.inOnlineSimulationMode()) return null; if (pastInfoVsNewNpCursor == pastInfoVsNewNp.size() - 1) return null; this.pastInfoVsNewNpCursor++; final TimelineState currentState = pastInfoVsNewNp.get(this.pastInfoVsNewNpCursor); this.backupState = currentState; return currentState.getStateDefinition(); } private class TimelineState { private final NetPlan netPlan; private final BidiMap<NetworkLayer, Integer> layerOrderMap; private final Map<NetworkLayer, Boolean> layerVisibilityMap; public TimelineState(final NetPlan netPlan, final BidiMap<NetworkLayer, Integer> layerOrderMap, final Map<NetworkLayer, Boolean> layerVisibilityMap) { this.netPlan = netPlan; this.layerOrderMap = layerOrderMap; this.layerVisibilityMap = layerVisibilityMap; } public Triple<NetPlan, BidiMap<NetworkLayer, Integer>, Map<NetworkLayer, Boolean>> getStateDefinition() { return Triple.unmodifiableOf(netPlan, layerOrderMap, layerVisibilityMap); } } }
package cs414.pos.ui; import cs414.pos.Customer; import cs414.pos.Employee; import cs414.pos.Item; import cs414.pos.Menu; import cs414.pos.Order; import cs414.pos.OrderItem; import cs414.pos.SaverLoader; import cs414.pos.Store; import java.awt.EventQueue; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Nathan Lighthart */ public class UIController { private LoginUI loginView; private MainUI mainView; private EditMenuItemUI editMenuItemView; private EditMenuUI editMenuView; private PlaceOrderUI placeOrderView; private CompleteOrderUI completeOrderView; private Store store; private Employee currentEmployee; private boolean isKiosk; // Id is the id of the register or kiosk private int id; private Order currentOrder; public UIController(Store store, boolean isKiosk, int registerOrKioskId) { this.store = store; this.isKiosk = isKiosk; this.id = registerOrKioskId; } public void start() { loginView = new LoginUI(this); mainView = new MainUI(this); editMenuItemView = new EditMenuItemUI(this); editMenuView = new EditMenuUI(this); placeOrderView = new PlaceOrderUI(this); completeOrderView = new CompleteOrderUI(this); EventQueue.invokeLater(new Runnable() { @Override public void run() { loginView.init(); mainView.init(); editMenuItemView.init(); editMenuView.init(); placeOrderView.init(); completeOrderView.init(); if(isKiosk) { mainView.setCanEditMenu(false); mainView.setCanPlaceOrder(true); mainView.setCanCompleteOrder(false); mainView.setVisible(true); } else { loginView.setVisible(true); } } }); } public void login(String loginID, String password) { Employee temp = store.loginAttempt(loginID, password); if(temp == null) { // Login Failed loginView.setStatus("Invalid Username/Password"); } else { currentEmployee = temp; loginView.clear(); loginView.setVisible(false); mainView.setCanEditMenu(currentEmployee.getRole().canEditMenu()); mainView.setCanPlaceOrder(currentEmployee.getRole().canUseKiosk()); mainView.setCanCompleteOrder(currentEmployee.getRole().canCompleteOrder()); mainView.setVisible(true); } } public void displayEditMenu() { mainView.setVisible(false); editMenuView.updateMenus(); editMenuView.setVisible(true); } public void displayEditMenuItem() { mainView.setVisible(false); editMenuItemView.updateItems(); editMenuItemView.setVisible(true); } public void displayPlaceOrder() { mainView.setVisible(false); if(isKiosk) { currentOrder = store.createOrderViaKiosk(id); } else { currentOrder = store.createOrderViaRegister(currentEmployee, id); } placeOrderView.updateMenus(); placeOrderView.updateOrder(); placeOrderView.setVisible(true); } public void displayCompleteOrder() { mainView.setVisible(false); completeOrderView.updateOrders(); completeOrderView.setVisible(true); } public boolean createMenu(String name, String description) { if(!isValidMenuName(name)) { return false; } Menu m = store.defineMenu(currentEmployee, name, description); return m != null; } public void deleteMenu(String name) { Menu menu = getSelectedMenu(name); store.getSetOfMenus().remove(menu); } public boolean addMenuItem(String menuName, String menuItemName) { Menu menu = getSelectedMenu(menuName); Item item = getSelectedItem(menuItemName); menu.addItem(item); return true; } public boolean removeMenuItem(String menuName, String menuItemName) { Menu menu = getSelectedMenu(menuName); Item item = getSelectedItem(menuItemName); menu.deleteItem(item); return true; } public boolean createMenuItem(String itemName, String itemDescription, double price) { if(!isValidMenuItemName(itemName)) { return false; } store.addMenuItem(currentEmployee, itemName, price, itemDescription); return true; } public void deleteMenuItem(String itemName) { Item item = getSelectedItem(itemName); store.deleteMenuItem(currentEmployee, item); } public boolean changeMenuItemName(String itemName, String newName) { if(!isValidMenuItemName(newName)) { return false; } Item item = getSelectedItem(itemName); item.setItemName(newName); return true; } public void changeMenuItemDescription(String itemName, String itemDescription) { Item item = getSelectedItem(itemName); item.setItemDescription(itemDescription); } public void changeMenuItemSpecial(String itemName) { Item item = getSelectedItem(itemName); if(item.isSpecial()) { item.removeSpecial(); } else { item.setSpecial(); } } public void completeOrder(int id) { Collection<Order> orders = getIncompleteOrdersSet(); for(Order order : orders) { if(order.getOrderID() == id) { order.setCompletedByEmployee(currentEmployee); } } } // deliveryType {0 = InHouse, 1 = TakeAway, 2 = Delivery} // paymentType {0 = cash, 1 = card} public boolean payOrder(String membershipID, int deliveryType, String address, int paymentType, String cardNumber, String expirationDate, String cv2, double amount) { if(membershipID != null) { Customer c = store.getMember(membershipID); if(c == null) { return false; } currentOrder.updateMembershipHoldingCustomer(c); } if(deliveryType == 0) { currentOrder.updateToInHouseOrder(); } else if(deliveryType == 1) { currentOrder.updateToTakeAwayOrder(); } else if(deliveryType == 2) { currentOrder.updateToHomeDeliveryOrder(address); } boolean success = false; if(paymentType == 0) { success = currentOrder.makeCashPayment(amount); } else if(paymentType == 1) { success = currentOrder.makeCardPayment(amount, cardNumber, expirationDate, cv2); } return success; } public void placeOrder() { store.placeOrder(currentOrder); } public void addOrderItem(String itemName, int quantity) { Item item = getSelectedItem(itemName); currentOrder.addItemToOrderByAmount(item, quantity); } public void removeOrderItem(String itemName, int quantity) { Item item = getSelectedItem(itemName); currentOrder.removeMultipleCountOfItemFromOrder(item, quantity); } public double getOrderChange() { return roundToTwo(currentOrder.getAmountReturned()); } public double getTotal() { return roundToTwo(currentOrder.getTotalPrice()); } public void closeMain() { try { SaverLoader.save(SaverLoader.SAVE_FILE, store); } catch(IOException ex) { Logger.getLogger(UIController.class.getName()).log(Level.SEVERE, null, ex); } System.exit(0); // close jvm } public void closeEditMenu() { editMenuView.setVisible(false); mainView.setVisible(true); } public void closeEditMenuItem() { editMenuItemView.setVisible(false); mainView.setVisible(true); } public void closeCompleteOrder() { completeOrderView.setVisible(false); mainView.setVisible(true); } public void closePlaceOrder() { placeOrderView.setVisible(false); currentOrder = null; mainView.setVisible(true); } public Iterable<String> getIncompleteOrders() { Collection<Order> orders = getIncompleteOrdersSet(); List<String> incompleteOrders = new ArrayList<>(); for(Order order : orders) { incompleteOrders.add(getOrderString(order)); } return incompleteOrders; } public Iterable<String> getMenus() { Collection<Menu> menus = store.getSetOfMenus(); List<String> menuList = new ArrayList<>(); for(Menu menu : menus) { menuList.add(menu.getMenuName()); } return menuList; } public Iterable<String> getAllMenuItems() { return getMenuItems(store.getSetOfItems()); } public Iterable<String> getAllFullMenuItems() { return getFullMenuItems(store.getSetOfItems()); } public Iterable<String> getMenuItemsNotOnMenu(String menuName) { Menu menu = getSelectedMenu(menuName); Collection<Item> items = getItemsNotOnMenu(menu); return getMenuItems(items); } public Iterable<String> getFullMenuItemsNotOnMenu(String menuName) { Menu menu = getSelectedMenu(menuName); Collection<Item> items = getItemsNotOnMenu(menu); return getFullMenuItems(items); } public Iterable<String> getMenuItems(String menuName) { Menu menu = getSelectedMenu(menuName); if(menu != null) { return getFullMenuItems(menu.getMenuItems()); } else { return new ArrayList<>(); } } public Iterable<String> getFullMenuItems(String menuName) { Menu menu = getSelectedMenu(menuName); if(menu != null) { return getFullMenuItems(menu.getMenuItems()); } else { return new ArrayList<>(); } } public Iterable<String> getOrderItems() { List<String> items = new ArrayList<>(); for(OrderItem item : currentOrder.getSetOfItems()) { items.add(getOrderItemString(item)); } return items; } public String getItemName(String itemString) { String[] split = itemString.split(" : "); return split[0]; } public int getOrderID(String orderString) { String id = orderString.substring("Order #".length()); try { return Integer.parseInt(id); } catch(NumberFormatException ex) { return -1; } } public String getOrderItemName(String orderItemString) { return orderItemString.substring(0, orderItemString.lastIndexOf("x")).trim(); } private Menu getSelectedMenu(String menuName) { Collection<Menu> menus = store.getSetOfMenus(); for(Menu menu : menus) { if(Objects.equals(menu.getMenuName(), menuName)) { return menu; } } return null; } private Item getSelectedItem(String itemName) { Collection<Item> items = store.getSetOfItems(); for(Item item : items) { if(Objects.equals(item.getItemName(), itemName)) { return item; } } return null; } private Iterable<String> getMenuItems(Collection<Item> items) { List<String> itemList = new ArrayList<>(); for(Item item : items) { itemList.add(item.getItemName()); } return itemList; } private Iterable<String> getFullMenuItems(Collection<Item> items) { List<String> itemList = new ArrayList<>(); for(Item item : items) { itemList.add(getItemString(item)); } return itemList; } private String getItemString(Item item) { String s = item.getItemName() + " : " + item.getItemDescription() + " $" + roundToTwo(item.getCurrentPrice()); if(item.isSpecial()) { s += " [Special]"; } return s; } private String getOrderString(Order order) { return "Order #" + order.getOrderID(); } private String getOrderItemString(OrderItem item) { return item.getItem().getItemName() + " x" + item.getQuantity() + " $" + roundToTwo(item.computeSubtotal()); } private double roundToTwo(double d) { return Math.round(d * 100.0) / 100.0; } private boolean isValidMenuName(String name) { if(name == null || name.trim().isEmpty()) { return false; } Iterable<String> menuNames = getMenus(); for(String menuName : menuNames) { if(Objects.equals(name, menuName)) { return false; } } return true; } private boolean isValidMenuItemName(String name) { if(name == null || name.trim().isEmpty() || name.contains(":")) { return false; } Iterable<String> itemNames = getAllMenuItems(); for(String itemName : itemNames) { if(Objects.equals(name, itemName)) { return false; } } return true; } private Collection<Item> getItemsNotOnMenu(Menu menu) { Collection<Item> items = new LinkedHashSet<>(store.getSetOfItems()); items.removeAll(menu.getMenuItems()); return items; } private Collection<Order> getIncompleteOrdersSet() { Collection<Order> allOrders = store.getListOfPlacedOrder(); Collection<Order> incompleteOrders = new LinkedHashSet<>(); for(Order order : allOrders) { if(order.isComplete()) { continue; } incompleteOrders.add(order); } return incompleteOrders; } }
package com.ppa8ball.service; import java.util.Collections; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.criterion.Order; import com.ppa8ball.models.Season; public class SeasonServiceImpl implements SeasonService { private Session session; public SeasonServiceImpl(Session session) { this.session = session; } @Override public void Save(Season season) { session.beginTransaction(); session.saveOrUpdate(season); session.getTransaction().commit(); } @Override public Season GetCurrent() { Criteria cr = session.createCriteria(Season.class); List<Season> seasons = cr.list(); Collections.sort(seasons ,Collections.reverseOrder()); return seasons.get(0); } @Override public Season Get(long id) { return (Season) session.get(Season.class, id); } }
package org.sugr.gearshift; import android.animation.Animator; import android.animation.AnimatorInflater; import android.animation.ValueAnimator; import android.annotation.TargetApi; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.text.Html; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import org.sugr.gearshift.datasource.DataSource; import org.sugr.gearshift.service.DataService; import org.sugr.gearshift.service.DataServiceManager; import org.sugr.gearshift.util.Base64; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.ArrayList; import java.util.Date; public class TorrentListActivity extends BaseTorrentActivity implements TorrentListFragment.Callbacks { public static final String ARG_FILE_URI = "torrent_file_uri"; public static final String ARG_FILE_PATH = "torrent_file_path"; public final static String ACTION_OPEN = "torrent_file_open_action"; /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ private boolean twoPaneLayout; private boolean intentConsumed = false; private boolean newTorrentDialogVisible = false; private boolean hasNewIntent = false; private boolean hasFatalError = false; private long lastServerActivity; private static final String STATE_INTENT_CONSUMED = "intent_consumed"; private static final String STATE_CURRENT_PROFILE = "current_profile"; private static final String STATE_FATAL_ERROR = "fatal_error"; private static final String STATE_LAST_SERVER_ACTIVITY = "last_server_activity"; private static final int BROWSE_REQUEST_CODE = 1; private DrawerLayout drawerLayout; private ActionBarDrawerToggle drawerToggle; private ValueAnimator detailSlideAnimator; private boolean detailPanelVisible; private int currentTorrentIndex = -1; private TransmissionProfileListAdapter profileAdapter; private boolean altSpeed = false; private boolean preventRefreshIndicator; private int expecting = 0; private static class Expecting { static int ALT_SPEED_ON = 1; static int ALT_SPEED_OFF = 1 << 1; } private LoaderManager.LoaderCallbacks<TransmissionProfile[]> profileLoaderCallbacks= new LoaderManager.LoaderCallbacks<TransmissionProfile[]>() { @Override public android.support.v4.content.Loader<TransmissionProfile[]> onCreateLoader( int id, Bundle args) { return new TransmissionProfileSupportLoader(TorrentListActivity.this); } @Override public void onLoadFinished( android.support.v4.content.Loader<TransmissionProfile[]> loader, TransmissionProfile[] profiles) { profile = null; profileAdapter.clear(); if (profiles.length > 0) { profileAdapter.addAll(profiles); } else { profileAdapter.add(TransmissionProfileListAdapter.EMPTY_PROFILE); TransmissionProfile.setCurrentProfile(null, TorrentListActivity.this); setRefreshing(false, DataService.Requests.GET_TORRENTS); } String currentId = TransmissionProfile.getCurrentProfileId(TorrentListActivity.this); int index = 0; for (TransmissionProfile prof : profiles) { if (prof.getId().equals(currentId)) { ActionBar actionBar = getActionBar(); if (actionBar != null) actionBar.setSelectedNavigationItem(index); setProfile(prof); break; } index++; } if (profile == null) { if (profiles.length > 0) { setProfile(profiles[0]); } else { setProfile(null); /* TODO: should display the message that the user hasn't created a profile yet */ } } else { /* The torrents might be loaded before the navigation * callback fires, which will cause the refresh indicator to * appear until the next server request */ preventRefreshIndicator = true; } TransmissionProfile.setCurrentProfile(profile, TorrentListActivity.this); } @Override public void onLoaderReset( android.support.v4.content.Loader<TransmissionProfile[]> loader) { profileAdapter.clear(); } }; /* The callback will get garbage collected if its a mere anon class */ private SharedPreferences.OnSharedPreferenceChangeListener profileChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (profile == null) return; if (!key.endsWith(profile.getId())) return; profile.load(); TransmissionProfile.setCurrentProfile(profile, TorrentListActivity.this); setProfile(profile); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); serviceReceiver = new ServiceReceiver(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); G.DEBUG = prefs.getBoolean(G.PREF_DEBUG, false); setContentView(R.layout.activity_torrent_list); PreferenceManager.setDefaultValues(this, R.xml.general_preferences, false); PreferenceManager.setDefaultValues(this, R.xml.sort_preferences, false); if (findViewById(R.id.torrent_detail_panel) != null) { // The detail container view will be present only in the // large-screen layouts (res/values-large and // res/values-sw600dp). If this view is present, then the // activity should be in two-pane mode. twoPaneLayout = true; // In two-pane mode, list items should be given the // 'activated' state when touched. ((TorrentListFragment) getSupportFragmentManager() .findFragmentById(R.id.torrent_list)) .setActivateOnItemClick(true); final LinearLayout slidingLayout = (LinearLayout) findViewById(R.id.sliding_layout); final View detailPanel = findViewById(R.id.torrent_detail_panel); detailSlideAnimator = (ValueAnimator) AnimatorInflater.loadAnimator(this, R.anim.weight_animator); detailSlideAnimator.setDuration(getResources().getInteger(android.R.integer.config_shortAnimTime)); detailSlideAnimator.setInterpolator(new DecelerateInterpolator()); detailSlideAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { final FragmentManager fm = getSupportFragmentManager(); TorrentDetailFragment fragment = (TorrentDetailFragment) fm.findFragmentByTag( G.DETAIL_FRAGMENT_TAG); if (fragment == null) { fragment = new TorrentDetailFragment(); fragment.setArguments(new Bundle()); fm.beginTransaction() .replace(R.id.torrent_detail_container, fragment, G.DETAIL_FRAGMENT_TAG) .commit(); fm.executePendingTransactions(); } fragment.setCurrentTorrent(currentTorrentIndex); G.logD("Opening the detail panel"); manager.setDetails(true); new TorrentTask(TorrentListActivity.this, TorrentTask.Flags.UPDATE).execute(); fragment.onCreateOptionsMenu(menu, getMenuInflater()); Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { View bg=findViewById(R.id.torrent_detail_placeholder_background); if (bg != null) { bg.setVisibility(View.GONE); } View pager = findViewById(R.id.torrent_detail_pager); pager.setVisibility(View.VISIBLE); pager.animate().alpha((float) 1.0); } }); } @Override public void onAnimationCancel(Animator animation) { } }); detailSlideAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (Float) animation.getAnimatedValue(); LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) detailPanel.getLayoutParams(); params.weight=value; slidingLayout.requestLayout(); } }); } if (savedInstanceState == null) { setRefreshing(true, DataService.Requests.GET_TORRENTS); } else { if (savedInstanceState.containsKey(STATE_INTENT_CONSUMED)) { intentConsumed = savedInstanceState.getBoolean(STATE_INTENT_CONSUMED); } } getWindow().setBackgroundDrawable(null); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, findViewById(R.id.sliding_menu_frame)); drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer) { }; drawerLayout.setDrawerListener(drawerToggle); if (twoPaneLayout) { toggleRightPane(false); } ActionBar actionBar = getActionBar(); if (actionBar != null) { actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); profileAdapter = new TransmissionProfileListAdapter(this); actionBar.setListNavigationCallbacks(profileAdapter, new ActionBar.OnNavigationListener() { @Override public boolean onNavigationItemSelected(int pos, long id) { TransmissionProfile profile = profileAdapter.getItem(pos); if (profile != TransmissionProfileListAdapter.EMPTY_PROFILE) { if (TorrentListActivity.this.profile != null) { SharedPreferences prefs = TransmissionProfile.getPreferences(TorrentListActivity.this); if (prefs != null) prefs.unregisterOnSharedPreferenceChangeListener(profileChangeListener); } TransmissionProfile.setCurrentProfile(profile, TorrentListActivity.this); setProfile(profile); SharedPreferences prefs = TransmissionProfile.getPreferences(TorrentListActivity.this); if (prefs != null) prefs.registerOnSharedPreferenceChangeListener(profileChangeListener); if (preventRefreshIndicator) { preventRefreshIndicator = false; } else { setRefreshing(true, DataService.Requests.GET_TORRENTS); } } return false; } }); actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE); } if (savedInstanceState != null) { if (savedInstanceState.containsKey(STATE_CURRENT_PROFILE)) { profile = savedInstanceState.getParcelable(STATE_CURRENT_PROFILE); manager = new DataServiceManager(this, profile.getId()) .onRestoreInstanceState(savedInstanceState).startUpdating(); new SessionTask(this).execute(SessionTask.Flags.START_TORRENT_TASK); } if (savedInstanceState.containsKey(STATE_FATAL_ERROR)) { hasFatalError = savedInstanceState.getBoolean(STATE_FATAL_ERROR, false); } if (savedInstanceState.containsKey(STATE_LAST_SERVER_ACTIVITY)) { lastServerActivity = savedInstanceState.getLong(STATE_LAST_SERVER_ACTIVITY, 0); } } getSupportLoaderManager().initLoader(G.PROFILES_LOADER_ID, null, profileLoaderCallbacks); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); drawerToggle.onConfigurationChanged(newConfig); } /** * Callback method from {@link TorrentListFragment.Callbacks} * indicating that the item with the given ID was selected. */ @Override public void onItemSelected(int position) { if (twoPaneLayout) { currentTorrentIndex = position; if (!toggleRightPane(true)) { TorrentDetailFragment fragment = (TorrentDetailFragment) getSupportFragmentManager().findFragmentByTag( G.DETAIL_FRAGMENT_TAG); if (fragment != null) { fragment.setCurrentTorrent(currentTorrentIndex); } } } else { // In single-pane mode, simply start the detail activity // for the selected item ID. Intent detailIntent = new Intent(this, TorrentDetailActivity.class); detailIntent.putExtra(G.ARG_PAGE_POSITION, position); detailIntent.putExtra(G.ARG_PROFILE, profile); detailIntent.putExtra(G.ARG_SESSION, session); startActivity(detailIntent); } } @Override public void onPageSelected(int position) { if (twoPaneLayout) { ((TorrentListFragment) getSupportFragmentManager() .findFragmentById(R.id.torrent_list)) .getListView().setItemChecked(position, true); } } @Override public void onBackPressed() { TorrentListFragment fragment = ((TorrentListFragment) getSupportFragmentManager() .findFragmentById(R.id.torrent_list)); int position = fragment.getListView().getCheckedItemPosition(); if (position == ListView.INVALID_POSITION) { super.onBackPressed(); } else { toggleRightPane(false); fragment.getListView().setItemChecked(position, false); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); this.menu = menu; getMenuInflater().inflate(R.menu.torrent_list_activity, menu); setSession(session); setRefreshing(refreshing, refreshType); setAltSpeed(altSpeed); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (drawerLayout.getDrawerLockMode( findViewById(R.id.sliding_menu_frame) ) == DrawerLayout.LOCK_MODE_UNLOCKED && drawerToggle.onOptionsItemSelected(item)) { return true; } Intent intent; switch(item.getItemId()) { case android.R.id.home: if (!twoPaneLayout) { return super.onOptionsItemSelected(item); } TorrentListFragment fragment = ((TorrentListFragment) getSupportFragmentManager() .findFragmentById(R.id.torrent_list)); int position = fragment.getListView().getCheckedItemPosition(); if (position == ListView.INVALID_POSITION) { return true; } else { toggleRightPane(false); fragment.getListView().setItemChecked(position, false); return true; } case R.id.menu_alt_speed: expecting&= ~(Expecting.ALT_SPEED_ON | Expecting.ALT_SPEED_OFF); if (altSpeed) { setAltSpeed(false); expecting|= Expecting.ALT_SPEED_OFF; } else { setAltSpeed(true); expecting|= Expecting.ALT_SPEED_ON; } session.setAltSpeedLimitEnabled(altSpeed); manager.setSession(session, "alt-speed-enabled"); return true; case R.id.menu_refresh: manager.update(); setRefreshing(true, DataService.Requests.GET_TORRENTS); return true; case R.id.menu_add_torrent: showAddTorrentDialog(); break; case R.id.menu_session_settings: intent = new Intent(this, TransmissionSessionActivity.class); intent.putExtra(G.ARG_PROFILE, profile); intent.putExtra(G.ARG_SESSION, session); startActivity(intent); return true; case R.id.menu_settings: intent = new Intent(this, SettingsActivity.class); if (session != null) { ArrayList<String> directories = new ArrayList<>(session.getDownloadDirectories()); directories.remove(session.getDownloadDir()); intent.putExtra(G.ARG_DIRECTORIES, directories); } if (profile != null) { intent.putExtra(G.ARG_PROFILE_ID, profile.getId()); } startActivity(intent); return true; case R.id.menu_about: intent = new Intent(this, AboutActivity.class); startActivity(intent); return true; } if (twoPaneLayout) { Fragment fragment = getSupportFragmentManager().findFragmentByTag(G.DETAIL_FRAGMENT_TAG); if (fragment != null && fragment.onOptionsItemSelected(item)) { return true; } } return super.onOptionsItemSelected(item); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putBoolean(STATE_INTENT_CONSUMED, intentConsumed); outState.putParcelable(STATE_CURRENT_PROFILE, profile); outState.putBoolean(STATE_FATAL_ERROR, hasFatalError); outState.putLong(STATE_LAST_SERVER_ACTIVITY, lastServerActivity); if (manager != null) { manager.onSaveInstanceState(outState); } } @Override public void onNewIntent(Intent intent) { if (!newTorrentDialogVisible) { intentConsumed = false; hasNewIntent = true; setIntent(intent); setRefreshing(true, null); /* Less than a minute ago */ if (new Date().getTime() - lastServerActivity < 60000) { consumeIntent(); } else if (manager != null) { manager.getSession(); } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent resultData) { if (requestCode == BROWSE_REQUEST_CODE && resultCode == Activity.RESULT_OK) { if (resultData != null) { Uri uri = resultData.getData(); new ReadTorrentDataTask().execute(uri); Toast.makeText(this, R.string.reading_torrent_file, Toast.LENGTH_SHORT).show(); } } } public DataServiceManager getDataServiceManager() { return manager; } public boolean isDetailPanelVisible() { return twoPaneLayout && detailPanelVisible; } private boolean toggleRightPane(boolean show) { if (!twoPaneLayout) return false; View pager = findViewById(R.id.torrent_detail_pager); if (show) { if (!detailPanelVisible) { detailPanelVisible = true; detailSlideAnimator.start(); return true; } } else { if (detailPanelVisible) { detailPanelVisible = false; LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) findViewById(R.id.torrent_detail_panel).getLayoutParams(); params.weight = 0; if (pager != null) { pager.setAlpha(0); pager.setVisibility(View.GONE); } manager.setDetails(false); FragmentManager manager = getSupportFragmentManager(); TorrentDetailFragment fragment = (TorrentDetailFragment) manager.findFragmentByTag(G.DETAIL_FRAGMENT_TAG); if (fragment != null) { fragment.removeMenuEntries(); } return true; } } return false; } public void setProfile(TransmissionProfile profile) { if (this.profile == profile || (this.profile != null && profile != null && profile.getId().equals(this.profile.getId()))) { return; } this.profile = profile; toggleRightPane(false); if (manager != null) { manager.reset(); } if (profile != null) { manager = new DataServiceManager(this, profile.getId()).startUpdating(); new SessionTask(this).execute(SessionTask.Flags.START_TORRENT_TASK); } } @Override public void setSession(TransmissionSession session) { if (session == null) { if (this.session != null) { drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, findViewById(R.id.sliding_menu_frame)); getActionBar().setDisplayHomeAsUpEnabled(false); invalidateOptionsMenu(); } this.session = null; if (menu != null) { menu.findItem(R.id.menu_session_settings).setVisible(false); } } else { boolean initial = false; if (this.session == null) { drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, findViewById(R.id.sliding_menu_frame)); getActionBar().setDisplayHomeAsUpEnabled(true); invalidateOptionsMenu(); initial = true; } else if (session.getRPCVersion() >= TransmissionSession.FREE_SPACE_METHOD_RPC_VERSION) { session.setDownloadDirFreeSpace(this.session.getDownloadDirFreeSpace()); } this.session = session; if (menu != null) { menu.findItem(R.id.menu_session_settings).setVisible(true); } if (initial && !intentConsumed && !newTorrentDialogVisible) { consumeIntent(); } } } private void setAltSpeed(boolean alt) { if (menu == null) { return; } altSpeed = alt; MenuItem altSpeed = menu.findItem(R.id.menu_alt_speed); MenuItem addTorrent = menu.findItem(R.id.menu_add_torrent); if (session == null) { altSpeed.setVisible(false); addTorrent.setVisible(false); } else { altSpeed.setVisible(true); addTorrent.setVisible(true); if (this.altSpeed) { altSpeed.setIcon(R.drawable.ic_action_data_usage_on); altSpeed.setTitle(R.string.alt_speed_label_off); } else { altSpeed.setIcon(R.drawable.ic_action_data_usage); altSpeed.setTitle(R.string.alt_speed_label_on); } } } private void consumeIntent() { Intent intent = getIntent(); String action = intent.getAction(); if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0 && (Intent.ACTION_VIEW.equals(action) || ACTION_OPEN.equals(action))) { Uri data = intent.getData(); String fileURI = intent.getStringExtra(ARG_FILE_URI); String filePath = intent.getStringExtra(ARG_FILE_PATH); showNewTorrentDialog(data, fileURI, filePath, null); } else { intentConsumed = true; } } private void showNewTorrentDialog(final Uri data, final String fileURI, final String filePath, final Uri documentUri) { if (manager == null || session == null) { return; } newTorrentDialogVisible = true; LocationDialogHelper helper = new LocationDialogHelper(this); int title; DialogInterface.OnClickListener okListener; if (data != null && data.getScheme().equals("magnet")) { title = R.string.add_new_magnet; okListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Spinner location = (Spinner) ((AlertDialog) dialog).findViewById(R.id.location_choice); EditText entry = (EditText) ((AlertDialog) dialog).findViewById(R.id.location_entry); CheckBox paused = (CheckBox) ((AlertDialog) dialog).findViewById(R.id.start_paused); String dir; if (location.getVisibility() != View.GONE) { dir = (String) location.getSelectedItem(); } else { dir = entry.getText().toString(); } if (TextUtils.isEmpty(dir)) { dir = session.getDownloadDir(); } manager.addTorrent(data.toString(), null, dir, paused.isChecked(), null, null); setRefreshing(true, DataService.Requests.ADD_TORRENT); intentConsumed = true; newTorrentDialogVisible = false; } }; } else if (fileURI != null) { title = R.string.add_new_torrent; okListener = new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { Spinner location = (Spinner) ((AlertDialog) dialog).findViewById(R.id.location_choice); EditText entry = (EditText) ((AlertDialog) dialog).findViewById(R.id.location_entry); CheckBox paused = (CheckBox) ((AlertDialog) dialog).findViewById(R.id.start_paused); CheckBox deleteLocal = (CheckBox) ((AlertDialog) dialog).findViewById(R.id.delete_local); BufferedReader reader = null; try { String dir; if (location.getVisibility() != View.GONE) { dir = (String) location.getSelectedItem(); } else { dir = entry.getText().toString(); } File file = new File(new URI(fileURI)); reader = new BufferedReader(new FileReader(file)); StringBuilder filedata = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { filedata.append(line).append("\n"); } if (!file.delete()) { Toast.makeText(TorrentListActivity.this, R.string.error_deleting_torrent_file, Toast.LENGTH_SHORT).show(); } String path = filePath; Uri uri = documentUri; if (!deleteLocal.isChecked()) { path = null; uri = null; } manager.addTorrent(null, filedata.toString(), dir, paused.isChecked(), path, uri); setRefreshing(true, DataService.Requests.ADD_TORRENT); } catch (Exception e) { Toast.makeText(TorrentListActivity.this, R.string.error_reading_torrent_file, Toast.LENGTH_SHORT).show(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } intentConsumed = true; newTorrentDialogVisible = false; } }; } else { return; } AlertDialog dialog = helper.showDialog(R.layout.new_torrent_dialog, title, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { intentConsumed = true; newTorrentDialogVisible = false; } }, okListener ); CheckBox startPaused = (CheckBox) dialog.findViewById(R.id.start_paused); startPaused.setChecked(profile != null && profile.getStartPaused()); CheckBox deleteLocal = (CheckBox) dialog.findViewById(R.id.delete_local); deleteLocal.setChecked(profile != null && profile.getDeleteLocal()); if (fileURI != null) { deleteLocal.setVisibility(View.VISIBLE); } } private void showAddTorrentDialog() { LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.add_torrent_dialog, null); AlertDialog.Builder builder = new AlertDialog.Builder(this) .setCancelable(true) .setView(view) .setTitle(R.string.add_torrent) .setNegativeButton(android.R.string.cancel, null) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText magnet = (EditText) ((AlertDialog) dialog).findViewById(R.id.magnet_link); Uri data = Uri.parse(magnet.getText().toString()); if (data != null && "magnet".equals(data.getScheme())) { showNewTorrentDialog(data, null, null, null); } else { Toast.makeText(TorrentListActivity.this, R.string.invalid_magnet_link, Toast.LENGTH_SHORT).show(); } } }); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { builder.setNeutralButton(R.string.browse, new DialogInterface.OnClickListener() { @TargetApi(Build.VERSION_CODES.KITKAT) @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("application/x-bittorrent"); startActivityForResult(intent, BROWSE_REQUEST_CODE); } }); } AlertDialog dialog = builder.create(); dialog.show(); } private static class TransmissionProfileListAdapter extends ArrayAdapter<TransmissionProfile> { public static final TransmissionProfile EMPTY_PROFILE = new TransmissionProfile(null); public TransmissionProfileListAdapter(Context context) { super(context, 0); add(EMPTY_PROFILE); } @Override public View getView(int position, View convertView, ViewGroup parent) { View rowView = convertView; TransmissionProfile profile = getItem(position); if (rowView == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = vi.inflate(R.layout.torrent_profile_selector, null); } TextView name = (TextView) rowView.findViewById(R.id.name); TextView summary = (TextView) rowView.findViewById(R.id.summary); if (profile == EMPTY_PROFILE) { name.setText(R.string.no_profiles); if (summary != null) summary.setText(R.string.create_profile_in_settings); } else { name.setText(profile.getName()); if (summary != null) summary.setText((profile.getUsername().length() > 0 ? profile.getUsername() + "@" : "") + profile.getHost() + ":" + profile.getPort()); } return rowView; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View rowView = convertView; if (rowView == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = vi.inflate(R.layout.torrent_profile_selector_dropdown, null); } return getView(position, rowView, parent); } } private class ServiceReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { int error = intent.getIntExtra(G.ARG_ERROR, 0); hasFatalError = false; String type = intent.getStringExtra(G.ARG_REQUEST_TYPE); switch (type) { case DataService.Requests.GET_SESSION: case DataService.Requests.SET_SESSION: case DataService.Requests.GET_TORRENTS: case DataService.Requests.ADD_TORRENT: case DataService.Requests.REMOVE_TORRENT: case DataService.Requests.SET_TORRENT: case DataService.Requests.SET_TORRENT_ACTION: case DataService.Requests.SET_TORRENT_LOCATION: case DataService.Requests.GET_FREE_SPACE: setRefreshing(false, type); lastServerActivity = new Date().getTime(); if (error == 0) { findViewById(R.id.fatal_error_layer).setVisibility(View.GONE); int flags = TorrentTask.Flags.CONNECTED; switch (type) { case DataService.Requests.GET_SESSION: new SessionTask(TorrentListActivity.this).execute(); break; case DataService.Requests.SET_SESSION: manager.getSession(); break; case DataService.Requests.GET_TORRENTS: boolean added = intent.getBooleanExtra(G.ARG_ADDED, false); boolean removed = intent.getBooleanExtra(G.ARG_REMOVED, false); boolean statusChanged = intent.getBooleanExtra(G.ARG_STATUS_CHANGED, false); boolean incomplete = intent.getBooleanExtra(G.ARG_INCOMPLETE_METADATA, false); if (added) { flags |= TorrentTask.Flags.HAS_ADDED; } if (removed) { flags |= TorrentTask.Flags.HAS_REMOVED; } if (statusChanged) { flags |= TorrentTask.Flags.HAS_STATUS_CHANGED; } if (incomplete) { flags |= TorrentTask.Flags.HAS_INCOMPLETE_METADATA; } new TorrentTask(TorrentListActivity.this, flags).execute(); break; case DataService.Requests.ADD_TORRENT: manager.update(); flags |= TorrentTask.Flags.HAS_ADDED | TorrentTask.Flags.HAS_INCOMPLETE_METADATA; new TorrentTask(TorrentListActivity.this, flags).execute(); break; case DataService.Requests.REMOVE_TORRENT: manager.update(); flags |= TorrentTask.Flags.HAS_REMOVED; new TorrentTask(TorrentListActivity.this, flags).execute(); break; case DataService.Requests.SET_TORRENT_LOCATION: manager.update(); flags |= TorrentTask.Flags.HAS_ADDED | TorrentTask.Flags.HAS_REMOVED; new TorrentTask(TorrentListActivity.this, flags).execute(); break; case DataService.Requests.SET_TORRENT: case DataService.Requests.SET_TORRENT_ACTION: manager.update(); flags |= TorrentTask.Flags.HAS_STATUS_CHANGED; new TorrentTask(TorrentListActivity.this, flags).execute(); break; case DataService.Requests.GET_FREE_SPACE: long freeSpace = intent.getLongExtra(G.ARG_FREE_SPACE, 0); TransmissionSession session = getSession(); if (session != null && freeSpace != 0) { session.setDownloadDirFreeSpace(freeSpace); } break; } } else { if (error == TransmissionData.Errors.DUPLICATE_TORRENT) { Toast.makeText(TorrentListActivity.this, R.string.duplicate_torrent, Toast.LENGTH_SHORT).show(); } else if (error == TransmissionData.Errors.INVALID_TORRENT) { Toast.makeText(TorrentListActivity.this, R.string.invalid_torrent, Toast.LENGTH_SHORT).show(); } else { findViewById(R.id.fatal_error_layer).setVisibility(View.VISIBLE); TextView text = (TextView) findViewById(R.id.transmission_error); expecting = 0; hasFatalError = true; toggleRightPane(false); FragmentManager manager = getSupportFragmentManager(); TorrentListFragment fragment = (TorrentListFragment) manager.findFragmentById(R.id.torrent_list); if (fragment != null) { fragment.notifyTorrentListChanged(null, error, false, false, false, false, false); } if (error == TransmissionData.Errors.NO_CONNECTIVITY) { text.setText(Html.fromHtml(getString(R.string.no_connectivity_empty_list))); } else if (error == TransmissionData.Errors.ACCESS_DENIED) { text.setText(Html.fromHtml(getString(R.string.access_denied_empty_list))); } else if (error == TransmissionData.Errors.NO_JSON) { text.setText(Html.fromHtml(getString(R.string.no_json_empty_list))); } else if (error == TransmissionData.Errors.NO_CONNECTION) { text.setText(Html.fromHtml(getString(R.string.no_connection_empty_list))); } else if (error == TransmissionData.Errors.THREAD_ERROR) { text.setText(Html.fromHtml(getString(R.string.thread_error_empty_list))); } else if (error == TransmissionData.Errors.RESPONSE_ERROR) { text.setText(Html.fromHtml(getString(R.string.response_error_empty_list))); } else if (error == TransmissionData.Errors.TIMEOUT) { text.setText(Html.fromHtml(getString(R.string.timeout_empty_list))); } else if (error == TransmissionData.Errors.OUT_OF_MEMORY) { text.setText(Html.fromHtml(getString(R.string.out_of_memory_empty_list))); } else if (error == TransmissionData.Errors.JSON_PARSE_ERROR) { text.setText(Html.fromHtml(getString(R.string.json_parse_empty_list))); } } } break; } } } private class SessionTask extends AsyncTask<Integer, Void, TransmissionSession> { DataSource readSource; boolean startTorrentTask; public class Flags { public static final int START_TORRENT_TASK = 1; } public SessionTask(Context context) { super(); readSource = new DataSource(context); } @Override protected TransmissionSession doInBackground(Integer... flags) { try { readSource.open(); TransmissionSession session = readSource.getSession(); if (profile != null) { session.setDownloadDirectories(profile, readSource.getDownloadDirectories()); } if (flags.length == 1) { if ((flags[0] & Flags.START_TORRENT_TASK) == Flags.START_TORRENT_TASK) { startTorrentTask = true; } } return session; } finally { if (readSource.isOpen()) { readSource.close(); } } } @Override protected void onPostExecute(TransmissionSession session) { setSession(session); if (session.getRPCVersion() >= TransmissionSession.FREE_SPACE_METHOD_RPC_VERSION && manager != null) { manager.getFreeSpace(session.getDownloadDir()); } if (startTorrentTask) { new TorrentTask(TorrentListActivity.this, TorrentTask.Flags.UPDATE).execute(); } if (hasNewIntent && session != null) { hasNewIntent = false; if (!intentConsumed && !newTorrentDialogVisible) { consumeIntent(); } } } } private class TorrentTask extends AsyncTask<Void, Void, Cursor> { DataSource readSource; boolean added, removed, statusChanged, incompleteMetadata, update, connected; public class Flags { public static final int HAS_ADDED = 1; public static final int HAS_REMOVED = 1 << 1; public static final int HAS_STATUS_CHANGED = 1 << 2; public static final int HAS_INCOMPLETE_METADATA = 1 << 3; public static final int UPDATE = 1 << 4; public static final int CONNECTED = 1 << 5; } public TorrentTask(Context context, int flags) { super(); readSource = new DataSource(context); if ((flags & Flags.HAS_ADDED) == Flags.HAS_ADDED) { added = true; } if ((flags & Flags.HAS_REMOVED) == Flags.HAS_REMOVED) { removed = true; } if ((flags & Flags.HAS_STATUS_CHANGED) == Flags.HAS_STATUS_CHANGED) { statusChanged = true; } if ((flags & Flags.HAS_INCOMPLETE_METADATA) == Flags.HAS_INCOMPLETE_METADATA) { incompleteMetadata = true; } if ((flags & Flags.UPDATE) == Flags.UPDATE) { update = true; } if ((flags & Flags.CONNECTED) == Flags.CONNECTED) { connected = true; } } @Override protected Cursor doInBackground(Void... unused) { try { readSource.open(); Cursor cursor = readSource.getTorrentCursor(); /* Fill the cursor window */ cursor.getCount(); return cursor; } finally { if (readSource.isOpen()) { readSource.close(); } } } @Override protected void onPostExecute(Cursor cursor) { if (altSpeed == session.isAltSpeedLimitEnabled()) { expecting &= ~(Expecting.ALT_SPEED_ON | Expecting.ALT_SPEED_OFF); } else { if (expecting == 0 || (expecting & Expecting.ALT_SPEED_ON) > 0 && session.isAltSpeedLimitEnabled() || (expecting & Expecting.ALT_SPEED_OFF) > 0 && !session.isAltSpeedLimitEnabled()) { setAltSpeed(session.isAltSpeedLimitEnabled()); expecting &= ~(Expecting.ALT_SPEED_ON | Expecting.ALT_SPEED_OFF); } } FragmentManager fm = getSupportFragmentManager(); TorrentListFragment fragment = (TorrentListFragment) fm.findFragmentById(R.id.torrent_list); if (fragment != null) { fragment.notifyTorrentListChanged(cursor, 0, added, removed, statusChanged, incompleteMetadata, connected); } if (update) { update = false; if (manager != null) { manager.update(); } } } } private class ReadTorrentDataTask extends AsyncTask<Uri, Void, ReadTorrentDataTask.TaskData> { public class TaskData { public File file; public Uri uri; } @Override protected TaskData doInBackground(Uri... params) { if (params.length == 0) { return null; } Uri uri = params[0]; ContentResolver cr = getContentResolver(); InputStream stream = null; Base64.InputStream base64 = null; try { stream = cr.openInputStream(uri); base64 = new Base64.InputStream(stream, Base64.ENCODE | Base64.DO_BREAK_LINES); StringBuilder fileContent = new StringBuilder(""); int ch; while( (ch = base64.read()) != -1) fileContent.append((char)ch); File file = new File(TorrentListActivity.this.getCacheDir(), "torrentdata"); if (file.exists()) { //noinspection ResultOfMethodCallIgnored file.delete(); } if (file.createNewFile()) { BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.append(fileContent); bw.close(); G.logD("Torrent file uri: " + uri.toString()); TaskData data = new TaskData(); data.file = file; data.uri = uri; return data; } else { return null; } } catch (Exception e) { G.logE("Error while reading the torrent file", e); return null; } finally { try { if (base64 != null) base64.close(); if (stream != null) stream.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override protected void onPostExecute(TaskData data) { if (data == null) { Toast.makeText(TorrentListActivity.this, R.string.error_reading_torrent_file, Toast.LENGTH_SHORT).show(); } else { showNewTorrentDialog(null, data.file.toURI().toString(), null, data.uri); } } } }
package org.csstudio.alarm.beast.ui.alarmtable; import org.csstudio.alarm.beast.SeverityLevel; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; /** * * <code>SeverityAltColorProvider</code> provides alternate colors to be paired with severity colors. * Used together with SeverityColorProvider for the alarm table's message column for the foreground/background color. * * @author Boris Versic * */ public class SeverityColorPairProvider implements DisposeListener { /** Colors to be used as pairs for the configured severity colors. * Will be used for the text of given severity (or background, if painted reversed). * Can contain null values, denoting that the default color should be used for a given severity. */ final private Color colors[]; /** Initialize * @param parent Parent widget; dispose listener is added to allow cleanup * @throws Exception on error */ public SeverityColorPairProvider(final Composite parent) { colors = new Color[SeverityLevel.values().length]; parent.addDisposeListener(this); final String[] pref_colors = Preferences.getSeverityPairColors(); if (pref_colors.length == 0) return; final Display display = parent.getDisplay(); for (String pref : pref_colors) { final String[] values = pref.split(","); if (values.length != 4) continue; // ignore incorrect setting try { final String severity = values[0].trim(); final int red = Integer.parseInt(values[1].trim()); final int green = Integer.parseInt(values[2].trim()); final int blue = Integer.parseInt(values[3].trim()); SeverityLevel level = SeverityLevel.parse(severity); colors[level.ordinal()] = new Color(display, red, green, blue); // INVALID color pair is also used for UNDEFINED if (level == SeverityLevel.INVALID) colors[SeverityLevel.UNDEFINED.ordinal()] = new Color(display, red, green, blue); if (level == SeverityLevel.INVALID_ACK) colors[SeverityLevel.UNDEFINED_ACK.ordinal()] = new Color(display, red, green, blue); } catch (NumberFormatException ex) { continue; // ignore incorrect setting } } // If the *_ACK severity color pairs weren't specified, the // MAJOR, MINOR & INVALID color pair is used for them if (colors[SeverityLevel.MINOR_ACK.ordinal()] == null && colors[SeverityLevel.MINOR.ordinal()] != null) colors[SeverityLevel.MINOR_ACK.ordinal()] = new Color(display, colors[SeverityLevel.MINOR.ordinal()].getRGB()); if (colors[SeverityLevel.MAJOR_ACK.ordinal()] == null && colors[SeverityLevel.MAJOR.ordinal()] != null) colors[SeverityLevel.MAJOR_ACK.ordinal()] = new Color(display, colors[SeverityLevel.MAJOR.ordinal()].getRGB()); if (colors[SeverityLevel.INVALID_ACK.ordinal()] == null && colors[SeverityLevel.INVALID.ordinal()] != null) colors[SeverityLevel.INVALID_ACK.ordinal()] = new Color(display, colors[SeverityLevel.INVALID.ordinal()].getRGB()); } /** @see DisposeListener */ @Override public void widgetDisposed(DisposeEvent e) { for (Color color : colors) if (color != null) color.dispose(); } /** Obtain the color to be used as the color-pair for the given severity level, or null if default should be used. * @param severity SeverityLevel * @return Color for that level or null if default should be used */ public Color getColor(final SeverityLevel severity) { return colors[severity.ordinal()]; } }
package com.sandwell.JavaSimulation; import javax.swing.JFrame; import com.jaamsim.events.ProcessTarget; import com.jaamsim.input.InputAgent; import com.jaamsim.input.Keyword; import com.jaamsim.input.Output; import com.jaamsim.input.ValueInput; import com.jaamsim.ui.EditBox; import com.jaamsim.ui.EntityPallet; import com.jaamsim.ui.ExceptionBox; import com.jaamsim.ui.FrameBox; import com.jaamsim.ui.LogBox; import com.jaamsim.ui.OutputBox; import com.jaamsim.ui.PropertyBox; import com.jaamsim.units.TimeUnit; import com.sandwell.JavaSimulation3D.Clock; import com.sandwell.JavaSimulation3D.GUIFrame; import com.sandwell.JavaSimulation3D.ObjectSelector; /** * Class Simulation - Sandwell Discrete Event Simulation * <p> * Class structure defining essential simulation objects. Eventmanager is * instantiated to manage events generated in the simulation. Function prototypes * are defined which any simulation must define in order to run. */ public class Simulation extends Entity { @Keyword(description = "The initialization period for the simulation run. The model will " + "run for the initialization period and then clear the statistics " + "and execute for the specified run duration. The total length of the " + "simulation run will be the sum of Initialization and Duration.", example = "Simulation Initialization { 720 h }") private static final ValueInput initializationTime; @Keyword(description = "Date at which the simulation run is started (yyyy-mm-dd). This " + "input has no effect on the simulation results unless the seasonality " + "factors vary from month to month.", example = "Simulation StartDate { 2011-01-01 }") private static final StringInput startDate; @Keyword(description = "Time at which the simulation run is started (hh:mm).", example = "Simulation StartTime { 2160 h }") private static final ValueInput startTimeInput; @Keyword(description = "The duration of the simulation run in which all statistics will be recorded.", example = "Simulation Duration { 8760 h }") private static final ValueInput runDuration; @Keyword(description = "The number of discrete time units in one hour.", example = "Simulation SimulationTimeScale { 4500 }") private static final DoubleInput simTimeScaleInput; @Keyword(description = "If the value is TRUE, then the input report file will be printed after loading the " + "configuration file. The input report can always be generated when needed by selecting " + "\"Print Input Report\" under the File menu.", example = "Simulation PrintInputReport { TRUE }") private static final BooleanInput printInputReport; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private static final BooleanInput traceEventsInput; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private static final BooleanInput verifyEventsInput; @Keyword(description = "The real time speed up factor", example = "RunControl RealTimeFactor { 1200 }") private static final IntegerInput realTimeFactor; public static final int DEFAULT_REAL_TIME_FACTOR = 10000; public static final int MIN_REAL_TIME_FACTOR = 1; public static final int MAX_REAL_TIME_FACTOR= 1000000; @Keyword(description = "A Boolean to turn on or off real time in the simulation run", example = "RunControl RealTime { TRUE }") private static final BooleanInput realTime; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private static final BooleanInput exitAtStop; @Keyword(description = "Indicates whether the Model Builder tool should be shown on startup.", example = "Simulation ShowModelBuilder { TRUE }") private static final BooleanInput showModelBuilder; @Keyword(description = "Indicates whether the Object Selector tool should be shown on startup.", example = "Simulation ShowObjectSelector { TRUE }") private static final BooleanInput showObjectSelector; @Keyword(description = "Indicates whether the Input Editor tool should be shown on startup.", example = "Simulation ShowInputEditor { TRUE }") private static final BooleanInput showInputEditor; @Keyword(description = "Indicates whether the Output Viewer tool should be shown on startup.", example = "Simulation ShowOutputViewer { TRUE }") private static final BooleanInput showOutputViewer; @Keyword(description = "Indicates whether the Output Viewer tool should be shown on startup.", example = "Simulation ShowPropertyViewer { TRUE }") private static final BooleanInput showPropertyViewer; @Keyword(description = "Indicates whether the Log Viewer tool should be shown on startup.", example = "Simulation ShowLogViewer { TRUE }") private static final BooleanInput showLogViewer; private static double startTime; private static double endTime; private static Simulation myInstance; private static String modelName = "JaamSim"; static { initializationTime = new ValueInput("InitializationDuration", "Key Inputs", 0.0); initializationTime.setUnitType(TimeUnit.class); initializationTime.setValidRange(0.0d, Double.POSITIVE_INFINITY); runDuration = new ValueInput("RunDuration", "Key Inputs", 31536000.0d); runDuration.setUnitType(TimeUnit.class); runDuration.setValidRange(1e-15d, Double.POSITIVE_INFINITY); startDate = new StringInput("StartDate", "Key Inputs", null); startTimeInput = new ValueInput("StartTime", "Key Inputs", 0.0d); startTimeInput.setUnitType(TimeUnit.class); startTimeInput.setValidRange(0.0d, Double.POSITIVE_INFINITY); simTimeScaleInput = new DoubleInput("SimulationTimeScale", "Key Inputs", 4000.0d); simTimeScaleInput.setValidRange(1e-15d, Double.POSITIVE_INFINITY); traceEventsInput = new BooleanInput("TraceEvents", "Key Inputs", false); verifyEventsInput = new BooleanInput("VerifyEvents", "Key Inputs", false); printInputReport = new BooleanInput("PrintInputReport", "Key Inputs", false); realTimeFactor = new IntegerInput("RealTimeFactor", "Key Inputs", DEFAULT_REAL_TIME_FACTOR); realTimeFactor.setValidRange(MIN_REAL_TIME_FACTOR, MAX_REAL_TIME_FACTOR); realTime = new BooleanInput("RealTime", "Key Inputs", false); exitAtStop = new BooleanInput("ExitAtStop", "Key Inputs", false); showModelBuilder = new BooleanInput("ShowModelBuilder", "Key Inputs", false); showObjectSelector = new BooleanInput("ShowObjectSelector", "Key Inputs", false); showInputEditor = new BooleanInput("ShowInputEditor", "Key Inputs", false); showOutputViewer = new BooleanInput("ShowOutputViewer", "Key Inputs", false); showPropertyViewer = new BooleanInput("ShowPropertyViewer", "Key Inputs", false); showLogViewer = new BooleanInput("ShowLogViewer", "Key Inputs", false); // Create clock Clock.setStartDate(2000, 1, 1); // Initialize basic model information startTime = 0.0; endTime = 8760.0; } { this.addInput(runDuration); this.addInput(initializationTime); this.addInput(startDate); this.addInput(startTimeInput); this.addInput(simTimeScaleInput); this.addInput(traceEventsInput); this.addInput(verifyEventsInput); this.addInput(printInputReport); this.addInput(realTimeFactor); this.addInput(realTime); this.addInput(exitAtStop); this.addInput(showModelBuilder); this.addInput(showObjectSelector); this.addInput(showInputEditor); this.addInput(showOutputViewer); this.addInput(showPropertyViewer); this.addInput(showLogViewer); } public Simulation() {} public static Simulation getInstance() { if (myInstance == null) { for (Entity ent : Entity.getAll()) { if (ent instanceof Simulation ) { myInstance = (Simulation) ent; break; } } } return myInstance; } @Override public void validate() { super.validate(); if( startDate.getValue() != null && !Tester.isDate( startDate.getValue() ) ) { throw new InputErrorException("The value for Start Date must be a valid date."); } } @Override public void updateForInput( Input<?> in ) { super.updateForInput( in ); if(in == realTimeFactor || in == realTime) { updateRealTime(); return; } if (in == showModelBuilder) { setWindowVisible(EntityPallet.getInstance(), showModelBuilder.getValue()); return; } if (in == showObjectSelector) { setWindowVisible(ObjectSelector.getInstance(), showObjectSelector.getValue()); return; } if (in == showInputEditor) { setWindowVisible(EditBox.getInstance(), showInputEditor.getValue()); FrameBox.setSelectedEntity(ObjectSelector.currentEntity); return; } if (in == showOutputViewer) { setWindowVisible(OutputBox.getInstance(), showOutputViewer.getValue()); FrameBox.setSelectedEntity(ObjectSelector.currentEntity); return; } if (in == showPropertyViewer) { setWindowVisible(PropertyBox.getInstance(), showPropertyViewer.getValue()); FrameBox.setSelectedEntity(ObjectSelector.currentEntity); return; } if (in == showLogViewer) { setWindowVisible(LogBox.getInstance(), showLogViewer.getValue()); FrameBox.setSelectedEntity(ObjectSelector.currentEntity); return; } } public static void clear() { EventTracer.init(); root.clear(); root.setTraceListener(null); initializationTime.reset(); runDuration.reset(); simTimeScaleInput.reset(); traceEventsInput.reset(); verifyEventsInput.reset(); printInputReport.reset(); realTimeFactor.reset(); realTime.reset(); updateRealTime(); exitAtStop.reset(); startDate.reset(); startTimeInput.reset(); showModelBuilder.reset(); showObjectSelector.reset(); showInputEditor.reset(); showOutputViewer.reset(); showPropertyViewer.reset(); showLogViewer.reset(); // Create clock Clock.setStartDate(2000, 1, 1); // Initialize basic model information startTime = 0.0; endTime = 8760.0; // close warning/error trace file InputAgent.closeLogFile(); // Kill all entities except simulation while(Entity.getAll().size() > 0) { Entity ent = Entity.getAll().get(Entity.getAll().size()-1); ent.kill(); } } /** * Initializes and starts the model * 1) Initializes EventManager to accept events. * 2) calls startModel() to allow the model to add its starting events to EventManager * 3) start EventManager processing events */ public static void start() { // Validate each entity based on inputs only for (int i = 0; i < Entity.getAll().size(); i++) { try { Entity.getAll().get(i).validate(); } catch (Throwable e) { InputAgent.doError(e); ExceptionBox.instance().setInputError(Entity.getAll().get(i), e); return; } } InputAgent.prepareReportDirectory(); EventTracer.init(); root.clear(); root.setTraceListener(null); if( traceEventsInput.getValue() ) { EventTracer.traceAllEvents(root, traceEventsInput.getValue()); } else if( verifyEventsInput.getValue() ) { EventTracer.verifyAllEvents(root, verifyEventsInput.getValue()); } root.setSimTimeScale(simTimeScaleInput.getValue()); if( startDate.getValue() != null ) { Clock.getStartingDateFromString( startDate.getValue() ); } double startTimeHours = startTimeInput.getValue() / 3600.0d; startTime = Clock.calcTimeForYear_Month_Day_Hour(1, Clock.getStartingMonth(), Clock.getStartingDay(), startTimeHours); endTime = startTime + Simulation.getInitializationHours() + Simulation.getRunDurationHours(); root.scheduleProcess(0, Entity.PRIO_DEFAULT, false, new InitModelTarget()); } public static final void resume(double secs) { long ticks = root.secondsToNearestTick(secs); root.resume(ticks); } /** * Requests the EventManager to stop processing events. */ public static final void pause() { root.pause(); } /** * Requests the EventManager to stop processing events. */ public static final void stop() { root.pause(); root.clear(); GUIFrame.instance().updateForSimulationState(GUIFrame.SIM_STATE_STOPPED); // kill all generated objects for (int i = 0; i < Entity.getAll().size();) { Entity ent = Entity.getAll().get(i); if (ent.testFlag(Entity.FLAG_GENERATED)) ent.kill(); else i++; } } private static class StartUpTarget extends ProcessTarget { final Entity ent; StartUpTarget(Entity ent) { this.ent = ent; } @Override public String getDescription() { return ent.getInputName() + ".startUp"; } @Override public void process() { ent.startUp(); } } private static class InitModelTarget extends ProcessTarget { InitModelTarget() {} @Override public String getDescription() { return "SimulationInit"; } @Override public void process() { for (int i = 0; i < Entity.getAll().size(); i++) { Entity.getAll().get(i).earlyInit(); } long startTick = calculateDelayLength(Simulation.getStartHours()); root.scheduleProcess(startTick, Entity.PRIO_DEFAULT, false, new StartModelTarget()); long endTick = calculateDelayLength(Simulation.getEndHours()); root.scheduleProcess(endTick, Entity.PRIO_DEFAULT, false, new EndModelTarget()); } } private static class StartModelTarget extends ProcessTarget { StartModelTarget() {} @Override public String getDescription() { return "SimulationStart"; } @Override public void process() { for (int i = 0; i < Entity.getAll().size(); i++) { root.start(new StartUpTarget(Entity.getAll().get(i))); } } } private static class EndModelTarget extends ProcessTarget { EndModelTarget() {} @Override public String getDescription() { return "SimulationEnd"; } @Override public void process() { Simulation.pause(); for (int i = 0; i < Entity.getAll().size(); i++) { Entity.getAll().get(i).doEnd(); } System.out.println( "Made it to do end at" ); // close warning/error trace file InputAgent.closeLogFile(); if (Simulation.getExitAtStop() || InputAgent.getBatch()) GUIFrame.shutdown(0); Simulation.pause(); } } /** * Returns the end time of the run. * @return double - the time the current run will stop */ public static double getEndHours() { return endTime; } /** * Return the run duration for the run (not including intialization) */ public static double getRunDurationHours() { return runDuration.getValue() / 3600.0d; } /** * Returns the start time of the run. */ public static double getStartHours() { return startTime; } /** * Return the initialization duration in hours */ public static double getInitializationHours() { return initializationTime.getValue() / 3600.0d; } static void updateRealTime() { root.setExecuteRealTime(realTime.getValue(), realTimeFactor.getValue()); GUIFrame.instance().updateForRealTime(realTime.getValue(), realTimeFactor.getValue()); } public static void setRealTime(boolean rt) { StringVector t = new StringVector(1); if (rt) t.add("TRUE"); else t.add("FALSE"); realTime.parse(t); updateRealTime(); } public static void setRealTimeFactor(String fac) { StringVector t = new StringVector(1); t.add(fac); realTimeFactor.parse(t); updateRealTime(); } public static void setModelName(String newModelName) { modelName = newModelName; } public static String getModelName() { return modelName; } public static boolean getExitAtStop() { return exitAtStop.getValue(); } public static boolean getPrintInputReport() { return printInputReport.getValue(); } private static void setWindowVisible(JFrame f, boolean visible) { f.setVisible(visible); if (visible) f.toFront(); } /** * Re-open any Tools windows that have been closed temporarily. */ public static void showActiveTools() { setWindowVisible(EntityPallet.getInstance(), showModelBuilder.getValue()); setWindowVisible(ObjectSelector.getInstance(), showObjectSelector.getValue()); setWindowVisible(EditBox.getInstance(), showInputEditor.getValue()); setWindowVisible(OutputBox.getInstance(), showOutputViewer.getValue()); setWindowVisible(PropertyBox.getInstance(), showPropertyViewer.getValue()); setWindowVisible(LogBox.getInstance(), showLogViewer.getValue()); } @Output(name = "Configuration File", description = "The present configuration file.") public String getConfigFileName(double simTime) { return InputAgent.getConfigFile().getPath(); } }
package org.redisson; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.awaitility.Duration; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.redisson.ClusterRunner.ClusterProcesses; import org.redisson.RedisRunner.RedisProcess; import org.redisson.RedissonTopicPatternTest.Message; import org.redisson.api.RFuture; import org.redisson.api.RPatternTopic; import org.redisson.api.RSet; import org.redisson.api.RTopic; import org.redisson.api.RedissonClient; import org.redisson.api.listener.BaseStatusListener; import org.redisson.api.listener.MessageListener; import org.redisson.api.listener.PatternMessageListener; import org.redisson.api.listener.StatusListener; import org.redisson.client.codec.LongCodec; import org.redisson.client.codec.StringCodec; import org.redisson.config.Config; import org.redisson.config.SubscriptionMode; import org.redisson.connection.balancer.RandomLoadBalancer; public class RedissonTopicTest { @BeforeClass public static void beforeClass() throws IOException, InterruptedException { if (!RedissonRuntimeEnvironment.isTravis) { RedisRunner.startDefaultRedisServerInstance(); } } @AfterClass public static void afterClass() throws IOException, InterruptedException { if (!RedissonRuntimeEnvironment.isTravis) { RedisRunner.shutDownDefaultRedisServerInstance(); } } @Before public void before() throws IOException, InterruptedException { if (RedissonRuntimeEnvironment.isTravis) { RedisRunner.startDefaultRedisServerInstance(); } } @After public void after() throws InterruptedException { if (RedissonRuntimeEnvironment.isTravis) { RedisRunner.shutDownDefaultRedisServerInstance(); } } public static class Message implements Serializable { private String name; public Message() { } public Message(String name) { this.name = name; } public String getName() { return name; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Message other = (Message) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } } @Test public void testPing() throws InterruptedException { Config config = BaseTest.createConfig(); config.useSingleServer() .setPingConnectionInterval(50) .setConnectTimeout(20_000) .setTimeout(25_000_000) .setRetryInterval(750) .setConnectionMinimumIdleSize(4) .setConnectionPoolSize(16); RedissonClient redisson = Redisson.create(config); int count = 6000; CountDownLatch latch = new CountDownLatch(count); RTopic eventsTopic = redisson.getTopic("eventsTopic"); eventsTopic.addListener(String.class, (channel, msg) -> { latch.countDown(); }); for(int i = 0; i<count; i++){ final String message = UUID.randomUUID().toString(); eventsTopic.publish(message); Thread.sleep(10); } assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue(); redisson.shutdown(); } @Test public void testConcurrentTopic() throws Exception { RedissonClient redisson = BaseTest.createInstance(); int threads = 30; int loops = 50000; ExecutorService executor = Executors.newFixedThreadPool(threads); List<Future<?>> futures = new ArrayList<>(); for (int i = 0; i < threads; i++) { Runnable worker = new Runnable() { @Override public void run() { for (int j = 0; j < loops; j++) { RTopic t = redisson.getTopic("PUBSUB_" + j); int listenerId = t.addListener(new StatusListener() { @Override public void onUnsubscribe(String channel) { } @Override public void onSubscribe(String channel) { } }); t.publish("message"); t.removeListener(listenerId); } } }; Future<?> s = executor.submit(worker); futures.add(s); } executor.shutdown(); Assert.assertTrue(executor.awaitTermination(threads * loops * 1000, TimeUnit.SECONDS)); for (Future<?> future : futures) { future.get(); } redisson.shutdown(); } @Test public void testCommandsOrdering() throws InterruptedException { RedissonClient redisson1 = BaseTest.createInstance(); RTopic topic1 = redisson1.getTopic("topic", LongCodec.INSTANCE); AtomicBoolean stringMessageReceived = new AtomicBoolean(); topic1.addListener(Long.class, (channel, msg) -> { assertThat(msg).isEqualTo(123); stringMessageReceived.set(true); }); topic1.publish(123L); await().atMost(Duration.ONE_SECOND).untilTrue(stringMessageReceived); redisson1.shutdown(); } @Test public void testTopicState() throws InterruptedException { RedissonClient redisson = BaseTest.createInstance(); RTopic stringTopic = redisson.getTopic("test1", StringCodec.INSTANCE); for (int i = 0; i < 3; i++) { AtomicInteger stringMessageReceived = new AtomicInteger(); int listenerId = stringTopic.addListener(String.class, new MessageListener<String>() { @Override public void onMessage(CharSequence channel, String msg) { assertThat(msg).isEqualTo("testmsg"); stringMessageReceived.incrementAndGet(); } }); RPatternTopic patternTopic = redisson.getPatternTopic("test*", StringCodec.INSTANCE); int patternListenerId = patternTopic.addListener(String.class, new PatternMessageListener<String>() { @Override public void onMessage(CharSequence pattern, CharSequence channel, String msg) { assertThat(msg).isEqualTo("testmsg"); stringMessageReceived.incrementAndGet(); } }); stringTopic.publish("testmsg"); await().atMost(Duration.ONE_SECOND).until(() -> stringMessageReceived.get() == 2); stringTopic.removeListener(listenerId); patternTopic.removeListener(patternListenerId); } redisson.shutdown(); } @Test public void testMultiTypeConnection() throws InterruptedException { RedissonClient redisson = BaseTest.createInstance(); RTopic stringTopic = redisson.getTopic("test1", StringCodec.INSTANCE); AtomicBoolean stringMessageReceived = new AtomicBoolean(); stringTopic.addListener(String.class, new MessageListener<String>() { @Override public void onMessage(CharSequence channel, String msg) { assertThat(msg).isEqualTo("testmsg"); stringMessageReceived.set(true); } }); stringTopic.publish("testmsg"); RTopic longTopic = redisson.getTopic("test2", LongCodec.INSTANCE); AtomicBoolean longMessageReceived = new AtomicBoolean(); longTopic.addListener(Long.class, new MessageListener<Long>() { @Override public void onMessage(CharSequence channel, Long msg) { assertThat(msg).isEqualTo(1L); longMessageReceived.set(true); } }); longTopic.publish(1L); await().atMost(Duration.ONE_SECOND).untilTrue(stringMessageReceived); await().atMost(Duration.ONE_SECOND).untilTrue(longMessageReceived); } @Test public void testSyncCommands() throws InterruptedException { RedissonClient redisson = BaseTest.createInstance(); RTopic topic = redisson.getTopic("system_bus"); RSet<String> redissonSet = redisson.getSet("set1"); CountDownLatch latch = new CountDownLatch(1); topic.addListener(String.class, (channel, msg) -> { for (int j = 0; j < 1000; j++) { System.out.println("start: " + j); redissonSet.contains("" + j); System.out.println("end: " + j); } latch.countDown(); }); topic.publish("sometext"); latch.await(); redisson.shutdown(); } @Test public void testInnerPublish() throws InterruptedException { RedissonClient redisson1 = BaseTest.createInstance(); final RTopic topic1 = redisson1.getTopic("topic1"); final CountDownLatch messageRecieved = new CountDownLatch(3); int listenerId = topic1.addListener(Message.class, (channel, msg) -> { Assert.assertEquals(msg, new Message("test")); messageRecieved.countDown(); }); RedissonClient redisson2 = BaseTest.createInstance(); final RTopic topic2 = redisson2.getTopic("topic2"); topic2.addListener(Message.class, (channel, msg) -> { messageRecieved.countDown(); Message m = new Message("test"); if (!msg.equals(m)) { topic1.publish(m); topic2.publish(m); } }); topic2.publish(new Message("123")); Assert.assertTrue(messageRecieved.await(5, TimeUnit.SECONDS)); redisson1.shutdown(); redisson2.shutdown(); } @Test public void testStatus() throws InterruptedException { RedissonClient redisson = BaseTest.createInstance(); final RTopic topic1 = redisson.getTopic("topic1"); final CountDownLatch l = new CountDownLatch(1); int listenerId = topic1.addListener(new BaseStatusListener() { @Override public void onSubscribe(String channel) { Assert.assertEquals("topic1", channel); l.countDown(); } }); Thread.sleep(500); int listenerId2 = topic1.addListener(new BaseStatusListener() { @Override public void onUnsubscribe(String channel) { Assert.assertEquals("topic1", channel); l.countDown(); } }); topic1.removeListener(listenerId); topic1.removeListener(listenerId2); Assert.assertTrue(l.await(5, TimeUnit.SECONDS)); } @Test public void testUnsubscribe() throws InterruptedException { final CountDownLatch messageRecieved = new CountDownLatch(1); RedissonClient redisson = BaseTest.createInstance(); RTopic topic1 = redisson.getTopic("topic1"); int listenerId = topic1.addListener(Message.class, (channel, msg) -> { Assert.fail(); }); topic1.addListener(Message.class, (channel, msg) -> { Assert.assertEquals("topic1", channel.toString()); Assert.assertEquals(new Message("123"), msg); messageRecieved.countDown(); }); topic1.removeListener(listenerId); topic1 = redisson.getTopic("topic1"); topic1.publish(new Message("123")); Assert.assertTrue(messageRecieved.await(5, TimeUnit.SECONDS)); redisson.shutdown(); } @Test public void testRemoveAllListeners() throws InterruptedException { RedissonClient redisson = BaseTest.createInstance(); RTopic topic1 = redisson.getTopic("topic1"); for (int i = 0; i < 10; i++) { topic1.addListener(Message.class, (channel, msg) -> { Assert.fail(); }); } topic1 = redisson.getTopic("topic1"); topic1.removeAllListeners(); topic1.publish(new Message("123")); redisson.shutdown(); } @Test public void testRemoveByInstance() throws InterruptedException { RedissonClient redisson = BaseTest.createInstance(); RTopic topic1 = redisson.getTopic("topic1"); MessageListener listener = new MessageListener() { @Override public void onMessage(CharSequence channel, Object msg) { Assert.fail(); } }; topic1.addListener(Message.class, listener); topic1 = redisson.getTopic("topic1"); topic1.removeListener(listener); topic1.publish(new Message("123")); redisson.shutdown(); } @Test public void testLazyUnsubscribe() throws InterruptedException { final CountDownLatch messageRecieved = new CountDownLatch(1); RedissonClient redisson1 = BaseTest.createInstance(); RTopic topic1 = redisson1.getTopic("topic"); int listenerId = topic1.addListener(Message.class, (channel, msg) -> { Assert.fail(); }); Thread.sleep(1000); topic1.removeListener(listenerId); Thread.sleep(1000); RedissonClient redisson2 = BaseTest.createInstance(); RTopic topic2 = redisson2.getTopic("topic"); topic2.addListener(Message.class, (channel, msg) -> { Assert.assertEquals(new Message("123"), msg); messageRecieved.countDown(); }); topic2.publish(new Message("123")); Assert.assertTrue(messageRecieved.await(5, TimeUnit.SECONDS)); redisson1.shutdown(); redisson2.shutdown(); } @Test public void test() throws InterruptedException { final CountDownLatch messageRecieved = new CountDownLatch(2); RedissonClient redisson1 = BaseTest.createInstance(); RTopic topic1 = redisson1.getTopic("topic"); topic1.addListener(Message.class, (channel, msg) -> { Assert.assertEquals(new Message("123"), msg); messageRecieved.countDown(); }); RedissonClient redisson2 = BaseTest.createInstance(); RTopic topic2 = redisson2.getTopic("topic"); topic2.addListener(Message.class, (channel, msg) -> { Assert.assertEquals(new Message("123"), msg); messageRecieved.countDown(); }); topic2.publish(new Message("123")); messageRecieved.await(); redisson1.shutdown(); redisson2.shutdown(); } volatile long counter; @Test public void testHeavyLoad() throws InterruptedException { final CountDownLatch messageRecieved = new CountDownLatch(1000); RedissonClient redisson1 = BaseTest.createInstance(); RTopic topic1 = redisson1.getTopic("topic"); topic1.addListener(Message.class, (channel, msg) -> { Assert.assertEquals(new Message("123"), msg); messageRecieved.countDown(); counter++; }); RedissonClient redisson2 = BaseTest.createInstance(); RTopic topic2 = redisson2.getTopic("topic"); topic2.addListener(Message.class, (channel, msg) -> { Assert.assertEquals(new Message("123"), msg); messageRecieved.countDown(); }); for (int i = 0; i < 5000; i++) { topic2.publish(new Message("123")); } messageRecieved.await(); Thread.sleep(1000); Assert.assertEquals(5000, counter); redisson1.shutdown(); redisson2.shutdown(); } @Test public void testListenerRemove() throws InterruptedException { RedissonClient redisson1 = BaseTest.createInstance(); RTopic topic1 = redisson1.getTopic("topic"); int id = topic1.addListener(Message.class, (channel, msg) -> { Assert.fail(); }); RedissonClient redisson2 = BaseTest.createInstance(); RTopic topic2 = redisson2.getTopic("topic"); topic1.removeListener(id); topic2.publish(new Message("123")); Thread.sleep(1000); redisson1.shutdown(); redisson2.shutdown(); } @Test public void testReattach() throws Exception { RedisProcess runner = new RedisRunner() .nosave() .randomDir() .randomPort() .run(); Config config = new Config(); config.useSingleServer().setAddress(runner.getRedisServerAddressAndPort()); RedissonClient redisson = Redisson.create(config); final AtomicBoolean executed = new AtomicBoolean(); final AtomicInteger subscriptions = new AtomicInteger(); RTopic topic = redisson.getTopic("topic"); topic.addListener(new StatusListener() { @Override public void onUnsubscribe(String channel) { } @Override public void onSubscribe(String channel) { subscriptions.incrementAndGet(); } }); topic.addListener(Integer.class, new MessageListener<Integer>() { @Override public void onMessage(CharSequence channel, Integer msg) { executed.set(true); } }); runner.stop(); runner = new RedisRunner() .port(runner.getRedisServerPort()) .nosave() .randomDir() .run(); Thread.sleep(1000); redisson.getTopic("topic").publish(1); await().atMost(2, TimeUnit.SECONDS).untilTrue(executed); await().atMost(2, TimeUnit.SECONDS).until(() -> subscriptions.get() == 2); redisson.shutdown(); runner.stop(); } // @Test public void testReattachInSentinelLong() throws Exception { for (int i = 0; i < 25; i++) { testReattachInSentinel(); } } // @Test public void testReattachInClusterLong() throws Exception { for (int i = 0; i < 25; i++) { testReattachInCluster(); } } @Test public void testReattachInSentinel() throws Exception { RedisRunner.RedisProcess master = new RedisRunner() .nosave() .randomDir() .run(); RedisRunner.RedisProcess slave1 = new RedisRunner() .port(6380) .nosave() .randomDir() .slaveof("127.0.0.1", 6379) .run(); RedisRunner.RedisProcess slave2 = new RedisRunner() .port(6381) .nosave() .randomDir() .slaveof("127.0.0.1", 6379) .run(); RedisRunner.RedisProcess sentinel1 = new RedisRunner() .nosave() .randomDir() .port(26379) .sentinel() .sentinelMonitor("myMaster", "127.0.0.1", 6379, 2) .run(); RedisRunner.RedisProcess sentinel2 = new RedisRunner() .nosave() .randomDir() .port(26380) .sentinel() .sentinelMonitor("myMaster", "127.0.0.1", 6379, 2) .run(); RedisRunner.RedisProcess sentinel3 = new RedisRunner() .nosave() .randomDir() .port(26381) .sentinel() .sentinelMonitor("myMaster", "127.0.0.1", 6379, 2) .run(); Thread.sleep(5000); Config config = new Config(); config.useSentinelServers() .setLoadBalancer(new RandomLoadBalancer()) .addSentinelAddress(sentinel3.getRedisServerAddressAndPort()).setMasterName("myMaster"); RedissonClient redisson = Redisson.create(config); final AtomicBoolean executed = new AtomicBoolean(); final AtomicInteger subscriptions = new AtomicInteger(); RTopic topic = redisson.getTopic("topic"); topic.addListener(new StatusListener() { @Override public void onUnsubscribe(String channel) { } @Override public void onSubscribe(String channel) { subscriptions.incrementAndGet(); } }); topic.addListener(Integer.class, new MessageListener<Integer>() { @Override public void onMessage(CharSequence channel, Integer msg) { executed.set(true); } }); sendCommands(redisson); sentinel1.stop(); sentinel2.stop(); sentinel3.stop(); master.stop(); slave1.stop(); slave2.stop(); Thread.sleep(TimeUnit.SECONDS.toMillis(20)); master = new RedisRunner() .port(6390) .nosave() .randomDir() .run(); slave1 = new RedisRunner() .port(6391) .nosave() .randomDir() .slaveof("127.0.0.1", 6390) .run(); slave2 = new RedisRunner() .port(6392) .nosave() .randomDir() .slaveof("127.0.0.1", 6390) .run(); sentinel1 = new RedisRunner() .nosave() .randomDir() .port(26379) .sentinel() .sentinelMonitor("myMaster", "127.0.0.1", 6390, 2) .run(); sentinel2 = new RedisRunner() .nosave() .randomDir() .port(26380) .sentinel() .sentinelMonitor("myMaster", "127.0.0.1", 6390, 2) .run(); sentinel3 = new RedisRunner() .nosave() .randomDir() .port(26381) .sentinel() .sentinelMonitor("myMaster", "127.0.0.1", 6390, 2) .run(); redisson.getTopic("topic").publish(1); await().atMost(20, TimeUnit.SECONDS).until(() -> subscriptions.get() == 2); Assert.assertTrue(executed.get()); redisson.shutdown(); sentinel1.stop(); sentinel2.stop(); sentinel3.stop(); master.stop(); slave1.stop(); slave2.stop(); } protected void sendCommands(RedissonClient redisson) { Thread t = new Thread() { public void run() { List<RFuture<?>> futures = new ArrayList<RFuture<?>>(); for (int i = 0; i < 100; i++) { RFuture<?> f1 = redisson.getBucket("i" + i).getAsync(); RFuture<?> f2 = redisson.getBucket("i" + i).setAsync(""); RFuture<?> f3 = redisson.getTopic("topic").publishAsync(1); futures.add(f1); futures.add(f2); futures.add(f3); } for (RFuture<?> rFuture : futures) { rFuture.awaitUninterruptibly(); } }; }; t.start(); } @Test public void testReattachInCluster() throws Exception { RedisRunner master1 = new RedisRunner().randomPort().randomDir().nosave(); RedisRunner master2 = new RedisRunner().randomPort().randomDir().nosave(); RedisRunner master3 = new RedisRunner().randomPort().randomDir().nosave(); RedisRunner slave1 = new RedisRunner().randomPort().randomDir().nosave(); RedisRunner slave2 = new RedisRunner().randomPort().randomDir().nosave(); RedisRunner slave3 = new RedisRunner().randomPort().randomDir().nosave(); ClusterRunner clusterRunner = new ClusterRunner() .addNode(master1, slave1) .addNode(master2, slave2) .addNode(master3, slave3); ClusterProcesses process = clusterRunner.run(); Config config = new Config(); config.useClusterServers() .setSubscriptionMode(SubscriptionMode.SLAVE) .setLoadBalancer(new RandomLoadBalancer()) .addNodeAddress(process.getNodes().stream().findAny().get().getRedisServerAddressAndPort()); RedissonClient redisson = Redisson.create(config); final AtomicBoolean executed = new AtomicBoolean(); final AtomicInteger subscriptions = new AtomicInteger(); RTopic topic = redisson.getTopic("topic"); topic.addListener(new StatusListener() { @Override public void onUnsubscribe(String channel) { } @Override public void onSubscribe(String channel) { subscriptions.incrementAndGet(); } }); topic.addListener(Integer.class, new MessageListener<Integer>() { @Override public void onMessage(CharSequence channel, Integer msg) { executed.set(true); } }); sendCommands(redisson); process.getNodes().stream().filter(x -> Arrays.asList(slave1.getPort(), slave2.getPort(), slave3.getPort()).contains(x.getRedisServerPort())) .forEach(x -> { try { x.stop(); Thread.sleep(18000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); Thread.sleep(15000); redisson.getTopic("topic").publish(1); await().atMost(75, TimeUnit.SECONDS).until(() -> subscriptions.get() == 2); Assert.assertTrue(executed.get()); redisson.shutdown(); process.shutdown(); } }
package com.sandwell.JavaSimulation; import java.util.ArrayList; import javax.swing.JFrame; import com.jaamsim.events.EventManager; import com.jaamsim.events.ProcessTarget; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.Keyword; import com.jaamsim.input.KeywordIndex; import com.jaamsim.input.Output; import com.jaamsim.input.ValueInput; import com.jaamsim.ui.EditBox; import com.jaamsim.ui.EntityPallet; import com.jaamsim.ui.ExceptionBox; import com.jaamsim.ui.FrameBox; import com.jaamsim.ui.LogBox; import com.jaamsim.ui.ObjectSelector; import com.jaamsim.ui.OutputBox; import com.jaamsim.ui.PropertyBox; import com.jaamsim.units.TimeUnit; import com.sandwell.JavaSimulation3D.Clock; import com.sandwell.JavaSimulation3D.GUIFrame; /** * Class Simulation - Sandwell Discrete Event Simulation * <p> * Class structure defining essential simulation objects. Eventmanager is * instantiated to manage events generated in the simulation. Function prototypes * are defined which any simulation must define in order to run. */ public class Simulation extends Entity { @Keyword(description = "The initialization period for the simulation run. The model will " + "run for the initialization period and then clear the statistics " + "and execute for the specified run duration. The total length of the " + "simulation run will be the sum of Initialization and Duration.", example = "Simulation Initialization { 720 h }") private static final ValueInput initializationTime; @Keyword(description = "Date at which the simulation run is started (yyyy-mm-dd). This " + "input has no effect on the simulation results unless the seasonality " + "factors vary from month to month.", example = "Simulation StartDate { 2011-01-01 }") private static final StringInput startDate; @Keyword(description = "Time at which the simulation run is started (hh:mm).", example = "Simulation StartTime { 2160 h }") private static final ValueInput startTimeInput; @Keyword(description = "The duration of the simulation run in which all statistics will be recorded.", example = "Simulation Duration { 8760 h }") private static final ValueInput runDuration; @Keyword(description = "The number of discrete time units in one hour.", example = "Simulation SimulationTimeScale { 4500 }") private static final DoubleInput simTimeScaleInput; @Keyword(description = "If the value is TRUE, then the input report file will be printed after loading the " + "configuration file. The input report can always be generated when needed by selecting " + "\"Print Input Report\" under the File menu.", example = "Simulation PrintInputReport { TRUE }") private static final BooleanInput printInputReport; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private static final BooleanInput traceEventsInput; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private static final BooleanInput verifyEventsInput; @Keyword(description = "The real time speed up factor", example = "RunControl RealTimeFactor { 1200 }") private static final IntegerInput realTimeFactor; public static final int DEFAULT_REAL_TIME_FACTOR = 10000; public static final int MIN_REAL_TIME_FACTOR = 1; public static final int MAX_REAL_TIME_FACTOR= 1000000; @Keyword(description = "A Boolean to turn on or off real time in the simulation run", example = "RunControl RealTime { TRUE }") private static final BooleanInput realTime; @Keyword(description = "This is placeholder description text", example = "This is placeholder example text") private static final BooleanInput exitAtStop; @Keyword(description = "Indicates whether the Model Builder tool should be shown on startup.", example = "Simulation ShowModelBuilder { TRUE }") private static final BooleanInput showModelBuilder; @Keyword(description = "Indicates whether the Object Selector tool should be shown on startup.", example = "Simulation ShowObjectSelector { TRUE }") private static final BooleanInput showObjectSelector; @Keyword(description = "Indicates whether the Input Editor tool should be shown on startup.", example = "Simulation ShowInputEditor { TRUE }") private static final BooleanInput showInputEditor; @Keyword(description = "Indicates whether the Output Viewer tool should be shown on startup.", example = "Simulation ShowOutputViewer { TRUE }") private static final BooleanInput showOutputViewer; @Keyword(description = "Indicates whether the Output Viewer tool should be shown on startup.", example = "Simulation ShowPropertyViewer { TRUE }") private static final BooleanInput showPropertyViewer; @Keyword(description = "Indicates whether the Log Viewer tool should be shown on startup.", example = "Simulation ShowLogViewer { TRUE }") private static final BooleanInput showLogViewer; private static double timeScale; // the scale from discrete to continuous time private static double startTime; private static double endTime; private static Simulation myInstance; private static String modelName = "JaamSim"; static { initializationTime = new ValueInput("InitializationDuration", "Key Inputs", 0.0); initializationTime.setUnitType(TimeUnit.class); initializationTime.setValidRange(0.0d, Double.POSITIVE_INFINITY); runDuration = new ValueInput("RunDuration", "Key Inputs", 31536000.0d); runDuration.setUnitType(TimeUnit.class); runDuration.setValidRange(1e-15d, Double.POSITIVE_INFINITY); startDate = new StringInput("StartDate", "Key Inputs", null); startTimeInput = new ValueInput("StartTime", "Key Inputs", 0.0d); startTimeInput.setUnitType(TimeUnit.class); startTimeInput.setValidRange(0.0d, Double.POSITIVE_INFINITY); simTimeScaleInput = new DoubleInput("SimulationTimeScale", "Key Inputs", 4000.0d); simTimeScaleInput.setValidRange(1e-15d, Double.POSITIVE_INFINITY); traceEventsInput = new BooleanInput("TraceEvents", "Key Inputs", false); verifyEventsInput = new BooleanInput("VerifyEvents", "Key Inputs", false); printInputReport = new BooleanInput("PrintInputReport", "Key Inputs", false); realTimeFactor = new IntegerInput("RealTimeFactor", "Key Inputs", DEFAULT_REAL_TIME_FACTOR); realTimeFactor.setValidRange(MIN_REAL_TIME_FACTOR, MAX_REAL_TIME_FACTOR); realTime = new BooleanInput("RealTime", "Key Inputs", false); exitAtStop = new BooleanInput("ExitAtStop", "Key Inputs", false); showModelBuilder = new BooleanInput("ShowModelBuilder", "Key Inputs", false); showObjectSelector = new BooleanInput("ShowObjectSelector", "Key Inputs", false); showInputEditor = new BooleanInput("ShowInputEditor", "Key Inputs", false); showOutputViewer = new BooleanInput("ShowOutputViewer", "Key Inputs", false); showPropertyViewer = new BooleanInput("ShowPropertyViewer", "Key Inputs", false); showLogViewer = new BooleanInput("ShowLogViewer", "Key Inputs", false); // Create clock Clock.setStartDate(2000, 1, 1); // Initialize basic model information startTime = 0.0; endTime = 8760.0; } { this.addInput(runDuration); this.addInput(initializationTime); this.addInput(startDate); this.addInput(startTimeInput); this.addInput(simTimeScaleInput); this.addInput(traceEventsInput); this.addInput(verifyEventsInput); this.addInput(printInputReport); this.addInput(realTimeFactor); this.addInput(realTime); this.addInput(exitAtStop); this.addInput(showModelBuilder); this.addInput(showObjectSelector); this.addInput(showInputEditor); this.addInput(showOutputViewer); this.addInput(showPropertyViewer); this.addInput(showLogViewer); } public Simulation() {} public static Simulation getInstance() { if (myInstance == null) { for (Entity ent : Entity.getAll()) { if (ent instanceof Simulation ) { myInstance = (Simulation) ent; break; } } } return myInstance; } private static EventManager root; public static synchronized final EventManager initEVT() { if (root != null) return root; root = EventManager.initEventManager("DefaultEventManager"); return root; } @Override public void validate() { super.validate(); if( startDate.getValue() != null && !Tester.isDate( startDate.getValue() ) ) { throw new InputErrorException("The value for Start Date must be a valid date."); } } @Override public void updateForInput( Input<?> in ) { super.updateForInput( in ); if(in == realTimeFactor || in == realTime) { updateRealTime(); return; } if (in == showModelBuilder) { setWindowVisible(EntityPallet.getInstance(), showModelBuilder.getValue()); return; } if (in == showObjectSelector) { setWindowVisible(ObjectSelector.getInstance(), showObjectSelector.getValue()); return; } if (in == showInputEditor) { setWindowVisible(EditBox.getInstance(), showInputEditor.getValue()); FrameBox.setSelectedEntity(ObjectSelector.currentEntity); return; } if (in == showOutputViewer) { setWindowVisible(OutputBox.getInstance(), showOutputViewer.getValue()); FrameBox.setSelectedEntity(ObjectSelector.currentEntity); return; } if (in == showPropertyViewer) { setWindowVisible(PropertyBox.getInstance(), showPropertyViewer.getValue()); FrameBox.setSelectedEntity(ObjectSelector.currentEntity); return; } if (in == showLogViewer) { setWindowVisible(LogBox.getInstance(), showLogViewer.getValue()); FrameBox.setSelectedEntity(ObjectSelector.currentEntity); return; } } public static void clear() { EventTracer.init(); initializationTime.reset(); runDuration.reset(); simTimeScaleInput.reset(); traceEventsInput.reset(); verifyEventsInput.reset(); printInputReport.reset(); realTimeFactor.reset(); realTime.reset(); updateRealTime(); exitAtStop.reset(); startDate.reset(); startTimeInput.reset(); showModelBuilder.reset(); showObjectSelector.reset(); showInputEditor.reset(); showOutputViewer.reset(); showPropertyViewer.reset(); showLogViewer.reset(); // Create clock Clock.setStartDate(2000, 1, 1); // Initialize basic model information startTime = 0.0; endTime = 8760.0; // close warning/error trace file InputAgent.closeLogFile(); // Kill all entities except simulation while(Entity.getAll().size() > 0) { Entity ent = Entity.getAll().get(Entity.getAll().size()-1); ent.kill(); } } /** * Initializes and starts the model * 1) Initializes EventManager to accept events. * 2) calls startModel() to allow the model to add its starting events to EventManager * 3) start EventManager processing events */ public static void start() { // Validate each entity based on inputs only for (int i = 0; i < Entity.getAll().size(); i++) { try { Entity.getAll().get(i).validate(); } catch (Throwable e) { InputAgent.doError(e); ExceptionBox.instance().setInputError(Entity.getAll().get(i), e); return; } } InputAgent.prepareReportDirectory(); EventTracer.init(); root.clear(); root.setTraceListener(null); if( traceEventsInput.getValue() ) { EventTracer.traceAllEvents(root, traceEventsInput.getValue()); } else if( verifyEventsInput.getValue() ) { EventTracer.verifyAllEvents(root, verifyEventsInput.getValue()); } root.setSimTimeScale(simTimeScaleInput.getValue()); setSimTimeScale(simTimeScaleInput.getValue()); FrameBox.setSecondsPerTick(3600.0d / simTimeScaleInput.getValue()); if( startDate.getValue() != null ) { Clock.getStartingDateFromString( startDate.getValue() ); } double startTimeHours = startTimeInput.getValue() / 3600.0d; startTime = Clock.calcTimeForYear_Month_Day_Hour(1, Clock.getStartingMonth(), Clock.getStartingDay(), startTimeHours); endTime = startTime + Simulation.getInitializationHours() + Simulation.getRunDurationHours(); root.scheduleProcess(0, Entity.PRIO_DEFAULT, false, new InitModelTarget()); } static void setSimTimeScale(double scale) { timeScale = scale; } public static double getSimTimeFactor() { return timeScale; } public static double getEventTolerance() { return (1.0d / getSimTimeFactor()); } private static class StartUpTarget extends ProcessTarget { final Entity ent; StartUpTarget(Entity ent) { this.ent = ent; } @Override public String getDescription() { return ent.getInputName() + ".startUp"; } @Override public void process() { ent.startUp(); } } private static class InitModelTarget extends ProcessTarget { InitModelTarget() {} @Override public String getDescription() { return "SimulationInit"; } @Override public void process() { for (int i = 0; i < Entity.getAll().size(); i++) { Entity.getAll().get(i).earlyInit(); } EventManager cur = EventManager.current(); long startTick = calculateDelayLength(Simulation.getStartHours()); for (int i = Entity.getAll().size() - 1; i >= 0; i cur.scheduleProcess(startTick, 0, false, new StartUpTarget(Entity.getAll().get(i))); } long endTick = calculateDelayLength(Simulation.getEndHours()); cur.scheduleProcess(endTick, Entity.PRIO_DEFAULT, false, new EndModelTarget()); } } private static class EndModelTarget extends ProcessTarget { EndModelTarget() {} @Override public String getDescription() { return "SimulationEnd"; } @Override public void process() { EventManager.current().pause(); for (int i = 0; i < Entity.getAll().size(); i++) { Entity.getAll().get(i).doEnd(); } System.out.println( "Made it to do end at" ); // close warning/error trace file InputAgent.closeLogFile(); if (Simulation.getExitAtStop() || InputAgent.getBatch()) GUIFrame.shutdown(0); EventManager.current().pause(); } } /** * Returns the end time of the run. * @return double - the time the current run will stop */ public static double getEndHours() { return endTime; } /** * Return the run duration for the run (not including intialization) */ public static double getRunDurationHours() { return runDuration.getValue() / 3600.0d; } /** * Returns the start time of the run. */ public static double getStartHours() { return startTime; } /** * Return the initialization duration in hours */ public static double getInitializationHours() { return initializationTime.getValue() / 3600.0d; } static void updateRealTime() { root.setExecuteRealTime(realTime.getValue(), realTimeFactor.getValue()); GUIFrame.instance().updateForRealTime(realTime.getValue(), realTimeFactor.getValue()); } public static void setRealTime(boolean rt) { ArrayList<String> toks = new ArrayList<String>(5); toks.add(realTime.getKeyword()); toks.add("{"); if (rt) toks.add("TRUE"); else toks.add("FALSE"); toks.add("}"); KeywordIndex kw = new KeywordIndex(toks, 0, toks.size() - 1, null); realTime.parse(kw); updateRealTime(); } public static void setRealTimeFactor(String fac) { StringVector t = new StringVector(1); t.add(fac); realTimeFactor.parse(t); updateRealTime(); } public static void setModelName(String newModelName) { modelName = newModelName; } public static String getModelName() { return modelName; } public static boolean getExitAtStop() { return exitAtStop.getValue(); } public static boolean getPrintInputReport() { return printInputReport.getValue(); } private static void setWindowVisible(JFrame f, boolean visible) { f.setVisible(visible); if (visible) f.toFront(); } /** * Re-open any Tools windows that have been closed temporarily. */ public static void showActiveTools() { setWindowVisible(EntityPallet.getInstance(), showModelBuilder.getValue()); setWindowVisible(ObjectSelector.getInstance(), showObjectSelector.getValue()); setWindowVisible(EditBox.getInstance(), showInputEditor.getValue()); setWindowVisible(OutputBox.getInstance(), showOutputViewer.getValue()); setWindowVisible(PropertyBox.getInstance(), showPropertyViewer.getValue()); setWindowVisible(LogBox.getInstance(), showLogViewer.getValue()); } @Output(name = "Configuration File", description = "The present configuration file.") public String getConfigFileName(double simTime) { return InputAgent.getConfigFile().getPath(); } }
package com.dferens.rocketgame; import com.badlogic.gdx.maps.MapLayer; import com.badlogic.gdx.maps.MapLayers; import com.badlogic.gdx.maps.MapObject; import com.badlogic.gdx.maps.objects.RectangleMapObject; import com.badlogic.gdx.maps.tiled.TiledMapTileLayer; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.math.Vector2; import com.dferens.core.EntityManager; import com.dferens.core.levels.LevelParseException; import com.dferens.core.levels.TmxLevel; public class RocketGameLevel extends TmxLevel { private static String LAYER_COLLISION = "BLOCKS"; private static String LAYER_CONTROLS = "CONTROLS"; private static String POINT_SPAWN = "POINT_SPAWN"; private static String POINT_FINISH = "POINT_FINISH"; private final MapLayers backgroundLayers; private final MapLayers foregroundLayers; private TiledMapTileLayer collisionLayer; private MapLayer controlLayer; private Vector2 spawnPoint; private Vector2 finishPoint; public Vector2 getSpawnPoint() { return spawnPoint; } public Vector2 getFinishPoint() { return finishPoint; } public MapLayers getBackgroundLayers() { return backgroundLayers; } public MapLayers getForegroundLayers() { return foregroundLayers; } public RocketGameLevel(String levelFilePath) throws LevelParseException { super(levelFilePath); this.backgroundLayers = new MapLayers(); this.foregroundLayers = new MapLayers(); this.spawnPoint = new Vector2(); this.finishPoint = new Vector2(); this.parse(); } @Override public TiledMapTileLayer getMainLayer() { return this.getCollisionLayer(); } private MapLayer getControlsLayer() { return this.getMapLayer(LAYER_CONTROLS); } private TiledMapTileLayer getCollisionLayer() { return this.getMapLayer(LAYER_COLLISION, TiledMapTileLayer.class); } @Override public void parse() throws LevelParseException { this.collisionLayer = this.getCollisionLayer(); this.controlLayer = this.getControlsLayer(); if (collisionLayer == null) { throw new LevelParseException("No collision layer found"); } else if (controlLayer == null) { throw new LevelParseException("No control layer found"); } else if (collisionLayer.getHeight() <= 1 || collisionLayer.getWidth() <= 1) { throw new LevelParseException("Map is too small"); } MapObject spawnPointObject = controlLayer.getObjects().get(POINT_SPAWN); MapObject finishPointObject = controlLayer.getObjects().get(POINT_FINISH); if (spawnPointObject == null) { throw new LevelParseException("No spawn point specified"); } else if (!(spawnPointObject instanceof RectangleMapObject)) { throw new LevelParseException("Spawn point should be specified with rectangle object"); } else if (finishPointObject == null) { throw new LevelParseException("No finish point specified"); } else if (!(finishPointObject instanceof RectangleMapObject)) { throw new LevelParseException("Finish point should be specified with rectangle object"); } // Spawn & finish points Rectangle spawnBounds = ((RectangleMapObject) spawnPointObject).getRectangle(); Rectangle finishBounds = ((RectangleMapObject) finishPointObject).getRectangle(); Vector2 positionPixels = new Vector2(); spawnBounds.getCenter(positionPixels); this.spawnPoint.set(positionPixels.x / this.getTileSizePixels(), positionPixels.y / this.getTileSizePixels()); finishBounds.getCenter(positionPixels); this.finishPoint.set(positionPixels.x / this.getTileSizePixels(), positionPixels.y / this.getTileSizePixels()); // Load background & foreground layers MapLayers targetMapList = this.backgroundLayers; for (MapLayer layer : this.tiledMap.getLayers()) { if (layer == collisionLayer) { targetMapList = this.foregroundLayers; continue; } if (layer instanceof TiledMapTileLayer) targetMapList.add(layer); } } @Override public void loadEntities(EntityManager entityManager) { int layerHeight = collisionLayer.getHeight(); for (int mapY = 0; mapY < layerHeight; mapY++) { for (int mapX = 0; mapX < collisionLayer.getWidth(); mapX++) { if (collisionLayer.getCell(mapX, mapY) != null) entityManager.createEntity(new BlockEntity(mapX, mapY)); } } } }
package com.vmichalak.protocol.ssdp; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Client for discovering UPNP devices with SSDP (Simple Service Discovery Protocol). */ public class SSDPClient { public static List<Device> discover(int timeout, String serviceType) throws IOException { ArrayList<Device> devices = new ArrayList<Device>(); byte[] sendData; byte[] receiveData = new byte[1024]; /* Create the search request */ StringBuilder msearch = new StringBuilder( "M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\n"); if (serviceType == null) { msearch.append("ST: ssdp:all\n"); } else { msearch.append("ST: ").append(serviceType).append("\n"); } /* Send the request */ sendData = msearch.toString().getBytes(); DatagramPacket sendPacket = new DatagramPacket( sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900); DatagramSocket clientSocket = new DatagramSocket(); clientSocket.setSoTimeout(timeout); clientSocket.send(sendPacket); /* Receive all responses */ while (true) { try { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); devices.add(Device.parse(receivePacket)); } catch (SocketTimeoutException e) { break; } } clientSocket.close(); return Collections.unmodifiableList(devices); } public static Device discoverOne(int timeout, String serviceType) throws IOException { Device device; byte[] sendData; byte[] receiveData = new byte[1024]; /* Create the search request */ StringBuilder msearch = new StringBuilder( "M-SEARCH * HTTP/1.1\nHost: 239.255.255.250:1900\nMan: \"ssdp:discover\"\n"); if (serviceType == null) { msearch.append("ST: ssdp:all\n"); } else { msearch.append("ST: ").append(serviceType).append("\n"); } /* Send the request */ sendData = msearch.toString().getBytes(); DatagramPacket sendPacket = new DatagramPacket( sendData, sendData.length, InetAddress.getByName("239.255.255.250"), 1900); DatagramSocket clientSocket = new DatagramSocket(); clientSocket.setSoTimeout(timeout); clientSocket.send(sendPacket); /* Receive one response */ try { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); device = Device.parse(receivePacket); } catch (SocketTimeoutException e) { } clientSocket.close(); return device; } }
package org.opendaylight.controller.connectionmanager.northbound; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import org.codehaus.enunciate.jaxrs.ResponseCode; import org.codehaus.enunciate.jaxrs.StatusCodes; import org.codehaus.enunciate.jaxrs.TypeHint; import org.opendaylight.controller.connectionmanager.IConnectionManager; import org.opendaylight.controller.northbound.commons.exception.NotAcceptableException; import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException; import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException; import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException; import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils; import org.opendaylight.controller.sal.authorization.Privilege; import org.opendaylight.controller.sal.connection.ConnectionConstants; import org.opendaylight.controller.sal.core.Node; import org.opendaylight.controller.sal.utils.NetUtils; import org.opendaylight.controller.sal.utils.ServiceHelper; import org.opendaylight.controller.sal.utils.Status; /** * Connection Manager Northbound APIs */ @Path("/") public class ConnectionManagerNorthbound { private String username; @Context public void setSecurityContext(SecurityContext context) { if (context != null && context.getUserPrincipal() != null) username = context.getUserPrincipal().getName(); } protected String getUserName() { return username; } private IConnectionManager getConnectionManager() { return (IConnectionManager) ServiceHelper .getGlobalInstance(IConnectionManager.class, this); } @Path("/nodes") @GET @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @TypeHint(Nodes.class) @StatusCodes( { @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), @ResponseCode(code = 406, condition = "Invalid Controller IP Address passed."), @ResponseCode(code = 503, condition = "Connection Manager Service not available")}) public Nodes getNodes(@DefaultValue("") @QueryParam("controller") String controllerAddress) { if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) { throw new UnauthorizedException("User is not authorized to perform this operation on container"); } IConnectionManager connectionManager = getConnectionManager(); if (connectionManager == null) { throw new ServiceUnavailableException("IConnectionManager not available."); } if ((controllerAddress != null) && (controllerAddress.trim().length() > 0) && !NetUtils.isIPv4AddressValid(controllerAddress)) { throw new NotAcceptableException("Invalid ip address "+controllerAddress); } Set<Node> nodeSet = null; if (controllerAddress != null) { try { nodeSet = connectionManager.getNodes(InetAddress.getByName(controllerAddress)); } catch (UnknownHostException e) { throw new NotAcceptableException("Invalid ip address "+controllerAddress); } } else { nodeSet = connectionManager.getLocalNodes(); } return new Nodes(nodeSet); } @Path("/node/{nodeId}/address/{ipAddress}/port/{port}/") @PUT @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @TypeHint(Node.class) @StatusCodes( { @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), @ResponseCode(code = 404, condition = "Could not connect to the Node with the specified parameters"), @ResponseCode(code = 406, condition = "Invalid IP Address or Port parameter passed."), @ResponseCode(code = 503, condition = "Connection Manager Service not available")} ) public Node connect( @PathParam(value = "nodeId") String nodeId, @PathParam(value = "ipAddress") String ipAddress, @PathParam(value = "port") String port) { if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.WRITE, this)) { throw new UnauthorizedException("User is not authorized to perform this operation on container"); } IConnectionManager connectionManager = getConnectionManager(); if (connectionManager == null) { throw new ServiceUnavailableException("IConnectionManager not available."); } if (!NetUtils.isIPv4AddressValid(ipAddress)) { throw new NotAcceptableException("Invalid ip address "+ipAddress); } try { Integer.parseInt(port); } catch (Exception e) { throw new NotAcceptableException("Invalid Layer4 Port "+port); } Map<ConnectionConstants, String> params = new HashMap<ConnectionConstants, String>(); params.put(ConnectionConstants.ADDRESS, ipAddress); params.put(ConnectionConstants.PORT, port); Node node = null; try { node = connectionManager.connect(nodeId, params); if (node == null) { throw new ResourceNotFoundException("Failed to connect to Node at "+ipAddress+":"+port); } return node; } catch (Exception e) { throw new ResourceNotFoundException("Failed to connect to Node with Exception "+e.getMessage()); } } @Path("/node/{nodeType}/{nodeId}/address/{ipAddress}/port/{port}/") @PUT @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @TypeHint(Node.class) @StatusCodes( { @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), @ResponseCode(code = 404, condition = "Could not connect to the Node with the specified parameters"), @ResponseCode(code = 406, condition = "Invalid IP Address or Port parameter passed."), @ResponseCode(code = 503, condition = "Connection Manager Service not available")} ) public Node connect( @PathParam(value = "nodeType") String nodeType, @PathParam(value = "nodeId") String nodeId, @PathParam(value = "ipAddress") String ipAddress, @PathParam(value = "port") String port) { if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.WRITE, this)) { throw new UnauthorizedException("User is not authorized to perform this operation on container"); } IConnectionManager connectionManager = getConnectionManager(); if (connectionManager == null) { throw new ServiceUnavailableException("IConnectionManager not available."); } if (!NetUtils.isIPv4AddressValid(ipAddress)) { throw new NotAcceptableException("Invalid ip address "+ipAddress); } try { Integer.parseInt(port); } catch (Exception e) { throw new NotAcceptableException("Invalid Layer4 Port "+port); } Map<ConnectionConstants, String> params = new HashMap<ConnectionConstants, String>(); params.put(ConnectionConstants.ADDRESS, ipAddress); params.put(ConnectionConstants.PORT, port); Node node = null; try { node = connectionManager.connect(nodeType, nodeId, params); if (node == null) { throw new ResourceNotFoundException("Failed to connect to Node at "+ipAddress+":"+port); } return node; } catch (Exception e) { throw new ResourceNotFoundException(e.getMessage()); } } @Path("/node/{nodeType}/{nodeId}/") @DELETE @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @TypeHint(Response.class) @StatusCodes( { @ResponseCode(code = 401, condition = "User not authorized to perform this operation"), @ResponseCode(code = 200, condition = "Node disconnected successfully"), @ResponseCode(code = 404, condition = "Could not find a connection with the specified Node identifier"), @ResponseCode(code = 503, condition = "Connection Manager Service not available")} ) public Response disconnect( @PathParam(value = "nodeType") String nodeType, @PathParam(value = "nodeId") String nodeId) { if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.WRITE, this)) { throw new UnauthorizedException("User is not authorized to perform this operation on container"); } IConnectionManager connectionManager = getConnectionManager(); if (connectionManager == null) { throw new ServiceUnavailableException("IConnectionManager not available."); } try { Node node = Node.fromString(nodeType, nodeId); Status status = connectionManager.disconnect(node); if (status.isSuccess()) { return Response.ok().build(); } return NorthboundUtils.getResponse(status); } catch (Exception e) { throw new ResourceNotFoundException(e.getMessage()); } } }
package cubicchunks.asm; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Set; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.spongepowered.asm.lib.tree.ClassNode; import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import cubicchunks.CubicChunks; import it.unimi.dsi.fastutil.objects.Object2BooleanLinkedOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2BooleanMap; /** * This Mixin configuration plugin class launched from cubicchunks.mixin.selectable.json. * Note, that this plugin is not working in JUnit tests due to missing field of * FMLInjectionData required for MinecraftForge configuration used here. * Therefore two Mixin classes with an injection in a same method and with a same priority will cause Mixin to fail. */ public class CubicChunksMixinConfig implements IMixinConfigPlugin { @Nonnull public static Logger LOGGER = LogManager.getLogger("CubicChunksMixinConfig"); private final Object2BooleanMap<String> modDependencyConditions = new Object2BooleanLinkedOpenHashMap<String>(); @SuppressWarnings({"unchecked", "rawtypes"}) @Override public void onLoad(String mixinPackage) { OptifineState optifineState = OptifineState.NOT_LOADED; String optifineVersion = System.getProperty("cubicchunks.optifineVersion", "empty"); if (optifineVersion.equals("empty")) { try { Class optifineInstallerClass = Class.forName("optifine.Installer"); Method getVersionHandler = optifineInstallerClass.getMethod("getOptiFineVersion", new Class[0]); optifineVersion = (String) getVersionHandler.invoke(null, new Object[0]); optifineVersion = optifineVersion.replace("_pre", ""); optifineVersion = optifineVersion.substring(optifineVersion.length() - 2, optifineVersion.length()); CubicChunks.LOGGER.info("Detected Optifine version: " + optifineVersion); } catch (ClassNotFoundException e) { optifineVersion = "ignore"; CubicChunks.LOGGER.info("No Optifine detected"); } catch (Exception e) { CubicChunks.LOGGER.info("Optifine detected, but have incompatible build. Optifine D1 specific mixins will be loaded."); optifineVersion = "D1"; } } if(optifineVersion.equalsIgnoreCase("ignore")) optifineState = OptifineState.NOT_LOADED; else if (optifineVersion.compareTo("D1") >= 0) optifineState = OptifineState.LOADED_D1; else optifineState = OptifineState.LOADED_C7; modDependencyConditions.defaultReturnValue(true); modDependencyConditions.put( "cubicchunks.asm.mixin.selectable.client.MixinRenderGlobalNoOptifine", optifineState == OptifineState.NOT_LOADED); modDependencyConditions.put( "cubicchunks.asm.mixin.selectable.client.MixinRenderGlobalOptifineSpecific", optifineState != OptifineState.NOT_LOADED); modDependencyConditions.put( "cubicchunks.asm.mixin.selectable.client.MixinRenderGlobalOptifineSpecificC7", optifineState == OptifineState.LOADED_C7); modDependencyConditions.put( "cubicchunks.asm.mixin.selectable.client.MixinRenderGlobalOptifineSpecificD1", optifineState == OptifineState.LOADED_D1); File folder = new File(".", "config"); folder.mkdirs(); File configFile = new File(folder, "cubicchunks_mixin_config.json"); LOGGER.info("Loading configuration file " + configFile.getAbsolutePath()); try { if (!configFile.exists()) this.writeConfigToJson(configFile); this.readConfigFromJson(configFile); } catch (IOException e) { e.printStackTrace(); } } @Override public String getRefMapperConfig() { return null; } @Override public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { return this.shouldApplyMixin(mixinClassName); } public boolean shouldApplyMixin(String mixinClassName) { for (BoolOptions configOption : BoolOptions.values()) { for (String mixinClassNameOnTrue : configOption.mixinClassNamesOnTrue) if (mixinClassName.equals(mixinClassNameOnTrue)) return configOption.value && modDependencyConditions.getBoolean(mixinClassName); for (String mixinClassNameOnFalse : configOption.mixinClassNamesOnFalse) if (mixinClassName.equals(mixinClassNameOnFalse)) return !configOption.value && modDependencyConditions.getBoolean(mixinClassName); } return modDependencyConditions.getBoolean(mixinClassName); } @Override public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) { } @Override public List<String> getMixins() { return null; } @Override public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } @Override public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } public static enum BoolOptions { OPTIMIZE_PATH_NAVIGATOR(false, new String[] {}, new String[] {"cubicchunks.asm.mixin.selectable.common.MixinPathNavigate", "cubicchunks.asm.mixin.selectable.common.MixinWalkNodeProcessor"}, "Enabling this option will optimize work of vanilla path navigator." + "Using this option in some cases turn entity AI a little dumber." + " Mob standing in a single axis aligned line with player in a middle of a" + " chunk will not try to seek path to player outside of chunks if direct path is blocked." + " You need to restart Minecraft to apply changes."), USE_CUBE_ARRAYS_INSIDE_CHUNK_CACHE(true, new String[] {}, new String[] {"cubicchunks.asm.mixin.selectable.common.MixinWorld_ChunkCache"}, "Enabling this option will mix cube array into chunk cache" + " for using in entity path navigator." + " Potentially this will slightly reduce server tick time" + " in presence of huge amount of living entities." + " You need to restart Minecraft to apply changes."), USE_FAST_COLLISION_CHECK(false, new String[] {"cubicchunks.asm.mixin.selectable.common.MixinWorld_SlowCollisionCheck"}, new String[] {"cubicchunks.asm.mixin.selectable.common.MixinWorld_CollisionCheck", "cubicchunks.asm.mixin.selectable.common.MixinBlock_FastCollision"}, "Enabling this option allow using fast collision check." + " Fast collision check can reduce server lag." + " You need to restart Minecraft to apply changes. DO NOT USE UNTIL FIXED!"), RANDOM_TICK_IN_CUBE(true, new String[] {}, new String[] {"cubicchunks.asm.mixin.selectable.common.MixinWorldServer_UpdateBlocks"}, "If set to true, random tick wil be launched from cube instance instead of chunk." + " Cube based random tick may slightly reduce server lag." + " You need to restart Minecraft to apply changes."); private final boolean defaultValue; // Load this Mixin class only if option is false. private final String[] mixinClassNamesOnFalse; // Load this Mixin class only if option is true. private final String[] mixinClassNamesOnTrue; private final String description; private boolean value; private BoolOptions(boolean defaultValue1, String[] mixinClassNamesOnFalse1, String[] mixinClassNamesOnTrue1, String description1) { defaultValue = defaultValue1; mixinClassNamesOnFalse = mixinClassNamesOnFalse1; mixinClassNamesOnTrue = mixinClassNamesOnTrue1; description = description1; value = defaultValue; } public boolean getValue() { return value; } } public static String getNicelyFormattedName(String name) { StringBuffer out = new StringBuffer(); char char_ = '_'; char prevchar = 0; for (char c : name.toCharArray()) { if (c != char_ && prevchar != char_) { out.append(String.valueOf(c).toLowerCase()); } else if (c != char_) { out.append(String.valueOf(c)); } prevchar = c; } return out.toString(); } private void writeConfigToJson(File configFile) throws IOException { JsonWriter writer = new JsonWriter(new FileWriter(configFile)); writer.setIndent(" "); writer.beginArray(); for (BoolOptions configOption : BoolOptions.values()) { writer.beginObject(); writer.name(configOption.name()); writer.value(configOption.value); writer.name("description"); writer.value(configOption.description); writer.endObject(); } writer.endArray(); writer.close(); } private void readConfigFromJson(File configFile) throws IOException { int expectingOptionsNumber = BoolOptions.values().length; JsonReader reader = new JsonReader(new FileReader(configFile)); reader.beginArray(); while(reader.hasNext()){ reader.beginObject(); next_object:while(reader.hasNext()){ String name = reader.nextName(); for(BoolOptions option:BoolOptions.values()){ if(option.name().equals(name)){ expectingOptionsNumber option.value = reader.nextBoolean(); continue next_object; } } reader.skipValue(); } reader.endObject(); } reader.endArray(); reader.close(); if (expectingOptionsNumber != 0) this.writeConfigToJson(configFile); } private enum OptifineState { NOT_LOADED, LOADED_C7, LOADED_D1 } }
package net.i2p.router.tunnel; import java.io.IOException; import java.util.HashMap; import java.util.Map; import net.i2p.I2PAppContext; import net.i2p.data.Base64; import net.i2p.data.ByteArray; import net.i2p.data.DataHelper; import net.i2p.data.Hash; import net.i2p.data.TunnelId; import net.i2p.data.i2np.I2NPMessage; import net.i2p.data.i2np.I2NPMessageException; import net.i2p.data.i2np.I2NPMessageHandler; import net.i2p.util.ByteCache; import net.i2p.util.Log; import net.i2p.util.SimpleTimer; /** * Handle fragments at the endpoint of a tunnel, peeling off fully completed * I2NPMessages when they arrive, and dropping fragments if they take too long * to arrive. * */ public class FragmentHandler { private I2PAppContext _context; private Log _log; private final Map _fragmentedMessages; private DefragmentedReceiver _receiver; private int _completed; private int _failed; /** don't wait more than 60s to defragment the partial message */ static long MAX_DEFRAGMENT_TIME = 60*1000; private static final ByteCache _cache = ByteCache.getInstance(512, TrivialPreprocessor.PREPROCESSED_SIZE); public FragmentHandler(I2PAppContext context, DefragmentedReceiver receiver) { _context = context; _log = context.logManager().getLog(FragmentHandler.class); _fragmentedMessages = new HashMap(4); _receiver = receiver; _context.statManager().createRateStat("tunnel.smallFragments", "How many pad bytes are in small fragments?", "Tunnels", new long[] { 10*60*1000l, 60*60*1000l, 3*60*60*1000l, 24*60*60*1000 }); _context.statManager().createRateStat("tunnel.fullFragments", "How many tunnel messages use the full data area?", "Tunnels", new long[] { 10*60*1000l, 60*60*1000l, 3*60*60*1000l, 24*60*60*1000 }); _context.statManager().createRateStat("tunnel.fragmentedComplete", "How many fragments were in a completely received message?", "Tunnels", new long[] { 10*60*1000l, 60*60*1000l, 3*60*60*1000l, 24*60*60*1000 }); _context.statManager().createRateStat("tunnel.fragmentedDropped", "How many fragments were in a partially received yet failed message?", "Tunnels", new long[] { 10*60*1000l, 60*60*1000l, 3*60*60*1000l, 24*60*60*1000 }); _context.statManager().createRateStat("tunnel.corruptMessage", "How many corrupted messages arrived?", "Tunnels", new long[] { 10*60*1000l, 60*60*1000l, 3*60*60*1000l, 24*60*60*1000 }); } /** * Receive the raw preprocessed message at the endpoint, parsing out each * of the fragments, using those to fill various FragmentedMessages, and * sending the resulting I2NPMessages where necessary. The received * fragments are all verified. * */ public void receiveTunnelMessage(byte preprocessed[], int offset, int length) { boolean ok = verifyPreprocessed(preprocessed, offset, length); if (!ok) { if (_log.shouldLog(Log.WARN)) _log.warn("Unable to verify preprocessed data (pre.length=" + preprocessed.length + " off=" +offset + " len=" + length); _cache.release(new ByteArray(preprocessed)); _context.statManager().addRateData("tunnel.corruptMessage", 1, 1); return; } offset += HopProcessor.IV_LENGTH; // skip the IV offset += 4; // skip the hash segment int padding = 0; while (preprocessed[offset] != (byte)0x00) { offset++; // skip the padding if (offset >= TrivialPreprocessor.PREPROCESSED_SIZE) { _cache.release(new ByteArray(preprocessed)); _context.statManager().addRateData("tunnel.corruptMessage", 1, 1); return; } padding++; } offset++; // skip the final 0x00, terminating the padding if (_log.shouldLog(Log.DEBUG)) { _log.debug("Fragments begin at offset=" + offset + " padding=" + padding); //_log.debug("fragments: " + Base64.encode(preprocessed, offset, preprocessed.length-offset)); } try { while (offset < length) { int off = receiveFragment(preprocessed, offset, length); if (off < 0) { _context.statManager().addRateData("tunnel.corruptMessage", 1, 1); return; } offset = off; } } catch (ArrayIndexOutOfBoundsException aioobe) { _context.statManager().addRateData("tunnel.corruptMessage", 1, 1); } catch (NullPointerException npe) { if (_log.shouldLog(Log.ERROR)) _log.error("Corrupt fragment received: offset = " + offset, npe); _context.statManager().addRateData("tunnel.corruptMessage", 1, 1); } catch (RuntimeException e) { if (_log.shouldLog(Log.ERROR)) _log.error("Corrupt fragment received: offset = " + offset, e); _context.statManager().addRateData("tunnel.corruptMessage", 1, 1); // at net.i2p.router.tunnel.FragmentedMessage.getCompleteSize(FragmentedMessage.java:194) // at net.i2p.router.tunnel.FragmentedMessage.toByteArray(FragmentedMessage.java:223) // at net.i2p.router.tunnel.FragmentHandler.receiveComplete(FragmentHandler.java:380) // at net.i2p.router.tunnel.FragmentHandler.receiveSubsequentFragment(FragmentHandler.java:353) // at net.i2p.router.tunnel.FragmentHandler.receiveFragment(FragmentHandler.java:208) // at net.i2p.router.tunnel.FragmentHandler.receiveTunnelMessage(FragmentHandler.java:92) // still trying to find root cause // let's limit the damage here and skip the: // .transport.udp.MessageReceiver: b0rked receiving a message.. wazza huzza hmm? //throw e; } finally { // each of the FragmentedMessages populated make a copy out of the // payload, which they release separately, so we can release // immediately _cache.release(new ByteArray(preprocessed)); } } public int getCompleteCount() { return _completed; } public int getFailedCount() { return _failed; } private static final ByteCache _validateCache = ByteCache.getInstance(512, TrivialPreprocessor.PREPROCESSED_SIZE); private boolean verifyPreprocessed(byte preprocessed[], int offset, int length) { // now we need to verify that the message was received correctly int paddingEnd = HopProcessor.IV_LENGTH + 4; while (preprocessed[offset+paddingEnd] != (byte)0x00) { paddingEnd++; if (offset+paddingEnd >= length) { if (_log.shouldLog(Log.WARN)) _log.warn("cannot verify, going past the end [off=" + offset + " len=" + length + " paddingEnd=" + paddingEnd + " data:\n" + Base64.encode(preprocessed, offset, length)); return false; } } paddingEnd++; // skip the last ByteArray ba = _validateCache.acquire(); // larger than necessary, but always sufficient byte preV[] = ba.getData(); int validLength = length - offset - paddingEnd + HopProcessor.IV_LENGTH; System.arraycopy(preprocessed, offset + paddingEnd, preV, 0, validLength - HopProcessor.IV_LENGTH); System.arraycopy(preprocessed, 0, preV, validLength - HopProcessor.IV_LENGTH, HopProcessor.IV_LENGTH); if (_log.shouldLog(Log.DEBUG)) _log.debug("endpoint IV: " + Base64.encode(preV, validLength - HopProcessor.IV_LENGTH, HopProcessor.IV_LENGTH)); Hash v = _context.sha().calculateHash(preV, 0, validLength); //Hash v = _context.sha().calculateHash(preV, 0, validLength); boolean eq = DataHelper.eq(v.getData(), 0, preprocessed, offset + HopProcessor.IV_LENGTH, 4); if (!eq) { if (_log.shouldLog(Log.WARN)) _log.warn("Corrupt tunnel message - verification fails: \n" + Base64.encode(preprocessed, offset+HopProcessor.IV_LENGTH, 4) + "\n" + Base64.encode(v.getData(), 0, 4)); if (_log.shouldLog(Log.WARN)) _log.warn("nomatching endpoint: # pad bytes: " + (paddingEnd-(HopProcessor.IV_LENGTH+4)-1) + "\n" + " offset=" + offset + " length=" + length + " paddingEnd=" + paddingEnd + Base64.encode(preprocessed, offset, length)); } _validateCache.release(ba); if (eq) { int excessPadding = paddingEnd - (HopProcessor.IV_LENGTH + 4 + 1); if (excessPadding > 0) // suboptimal fragmentation _context.statManager().addRateData("tunnel.smallFragments", excessPadding, 0); else _context.statManager().addRateData("tunnel.fullFragments", 1, 0); } return eq; } /** is this a follw up byte? */ static final byte MASK_IS_SUBSEQUENT = (byte)(1 << 7); /** how should this be delivered. shift this 5 the right and get TYPE_* */ static final byte MASK_TYPE = (byte)(3 << 5); /** is this the first of a fragmented message? */ static final byte MASK_FRAGMENTED = (byte)(1 << 3); /** are there follow up headers? */ static final byte MASK_EXTENDED = (byte)(1 << 2); /** for subsequent fragments, which bits contain the fragment #? */ private static final int MASK_FRAGMENT_NUM = (byte)((1 << 7) - 2); // 0x7E; static final short TYPE_LOCAL = 0; static final short TYPE_TUNNEL = 1; static final short TYPE_ROUTER = 2; /** * @return the offset for the next byte after the received fragment */ private int receiveFragment(byte preprocessed[], int offset, int length) { if (_log.shouldLog(Log.DEBUG)) _log.debug("CONTROL: " + Integer.toHexString(preprocessed[offset]) + " / " + "/" + Base64.encode(preprocessed, offset, 1) + " at offset " + offset); if (0 == (preprocessed[offset] & MASK_IS_SUBSEQUENT)) return receiveInitialFragment(preprocessed, offset, length); else return receiveSubsequentFragment(preprocessed, offset, length); } /** * Handle the initial fragment in a message (or a full message, if it fits) * * @return offset after reading the full fragment */ private int receiveInitialFragment(byte preprocessed[], int offset, int length) { if (_log.shouldLog(Log.DEBUG)) _log.debug("initial begins at " + offset + " for " + length); int type = (preprocessed[offset] & MASK_TYPE) >>> 5; boolean fragmented = (0 != (preprocessed[offset] & MASK_FRAGMENTED)); boolean extended = (0 != (preprocessed[offset] & MASK_EXTENDED)); offset++; TunnelId tunnelId = null; Hash router = null; long messageId = -1; if (type == TYPE_TUNNEL) { if (offset + 4 >= preprocessed.length) return -1; long id = DataHelper.fromLong(preprocessed, offset, 4); tunnelId = new TunnelId(id); offset += 4; } if ( (type == TYPE_ROUTER) || (type == TYPE_TUNNEL) ) { byte h[] = new byte[Hash.HASH_LENGTH]; if (offset + Hash.HASH_LENGTH >= preprocessed.length) return -1; System.arraycopy(preprocessed, offset, h, 0, Hash.HASH_LENGTH); router = new Hash(h); offset += Hash.HASH_LENGTH; } if (fragmented) { if (offset + 4 >= preprocessed.length) return -1; messageId = DataHelper.fromLong(preprocessed, offset, 4); if (_log.shouldLog(Log.DEBUG)) _log.debug("reading messageId " + messageId + " at offset "+ offset + " type = " + type + " router = " + (router != null ? router.toBase64().substring(0,4) : "n/a") + " tunnelId = " + tunnelId); offset += 4; } if (extended) { int extendedSize = (int)DataHelper.fromLong(preprocessed, offset, 1); offset++; offset += extendedSize; // we don't interpret these yet, but skip them for now } if (offset + 2 >= preprocessed.length) return -1; int size = (int)DataHelper.fromLong(preprocessed, offset, 2); offset += 2; boolean isNew = false; FragmentedMessage msg = null; if (fragmented) { synchronized (_fragmentedMessages) { msg = (FragmentedMessage)_fragmentedMessages.get(new Long(messageId)); if (msg == null) { msg = new FragmentedMessage(_context); _fragmentedMessages.put(new Long(messageId), msg); isNew = true; } } } else { msg = new FragmentedMessage(_context); } boolean ok = msg.receive(messageId, preprocessed, offset, size, !fragmented, router, tunnelId); if (!ok) return -1; if (msg.isComplete()) { if (fragmented) { synchronized (_fragmentedMessages) { _fragmentedMessages.remove(new Long(messageId)); } } if (msg.getExpireEvent() != null) SimpleTimer.getInstance().removeEvent(msg.getExpireEvent()); receiveComplete(msg); } else { noteReception(msg.getMessageId(), 0, msg); } if (isNew && fragmented && !msg.isComplete()) { RemoveFailed evt = new RemoveFailed(msg); msg.setExpireEvent(evt); if (_log.shouldLog(Log.DEBUG)) _log.debug("In " + MAX_DEFRAGMENT_TIME + " dropping " + messageId); SimpleTimer.getInstance().addEvent(evt, MAX_DEFRAGMENT_TIME); } offset += size; if (_log.shouldLog(Log.DEBUG)) _log.debug("Handling finished message " + msg.getMessageId() + " at offset " + offset); return offset; } /** * Handle a fragment beyond the initial fragment in a message * * @return offset after reading the full fragment */ private int receiveSubsequentFragment(byte preprocessed[], int offset, int length) { if (_log.shouldLog(Log.DEBUG)) _log.debug("subsequent begins at " + offset + " for " + length); int fragmentNum = ((preprocessed[offset] & MASK_FRAGMENT_NUM) >>> 1); boolean isLast = (0 != (preprocessed[offset] & 1)); offset++; long messageId = DataHelper.fromLong(preprocessed, offset, 4); offset += 4; int size = (int)DataHelper.fromLong(preprocessed, offset, 2); offset += 2; if (messageId < 0) throw new RuntimeException("Preprocessed message was invalid [messageId =" + messageId + " size=" + size + " offset=" + offset + " fragment=" + fragmentNum); boolean isNew = false; FragmentedMessage msg = null; synchronized (_fragmentedMessages) { msg = (FragmentedMessage)_fragmentedMessages.get(new Long(messageId)); if (msg == null) { msg = new FragmentedMessage(_context); _fragmentedMessages.put(new Long(messageId), msg); isNew = true; } } boolean ok = msg.receive(messageId, fragmentNum, preprocessed, offset, size, isLast); if (!ok) return -1; if (msg.isComplete()) { synchronized (_fragmentedMessages) { _fragmentedMessages.remove(new Long(messageId)); } if (msg.getExpireEvent() != null) SimpleTimer.getInstance().removeEvent(msg.getExpireEvent()); _context.statManager().addRateData("tunnel.fragmentedComplete", msg.getFragmentCount(), msg.getLifetime()); receiveComplete(msg); } else { noteReception(msg.getMessageId(), fragmentNum, msg); } if (isNew && !msg.isComplete()) { RemoveFailed evt = new RemoveFailed(msg); msg.setExpireEvent(evt); if (_log.shouldLog(Log.DEBUG)) _log.debug("In " + MAX_DEFRAGMENT_TIME + " dropping " + msg.getMessageId() + "/" + fragmentNum); SimpleTimer.getInstance().addEvent(evt, MAX_DEFRAGMENT_TIME); } offset += size; return offset; } private void receiveComplete(FragmentedMessage msg) { if (msg == null) return; _completed++; String stringified = null; if (_log.shouldLog(Log.DEBUG)) stringified = msg.toString(); try { int fragmentCount = msg.getFragmentCount(); // toByteArray destroys the contents of the message completely byte data[] = msg.toByteArray(); if (data == null) throw new I2NPMessageException("null data"); // fragments already released??? if (_log.shouldLog(Log.DEBUG)) _log.debug("RECV(" + data.length + "): " + Base64.encode(data) + " " + _context.sha().calculateHash(data).toBase64()); I2NPMessage m = new I2NPMessageHandler(_context).readMessage(data); noteReception(m.getUniqueId(), fragmentCount-1, "complete: ");// + msg.toString()); noteCompletion(m.getUniqueId()); _receiver.receiveComplete(m, msg.getTargetRouter(), msg.getTargetTunnel()); } catch (IOException ioe) { if (stringified == null) stringified = msg.toString(); if (_log.shouldLog(Log.ERROR)) _log.error("Error receiving fragmented message (corrupt?): " + stringified, ioe); } catch (I2NPMessageException ime) { if (stringified == null) stringified = msg.toString(); if (_log.shouldLog(Log.WARN)) _log.warn("Error receiving fragmented message (corrupt?): " + stringified, ime); } } protected void noteReception(long messageId, int fragmentId, Object status) {} protected void noteCompletion(long messageId) {} protected void noteFailure(long messageId, String status) {} /** * Receive messages out of the tunnel endpoint. There should be a single * instance of this object per tunnel so that it can tell what tunnel various * messages come in on (e.g. to prevent DataMessages arriving from anywhere * other than the client's inbound tunnels) * */ public interface DefragmentedReceiver { /** * Receive a fully formed I2NPMessage out of the tunnel * * @param msg message received * @param toRouter where we are told to send the message (null means locally) * @param toTunnel where we are told to send the message (null means locally or to the specified router) */ public void receiveComplete(I2NPMessage msg, Hash toRouter, TunnelId toTunnel); } private class RemoveFailed implements SimpleTimer.TimedEvent { private FragmentedMessage _msg; public RemoveFailed(FragmentedMessage msg) { _msg = msg; } public void timeReached() { boolean removed = false; synchronized (_fragmentedMessages) { removed = (null != _fragmentedMessages.remove(new Long(_msg.getMessageId()))); } if (removed && !_msg.getReleased()) { _failed++; noteFailure(_msg.getMessageId(), _msg.toString()); if (_log.shouldLog(Log.WARN)) _log.warn("Dropped failed fragmented message: " + _msg); _context.statManager().addRateData("tunnel.fragmentedDropped", _msg.getFragmentCount(), _msg.getLifetime()); _msg.failed(); } else { // succeeded before timeout } } } }
package org.insightech.er.editor.controller.command.diagram_contents.element.connection.relation; import org.insightech.er.ResourceString; import org.insightech.er.editor.controller.command.diagram_contents.element.connection.AbstractCreateConnectionCommand; import org.insightech.er.editor.model.diagram_contents.element.node.table.ERTable; public abstract class AbstractCreateRelationCommand extends AbstractCreateConnectionCommand { /** * {@inheritDoc} */ @Override public String validate() { ERTable sourceTable = (ERTable) this.getSourceModel(); if (!sourceTable.isReferable()) { return ResourceString .getResourceString("error.no.referenceable.column"); } return null; } /** * {@inheritDoc} */ @Override public boolean canExecute() { if (!super.canExecute()) { return false; } if (!(this.getSourceModel() instanceof ERTable) || !(this.getTargetModel() instanceof ERTable)) { return false; } return true; } }
package de.hwrberlin.it2014.sweproject.cbr; import de.hwrberlin.it2014.sweproject.cbr.Request; import de.hwrberlin.it2014.sweproject.database.DatabaseConnection; import de.hwrberlin.it2014.sweproject.database.TableResultsSQL; import de.hwrberlin.it2014.sweproject.model.Result; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; /** * implementiert den FBS-Zyklus. Im Konstruktor kann die Anzahl der Ergebnisse angegeben werden. * Zum Starten aufrufen: startCBR(ArrayList<String> oder String[] oder String). * saveUserRating(int,float) speichert die NutzerWertung zu einem bestimmten Fall * * @author Max Bock & Felix Lehmann * */ public class CBR { private int COUNT_TO_RETURN; public CBR() { COUNT_TO_RETURN=30; } public CBR(int count) { COUNT_TO_RETURN=count; } /** * leitet Nutzeranfrage weiter und gibt aehnliche Faelle zurueck * @author Max Bock * @param usersInput (String) * @return aehnliche Faelle */ public ArrayList<Result> startCBR(String usersInput) { String[] ar = usersInput.split(" "); return startCBR(ar); } /** * leitet Nutzeranfrage weiter und gibt aehnliche Faelle zurueck * @author Max Bock * @param usersInput (String[]) * @return aehnliche Faelle */ public ArrayList<Result> startCBR(String[] usersInput) { ArrayList<String> al = new ArrayList<>(); for(String s : usersInput){ al.add(s); } return startCBR(al); } /** * leitet Nutzeranfrage weiter und gibt aehnliche Faelle zurueck * @author Max Bock * @param usersInput (ArrayList<String>) * @return aehnliche Faelle */ public ArrayList<Result> startCBR(ArrayList<String> usersInput) { ArrayList<Result> resList; try { Request rq = new Request(usersInput); resList=rq.getSimilarFromDB(COUNT_TO_RETURN); } catch (SQLException e) { resList=new ArrayList<>(); e.printStackTrace(); } return resList; } /** * speichert die Bewertung zu einem Fall einer Anfrage * @param id der Anfrage * @param evaluation Bewertung * @return null * @throws SQLException */ public String saveUserRating(int idOfResult, float rating) throws SQLException { //TODO //doesnt work yet //use saveRating instead if(idOfResult<=-1) return "invalid id"; String query = TableResultsSQL.getSelectSQLCode(idOfResult); DatabaseConnection dbc=new DatabaseConnection(); dbc.connectToMysql(); ResultSet rs = dbc.executeQuery(query); ArrayList<Result> rl = dbc.convertResultSetToResultList(rs); Result result = rl.get(0); if(result.getUserRating()!=0.0f){ result.setUserRating(rating); String updateQuery = TableResultsSQL.getUpdateSQLCodeForUserRating(result); dbc.executeUpdate(updateQuery); return "success"; } else { return "fail: is already rated"; } } public boolean saveRating(int id, float rating) { DatabaseConnection con = new DatabaseConnection(); int update = TableResultsSQL.saveUserRating(id, rating, con); if(update <=0){ return false; } return true; } }
package de.tum.in.www1.artemis.domain; import static de.tum.in.www1.artemis.config.Constants.FEEDBACK_DETAIL_TEXT_MAX_CHARACTERS; import java.util.*; import javax.annotation.Nullable; import javax.persistence.*; import javax.validation.constraints.Size; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import de.tum.in.www1.artemis.domain.enumeration.FeedbackType; import de.tum.in.www1.artemis.domain.enumeration.Visibility; /** * A Feedback. */ @Entity @Table(name = "feedback") @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) @JsonInclude(JsonInclude.Include.NON_EMPTY) public class Feedback extends DomainObject { public static final int MAX_REFERENCE_LENGTH = 2000; public static final String STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER = "SCAFeedbackIdentifier:"; public static final String SUBMISSION_POLICY_FEEDBACK_IDENTIFIER = "SubPolFeedbackIdentifier:"; @Size(max = 500) @Column(name = "text", length = 500) private String text; @Size(max = FEEDBACK_DETAIL_TEXT_MAX_CHARACTERS) // this ensures that the detail_text can be stored, even for long feedback @Column(name = "detail_text", length = FEEDBACK_DETAIL_TEXT_MAX_CHARACTERS) private String detailText; /** * Reference to the assessed element (e.g. model element id or text element string) */ @Size(max = MAX_REFERENCE_LENGTH) @Column(name = "reference", length = MAX_REFERENCE_LENGTH) private String reference; /** * Absolute score for the assessed element (e.g. +0.5, -1.0, +2.0, etc.) */ @Column(name = "credits") private Double credits; @Column(name = "positive") private Boolean positive; @Enumerated(EnumType.STRING) @Column(name = "type") private FeedbackType type; @Enumerated(EnumType.STRING) @Column(name = "visibility") private Visibility visibility; @ManyToOne @JsonIgnoreProperties("feedbacks") private Result result; @ManyToOne private GradingInstruction gradingInstruction; /** * Represents the reference of the previously assessed block, whose feedback we are reusing */ @Transient @JsonSerialize private String suggestedFeedbackReference; /** * Represents the submission of the previously assessed block, whose feedback we are reusing */ @Transient @JsonSerialize private Long suggestedFeedbackOriginSubmissionReference; /** * Represents the participation reference of the submission to which the previously assessed block being reused belongs to */ @Transient @JsonSerialize private Long suggestedFeedbackParticipationReference; // TODO: JP remove these two references as they are not really needed @OneToMany(mappedBy = "firstFeedback", orphanRemoval = true) private List<FeedbackConflict> firstConflicts = new ArrayList<>(); @OneToMany(mappedBy = "secondFeedback", orphanRemoval = true) private List<FeedbackConflict> secondConflicts = new ArrayList<>(); public String getText() { return text; } public Feedback text(String text) { this.text = text; return this; } public void setText(String text) { this.text = text; } public String getDetailText() { return detailText; } public Feedback detailText(@Nullable String detailText) { this.setDetailText(detailText); return this; } /** * sets the detail text of the feedback. In case the detail text is longer than 5000 characters, the additional characters are cut off to avoid database issues * @param detailText the new detail text for the feedback, can be null */ public void setDetailText(@Nullable String detailText) { if (detailText == null || detailText.length() <= FEEDBACK_DETAIL_TEXT_MAX_CHARACTERS) { this.detailText = detailText; } else { this.detailText = detailText.substring(0, FEEDBACK_DETAIL_TEXT_MAX_CHARACTERS); } } public String getReference() { return reference; } public Feedback reference(String reference) { this.reference = reference; return this; } public boolean hasReference() { return reference != null && !reference.isEmpty(); } public void setReference(String reference) { this.reference = reference; } /** * For modeling submissions the reference looks like "<umlElementType>:<jsonElementId>". This function tries to split the reference string at ':' and returns the second part * (i.e. the jsonElementId). * * @return the jsonElementId for modeling submissions or null if the reference string does not contain ':' */ @JsonIgnore public String getReferenceElementId() { if (reference == null || !reference.contains(":")) { return null; } return reference.split(":")[1]; } /** * For modeling submissions the reference looks like "<umlElementType>:<jsonElementId>". This function tries to split the reference string at ':' and returns the first part * (i.e. the umlElementType). * * @return the umlElementType for modeling submissions or null if the reference string does not contain ':' */ @JsonIgnore public String getReferenceElementType() { if (!reference.contains(":")) { return null; } return reference.split(":")[0]; } public Double getCredits() { return credits; } public Feedback credits(Double credits) { this.credits = credits; return this; } public void setCredits(Double credits) { this.credits = credits; } /** * Returns if this is a positive feedback. * * This value can actually be {@code null} for feedbacks that are neither positive nor negative, e.g. when this is a * feedback for a programming exercise test case that has not been executed for the submission. * * @return true, if this is a positive feedback. */ public Boolean isPositive() { return positive; } public Feedback positive(Boolean positive) { this.positive = positive; return this; } public void setPositive(Boolean positive) { this.positive = positive; } public FeedbackType getType() { return type; } public Feedback type(FeedbackType type) { this.type = type; return this; } public void setType(FeedbackType type) { this.type = type; } public Visibility getVisibility() { return visibility; } @JsonIgnore public boolean isAfterDueDate() { return this.visibility == Visibility.AFTER_DUE_DATE; } @JsonIgnore public boolean isInvisible() { return this.visibility == Visibility.NEVER; } public Feedback visibility(Visibility visibility) { this.visibility = visibility; return this; } public void setVisibility(Visibility visibility) { this.visibility = visibility; } public Result getResult() { return result; } public Feedback result(Result result) { this.result = result; return this; } /** * be careful when using this method as it might result in org.hibernate.HibernateException: null index column for collection: de.tum.in.www1.artemis.domain.Result.feedbacks * when saving the result. The result object is the container that owns the feedback and uses CascadeType.ALL and orphanRemoval * @param result the result container object that owns the feedback */ public void setResult(Result result) { this.result = result; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove public GradingInstruction getGradingInstruction() { return gradingInstruction; } public void setGradingInstruction(GradingInstruction gradingInstruction) { this.gradingInstruction = gradingInstruction; } public String getSuggestedFeedbackReference() { return suggestedFeedbackReference; } public void setSuggestedFeedbackOriginBlock(String suggestedFeedbackOriginBlockId) { this.suggestedFeedbackReference = suggestedFeedbackOriginBlockId; } public Long getSuggestedFeedbackOriginSubmissionReference() { return suggestedFeedbackOriginSubmissionReference; } public void setSuggestedFeedbackOriginSubmission(Long suggestedFeedbackOriginSubmission) { this.suggestedFeedbackOriginSubmissionReference = suggestedFeedbackOriginSubmission; } public Long getSuggestedFeedbackParticipationReference() { return suggestedFeedbackParticipationReference; } public void setSuggestedFeedbackParticipationReference(Long suggestedFeedbackParticipationReference) { this.suggestedFeedbackParticipationReference = suggestedFeedbackParticipationReference; } /** * This function sets the described parameters and then returns the current instance with the updated references. * * @param suggestedFeedbackOriginBlockReference - Block reference of the suggested (automatic) feedback * @param submissionId - Submission reference where the suggested feedback was generated from * @param suggestedFeedbackParticipationId - respective participation reference * @return updated Feedback */ public Feedback suggestedFeedbackOrigin(String suggestedFeedbackOriginBlockReference, Long submissionId, Long suggestedFeedbackParticipationId) { this.suggestedFeedbackReference = suggestedFeedbackOriginBlockReference; this.suggestedFeedbackOriginSubmissionReference = submissionId; this.suggestedFeedbackParticipationReference = suggestedFeedbackParticipationId; return this; } public List<FeedbackConflict> getFirstConflicts() { return firstConflicts; } public void setFirstConflicts(List<FeedbackConflict> firstConflicts) { this.firstConflicts = firstConflicts; } public List<FeedbackConflict> getSecondConflicts() { return secondConflicts; } public void setSecondConflicts(List<FeedbackConflict> secondConflicts) { this.secondConflicts = secondConflicts; } @JsonIgnore public boolean isStaticCodeAnalysisFeedback() { return this.text != null && this.text.startsWith(STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER) && this.type == FeedbackType.AUTOMATIC; } /** * Returns the Artemis static code analysis category to which this feedback belongs. The method returns an empty * String, if the feedback is not static code analysis feedback. * * @return The Artemis static code analysis category to which this feedback belongs */ @JsonIgnore public String getStaticCodeAnalysisCategory() { if (isStaticCodeAnalysisFeedback()) { return this.getText().substring(Feedback.STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER.length()); } return ""; } /** * Copies an automatic feedback to be used for the manual result of a programming exercise * @return Copy of the automatic feedback without its original ID */ public Feedback copyFeedback() { var feedback = new Feedback(); feedback.setDetailText(getDetailText()); feedback.setType(getType()); // For manual result each feedback needs to have a credit. If no credit is set, we set it to 0.0 feedback.setCredits(Optional.ofNullable(getCredits()).orElse(0.0)); feedback.setText(getText()); feedback.setPositive(isPositive()); feedback.setReference(getReference()); feedback.setVisibility(getVisibility()); feedback.setGradingInstruction(getGradingInstruction()); return feedback; } @Override public String toString() { return "Feedback{" + "id=" + getId() + ", text='" + getText() + "'" + ", detailText='" + getDetailText() + "'" + ", reference='" + getReference() + "'" + ", positive='" + isPositive() + "'" + ", type='" + getType() + ", visibility=" + getVisibility() + ", gradingInstruction='" + getGradingInstruction() + "'" + "}"; } /** * Calculates the score over all feedback elements that were set using structured grading instructions (SGI) * @param inputScore totalScore which is summed up. * @param gradingInstructions empty grading instruction Map to collect the used gradingInstructions * @return calculated total score from feedback elements set by SGI */ @JsonIgnore public double computeTotalScore(double inputScore, Map<Long, Integer> gradingInstructions) { double totalScore = inputScore; if (gradingInstructions.get(getGradingInstruction().getId()) != null) { // We Encountered this grading instruction before var maxCount = getGradingInstruction().getUsageCount(); var encounters = gradingInstructions.get(getGradingInstruction().getId()); if (maxCount > 0) { if (encounters >= maxCount) { // the structured grading instruction was applied on assessment models more often that the usageCount limit allows, so we don't sum the feedback credit gradingInstructions.put(getGradingInstruction().getId(), encounters + 1); } else { // the usageCount limit was not exceeded yet, so we add the credit and increase the nrOfEncounters counter gradingInstructions.put(getGradingInstruction().getId(), encounters + 1); totalScore += getGradingInstruction().getCredits(); } } else { totalScore += getCredits(); } } else { // First time encountering the grading instruction gradingInstructions.put(getGradingInstruction().getId(), 1); totalScore += getCredits(); } return totalScore; } }
package org.xwiki.crypto.pkix.internal; import java.io.IOException; import java.math.BigInteger; import java.util.Date; import org.bouncycastle.asn1.ASN1Integer; import org.bouncycastle.asn1.x509.TBSCertificate; import org.bouncycastle.asn1.x509.Time; import org.bouncycastle.asn1.x509.V3TBSCertificateGenerator; import org.xwiki.crypto.params.cipher.asymmetric.PublicKeyParameters; import org.xwiki.crypto.pkix.internal.extension.BcX509Extensions; import org.xwiki.crypto.pkix.internal.extension.DefaultX509ExtensionBuilder; import org.xwiki.crypto.pkix.params.CertifiedPublicKey; import org.xwiki.crypto.pkix.params.PrincipalIndentifier; import org.xwiki.crypto.pkix.params.x509certificate.extension.X509Extensions; import org.xwiki.crypto.signer.Signer; /** * To Be Signed version 3 certificate builder. * * @version $Id$ * @since 5.4 */ public class BcX509v3TBSCertificateBuilder implements BcX509TBSCertificateBuilder { private final V3TBSCertificateGenerator tbsGen = new V3TBSCertificateGenerator(); @Override public BcX509TBSCertificateBuilder setSerialNumber(BigInteger serial) { tbsGen.setSerialNumber(new ASN1Integer(serial)); return this; } @Override public BcX509TBSCertificateBuilder setSubjectPublicKeyInfo(PublicKeyParameters subject) { tbsGen.setSubjectPublicKeyInfo(BcUtils.getSubjectPublicKeyInfo(subject)); return this; } @Override public BcX509TBSCertificateBuilder setIssuer(PrincipalIndentifier issuer) { tbsGen.setIssuer(BcUtils.getX500Name(issuer)); return this; } @Override public BcX509TBSCertificateBuilder setSubject(PrincipalIndentifier subject) { tbsGen.setSubject(BcUtils.getX500Name(subject)); return this; } @Override public BcX509TBSCertificateBuilder setStartDate(Date time) { tbsGen.setStartDate(new Time(time)); return this; } @Override public BcX509TBSCertificateBuilder setEndDate(Date time) { tbsGen.setEndDate(new Time(time)); return this; } @Override public BcX509TBSCertificateBuilder setSignature(Signer signer) { tbsGen.setSignature(BcUtils.getSignerAlgoritmIdentifier(signer)); return this; } @Override public TBSCertificate build() { return tbsGen.generateTBSCertificate(); } /** * Set the extensions of a self-signed v3 certificate. * * @param subject the subject certified public key parameters to compute the Subject Key Identifier, or null for * none. * @param extensions1 the common extensions set. * @param extensions2 the subject extensions set. * @return this builder to allow chaining. * @throws IOException on encoding error. */ public BcX509v3TBSCertificateBuilder setExtensions(PublicKeyParameters subject, X509Extensions extensions1, X509Extensions extensions2) throws IOException { DefaultX509ExtensionBuilder extBuilder = new DefaultX509ExtensionBuilder(); if (extensions1 != null || extensions2 != null) { extBuilder.addAuthorityKeyIdentifier(subject) .addSubjectKeyIdentifier(subject) .addExtensions(extensions1) .addExtensions(extensions2); } if (!extBuilder.isEmpty()) { tbsGen.setExtensions(((BcX509Extensions) extBuilder.build()).getExtensions()); } return this; } /** * Set the extensions of a v3 certificate. * * @param issuer the issuer certified public key to compute the Authority Key Identifier, or null for none. * @param subject the subject certified public key parameters to compute the Subject Key Identifier, or null for * none. * @param extensions1 the common extensions set. * @param extensions2 the subject extensions set. * @return this builder to allow chaining. * @throws IOException on encoding error. */ public BcX509v3TBSCertificateBuilder setExtensions(CertifiedPublicKey issuer, PublicKeyParameters subject, X509Extensions extensions1, X509Extensions extensions2) throws IOException { DefaultX509ExtensionBuilder extBuilder = new DefaultX509ExtensionBuilder(); extBuilder.addAuthorityKeyIdentifier(issuer) .addSubjectKeyIdentifier(subject) .addExtensions(extensions1) .addExtensions(extensions2); if (!extBuilder.isEmpty()) { tbsGen.setExtensions(((BcX509Extensions) extBuilder.build()).getExtensions()); } return this; } }
package fr.insee.rmes.modeles.operations; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlElementWrapper; import org.apache.commons.lang3.StringUtils; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import fr.insee.rmes.modeles.StringWithLang; import fr.insee.rmes.utils.Lang; import io.swagger.v3.oas.annotations.media.Schema; @Schema(description = "Objet représentant une série d'opérations statistiques") public class Serie { private String id = null; private List<StringWithLang> label = new ArrayList<>(); @Schema(example = "http://id.insee.fr/operations/serie/s1234") private String uri = null; @JsonInclude(Include.NON_NULL) private SimpleObject family = null; @JsonInclude(Include.NON_NULL) private List<StringWithLang> abstractSerie; @JsonInclude(Include.NON_NULL) private List<StringWithLang> historyNote; @JsonInclude(Include.NON_NULL) private List<StringWithLang> altLabel; @JsonInclude(Include.NON_NULL) private SimpleObject type = null; @JsonInclude(Include.NON_NULL) private SimpleObject accrualPeriodicity = null; @Schema(example = "1011") @JsonInclude(Include.NON_NULL) private String simsId = null; @JsonInclude(Include.NON_NULL) private List<Operation> operations; @JsonInclude(Include.NON_NULL) private List<Indicateur> indicateurs; @JsonInclude(Include.NON_NULL) private List<SeriePrecedente> replaces; @JsonInclude(Include.NON_NULL) private List<SerieSuivante> isReplacedBy; @JsonInclude(Include.NON_NULL) private List<ObjectWithSimsId> seeAlso; @JsonInclude(Include.NON_NULL) private List<SimpleObject> publishers; @JsonInclude(Include.NON_NULL) private List<SimpleObject> contributors; public Serie(String uri, String id, String labelLg1, String labelLg2) { this.id = id; label.add(new StringWithLang(labelLg1, Lang.FR)); if ( ! labelLg2.equals("")) { label.add(new StringWithLang(labelLg2, Lang.EN)); } this.uri = uri; } public Serie() { super(); } public void addOperation(Operation op) { if (operations == null) { this.setOperations(new ArrayList<>()); } this.operations.add(op); } public void addIndicateur(Indicateur indic) { if (indicateurs == null) { this.setIndicateurs(new ArrayList<>()); } this.indicateurs.add(indic); } public void addSeeAlso(ObjectWithSimsId sa) { if (seeAlso == null) { this.setSeeAlso(new ArrayList<>()); } this.seeAlso.add(sa); } public void addReplaces(SeriePrecedente rep) { if (replaces == null) { this.setReplaces(new ArrayList<>()); } this.replaces.add(rep); } public void addIsReplacedBy(SerieSuivante irb) { if (isReplacedBy == null) { this.setIsReplacedBy(new ArrayList<>()); } this.isReplacedBy.add(irb); } public String getId() { return id; } public void setId(String id) { this.id = id; } @JacksonXmlProperty(localName = "label") @JacksonXmlElementWrapper(useWrapping = false) public List<StringWithLang> getLabel() { return label; } @JacksonXmlProperty(localName = "SimsId") public String getSimsId() { return simsId; } public void setSimsId(String simsId) { if ( ! simsId.equals("")) { this.simsId = simsId; } } @JacksonXmlProperty(isAttribute = true, localName = "Operation") @JacksonXmlElementWrapper(useWrapping = false) public List<Operation> getOperations() { return operations; } public void setOperations(List<Operation> operations) { this.operations = operations; } @JacksonXmlProperty(isAttribute = true, localName = "Indicateur") @JacksonXmlElementWrapper(useWrapping = false) public List<Indicateur> getIndicateurs() { return indicateurs; } public void setIndicateurs(List<Indicateur> indicateurs) { this.indicateurs = indicateurs; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public void setFamily(SimpleObject f) { this.family = f; } @JsonProperty("famille") @JacksonXmlProperty(isAttribute = true, localName = "Famille") @JacksonXmlElementWrapper(useWrapping = false) public SimpleObject getFamily() { return family; } @JacksonXmlProperty(localName = "Type") public SimpleObject getType() { return type; } public void setType(SimpleObject type) { this.type = type; } @JsonInclude(Include.NON_EMPTY) @JsonProperty("seriesPrecedentes") @XmlElementWrapper(name = "SeriesPrecedentes") @JacksonXmlElementWrapper(localName = "SeriesPrecedentes") @JacksonXmlProperty(localName = "SeriePrecedente") public List<SeriePrecedente> getReplaces() { return replaces; } public void setReplaces(List<SeriePrecedente> replaces) { this.replaces = replaces; } @JsonInclude(Include.NON_EMPTY) @JsonProperty("seriesSuivantes") //json example @XmlElementWrapper(name = "SeriesSuivantes") //xml example list @JacksonXmlElementWrapper(localName = "SeriesSuivantes") //xml response @JacksonXmlProperty(localName = "SerieSuivante") //xml response public List<SerieSuivante> getIsReplacedBy() { return isReplacedBy; } public void setIsReplacedBy(List<SerieSuivante> isReplacedBy) { this.isReplacedBy = isReplacedBy; } @JsonProperty("voirAussi") @JacksonXmlProperty(isAttribute = true, localName = "VoirAussi") @JacksonXmlElementWrapper(useWrapping = false) public List<ObjectWithSimsId> getSeeAlso() { return seeAlso; } public void setSeeAlso(List<ObjectWithSimsId> seeAlso) { this.seeAlso = seeAlso; } @JsonProperty("periodicite") @JacksonXmlProperty(isAttribute = true, localName = "Periodicite") @JacksonXmlElementWrapper(useWrapping = false) public SimpleObject getAccrualPeriodicity() { return accrualPeriodicity; } public void setAccrualPeriodicity(SimpleObject accrualPeriodicity) { this.accrualPeriodicity = accrualPeriodicity; } @JsonProperty("resume") @JacksonXmlProperty(localName = "Resume") @JacksonXmlElementWrapper(useWrapping = false) public List<StringWithLang> getAbstractSerie() { return abstractSerie; } public void setAbstractLg1(String abstractLg1) { setAbstract(abstractLg1, Lang.FR); } public void setAbstractLg2(String abstractLg2) { setAbstract(abstractLg2, Lang.EN); } private void setAbstract(String abstr, Lang lang) { if (StringUtils.isNotEmpty(abstr)) { if (abstractSerie == null) { abstractSerie = new ArrayList<>(); } abstractSerie.add(new StringWithLang(abstr, lang)); } } @JsonProperty("noteHistorique") @JacksonXmlProperty(localName = "NoteHistorique") @JacksonXmlElementWrapper(useWrapping = false) public List<StringWithLang> getHistoryNote() { return historyNote; } public void setHistoryNoteLg1(String str) { setHistoryNote(str, Lang.FR); } public void setHistoryNoteLg2(String str) { setHistoryNote(str, Lang.EN); } private void setHistoryNote(String str, Lang lang) { if (StringUtils.isNotEmpty(str)) { if (historyNote == null) { historyNote = new ArrayList<>(); } historyNote.add(new StringWithLang(str, lang)); } } @JsonInclude(Include.NON_EMPTY) @JsonProperty("organismesResponsables") //json example @XmlElementWrapper(name = "OrganismesResponsables") //xml example list @JacksonXmlElementWrapper(localName = "OrganismesResponsables") //xml response @JacksonXmlProperty(localName = "OrganismeResponsable") //xml response public List<SimpleObject> getPublishers() { return publishers; } public void setPublishers(List<SimpleObject> publishers) { this.publishers = publishers; } @JsonInclude(Include.NON_EMPTY) @JsonProperty("partenaires") //json example @XmlElementWrapper(name = "Partenaires") //xml example list @JacksonXmlElementWrapper(localName = "Partenaires") //xml response @JacksonXmlProperty(localName = "Partenaire") //xml response public List<SimpleObject> getContributors() { return contributors; } public void setContributors(List<SimpleObject> contributors) { this.contributors = contributors; } public void setLabelFr(String labelFr) { setLabel(labelFr, Lang.FR); } public void setLabelEn(String labelEn) { setLabel(labelEn, Lang.EN); } private void setLabel(String newlabel, Lang lang) { if (StringUtils.isNotEmpty(newlabel)) { label.add(new StringWithLang(newlabel, lang)); } } @JacksonXmlProperty(localName = "AltLabel") @JacksonXmlElementWrapper(useWrapping = false) public List<StringWithLang> getAltLabel() { return altLabel; } public void setAltLabel(String altLabelLg1, String altLabelLg2) { if ( ! altLabelLg1.equals("")) { initAltLabel(); altLabel.add(new StringWithLang(altLabelLg1, Lang.FR)); } if ( ! altLabelLg2.equals("")) { initAltLabel(); altLabel.add(new StringWithLang(altLabelLg2, Lang.EN)); } } private void initAltLabel() { if (altLabel == null) { altLabel = new ArrayList<>(); } } }
package org.xwiki.extension.repository.internal; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import org.xwiki.extension.Extension; import org.xwiki.extension.repository.result.CollectionIterableResult; import org.xwiki.extension.repository.search.ExtensionQuery; import org.xwiki.extension.repository.search.ExtensionQuery.COMPARISON; import org.xwiki.extension.repository.search.ExtensionQuery.Filter; import org.xwiki.extension.repository.search.ExtensionQuery.SortClause; /** * A set of Repository related tools. * * @version $Id$ * @since 4.0M2 */ public final class RepositoryUtils { /** * The suffix and prefix to add to the regex when searching for a core extension. */ public static final String SEARCH_PATTERN_SUFFIXNPREFIX = ".*"; /** * Utility class. */ private RepositoryUtils() { } /** * @param pattern the pattern to match * @param offset the offset where to start returning elements * @param nb the number of maximum element to return * @param extensions the extension collection to search in * @return the search result * @param <E> the type of element in the {@link Collection} */ public static <E extends Extension> CollectionIterableResult<E> searchInCollection(String pattern, int offset, int nb, Collection<E> extensions) { return searchInCollection(pattern, offset, nb, extensions, false); } /** * @param pattern the pattern to match * @param offset the offset where to start returning elements * @param nb the number of maximum element to return * @param extensions the extension collection to search in * @param forceUnique make sure returned elements are unique * @return the search result * @since 6.4.1 * @param <E> the type of element in the {@link Collection} */ public static <E extends Extension> CollectionIterableResult<E> searchInCollection(String pattern, int offset, int nb, Collection<E> extensions, boolean forceUnique) { ExtensionQuery query = new ExtensionQuery(pattern); query.setOffset(offset); query.setLimit(nb); return searchInCollection(query, extensions, forceUnique); } /** * @param query the query * @param extensions the extension collection to search in * @param forceUnique make sure returned elements are unique * @return the search result * @since 7.0M2 * @param <E> the type of element in the {@link Collection} */ public static <E extends Extension> CollectionIterableResult<E> searchInCollection(ExtensionQuery query, Collection<E> extensions, boolean forceUnique) { List<E> result; // Filter if (StringUtils.isEmpty(query.getQuery())) { result = extensions instanceof List ? (List<E>) extensions : new ArrayList<E>(extensions); } else { result = filter(query.getQuery(), query.getFilters(), extensions, forceUnique); } // Sort sort(result, query.getSortClauses()); // Create result return RepositoryUtils.getIterableResult(query.getOffset(), query.getLimit(), result); } /** * @param offset the offset where to start returning elements * @param nb the number of maximum element to return * @param elements the element collection to search in * @return the result to limit * @param <E> the type of element in the {@link Collection} */ public static <E> CollectionIterableResult<E> getIterableResult(int offset, int nb, Collection<E> elements) { if (nb == 0 || offset >= elements.size()) { return new CollectionIterableResult<E>(elements.size(), offset, Collections.<E>emptyList()); } List<E> list; if (elements instanceof List) { list = (List<E>) elements; } else { list = new ArrayList<E>(elements); } return getIterableResultFromList(offset, nb, list); } /** * @param offset the offset where to start returning elements * @param nb the number of maximum element to return * @param elements the element collection to search in * @return the result to limit * @param <E> the type of element in the {@link List} */ private static <E> CollectionIterableResult<E> getIterableResultFromList(int offset, int nb, List<E> elements) { int fromIndex = offset; if (fromIndex < 0) { fromIndex = 0; } int toIndex; if (nb > 0) { toIndex = nb + fromIndex; if (toIndex > elements.size()) { toIndex = elements.size(); } } else { toIndex = elements.size(); } return new CollectionIterableResult<E>(elements.size(), offset, elements.subList(fromIndex, toIndex)); } /** * @param pattern the pattern to match * @param filters the filters * @param extensions the extension collection to search in * @param forceUnique make sure returned elements are unique * @return the filtered list of extensions * @since 7.0M2 * @param <E> the type of element in the {@link Collection} */ private static <E extends Extension> List<E> filter(String pattern, Collection<Filter> filters, Collection<E> extensions, boolean forceUnique) { List<E> result = new ArrayList<E>(extensions.size()); Pattern patternMatcher = Pattern.compile(SEARCH_PATTERN_SUFFIXNPREFIX + pattern.toLowerCase() + SEARCH_PATTERN_SUFFIXNPREFIX); for (E extension : extensions) { if (matches(patternMatcher, filters, extension)) { result.add(extension); } } // Make sure all the elements of the list are unique if (forceUnique && result.size() > 1) { result = new ArrayList<>(new LinkedHashSet<>(result)); } return result; } /** * Matches an extension in a case insensitive way. * * @param patternMatcher the pattern to match * @param filters the filters * @param extension the extension to match * @return true if one of the element is matched * @since 7.0M2 */ public static boolean matches(Pattern patternMatcher, Collection<Filter> filters, Extension extension) { if (matches(patternMatcher, extension.getId().getId(), extension.getDescription(), extension.getSummary(), extension.getName(), extension.getFeatures())) { for (Filter filter : filters) { if (!matches(filter, extension)) { return false; } } return true; } return false; } /** * @param filter the filter * @param extension the extension to match * @return true if the extension is matched by the filer * @since 7.0M2 */ public static boolean matches(Filter filter, Extension extension) { return matches(filter, extension.get(filter.getField())); } /** * @param filter the filter * @param element the element to match * @return true if the element is matched by the filer * @since 7.0M2 */ public static boolean matches(Filter filter, Object element) { if (element == null) { return filter.getValue() == null; } else if (filter.getValue() == null) { return false; } // TODO: add support for more than String String filterValue = String.valueOf(filter.getValue()); String elementValue = String.valueOf(element); if (filter.getComparison() == COMPARISON.MATCH) { Pattern patternMatcher = createPatternMatcher(filterValue); if (matches(patternMatcher, elementValue)) { return true; } } else if (filter.getComparison() == COMPARISON.EQUAL) { if (filterValue.equals(elementValue)) { return true; } } return false; } /** * Matches a set of elements in a case insensitive way. * * @param patternMatcher the pattern to match * @param elements the elements to match * @return true if one of the element is matched */ public static boolean matches(Pattern patternMatcher, Object... elements) { if (patternMatcher == null) { return true; } for (Object element : elements) { if (matches(patternMatcher, element)) { return true; } } return false; } /** * @param patternMatcher the pattern to match * @param element the element to match with the pattern * @return true of the element is matched by the pattern */ public static boolean matches(Pattern patternMatcher, Object element) { if (element != null) { if (patternMatcher.matcher(element.toString().toLowerCase()).matches()) { return true; } } return false; } /** * @param pattern the pattern to match * @return a {@link Pattern} used to search the passed pattern inside a {@link String} */ public static Pattern createPatternMatcher(String pattern) { return StringUtils.isEmpty(pattern) ? null : Pattern.compile(RepositoryUtils.SEARCH_PATTERN_SUFFIXNPREFIX + Pattern.quote(pattern.toLowerCase()) + RepositoryUtils.SEARCH_PATTERN_SUFFIXNPREFIX); } /** * Sort the passed extensions list based on the passed sort clauses. * * @param extensions the list of extensions to sort * @param sortClauses the sort clauses * @since 7.0M2 */ public static void sort(List<? extends Extension> extensions, Collection<SortClause> sortClauses) { Collections.sort(extensions, new SortClauseComparator(sortClauses)); } }
// GeoJSONReader // reads some GeoJSON into a PoiWayBundle package freemap.mapsforgegeojson; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Iterator; import java.util.ArrayList; import org.mapsforge.core.model.Tag; import org.mapsforge.core.model.Tile; import org.mapsforge.core.model.LatLong; import org.mapsforge.map.datastore.MapReadResult; import org.mapsforge.map.datastore.Way; import org.mapsforge.map.datastore.PointOfInterest; import org.json.JSONObject; import org.json.JSONArray; import org.json.JSONException; public class GeoJSONReader { private boolean poisOnly; static class FeatureTests { public static boolean isWaterFeature(String k, String v) { return k.equals("natural") && v.equals("water") || k.equals("waterway"); } public static boolean isLandscapeFeature(String k, String v) { return k.equals("natural") && v.equals("wood") || k.equals("landuse") && v.equals("forest") || k.equals("natural") && v.equals("heath"); } public static boolean isLand(String k, String v) { return k.equals("natural") && v.equals("nosea"); } public static boolean isSea(String k, String v) { return k.equals("natural") && v.equals("sea"); } } public GeoJSONReader() { this(false); } public GeoJSONReader(boolean poisOnly) { this.poisOnly = poisOnly; } public MapReadResult read(InputStream is, DownloadCache cache, Tile tile) throws IOException, JSONException { /* PoiWayBundle bundle = new PoiWayBundle (new ArrayList<PointOfInterest>(), new ArrayList<Way>()); */ MapReadResult result = new MapReadResult(); String jsonString = readFromStream(is); JSONObject data = new JSONObject(jsonString); JSONArray features = data.getJSONArray("features"); byte layer; if(cache!=null && features.length() > 0) { cache.write(tile, jsonString); } for (int i=0; i<features.length(); i++) { JSONObject currentFeature = features.getJSONObject(i); String type = currentFeature.getString("type"); layer=(byte)6; // default for roads, paths etc if(type.equals("Feature")) { JSONObject geometry = currentFeature.getJSONObject("geometry"), properties = currentFeature.getJSONObject("properties"); String gType = geometry.getString("type"); if(!poisOnly || gType.equals("Point")) { ArrayList<Tag> tags = new ArrayList<Tag>(); Iterator it = properties.keys(); while(it.hasNext()) { String k = (String)it.next(), v=properties.getString(k); if(k.equals("contour")) { layer = (byte)4; // contours under roads/paths } else if (k.equals("power")) { layer = (byte)7; // power lines above all else } else if (FeatureTests.isLandscapeFeature(k,v)) { layer = (byte)3; // woods etc below contours } else if (FeatureTests.isWaterFeature(k,v)) { layer = (byte)5; // lakes above contours, below rds } else if (FeatureTests.isLand(k,v)) { layer = (byte)2; // land below everything else } else if (FeatureTests.isSea(k,v)) { layer = (byte)1; // land below everything else } tags.add(new Tag(k,v)); } JSONArray coords = geometry.getJSONArray("coordinates"); if(gType.equals("Point")) { LatLong ll = new LatLong ( coords.getDouble(1), coords.getDouble(0) ); PointOfInterest poi = new PointOfInterest ((byte)6, tags, ll); // pois above all else result.pointOfInterests.add(poi); } else if (gType.equals("LineString")) { LatLong[][] points = readWayFeature(coords); Way way = new Way(layer, tags, points, null); result.ways.add(way); } else if (gType.equals("MultiLineString")) { LatLong[][] points = readMultiWayFeature(coords); Way way = new Way(layer, tags, points, null); result.ways.add(way); } else if (gType.equals("Polygon")) { // polygons are 3-deep in geojson but only actually // contain one line so we simplify them LatLong[][] points = readWayFeature (coords.getJSONArray(0)); Way way = new Way(layer, tags, points, null); result.ways.add(way); } else if (gType.equals("MultiPolygon")) { LatLong[][] points=readMultiWayFeature (coords.getJSONArray(0)); Way way = new Way(layer, tags, points, null); result.ways.add(way); } } } } return result; } private String readFromStream (InputStream is) throws IOException { byte[] bytes = new byte[1024]; StringBuffer text = new StringBuffer(); int bytesRead; while((bytesRead = is.read(bytes,0,1024))>=0) { text.append(new String(bytes,0,bytesRead)); } return text.toString(); } private LatLong[][] readWayFeature(JSONArray coords) { LatLong[][] points = new LatLong[1][]; points[0] = new LatLong[coords.length()]; readLineString(points[0], coords); return points; } private void readLineString(LatLong[] points, JSONArray coords) { for(int j=0; j<coords.length(); j++) { JSONArray curPoint = coords.getJSONArray(j); points[j] = new LatLong(curPoint.getDouble(1), curPoint.getDouble(0)); } } private LatLong[][] readMultiWayFeature (JSONArray coords) { LatLong[][] points = new LatLong[coords.length()][]; for(int i=0; i<coords.length(); i++) { points[i]=new LatLong[coords.getJSONArray(i).length()]; readLineString(points[i], coords.getJSONArray(i)); } return points; } }
package io.mycat.manager.response; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.locks.ReentrantLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import io.mycat.MycatServer; import io.mycat.backend.BackendConnection; import io.mycat.backend.datasource.PhysicalDBNode; import io.mycat.backend.datasource.PhysicalDBPool; import io.mycat.backend.datasource.PhysicalDatasource; import io.mycat.backend.jdbc.JDBCConnection; import io.mycat.backend.mysql.nio.MySQLConnection; import io.mycat.config.ConfigInitializer; import io.mycat.config.ErrorCode; import io.mycat.config.MycatCluster; import io.mycat.config.MycatConfig; import io.mycat.config.model.FirewallConfig; import io.mycat.config.model.SchemaConfig; import io.mycat.config.model.UserConfig; import io.mycat.config.util.DnPropertyUtil; import io.mycat.manager.ManagerConnection; import io.mycat.net.NIOProcessor; import io.mycat.net.mysql.OkPacket; /** * @author mycat * @author zhuam */ public final class ReloadConfig { private static final Logger LOGGER = LoggerFactory.getLogger(ReloadConfig.class); public static void execute(ManagerConnection c, final boolean loadAll) { // reload @@config_all if ( loadAll && !NIOProcessor.backends_old.isEmpty() ) { c.writeErrMessage(ErrorCode.ER_YES, "The are several unfinished db transactions before executing \"reload @@config_all\", therefore the execution is terminated for logical integrity and please try again later."); return; } final ReentrantLock lock = MycatServer.getInstance().getConfig().getLock(); lock.lock(); try { ListenableFuture<Boolean> listenableFuture = MycatServer.getInstance().getListeningExecutorService().submit( new Callable<Boolean>() { @Override public Boolean call() throws Exception { return loadAll ? reload_all() : reload(); } } ); Futures.addCallback(listenableFuture, new ReloadCallBack(c), MycatServer.getInstance().getListeningExecutorService()); } finally { lock.unlock(); } } public static boolean reload_all() { /** * 1 * 1.1ConfigInitializer * 1.2DataNode/DataHost */ ConfigInitializer loader = new ConfigInitializer(true); Map<String, UserConfig> newUsers = loader.getUsers(); Map<String, SchemaConfig> newSchemas = loader.getSchemas(); Map<String, PhysicalDBNode> newDataNodes = loader.getDataNodes(); Map<String, PhysicalDBPool> newDataHosts = loader.getDataHosts(); MycatCluster newCluster = loader.getCluster(); FirewallConfig newFirewall = loader.getFirewall(); loader.testConnection(); /** * 2 * 2.1 dataSource * 2.2 dataSource 2.3 * 2.3 dataSource * 2.4 dataSource * 2.5 dataSource */ MycatConfig config = MycatServer.getInstance().getConfig(); /** * 2.1 dataSource */ boolean isReloadStatusOK = true; /** * 2.2 dataHosts */ for (PhysicalDBPool dbPool : newDataHosts.values()) { String hostName = dbPool.getHostName(); // schemas ArrayList<String> dnSchemas = new ArrayList<String>(30); for (PhysicalDBNode dn : newDataNodes.values()) { if (dn.getDbPool().getHostName().equals(hostName)) { dnSchemas.add(dn.getDatabase()); } } dbPool.setSchemas( dnSchemas.toArray(new String[dnSchemas.size()]) ); // data host String dnIndex = DnPropertyUtil.loadDnIndexProps().getProperty(dbPool.getHostName(), "0"); if ( !"0".equals(dnIndex) ) { LOGGER.info("init datahost: " + dbPool.getHostName() + " to use datasource index:" + dnIndex); } dbPool.init( Integer.valueOf(dnIndex) ); if ( !dbPool.isInitSuccess() ) { isReloadStatusOK = false; break; } } /** * TODO * * dataHosts */ if ( isReloadStatusOK ) { config.reload(newUsers, newSchemas, newDataNodes, newDataHosts, newCluster, newFirewall, true); LOGGER.warn("1clear old backend connection(size): " + NIOProcessor.backends_old.size()); // reload old Cons Iterator<BackendConnection> iter = NIOProcessor.backends_old.iterator(); while( iter.hasNext() ) { BackendConnection con = iter.next(); con.close("clear old datasources"); iter.remove(); } Map<String, PhysicalDBPool> oldDataHosts = config.getBackupDataHosts(); for (PhysicalDBPool dbPool : oldDataHosts.values()) { dbPool.stopHeartbeat(); for (PhysicalDatasource ds : dbPool.getAllDataSources()) { for (NIOProcessor processor : MycatServer.getInstance().getProcessors()) { for (BackendConnection con : processor.getBackends().values()) { if (con instanceof MySQLConnection) { MySQLConnection mysqlCon = (MySQLConnection) con; if ( mysqlCon.getPool() == ds) { NIOProcessor.backends_old.add( con ); } } else if (con instanceof JDBCConnection) { JDBCConnection jdbcCon = (JDBCConnection) con; if (jdbcCon.getPool() == ds) { NIOProcessor.backends_old.add( con ); } } } } } } LOGGER.warn("2to be recycled old backend connection(size): " + NIOProcessor.backends_old.size()); MycatServer.getInstance().getCacheService().clearCache(); return true; } else { LOGGER.warn("reload failed, clear previously created datasources "); for (PhysicalDBPool dbPool : newDataHosts.values()) { dbPool.clearDataSources("reload config"); dbPool.stopHeartbeat(); } return false; } } public static boolean reload() { /** * 1 ConfigInitializer , , dataHost dataNode */ ConfigInitializer loader = new ConfigInitializer(false); Map<String, UserConfig> users = loader.getUsers(); Map<String, SchemaConfig> schemas = loader.getSchemas(); Map<String, PhysicalDBNode> dataNodes = loader.getDataNodes(); Map<String, PhysicalDBPool> dataHosts = loader.getDataHosts(); MycatCluster cluster = loader.getCluster(); FirewallConfig firewall = loader.getFirewall(); MycatServer.getInstance().getConfig().reload(users, schemas, dataNodes, dataHosts, cluster, firewall, false); MycatServer.getInstance().getCacheService().clearCache(); return true; } private static class ReloadCallBack implements FutureCallback<Boolean> { private ManagerConnection mc; private ReloadCallBack(ManagerConnection c) { this.mc = c; } @Override public void onSuccess(Boolean result) { if (result) { LOGGER.warn("send ok package to client " + String.valueOf(mc)); OkPacket ok = new OkPacket(); ok.packetId = 1; ok.affectedRows = 1; ok.serverStatus = 2; ok.message = "Reload config success".getBytes(); ok.write(mc); } else { mc.writeErrMessage(ErrorCode.ER_YES, "Reload config failure"); } } @Override public void onFailure(Throwable t) { mc.writeErrMessage(ErrorCode.ER_YES, "Reload config failure"); } } }
package me.rkfg.xmpp.bot.plugins; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.util.StringUtils; import ru.ppsrk.gwt.client.ClientAuthenticationException; import ru.ppsrk.gwt.client.LogicException; import ru.ppsrk.gwt.shared.SharedUtils; public abstract class CommandPlugin extends MessagePluginImpl { private static final String PREFIX = "%"; @Override public Pattern getPattern() { return Pattern.compile("^" + PREFIX + "(" + SharedUtils.join(getCommand(), "|") + ")( +(.*)|$)"); } @Override public String process(Message message, Matcher matcher) { if (!isMessageFromUser(message)){ return null; } try { return StringUtils.parseResource(message.getFrom()) + ", " + processCommand(message, matcher); } catch (ClientAuthenticationException e) { e.printStackTrace(); } catch (LogicException e) { log.warn("LogicError while processing command: ", e); } return "ошибка обработки команды, подробности в логе."; } public abstract String processCommand(Message message, Matcher matcher) throws ClientAuthenticationException, LogicException; public abstract List<String> getCommand(); }
package edu.kit.ipd.sdq.vitruvius.framework.contracts.datatypes; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.log4j.Logger; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.util.EcoreUtil; import edu.kit.ipd.sdq.vitruvius.framework.contracts.util.bridges.EcoreResourceBridge; import edu.kit.ipd.sdq.vitruvius.framework.contracts.util.datatypes.ClaimableHashMap; import edu.kit.ipd.sdq.vitruvius.framework.contracts.util.datatypes.ClaimableMap; import edu.kit.ipd.sdq.vitruvius.framework.meta.correspondence.Correspondence; import edu.kit.ipd.sdq.vitruvius.framework.meta.correspondence.CorrespondenceFactory; import edu.kit.ipd.sdq.vitruvius.framework.meta.correspondence.Correspondences; import edu.kit.ipd.sdq.vitruvius.framework.meta.correspondence.EFeatureCorrespondence; import edu.kit.ipd.sdq.vitruvius.framework.meta.correspondence.EObjectCorrespondence; import edu.kit.ipd.sdq.vitruvius.framework.meta.correspondence.SameTypeCorrespondence; // TODO move all methods that don't need direct instance variable access to some kind of util class /** * Contains all correspondences for all model instances that conform to the metamodels of a give * mapping. The correspondences do not store any information on metamodels. Only correspondence * instances link to the metamodels. Therefore every elementA of a correspondence has to be an * instance of a metaclass of the first metamodel of the containing correspondence instance. And * every elementB of a correspondence has to be an instance of a metaclass of the second metamodel * of the containing correspondence instance. * * @author kramerm * */ public class CorrespondenceInstance extends ModelInstance { private static final Logger logger = Logger.getLogger(CorrespondenceInstance.class.getSimpleName()); private Mapping mapping; private Correspondences correspondences; private ClaimableMap<String, Set<Correspondence>> tuid2CorrespondencesMap; private ClaimableMap<String, Set<EObject>> tuid2CorrespondingEObjectsMap; private ClaimableMap<FeatureInstance, Set<FeatureInstance>> featureInstance2CorrespondingFIMap; // the following map (tuid2CorrespondenceSetsWithComprisedFeatureInstanceMap) is only used to // correctly update the previous map (featureInstance2CorrespondingFIMap) private ClaimableMap<String, Set<Set<FeatureInstance>>> tuid2CorrespondenceSetsWithComprisedFeatureInstanceMap; private boolean changedAfterLastSave = false; public CorrespondenceInstance(final Mapping mapping, final VURI correspondencesVURI, final Resource correspondencesResource) { super(correspondencesVURI, correspondencesResource); this.mapping = mapping; // TODO implement lazy loading for correspondences because they may get really big EObject correspondences = EcoreResourceBridge.getResourceContentRootIfUnique(correspondencesResource); if (correspondences == null) { this.correspondences = CorrespondenceFactory.eINSTANCE.createCorrespondences(); correspondencesResource.getContents().add(this.correspondences); } else { if (correspondences instanceof Correspondences) { this.correspondences = (Correspondences) correspondences; } else { throw new RuntimeException("The unique root object '" + correspondences + "' of the correspondence model '" + correspondencesVURI + "' is not correctly typed!"); } } // FIXME implement loading of existing correspondences from resources (fill maps) // FIXME create TUIDs during loading of existing corresponding from resource this.tuid2CorrespondencesMap = new ClaimableHashMap<String, Set<Correspondence>>(); this.tuid2CorrespondingEObjectsMap = new ClaimableHashMap<String, Set<EObject>>(); this.featureInstance2CorrespondingFIMap = new ClaimableHashMap<FeatureInstance, Set<FeatureInstance>>(); this.tuid2CorrespondenceSetsWithComprisedFeatureInstanceMap = new ClaimableHashMap<String, Set<Set<FeatureInstance>>>(); } public Mapping getMapping() { return this.mapping; } /** * Returns whether at least one object corresponds to the given object. * * @param eObject * the object for which correspondences should be looked up * @return # of corresponding objects > 0 */ public boolean hasCorrespondences(final EObject eObject) { String tuid = getTUIDFromEObject(eObject); Set<Correspondence> correspondences = this.tuid2CorrespondencesMap.get(tuid); return correspondences != null && correspondences.size() > 0; } /** * Returns the correspondences for the specified object and throws a * {@link java.lang.RuntimeException} if no correspondence exists. * * @param eObject * the object for which correspondences are to be returned * @return the correspondences for the specified object */ public Set<Correspondence> claimCorrespondences(final EObject eObject) { String tuid = getTUIDFromEObject(eObject); return claimCorrespondeceSetNotEmpty(eObject, tuid); } private Set<Correspondence> claimCorrespondeceSetNotEmpty(final EObject eObject, final String tuid) { Set<Correspondence> correspondences = this.tuid2CorrespondencesMap.claimValueForKey(tuid); return claimCorrespondeceSetNotEmpty(eObject, tuid, correspondences); } private <T> Set<T> claimCorrespondeceSetNotEmpty(final EObject eObject, final String tuid, final Set<T> correspondences) { if (correspondences.size() > 0) { return correspondences; } else { throw new RuntimeException("The eObject '" + eObject + "' is only mapped to an empty correspondence set: '" + correspondences + "'!"); } } /** * Returns all correspondences for the specified object and an empty set if the object has no * correspondences. Should never return {@link null}. * * @param eObject * @return all correspondences for the specified object and an empty set if the object has no * correspondences. */ public Set<Correspondence> getAllCorrespondences(final EObject eObject) { String tuid = getTUIDFromEObject(eObject); return getOrCreateCorrespondenceSet(tuid); } private Set<Correspondence> getOrCreateCorrespondenceSet(final String involvedTUID) { Set<Correspondence> correspondences = this.tuid2CorrespondencesMap.get(involvedTUID); if (correspondences == null) { correspondences = new HashSet<Correspondence>(); this.tuid2CorrespondencesMap.put(involvedTUID, correspondences); } return correspondences; } /** * Returns the corresponding objects for the specified object and throws a * {@link java.lang.RuntimeException} if no correspondence exists. * * @param eObject * the object for which corresponding objects are to be returned * @return the corresponding objects for the specified object */ public Set<EObject> claimCorrespondingEObjects(final EObject eObject) { String tuid = getTUIDFromEObject(eObject); Set<EObject> correspondingEObjects = this.tuid2CorrespondingEObjectsMap.claimValueForKey(tuid); return claimCorrespondeceSetNotEmpty(eObject, tuid, correspondingEObjects); } /** * Returns all corresponding objects for the specified object and an empty set if the object has * no correspondences. Should never return {@link null}. * * @param eObject * the object for which corresponding objects are to be returned * @return all corresponding objects for the specified object and an empty set if the object has * no correspondences. */ public Set<EObject> getAllCorrespondingEObjects(final EObject eObject) { String tuid = getTUIDFromEObject(eObject); return getOrCreateCorrespondingEObjectsSet(tuid); } private Set<EObject> getOrCreateCorrespondingEObjectsSet(final String tuid) { Set<EObject> correspondingEObjects = this.tuid2CorrespondingEObjectsMap.get(tuid); if (correspondingEObjects == null) { correspondingEObjects = new HashSet<EObject>(); this.tuid2CorrespondingEObjectsMap.put(tuid, correspondingEObjects); } return correspondingEObjects; } /** * Returns the corresponding object for the specified object if there is exactly one * corresponding object and throws a {@link java.lang.RuntimeException} otherwise. * * @param eObject * the object for which the corresponding object is to be returned * @return the corresponding object for the specified object if there is exactly one * corresponding object */ public EObject claimUniqueCorrespondingEObject(final EObject eObject) { Set<EObject> correspondingEObjects = claimCorrespondingEObjects(eObject); if (correspondingEObjects.size() != 1) { throw new RuntimeException("The eObjects corresponding to '" + eObject + "' are not unique: " + correspondingEObjects); } return correspondingEObjects.iterator().next(); } /** * Returns the corresponding objects of the specified type for the specified object and throws a * {@link java.lang.RuntimeException} if no correspondences of this type exist. * * @param eObject * the object for which corresponding objects are to be returned * @param type * the class of which instances are to be returned * @return the corresponding objects of the specified type for the specified object */ public <T> Set<T> claimCorrespondingEObjectsByType(final EObject eObject, final Class<T> type) { Set<EObject> correspondingEObjects = claimCorrespondingEObjects(eObject); Set<T> correspondingEObjectsByType = new HashSet<T>(); for (EObject correspondingEObject : correspondingEObjects) { if (type.isInstance(correspondingEObject)) { correspondingEObjectsByType.add(type.cast(correspondingEObject)); } } if (correspondingEObjectsByType.size() == 0) { throw new RuntimeException("There are no eObjects of type '" + type + "' that correspond to the eObject '" + eObject + "!"); } return correspondingEObjectsByType; } /** * Returns the corresponding object of the specified type for the specified object if there is * exactly one corresponding object of this type and throws a {@link java.lang.RuntimeException} * otherwise. * * @param eObject * the object for which the corresponding object is to be returned * @param type * the class of which an instance is to be returned * @return the corresponding object of the specified type for the specified object if there is * exactly one corresponding object of this type */ public <T> T claimUniqueCorrespondingEObjectByType(final EObject eObject, final Class<T> type) { Set<T> correspondingEObjectsByType = claimCorrespondingEObjectsByType(eObject, type); if (1 != correspondingEObjectsByType.size()) { throw new RuntimeException("claimCorrespondingEObjectForTypeIfUnique failed: " + correspondingEObjectsByType.size() + " corresponding objects found (expected 1)" + correspondingEObjectsByType); } return correspondingEObjectsByType.iterator().next(); } /** * Returns the correspondence for the given eObject if it is unique, or null if no * correspondence exists and throws a {@link RuntimeException} if more than one correspondence * exists. * * @param eObject * the object for which the correspondence is to be returned * @return the correspondence for the given eObject if it is unique, or null if no * correspondence exists */ public Correspondence claimUniqueOrNullCorrespondenceForEObject(final EObject eObject) { if (!hasCorrespondences(eObject)) { return null; } return claimUniqueCorrespondence(eObject); } /** * Returns the correspondence for the given eObject if it is unique and throws a * {@link RuntimeException} if there is not exactly one corresponding object. * * @param eObject * the object for which the correspondence is to be returned * @return the correspondence for the given eObject if there is exactly one corresponding object */ public Correspondence claimUniqueCorrespondence(final EObject eObject) { Set<Correspondence> objectCorrespondences = claimCorrespondences(eObject); if (objectCorrespondences.size() != 1) { throw new RuntimeException("The correspondence for eObject '" + eObject + "' is not unique: " + objectCorrespondences); } return objectCorrespondences.iterator().next(); } /** * Returns all eObjects that have some correspondence and are an instance of the given class. * * @param type * the class for which instances should be returned * @return a set containing all eObjects of the given type that have a correspondence */ public <T> Set<T> getAllEObjectsInCorrespondencesWithType(final Class<T> type) { Set<T> correspondencesWithType = new HashSet<T>(); for (Correspondence correspondence : this.correspondences.getCorrespondences()) { if (correspondence instanceof EObjectCorrespondence) { EObjectCorrespondence eObjectCorrespondence = (EObjectCorrespondence) correspondence; if (type.isInstance(eObjectCorrespondence.getElementA())) { @SuppressWarnings("unchecked") T t = (T) eObjectCorrespondence.getElementA(); correspondencesWithType.add(t); } else if (type.isInstance(eObjectCorrespondence.getElementB())) { @SuppressWarnings("unchecked") T t = (T) eObjectCorrespondence.getElementB(); correspondencesWithType.add(t); } } } return correspondencesWithType; } public void addSameTypeCorrespondence(final SameTypeCorrespondence correspondence) { addSameTypeCorrespondence(correspondence, null); } public void addSameTypeCorrespondence(final SameTypeCorrespondence correspondence, final Correspondence parent) { EObject elementA = correspondence.getElementA(); EObject elementB = correspondence.getElementB(); // add TUIDs String tuidA = this.mapping.getMetamodelA().getTUID(elementA); String tuidB = this.mapping.getMetamodelB().getTUID(elementB); correspondence.setElementATUID(tuidA); correspondence.setElementBTUID(tuidB); // add correspondence to model EList<Correspondence> correspondenceListForAddition; if (parent == null) { correspondenceListForAddition = this.correspondences.getCorrespondences(); } else { correspondenceListForAddition = parent.getDependentCorrespondences(); } correspondenceListForAddition.add(correspondence); List<EObject> allInvolvedEObjects = Arrays.asList(elementA, elementB); List<String> allInvolvedTUIDs = Arrays.asList(tuidA, tuidB); // add all involved eObjects to the sets for these objects in the map for (String involvedTUID : allInvolvedTUIDs) { Set<Correspondence> correspondences = getOrCreateCorrespondenceSet(involvedTUID); if (!correspondences.contains(correspondence)) { correspondences.add(correspondence); } } if (correspondence instanceof EObjectCorrespondence) { for (String involvedTUID : allInvolvedTUIDs) { Set<EObject> correspondingEObjects = getOrCreateCorrespondingEObjectsSet(involvedTUID); correspondingEObjects.addAll(allInvolvedEObjects); if (involvedTUID.equals(tuidA)) { correspondingEObjects.remove(elementA); } else if (involvedTUID.equals(tuidB)) { correspondingEObjects.remove(elementB); } else { throw new RuntimeException("allInvolvedEObjects ('" + allInvolvedEObjects + "' contained a TUID that is neither '" + tuidA + "' nor '" + tuidB + "'!"); } } } else if (correspondence instanceof EFeatureCorrespondence) { EFeatureCorrespondence<?> featureCorrespondence = (EFeatureCorrespondence<?>) correspondence; FeatureInstance featureInstanceA = FeatureInstance.getInstance(featureCorrespondence.getElementA(), featureCorrespondence.getFeatureA()); FeatureInstance featureInstanceB = FeatureInstance.getInstance(featureCorrespondence.getElementB(), featureCorrespondence.getFeatureB()); Set<FeatureInstance> featureInstancesCorrespondingToFIA = this.featureInstance2CorrespondingFIMap .get(featureInstanceA); if (featureInstancesCorrespondingToFIA == null) { featureInstancesCorrespondingToFIA = new HashSet<FeatureInstance>(); this.featureInstance2CorrespondingFIMap.put(featureInstanceA, featureInstancesCorrespondingToFIA); } featureInstancesCorrespondingToFIA.add(featureInstanceB); storeFeatureInstancesForTUID(tuidB, featureInstancesCorrespondingToFIA); Set<FeatureInstance> featureInstancesCorrespondingToFIB = this.featureInstance2CorrespondingFIMap .get(featureInstanceB); if (featureInstancesCorrespondingToFIB == null) { featureInstancesCorrespondingToFIB = new HashSet<FeatureInstance>(); this.featureInstance2CorrespondingFIMap.put(featureInstanceB, featureInstancesCorrespondingToFIB); } featureInstancesCorrespondingToFIB.add(featureInstanceA); // store the usage of a feature instance with a parent object that has the tuid tuidA storeFeatureInstancesForTUID(tuidA, featureInstancesCorrespondingToFIB); } setChangeAfterLastSaveFlag(); } private void setChangeAfterLastSaveFlag() { this.changedAfterLastSave = true; } public boolean changedAfterLastSave() { return this.changedAfterLastSave; } public void resetChangedAfterLastSave() { this.changedAfterLastSave = false; } private void storeFeatureInstancesForTUID(final String tuid, final Set<FeatureInstance> correspondenceSetWithFIofTUID) { Set<Set<FeatureInstance>> correspondeceSetsWithFIsOfTUID = this.tuid2CorrespondenceSetsWithComprisedFeatureInstanceMap .get(tuid); if (correspondeceSetsWithFIsOfTUID == null) { correspondeceSetsWithFIsOfTUID = new HashSet<Set<FeatureInstance>>(); this.tuid2CorrespondenceSetsWithComprisedFeatureInstanceMap.put(tuid, correspondeceSetsWithFIsOfTUID); } correspondeceSetsWithFIsOfTUID.add(correspondenceSetWithFIofTUID); } /** * Removes all correspondences for the given eObject and all child-correspondences of these * correspondences. * * @param eObject * from which all correspondences should be removed */ public void removeAllCorrespondences(final EObject eObject) { // TODO: Check if it is working String tuid = getTUIDFromEObject(eObject); Set<Correspondence> correspondencesForEObj = this.tuid2CorrespondencesMap.get(tuid); if (null == correspondencesForEObj) { return; } this.tuid2CorrespondencesMap.remove(tuid); for (Correspondence correspondence : correspondencesForEObj) { removeCorrespondenceAndAllDependentCorrespondences(correspondence); } // FIXME: remove feature correspondences } /** * Removes correspondence and all child Correspondences of this correspondence * * @param correspondence */ public void removeCorrespondenceAndAllDependentCorrespondences(final Correspondence correspondence) { Set<Correspondence> dependencyList = new HashSet<Correspondence>(); removeCorrespondenceAndAllDependentCorrespondences(correspondence, dependencyList); } /** * Does the removing recursively. Marks all correspondences that will be deleted in a * dependencyList --> Avoid stack overflow with correspondences that have a mutual dependency * * @param correspondence * @param dependencyList */ private void removeCorrespondenceAndAllDependentCorrespondences(final Correspondence correspondence, final Set<Correspondence> dependencyList) { if (null == correspondence || null == correspondence.getDependentCorrespondences()) { return; } dependencyList.add(correspondence); for (Correspondence dependentCorrespondence : correspondence.getDependentCorrespondences()) { if (null != dependentCorrespondence && !dependencyList.contains(dependentCorrespondence)) { removeCorrespondenceFromMaps(dependentCorrespondence); removeCorrespondenceAndAllDependentCorrespondences(dependentCorrespondence, dependencyList); } } removeCorrespondenceFromMaps(correspondence); EcoreUtil.remove(correspondence); setChangeAfterLastSaveFlag(); } private void removeCorrespondenceFromMaps(final Correspondence possibleChildCorrespondence) { if (possibleChildCorrespondence instanceof EObjectCorrespondence) { EObjectCorrespondence eObjCorrespondence = (EObjectCorrespondence) possibleChildCorrespondence; String elementATUID = getTUIDFromEObject(eObjCorrespondence.getElementA()); String elementBTUID = getTUIDFromEObject(eObjCorrespondence.getElementB()); this.tuid2CorrespondencesMap.remove(elementATUID); this.tuid2CorrespondencesMap.remove(elementBTUID); this.tuid2CorrespondingEObjectsMap.remove(elementATUID); this.tuid2CorrespondingEObjectsMap.remove(elementBTUID); } } public Set<FeatureInstance> getAllCorrespondingFeatureInstances(final EObject parentEObject, final EStructuralFeature feature) { FeatureInstance featureInstance = FeatureInstance.getInstance(parentEObject, feature); return getAllCorrespondingFeatureInstances(featureInstance); } public Set<FeatureInstance> getAllCorrespondingFeatureInstances(final FeatureInstance featureInstance) { return this.featureInstance2CorrespondingFIMap.get(featureInstance); } public Set<FeatureInstance> claimCorrespondingFeatureInstances(final FeatureInstance featureInstance) { return this.featureInstance2CorrespondingFIMap.claimValueForKey(featureInstance); } public FeatureInstance claimUniqueCorrespondingFeatureInstance(final FeatureInstance featureInstance) { Set<FeatureInstance> featureInstances = claimCorrespondingFeatureInstances(featureInstance); if (featureInstances.size() != 1) { throw new RuntimeException("The feature instance corresponding to '" + featureInstance + "' is not unique: " + featureInstances); } return featureInstances.iterator().next(); } private String getTUIDFromEObject(final EObject eObject) { if (this.mapping.getMetamodelA().hasMetaclassInstance(eObject)) { return this.mapping.getMetamodelA().getTUID(eObject); } if (this.mapping.getMetamodelB().hasMetaclassInstance(eObject)) { return this.mapping.getMetamodelB().getTUID(eObject); } logger.warn("EObject: '" + eObject + "' is neither an instance of MM1 nor an instance of MM2. NsURI of object: " + eObject.eClass().getEPackage().getNsURI()); return null; } public void update(final EObject oldEObject, final EObject newEObject) { String oldTUID = getTUIDFromEObject(oldEObject); String newTUID = getTUIDFromEObject(newEObject); boolean sameTUID = oldTUID != null ? oldTUID.equals(newTUID) : newTUID == null; updateTUID2CorrespondencesMap(oldEObject, newEObject, oldTUID, newTUID, sameTUID); updateTUID2CorrespondingEObjectsMap(oldTUID, newTUID, sameTUID); updateFeatureInstances(oldEObject, newEObject, oldTUID); } private void updateFeatureInstances(final EObject oldEObject, final EObject newEObject, final String oldTUID) { Collection<FeatureInstance> oldFeatureInstances = FeatureInstance.getAllInstances(oldEObject); // WARNING: We assume that everybody that uses the FeatureInstance multiton wants to be // informed of this update FeatureInstance.update(oldEObject, newEObject); for (FeatureInstance oldFeatureInstance : oldFeatureInstances) { Set<FeatureInstance> correspondingFeatureInstances = this.featureInstance2CorrespondingFIMap .remove(oldFeatureInstance); if (correspondingFeatureInstances != null) { EStructuralFeature feature = oldFeatureInstance.getFeature(); FeatureInstance newFeatureInstance = FeatureInstance.getInstance(newEObject, feature); this.featureInstance2CorrespondingFIMap.put(newFeatureInstance, correspondingFeatureInstances); } } Set<Set<FeatureInstance>> correspondenceSetsWithFIofOldTUID = this.tuid2CorrespondenceSetsWithComprisedFeatureInstanceMap .get(oldTUID); for (Set<FeatureInstance> correspondenceSetWithFIofOldTUID : correspondenceSetsWithFIofOldTUID) { for (FeatureInstance featureInstance : correspondenceSetWithFIofOldTUID) { if (oldFeatureInstances.contains(featureInstance)) { // featureInstance belongs to oldTUID correspondenceSetWithFIofOldTUID.remove(featureInstance); EStructuralFeature feature = featureInstance.getFeature(); FeatureInstance newFeatureInstance = FeatureInstance.getInstance(newEObject, feature); correspondenceSetWithFIofOldTUID.add(newFeatureInstance); } } } setChangeAfterLastSaveFlag(); } private void updateTUID2CorrespondingEObjectsMap(final String oldTUID, final String newTUID, final boolean sameTUID) { if (!sameTUID) { Set<EObject> correspondingEObjects = this.tuid2CorrespondingEObjectsMap.remove(oldTUID); this.tuid2CorrespondingEObjectsMap.put(newTUID, correspondingEObjects); } } private void updateTUID2CorrespondencesMap(final EObject oldEObject, final EObject newEObject, final String oldTUID, final String newTUID, final boolean sameTUID) { Set<Correspondence> correspondences = this.tuid2CorrespondencesMap.get(oldTUID); for (Correspondence correspondence : correspondences) { if (correspondence instanceof SameTypeCorrespondence) { SameTypeCorrespondence stc = (SameTypeCorrespondence) correspondence; if (oldTUID != null && oldTUID.equals(stc.getElementATUID())) { stc.setElementA(newEObject); if (!sameTUID) { stc.setElementATUID(newTUID); } // update incoming links in tuid2CorrespondingEObjectsMap String elementBTUID = stc.getElementBTUID(); updateCorrespondingLinksForUpdatedEObject(oldEObject, newEObject, oldTUID, elementBTUID); } else if (oldTUID != null && oldTUID.equals(stc.getElementBTUID())) { stc.setElementB(newEObject); if (!sameTUID) { stc.setElementBTUID(newTUID); } // update incoming links in tuid2CorrespondingEObjectsMap String elementATUID = stc.getElementATUID(); updateCorrespondingLinksForUpdatedEObject(oldEObject, newEObject, oldTUID, elementATUID); } else { throw new RuntimeException("None of the corresponding elements in '" + correspondence + "' has the TUID '" + oldTUID + "'!"); } if (!sameTUID) { this.tuid2CorrespondencesMap.remove(oldTUID); this.tuid2CorrespondencesMap.put(newTUID, correspondences); } } // TODO handle not same type correspondence case } } private void updateCorrespondingLinksForUpdatedEObject(final EObject oldEObject, final EObject newEObject, final String oldTUID, final String elementBTUID) { Set<EObject> correspondingEObjects = this.tuid2CorrespondingEObjectsMap.get(elementBTUID); for (EObject correspondingEObject : correspondingEObjects) { String correspondingTUID = getTUIDFromEObject(correspondingEObject); if (correspondingTUID != null && correspondingTUID.equals(oldTUID)) { correspondingEObjects.remove(oldEObject); correspondingEObjects.add(newEObject); } } } }
package net.cryptonomica.servlets; import com.google.gson.Gson; import org.apache.commons.io.IOUtils; import org.json.HTTP; import org.json.JSONException; import org.json.JSONObject; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import java.util.logging.Logger; /** * Utilities to use in servlets */ public class ServletUtils { /* ---- Logger: */ private static final Logger LOG = Logger.getLogger(ServletUtils.class.getName()); /* --- Gson: */ private static Gson GSON = new Gson(); public static JSONObject getJsonObjectFromRequest(HttpServletRequest request) throws IOException { StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { throw new IOException(e.getMessage()); } JSONObject jsonObject = null; try { jsonObject = HTTP.toJSONObject(jb.toString()); LOG.warning("jsonObject:"); LOG.warning(jsonObject.toString()); for (String key : jsonObject.keySet()) { LOG.warning(key); LOG.warning(jsonObject.get(key).getClass().getName()); LOG.warning(jsonObject.get(key).toString()); } } catch (JSONException e) { throw new IOException("Error parsing JSON request string"); } // Work with the data using methods like... // int someInt = jsonObject.getInt("intParamName"); // String someString = jsonObject.getString("stringParamName"); // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName"); // JSONArray arr = jsonObject.getJSONArray("arrayParamName"); // etc... return jsonObject; } public static JSONObject getJsonObjectFromRequestWithIOUtils(HttpServletRequest request) throws IOException { String jsonString = IOUtils.toString(request.getInputStream()); JSONObject jsonObject = new JSONObject(jsonString); LOG.warning("jsonObject"); LOG.warning(jsonObject.toString()); // JSONObject messageJsonObject = jsonObject.getJSONObject("message"); // LOG.warning("messageJsonObject:"); // LOG.warning(messageJsonObject.toString()); // String messageTextStr = messageJsonObject.getString("text"); // LOG.warning("messageTextStr: " + messageTextStr); // LOG.warning("jsonObject:"); // LOG.warning(jsonObject.toString()); for (String key : jsonObject.keySet()) { LOG.warning(key); LOG.warning(jsonObject.get(key).getClass().getName()); LOG.warning(jsonObject.get(key).toString()); } return jsonObject; } public static String getRequestParameters(HttpServletRequest request) { String result = "{"; Enumeration<String> enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { String parametername = enumeration.nextElement(); result += "\"" + parametername + "\":\"" + request.getParameter(parametername) + "\","; } result = removeLastComma(result) + "}"; // LOG.warning(result); return result; } // end of getRequestParameters() public static String getCookies(HttpServletRequest request) { String result = "["; Cookie[] cookies = request.getCookies(); if (cookies == null) { result += ""; } else { for (Cookie cookie : cookies) { result += "{" + "\"name\": \"" + cookie.getName() + "\"," + "\"value\": \"" + cookie.getValue() + "\"," + "\"domain\": \"" + cookie.getDomain() + "\"," + "\"path\": \"" + cookie.getPath() + "\"," + "\"comment\": \"" + cookie.getComment() + "},"; } result = removeLastComma(result); } result += "]"; // LOG.warning(result); return result; } // end of getCookies() public static String getRequestHeaders(HttpServletRequest request) { String result = "{"; Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); result += "\"" + headerName + "\":\"" + request.getHeader(headerName) + "\","; } result = removeLastComma(result) + "}"; // LOG.warning(result); return result; } // end of getRequestHeaderNames() public static String getAllRequestData(HttpServletRequest request) { String headerNamesStr = ServletUtils.getRequestHeaders(request); String requestParametersStr = ServletUtils.getRequestParameters(request); String cookiesStr = ServletUtils.getCookies(request); String requestDataSrt = "{\"request\": " + "{" + "\"requestHeaders\": " + headerNamesStr + "," + "\"requestParameters\": " + requestParametersStr + "," + "\"cookies\":" + cookiesStr + "}" + "}"; return requestDataSrt; } public static void sendTxtResponse(HttpServletResponse response, final String text) throws IOException { response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); PrintWriter pw = response.getWriter(); //get the stream to write the data pw.println(text); pw.close(); //closing the stream } // end of sendTxtResponse() public static void sendJsonResponse(HttpServletResponse response, final String jsonStr) throws IOException { response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter pw = response.getWriter(); //get the stream to write the data pw.println(jsonStr); pw.close(); //closing the stream } // end of sendJsonResponse() public static String removeLastComma(String str) { int commaIndex = str.lastIndexOf(","); // -1 if there is no such occurrence. if (commaIndex > 0 && commaIndex == str.length() - 1) { str = str.substring(0, commaIndex); } return str; } public static String getUrlKey(HttpServletRequest request) { // https://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#getRequestURI-- String requestURI = request.getRequestURI(); LOG.warning("request.getRequestURI(): " + request.getRequestURI()); String urlKey = requestURI.substring(requestURI.lastIndexOf('/') + 1); return urlKey; } }
package net.darkhax.bookshelf.util; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.vertex.IVertexBuilder; import net.minecraft.block.Block; import net.minecraft.block.BlockState; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.BlockModelRenderer; import net.minecraft.client.renderer.BlockRendererDispatcher; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.RenderState; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.RenderTypeLookup; import net.minecraft.client.renderer.WorldRenderer; import net.minecraft.client.renderer.model.BakedQuad; import net.minecraft.client.renderer.model.IBakedModel; import net.minecraft.client.renderer.model.ModelResourceLocation; import net.minecraft.client.renderer.texture.OverlayTexture; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.crash.ReportedException; import net.minecraft.fluid.Fluid; import net.minecraft.fluid.FluidState; import net.minecraft.inventory.container.PlayerContainer; import net.minecraft.item.ItemStack; import net.minecraft.util.Direction; import net.minecraft.util.IReorderingProcessor; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.vector.Matrix4f; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.IBlockDisplayReader; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.client.model.data.EmptyModelData; import net.minecraftforge.client.model.data.IModelData; @OnlyIn(Dist.CLIENT) public final class RenderUtils { private static final Random RANDOM = new Random(); private static final BitSet BITS = new BitSet(3); /** * Gets the particle texture for an item stack. * * @param stack The item to get the particle texture of. * @return The particle texture for the item stack. */ public static TextureAtlasSprite getParticleSprite (ItemStack stack) { return Minecraft.getInstance().getItemRenderer().getItemModelMesher().getItemModel(stack).getParticleTexture(); } /** * Gets the particle sprite for a block with world context. * * @param state The state to get the particle texture of. * @param world The world the block is in. * @param pos The position of the block. * @return The particle texture for the block state. */ public TextureAtlasSprite getParticleSprite (BlockState state, World world, BlockPos pos) { return Minecraft.getInstance().getBlockRendererDispatcher().getBlockModelShapes().getTexture(state, world, pos); } /** * Gets the particle texture for a block state. * * @param state The state to get the particle texture of. * @return The particle texture for the block state. */ public static TextureAtlasSprite getParticleSprite (BlockState state) { return Minecraft.getInstance().getBlockRendererDispatcher().getBlockModelShapes().getTexture(state); } /** * Gets a model by it's location name. * * @param name The model location name. * @return The associated model. */ public static IBakedModel getModel (ModelResourceLocation name) { return Minecraft.getInstance().getBlockRendererDispatcher().getBlockModelShapes().getModelManager().getModel(name); } /** * Gets a model for an item stack. * * @param stack The stack to get the model for. * @return The model for the stack. */ public static IBakedModel getModel (ItemStack stack) { return Minecraft.getInstance().getItemRenderer().getItemModelMesher().getItemModel(stack); } /** * Gets a model for a block state. * * @param state The state to get the model for. * @return The model for the state. */ public static IBakedModel getModel (BlockState state) { return Minecraft.getInstance().getBlockRendererDispatcher().getModelForState(state); } /** * Renders a block model. Allows the sites rendered to be specifically controlled by the * caller. * * @param renderer The block model renderer instance. * @param world The world instance. * @param model The model to render. * @param state The state of the block. * @param pos The position of the block. * @param matrix The render matrix. * @param buffer The render buffer. * @param sides The sides of the model to render. */ public static void renderModel (BlockModelRenderer renderer, IBlockDisplayReader world, IBakedModel model, BlockState state, BlockPos pos, MatrixStack matrix, IVertexBuilder buffer, Direction[] sides) { final IModelData modelData = model.getModelData(world, pos, state, EmptyModelData.INSTANCE); // Renders only the sided model quads. for (final Direction side : sides) { RANDOM.setSeed(0L); final List<BakedQuad> sidedQuads = model.getQuads(state, side, RANDOM, modelData); if (!sidedQuads.isEmpty()) { final int lightForSide = WorldRenderer.getPackedLightmapCoords(world, state, pos.offset(side)); renderer.renderQuadsFlat(world, state, pos, lightForSide, OverlayTexture.NO_OVERLAY, false, matrix, buffer, sidedQuads, BITS); } } // Renders the non-sided model quads. RANDOM.setSeed(0L); final List<BakedQuad> unsidedQuads = model.getQuads(state, null, RANDOM, modelData); if (!unsidedQuads.isEmpty()) { renderer.renderQuadsFlat(world, state, pos, -1, OverlayTexture.NO_OVERLAY, true, matrix, buffer, unsidedQuads, BITS); } } /** * Directly get the name of a render state such as a RenderType. This field is normally * private and has been made accessible through access transformers. This method is * required for use in dev environments. * * @param state The state to get the name of. * @return The name of the state. */ public static String getName (RenderState state) { return state.name; } /** * A cache of render types lazily generated by queries to * {@link #getRenderType(BlockState)}. The vanilla maps don't support modded blocks and are * deprecated. */ private static final Map<Block, RenderType> RENDER_TYPES = new HashMap<>(); /** * Gets a RenderType for a given block. * * @param state The block to get the type of. * @return The RenderType for the block. */ public static RenderType getRenderType (BlockState state) { return RENDER_TYPES.computeIfAbsent(state.getBlock(), k -> findRenderType(state)); } /** * Finds a valid RenderType for a block. This is done by testing all the block types and * returning the first valid match. * * @param state The block to get the type of. * @return The RenderType for the block. */ public static RenderType findRenderType (BlockState state) { for (final RenderType blockType : RenderType.getBlockRenderTypes()) { if (RenderTypeLookup.canRenderInLayer(state, blockType)) { return blockType; } } return RenderTypeLookup.func_239221_b_(state); } /** * Renders a block state into the world. * * @param state The state to render. * @param world The world context to render into. * @param pos The position of the block. * @param matrix The render matrix. * @param buffer The render buffer. * @param preferredSides The sides to render, allows faces to be culled. Will be ignored if * Optifine is installed. * @deprecated Use water logging version below. */ @Deprecated public static void renderState (BlockState state, World world, BlockPos pos, MatrixStack matrix, IRenderTypeBuffer buffer, Direction[] preferredSides) { if (!ModUtils.isOptifineLoaded()) { renderBlock(state, world, pos, matrix, buffer, preferredSides); } else { renderBlock(state, world, pos, matrix, buffer); } } /** * Renders a block state into the world. * * @param state The state to render. * @param world The world context to render into. * @param pos The position of the block. * @param matrix The render matrix. * @param buffer The render buffer. * @param preferredSides The sides to render, allows faces to be culled. Will be ignored if * Optifine is installed. * @param withFluid Should fluid states also be rendered? */ public static void renderState (BlockState state, World world, BlockPos pos, MatrixStack matrix, IRenderTypeBuffer buffer, int light, int overlay, boolean withFluid, Direction... preferredSides) { if (!ModUtils.isOptifineLoaded()) { renderBlock(state, world, pos, matrix, buffer, preferredSides); } else { renderBlock(state, world, pos, matrix, buffer); } if (withFluid) { // Handle fluids and waterlogging. final FluidState fluidState = state.getFluidState(); if (fluidState != null && !fluidState.isEmpty()) { final Fluid fluid = fluidState.getFluid(); final ResourceLocation texture = fluid.getAttributes().getStillTexture(); final int[] color = unpackColor(fluid.getAttributes().getColor(world, pos)); final TextureAtlasSprite sprite = Minecraft.getInstance().getAtlasSpriteGetter(PlayerContainer.LOCATION_BLOCKS_TEXTURE).apply(texture); renderBlockSprite(buffer.getBuffer(RenderType.getTranslucent()), matrix, sprite, light, overlay, color); } } } /** * Renders a block state into the world. * * @param state The state to render. * @param world The world context to render into. * @param pos The position of the block. * @param matrix The render matrix. * @param buffer The render buffer. * @param preferredSides The sides to render, allows faces to be culled. */ private static void renderBlock (BlockState state, World world, BlockPos pos, MatrixStack matrix, IRenderTypeBuffer buffer, Direction[] renderSides) { final BlockRendererDispatcher dispatcher = Minecraft.getInstance().getBlockRendererDispatcher(); final IBakedModel model = dispatcher.getModelForState(state); final RenderType type = RenderUtils.findRenderType(state); if (type != null) { ForgeHooksClient.setRenderLayer(type); final IVertexBuilder builder = buffer.getBuffer(type); RenderUtils.renderModel(dispatcher.getBlockModelRenderer(), world, model, state, pos, matrix, builder, renderSides); ForgeHooksClient.setRenderLayer(null); } } /** * Renders a block state into the world. This only exists for optifine compatibility mode. * * @param state The state to render. * @param world The world context to render into. * @param pos The position of the block. * @param matrix The render matrix. * @param buffer The render buffer. */ private static void renderBlock (BlockState state, World world, BlockPos pos, MatrixStack matrix, IRenderTypeBuffer buffer) { final BlockRendererDispatcher dispatcher = Minecraft.getInstance().getBlockRendererDispatcher(); final IBakedModel model = dispatcher.getModelForState(state); final boolean useAO = Minecraft.isAmbientOcclusionEnabled() && state.getLightValue(world, pos) == 0 && model.isAmbientOcclusion(); final RenderType type = RenderUtils.findRenderType(state); if (type != null) { ForgeHooksClient.setRenderLayer(type); final IVertexBuilder builder = buffer.getBuffer(type); renderModel(dispatcher.getBlockModelRenderer(), useAO, world, model, state, pos, matrix, builder, false, OverlayTexture.NO_OVERLAY); ForgeHooksClient.setRenderLayer(null); } } /** * This only exists for optifine compatibility mode. */ private static boolean renderModel (BlockModelRenderer renderer, boolean useAO, IBlockDisplayReader world, IBakedModel model, BlockState state, BlockPos pos, MatrixStack matrix, IVertexBuilder buffer, boolean checkSides, int overlay) { try { final IModelData modelData = model.getModelData(world, pos, state, EmptyModelData.INSTANCE); return useAO ? renderer.renderModelSmooth(world, model, state, pos, matrix, buffer, checkSides, RANDOM, 0L, overlay, modelData) : renderer.renderModelFlat(world, model, state, pos, matrix, buffer, checkSides, RANDOM, 0L, overlay, modelData); } catch (final Throwable throwable) { final CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Tesselating block model"); final CrashReportCategory crashreportcategory = crashreport.makeCategory("Block model being tesselated"); CrashReportCategory.addBlockInfo(crashreportcategory, pos, state); crashreportcategory.addDetail("Using AO", useAO); throw new ReportedException(crashreport); } } public static void renderLinesWrapped (MatrixStack matrix, int x, int y, ITextComponent text, int textWidth) { final FontRenderer font = Minecraft.getInstance().fontRenderer; renderLinesWrapped(matrix, font, x, y, font.FONT_HEIGHT, 0, text, textWidth); } public static void renderLinesWrapped (MatrixStack matrix, FontRenderer fontRenderer, int x, int y, int spacing, int defaultColor, ITextComponent text, int textWidth) { // trimStringToWidth is actually wrapToWidth renderLinesWrapped(matrix, fontRenderer, x, y, spacing, defaultColor, fontRenderer.trimStringToWidth(text, textWidth)); } public static void renderLinesWrapped (MatrixStack matrix, FontRenderer fontRenderer, int x, int y, int spacing, int defaultColor, List<IReorderingProcessor> lines) { for (int lineNum = 0; lineNum < lines.size(); lineNum++) { final IReorderingProcessor lineFragment = lines.get(lineNum); fontRenderer.func_238422_b_(matrix, lineFragment, x, y + lineNum * spacing, defaultColor); } } public static int renderLinesReversed (MatrixStack matrix, int x, int y, ITextComponent text, int textWidth) { final FontRenderer font = Minecraft.getInstance().fontRenderer; return renderLinesReversed(matrix, font, x, y, font.FONT_HEIGHT, 0xffffff, text, textWidth); } public static int renderLinesReversed (MatrixStack matrix, FontRenderer fontRenderer, int x, int y, int spacing, int defaultColor, ITextComponent text, int textWidth) { // trimStringToWidth is actually wrapToWidth return renderLinesReversed(matrix, fontRenderer, x, y, spacing, defaultColor, fontRenderer.trimStringToWidth(text, textWidth)); } public static int renderLinesReversed (MatrixStack matrix, FontRenderer fontRenderer, int x, int y, int spacing, int defaultColor, List<IReorderingProcessor> lines) { final int lineCount = lines.size(); for (int lineNum = lineCount - 1; lineNum >= 0; lineNum final IReorderingProcessor lineFragment = lines.get(lineCount - 1 - lineNum); fontRenderer.func_238422_b_(matrix, lineFragment, x, y - (lineNum + 1) * (spacing + 1), defaultColor); } return lineCount * (spacing + 1); } /** * Unpacks a color into ARGB byte channels. * * @param color The color to unpack. * @return An array containing the ARGB color channels. */ public static int[] unpackColor (int color) { final int[] colors = new int[4]; colors[0] = color >> 24 & 0xff; // alpha colors[1] = color >> 16 & 0xff; // red colors[2] = color >> 8 & 0xff; // green colors[3] = color & 0xff; // blue return colors; } /** * Renders a block sprite as a cube. * * @param builder The vertex builder. * @param stack The render stack. * @param sprite The sprite to render. * @param light The packed lighting data. * @param overlay The packed overlay data. * @param color RGBA color to render. */ public static void renderBlockSprite (IVertexBuilder builder, MatrixStack stack, TextureAtlasSprite sprite, int light, int overlay, int[] color) { renderBlockSprite(builder, stack.getLast().getMatrix(), sprite, light, overlay, 0f, 1f, 0f, 1f, 0f, 1f, color); } /** * Renders a block sprite as a cube. * * @param builder The vertex builder. * @param stack The render stack. * @param sprite The sprite to render. * @param light The packed lighting data. * @param overlay The packed overlay data. * @param x1 The min x width of the cube to render. Between 0 and 1. * @param x2 The max x width of the cube to render. Between 0 and 1. * @param y1 The min y width of the cube to render. Between 0 and 1. * @param y2 The max y width of the cube to render. Between 0 and 1. * @param z1 The min z width of the cube to render. Between 0 and 1. * @param z2 The max z width of the cube to render. Between 0 and 1. * @param color RGBA color to render. */ public static void renderBlockSprite (IVertexBuilder builder, MatrixStack stack, TextureAtlasSprite sprite, int light, int overlay, float x1, float x2, float y1, float y2, float z1, float z2, int[] color) { renderBlockSprite(builder, stack.getLast().getMatrix(), sprite, light, overlay, x1, x2, y1, y2, z1, z2, color); } /** * Renders a block sprite as a cube. * * @param builder The vertex builder. * @param pos The render position. * @param sprite The sprite to render. * @param light The packed lighting data. * @param overlay The packed overlay data. * @param x1 The min x width of the cube to render. Between 0 and 1. * @param x2 The max x width of the cube to render. Between 0 and 1. * @param y1 The min y width of the cube to render. Between 0 and 1. * @param y2 The max y width of the cube to render. Between 0 and 1. * @param z1 The min z width of the cube to render. Between 0 and 1. * @param z2 The max z width of the cube to render. Between 0 and 1. * @param color RGBA color to render. */ public static void renderBlockSprite (IVertexBuilder builder, Matrix4f pos, TextureAtlasSprite sprite, int light, int overlay, float x1, float x2, float y1, float y2, float z1, float z2, int[] color) { renderSpriteSide(builder, pos, sprite, Direction.DOWN, light, overlay, x1, x2, y1, y2, z1, z2, color); renderSpriteSide(builder, pos, sprite, Direction.UP, light, overlay, x1, x2, y1, y2, z1, z2, color); renderSpriteSide(builder, pos, sprite, Direction.NORTH, light, overlay, x1, x2, y1, y2, z1, z2, color); renderSpriteSide(builder, pos, sprite, Direction.SOUTH, light, overlay, x1, x2, y1, y2, z1, z2, color); renderSpriteSide(builder, pos, sprite, Direction.WEST, light, overlay, x1, x2, y1, y2, z1, z2, color); renderSpriteSide(builder, pos, sprite, Direction.EAST, light, overlay, x1, x2, y1, y2, z1, z2, color); } /** * Renders a block sprite as a side of a cube. * * @param builder The vertex builder. * @param pos The render position. * @param sprite The sprite to render. * @param side The side of the cube to render. * @param light The packed lighting data. * @param overlay The packed overlay data. * @param x1 The min x width of the cube to render. Between 0 and 1. * @param x2 The max x width of the cube to render. Between 0 and 1. * @param y1 The min y width of the cube to render. Between 0 and 1. * @param y2 The max y width of the cube to render. Between 0 and 1. * @param z1 The min z width of the cube to render. Between 0 and 1. * @param z2 The max z width of the cube to render. Between 0 and 1. * @param color RGBA color to render. */ public static void renderSpriteSide (IVertexBuilder builder, Matrix4f pos, TextureAtlasSprite sprite, Direction side, int light, int overlay, float x1, float x2, float y1, float y2, float z1, float z2, int[] color) { // Convert block size to pixel size final double px1 = x1 * 16; final double px2 = x2 * 16; final double py1 = y1 * 16; final double py2 = y2 * 16; final double pz1 = z1 * 16; final double pz2 = z2 * 16; if (side == Direction.DOWN) { final float u1 = sprite.getInterpolatedU(px1); final float u2 = sprite.getInterpolatedU(px2); final float v1 = sprite.getInterpolatedV(pz1); final float v2 = sprite.getInterpolatedV(pz2); builder.pos(pos, x1, y1, z2).color(color[1], color[2], color[3], color[0]).tex(u1, v2).overlay(overlay).lightmap(light).normal(0f, -1f, 0f).endVertex(); builder.pos(pos, x1, y1, z1).color(color[1], color[2], color[3], color[0]).tex(u1, v1).overlay(overlay).lightmap(light).normal(0f, -1f, 0f).endVertex(); builder.pos(pos, x2, y1, z1).color(color[1], color[2], color[3], color[0]).tex(u2, v1).overlay(overlay).lightmap(light).normal(0f, -1f, 0f).endVertex(); builder.pos(pos, x2, y1, z2).color(color[1], color[2], color[3], color[0]).tex(u2, v2).overlay(overlay).lightmap(light).normal(0f, -1f, 0f).endVertex(); } if (side == Direction.UP) { final float u1 = sprite.getInterpolatedU(px1); final float u2 = sprite.getInterpolatedU(px2); final float v1 = sprite.getInterpolatedV(pz1); final float v2 = sprite.getInterpolatedV(pz2); builder.pos(pos, x1, y2, z2).color(color[1], color[2], color[3], color[0]).tex(u1, v2).overlay(overlay).lightmap(light).normal(0f, 1f, 0f).endVertex(); builder.pos(pos, x2, y2, z2).color(color[1], color[2], color[3], color[0]).tex(u2, v2).overlay(overlay).lightmap(light).normal(0f, 1f, 0f).endVertex(); builder.pos(pos, x2, y2, z1).color(color[1], color[2], color[3], color[0]).tex(u2, v1).overlay(overlay).lightmap(light).normal(0f, 1f, 0f).endVertex(); builder.pos(pos, x1, y2, z1).color(color[1], color[2], color[3], color[0]).tex(u1, v1).overlay(overlay).lightmap(light).normal(0f, 1f, 0f).endVertex(); } if (side == Direction.NORTH) { final float u1 = sprite.getInterpolatedU(px1); final float u2 = sprite.getInterpolatedU(px2); final float v1 = sprite.getInterpolatedV(py1); final float v2 = sprite.getInterpolatedV(py2); builder.pos(pos, x1, y1, z1).color(color[1], color[2], color[3], color[0]).tex(u1, v1).overlay(overlay).lightmap(light).normal(0f, 0f, -1f).endVertex(); builder.pos(pos, x1, y2, z1).color(color[1], color[2], color[3], color[0]).tex(u1, v2).overlay(overlay).lightmap(light).normal(0f, 0f, -1f).endVertex(); builder.pos(pos, x2, y2, z1).color(color[1], color[2], color[3], color[0]).tex(u2, v2).overlay(overlay).lightmap(light).normal(0f, 0f, -1f).endVertex(); builder.pos(pos, x2, y1, z1).color(color[1], color[2], color[3], color[0]).tex(u2, v1).overlay(overlay).lightmap(light).normal(0f, 0f, -1f).endVertex(); } if (side == Direction.SOUTH) { final float u1 = sprite.getInterpolatedU(px1); final float u2 = sprite.getInterpolatedU(px2); final float v1 = sprite.getInterpolatedV(py1); final float v2 = sprite.getInterpolatedV(py2); builder.pos(pos, x2, y1, z2).color(color[1], color[2], color[3], color[0]).tex(u2, v1).overlay(overlay).lightmap(light).normal(0f, 0f, 1f).endVertex(); builder.pos(pos, x2, y2, z2).color(color[1], color[2], color[3], color[0]).tex(u2, v2).overlay(overlay).lightmap(light).normal(0f, 0f, 1f).endVertex(); builder.pos(pos, x1, y2, z2).color(color[1], color[2], color[3], color[0]).tex(u1, v2).overlay(overlay).lightmap(light).normal(0f, 0f, 1f).endVertex(); builder.pos(pos, x1, y1, z2).color(color[1], color[2], color[3], color[0]).tex(u1, v1).overlay(overlay).lightmap(light).normal(0f, 0f, 1f).endVertex(); } if (side == Direction.WEST) { final float u1 = sprite.getInterpolatedU(py1); final float u2 = sprite.getInterpolatedU(py2); final float v1 = sprite.getInterpolatedV(pz1); final float v2 = sprite.getInterpolatedV(pz2); builder.pos(pos, x1, y1, z2).color(color[1], color[2], color[3], color[0]).tex(u1, v2).overlay(overlay).lightmap(light).normal(-1f, 0f, 0f).endVertex(); builder.pos(pos, x1, y2, z2).color(color[1], color[2], color[3], color[0]).tex(u2, v2).overlay(overlay).lightmap(light).normal(-1f, 0f, 0f).endVertex(); builder.pos(pos, x1, y2, z1).color(color[1], color[2], color[3], color[0]).tex(u2, v1).overlay(overlay).lightmap(light).normal(-1f, 0f, 0f).endVertex(); builder.pos(pos, x1, y1, z1).color(color[1], color[2], color[3], color[0]).tex(u1, v1).overlay(overlay).lightmap(light).normal(-1f, 0f, 0f).endVertex(); } if (side == Direction.EAST) { final float u1 = sprite.getInterpolatedU(py1); final float u2 = sprite.getInterpolatedU(py2); final float v1 = sprite.getInterpolatedV(pz1); final float v2 = sprite.getInterpolatedV(pz2); builder.pos(pos, x2, y1, z1).color(color[1], color[2], color[3], color[0]).tex(u1, v1).overlay(overlay).lightmap(light).normal(1f, 0f, 0f).endVertex(); builder.pos(pos, x2, y2, z1).color(color[1], color[2], color[3], color[0]).tex(u2, v1).overlay(overlay).lightmap(light).normal(1f, 0f, 0f).endVertex(); builder.pos(pos, x2, y2, z2).color(color[1], color[2], color[3], color[0]).tex(u2, v2).overlay(overlay).lightmap(light).normal(1f, 0f, 0f).endVertex(); builder.pos(pos, x2, y1, z2).color(color[1], color[2], color[3], color[0]).tex(u1, v2).overlay(overlay).lightmap(light).normal(1f, 0f, 0f).endVertex(); } } }
package net.goldolphin.maria; import java.util.concurrent.CompletableFuture; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.FullHttpResponse; /** * @author caofuxiang * 2016-04-05 10:27:27. */ public class HttpClientHandler extends SimpleChannelInboundHandler<FullHttpResponse> { private static final Logger logger = LoggerFactory.getLogger(HttpClientHandler.class); private final CompletableFuture<FullHttpResponse> future; public HttpClientHandler(CompletableFuture<FullHttpResponse> future) { this.future = future; } protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpResponse response) throws Exception { // Ensure that we copied a response with unpooled buffer. DefaultFullHttpResponse copy = new DefaultFullHttpResponse( response.getProtocolVersion(), response.getStatus(), Unpooled.copiedBuffer(response.content())); copy.headers().set(response.headers()); copy.trailingHeaders().set(response.trailingHeaders()); future.complete(copy); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { future.completeExceptionally(cause); ctx.close(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { future.completeExceptionally(new NoHttpResponseException("Server failed to respond")); super.channelInactive(ctx); } }
package net.rubyeye.xmemcached; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.TimeoutException; import net.rubyeye.xmemcached.auth.AuthInfo; import net.rubyeye.xmemcached.buffer.BufferAllocator; import net.rubyeye.xmemcached.exception.MemcachedException; import net.rubyeye.xmemcached.impl.ReconnectRequest; import net.rubyeye.xmemcached.networking.Connector; import net.rubyeye.xmemcached.transcoders.Transcoder; import net.rubyeye.xmemcached.utils.Protocol; /** * The memcached client's interface * * @author dennis * */ public interface MemcachedClient { /** * Default thread number for reading nio's receive buffer and dispatch * commands.Recommend users to set it equal or less to the memcached * server's number on linux platform,keep default on windows.Default is 0. */ public static final int DEFAULT_READ_THREAD_COUNT = 0; /** * Default TCP keeplive option,which is true */ public static final boolean DEFAULT_TCP_KEEPLIVE = true; /** * Default connect timeout,1 minutes */ public static final int DEFAULT_CONNECT_TIMEOUT = 60000; /** * Default socket's send buffer size,8k */ public static final int DEFAULT_TCP_SEND_BUFF_SIZE = 32 * 1024; /** * Disable nagle algorithm by default * */ public static final boolean DEFAULT_TCP_NO_DELAY = true; /** * Default session read buffer size,16k */ public static final int DEFAULT_SESSION_READ_BUFF_SIZE = 128 * 1024; /** * Default socket's receive buffer size,16k */ public static final int DEFAULT_TCP_RECV_BUFF_SIZE = 64 * 1024; /** * Default operation timeout,if the operation is not returned in 1 * second,throw TimeoutException */ public static final long DEFAULT_OP_TIMEOUT = 1000L; /** * With java nio,there is only one connection to a memcached.In a high * concurrent enviroment,you may want to pool memcached clients.But a * xmemcached client has to start a reactor thread and some thread pools,if * you create too many clients,the cost is very large. Xmemcached supports * connection pool instreadof client pool.you can create more connections to * one or more memcached servers,and these connections share the same * reactor and thread pools,it will reduce the cost of system.Default pool * size is 1. */ public static final int DEFAULT_CONNECTION_POOL_SIZE = 1; /** * Default session idle timeout,if session is idle,xmemcached will do a * heartbeat action to check if connection is alive. */ public static final int DEFAULT_SESSION_IDLE_TIMEOUT = 5000; int MAX_QUEUED_NOPS = 40000; int DYNAMIC_MAX_QUEUED_NOPS = (int) (MAX_QUEUED_NOPS * (Runtime .getRuntime().maxMemory() / 1024.0 / 1024.0 / 1024.0)); /** * Default max queued noreply operations number.It is calcuated dynamically * based on your jvm maximum memory. * * @since 1.3.8 */ public static final int DEFAULT_MAX_QUEUED_NOPS = DYNAMIC_MAX_QUEUED_NOPS > MAX_QUEUED_NOPS ? MAX_QUEUED_NOPS : DYNAMIC_MAX_QUEUED_NOPS; /** * Set the merge factor,this factor determins how many 'get' commands would * be merge to one multi-get command.default is 150 * * @param mergeFactor */ public void setMergeFactor(final int mergeFactor); /** * Get the connect timeout * * @param connectTimeout */ public long getConnectTimeout(); /** * Set the connect timeout,default is 1 minutes * * @param connectTimeout */ public void setConnectTimeout(long connectTimeout); /** * return the session manager * * @return */ public Connector getConnector(); /** * Enable/Disable merge many get commands to one multi-get command.true is * to enable it,false is to disable it.Default is true.Recommend users to * enable it. * * @param optimizeGet */ public void setOptimizeGet(final boolean optimizeGet); /** * Enable/Disable merge many command's buffers to one big buffer fit * socket's send buffer size.Default is true.Recommend true. * * @param optimizeMergeBuffer */ public void setOptimizeMergeBuffer(final boolean optimizeMergeBuffer); /** * @return */ public boolean isShutdown(); /** * Aadd a memcached server,the thread call this method will be blocked until * the connecting operations completed(success or fail) * * @param server * host string * @param port * port number */ public void addServer(final String server, final int port) throws IOException; /** * Add a memcached server,the thread call this method will be blocked until * the connecting operations completed(success or fail) * * @param inetSocketAddress * memcached server's socket address */ public void addServer(final InetSocketAddress inetSocketAddress) throws IOException; /** * Add many memcached servers.You can call this method through JMX or * program * * @param host * String like [host1]:[port1] [host2]:[port2] ... */ public void addServer(String hostList) throws IOException; /** * Get current server list.You can call this method through JMX or program */ public List<String> getServersDescription(); /** * Remove many memcached server * * @param host * String like [host1]:[port1] [host2]:[port2] ... */ public void removeServer(String hostList); /** * Set the nio's ByteBuffer Allocator,use SimpleBufferAllocator by default. * * * @param bufferAllocator * @return */ @Deprecated public void setBufferAllocator(final BufferAllocator bufferAllocator); /** * Get value by key * * @param <T> * @param key * Key * @param timeout * Operation timeout,if the method is not returned in this * time,throw TimeoutException * @param transcoder * The value's transcoder * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> T get(final String key, final long timeout, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; public <T> T get(final String key, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; public <T> T get(final String key, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; public <T> T get(final String key) throws TimeoutException, InterruptedException, MemcachedException; /** * Just like get,But it return a GetsResponse,include cas value for cas * update. * * @param <T> * @param key * key * @param timeout * operation timeout * @param transcoder * * @return GetsResponse * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> GetsResponse<T> gets(final String key, final long timeout, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #gets(String, long, Transcoder) * @param <T> * @param key * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> GetsResponse<T> gets(final String key) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #gets(String, long, Transcoder) * @param <T> * @param key * @param timeout * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> GetsResponse<T> gets(final String key, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #gets(String, long, Transcoder) * @param <T> * @param key * @param transcoder * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ @SuppressWarnings("unchecked") public <T> GetsResponse<T> gets(final String key, final Transcoder transcoder) throws TimeoutException, InterruptedException, MemcachedException; /** * Bulk get items * * @param <T> * @param keyCollections * key collection * @param opTimeout * opTimeout * @param transcoder * Value transcoder * @return Exists items map * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> Map<String, T> get(final Collection<String> keyCollections, final long opTimeout, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #get(Collection, long, Transcoder) * @param <T> * @param keyCollections * @param transcoder * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> Map<String, T> get(final Collection<String> keyCollections, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #get(Collection, long, Transcoder) * @param <T> * @param keyCollections * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> Map<String, T> get(final Collection<String> keyCollections) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #get(Collection, long, Transcoder) * @param <T> * @param keyCollections * @param timeout * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> Map<String, T> get(final Collection<String> keyCollections, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * Bulk gets items * * @param <T> * @param keyCollections * key collection * @param opTime * Operation timeout * @param transcoder * Value transcoder * @return Exists GetsResponse map * @see net.rubyeye.xmemcached.GetsResponse * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> Map<String, GetsResponse<T>> gets( final Collection<String> keyCollections, final long opTime, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #gets(Collection, long, Transcoder) * @param <T> * @param keyCollections * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> Map<String, GetsResponse<T>> gets( final Collection<String> keyCollections) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #gets(Collection, long, Transcoder) * @param <T> * @param keyCollections * @param timeout * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> Map<String, GetsResponse<T>> gets( final Collection<String> keyCollections, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #gets(Collection, long, Transcoder) * @param <T> * @param keyCollections * @param transcoder * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> Map<String, GetsResponse<T>> gets( final Collection<String> keyCollections, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; /** * Store key-value item to memcached * * @param <T> * @param key * stored key * @param exp * An expiration time, in seconds. Can be up to 30 days. After 30 * days, is treated as a unix timestamp of an exact date. * @param value * stored data * @param transcoder * transocder * @param timeout * operation timeout,in milliseconds * @return boolean result * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean set(final String key, final int exp, final T value, final Transcoder<T> transcoder, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #set(String, int, Object, Transcoder, long) */ public boolean set(final String key, final int exp, final Object value) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #set(String, int, Object, Transcoder, long) */ public boolean set(final String key, final int exp, final Object value, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #set(String, int, Object, Transcoder, long) */ public <T> boolean set(final String key, final int exp, final T value, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; /** * Store key-value item to memcached,doesn't wait for reply * * @param <T> * @param key * stored key * @param exp * An expiration time, in seconds. Can be up to 30 days. After 30 * days, is treated as a unix timestamp of an exact date. * @param value * stored data * @param transcoder * transocder * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public void setWithNoReply(final String key, final int exp, final Object value) throws InterruptedException, MemcachedException; /** * @see #setWithNoReply(String, int, Object, Transcoder) * @param <T> * @param key * @param exp * @param value * @param transcoder * @throws InterruptedException * @throws MemcachedException */ public <T> void setWithNoReply(final String key, final int exp, final T value, final Transcoder<T> transcoder) throws InterruptedException, MemcachedException; /** * Add key-value item to memcached, success only when the key is not exists * in memcached. * * @param <T> * @param key * @param exp * An expiration time, in seconds. Can be up to 30 days. After 30 * days, is treated as a unix timestamp of an exact date. * @param value * @param transcoder * @param timeout * @return boolean result * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean add(final String key, final int exp, final T value, final Transcoder<T> transcoder, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #add(String, int, Object, Transcoder, long) * @param key * @param exp * @param value * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean add(final String key, final int exp, final Object value) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #add(String, int, Object, Transcoder, long) * @param key * @param exp * @param value * @param timeout * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean add(final String key, final int exp, final Object value, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #add(String, int, Object, Transcoder, long) * * @param <T> * @param key * @param exp * @param value * @param transcoder * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean add(final String key, final int exp, final T value, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; /** * Add key-value item to memcached, success only when the key is not exists * in memcached.This method doesn't wait for reply. * * @param <T> * @param key * @param exp * An expiration time, in seconds. Can be up to 30 days. After 30 * days, is treated as a unix timestamp of an exact date. * @param value * @param transcoder * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public void addWithNoReply(final String key, final int exp, final Object value) throws InterruptedException, MemcachedException; /** * @see #addWithNoReply(String, int, Object, Transcoder) * @param <T> * @param key * @param exp * @param value * @param transcoder * @throws InterruptedException * @throws MemcachedException */ public <T> void addWithNoReply(final String key, final int exp, final T value, final Transcoder<T> transcoder) throws InterruptedException, MemcachedException; /** * Replace the key's data item in memcached,success only when the key's data * item is exists in memcached.This method will wait for reply from server. * * @param <T> * @param key * @param exp * An expiration time, in seconds. Can be up to 30 days. After 30 * days, is treated as a unix timestamp of an exact date. * @param value * @param transcoder * @param timeout * @return boolean result * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean replace(final String key, final int exp, final T value, final Transcoder<T> transcoder, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #replace(String, int, Object, Transcoder, long) * @param key * @param exp * @param value * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean replace(final String key, final int exp, final Object value) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #replace(String, int, Object, Transcoder, long) * @param key * @param exp * @param value * @param timeout * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean replace(final String key, final int exp, final Object value, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #replace(String, int, Object, Transcoder, long) * @param <T> * @param key * @param exp * @param value * @param transcoder * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean replace(final String key, final int exp, final T value, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; /** * Replace the key's data item in memcached,success only when the key's data * item is exists in memcached.This method doesn't wait for reply from * server. * * @param <T> * @param key * @param exp * An expiration time, in seconds. Can be up to 30 days. After 30 * days, is treated as a unix timestamp of an exact date. * @param value * @param transcoder * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public void replaceWithNoReply(final String key, final int exp, final Object value) throws InterruptedException, MemcachedException; /** * @see #replaceWithNoReply(String, int, Object, Transcoder) * @param <T> * @param key * @param exp * @param value * @param transcoder * @throws InterruptedException * @throws MemcachedException */ public <T> void replaceWithNoReply(final String key, final int exp, final T value, final Transcoder<T> transcoder) throws InterruptedException, MemcachedException; /** * @see #append(String, Object, long) * @param key * @param value * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean append(final String key, final Object value) throws TimeoutException, InterruptedException, MemcachedException; /** * Append value to key's data item,this method will wait for reply * * @param key * @param value * @param timeout * @return boolean result * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean append(final String key, final Object value, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * Append value to key's data item,this method doesn't wait for reply. * * @param key * @param value * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public void appendWithNoReply(final String key, final Object value) throws InterruptedException, MemcachedException; /** * @see #prepend(String, Object, long) * @param key * @param value * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean prepend(final String key, final Object value) throws TimeoutException, InterruptedException, MemcachedException; /** * Prepend value to key's data item in memcached.This method doesn't wait * for reply. * * @param key * @param value * @return boolean result * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean prepend(final String key, final Object value, final long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * Prepend value to key's data item in memcached.This method doesn't wait * for reply. * * @param key * @param value * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public void prependWithNoReply(final String key, final Object value) throws InterruptedException, MemcachedException; /** * @see #cas(String, int, Object, Transcoder, long, long) * @param key * @param exp * @param value * @param cas * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean cas(final String key, final int exp, final Object value, final long cas) throws TimeoutException, InterruptedException, MemcachedException; /** * Cas is a check and set operation which means "store this data but only if * no one else has updated since I last fetched it." * * @param <T> * @param key * @param exp * An expiration time, in seconds. Can be up to 30 days. After 30 * days, is treated as a unix timestamp of an exact date. * @param value * @param transcoder * @param timeout * @param cas * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean cas(final String key, final int exp, final T value, final Transcoder<T> transcoder, final long timeout, final long cas) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #cas(String, int, Object, Transcoder, long, long) * @param key * @param exp * @param value * @param timeout * @param cas * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean cas(final String key, final int exp, final Object value, final long timeout, final long cas) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #cas(String, int, Object, Transcoder, long, long) * @param <T> * @param key * @param exp * @param value * @param transcoder * @param cas * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean cas(final String key, final int exp, final T value, final Transcoder<T> transcoder, final long cas) throws TimeoutException, InterruptedException, MemcachedException; /** * Cas is a check and set operation which means "store this data but only if * no one else has updated since I last fetched it." * * @param <T> * @param key * @param exp * An expiration time, in seconds. Can be up to 30 days. After 30 * days, is treated as a unix timestamp of an exact date. * @param operation * CASOperation * @param transcoder * object transcoder * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean cas(final String key, final int exp, final CASOperation<T> operation, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; /** * cas is a check and set operation which means "store this data but only if * no one else has updated since I last fetched it." * * @param <T> * @param key * @param exp * An expiration time, in seconds. Can be up to 30 days. After 30 * days, is treated as a unix timestamp of an exact date. * @param getsReponse * gets method's result * @param operation * CASOperation * @param transcoder * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean cas(final String key, final int exp, GetsResponse<T> getsReponse, final CASOperation<T> operation, final Transcoder<T> transcoder) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #cas(String, int, GetsResponse, CASOperation, Transcoder) * @param <T> * @param key * @param exp * @param getsReponse * @param operation * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean cas(final String key, final int exp, GetsResponse<T> getsReponse, final CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #cas(String, int, GetsResponse, CASOperation, Transcoder) * @param <T> * @param key * @param getsResponse * @param operation * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean cas(final String key, GetsResponse<T> getsResponse, final CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #cas(String, int, GetsResponse, CASOperation, Transcoder) * @param <T> * @param key * @param exp * @param operation * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean cas(final String key, final int exp, final CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #cas(String, int, GetsResponse, CASOperation, Transcoder) * @param <T> * @param key * @param operation * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> boolean cas(final String key, final CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException; /** * * @param <T> * @param key * @param getsResponse * @param operation * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> void casWithNoReply(final String key, GetsResponse<T> getsResponse, final CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException; /** * cas noreply * * @param <T> * @param key * @param exp * @param getsReponse * @param operation * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> void casWithNoReply(final String key, final int exp, GetsResponse<T> getsReponse, final CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #casWithNoReply(String, int, GetsResponse, CASOperation) * @param <T> * @param key * @param exp * @param operation * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> void casWithNoReply(final String key, final int exp, final CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException; /** * @see #casWithNoReply(String, int, GetsResponse, CASOperation) * @param <T> * @param key * @param operation * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> void casWithNoReply(final String key, final CASOperation<T> operation) throws TimeoutException, InterruptedException, MemcachedException; /** * Delete key's data item from memcached.It it is not exists,return * false.</br> time is the amount of time in seconds (or Unix time * until</br> which) the client wishes the server to refuse "add" and * "replace"</br> commands with this key. For this amount of item, the item * is put into a</br> delete queue, which means that it won't possible to * retrieve it by the</br> "get" command, but "add" and "replace" command * with this key will also</br> fail (the "set" command will succeed, * however). After the time passes,</br> the item is finally deleted from * server memory. </br><strong>Note: This method is deprecated,because * memcached 1.4.0 remove the optional argument "time".You can still use * this method on old version,but is not recommended.</strong> * * @param key * @param time * @throws InterruptedException * @throws MemcachedException */ @Deprecated public boolean delete(final String key, final int time) throws TimeoutException, InterruptedException, MemcachedException; /** * Delete key's date item from memcached * * @param key * @param opTimeout * Operation timeout * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException * @since 1.3.2 */ public boolean delete(final String key, long opTimeout) throws TimeoutException, InterruptedException, MemcachedException; /** * Set a new expiration time for an existing item * * @param key * item's key * @param exp * New expiration time, in seconds. Can be up to 30 days. After * 30 days, is treated as a unix timestamp of an exact date. * @param opTimeout * operation timeout * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean touch(final String key, int exp, long opTimeout) throws TimeoutException, InterruptedException, MemcachedException; /** * Set a new expiration time for an existing item,using default opTimeout * second. * * @param key * item's key * @param exp * New expiration time, in seconds. Can be up to 30 days. After * 30 days, is treated as a unix timestamp of an exact date. * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public boolean touch(final String key, int exp) throws TimeoutException, InterruptedException, MemcachedException; /** * Get item and set a new expiration time for it * * @param <T> * @param key * item's key * @param newExp * New expiration time, in seconds. Can be up to 30 days. After * 30 days, is treated as a unix timestamp of an exact date. * @param opTimeout * operation timeout * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> T getAndTouch(final String key, int newExp, long opTimeout) throws TimeoutException, InterruptedException, MemcachedException; /** * Get item and set a new expiration time for it,using default opTimeout * * @param <T> * @param key * @param newExp * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public <T> T getAndTouch(final String key, int newExp) throws TimeoutException, InterruptedException, MemcachedException; /** * Bulk get items and touch them * * @param <T> * @param keyExpMap * A map,key is item's key,and value is a new expiration time for * the item. * @param opTimeout * operation timeout * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ // public <T> Map<String, T> getAndTouch(Map<String, Integer> keyExpMap, // long opTimeout) throws TimeoutException, InterruptedException, // MemcachedException; /** * Bulk get items and touch them,using default opTimeout * * @see #getAndTouch(Map, long) * @param <T> * @param keyExpMap * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ // public <T> Map<String, T> getAndTouch(Map<String, Integer> keyExpMap) // throws TimeoutException, InterruptedException, MemcachedException; /** * Get all connected memcached servers's version. * * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public Map<InetSocketAddress, String> getVersions() throws TimeoutException, InterruptedException, MemcachedException; /** * "incr" are used to change data for some item in-place, incrementing it. * The data for the item is treated as decimal representation of a 64-bit * unsigned integer. If the current data value does not conform to such a * representation, the commands behave as if the value were 0. Also, the * item must already exist for incr to work; these commands won't pretend * that a non-existent key exists with value 0; instead, it will fail.This * method doesn't wait for reply. * * @return the new value of the item's data, after the increment operation * was carried out. * @param key * @param num * @throws InterruptedException * @throws MemcachedException */ public long incr(final String key, final long delta) throws TimeoutException, InterruptedException, MemcachedException; public long incr(final String key, final long delta, final long initValue) throws TimeoutException, InterruptedException, MemcachedException; /** * "incr" are used to change data for some item in-place, incrementing it. * The data for the item is treated as decimal representation of a 64-bit * unsigned integer. If the current data value does not conform to such a * representation, the commands behave as if the value were 0. Also, the * item must already exist for incr to work; these commands won't pretend * that a non-existent key exists with value 0; instead, it will fail.This * method doesn't wait for reply. * * @param key * key * @param num * increment * @param initValue * initValue if the data is not exists. * @param timeout * operation timeout * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public long incr(final String key, final long delta, final long initValue, long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * "decr" are used to change data for some item in-place, decrementing it. * The data for the item is treated as decimal representation of a 64-bit * unsigned integer. If the current data value does not conform to such a * representation, the commands behave as if the value were 0. Also, the * item must already exist for decr to work; these commands won't pretend * that a non-existent key exists with value 0; instead, it will fail.This * method doesn't wait for reply. * * @return the new value of the item's data, after the decrement operation * was carried out. * @param key * @param num * @throws InterruptedException * @throws MemcachedException */ public long decr(final String key, final long delta) throws TimeoutException, InterruptedException, MemcachedException; /** * @see decr * @param key * @param num * @param initValue * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public long decr(final String key, final long delta, long initValue) throws TimeoutException, InterruptedException, MemcachedException; /** * "decr" are used to change data for some item in-place, decrementing it. * The data for the item is treated as decimal representation of a 64-bit * unsigned integer. If the current data value does not conform to such a * representation, the commands behave as if the value were 0. Also, the * item must already exist for decr to work; these commands won't pretend * that a non-existent key exists with value 0; instead, it will fail.This * method doesn't wait for reply. * * @param key * The key * @param num * The increment * @param initValue * The initial value if the data is not exists. * @param timeout * Operation timeout * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public long decr(final String key, final long delta, long initValue, long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * Make All connected memcached's data item invalid * * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public void flushAll() throws TimeoutException, InterruptedException, MemcachedException; public void flushAllWithNoReply() throws InterruptedException, MemcachedException; /** * Make All connected memcached's data item invalid * * @param timeout * operation timeout * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public void flushAll(long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * Invalidate all existing items immediately * * @param address * Target memcached server * @param timeout * operation timeout * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public void flushAll(InetSocketAddress address) throws MemcachedException, InterruptedException, TimeoutException; public void flushAllWithNoReply(InetSocketAddress address) throws MemcachedException, InterruptedException; public void flushAll(InetSocketAddress address, long timeout) throws MemcachedException, InterruptedException, TimeoutException; /** * This method is deprecated,please use flushAll(InetSocketAddress) instead. * * @deprecated * @param host * * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ @Deprecated public void flushAll(String host) throws TimeoutException, InterruptedException, MemcachedException; public Map<String, String> stats(InetSocketAddress address) throws MemcachedException, InterruptedException, TimeoutException; public Map<String, String> stats(InetSocketAddress address, long timeout) throws MemcachedException, InterruptedException, TimeoutException; /** * Get stats from all memcached servers * * @param timeout * @return server->item->value map * @throws MemcachedException * @throws InterruptedException * @throws TimeoutException */ public Map<InetSocketAddress, Map<String, String>> getStats(long timeout) throws MemcachedException, InterruptedException, TimeoutException; public Map<InetSocketAddress, Map<String, String>> getStats() throws MemcachedException, InterruptedException, TimeoutException; /** * Get special item stats. "stats items" for example * * @param item * @return */ public Map<InetSocketAddress, Map<String, String>> getStatsByItem( String itemName) throws MemcachedException, InterruptedException, TimeoutException;; public void shutdown() throws IOException; public boolean delete(final String key) throws TimeoutException, InterruptedException, MemcachedException; /** * return default transcoder,default is SerializingTranscoder * * @return */ @SuppressWarnings("unchecked") public Transcoder getTranscoder(); /** * set transcoder * * @param transcoder */ @SuppressWarnings("unchecked") public void setTranscoder(final Transcoder transcoder); public Map<InetSocketAddress, Map<String, String>> getStatsByItem( String itemName, long timeout) throws MemcachedException, InterruptedException, TimeoutException; /** * get operation timeout setting * * @return */ public long getOpTimeout(); /** * set operation timeout,default is one second. * * @param opTimeout */ public void setOpTimeout(long opTimeout); public Map<InetSocketAddress, String> getVersions(long timeout) throws TimeoutException, InterruptedException, MemcachedException; /** * Returns available memcached servers list.This method is drepcated,please * use getAvailableServers instead. * * @see #getAvailableServers() * @return */ @Deprecated public Collection<InetSocketAddress> getAvaliableServers(); /** * Returns available memcached servers list. * * @return A available server collection */ public Collection<InetSocketAddress> getAvailableServers(); /** * add a memcached server to MemcachedClient * * @param server * @param port * @param weight * @throws IOException */ public void addServer(final String server, final int port, int weight) throws IOException; public void addServer(final InetSocketAddress inetSocketAddress, int weight) throws IOException; @Deprecated public void deleteWithNoReply(final String key, final int time) throws InterruptedException, MemcachedException; public void deleteWithNoReply(final String key) throws InterruptedException, MemcachedException; /** * "incr" are used to change data for some item in-place, incrementing it. * The data for the item is treated as decimal representation of a 64-bit * unsigned integer. If the current data value does not conform to such a * representation, the commands behave as if the value were 0. Also, the * item must already exist for incr to work; these commands won't pretend * that a non-existent key exists with value 0; instead, it will fail.This * method doesn't wait for reply. * * @param key * @param num * @throws InterruptedException * @throws MemcachedException */ public void incrWithNoReply(final String key, final long delta) throws InterruptedException, MemcachedException; /** * "decr" are used to change data for some item in-place, decrementing it. * The data for the item is treated as decimal representation of a 64-bit * unsigned integer. If the current data value does not conform to such a * representation, the commands behave as if the value were 0. Also, the * item must already exist for decr to work; these commands won't pretend * that a non-existent key exists with value 0; instead, it will fail.This * method doesn't wait for reply. * * @param key * @param num * @throws InterruptedException * @throws MemcachedException */ public void decrWithNoReply(final String key, final long delta) throws InterruptedException, MemcachedException; /** * Set the verbosity level of the memcached's logging output.This method * will wait for reply. * * @param address * @param level * logging level * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ public void setLoggingLevelVerbosity(InetSocketAddress address, int level) throws TimeoutException, InterruptedException, MemcachedException; /** * Set the verbosity level of the memcached's logging output.This method * doesn't wait for reply from server * * @param address * memcached server address * @param level * logging level * @throws InterruptedException * @throws MemcachedException */ public void setLoggingLevelVerbosityWithNoReply(InetSocketAddress address, int level) throws InterruptedException, MemcachedException; /** * Add a memcached client listener * * @param listener */ public void addStateListener(MemcachedClientStateListener listener); /** * Remove a memcached client listener * * @param listener */ public void removeStateListener(MemcachedClientStateListener listener); /** * Get all current state listeners * * @return */ public Collection<MemcachedClientStateListener> getStateListeners(); public void flushAllWithNoReply(int exptime) throws InterruptedException, MemcachedException; public void flushAll(int exptime, long timeout) throws TimeoutException, InterruptedException, MemcachedException; public void flushAllWithNoReply(InetSocketAddress address, int exptime) throws MemcachedException, InterruptedException; public void flushAll(InetSocketAddress address, long timeout, int exptime) throws MemcachedException, InterruptedException, TimeoutException; /** * If the memcached dump or network error cause connection closed,xmemcached * would try to heal the connection.The interval between reconnections is 2 * seconds by default. You can change that value by this method. * * @param healConnectionInterval * MILLISECONDS */ public void setHealSessionInterval(long healConnectionInterval); /** * Return the default heal session interval in milliseconds * * @return */ public long getHealSessionInterval(); public Protocol getProtocol(); /** * Store all primitive type as string,defualt is false. */ public void setPrimitiveAsString(boolean primitiveAsString); /** * In a high concurrent enviroment,you may want to pool memcached * clients.But a xmemcached client has to start a reactor thread and some * thread pools,if you create too many clients,the cost is very large. * Xmemcached supports connection pool instreadof client pool.you can create * more connections to one or more memcached servers,and these connections * share the same reactor and thread pools,it will reduce the cost of * system. * * @param poolSize * pool size,default is one,every memcached has only one * connection. */ public void setConnectionPoolSize(int poolSize); /** * Whether to enable heart beat * * @param enableHeartBeat * if true,then enable heartbeat,true by default */ public void setEnableHeartBeat(boolean enableHeartBeat); /** * Enables/disables sanitizing keys by URLEncoding. * * @param sanitizeKey * if true, then URLEncode all keys */ public void setSanitizeKeys(boolean sanitizeKey); public boolean isSanitizeKeys(); /** * Get counter for key,and if the key's value is not set,then set it with 0. * * @param key * @return */ public Counter getCounter(String key); /** * Get counter for key,and if the key's value is not set,then set it with * initial value. * * @param key * @param initialValue * @return */ public Counter getCounter(String key, long initialValue); /** * Get key iterator for special memcached server.You must known that the * iterator is a snapshot for memcached all keys,it is not real-time.The * 'stats cachedump" has length limitation,so iterator could not visit all * keys if you have many keys.Your application should not be dependent on * this feature. * * @deprecated memcached 1.6.x will remove cachedump stats command,so this * method will be removed in the future * @param address * @return */ @Deprecated public KeyIterator getKeyIterator(InetSocketAddress address) throws MemcachedException, InterruptedException, TimeoutException; /** * Configure auth info * * @param map * Auth info map,key is memcached server address,and value is the * auth info for the key. */ public void setAuthInfoMap(Map<InetSocketAddress, AuthInfo> map); /** * return current all auth info * * @return Auth info map,key is memcached server address,and value is the * auth info for the key. */ public Map<InetSocketAddress, AuthInfo> getAuthInfoMap(); /** * "incr" are used to change data for some item in-place, incrementing it. * The data for the item is treated as decimal representation of a 64-bit * unsigned integer. If the current data value does not conform to such a * representation, the commands behave as if the value were 0. Also, the * item must already exist for incr to work; these commands won't pretend * that a non-existent key exists with value 0; instead, it will fail.This * method doesn't wait for reply. * * @param key * @param delta * @param initValue * the initial value to be added when value is not found * @param timeout * @param exp * the initial vlaue expire time, in seconds. Can be up to 30 * days. After 30 days, is treated as a unix timestamp of an * exact date. * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ long decr(String key, long delta, long initValue, long timeout, int exp) throws TimeoutException, InterruptedException, MemcachedException; /** * "incr" are used to change data for some item in-place, incrementing it. * The data for the item is treated as decimal representation of a 64-bit * unsigned integer. If the current data value does not conform to such a * representation, the commands behave as if the value were 0. Also, the * item must already exist for incr to work; these commands won't pretend * that a non-existent key exists with value 0; instead, it will fail.This * method doesn't wait for reply. * * @param key * key * @param delta * increment delta * @param initValue * the initial value to be added when value is not found * @param timeout * operation timeout * @param exp * the initial vlaue expire time, in seconds. Can be up to 30 * days. After 30 days, is treated as a unix timestamp of an * exact date. * @return * @throws TimeoutException * @throws InterruptedException * @throws MemcachedException */ long incr(String key, long delta, long initValue, long timeout, int exp) throws TimeoutException, InterruptedException, MemcachedException; /** * Return the cache instance name * * @return */ public String getName(); /** * Set cache instance name * * @param name */ public void setName(String name); /** * Returns reconnecting task queue,the queue is thread-safe and 'weakly * consistent',but maybe you <strong>should not modify it</strong> at all. * * @return The reconnecting task queue,if the client has not been * started,returns null. */ public Queue<ReconnectRequest> getReconnectRequestQueue(); /** * Configure wheather to set client in failure mode.If set it to true,that * means you want to configure client in failure mode. Failure mode is that * when a memcached server is down,it would not taken from the server list * but marked as unavailable,and then further requests to this server will * be transformed to standby node if configured or throw an exception until * it comes back up. * * @param failureMode * true is to configure client in failure mode. */ public void setFailureMode(boolean failureMode); /** * Returns if client is in failure mode. * * @return */ public boolean isFailureMode(); /** * Set a key provider for pre-processing keys before sending them to * memcached. * * @since 1.3.8 * @param keyProvider */ public void setKeyProvider(KeyProvider keyProvider); }
package org.hisp.dhis.android.core.trackedentity.internal; import org.hisp.dhis.android.core.D2; import org.hisp.dhis.android.core.D2Factory; import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttribute; import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeReservedValue; import org.hisp.dhis.android.core.utils.integration.real.BaseRealIntegrationTest; import org.junit.Before; import java.io.IOException; import java.util.List; import static com.google.common.truth.Truth.assertThat; public class TrackedEntityAttributeReservedValueEndpointCallRealIntegrationShould extends BaseRealIntegrationTest { /** * A quick integration test that is probably flaky, but will help with finding bugs related to the * metadataSyncCall. It works against the demo server. */ private D2 d2; private Integer numberToReserve = 5; private String orgunitUid = "DiszpKrYNg8"; @Before @Override public void setUp() throws IOException { super.setUp(); d2 = D2Factory.forNewDatabase(); } private void reserveValues() { d2.trackedEntityModule().reservedValueManager().blockingDownloadReservedValues("xs8A6tQJY0s", numberToReserve); } private String getValue() { return d2.trackedEntityModule().reservedValueManager().blockingGetValue("xs8A6tQJY0s", orgunitUid); } // @Test public void reserve_and_download() { login(); syncMetadata(); reserveValues(); String value = getValue(); } // @Test public void download_and_persist_reserved_values() { login(); syncMetadata(); reserveValues(); List<TrackedEntityAttributeReservedValue> reservedValues = TrackedEntityAttributeReservedValueStore.create( databaseAdapter()).selectAll(); assertThat(reservedValues.size()).isEqualTo(numberToReserve); } // @Test public void download_and_persist_all_reserved_values() { login(); syncMetadata(); d2.trackedEntityModule().reservedValueManager().blockingDownloadAllReservedValues(20); List<TrackedEntityAttributeReservedValue> reservedValues = TrackedEntityAttributeReservedValueStore.create( databaseAdapter()).selectAll(); String value = d2.trackedEntityModule().reservedValueManager().blockingGetValue("xs8A6tQJY0s", orgunitUid); } // @Test public void reserve_and_count() { login(); syncMetadata(); TrackedEntityAttribute trackedEntityAttribute = d2.trackedEntityModule().trackedEntityAttributes().byGenerated().isTrue().one().blockingGet(); d2.trackedEntityModule().reservedValueManager() .blockingDownloadReservedValues(trackedEntityAttribute.uid(), numberToReserve); int attributeCount = d2.trackedEntityModule().reservedValueManager() .blockingCount(trackedEntityAttribute.uid(), null); int attributeAndOrgUnitCount = d2.trackedEntityModule().reservedValueManager() .blockingCount(trackedEntityAttribute.uid(), orgunitUid); assertThat(attributeCount).isEqualTo(numberToReserve); assertThat(attributeAndOrgUnitCount).isEqualTo(numberToReserve); } private void login() { if (!d2.userModule().isLogged().blockingGet()) { d2.userModule().logIn(username, password, url).blockingGet(); } } private void syncMetadata() { d2.metadataModule().blockingDownload(); } }
package netdiscovery; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.Inet6Address; import java.net.InetSocketAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketAddress; import java.net.SocketException; import java.util.Enumeration; import java.util.Timer; import java.util.TimerTask; import plugincore.PluginEngine; import com.google.gson.Gson; import shared.MsgEvent; import shared.MsgEventType; public class DiscoveryClientWorkerIPv6 { private DatagramSocket c; //private MulticastSocket c; private Gson gson; public Timer timer; public int discoveryTimeout; public String multiCastNetwork; public DiscoveryClientWorkerIPv6(int discoveryTimeout, String multiCastNetwork) { gson = new Gson(); //timer = new Timer(); //timer.scheduleAtFixedRate(new StopListnerTask(), 1000, discoveryTimeout); this.discoveryTimeout = discoveryTimeout; this.multiCastNetwork = multiCastNetwork; } public class IPv6Responder implements Runnable { DatagramSocket socket = null; DatagramPacket packet = null; String hostAddress = null; Gson gson; public IPv6Responder(DatagramSocket socket, DatagramPacket packet, String hostAddress) { this.socket = socket; this.packet = packet; this.hostAddress = hostAddress; gson = new Gson(); } public void run() { //byte[] data = makeResponse(); // code not shown //We have a response System.out.println(getClass().getName() + ">>> Broadcast response from server: " + packet.getAddress().getHostAddress()); //Check if the message is correct //System.out.println(new String(receivePacket.getData())); String json = new String(packet.getData()).trim(); //String response = "region=region0,agent=agent0,recaddr=" + packet.getAddress().getHostAddress(); try { MsgEvent me = gson.fromJson(json, MsgEvent.class); if(me != null) { //System.out.println("RESPONCE: " + me.getParamsString()); String remoteAddress = packet.getAddress().getHostAddress(); if(remoteAddress.contains("%")) { String[] remoteScope = hostAddress.split("%"); remoteAddress = remoteScope[0]; } me.setParam("dst_ip", remoteAddress); me.setParam("dst_region", me.getParam("src_region")); me.setParam("dst_agent", me.getParam("src_agent")); PluginEngine.incomingCanidateBrokers.offer(me); } } catch(Exception ex) { System.out.println("DiscoveryClientWorker in loop 0" + ex.toString()); } } } class StopListnerTask extends TimerTask { public void run() { //user timer to close socket c.close(); timer.cancel(); } } public void discover() { // Find the server using UDP broadcast try { // Broadcast the message over all the network interfaces Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = (NetworkInterface) interfaces.nextElement(); //if (networkInterface.isLoopback() || !networkInterface.isUp()) { if (networkInterface.getDisplayName().startsWith("veth") || networkInterface.isLoopback() || !networkInterface.isUp() || !networkInterface.supportsMulticast() || networkInterface.isPointToPoint() || networkInterface.isVirtual()) { continue; // Don't want to broadcast to the loopback interface } if(networkInterface.supportsMulticast()) { for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { { try { //if((interfaceAddress.getAddress() instanceof Inet6Address) && !interfaceAddress.getAddress().isLinkLocalAddress()) if((interfaceAddress.getAddress() instanceof Inet6Address)) { //c = new MulticastSocket(null); c = new DatagramSocket(null); //c.setReuseAddress(true); //System.out.println("prebind1"); String hostAddress = interfaceAddress.getAddress().getHostAddress(); if(hostAddress.contains("%")) { String[] hostScope = hostAddress.split("%"); hostAddress = hostScope[0]; } SocketAddress sa = new InetSocketAddress(hostAddress,0); //System.out.println("prebind2"); c.bind(sa); //System.out.println("prebind3"); //start timer to clost discovery timer = new Timer(); timer.schedule(new StopListnerTask(), discoveryTimeout); MsgEvent sme = new MsgEvent(MsgEventType.DISCOVER,PluginEngine.region,PluginEngine.agent,PluginEngine.plugin,"Discovery request."); sme.setParam("broadcast_ip",multiCastNetwork); sme.setParam("src_region",PluginEngine.region); sme.setParam("src_agent",PluginEngine.agent); //me.setParam("clientip", packet.getAddress().getHostAddress()); // convert java object to JSON format, // and returned as JSON formatted string String sendJson = gson.toJson(sme); byte[] sendData = sendJson.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, Inet6Address.getByName(multiCastNetwork), 32005); c.send(sendPacket); System.out.println(getClass().getName() + ">>> Request packet sent to: " + multiCastNetwork + ": from : " + interfaceAddress.getAddress().getHostAddress()); while(!c.isClosed()) { try { byte[] recvBuf = new byte[15000]; DatagramPacket receivePacket = new DatagramPacket(recvBuf, recvBuf.length); c.receive(receivePacket); new Thread(new IPv6Responder(c,receivePacket,hostAddress)).start(); } catch(SocketException ex) { //eat message.. this should happen //System.out.println(ex.getMessage()); } catch(Exception ex) { System.out.println("DiscoveryClientWorkerIPv6 : discovery" + ex.getMessage()); } } //Close the port! } } catch (IOException ie) { //eat exception we are closing port //System.out.println("DiscoveryClientWorkerIPv6 : getDiscoveryMap IO Error : " + ie.getMessage()); } catch (Exception e) { System.out.println("DiscoveryClientWorkerIPv6 : getDiscoveryMap Error : " + e.toString()); } } } } //Wait for a response //c.close(); //System.out.println("CODY : Dicsicer Client Worker Engned!"); } } catch (Exception ex) { System.out.println("while not closed: " + ex.toString()); } } }
package nl.topicus.jdbc; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Statement; import java.util.Arrays; import java.util.Properties; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import com.google.auth.oauth2.AccessToken; import com.google.auth.oauth2.GoogleCredentials; import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.auth.oauth2.UserCredentials; import com.google.cloud.Timestamp; import com.google.cloud.spanner.DatabaseAdminClient; import com.google.cloud.spanner.DatabaseClient; import com.google.cloud.spanner.DatabaseId; import com.google.cloud.spanner.Operation; import com.google.cloud.spanner.Spanner; import com.google.cloud.spanner.SpannerException; import com.google.cloud.spanner.SpannerOptions; import com.google.cloud.spanner.SpannerOptions.Builder; import com.google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata; import nl.topicus.jdbc.MetaDataStore.TableKeyMetaData; import nl.topicus.jdbc.statement.CloudSpannerPreparedStatement; import nl.topicus.jdbc.statement.CloudSpannerStatement; import nl.topicus.jdbc.transaction.CloudSpannerTransaction; /** * JDBC Driver for Google Cloud Spanner. * * @author loite * */ public class CloudSpannerConnection extends AbstractCloudSpannerConnection { private final CloudSpannerDriver driver; private Spanner spanner; private String clientId; private DatabaseClient dbClient; private DatabaseAdminClient adminClient; private boolean autoCommit = true; private boolean closed; private boolean readOnly; private final String url; private final Properties suppliedProperties; private final boolean allowExtendedMode; private String simulateProductName; private String instanceId; private String database; private CloudSpannerTransaction transaction; private Timestamp lastCommitTimestamp; private MetaDataStore metaDataStore; CloudSpannerConnection(CloudSpannerDriver driver, String url, String projectId, String instanceId, String database, String credentialsPath, String oauthToken, boolean allowExtendedMode, Properties suppliedProperties) throws SQLException { this.driver = driver; this.instanceId = instanceId; this.database = database; this.url = url; this.allowExtendedMode = allowExtendedMode; this.suppliedProperties = suppliedProperties; try { Builder builder = SpannerOptions.newBuilder(); if (projectId != null) builder.setProjectId(projectId); GoogleCredentials credentials = null; if (credentialsPath != null) { credentials = getCredentialsFromFile(credentialsPath); builder.setCredentials(credentials); } else if (oauthToken != null) { credentials = getCredentialsFromOAuthToken(oauthToken); builder.setCredentials(credentials); } if (credentials != null) { if (credentials instanceof UserCredentials) { clientId = ((UserCredentials) credentials).getClientId(); } if (credentials instanceof ServiceAccountCredentials) { clientId = ((ServiceAccountCredentials) credentials).getClientId(); } } SpannerOptions options = builder.build(); spanner = options.getService(); dbClient = spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), instanceId, database)); adminClient = spanner.getDatabaseAdminClient(); transaction = new CloudSpannerTransaction(dbClient, this); metaDataStore = new MetaDataStore(this); } catch (Exception e) { throw new SQLException("Error when opening Google Cloud Spanner connection: " + e.getMessage(), e); } } public static GoogleCredentials getCredentialsFromOAuthToken(String oauthToken) { GoogleCredentials credentials = null; if (oauthToken != null && oauthToken.length() > 0) { credentials = new GoogleCredentials(new AccessToken(oauthToken, null)); } return credentials; } public static GoogleCredentials getCredentialsFromFile(String credentialsPath) throws IOException { if (credentialsPath == null || credentialsPath.length() == 0) throw new IllegalArgumentException("credentialsPath may not be null or empty"); GoogleCredentials credentials = null; File credentialsFile = new File(credentialsPath); if (!credentialsFile.isFile()) { throw new IOException( String.format("Error reading credential file %s: File does not exist", credentialsPath)); } try (InputStream credentialsStream = new FileInputStream(credentialsFile)) { credentials = GoogleCredentials.fromStream(credentialsStream, CloudSpannerOAuthUtil.HTTP_TRANSPORT_FACTORY); } return credentials; } public static String getServiceAccountProjectId(String credentialsPath) { String project = null; if (credentialsPath != null) { try (InputStream credentialsStream = new FileInputStream(credentialsPath)) { JSONObject json = new JSONObject(new JSONTokener(credentialsStream)); project = json.getString("project_id"); } catch (IOException | JSONException ex) { // ignore } } return project; } Spanner getSpanner() { return spanner; } public void setSimulateProductName(String productName) { this.simulateProductName = productName; } public Void executeDDL(String sql) throws SQLException { try { Operation<Void, UpdateDatabaseDdlMetadata> operation = adminClient.updateDatabaseDdl(instanceId, database, Arrays.asList(sql), null); operation = operation.waitFor(); return operation.getResult(); } catch (SpannerException e) { throw new SQLException("Could not execute DDL statement " + sql + ": " + e.getLocalizedMessage(), e); } } String getProductName() { if (simulateProductName != null) return simulateProductName; return "Google Cloud Spanner"; } @Override public CloudSpannerStatement createStatement() throws SQLException { return new CloudSpannerStatement(this, dbClient); } @Override public CloudSpannerPreparedStatement prepareStatement(String sql) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public CallableStatement prepareCall(String sql) throws SQLException { throw new SQLFeatureNotSupportedException(); } @Override public String nativeSQL(String sql) throws SQLException { return sql; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { this.autoCommit = autoCommit; } @Override public boolean getAutoCommit() throws SQLException { return autoCommit; } @Override public void commit() throws SQLException { lastCommitTimestamp = transaction.commit(); } @Override public void rollback() throws SQLException { transaction.rollback(); } public CloudSpannerTransaction getTransaction() { return transaction; } @Override public void close() throws SQLException { transaction.rollback(); closed = true; driver.closeConnection(this); } @Override public boolean isClosed() throws SQLException { return closed; } @Override public CloudSpannerDatabaseMetaData getMetaData() throws SQLException { return new CloudSpannerDatabaseMetaData(this); } @Override public void setReadOnly(boolean readOnly) throws SQLException { if (transaction.isRunning()) throw new SQLException( "There is currently a transaction running. Commit or rollback the running transaction before changing read-only mode."); this.readOnly = readOnly; } @Override public boolean isReadOnly() throws SQLException { return readOnly; } @Override public void setTransactionIsolation(int level) throws SQLException { if (level != Connection.TRANSACTION_SERIALIZABLE) { throw new SQLException("Transaction level " + level + " is not supported. Only Connection.TRANSACTION_SERIALIZABLE is supported"); } } @Override public int getTransactionIsolation() throws SQLException { return Connection.TRANSACTION_SERIALIZABLE; } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return new CloudSpannerStatement(this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return new CloudSpannerStatement(this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return new CloudSpannerPreparedStatement(sql, this, dbClient); } public String getUrl() { return url; } public String getClientId() { return clientId; } @Override public boolean isValid(int timeout) throws SQLException { Statement statement = createStatement(); statement.setQueryTimeout(timeout); try (ResultSet rs = statement.executeQuery("SELECT 1")) { if (rs.next()) return true; } return false; } @Override public CloudSpannerArray createArrayOf(String typeName, Object[] elements) throws SQLException { return CloudSpannerArray.createArray(typeName, elements); } public TableKeyMetaData getTable(String name) throws SQLException { return metaDataStore.getTable(name); } public Properties getSuppliedProperties() { return suppliedProperties; } public boolean isAllowExtendedMode() { return allowExtendedMode; } /** * * @return The commit timestamp of the last transaction that committed * succesfully */ public Timestamp getLastCommitTimestamp() { return lastCommitTimestamp; } }
package ohtuhatut.controller; import ohtuhatut.domain.BookReference; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * * @author tuomokar */ @Controller public class DefaultController { @RequestMapping("*") public String index() { return "index"; } }
package org.animotron.statement.operator; import org.animotron.exception.AnimoException; import org.animotron.expression.Expression; import org.animotron.graph.GraphOperation; import org.animotron.graph.index.AbstractIndex; import org.animotron.manipulator.OnQuestion; import org.animotron.manipulator.PFlow; import org.animotron.manipulator.QCAVector; import org.animotron.statement.AbstractStatement; import org.animotron.statement.instruction.Instruction; import org.animotron.statement.string.LOWER_CASE; import org.animotron.statement.string.UPPER_CASE; import org.neo4j.graphdb.Node; import org.neo4j.graphdb.Relationship; import org.neo4j.graphdb.index.IndexManager; import org.neo4j.index.bdbje.BerkeleyDbIndexImplementation; import java.io.IOException; import java.math.BigDecimal; import java.util.Stack; import static org.animotron.graph.AnimoGraph.createNode; import static org.animotron.graph.AnimoGraph.execute; import static org.animotron.graph.Properties.VALUE; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class VALUE extends AbstractStatement implements Prepare { public final static VALUE _ = new VALUE(); private Processor processor = null; private VALUE() { super("value"); } private AbstractIndex<Node> value = new AbstractIndex<Node>(name()) { @Override public void init(IndexManager index) { init(index.forNodes(name, BerkeleyDbIndexImplementation.DEFAULT_CONFIG)); } }; public void init(IndexManager index) { value.init(index); if (processor != null) processor.thread.interrupt(); processor = new Processor(); } public void add(Node n, Object reference) { value.add(n, reference); } public Node get(Object name) { return value.get(name); } @Override protected Node createChild(Object reference, boolean ready, boolean ignoreNotFound) throws AnimoException { if (reference == null) return createNode(); Node child = createNode(); VALUE.set(child, reference); add(child, reference); return child; } @Override public Object reference(Relationship r) { return reference(r.getEndNode()); } public Object reference(Node n) { if (VALUE.has(n)) { return VALUE.get(n); } else { return null; } } public static Object value(Object o) { if (o instanceof String) { String s = (String) o; try { return Long.valueOf(s); } catch (NumberFormatException el) { try { return Double.valueOf(s); } catch (NumberFormatException ed) { if (Boolean.FALSE.toString().equals(s)) return Boolean.FALSE; if (Boolean.TRUE.toString().equals(s)) return Boolean.TRUE; return s; } } } return o; } public static Number number(Object o) { if (o instanceof Number) { return (Number)o; } else if (o instanceof String) { String s = (String) o; try { return Long.valueOf(s); } catch (NumberFormatException el) { try { return Double.valueOf(s); } catch (NumberFormatException ed) { if (Boolean.FALSE.toString().equals(s)) return BigDecimal.ZERO; else if (Boolean.TRUE.toString().equals(s)) return BigDecimal.ONE; else if (s.isEmpty()) return BigDecimal.ZERO; } } } throw new IllegalArgumentException("This is not a number '"+o+"'."); } public void shutdown() throws IOException, InterruptedException { processor.toProcess(null); processor.thread.join(); } @Override public OnQuestion onPrepareQuestion() { return new Prepare(); } class Prepare extends OnQuestion { public boolean needAnswer() { return false; } @Override public void act(PFlow pf) throws Throwable { processor.toProcess(pf.getVector()); } } class Processor implements Runnable { // Pipe pipe = Pipe.newInstance(); Stack<QCAVector> stack = new Stack<QCAVector>(); Thread thread; public Processor() { thread = new Thread(this); thread.start(); } public void toProcess(QCAVector v) throws IOException { //XXX: put mark here? // pipe.write(v); stack.add(v); } @Override public void run() { QCAVector v; // while ((v = pipe.take()) != null) { while (true) { while (stack.empty()) { try { Thread.sleep(50); } catch (Exception e) {} } v = stack.pop(); if (v == null) return; // process(v.getClosest()); } } private void process(final Relationship r) { Object o = reference(r); if (o instanceof String) { final String s = (String) o; // System.out.println("-> "+Thread.currentThread()+" "+s); if (s.length() > 1) { try { execute(new GraphOperation<Void>() { @Override public Void execute() throws Throwable { Relationship x = new Expression() { private Expression letter(final String uuid1, final Instruction c, final String uuid2) { return new Expression() { @Override public void build() throws Throwable { builder.start(DEF._, uuid1); builder._(uuid1); builder.start(AN._); builder._(REF._, "letter"); builder.end(); builder.start(AN._); builder._(REF._, c.name()); builder.start(AN._); builder._(REF._, uuid2); builder.end(); builder.end(); builder.end(); } }; } private void step(final String value, final int i) throws AnimoException, IOException { if (i >= 0) { Relationship def; final String s = String.valueOf(value.charAt(i)); // System.out.println("> "+Thread.currentThread()+" "+expression.charAt(i)); if (!s.toLowerCase().equals(s.toUpperCase())) { Relationship l = __(letter(s.toLowerCase(), UPPER_CASE._, s.toUpperCase())); Relationship u = __(letter(s.toUpperCase(), LOWER_CASE._, s.toLowerCase())); def = s.equals(s.toLowerCase()) ? l : u; } else { def = new Expression() { @Override public void build() throws Throwable { builder.start(DEF._); builder._(s); builder.end(); } }; } builder.start(AN._); try { builder._(REF._, def.getEndNode()); } catch (Exception e) { System.out.println(""+Thread.currentThread()+" "+e.getMessage()); e.printStackTrace(); } step(value, i-1); builder.end(); } } @Override public void build() throws Throwable { builder.start(DEF._); step(s, s.length()-1); builder.end(); } }; Node proxy = createNode(); r.getEndNode().createRelationshipTo(proxy, AN._); proxy.createRelationshipTo(x.getEndNode(), REF._); return null; } }); } catch (Throwable e) { // TODO: handle exception e.printStackTrace(); } } } } } public static Expression expression(final Object o) { return new Expression() { @Override public void build() throws Throwable { builder._(o); } }; } //used by tests public void waitToBeEmpty() { while (!processor.stack.isEmpty()) try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); } } }
package com.ingidear.webview; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ProgressBar; import android.widget.Toast; import com.ingidear.webview.utilidades.FakeR; public class WebViewActivity extends Activity { private String TAG = WebViewActivity.class.getSimpleName(); private ProgressBar progress; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FakeR fakeR = new FakeR(getApplication().getApplicationContext()); requestWindowFeature(Window.FEATURE_ACTION_BAR); setContentView(fakeR.getId("layout", "activity_webview")); webView = (WebView) this.findViewById(fakeR.getId("id", "webview")); progress = (ProgressBar) findViewById(fakeR.getId("id", "progressBar")); progress.setVisibility(View.GONE); String url = "https: String nombreApp = "WebViewPlugin"; String color = "#FFff0000"; Bundle datos; datos = getIntent().getExtras(); if (datos != null) { try { url = datos.getString("Url"); nombreApp = datos.getString("NombreApp"); color = datos.getString("colorBar"); } catch (NullPointerException e) { Log.e(TAG, "Error " + e); } } /** * Se habilita javascript */ WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); try { if (getActionBar()!=null) { getActionBar().setHomeButtonEnabled(true); getActionBar().setDisplayHomeAsUpEnabled(true); getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor(color))); getActionBar().setTitle(nombreApp); } } catch (Exception ex) { Log.e(TAG, "" + ex); } /** * Se lanza el listener de la pagina web */ webView.setWebViewClient(new MWebViewClient()); //Se carga la url webView.loadUrl(url); } @Override public boolean onCreateOptionsMenu(Menu menu) { return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } private class MWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { logToast("MWebViewClient " + url); view.loadUrl(url); return true; } /** * Listener cuando la pagina termina de cargar * * @param view * @param url */ @Override public void onPageFinished(WebView view, String url) { progress.setVisibility(View.GONE); WebViewActivity.this.progress.setProgress(100); logToast("onPageFinished " + url); super.onPageFinished(view, url); } /** * Listener cuando se empieza a cargar la pagina * * @param view * @param url * @param favicon */ @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { progress.setVisibility(View.VISIBLE); WebViewActivity.this.progress.setProgress(0); logToast("onPageStarted " + url); super.onPageStarted(view, url, favicon); } } private void logToast(String mensaje) { CharSequence text = mensaje; int duration = Toast.LENGTH_SHORT; Log.d(TAG, mensaje); Toast toast = Toast.makeText(this, text, duration); //toast.show(); } }
package be.kuleuven.cs.distrinet.rejuse.predicate; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.List; import be.kuleuven.cs.distrinet.rejuse.java.collections.CollectionOperator; /*@ model import org.jutil.java.collections.Collections; @*/ /** * <p>A class of predicates. A predicate is a function that evaluate to <code>true</code> or * <code>false</code> for an object.</p> * * <p>The Predicate class is an implementation of the <em>Strategy</em> * pattern. You can write code that works with predicates (e.g. filters, * quantifiers,...) in general, and the user of that code can write the specific * predicate.</p> * * <p>The <a href="ForAll.html"><code>ForAll</code></a>, * <a href="Exists.html"><code>Exists</code></a>, * <a href="Counter.html"><code>Counter</code></a> and * <a href="Filter.html"><code>Filter</code></a> classes are replaced by * instance methods of this class so they can be removed in the future. * The recommended use for operations that do not work on collections is to * use an internal iterator (like the forall,... method of this class) in the * objects that contain the information. This was not possible for collections * since we don't have access to the source code, and so these methods are * put in this class.</p> * * <p>Typically, this class will be used as an anonymous inner class as follows:</p> * <pre><code> * Predicate myPredicate = new AbstractPredicate() { * /oo * o also public behavior * o * o post postcondition; * o/ * public boolean eval(T o) throws MyException { * //calculate boolean value * //using the given object * } * * }; * </code></pre> * * <p><code>AbstractPredicate</code> implements all methods of this interface except for * <a href="Predicate.html#eval(Object)"><code>eval()</code></a>.</p> * * <p>If your predicate does not throw an exception, you should use * <a href="TotalPredicate.html"><code>TotalPredicate</code></a>, so users * of your predicate won't have to write try-catch constructions when no * exceptions can be thrown.</p> * * <p>In case your predicate doesn't wrap another one, use <a href="PrimitivePredicate.html"><code>PrimitivePredicate</code></a>. If it also doesn't throw * exceptions, extend <a href="PrimitiveTotalPredicate.html"><code>PrimitiveTotalPredicate</code></a>.</p> */ public interface Predicate<T> extends CollectionOperator { /** * Evaluate this Predicate for the given object. * * @param object The object for which this Predicate must be evaluated. In general, * because collections can contain null, this might be null. */ public /*@ pure @*/ abstract boolean eval(T object) throws Exception; /** * Check wether or not the given collection contains an object for which * this predicate evaluates to <code>true</code>. * * @param collection The collection which has to be searched for an object * for which this Predicate evaluates to <code>true</code>. */ /*@ @ public behavior @ @ post collection != null ==> \result == (\exists Object o; Collections.containsExplicitly(collection, o); eval(o) == true); @ post collection == null ==> \result == false; @ @ signals (ConcurrentModificationException) @ (* The collection was modified while accumulating *); @ signals (Exception) (collection != null) && @ (\exists Object o; @ (collection != null) && @ Collections.containsExplicitly(collection, o); @ ! isValidElement(o)); @*/ public /*@ pure @*/ boolean exists(Collection<T> collection) throws ConcurrentModificationException, Exception; /** * Check wether or not this Predicate evaluates to <code>true</code> * for all object in the given collection. * * @param collection The collection of which one wants to know if all object * evaluate to <code>true</code> for this Predicate. */ /*@ @ public behavior @ @ post collection != null ==> \result == (\forall Object o; Collections.containsExplicitly(collection, o); eval(o) == true); @ post collection == null ==> \result == true; @ @ signals (ConcurrentModificationException) @ (* The collection was modified while accumulating *); @ signals (Exception) (collection != null) && @ (\exists Object o; @ (collection != null) && @ Collections.containsExplicitly(collection, o); @ ! isValidElement(o)); @*/ public /*@ pure @*/ boolean forAll(Collection<T> collection) throws ConcurrentModificationException, Exception; /** * Count the number of object in the given collection for which this * Predicate evaluates to <code>true</code>. * * @param collection The collection for which the number of object evaluating to * <code>true</code> for this Predicate must be counted. */ /*@ @ public behavior @ @ post collection != null ==> \result == (\num_of Object o; @ Collections.containsExplicitly(collection,o); @ eval(o) == true); @ post collection == null ==> \result == 0; @ @ signals (ConcurrentModificationException) @ (* The collection was modified while accumulating *); @ signals (Exception) (collection != null) && @ (\exists Object o; @ (collection != null) && @ Collections.containsExplicitly(collection, o); @ ! isValidElement(o)); @*/ public /*@ pure @*/ int count(Collection<T> collection) throws ConcurrentModificationException, Exception; /** * <p>Remove all objects for which this Predicate evaluates to <code>false</code> * from the given collection.</p> * * <p>If you want to remove all object for which this Predicate evaluates * to <code>true</code>, wrap a <code>Not</code> predicate around this predicate, and * perform the filter using that predicate. For example:</p> * <pre><code> * new Not(myPredicate).filter(collection); * </code></pre> * * @param collection The collection to be filtered. */ /*@ @ public behavior @ @ // All object that evaluate to false have been removed. @ post collection != null ==> (\forall Object o; Collections.containsExplicitly(collection, o); eval(o) == true); @ // No new objects have been put in the collection, and object that evaluate to true @ // remain untouched. @ post collection != null ==> (\forall Object o; \old(Collections.containsExplicitly(collection, o)); @ (eval(o) == true) ==> @ ( @ Collections.nbExplicitOccurrences(o, collection) == @ \old(Collections.nbExplicitOccurrences(o, collection)) @ ) @ ); @ @ signals (ConcurrentModificationException) @ (* The collection was modified while accumulating *); @ // If a Exception occurs, nothing will happen. @ signals (Exception) (collection != null) && @ (\exists Object o; @ (collection != null) && @ Collections.containsExplicitly(collection, o); @ ! isValidElement(o)); @*/ public <X extends T> void filter(Collection<X> collection) throws ConcurrentModificationException, Exception; /** * Return the subpredicates of this Predicate. */ /*@ @ public behavior @ @ post \result != null; @ post ! \result.contains(null); @ // There may be no loops @ post ! \result.contains(this); @*/ // public /*@ pure @*/ List<Predicate<T>> getSubPredicates(); /** * Check whether or not this Predicate equals another object * * @param other The object to compare this Predicate with. */ /*@ @ also public behavior @ @ post \result == (other instanceof Predicate) && @ (\forall Object o; ; @ ((Predicate)other).isValidElement(o) == isValidElement(o) && @ ((Predicate)other).isValidElement(o) ==> ((Predicate)other).eval(o) == eval(o)); @*/ public /*@ pure @*/ boolean equals(Object other); /** * Return the size of this Predicate. */ /*@ @ public behavior @ @ post \result == getSubPredicates().size(); @*/ // public /*@ pure @*/ int nbSubPredicates(); public <X extends T> List<X> filteredList(Collection<X> collection) throws Exception; }
package org.apache.ibatis.jdbc; import static java.util.Arrays.asList; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; public class DataSourceUtils { /** * For each type, the supported DatabaseProductNameS * * TODO is this useful? */ private static Map<String, Collection<String>> TYPE_NAME = new HashMap<String, Collection<String>>(); /** * For each DatabaseProductName, the related type */ private static Map<String, String> NAME_TYPE = new HashMap<String, String>(); static { register("cache", "Cache"); register("db2", "DB2", "DB2 (DataDirect)"); register("generic", "DB2 for AS/400 (JTOpen)", "JDBC/ODBC Bridge", "McKoi"); register("firebird", "Firebird"); register("frontbase", "FrontBase"); register("neoview", "HP Neoview"); register("hsql", "HSQLDB server", "HSQLDB embedded"); register("h2", "H2 server", "H2 embedded"); register("informix", "Informix", "Informix (DataDirect)"); register("derby", "JavaDB/Derby server", "JavaDB/Derby embedded"); register("jdatastore", "JDataStore"); register("maxdb", "MaxDB"); register("mimer", "Mimer"); register("mysql", "MySQL"); register("netezza", "Netezza"); register("oracle", "Oracle Thin", "Oracle OCI", "Oracle (DataDirect)"); register("pervasive", "Pervasive"); register("postgresql", "PostgreSQL"); register("progress", "Progress"); register("sqlite", "SQLite"); register("sqlserver", "SQL Server (DataDirect)", "SQL Server (jTDS)", "SQL Server (Microsoft JDBC Driver)", "SQL Server 2008 (Microsoft JDBC Driver)" ); register("sybase-ase", "Sybase ASE (jTDS)", "Sybase ASE (JConnect)", "Sybase SQL Anywhere (JConnect)"); register("sybase", "Sybase (DataDirect)"); } private static void register(String type, String...databaseProductNames) { TYPE_NAME.put(type, asList(databaseProductNames)); for (String databaseProductName : databaseProductNames) { NAME_TYPE.put(databaseProductName, type); } } public static String getDatabaseName(DataSource dataSource) { Connection con = null; try { con = dataSource.getConnection(); if (con == null) { throw new RuntimeException("Connection returned by DataSource [" + dataSource + "] was null"); } DatabaseMetaData metaData = con.getMetaData(); if (metaData == null) { throw new RuntimeException("DatabaseMetaData returned by Connection [" + con + "] was null"); } String productName = metaData.getDatabaseProductName(); return NAME_TYPE.get(productName); } catch (SQLException e) { throw new RuntimeException("Could not get database product name", e); } finally { if (con != null) { try { con.close(); } catch (SQLException e) { // ignored } } } } }
package ch.ffhs.esa.bewegungsmelder.activities; import android.os.Bundle; import android.os.Vibrator; import android.app.Activity; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import ch.ffhs.esa.bewegungsmelder.R; import ch.ffhs.esa.bewegungsmelder.helpers.Helper; import ch.ffhs.esa.bewegungsmelder.helpers.KontaktDBHelper; import ch.ffhs.esa.bewegungsmelder.receivers.SMSReceiver; import ch.ffhs.esa.bewegungsmelder.services.LocationService; import ch.ffhs.esa.bewegungsmelder.services.MotionDetectionService; import ch.ffhs.esa.bewegungsmelder.services.SMSSenderTimerService; import ch.ffhs.esa.bewegungsmelder.services.ServerService; import java.util.ArrayList; public class MainActivity extends Activity { public static final String MODE = "ch.ffhs.esa.bewegungsmelder.MODE"; private static final String TAG = MainActivity.class.getSimpleName(); boolean motionServiceRunning = false; private static final int RESULT_SETTINGS = 1; private float latitude = 0; private float longitude = 0; private float accuracy = 0; private boolean dayMode = true; private SMSReceiver smsReceiver = new SMSReceiver(); @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "Method: onCreate"); // Starting the SMS Receiver // KoM 2013-12-23 Log.d(TAG, "Registering SMS Receiver!"); registerReceiver(smsReceiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED")); // Starting the Server Service // KoM 2013-12-23 Log.d(TAG, "Starting the Server Service!"); Intent i = new Intent(this, ServerService.class); startService(i); // Starting the Resend Service // KoM 2013-01-04 Log.d(TAG, "Starting the SMSSenderTimerService!"); Intent j = new Intent(this, SMSSenderTimerService.class); startService(j); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override /** * stop the services before destroying * * @author Michael Kohler */ public void onDestroy() { Log.d(TAG, "Method: onDestroy"); MainActivity.this.stopService(new Intent(MainActivity.this, MotionDetectionService.class)); MainActivity.this.stopService(new Intent(MainActivity.this, ServerService.class)); MainActivity.this.stopService(new Intent(MainActivity.this, SMSSenderTimerService.class)); unregisterReceiver(smsReceiver); 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 onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: Intent i = new Intent(this, UserSettingActivity.class); startActivityForResult(i, RESULT_SETTINGS); break; } return true; } public void onContactButtonClick(View view) { Intent intent = new Intent(this, AddContact.class); startActivity(intent); } public void onModeButtonClicked(View view){ String buttonModeLabel; Button buttonMode = (Button) findViewById(R.id.buttonMode); if(dayMode){ dayMode = false; buttonModeLabel = "Nachtmodus"; } else{ dayMode = true; buttonModeLabel = "Tagmodus"; } buttonMode.setText(buttonModeLabel); } /** * * @author Ralf Wittich */ public void onSupervisionButtonClicked(View view) { /* Test if service running */ motionServiceRunning = isServiceRunning(); // Stop if running if(motionServiceRunning){ disableSupervision(); } // Start if not running else{ enableSupervision(); } } // Receiver des MotionDetection Services public class MotionDetectionStatusReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(MotionDetectionService.MOTION_DETECTION_ACTION)){ Log.d(TAG, "MotionDetection Broadcast received!!!"); Bundle bundle = intent.getExtras(); if (bundle != null){ Log.d(TAG, "bundle != null"); String timeLeft = (String) bundle.get("TIME_LEFT"); String textMsg = "Status: " + (String) bundle.get("TIMER_RUNNING_STR") + " Time left: " + timeLeft; TextView textViewTimeLeft = (TextView) findViewById(R.id.textViewTimeLeft); textViewTimeLeft.setText(timeLeft); Log.d(TAG, textMsg); // set progress bar accordingly ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar); progressBar.setProgress((Integer) bundle.get("TIMER_PROGRESS_LEVEL")); Log.d(TAG, "Progress Bar Set"); // stop service if(!(Boolean)bundle.get("TIMER_RUNNING_BOOL")){ context.stopService(new Intent(context, MotionDetectionService.class)); context.unregisterReceiver(MotionDetectionStatusReceiver.this); Log.d(TAG, "Broadcast receiver unregistered, service stopped!"); runLocationService(); } } else{ Log.d(TAG, "Timer_Stopped"); context.unregisterReceiver(MotionDetectionStatusReceiver.this); } } } } private boolean isServiceRunning(){ boolean rs = false; ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); for(RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)){ if(MotionDetectionService.class.getName().equals(service.service.getClassName())){ rs = true; } } return rs; } private void enableSupervision() { Log.d(TAG, "Method: enableSupervision"); ((TextView) findViewById(R.id.labelTopLeft)).setText(R.string.supervision_running); ((Button) findViewById(R.id.buttonToggleSupervision)).setText(R.string.stop_supervision); Log.d(TAG, "Starting motion service!"); // Register MotionDetectionReceiver MotionDetectionStatusReceiver br = new MotionDetectionStatusReceiver(); registerReceiver(br, new IntentFilter(MotionDetectionService.MOTION_DETECTION_ACTION)); Intent i = new Intent(this, MotionDetectionService.class); i.putExtra("MODE", dayMode); // Day or Night Mode startService(i); } private void disableSupervision() { Log.d(TAG, "Method: disableSupervision"); ((TextView) findViewById(R.id.labelTopLeft)).setText(R.string.supervision_stopped); ((Button) findViewById(R.id.buttonToggleSupervision)).setText(R.string.start_supervision); Log.d(TAG, "Stopping motion service!"); stopService(new Intent(this, MotionDetectionService.class)); motionServiceRunning = false; TextView textViewTimeLeft = (TextView) findViewById(R.id.textViewTimeLeft); textViewTimeLeft.setText("-"); } // Setzt die Positionsdaten, wird aufgerufen, wenn die Accuracy ok ist. private void setPositionData(float lat, float lon, float acc){ latitude = lat; longitude = lon; accuracy = acc; Log.d(TAG, "Location Set: Lat: " + latitude + " Long: " + longitude + " Accuracy: " +accuracy); } private void runLocationService() { Log.d(TAG, "Getting Position..."); // Register LocationReceiver LocationReceiver lr = new LocationReceiver(); registerReceiver(lr, new IntentFilter(LocationService.LOCATION_ACTION)); startService(new Intent(this, LocationService.class)); } // Receiver des Location Services public class LocationReceiver extends BroadcastReceiver{ float mLat = 0.0f; float mLong = 0.0f; float mAcc = 0.0f; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(LocationService.LOCATION_ACTION)){ Log.d(TAG, "Location Broadcast received!!!"); Bundle bundle = intent.getExtras(); if (bundle != null){ Log.d(TAG, "bundle != null"); mAcc = bundle.getFloat("ACCURACY"); Log.d(TAG, "Location: Lat: " + mLat + " Long: " + mLong + " Accuracy: " + mAcc); // wait for accurate signal, setPosition, stop service, unregister Broadcast receiver // 9999 if no accurate position can be found if(mAcc < 20 || mAcc == 9999){ mLat = bundle.getFloat("LATITUDE"); mLong = bundle.getFloat("LONGITUDE"); setPositionData(mLat, mLong, mAcc); ArrayList<String> phoneNumbers = new KontaktDBHelper(MainActivity.this).getAllContactsNumbers(); if (phoneNumbers.size() > 0) { handleEmergencySMS(phoneNumbers.get(0)); } else { Toast.makeText(context, "KEIN KONTAKT ERFASST -> KEINE SMS GESENDET!", Toast.LENGTH_SHORT).show(); } context.stopService(new Intent(context, LocationService.class)); context.unregisterReceiver(LocationReceiver.this); Log.d(TAG, "Broadcast receiver unregistered, service stopped! Accuracy: " +mAcc); } } } } } /** * facilitates the emergency button click * * @author Michael Kohler * @param View view the View from which this function is called */ public void onEmergencyButtonClicked(View view) { ArrayList<String> phoneNumbers = new KontaktDBHelper(MainActivity.this).getAllContactsNumbers(); if (phoneNumbers.size() > 0) { SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this); String emergencyHandlingPref = sharedPref.getString("pref_direktruf_aktion", "SMS"); if (emergencyHandlingPref.equals("CALL")) { Helper.call(phoneNumbers.get(0), MainActivity.this); } else { runLocationService(); } } else { Toast.makeText(this, "KEIN KONTAKT ERFASST -> KEINE SMS GESENDET!", Toast.LENGTH_SHORT).show(); } } /** * handles the emergency SMS case * * @author Michael Kohler * @param String aPhoneNumber phone number of the recipient */ private void handleEmergencySMS(String aPhoneNumber) { // accuracy 9999 is set after 20 position changes w/o reaching acc < 20 String acc = ""; if(accuracy == 9999){ acc = "Position ungenau!!!"; }; String emergencyMessage = "Notruf! " + acc + " Position: https://maps.google.com/maps?q=" + Float.toString(latitude) +","+ Float.toString(longitude) + ".. Bitte mit einer SMS mit OK als Text bestaetigen."; Helper.setEmergencyMessage(emergencyMessage, this); // save emergencyMessage for later Helper.setEmergencyOngoing(true, this); Helper.setEmergencyConfirmed(false, this); Log.d(TAG, "Sending SMS: Number: " + aPhoneNumber + " Content: " + emergencyMessage); Helper.sendEmergencySMS(aPhoneNumber, emergencyMessage); Context context = getApplicationContext(); Toast.makeText(context, "Message sent!", Toast.LENGTH_LONG).show(); Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(500); } }
package org.apdplat.word.util; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author */ public class DirectoryWatcher { private static final Logger LOGGER = LoggerFactory.getLogger(DirectoryWatcher.class); private WatchService watchService = null; private final Map<WatchKey, Path> directories = new HashMap<>(); private static ExecutorService EXECUTOR_SERVICE = null; private WatchEvent.Kind<?>[] events; public static DirectoryWatcher getDirectoryWatcher(final WatcherCallback watcherCallback, WatchEvent.Kind<?>... events){ if("true".equals(WordConfTools.get("auto.detect", "true"))){ return new DirectoryWatcher(watcherCallback, events); } LOGGER.warn("word.local.confauto.detect=true"); return new DirectoryWatcher(){ @Override public void close() {} @Override public void watchDirectoryTree(Path path) {} @Override public void watchDirectoryTree(String path) {} @Override public void watchDirectory(Path path) {} @Override public void watchDirectory(String path) {} }; } private DirectoryWatcher(){} private DirectoryWatcher(final WatcherCallback watcherCallback, WatchEvent.Kind<?>... events){ try { if(events.length == 0){ throw new RuntimeException("StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE"); } synchronized(DirectoryWatcher.class){ if(EXECUTOR_SERVICE == null){ EXECUTOR_SERVICE = Executors.newCachedThreadPool(); } } this.events = new WatchEvent.Kind<?>[events.length]; int i=0; for(WatchEvent.Kind<?> event : events){ this.events[i++] = event; LOGGER.info(""+event.name()); } watchService = FileSystems.getDefault().newWatchService(); EXECUTOR_SERVICE.submit(new Runnable(){ @Override public void run() { watch(watcherCallback); } }); } catch (IOException ex) { LOGGER.error("", ex); throw new RuntimeException(ex); } } /** * * @param path */ public void watchDirectory(String path) { watchDirectory(Paths.get(path)); } /** * * @param path */ public void watchDirectory(Path path) { registerDirectory(path); } /** * * @param path */ public void watchDirectoryTree(String path) { watchDirectoryTree(Paths.get(path)); } /** * * @param path */ public void watchDirectoryTree(Path path) { registerDirectoryTree(path); } public void close(){ EXECUTOR_SERVICE.shutdown(); } /** * * @param watcherCallback */ private void watch(WatcherCallback watcherCallback){ try { while (true) { final WatchKey key = watchService.take(); if(key == null){ continue; } for (WatchEvent<?> watchEvent : key.pollEvents()) { final WatchEvent.Kind<?> kind = watchEvent.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; //path final Path contextPath = watchEventPath.context(); LOGGER.info("contextPath:"+contextPath); final Path directoryPath = directories.get(key); LOGGER.info("directoryPath:"+directoryPath); final Path absolutePath = directoryPath.resolve(contextPath); LOGGER.info("absolutePath:"+absolutePath); LOGGER.info("kind:"+kind); switch (kind.name()) { case "ENTRY_CREATE": if (Files.isDirectory(absolutePath, LinkOption.NOFOLLOW_LINKS)) { LOGGER.info("" + absolutePath); registerDirectoryTree(absolutePath); }else{ LOGGER.info("" + absolutePath); } break; case "ENTRY_DELETE": LOGGER.info("" + absolutePath); break; case "ENTRY_MODIFY": LOGGER.info("" + absolutePath); break; } watcherCallback.execute(kind, absolutePath.toAbsolutePath().toString()); } boolean valid = key.reset(); if (!valid) { if(directories.get(key) != null){ LOGGER.info(""+directories.get(key)); directories.remove(key); } } } } catch (InterruptedException ex) { LOGGER.info(""); } finally{ try { watchService.close(); LOGGER.info(""); } catch (IOException ex) { LOGGER.error("", ex); } } } /** * * @param path */ private void registerDirectoryTree(Path path) { try { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { registerDirectory(dir); return FileVisitResult.CONTINUE; } }); } catch (IOException ex) { LOGGER.error("" + path.toAbsolutePath(), ex); } } /** * * @param path */ private void registerDirectory(Path path) { try { LOGGER.info(":" + path); WatchKey key = path.register(watchService, events); directories.put(key, path); } catch (IOException ex) { LOGGER.error("" + path.toAbsolutePath(), ex); } } public static void main(String[] args) { DirectoryWatcher dictionaryWatcher = new DirectoryWatcher(new WatcherCallback(){ private long lastExecute = System.currentTimeMillis(); @Override public void execute(WatchEvent.Kind<?> kind, String path) { if(System.currentTimeMillis() - lastExecute > 1000){ lastExecute = System.currentTimeMillis(); System.out.println(""+kind.name()+" ,"+path); } } }, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); //DIC... dictionaryWatcher.watchDirectoryTree("d:/DIC"); //DIC2 dictionaryWatcher.watchDirectory("d:/DIC2"); } public static interface WatcherCallback{ public void execute(WatchEvent.Kind<?> kind, String path); } }
package org.ranksys.lda; import cc.mallet.pipe.Noop; import cc.mallet.topics.ParallelTopicModel; import cc.mallet.types.Alphabet; import cc.mallet.types.FeatureSequence; import cc.mallet.types.Instance; import cc.mallet.types.InstanceList; import es.uam.eps.ir.ranksys.fast.preference.FastPreferenceData; import java.io.IOException; import java.util.Iterator; import static java.util.stream.IntStream.range; public class LDAModelEstimator { /** * Estimate a topic model for collaborative filtering data. * * @param <U> user type * @param <I> item type * @param preferences preference data * @param k number of topics * @param alpha alpha in model * @param beta beta in model * @param numIterations number of iterations * @param burninPeriod burnin period * @return a topic model * @throws IOException when internal IO error occurs */ public static <U, I> ParallelTopicModel estimate(FastPreferenceData<U, I> preferences, int k, double alpha, double beta, int numIterations, int burninPeriod) throws IOException { ParallelTopicModel topicModel = new ParallelTopicModel(k, alpha * k, beta); topicModel.addInstances(new LDAInstanceList<>(preferences)); topicModel.setTopicDisplay(numIterations + 1, 0); topicModel.setNumIterations(numIterations); topicModel.setBurninPeriod(burninPeriod); topicModel.setNumThreads(Runtime.getRuntime().availableProcessors()); topicModel.estimate(); return topicModel; } private static class LDAAlphabet extends Alphabet { private final int numItems; public LDAAlphabet(int numItems) { this.numItems = numItems; } @Override public int size() { return numItems; } } private static class LDAInstanceList<U, I> extends InstanceList { private final FastPreferenceData<U, I> preferences; private final Alphabet alphabet; public LDAInstanceList(FastPreferenceData<U, I> preferences) { super(new Noop()); this.preferences = preferences; this.alphabet = new LDAAlphabet(preferences.numItems()); } @Override public Iterator<Instance> iterator() { Iterator<Instance> iterator = preferences.getAllUidx() .mapToObj(preferences::getUidxPreferences) .map(userPreferences -> { FeatureSequence sequence = new FeatureSequence(alphabet); userPreferences.forEach(pref -> { range(0, (int) pref.v).forEach(i -> sequence.add(pref.idx)); }); return new Instance(sequence, null, null, null); }) .iterator(); return iterator; } @Override public Alphabet getDataAlphabet() { return alphabet; } } }
package com.redhat.ceylon.compiler.metadata.java; // stef: disabled because the compiler doesn't let us use it otherwise //@Target(ElementType.PARAMETER) public @interface Name { String value() default ""; }
package org.codehaus.plexus.util; import java.io.File; import java.util.StringTokenizer; import java.util.Vector; /** * <p>This is a utility class used by selectors and DirectoryScanner. The * functionality more properly belongs just to selectors, but unfortunately * DirectoryScanner exposed these as protected methods. Thus we have to * support any subclasses of DirectoryScanner that may access these methods. * </p> * <p>This is a Singleton.</p> * * @author Arnout J. Kuiper * <a href="mailto:ajkuiper@wxs.nl">ajkuiper@wxs.nl</a> * @author Magesh Umasankar * @author <a href="mailto:bruce@callenish.com">Bruce Atherton</a> * @since 1.5 * @version $Id$ */ public final class SelectorUtils { public static final String PATTERN_HANDLER_PREFIX = "["; public static final String PATTERN_HANDLER_SUFFIX = "]"; public static final String REGEX_HANDLER_PREFIX = "%regex" + PATTERN_HANDLER_PREFIX; public static final String ANT_HANDLER_PREFIX = "%ant" + PATTERN_HANDLER_PREFIX; private static SelectorUtils instance = new SelectorUtils(); /** * Private Constructor */ private SelectorUtils() { } /** * Retrieves the manager of the Singleton. */ public static SelectorUtils getInstance() { return instance; } /** * Tests whether or not a given path matches the start of a given * pattern up to the first "**". * <p> * This is not a general purpose test and should only be used if you * can live with false positives. For example, <code>pattern=**\a</code> * and <code>str=b</code> will yield <code>true</code>. * * @param pattern The pattern to match against. Must not be * <code>null</code>. * @param str The path to match, as a String. Must not be * <code>null</code>. * * @return whether or not a given path matches the start of a given * pattern up to the first "**". */ public static boolean matchPatternStart( String pattern, String str ) { return matchPatternStart( pattern, str, true ); } /** * Tests whether or not a given path matches the start of a given * pattern up to the first "**". * <p> * This is not a general purpose test and should only be used if you * can live with false positives. For example, <code>pattern=**\a</code> * and <code>str=b</code> will yield <code>true</code>. * * @param pattern The pattern to match against. Must not be * <code>null</code>. * @param str The path to match, as a String. Must not be * <code>null</code>. * @param isCaseSensitive Whether or not matching should be performed * case sensitively. * * @return whether or not a given path matches the start of a given * pattern up to the first "**". */ public static boolean matchPatternStart( String pattern, String str, boolean isCaseSensitive ) { if ( pattern.length() > ( REGEX_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1 ) && pattern.startsWith( REGEX_HANDLER_PREFIX ) && pattern.endsWith( PATTERN_HANDLER_SUFFIX ) ) { // FIXME: ICK! But we can't do partial matches for regex, so we have to reserve judgement until we have // a file to deal with, or we can definitely say this is an exclusion... return true; } else { if ( pattern.length() > ( ANT_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1 ) && pattern.startsWith( ANT_HANDLER_PREFIX ) && pattern.endsWith( PATTERN_HANDLER_SUFFIX ) ) { pattern = pattern.substring( ANT_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length() ); } String altStr = str.replace( '\\', '/' ); return matchAntPathPatternStart( pattern, str, File.separator, isCaseSensitive ) || matchAntPathPatternStart( pattern, altStr, "/", isCaseSensitive ); } } private static boolean matchAntPathPatternStart( String pattern, String str, String separator, boolean isCaseSensitive ) { // When str starts with a File.separator, pattern has to start with a // File.separator. // When pattern starts with a File.separator, str has to start with a // File.separator. if ( str.startsWith( separator ) != pattern.startsWith( separator ) ) { return false; } Vector patDirs = tokenizePath( pattern, separator ); Vector strDirs = tokenizePath( str, separator ); int patIdxStart = 0; int patIdxEnd = patDirs.size() - 1; int strIdxStart = 0; int strIdxEnd = strDirs.size() - 1; // up to first '**' while ( patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd ) { String patDir = (String) patDirs.elementAt( patIdxStart ); if ( patDir.equals( "**" ) ) { break; } if ( !match( patDir, (String) strDirs.elementAt( strIdxStart ), isCaseSensitive ) ) { return false; } patIdxStart++; strIdxStart++; } if ( strIdxStart > strIdxEnd ) { // String is exhausted return true; } else if ( patIdxStart > patIdxEnd ) { // String not exhausted, but pattern is. Failure. return false; } else { // pattern now holds ** while string is not exhausted // this will generate false positives but we can live with that. return true; } } /** * Tests whether or not a given path matches a given pattern. * * @param pattern The pattern to match against. Must not be * <code>null</code>. * @param str The path to match, as a String. Must not be * <code>null</code>. * * @return <code>true</code> if the pattern matches against the string, * or <code>false</code> otherwise. */ public static boolean matchPath( String pattern, String str ) { return matchPath( pattern, str, true ); } /** * Tests whether or not a given path matches a given pattern. * * @param pattern The pattern to match against. Must not be * <code>null</code>. * @param str The path to match, as a String. Must not be * <code>null</code>. * @param isCaseSensitive Whether or not matching should be performed * case sensitively. * * @return <code>true</code> if the pattern matches against the string, * or <code>false</code> otherwise. */ public static boolean matchPath( String pattern, String str, boolean isCaseSensitive ) { return matchPath( pattern, str, File.separator, isCaseSensitive ); } public static boolean matchPath( String pattern, String str, String separator, boolean isCaseSensitive ) { if ( pattern.length() > ( REGEX_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1 ) && pattern.startsWith( REGEX_HANDLER_PREFIX ) && pattern.endsWith( PATTERN_HANDLER_SUFFIX ) ) { pattern = pattern.substring( REGEX_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length() ); return str.matches( pattern ); } else { if ( pattern.length() > ( ANT_HANDLER_PREFIX.length() + PATTERN_HANDLER_SUFFIX.length() + 1 ) && pattern.startsWith( ANT_HANDLER_PREFIX ) && pattern.endsWith( PATTERN_HANDLER_SUFFIX ) ) { pattern = pattern.substring( ANT_HANDLER_PREFIX.length(), pattern.length() - PATTERN_HANDLER_SUFFIX.length() ); } return matchAntPathPattern( pattern, str, separator, isCaseSensitive ); } } private static boolean matchAntPathPattern( String pattern, String str, String separator, boolean isCaseSensitive ) { // When str starts with a separator, pattern has to start with a // separator. // When pattern starts with a separator, str has to start with a // separator. if ( str.startsWith( separator ) != pattern.startsWith( separator ) ) { return false; } Vector patDirs = tokenizePath( pattern, separator ); Vector strDirs = tokenizePath( str, separator ); int patIdxStart = 0; int patIdxEnd = patDirs.size() - 1; int strIdxStart = 0; int strIdxEnd = strDirs.size() - 1; // up to first '**' while ( patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd ) { String patDir = (String) patDirs.elementAt( patIdxStart ); if ( patDir.equals( "**" ) ) { break; } if ( !match( patDir, (String) strDirs.elementAt( strIdxStart ), isCaseSensitive ) ) { patDirs = null; strDirs = null; return false; } patIdxStart++; strIdxStart++; } if ( strIdxStart > strIdxEnd ) { // String is exhausted for ( int i = patIdxStart; i <= patIdxEnd; i++ ) { if ( !patDirs.elementAt( i ).equals( "**" ) ) { patDirs = null; strDirs = null; return false; } } return true; } else { if ( patIdxStart > patIdxEnd ) { // String not exhausted, but pattern is. Failure. patDirs = null; strDirs = null; return false; } } // up to last '**' while ( patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd ) { String patDir = (String) patDirs.elementAt( patIdxEnd ); if ( patDir.equals( "**" ) ) { break; } if ( !match( patDir, (String) strDirs.elementAt( strIdxEnd ), isCaseSensitive ) ) { patDirs = null; strDirs = null; return false; } patIdxEnd strIdxEnd } if ( strIdxStart > strIdxEnd ) { // String is exhausted for ( int i = patIdxStart; i <= patIdxEnd; i++ ) { if ( !patDirs.elementAt( i ).equals( "**" ) ) { patDirs = null; strDirs = null; return false; } } return true; } while ( patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd ) { int patIdxTmp = -1; for ( int i = patIdxStart + 1; i <= patIdxEnd; i++ ) { if ( patDirs.elementAt( i ).equals( "**" ) ) { patIdxTmp = i; break; } } if ( patIdxTmp == patIdxStart + 1 ) { // '**/**' situation, so skip one patIdxStart++; continue; } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd int patLength = ( patIdxTmp - patIdxStart - 1 ); int strLength = ( strIdxEnd - strIdxStart + 1 ); int foundIdx = -1; strLoop: for ( int i = 0; i <= strLength - patLength; i++ ) { for ( int j = 0; j < patLength; j++ ) { String subPat = (String) patDirs.elementAt( patIdxStart + j + 1 ); String subStr = (String) strDirs.elementAt( strIdxStart + i + j ); if ( !match( subPat, subStr, isCaseSensitive ) ) { continue strLoop; } } foundIdx = strIdxStart + i; break; } if ( foundIdx == -1 ) { patDirs = null; strDirs = null; return false; } patIdxStart = patIdxTmp; strIdxStart = foundIdx + patLength; } for ( int i = patIdxStart; i <= patIdxEnd; i++ ) { if ( !patDirs.elementAt( i ).equals( "**" ) ) { patDirs = null; strDirs = null; return false; } } return true; } /** * Tests whether or not a string matches against a pattern. * The pattern may contain two special characters:<br> * '*' means zero or more characters<br> * '?' means one and only one character * * @param pattern The pattern to match against. * Must not be <code>null</code>. * @param str The string which must be matched against the pattern. * Must not be <code>null</code>. * * @return <code>true</code> if the string matches against the pattern, * or <code>false</code> otherwise. */ public static boolean match( String pattern, String str ) { return match( pattern, str, true ); } /** * Tests whether or not a string matches against a pattern. * The pattern may contain two special characters:<br> * '*' means zero or more characters<br> * '?' means one and only one character * * @param pattern The pattern to match against. * Must not be <code>null</code>. * @param str The string which must be matched against the pattern. * Must not be <code>null</code>. * @param isCaseSensitive Whether or not matching should be performed * case sensitively. * * * @return <code>true</code> if the string matches against the pattern, * or <code>false</code> otherwise. */ public static boolean match( String pattern, String str, boolean isCaseSensitive ) { char[] patArr = pattern.toCharArray(); char[] strArr = str.toCharArray(); int patIdxStart = 0; int patIdxEnd = patArr.length - 1; int strIdxStart = 0; int strIdxEnd = strArr.length - 1; char ch; boolean containsStar = false; for ( int i = 0; i < patArr.length; i++ ) { if ( patArr[i] == '*' ) { containsStar = true; break; } } if ( !containsStar ) { // No '*'s, so we make a shortcut if ( patIdxEnd != strIdxEnd ) { return false; // Pattern and string do not have the same size } for ( int i = 0; i <= patIdxEnd; i++ ) { ch = patArr[i]; if ( ch != '?' && !equals( ch, strArr[i], isCaseSensitive ) ) { return false; // Character mismatch } } return true; // String matches against pattern } if ( patIdxEnd == 0 ) { return true; // Pattern contains only '*', which matches anything } // Process characters before first star while ( ( ch = patArr[patIdxStart] ) != '*' && strIdxStart <= strIdxEnd ) { if ( ch != '?' && !equals( ch, strArr[strIdxStart], isCaseSensitive ) ) { return false; // Character mismatch } patIdxStart++; strIdxStart++; } if ( strIdxStart > strIdxEnd ) { // All characters in the string are used. Check if only '*'s are // left in the pattern. If so, we succeeded. Otherwise failure. for ( int i = patIdxStart; i <= patIdxEnd; i++ ) { if ( patArr[i] != '*' ) { return false; } } return true; } // Process characters after last star while ( ( ch = patArr[patIdxEnd] ) != '*' && strIdxStart <= strIdxEnd ) { if ( ch != '?' && !equals( ch, strArr[strIdxEnd], isCaseSensitive ) ) { return false; // Character mismatch } patIdxEnd strIdxEnd } if ( strIdxStart > strIdxEnd ) { // All characters in the string are used. Check if only '*'s are // left in the pattern. If so, we succeeded. Otherwise failure. for ( int i = patIdxStart; i <= patIdxEnd; i++ ) { if ( patArr[i] != '*' ) { return false; } } return true; } // process pattern between stars. padIdxStart and patIdxEnd point // always to a '*'. while ( patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd ) { int patIdxTmp = -1; for ( int i = patIdxStart + 1; i <= patIdxEnd; i++ ) { if ( patArr[i] == '*' ) { patIdxTmp = i; break; } } if ( patIdxTmp == patIdxStart + 1 ) { // Two stars next to each other, skip the first one. patIdxStart++; continue; } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd int patLength = ( patIdxTmp - patIdxStart - 1 ); int strLength = ( strIdxEnd - strIdxStart + 1 ); int foundIdx = -1; strLoop: for ( int i = 0; i <= strLength - patLength; i++ ) { for ( int j = 0; j < patLength; j++ ) { ch = patArr[patIdxStart + j + 1]; if ( ch != '?' && !equals( ch, strArr[strIdxStart + i + j], isCaseSensitive ) ) { continue strLoop; } } foundIdx = strIdxStart + i; break; } if ( foundIdx == -1 ) { return false; } patIdxStart = patIdxTmp; strIdxStart = foundIdx + patLength; } // All characters in the string are used. Check if only '*'s are left // in the pattern. If so, we succeeded. Otherwise failure. for ( int i = patIdxStart; i <= patIdxEnd; i++ ) { if ( patArr[i] != '*' ) { return false; } } return true; } /** * Tests whether two characters are equal. */ private static boolean equals( char c1, char c2, boolean isCaseSensitive ) { if ( c1 == c2 ) { return true; } if ( !isCaseSensitive ) { // NOTE: Try both upper case and lower case as done by String.equalsIgnoreCase() if ( Character.toUpperCase( c1 ) == Character.toUpperCase( c2 ) || Character.toLowerCase( c1 ) == Character.toLowerCase( c2 ) ) { return true; } } return false; } /** * Breaks a path up into a Vector of path elements, tokenizing on * <code>File.separator</code>. * * @param path Path to tokenize. Must not be <code>null</code>. * * @return a Vector of path elements from the tokenized path */ public static Vector tokenizePath( String path ) { return tokenizePath( path, File.separator ); } public static Vector tokenizePath( String path, String separator ) { Vector ret = new Vector(); StringTokenizer st = new StringTokenizer( path, separator ); while ( st.hasMoreTokens() ) { ret.addElement( st.nextToken() ); } return ret; } /** * Returns dependency information on these two files. If src has been * modified later than target, it returns true. If target doesn't exist, * it likewise returns true. Otherwise, target is newer than src and * is not out of date, thus the method returns false. It also returns * false if the src file doesn't even exist, since how could the * target then be out of date. * * @param src the original file * @param target the file being compared against * @param granularity the amount in seconds of slack we will give in * determining out of dateness * @return whether the target is out of date */ public static boolean isOutOfDate( File src, File target, int granularity ) { if ( !src.exists() ) { return false; } if ( !target.exists() ) { return true; } if ( ( src.lastModified() - granularity ) > target.lastModified() ) { return true; } return false; } /** * "Flattens" a string by removing all whitespace (space, tab, linefeed, * carriage return, and formfeed). This uses StringTokenizer and the * default set of tokens as documented in the single arguement constructor. * * @param input a String to remove all whitespace. * @return a String that has had all whitespace removed. */ public static String removeWhitespace( String input ) { StringBuffer result = new StringBuffer(); if ( input != null ) { StringTokenizer st = new StringTokenizer( input ); while ( st.hasMoreTokens() ) { result.append( st.nextToken() ); } } return result.toString(); } }
package com.exedio.cope.pattern; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import com.exedio.cope.BooleanField; import com.exedio.cope.Cope; import com.exedio.cope.DataField; import com.exedio.cope.DateField; import com.exedio.cope.Item; import com.exedio.cope.ItemField; import com.exedio.cope.LongField; import com.exedio.cope.Model; import com.exedio.cope.Pattern; import com.exedio.cope.Query; import com.exedio.cope.SetValue; import com.exedio.cope.Type; import com.exedio.cope.Wrapper; import com.exedio.cope.util.ReactivationConstructorDummy; public final class Dispatcher extends Pattern { private static final String ENCODING = "utf8"; private final int failureLimit; private final int searchSize; private final BooleanField pending = new BooleanField().defaultTo(true); private final DateField successDate = new DateField().optional(); private final LongField successElapsed = new LongField().optional(); ItemField<?> failureParent = null; final DateField failureDate = new DateField().toFinal(); final LongField failureElapsed = new LongField(); final DataField failureCause = new DataField().toFinal(); Type<Failure> failureType = null; public Dispatcher() { this(5, 100); } public Dispatcher(final int maxFailures, final int searchSize) { this.failureLimit = maxFailures; this.searchSize = searchSize; if(maxFailures<1) throw new IllegalArgumentException("failureLimit must be greater zero, but was " + maxFailures + "."); if(searchSize<1) throw new IllegalArgumentException("searchSize must be greater zero, but was " + searchSize + "."); registerSource(pending); registerSource(successDate); } @Override public void initialize() { final String name = getName(); initialize(pending, name + "Pending"); initialize(successDate, name + "SuccessDate"); initialize(successElapsed, name + "SuccessElapsed"); final Type<?> type = getType(); failureParent = type.newItemField(ItemField.DeletePolicy.CASCADE).toFinal(); final LinkedHashMap<String, com.exedio.cope.Feature> features = new LinkedHashMap<String, com.exedio.cope.Feature>(); features.put("parent", failureParent); features.put("date", failureDate); features.put("elapsed", failureElapsed); features.put("cause", failureCause); failureType = newType(Failure.class, features, "Failure"); } public int getFailureLimit() { return failureLimit; } public int getSearchSize() { return searchSize; } public BooleanField getPending() { return pending; } public DateField getSuccessDate() { return successDate; } public LongField getSuccessElapsed() { return successElapsed; } public <P extends Item> ItemField<P> getFailureParent(final Class<P> parentClass) { assert failureParent!=null; return failureParent.as(parentClass); } public DateField getFailureDate() { return failureDate; } public LongField getFailureElapsed() { return failureElapsed; } public DataField getFailureCause() { return failureCause; } public Type<Failure> getFailureType() { assert failureType!=null; return failureType; } @Override public List<Wrapper> getWrappers() { final ArrayList<Wrapper> result = new ArrayList<Wrapper>(); result.addAll(super.getWrappers()); result.add(new Wrapper( void.class, "dispatch", "Dispatch by {0}.", "dispatch"). setStatic()); result.add(new Wrapper( boolean.class, "isPending", "Returns, whether this item is yet to be dispatched by {0}.", "getter")); result.add(new Wrapper( Date.class, "getSuccessDate", "Returns the date, this item was successfully dispatched by {0}.", "getter")); result.add(new Wrapper( Long.class, "getSuccessElapsed", "Returns the milliseconds, this item needed to be successfully dispatched by {0}.", "getter")); result.add(new Wrapper( Wrapper.makeType(List.class, Failure.class), "getFailures", "Returns the failed attempts to dispatch this item by {0}.", "getter")); result.add(new Wrapper( Wrapper.makeType(ItemField.class, Wrapper.ClassVariable.class), "getFailureParent", "Returns the parent field of the failure type of {0}.", "parent"). setMethodWrapperPattern("{1}FailureParent"). setStatic()); return Collections.unmodifiableList(result); } public <P extends Item> void dispatch(final Class<P> parentClass) { final Type<P> type = getType().castType(parentClass); final Type.This<P> typeThis = type.getThis(); final Model model = type.getModel(); final String featureID = getID(); P lastDispatched = null; while(true) { final List<P> toDispatch; try { model.startTransaction(featureID + " search"); final Query<P> q = type.newQuery(pending.equal(true)); if(lastDispatched!=null) q.narrow(typeThis.greater(lastDispatched)); q.setOrderBy(typeThis, true); q.setLimit(0, searchSize); toDispatch = q.search(); model.commit(); } finally { model.rollbackIfNotCommitted(); } if(toDispatch.isEmpty()) break; for(final P item : toDispatch) { lastDispatched = item; final String itemID = item.getCopeID(); try { model.startTransaction(featureID + " dispatch " + itemID); if(!isPending(item)) { System.out.println("Already dispatched " + itemID + " by " + featureID + ", probably due to concurrent dispatching."); continue; } final long start = System.currentTimeMillis(); try { ((Dispatchable)item).dispatch(); final long elapsed = System.currentTimeMillis() - start; item.set( pending.map(false), successDate.map(new Date(start)), successElapsed.map(elapsed)); } catch(Exception cause) { final long elapsed = System.currentTimeMillis() - start; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final PrintStream out; try { out = new PrintStream(baos, false, ENCODING); } catch(UnsupportedEncodingException e) { throw new RuntimeException(e); } cause.printStackTrace(out); out.close(); final ItemField<P> failureParent = this.failureParent.as(parentClass); failureType.newItem( failureParent.map(item), failureDate.map(new Date(start)), failureElapsed.map(elapsed), failureCause.map(baos.toByteArray())); if(failureType.newQuery(failureParent.equal(item)).total()>=failureLimit) pending.set(item, false); } model.commit(); } finally { model.rollbackIfNotCommitted(); } } } } public boolean isPending(final Item item) { return pending.getMandatory(item); } public Date getSuccessDate(final Item item) { return successDate.get(item); } public Long getSuccessElapsed(final Item item) { return successElapsed.get(item); } public List<Failure> getFailures(final Item item) { return failureType.search(Cope.equalAndCast(failureParent, item), failureType.getThis(), true); } public static final class Failure extends Item { private static final long serialVersionUID = -1l; Failure(final SetValue[] setValues, final Type<? extends Item> type) { super(setValues, type); assert type!=null; } Failure(final ReactivationConstructorDummy reactivationDummy, final int pk, final Type<? extends Item> type) { super(reactivationDummy, pk, type); } public Dispatcher getPattern() { return (Dispatcher)getCopeType().getPattern(); } public Item getParent() { return getPattern().failureParent.get(this); } public Date getDate() { return getPattern().failureDate.get(this); } public long getElapsed() { return getPattern().failureElapsed.getMandatory(this); } public String getCause() { try { return new String(getPattern().failureCause.get(this).asArray(), ENCODING); } catch(UnsupportedEncodingException e) { throw new RuntimeException(e); } } } }
package com.brein.time.timeseries; import com.brein.time.exceptions.IllegalConfiguration; import java.io.Serializable; import java.util.Collection; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Supplier; import java.util.stream.StreamSupport; public class ContainerBucketTimeSeries<E extends Serializable & Collection<T>, T> extends BucketTimeSeries<E> { private static final long serialVersionUID = 1L; private final Supplier<E> supplier; public ContainerBucketTimeSeries(final Supplier<E> supplier, final BucketTimeSeriesConfig<E> config) { super(config); this.supplier = supplier; } public ContainerBucketTimeSeries(final Supplier<E> supplier, final BucketTimeSeriesConfig<E> config, final E[] timeSeries, final long now) { super(config, timeSeries, now); this.supplier = supplier; } public long[] createByContent(final ContainerBucketTimeSeries<E, T> timeSeries, final BiFunction<E, E, Long> create) { final ContainerBucketTimeSeries<E, T> syncedTs = sync(timeSeries, (ts) -> new ContainerBucketTimeSeries<>(ts.getSupplier(), ts.getConfig(), ts.timeSeries, ts.getNow())); final long[] result = new long[config.getTimeSeriesSize()]; for (int i = 0; i < config.getTimeSeriesSize(); i++) { final int idx = idx(currentNowIdx + i); final E coll = get(idx); final E syncedColl = syncedTs.get(syncedTs.idx(syncedTs.currentNowIdx + i)); final Long val = create.apply(coll, syncedColl); result[i] = val == null ? -1L : val; } return result; } public void combineByContent(final ContainerBucketTimeSeries<E, T> timeSeries, final BiConsumer<E, E> combine) throws IllegalConfiguration { combineByContent(timeSeries, (coll1, coll2) -> { final E in1, in2; if (coll1 == null && coll2 == null) { in1 = getSupplier().get(); in2 = getSupplier().get(); } else if (coll1 == null) { in1 = getSupplier().get(); in2 = coll2; } else if (coll2 == null) { in1 = coll1; in2 = getSupplier().get(); } else { in1 = coll1; in2 = coll2; } combine.accept(in1, in2); return in1; }); } public void combineByContent(final ContainerBucketTimeSeries<E, T> timeSeries, final BiFunction<E, E, E> combine) throws IllegalConfiguration { final ContainerBucketTimeSeries<E, T> syncedTs = sync(timeSeries, (ts) -> new ContainerBucketTimeSeries<>(ts.getSupplier(), ts.getConfig(), ts.timeSeries, ts.getNow())); for (int i = 0; i < config.getTimeSeriesSize(); i++) { final int idx = idx(currentNowIdx + i); final E coll = get(idx); final E syncedColl = syncedTs.get(syncedTs.idx(syncedTs.currentNowIdx + i)); final E result = combine.apply(coll, syncedColl); // let's see if the collection changed, if so we set it if (coll != result) { set(idx, result); } } } public void add(final long unixTimeStamp, final T value) { final int idx = handleDataUnixTimeStamp(unixTimeStamp); add(idx, value); } public void add(final int idx, final T value) { if (idx == -1) { return; } validateIdx(idx); getOrCreate(idx).add(value); } public int size(final int idx) { final Collection<T> coll = get(idx); return coll == null ? 0 : coll.size(); } public Supplier<E> getSupplier() { return supplier; } @SuppressWarnings("unchecked") public Class<E> getCollectionType() { return (Class<E>) supplier.get().getClass(); } @SuppressWarnings("unchecked") public Class<T> getCollectionContent() { final E res = StreamSupport.stream(this.spliterator(), false) .filter(coll -> coll != null && coll.stream() .filter(val -> val != null) .findFirst() .orElse(null) != null) .findFirst() .orElse(null); return res == null ? null : (Class<T>) res.stream().findFirst().get().getClass(); } protected E getOrCreate(final int idx) { final E coll = get(idx); if (coll == null) { final E newColl = supplier.get(); this.timeSeries[idx] = newColl; return newColl; } else { return coll; } } }
package com.dmdirc.ui.core.profiles; import com.dmdirc.config.profiles.Profile; import com.dmdirc.config.profiles.ProfileManager; import com.dmdirc.interfaces.ui.ProfilesDialogModel; import com.dmdirc.interfaces.ui.ProfilesDialogModelListener; import com.dmdirc.util.collections.ListenerList; import com.dmdirc.util.validators.FileNameValidator; import com.dmdirc.util.validators.IdentValidator; import com.dmdirc.util.validators.ListNotEmptyValidator; import com.dmdirc.util.validators.NotEmptyValidator; import com.dmdirc.util.validators.PermissiveValidator; import com.dmdirc.util.validators.Validator; import com.dmdirc.util.validators.ValidatorChain; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.SortedMap; import java.util.concurrent.ConcurrentSkipListMap; import javax.inject.Inject; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; public class CoreProfilesDialogModel implements ProfilesDialogModel { private final ListenerList listeners; private final ProfileManager profileManager; private final SortedMap<String, MutableProfile> profiles; private Optional<MutableProfile> selectedProfile = Optional.empty(); private Optional<String> selectedNickname = Optional.empty(); private Optional<String> selectedHighlight = Optional.empty(); @Inject public CoreProfilesDialogModel(final ProfileManager profileManager) { this.profileManager = profileManager; listeners = new ListenerList(); profiles = new ConcurrentSkipListMap<>(Comparator.naturalOrder()); } @Override public void loadModel() { profiles.clear(); profileManager.getProfiles().stream().map(MutableProfile::new).forEach(mp -> { profiles.put(mp.getName(), mp); listeners.getCallable(ProfilesDialogModelListener.class).profileAdded(mp); }); setSelectedProfile(Optional.ofNullable(Iterables.getFirst(profiles.values(), null))); } @Override public List<MutableProfile> getProfileList() { return ImmutableList.copyOf(profiles.values()); } @Override public Optional<MutableProfile> getProfile(final String name) { checkNotNull(name, "Name cannot be null"); return Optional.ofNullable(profiles.get(name)); } @Override public void addProfile(final String name, final String realname, final String ident, final List<String> nicknames) { checkNotNull(name, "Name cannot be null"); checkArgument(!profiles.containsKey(name), "Name cannot already exist"); final MutableProfile profile = new MutableProfile(name, realname, Optional.of(ident), nicknames); profiles.put(name, profile); listeners.getCallable(ProfilesDialogModelListener.class).profileAdded(profile); setSelectedProfile(Optional.of(profile)); } @Override public void removeProfile(final String name) { checkNotNull(name, "Name cannot be null"); checkArgument(profiles.containsKey(name), "profile must exist in list"); final MutableProfile profile = profiles.remove(name); if (getSelectedProfile().isPresent() && getSelectedProfile().get().equals(profile)) { setSelectedProfile(Optional.ofNullable(Iterables.getFirst(profiles.values(), null))); } listeners.getCallable(ProfilesDialogModelListener.class).profileRemoved(profile); } @Override public void save() { final List<Profile> profileList = Lists.newArrayList(profileManager.getProfiles()); profileList.forEach(profileManager::deleteProfile); profiles.values().forEach(p -> profileManager.addProfile( Profile.create(p.getName(), p.getRealname(), p.getIdent(), p.getNicknames(), p.getHighlights()))); } @Override public void setSelectedProfile(final Optional<MutableProfile> profile) { checkNotNull(profile, "profile cannot be null"); if (profile.isPresent()) { checkArgument(profiles.containsValue(profile.get()), "Profile must exist in list"); } if (!selectedProfile.equals(profile)) { selectedProfile = profile; listeners.getCallable(ProfilesDialogModelListener.class) .profileSelectionChanged(profile); } } @Override public Optional<MutableProfile> getSelectedProfile() { return selectedProfile; } @Override public Optional<String> getSelectedProfileName() { if (selectedProfile.isPresent()) { return Optional.of(selectedProfile.get().getName()); } return Optional.empty(); } @Override public void setSelectedProfileName(final Optional<String> name) { // TODO: should probably handle name being empty checkNotNull(name, "Name cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); selectedProfile.get().setName(name.orElse("")); listeners.getCallable(ProfilesDialogModelListener.class) .profileEdited(selectedProfile.get()); } @Override public Optional<String> getSelectedProfileRealname() { if (selectedProfile.isPresent()) { return Optional.of(selectedProfile.get().getRealname()); } return Optional.empty(); } @Override public void setSelectedProfileRealname(final Optional<String> realname) { checkNotNull(realname, "Realname cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); selectedProfile.get().setRealname(realname.orElse("")); listeners.getCallable(ProfilesDialogModelListener.class) .profileEdited(selectedProfile.get()); } @Override public Optional<String> getSelectedProfileIdent() { if (selectedProfile.isPresent()) { return selectedProfile.get().getIdent(); } return Optional.empty(); } @Override public void setSelectedProfileIdent(final Optional<String> ident) { checkNotNull(ident, "Ident cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); selectedProfile.get().setIdent(ident); listeners.getCallable(ProfilesDialogModelListener.class) .profileEdited(selectedProfile.get()); } @Override public Optional<List<String>> getSelectedProfileNicknames() { return selectedProfile.map(MutableProfile::getNicknames); } @Override public void setSelectedProfileNicknames(final Optional<List<String>> nicknames) { checkNotNull(nicknames, "nicknames cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); if (nicknames.isPresent()) { selectedProfile.get().setNicknames(nicknames.get()); } else { selectedProfile.get().setNicknames(Lists.newArrayList()); } listeners.getCallable(ProfilesDialogModelListener.class) .profileEdited(selectedProfile.get()); } @Override public void setSelectedProfileHighlights(final Optional<List<String>> highlights) { checkNotNull(highlights, "highlights cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); if (highlights.isPresent()) { selectedProfile.get().setHighlights(highlights.get()); } else { selectedProfile.get().setHighlights(Lists.newArrayList()); } listeners.getCallable(ProfilesDialogModelListener.class) .profileEdited(selectedProfile.get()); } @Override public void addSelectedProfileNickname(final String nickname) { checkNotNull(nickname, "Nickname cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); checkArgument(!selectedProfile.get().getNicknames().contains(nickname), "New nickname must not exist"); selectedProfile.get().addNickname(nickname); listeners.getCallable(ProfilesDialogModelListener.class) .selectedProfileNicknameAdded(nickname); } @Override public void removeSelectedProfileNickname(final String nickname) { checkNotNull(nickname, "Nickname cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); checkArgument(selectedProfile.get().getNicknames().contains(nickname), "Nickname must exist"); selectedProfile.get().removeNickname(nickname); listeners.getCallable(ProfilesDialogModelListener.class) .selectedProfileNicknameRemoved(nickname); } @Override public void editSelectedProfileNickname(final String oldName, final String newName) { checkNotNull(oldName, "Nickname cannot be null"); checkNotNull(newName, "Nickname cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); checkArgument(selectedProfile.get().getNicknames().contains(oldName), "Old nickname must exist"); checkArgument(!selectedProfile.get().getNicknames().contains(newName), "New nickname must not exist"); final int index = selectedProfile.get().getNicknames().indexOf(oldName); selectedProfile.get().setNickname(index, newName); selectedNickname = Optional.of(newName); listeners.getCallable(ProfilesDialogModelListener.class) .selectedProfileNicknameEdited(oldName, newName); } @Override public Optional<String> getSelectedProfileSelectedNickname() { return selectedNickname; } @Override public Optional<String> getSelectedProfileSelectedHighlight() { return selectedHighlight; } @Override public void setSelectedProfileSelectedNickname(final Optional<String> selectedNickname) { checkNotNull(selectedNickname, "Nickname cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); if (selectedNickname.isPresent()) { checkArgument(selectedProfile.get().getNicknames().contains(selectedNickname.get()), "Nickname must exist in nicknames list"); } this.selectedNickname = selectedNickname; listeners.getCallable(ProfilesDialogModelListener.class) .selectedNicknameChanged(selectedNickname); } @Override public void setSelectedProfileSelectedHighlight(final Optional<String> selectedHighlight) { checkNotNull(selectedHighlight, "Highlight cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); if (selectedHighlight.isPresent()) { checkArgument(selectedProfile.get().getHighlights().contains(selectedHighlight.get()), "Nickname must exist in nicknames list"); } this.selectedHighlight = selectedHighlight; listeners.getCallable(ProfilesDialogModelListener.class) .selectedHighlightChanged(selectedNickname); } @Override public void addListener(final ProfilesDialogModelListener listener) { checkNotNull(listener, "Listener must not be null"); listeners.add(ProfilesDialogModelListener.class, listener); } @Override public void removeListener(final ProfilesDialogModelListener listener) { checkNotNull(listener, "Listener must not be null"); listeners.remove(ProfilesDialogModelListener.class, listener); } @Override public boolean canSwitchProfiles() { return !selectedProfile.isPresent() || isSelectedProfileIdentValid() && isSelectedProfileNameValid() && isSelectedProfileNicknamesValid() && isSelectedProfileRealnameValid(); } @Override public boolean isSaveAllowed() { return isProfileListValid() && isSelectedProfileIdentValid() && isSelectedProfileNameValid() && isSelectedProfileNicknamesValid() && isSelectedProfileRealnameValid(); } @Override public boolean isSelectedProfileNicknamesValid() { return !getSelectedProfileNicknames().isPresent() || !getSelectedProfileNicknamesValidator() .validate(getSelectedProfileNicknames().get()).isFailure(); } @Override public boolean isSelectedProfileHighlightsValid() { return !getSelectedProfileHighlights().isPresent() || !getSelectedProfileHighlightsValidator().validate( getSelectedProfileHighlights().get()).isFailure(); } @Override public boolean isSelectedProfileIdentValid() { return !getSelectedProfileIdent().isPresent() || !getSelectedProfileIdentValidator().validate(getSelectedProfileIdent().get()) .isFailure(); } @Override public boolean isSelectedProfileRealnameValid() { return getSelectedProfileRealname().isPresent() || !getSelectedProfileRealnameValidator().validate(getSelectedProfileRealname().get()) .isFailure(); } @Override public boolean isSelectedProfileNameValid() { return getSelectedProfileName().isPresent() && !getSelectedProfileNameValidator().validate(getSelectedProfileName().get()) .isFailure(); } @Override public boolean isProfileListValid() { return !getProfileListValidator().validate(getProfileList()).isFailure(); } @Override public Validator<List<MutableProfile>> getProfileListValidator() { return new ListNotEmptyValidator<>(); } @Override public Validator<String> getSelectedProfileNameValidator() { return ValidatorChain.<String>builder() .addValidator(new EditSelectedProfileNameValidator(this)) .addValidator(new FileNameValidator()) .build(); } @Override public Validator<String> getNewProfileNameValidator() { return ValidatorChain.<String>builder() .addValidator(new NewProfileNameValidator(this)) .addValidator(new FileNameValidator()) .build(); } @Override public Validator<String> getSelectedProfileIdentValidator() { return new PermissiveValidator<>(); } @Override public Validator<String> getSelectedProfileRealnameValidator() { return new NotEmptyValidator(); } @Override public Validator<List<String>> getSelectedProfileNicknamesValidator() { return new ListNotEmptyValidator<>(); } @Override public Optional<List<String>> getSelectedProfileHighlights() { return selectedProfile.map(MutableProfile::getHighlights); } @Override public Validator<List<String>> getSelectedProfileHighlightsValidator() { return new PermissiveValidator<>(); } @Override public Validator<String> getSelectedProfileAddNicknameValidator() { return ValidatorChain.<String>builder() .addValidator(new NotEmptyValidator()) .addValidator(new AddNicknameValidator(this)) .build(); } @Override public Validator<String> getSelectedProfileEditNicknameValidator() { return ValidatorChain.<String>builder() .addValidator(new NotEmptyValidator()) .addValidator(new EditSelectedNicknameValidator(this)) .build(); } @Override public void addSelectedProfileHighlight(final String highlight) { checkNotNull(highlight, "highlight cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); if (!selectedProfile.get().getHighlights().contains(highlight)) { selectedProfile.get().addHighlight(highlight); listeners.getCallable(ProfilesDialogModelListener.class) .selectedProfileHighlightAdded(highlight); } } @Override public void removeSelectedProfileHighlight(final String highlight) { checkNotNull(highlight, "highlight cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); if (selectedProfile.get().getHighlights().contains(highlight)) { selectedProfile.get().removeHighlight(highlight); listeners.getCallable(ProfilesDialogModelListener.class) .selectedProfileHighlightRemoved(highlight); } } @Override public Validator<String> getSelectedProfileAddHighlightValidator() { return new NotEmptyValidator(); } @Override public void editSelectedProfileHighlight(final String oldHighlight, final String newHighlight) { checkNotNull(oldHighlight, "Highlight cannot be null"); checkNotNull(newHighlight, "Highlight cannot be null"); checkState(selectedProfile.isPresent(), "There must be a profile selected"); checkArgument(selectedProfile.get().getHighlights().contains(oldHighlight), "Old highlight must exist"); checkArgument(!selectedProfile.get().getHighlights().contains(newHighlight), "New highlight must not exist"); final int index = selectedProfile.get().getHighlights().indexOf(oldHighlight); selectedProfile.get().setHighlight(index, newHighlight); selectedHighlight = Optional.of(newHighlight); listeners.getCallable(ProfilesDialogModelListener.class) .selectedProfileHighlightEdited(oldHighlight, newHighlight); } @Override public Validator<String> getSelectedProfileEditHighlightValidator() { return new EditSelectedHighlightValidator(this); } @Override public Validator<List<String>> getNicknamesValidator() { return new ListNotEmptyValidator<>(); } @Override public Validator<List<String>> getHighlightsValidator() { return new PermissiveValidator<>(); } @Override public Validator<String> getRealnameValidator() { return new NotEmptyValidator(); } @Override public Validator<String> getIdentValidator() { return new IdentValidator(); } }
package org.davidmoten.rx.pool; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import com.github.davidmoten.guavamini.Preconditions; import io.reactivex.Scheduler; import io.reactivex.Single; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; public final class NonBlockingPool<T> implements Pool<T> { final Callable<? extends T> factory; final Predicate<? super T> healthy; final long idleTimeBeforeHealthCheckMs; final Consumer<? super T> disposer; final int maxSize; final long maxIdleTimeMs; final long checkoutRetryIntervalMs; final long returnToPoolDelayAfterHealthCheckFailureMs; final BiFunction<? super T, ? super Checkin, ? extends T> checkinDecorator; final Scheduler scheduler; final Action closeAction; private final AtomicReference<MemberSingle<T>> member = new AtomicReference<>(); private volatile boolean closed; NonBlockingPool(Callable<? extends T> factory, Predicate<? super T> healthy, Consumer<? super T> disposer, int maxSize, long returnToPoolDelayAfterHealthCheckFailureMs, long idleTimeBeforeHealthCheckMs, long maxIdleTimeMs, long checkoutRetryIntervalMs, BiFunction<? super T, ? super Checkin, ? extends T> checkinDecorator, Scheduler scheduler, Action closeAction) { Preconditions.checkNotNull(factory); Preconditions.checkNotNull(healthy); Preconditions.checkNotNull(disposer); Preconditions.checkArgument(maxSize > 0); Preconditions.checkArgument(returnToPoolDelayAfterHealthCheckFailureMs >= 0); Preconditions.checkNotNull(checkinDecorator); Preconditions.checkNotNull(scheduler); Preconditions.checkArgument(checkoutRetryIntervalMs >= 0, "checkoutRetryIntervalMs must be >=0"); Preconditions.checkNotNull(closeAction); Preconditions.checkArgument(maxIdleTimeMs >= 0, "maxIdleTime must be >=0"); this.factory = factory; this.healthy = healthy; this.disposer = disposer; this.maxSize = maxSize; this.returnToPoolDelayAfterHealthCheckFailureMs = returnToPoolDelayAfterHealthCheckFailureMs; this.idleTimeBeforeHealthCheckMs = idleTimeBeforeHealthCheckMs; this.maxIdleTimeMs = maxIdleTimeMs; this.checkoutRetryIntervalMs = checkoutRetryIntervalMs; this.checkinDecorator = checkinDecorator; this.scheduler = scheduler;// schedules retries this.closeAction = closeAction; } private MemberSingle<T> createMember() { return new MemberSingle<T>(this); } @Override public Single<Member<T>> member() { while (true) { MemberSingle<T> m = member.get(); if (m != null) return m; else { m = createMember(); if (member.compareAndSet(null, m)) { return m; } } } } public void checkin(Member<T> m) { MemberSingle<T> mem = member.get(); if (mem != null) { mem.checkin(m); } } @Override public void close() { closed = true; while (true) { MemberSingle<T> m = member.get(); if (m == null) { return; } else if (member.compareAndSet(m, null)) { m.close(); break; } } try { closeAction.run(); } catch (Exception e) { RxJavaPlugins.onError(e); } } boolean isClosed() { return closed; } public static <T> Builder<T> factory(Callable<T> factory) { return new Builder<T>().factory(factory); } public static class Builder<T> { private static final BiFunction<Object, Checkin, Object> DEFAULT_CHECKIN_DECORATOR = (x, y) -> x; private Callable<? extends T> factory; private Predicate<? super T> healthy = x -> true; private long idleTimeBeforeHealthCheckMs = 30; private Consumer<? super T> disposer = Consumers.doNothing(); private int maxSize = 10; private long returnToPoolDelayAfterHealthCheckFailureMs = 30000; private long checkoutRetryIntervalMs = 30000; private Scheduler scheduler = Schedulers.computation(); private long maxIdleTimeMs; @SuppressWarnings("unchecked") private BiFunction<? super T, ? super Checkin, ? extends T> checkinDecorator = (BiFunction<T, Checkin, T>) DEFAULT_CHECKIN_DECORATOR; private Action closeAction = () -> { }; private Builder() { } public Builder<T> factory(Callable<? extends T> factory) { Preconditions.checkNotNull(factory); this.factory = factory; return this; } public Builder<T> healthy(Predicate<? super T> healthy) { Preconditions.checkNotNull(healthy); this.healthy = healthy; return this; } public Builder<T> idleTimeBeforeHealthCheckMs(long value) { Preconditions.checkArgument(value >= 0); this.idleTimeBeforeHealthCheckMs = value; return this; } public Builder<T> idleTimeBeforeHealthCheck(long value, TimeUnit unit) { return idleTimeBeforeHealthCheckMs(unit.toMillis(value)); } public Builder<T> maxIdleTimeMs(long value) { this.maxIdleTimeMs = value; return this; } public Builder<T> maxIdleTime(long value, TimeUnit unit) { return maxIdleTimeMs(unit.toMillis(value)); } public Builder<T> checkoutRetryIntervalMs(long value) { checkoutRetryIntervalMs = value; return this; } public Builder<T> checkoutRetryInterval(long value, TimeUnit unit) { return checkoutRetryIntervalMs(unit.toMillis(value)); } public Builder<T> disposer(Consumer<? super T> disposer) { Preconditions.checkNotNull(disposer); this.disposer = disposer; return this; } public Builder<T> maxSize(int maxSize) { Preconditions.checkArgument(maxSize > 0); this.maxSize = maxSize; return this; } public Builder<T> returnToPoolDelayAfterHealthCheckFailureMs(long retryDelayMs) { Preconditions.checkArgument(retryDelayMs >= 0); this.returnToPoolDelayAfterHealthCheckFailureMs = retryDelayMs; return this; } public Builder<T> returnToPoolDelayAfterHealthCheckFailure(long value, TimeUnit unit) { Preconditions.checkNotNull(unit); return returnToPoolDelayAfterHealthCheckFailureMs(unit.toMillis(value)); } public Builder<T> scheduler(Scheduler scheduler) { Preconditions.checkNotNull(scheduler); this.scheduler = scheduler; return this; } public Builder<T> checkinDecorator(BiFunction<? super T, ? super Checkin, ? extends T> f) { this.checkinDecorator = f; return this; } public Builder<T> onClose(Action closeAction) { this.closeAction = closeAction; return this; } public NonBlockingPool<T> build() { return new NonBlockingPool<T>(factory, healthy, disposer, maxSize, returnToPoolDelayAfterHealthCheckFailureMs, idleTimeBeforeHealthCheckMs, maxIdleTimeMs, checkoutRetryIntervalMs, checkinDecorator, scheduler, closeAction); } } }
package com.hp.hpl.jena.db.impl; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.hp.hpl.jena.graph.*; import com.hp.hpl.jena.util.iterator.*; import com.hp.hpl.jena.shared.*; import com.hp.hpl.jena.vocabulary.RDF; /** * @author hkuno * @version $Version$ * * TripleStoreGraph is an abstract superclass for TripleStoreGraph * implementations. By "triple store," we mean that the subjects, predicate * and object URI's are stored in a single collection (denormalized). * */ public class SpecializedGraphReifier_RDB extends SpecializedGraphBase implements SpecializedGraphReifier { /** * holds PSet */ public PSet_ReifStore_RDB m_pset; /** * caches a copy of LSet properties */ public DBPropLSet m_dbPropLSet; /** * holds ID of graph in database (defaults to "0") */ public IDBID my_GID = null; // cache of reified statement status private ReifCacheMap m_reifCache; public PSet_ReifStore_RDB m_reif; // constructors /** * Constructor * Create a new instance of a TripleStore graph. */ SpecializedGraphReifier_RDB(DBPropLSet lProp, IPSet pSet, Integer dbGraphID) { m_pset = (PSet_ReifStore_RDB) pSet; m_dbPropLSet = lProp; my_GID = new DBIDInt(dbGraphID); m_reifCache = new ReifCacheMap(1); m_reif = (PSet_ReifStore_RDB) m_pset; } /** * Constructor * * Create a new instance of a TripleStore graph, taking * DBPropLSet and a PSet as arguments */ public SpecializedGraphReifier_RDB(IPSet pSet, Integer dbGraphID) { m_pset = (PSet_ReifStore_RDB) pSet; my_GID = new DBIDInt(dbGraphID); m_reifCache = new ReifCacheMap(1); m_reif = (PSet_ReifStore_RDB) m_pset; } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#add(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Triple, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag) */ public void add(Node n, Triple t, CompletionFlag complete) throws CannotReifyException { StmtMask same = new StmtMask(); StmtMask diff = new StmtMask(); ReifCache rs = m_reifCache.load(n, t, same, diff); if (rs == null) { m_reif.storeReifStmt(n, t, my_GID); } else { /* node already reifies something. is that a subset of triple t? */ if ( diff.hasNada() ) { boolean didUpdate = false; /* add whatever is missing to reify t */ if ( !same.hasSubj() ) { Triple st = new Triple(n,RDF.Nodes.subject,t.getSubject()); m_reif.updateFrag(n, st, new StmtMask(st), my_GID); didUpdate = true; } if ( !same.hasPred() ) { Triple pt = new Triple(n,RDF.Nodes.predicate,t.getPredicate()); m_reif.updateFrag(n, pt, new StmtMask(pt), my_GID); didUpdate = true; } if ( !same.hasObj() ) { Triple ot = new Triple(n,RDF.Nodes.object,t.getObject()); m_reif.updateFrag(n, ot, new StmtMask(ot), my_GID); didUpdate = true; } if ( !rs.mask.hasType() ) { Triple tt = new Triple(n,RDF.Nodes.type,RDF.Nodes.Statement); m_reif.updateFrag(n, tt, new StmtMask(tt), my_GID); didUpdate = true; } if ( didUpdate ) fragCompact(n); m_reifCache.flushAll(); } else { /* node reifies something that is not a subset of triple t */ if ( rs.mask.isStmt() ) throw new AlreadyReifiedException(n); else throw new CannotReifyException(n); } } complete.setDone(); } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#delete(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Triple, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag) */ public void delete(Node n, Triple t, CompletionFlag complete) { m_reifCache.flushAll(); m_reif.deleteReifStmt( n, t, my_GID); complete.setDone(); } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#contains(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.graph.Triple, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag) */ public boolean contains(Node n, Triple t, CompletionFlag complete) { if (true) throw new JenaException("SpecializedGraphReifier.contains called"); return false; } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#findReifiedNodes(com.hp.hpl.jena.graph.TripleMatch, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag) */ public ExtendedIterator findReifiedNodes(Triple t, CompletionFlag complete) { complete.setDone(); return m_reif.findReifStmtURIByTriple(t, my_GID); } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#findReifiedTriple(com.hp.hpl.jena.graph.Node, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag) */ public Triple findReifiedTriple(Node n, CompletionFlag complete) { ResultSetReifIterator it = m_reif.findReifStmt(n, true, my_GID, false); Triple res = null; if ( it.hasNext() ) { res = (Triple) it.next(); } complete.setDone(); return res; } /** Find all the triples corresponding to a given reified node. * In a perfect world, there would only ever be one, but when a user calls * add(Triple) there is nothing in RDF that prevents them from adding several * subjects,predicates or objects for the same statement. * * The resulting Triples may be incomplete, in which case some of the * nodes may be Node_ANY. * * For example, if an application had previously done: * add( new Triple( a, rdf.subject A )) and * add( new Triple( a, rdf.object B )) and * add( new Triple( a, rdf.object B2 )) * * Then the result of findReifiedTriple(a, flag) will be an iterator containing * Triple(A, ANY, B) and Triple(ANY, ANY, B2). * * @param n is the Node for which we are querying. * @param complete is true if we know we've returned all the triples which may exist. * @return ExtendedIterator. */ public ExtendedIterator findReifiedTriples(Node n, CompletionFlag complete) { complete.setDone(); return m_reif.findReifStmt(n, false, my_GID, true); } /** * Attempt to add all the triples from a graph to the specialized graph * * Caution - this call changes the graph passed in, deleting from * it each triple that is successfully added. * * Node that when calling add, if complete is true, then the entire * graph was added successfully and the graph g will be empty upon * return. If complete is false, then some triples in the graph could * not be added. Those triples remain in g after the call returns. * * If the triple can't be stored for any reason other than incompatability * (for example, a lack of disk space) then the implemenation should throw * a runtime exception. * * @param g is a graph containing triples to be added * @param complete is true if a subsequent call to contains(triple) will return true for any triple in g. */ public void add( Graph g, CompletionFlag complete ) { throw new AddDeniedException( "sorry, not implemented" ); } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraph#add(com.hp.hpl.jena.graph.Triple, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag) */ public void add(Triple frag, CompletionFlag complete) throws AlreadyReifiedException { StmtMask fragMask = new StmtMask(frag); if (fragMask.hasNada()) return; boolean fragHasType = fragMask.hasType(); Node stmtURI = frag.getSubject(); ReifCache cachedFrag = m_reifCache.load(stmtURI); if (cachedFrag == null) { // not in database m_reif.storeFrag(stmtURI, frag, fragMask, my_GID); complete.setDone(); } else { StmtMask cachedMask = cachedFrag.getStmtMask(); if (cachedMask.hasIntersect(fragMask)) { // see if this is a duplicate fragment boolean dup = fragHasType && cachedMask.hasType(); if (dup == false) { // not a type fragement; have to search db to check for dup ExtendedIterator it = m_reif.findFrag (stmtURI, frag, fragMask, my_GID); dup = it.hasNext(); if ( dup == false ) { if ( cachedMask.isStmt()) throw new AlreadyReifiedException(frag.getSubject()); // cannot perform a reificiation; store fragment m_reif.storeFrag(stmtURI, frag, fragMask, my_GID); m_reifCache.flush(cachedFrag); } } } else { // reification may be possible; update if possible, else compact if (cachedFrag.canMerge(fragMask)) { if ( cachedFrag.canUpdate(fragMask) ) { m_reif.updateFrag(stmtURI, frag, fragMask, my_GID); cachedFrag.update(fragMask); } else fragCompact(stmtURI); } else { // reification not possible m_reif.storeFrag(stmtURI, frag, fragMask, my_GID); } } } complete.setDone(); } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraph#delete(com.hp.hpl.jena.graph.Triple, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag) */ public void delete(Triple frag, CompletionFlag complete) { StmtMask fragMask = new StmtMask(frag); if (fragMask.hasNada()) return; boolean fragHasType = fragMask.hasType(); Node stmtURI = frag.getSubject(); ResultSetTripleIterator it = m_reif.findFrag(stmtURI, frag, fragMask, my_GID); if ( it.hasNext() ) { it.next(); Triple dbFrag = it.m_triple; StmtMask dbMask = new StmtMask(dbFrag); if ( dbMask.equals(fragMask) ) { /* last fragment in this tuple; can just delete it */ it.deleteRow(); it.close(); } else { /* remove fragment from row */ m_reif.nullifyFrag(stmtURI, fragMask, my_GID); /* compact remaining fragments, if possible */ it.close(); fragCompact(stmtURI); } // remove cache entry, if any ReifCache cachedFrag = m_reifCache.lookup(stmtURI); if ( cachedFrag != null ) m_reifCache.flush(cachedFrag); } complete.setDone(); } /* fragCompact * * Compact fragments for a given statement URI. * * first, find the unique row for stmtURI that with the HasType Statement fragment. * if no such row exists, we are done. then, get all fragments for stmtURI and * try to merge them with the hasType fragment, deleting each as they are merged. */ protected void fragCompact ( Node stmtURI ) { ResultSetReifIterator itHasType; Triple t; itHasType = m_reif.findReifStmt(stmtURI,true,my_GID, false); if ( itHasType.hasNext() ) { /* something to do */ t = (Triple) itHasType.next(); if ( itHasType.hasNext() ) throw new JenaException("Multiple HasType fragments for URI"); StmtMask htMask = new StmtMask(t); itHasType.close(); // now, look at fragments and try to merge them with the hasType fragement ResultSetReifIterator itFrag = m_reif.findReifStmt(stmtURI,false,my_GID, false); StmtMask upMask = new StmtMask(); while ( itFrag.hasNext() ) { t = (Triple) itFrag.next(); if ( itFrag.getHasType() ) continue; StmtMask fm = new StmtMask(rowToFrag(stmtURI, t)); if ( htMask.hasIntersect(fm) ) break; // can't merge all fragments // at this point, we can merge in the current fragment m_reif.updateFrag(stmtURI, t, fm, my_GID); htMask.setMerge(fm); itFrag.deleteRow(); } } } protected Triple rowToFrag ( Node stmtURI, Triple row ) { Node pred = null; Node obj = null; int valCnt = 0; if ( row.getSubject() != null ) { obj = row.getSubject(); pred = RDF.Nodes.subject; valCnt++; } if ( row.getPredicate() != null ) { obj = row.getPredicate(); pred = RDF.Nodes.predicate; valCnt++; } if ( row.getObject() != null ) { obj = row.getObject(); pred = RDF.Nodes.object; valCnt++; } if ( valCnt != 1 ) throw new JenaException("Partially reified row must have exactly one value"); return new Triple(stmtURI, pred, obj); } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraph#add(java.util.List, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag) */ public void add(List triples, CompletionFlag complete) { ArrayList remainingTriples = new ArrayList(); for( int i=0; i< triples.size(); i++) { CompletionFlag partialResult = newComplete(); add( (Triple)triples.get(i), partialResult); if( !partialResult.isDone()) remainingTriples.add(triples.get(i)); } triples.clear(); if( remainingTriples.isEmpty()) complete.setDone(); else triples.addAll(remainingTriples); } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraph#delete(java.util.List, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag) */ public void delete(List triples, CompletionFlag complete) { boolean result = true; Iterator it = triples.iterator(); while(it.hasNext()) { CompletionFlag partialResult = newComplete(); delete( (Triple)it.next(), partialResult); result = result && partialResult.isDone(); } if( result ) complete.setDone(); } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraph#tripleCount() */ public int tripleCount() { // A very inefficient, but simple implementation ExtendedIterator it = find( null, null, null, newComplete() ); int count = 0; while (it.hasNext()) { it.next(); count++; } it.close(); return count; } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraph#find(com.hp.hpl.jena.graph.TripleMatch, com.hp.hpl.jena.db.impl.SpecializedGraph.CompletionFlag) */ public ExtendedIterator find(TripleMatch t, CompletionFlag complete) { // Node stmtURI = t.getMatchSubject(); // note: can be null // ResultSetReifIterator it = m_reif.findReifStmt(stmtURI, false, my_GID, true); // return it.filterKeep( new TripleMatchFilter( t.asTriple() ) ); ResultSetReifIterator it = m_reif.findReifTripleMatch(t, my_GID); return it; } /** * Tests if a triple is contained in the specialized graph. * @param t is the triple to be tested * @param complete is true if the graph can guarantee that * no other specialized graph could hold any matching triples. * @return boolean result to indicate if the triple was contained */ public boolean contains(Triple t, CompletionFlag complete) { // A very inefficient, but simple implementation ExtendedIterator it = find( t, complete ); try { return it.hasNext(); } finally { it.close(); } } /* * @see com.hp.hpl.jena.db.impl.SpecializedGraph#close() */ public void close() { m_reif.close(); } /* * @see com.hp.hpl.jena.db.impl.SpecializedGraph#clear() */ public void clear() { m_reif.removeStatementsFromDB(my_GID); } public class ReifCacheMap { protected int cacheSize = 1; protected ReifCache[] cache; protected boolean[] inUse; ReifCacheMap(int size) { int i; inUse = new boolean[size]; cache = new ReifCache[size]; for (i = 0; i < size; i++) inUse[i] = false; } ReifCache lookup(Node stmtURI) { int i; for (i = 0; i < cache.length; i++) { if (inUse[i] && (cache[i].getStmtURI().equals(stmtURI))) return cache[i]; } return null; } public void flushAll() { int i; for (i = 0; i < cache.length; i++) inUse[i] = false; } public void flush(ReifCache entry) { flushAll(); // optimize later } public ReifCache load(Node stmtURI) { ReifCache entry = lookup(stmtURI); if (entry != null) return entry; return load(stmtURI, null, null, null); } public ReifCache load(Node stmtURI, Triple s, StmtMask sm, StmtMask dm ) { flushAll(); StmtMask m = new StmtMask(); Triple t; boolean hasSubj, hasPred, hasObj, hasType; boolean checkSame = sm != null; int cnt = 0; ResultSetReifIterator it = m_reif.findReifStmt(stmtURI,false,my_GID, false); while (it.hasNext()) { cnt++; Triple db = (Triple) it.next(); StmtMask n = new StmtMask(); hasSubj = !db.getSubject().equals(Node.NULL); if ( hasSubj && checkSame ) if ( db.getSubject().equals(s.getSubject()) ) sm.setHasSubj(); else dm.setHasSubj(); hasPred = !db.getPredicate().equals(Node.NULL); if ( hasPred && checkSame ) if ( db.getPredicate().equals(s.getPredicate()) ) sm.setHasPred(); else dm.setHasPred(); hasObj = !db.getObject().equals(Node.NULL); if ( hasObj && checkSame ) if ( db.getObject().equals(s.getObject()) ) sm.setHasObj(); else dm.setHasObj(); hasType = it.getHasType(); n.setMask( hasSubj, hasPred, hasObj, hasType ); if ( n.hasNada() ) throw new JenaException("Fragment has no data"); m.setMerge(n); } if ( cnt == 0 ) return null; // no fragments for subject if (m.hasSPOT() && (cnt == 1)) m.setIsStmt(); inUse[0] = true; cache[0] = new ReifCache(stmtURI, m, cnt); return cache[0]; } } class ReifCache { protected Node stmtURI; protected StmtMask mask; protected int tripleCnt; ReifCache( Node s, StmtMask m, int cnt ) { stmtURI = s; mask = m; tripleCnt = cnt; } public StmtMask getStmtMask() { return mask; } public int getCnt() { return tripleCnt; } public Node getStmtURI() { return stmtURI; } public void setMask ( StmtMask m ) { mask = m; } public void setCnt ( int cnt ) { tripleCnt = cnt; } public void incCnt ( int cnt ) { tripleCnt++; } public void decCnt ( int cnt ) { tripleCnt public boolean canMerge ( StmtMask fragMask ) { return (!mask.hasIntersect(fragMask)); } public boolean canUpdate ( StmtMask fragMask ) { return ( canMerge(fragMask) && (tripleCnt == 1)); } public void update ( StmtMask fragMask ) { mask.setMerge(fragMask); if ( isStmt() ) { mask.setIsStmt(); } } private boolean isStmt() { return mask.hasSPOT() && (tripleCnt == 1); } } static boolean isReifProp ( Node_URI p ) { return p.equals(RDF.Nodes.subject) || p.equals(RDF.Nodes.predicate)|| p.equals(RDF.Nodes.object) || p.equals(RDF.Nodes.type); } class StmtMask { protected int mask; public static final int HasSubj = 1; public static final int HasPred = 2; public static final int HasObj = 4; public static final int HasType = 8; public static final int HasSPOT = 15; public static final int IsStmt = 16; public static final int HasNada = 0; public boolean hasSubj () { return (mask & HasSubj) == HasSubj; } public boolean hasPred () { return (mask & HasPred) == HasPred; } public boolean hasObj () { return (mask & HasObj) == HasObj; } public boolean hasType () { return (mask & HasType) == HasType; } public boolean hasSPOT () { return (mask & HasSPOT) == HasSPOT; } public boolean isStmt () { return (mask & IsStmt) == IsStmt; } public boolean hasNada () { return mask == HasNada; } public boolean hasOneBit () { return ( (mask == HasSubj) || (mask == HasPred) || (mask == HasObj) || ( mask == HasType) ); } // note: have SPOT does not imply a reification since // 1) there may be multiple fragments for prop, obj // 2) the fragments may be in multiple tuples StmtMask ( Triple t ) { mask = HasNada; Node_URI p = (Node_URI) t.getPredicate(); if ( p != null ) { if ( p.equals(RDF.Nodes.subject) ) mask = HasSubj; else if ( p.equals(RDF.Nodes.predicate) ) mask = HasPred; else if ( p.equals(RDF.Nodes.object) ) mask = HasObj; else if ( p.equals(RDF.Nodes.type) ) { Node o = t.getObject(); if ( o.equals(RDF.Nodes.Statement) ) mask = HasType; } } } StmtMask () { mask = HasNada; } public void setMerge ( StmtMask m ) { mask |= m.mask; } public void setHasType () { mask |= HasType; } public void setMask ( boolean hasSubj, boolean hasProp, boolean hasObj, boolean hasType ) { if ( hasSubj ) mask |= HasSubj; if ( hasProp) mask |= HasPred; if ( hasObj) mask |= HasObj; if ( hasType ) mask |= HasType; } public void setHasSubj () { mask |= HasSubj; } public void setHasPred () { mask |= HasPred; } public void setHasObj () { mask |= HasObj; } public void setIsStmt () { mask |= IsStmt; } public boolean hasIntersect ( StmtMask m ) { return (mask & m.mask) != 0; } public boolean equals ( StmtMask m ) { return mask == m.mask; } } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#graphIdGet() */ public int getGraphId() { return ((DBIDInt)my_GID).getIntID(); } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#PSetGet() */ public IPSet getPSet() { return m_pset; } /* (non-Javadoc) * @see com.hp.hpl.jena.db.impl.SpecializedGraphReifier#DBPropLSetGet() */ public DBPropLSet getDBPropLSet() { return m_dbPropLSet; } public char subsumes ( Triple pattern ) { Node pred = pattern.getPredicate(); char res = noTriplesForPattern; if ( pred.isConcrete() ) { if ( pred.equals(RDF.Nodes.subject) || pred.equals(RDF.Nodes.predicate) || pred.equals(RDF.Nodes.object) ) res = allTriplesForPattern; else if ( pred.equals(RDF.Nodes.type) ) { Node obj = pattern.getObject(); if ( obj.equals(RDF.Nodes.Statement) ) res = allTriplesForPattern; else res = someTriplesForPattern; } } else if ( (pred.isVariable()) || pred.equals(Node.ANY) ) { res = someTriplesForPattern; } else throw new JenaException("Unexpected predicate: " + pred.toString()); return res; } }
package org.escalate42.javaz.future; import org.escalate42.javaz.common.applicative.Applicative; import org.escalate42.javaz.common.function.Applicable; import org.escalate42.javaz.common.function.Function; import org.escalate42.javaz.common.function.ThrowableClosure; import org.escalate42.javaz.common.monad.Monad; import org.escalate42.javaz.common.tuple.Tuple2; import org.escalate42.javaz.option.Option; import org.escalate42.javaz.trym.TryM; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.Executor; import java.util.concurrent.ForkJoinPool; import static org.escalate42.javaz.option.OptionImpl.*; import static org.escalate42.javaz.trym.TryMImpl.*; @SuppressWarnings("unchecked") public class FutureImpl<T> implements Future<T> { private final Executor executor; private final CompletableFuture<T> sourceFuture; private final CompletableFuture<T> body; private volatile Option<TryM<T>> result = none(); public static <T> FutureImpl<T> future(Executor executor) { return new FutureImpl<>(executor, new CompletableFuture<>()); } public static <T> FutureImpl<T> future(Executor executor, CompletableFuture<T> completableFuture) { return new FutureImpl<>(executor, completableFuture); } public static <T> FutureImpl<T> future(Executor executor, ThrowableClosure<T> closure) { return new FutureImpl<>(executor, CompletableFuture.supplyAsync(closure.ommitThrow()::apply, executor)); } public static <T> FutureImpl<T> completed(Executor executor, T value) { return new FutureImpl<>(executor, CompletableFuture.completedFuture(value)); } public static <T> FutureImpl<T> completed(Executor executor, Throwable t) { final CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(t); return new FutureImpl<>(executor, future); } public static <T> FutureImpl<T> future() { return future(ForkJoinPool.commonPool()); } public static <T> FutureImpl<T> future(CompletableFuture<T> completableFuture) { return future(ForkJoinPool.commonPool(), completableFuture); } public static <T> FutureImpl<T> future(ThrowableClosure<T> closure) { return future(ForkJoinPool.commonPool(), closure); } public static <T> FutureImpl<T> completed(T value) { return completed(ForkJoinPool.commonPool(), value); } public static <T> FutureImpl<T> completed(Throwable t) { return completed(ForkJoinPool.commonPool(), t); } private FutureImpl(final Executor executor, final CompletableFuture<T> future) { this.executor = executor; this.sourceFuture = future; this.body = future.whenComplete((r, t) -> { if (r != null) { result = some(success(r)); } else if (t != null) { result = some(fail(t.getCause().getCause())); } }); } @Override public boolean complete(T value) { return this.body.complete(value); } @Override public boolean complete(Throwable t) { return complete(fail(t)); } @Override public boolean complete(TryM<T> t) { return t.isSuccess() ? this.sourceFuture.complete(t.value()) : this.sourceFuture.completeExceptionally(t.throwable()); } @Override public void onSuccess(Applicable<T> onSuccess) { this.body.whenCompleteAsync((r, t) -> this.result.foreach((tryM) -> tryM.foreach(onSuccess)) ); } @Override public void onFailure(Applicable<Throwable> onFailure) { this.body.whenCompleteAsync((r, t) -> this.result.foreach((tryM) -> tryM.foreachFailure(onFailure)) ); } @Override public void onComplete(Applicable<TryM<T>> onComplete) { this.body.whenCompleteAsync((r, t) -> onComplete.apply(result.get())); } @Override public boolean isCompleted() { return this.body.isDone(); } @Override public <U> Future<U> recover(Function<Throwable, U> recover) { return null; } @Override public <U> Future<U> recoverWith(Function<Throwable, Future<U>> recover) { return null; } @Override public Option<TryM<T>> value() { return this.result; } @Override public <U> Future<Tuple2<T, U>> zip(Future<U> another) { return null; } @Override public <U, MM extends Monad<U, Future<?>>> Future<U> flatMap(Function<T, MM> function) { final Future<U> future = future(this.executor); final Function<T, Future<U>> toApply = (Function<T, Future<U>>)function; onComplete((tryM) ->{ if (tryM.isSuccess()) {toApply.apply(tryM.value()).onComplete(future::complete); } else { future.complete(tryM.throwable()); } }); return future; } @Override public <U> Future<U> pure(U value) { return completed(value); } @Override public <U, MM extends Applicative<Function<T, U>, Future<?>>> Future<U> amap(MM applicativeFunction) { return null; } @Override public <U> Future<U> map(Function<T, U> function) { return future(this.executor, this.body.handleAsync((r, t) -> { if (r != null) { return function.apply(r); } else if (t.getClass().equals(CompletionException.class)) { throw (CompletionException)t; } else { throw new RuntimeException(t); } })); } @Override public CompletableFuture<T> toCompletableFuture() { return this.body; } public static void main(final String[] args) throws InterruptedException { System.out.println("Showtime"); final Future<String> future = future(() -> {Thread.sleep(1000); return "Vadim";}); future.onComplete((r) -> System.out.println(r + "->" + future.value())); future.onSuccess((r) -> System.out.println(r + "->" + future.value())); future.onFailure(Throwable::printStackTrace); final Future<String> mapped = future.map(String::toUpperCase); mapped.onComplete((t) -> System.out.println("Mapped just have been completed")); final Future<String> flatMapped = future.flatMap((s) -> future((ThrowableClosure<String>)s::toUpperCase)); flatMapped.onComplete((t) -> System.out.println("FlatMapped just have been completed")); Thread.sleep(2000); System.out.println(future.value()); System.out.println(mapped.value()); System.out.println(flatMapped.value()); } }
package org.gbif.api.vocabulary; import org.gbif.dwc.terms.DwcTerm; import org.gbif.dwc.terms.GbifTerm; import org.gbif.dwc.terms.Term; import org.gbif.utils.AnnotationUtils; import java.util.Set; import com.google.common.collect.ImmutableSet; import static org.gbif.api.vocabulary.InterpretationRemarkSeverity.ERROR; import static org.gbif.api.vocabulary.InterpretationRemarkSeverity.INFO; import static org.gbif.api.vocabulary.InterpretationRemarkSeverity.WARNING; /** * Enumeration of issues for each name usage record encountered during checklist processing. */ public enum NameUsageIssue implements InterpretationRemark { /** * The value for dwc:parentNameUsageID could not be resolved. */ PARENT_NAME_USAGE_ID_INVALID(ERROR, DwcTerm.parentNameUsageID), /** * The value for dwc:acceptedNameUsageID could not be resolved. */ ACCEPTED_NAME_USAGE_ID_INVALID(ERROR, DwcTerm.acceptedNameUsageID), /** * The value for dwc:originalNameUsageID could not be resolved. */ ORIGINAL_NAME_USAGE_ID_INVALID(ERROR, DwcTerm.originalNameUsageID), /** * Synonym lacking an accepted name. */ ACCEPTED_NAME_MISSING(DwcTerm.taxonomicStatus, DwcTerm.acceptedNameUsageID, DwcTerm.acceptedNameUsage), /** * dwc:taxonRank could not be interpreted */ RANK_INVALID(DwcTerm.taxonRank), /** * dwc:nomenclaturalStatus could not be interpreted */ NOMENCLATURAL_STATUS_INVALID(DwcTerm.nomenclaturalStatus), /** * dwc:taxonomicStatus could not be interpreted */ TAXONOMIC_STATUS_INVALID(DwcTerm.taxonomicStatus), /** * The scientific name was assembled from the individual name parts and not given as a whole string. */ SCIENTIFIC_NAME_ASSEMBLED(INFO, DwcTerm.scientificName, DwcTerm.genus, DwcTerm.specificEpithet, DwcTerm.infraspecificEpithet, DwcTerm.taxonRank, DwcTerm.scientificNameAuthorship, DwcTerm.namePublishedInYear), /** * If a synonym points to another synonym as its accepted taxon the chain is resolved. */ CHAINED_SYNOYM(DwcTerm.acceptedNameUsageID, DwcTerm.acceptedNameUsage), /** * The authorship of the original name does not match the authorship in brackets of the actual name. */ BASIONYM_AUTHOR_MISMATCH(DwcTerm.scientificName, DwcTerm.scientificNameAuthorship, DwcTerm.originalNameUsageID, DwcTerm.originalNameUsage), TAXONOMIC_STATUS_MISMATCH(DwcTerm.taxonomicStatus, DwcTerm.acceptedNameUsageID, DwcTerm.acceptedNameUsage), /** * The child parent classification resulted into a cycle that needed to be resolved/cut. */ PARENT_CYCLE(ERROR, DwcTerm.parentNameUsageID, DwcTerm.parentNameUsage), /** * The given ranks of the names in the classification hierarchy do not follow the hierarchy of ranks. */ CLASSIFICATION_RANK_ORDER_INVALID(ERROR, DwcTerm.parentNameUsageID, DwcTerm.parentNameUsage, DwcTerm.taxonRank), /** * The denormalized classification could not be applied to the name usage. * For example if the id based classification has no ranks. */ CLASSIFICATION_NOT_APPLIED(DwcTerm.kingdom, DwcTerm.phylum, DwcTerm.class_, DwcTerm.order, DwcTerm.family, DwcTerm.genus), /** * At least one vernacular name extension record attached to this name usage is invalid. */ VERNACULAR_NAME_INVALID(DwcTerm.vernacularName), /** * At least one description extension record attached to this name usage is invalid. */ DESCRIPTION_INVALID(GbifTerm.Description), /** * At least one distribution extension record attached to this name usage is invalid. */ DISTRIBUTION_INVALID(GbifTerm.Distribution), /** * At least one species profile extension record attached to this name usage is invalid. */ SPECIES_PROFILE_INVALID(GbifTerm.SpeciesProfile), /** * At least one multimedia extension record attached to this name usage is invalid. * This covers multimedia coming in through various extensions including * Audubon core, Simple images or multimedia or EOL media. */ MULTIMEDIA_INVALID(GbifTerm.Multimedia), /** * At least one bibliographic reference extension record attached to this name usage is invalid. */ BIB_REFERENCE_INVALID(GbifTerm.Reference), /** * At least one alternative identifier extension record attached to this name usage is invalid. */ ALT_IDENTIFIER_INVALID(GbifTerm.Identifier), /** * Name usage could not be matched to the GBIF backbone. */ BACKBONE_MATCH_NONE(INFO, DwcTerm.scientificName, DwcTerm.scientificNameAuthorship, DwcTerm.kingdom, DwcTerm.taxonRank), /** * Name usage could only be matched to the GBIF backbone using fuzzy matching. * @deprecated because there should be no fuzzy matching being used anymore for matching checklist names */ @Deprecated BACKBONE_MATCH_FUZZY(DwcTerm.scientificName, DwcTerm.scientificNameAuthorship, DwcTerm.kingdom, DwcTerm.taxonRank), /** * Synonym has a verbatim accepted name which is not unique and refers to several records. */ ACCEPTED_NAME_NOT_UNIQUE(DwcTerm.acceptedNameUsage), /** * Record has a verbatim parent name which is not unique and refers to several records. */ PARENT_NAME_NOT_UNIQUE(DwcTerm.parentNameUsage), /** * Record has a verbatim original name (basionym) which is not unique and refers to several records. */ ORIGINAL_NAME_NOT_UNIQUE(DwcTerm.originalNameUsage), /** * There were problems representing all name usage relationships, * i.e. the link to the parent, accepted and/or original name. * The interpreted record in ChecklistBank is lacking some of the original source relation. */ RELATIONSHIP_MISSING(DwcTerm.parentNameUsageID, DwcTerm.acceptedNameUsageID, DwcTerm.originalNameUsageID, DwcTerm.parentNameUsage, DwcTerm.acceptedNameUsage, DwcTerm.originalNameUsage), /** * Record has a original name (basionym) relationship which was derived from name & authorship comparison, but did not exist explicitly in the data. * This should only be flagged in programmatically generated GBIF backbone usages. * GBIF backbone specific issue. */ ORIGINAL_NAME_DERIVED(INFO), /** * There have been more than one accepted name in a homotypical basionym group of names. * GBIF backbone specific issue. */ CONFLICTING_BASIONYM_COMBINATION(), /** * The group (currently only genera are tested) are lacking any accepted species * GBIF backbone specific issue. */ NO_SPECIES(INFO), /** * The (accepted) bi/trinomial name does not match the parent name and should be recombined into the parent genus/species. * For example the species Picea alba with a parent genus Abies is a mismatch and should be replaced by Abies alba. * GBIF backbone specific issue. */ NAME_PARENT_MISMATCH(), /** * A potential orthographic variant exists in the backbone. * GBIF backbone specific issue. */ ORTHOGRAPHIC_VARIANT(INFO), /** * A not synonymized homonym exists for this name in some other backbone source which have been ignored at build time. */ HOMONYM(INFO, DwcTerm.scientificName), /** * A bi/trinomial name published earlier than the parent genus was published. * This might indicate that the name should rather be a recombination. */ PUBLISHED_BEFORE_GENUS(DwcTerm.scientificName, DwcTerm.scientificNameAuthorship, DwcTerm.namePublishedInYear, DwcTerm.genus, DwcTerm.parentNameUsageID, DwcTerm.parentNameUsage); private final Set<Term> related; private final InterpretationRemarkSeverity severity; private final boolean isDeprecated; NameUsageIssue(Term ... related) { this(WARNING, related); } NameUsageIssue(InterpretationRemarkSeverity severity, Term ... related) { if (related == null) { this.related = ImmutableSet.of(); } else { this.related = ImmutableSet.copyOf(related); } this.severity = severity; this.isDeprecated = AnnotationUtils.isFieldDeprecated(NameUsageIssue.class, this.name()); } @Override public String getId() { return name(); } @Override public Set<Term> getRelatedTerms() { return related; } @Override public InterpretationRemarkSeverity getSeverity(){ return severity; } @Override public boolean isDeprecated(){ return isDeprecated; } }
package org.hyperic.sigar.test; import org.hyperic.sigar.Sigar; import org.hyperic.sigar.CpuInfo; public class TestCpuInfo extends SigarTestCase { public TestCpuInfo(String name) { super(name); } public void testCreate() throws Exception { Sigar sigar = getSigar(); CpuInfo[] infos = sigar.getCpuInfoList(); for (int i=0; i<infos.length; i++) { CpuInfo info = infos[i]; traceln("num=" + i); traceln("vendor=" + info.getVendor()); traceln("model=" + info.getModel()); traceln("mhz=" + info.getMhz()); traceln("cache size=" + info.getCacheSize()); assertGtZeroTrace("totalSockets", info.getTotalSockets()); assertGtZeroTrace("totalCores", info.getTotalCores()); assertTrue(info.getTotalSockets() <= info.getTotalCores()); } int mhz = infos[0].getMhz(); int current = sigar.getCpuInfoList()[0].getMhz(); assertEquals("Mhz=" + current + "/" + mhz, current, mhz); } }
package com.mebigfatguy.fbcontrib.detect; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import com.mebigfatguy.fbcontrib.utils.BugType; import com.mebigfatguy.fbcontrib.utils.RegisterUtils; import com.mebigfatguy.fbcontrib.utils.StopOpcodeParsingException; import com.mebigfatguy.fbcontrib.utils.TernaryPatcher; import com.mebigfatguy.fbcontrib.utils.UnmodifiableSet; import com.mebigfatguy.fbcontrib.utils.Values; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.BytecodeScanningDetector; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.OpcodeStack.CustomUserValue; import edu.umd.cs.findbugs.ba.ClassContext; import edu.umd.cs.findbugs.ba.XField; /** * looks for uses of sets or maps where the key is an enum. In these cases, it is more efficient to use EnumSet or EnumMap. It is a jdk1.5 only detector. */ @CustomUserValue public class UseEnumCollections extends BytecodeScanningDetector { private static final Set<String> nonEnumCollections = UnmodifiableSet.create("Ljava/util/HashSet;", "Ljava/util/HashMap;", "Ljava/util/TreeMap;", "Ljava/util/ConcurrentHashMap;", "Ljava/util/IdentityHashMap;", "Ljava/util/WeakHashMap;"); private final BugReporter bugReporter; private OpcodeStack stack; private Set<String> checkedFields; private Map<Integer, Boolean> enumRegs; private Map<String, Boolean> enumFields; /** * constructs a UEC detector given the reporter to report bugs on * * @param bugReporter * the sync of bug reports */ public UseEnumCollections(BugReporter bugReporter) { this.bugReporter = bugReporter; } /** * implements the visitor to check that the class is greater or equal than 1.5, and set and clear the stack * * @param classContext * the context object for the currently parsed class */ @Override public void visitClassContext(ClassContext classContext) { try { JavaClass cls = classContext.getJavaClass(); if (cls.getMajor() >= Constants.MAJOR_1_5) { stack = new OpcodeStack(); checkedFields = new HashSet<>(); enumRegs = new HashMap<>(); enumFields = new HashMap<>(); super.visitClassContext(classContext); } } finally { stack = null; checkedFields = null; enumRegs = null; enumFields = null; } } /** * implements the visitor to reset the state * * @param obj * the context object for the currently parsed method */ @Override public void visitMethod(Method obj) { stack.resetForMethodEntry(this); enumRegs.clear(); super.visitMethod(obj); } @Override public void visitCode(Code obj) { try { super.visitCode(obj); } catch (StopOpcodeParsingException e) { // method is already reported } } @Override public void sawOpcode(int seen) { Boolean sawEnumCollectionCreation = null; // true - enum, false - // nonenum try { stack.precomputation(this); if (seen == INVOKESTATIC) { String clsName = getClassConstantOperand(); String signature = getSigConstantOperand(); if ("java/util/EnumSet".equals(clsName) && signature.endsWith(")Ljava/util/EnumSet;")) { sawEnumCollectionCreation = Boolean.TRUE; } } else if (seen == INVOKESPECIAL) { String clsName = getClassConstantOperand(); String methodName = getNameConstantOperand(); if ("java/util/EnumMap".equals(clsName) && Values.CONSTRUCTOR.equals(methodName)) { sawEnumCollectionCreation = Boolean.TRUE; } else if (clsName.startsWith("java/util/") && (clsName.endsWith("Map") || clsName.endsWith("Set"))) { sawEnumCollectionCreation = Boolean.FALSE; } } else if ((seen == ASTORE) || ((seen >= ASTORE_0) && (seen <= ASTORE_3))) { if (stack.getStackDepth() > 0) { OpcodeStack.Item itm = stack.getStackItem(0); Integer reg = Integer.valueOf(RegisterUtils.getAStoreReg(this, seen)); if (itm.getUserValue() != null) { enumRegs.put(reg, (Boolean) itm.getUserValue()); } else { enumRegs.remove(reg); } } } else if ((seen == ALOAD) || ((seen >= ALOAD_0) && (seen <= ALOAD_3))) { Integer reg = Integer.valueOf(RegisterUtils.getALoadReg(this, seen)); sawEnumCollectionCreation = enumRegs.get(reg); } else if (seen == PUTFIELD) { if (stack.getStackDepth() > 0) { String fieldName = getNameConstantOperand(); OpcodeStack.Item itm = stack.getStackItem(0); if (itm.getUserValue() != null) { enumFields.put(fieldName, (Boolean) itm.getUserValue()); } else { enumFields.remove(fieldName); } } } else if (seen == GETFIELD) { String fieldName = getNameConstantOperand(); sawEnumCollectionCreation = enumFields.get(fieldName); } else if (seen == INVOKEINTERFACE) { boolean bug = false; String clsName = getClassConstantOperand(); String methodName = getNameConstantOperand(); String signature = getSigConstantOperand(); if (("java/util/Map".equals(clsName)) && ("put".equals(methodName)) && ("(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;".equals(signature))) { bug = isEnum(1) && !isEnumCollection(2) && !alreadyReported(2); } else if (("java/util/Set".equals(clsName)) && ("add".equals(methodName)) && ("(Ljava/lang/Object;)Z".equals(signature))) { bug = isEnum(0) && !isEnumCollection(1) && !alreadyReported(1); } if (bug) { bugReporter.reportBug( new BugInstance(this, BugType.UEC_USE_ENUM_COLLECTIONS.name(), NORMAL_PRIORITY).addClass(this).addMethod(this).addSourceLine(this)); throw new StopOpcodeParsingException(); } } } catch (ClassNotFoundException cnfe) { bugReporter.reportMissingClass(cnfe); } finally { TernaryPatcher.pre(stack, seen); stack.sawOpcode(this, seen); TernaryPatcher.post(stack, seen); if ((sawEnumCollectionCreation != null) && (stack.getStackDepth() > 0)) { OpcodeStack.Item itm = stack.getStackItem(0); itm.setUserValue(sawEnumCollectionCreation); } } } /** * returns whether the item at the stackPos location on the stack is an enum, and doesn't implement any interfaces * * @param stackPos * the position on the opstack to check * * @return whether the class is an enum * @throws ClassNotFoundException * if the class can not be loaded */ private boolean isEnum(int stackPos) throws ClassNotFoundException { if (stack.getStackDepth() > stackPos) { OpcodeStack.Item item = stack.getStackItem(stackPos); if (item.getSignature().charAt(0) != 'L') { return false; } JavaClass cls = item.getJavaClass(); if ((cls == null) || !cls.isEnum()) { return false; } // If the cls implements any interface, it's possible the collection // is based on that interface, so ignore if (cls.getInterfaces().length == 0) { return true; } } return false; } /** * returns whether the item at the stackpos location is an instance of an EnumSet or EnumMap * * @param stackPos * the position on the opstack to check * * @return whether the class is an EnumSet or EnumMap */ private boolean isEnumCollection(int stackPos) { if (stack.getStackDepth() <= stackPos) { return false; } OpcodeStack.Item item = stack.getStackItem(stackPos); Boolean userValue = (Boolean) item.getUserValue(); if (userValue != null) { return userValue.booleanValue(); } String realClass = item.getSignature(); if ("Ljava/util/EnumSet;".equals(realClass) || "Ljava/util/EnumMap;".equals(realClass)) { return true; } if (nonEnumCollections.contains(realClass)) { return false; } // Can't tell here so return true return true; } /** * returns whether the collection has already been reported on * * @param stackPos * the position on the opstack to check * * @return whether the collection has already been reported. */ private boolean alreadyReported(int stackPos) { if (stack.getStackDepth() <= stackPos) { return false; } OpcodeStack.Item item = stack.getStackItem(stackPos); XField field = item.getXField(); if (field == null) { return false; } String fieldName = field.getName(); boolean checked = checkedFields.contains(fieldName); checkedFields.add(fieldName); return checked; } }
package org.biojava.bio.structure; import org.biojava.bio.structure.align.util.AtomCache; import junit.framework.TestCase; public class TestAtomCache extends TestCase { public void testAtomCacheNameParsing(){ String name1= "4hhb"; String name2 = "4hhb.C"; String chainId2 = "C"; String name3 = "4hhb:1"; String chainId3 = "B"; String name4 = "4hhb:A:10-20,B:10-20,C:10-20"; String name5 = "4hhb:(A:10-20,A:30-40)"; String tmpDir = System.getProperty("java.io.tmpdir"); boolean isSplit = true; AtomCache cache = new AtomCache(tmpDir,isSplit); try { Structure s = cache.getStructure(name1); assertNotNull(s); assertTrue(s.getChains().size() == 4); s = cache.getStructure(name2); assertTrue(s.getChains().size() == 1); Chain c = s.getChainByPDB(chainId2); assertEquals(c.getName(),chainId2); s = cache.getStructure(name3); assertNotNull(s); assertTrue(s.getChains().size() == 1); c = s.getChainByPDB(chainId3); assertEquals(c.getName(),chainId3); s = cache.getStructure(name4); assertNotNull(s); assertEquals(s.getChains().size(), 3); c = s.getChainByPDB("B"); assertEquals(c.getAtomLength(),11); s =cache.getStructure(name5); assertNotNull(s); assertEquals(s.getChains().size(),1 ); c = s.getChainByPDB("A"); assertEquals(c.getAtomLength(),22); } catch (Exception e){ e.printStackTrace(); fail(e.getMessage()); } } }
package fr.openwide.core.jpa.more.business.file.model; import java.io.File; import java.io.InputStream; import java.util.List; import java.util.Locale; import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import fr.openwide.core.jpa.exception.SecurityServiceException; import fr.openwide.core.jpa.exception.ServiceException; import fr.openwide.core.jpa.more.util.image.exception.ImageThumbnailGenerationException; import fr.openwide.core.jpa.more.util.image.model.ImageInformation; import fr.openwide.core.jpa.more.util.image.model.ImageThumbnailFormat; import fr.openwide.core.jpa.more.util.image.service.IImageService; public class ImageGalleryFileStoreImpl extends SimpleFileStoreImpl { private static final Logger LOGGER = LoggerFactory.getLogger(ImageGalleryFileStoreImpl.class); private List<ImageThumbnailFormat> thumbnailFormats; @Autowired private IImageService imageService; public ImageGalleryFileStoreImpl(String key, String rootDirectoryPath, List<ImageThumbnailFormat> thumbnailFormats) { super(key, rootDirectoryPath, true); this.thumbnailFormats = thumbnailFormats; } @Override public FileInformation addFile(byte[] fileContent, String fileKey, String extension) throws ServiceException, SecurityServiceException { FileInformation information = super.addFile(fileContent, fileKey, extension.toLowerCase(Locale.ROOT)); addFileToGallery(information, fileKey, extension.toLowerCase(Locale.ROOT)); return information; } @Override public FileInformation addFile(File file, String fileKey, String extension) throws ServiceException, SecurityServiceException { FileInformation information = super.addFile(file, fileKey, extension); addFileToGallery(information, fileKey, extension.toLowerCase(Locale.ROOT)); return information; } @Override public FileInformation addFile(InputStream inputStream, String fileKey, String extension) throws ServiceException, SecurityServiceException { FileInformation information = super.addFile(inputStream, fileKey, extension); addFileToGallery(information, fileKey, extension.toLowerCase(Locale.ROOT)); return information; } protected FileInformation addFileToGallery(FileInformation fileInformation, String fileKey, String extension) throws ImageThumbnailGenerationException { ImageInformation imageInformation = imageService.getImageInformation(getFile(fileKey, extension)); fileInformation.addImageInformation(imageInformation); generateThumbnails(fileKey, extension); fileInformation.setImageThumbnailAvailable(true); return fileInformation; } protected void generateThumbnails(String fileKey, String extension) throws ImageThumbnailGenerationException { for (ImageThumbnailFormat thumbnailFormat : thumbnailFormats) { imageService.generateThumbnail(getFile(fileKey, extension), getThumbnailFile(fileKey, extension, thumbnailFormat), thumbnailFormat); } } @Override public void removeFile(String fileKey, String extension) { for (ImageThumbnailFormat thumbnailFormat : thumbnailFormats) { if (!getThumbnailFile(fileKey, extension, thumbnailFormat).delete()) { LOGGER.error("Error removing thumbnail file " + fileKey + " " + extension + " " + thumbnailFormat.getName()); } } super.removeFile(fileKey, extension); } public File getThumbnailFile(String fileKey, String extension, ImageThumbnailFormat thumbnailFormat) { return new File(getThumbnailFilePath(fileKey, extension, thumbnailFormat)); } protected String getThumbnailFilePath(String fileKey, String extension, ImageThumbnailFormat thumbnailFormat) { StringBuilder fileName = new StringBuilder(); fileName.append(fileKey); fileName.append("-"); fileName.append(thumbnailFormat.getName()); fileName.append("."); fileName.append(thumbnailFormat.getExtension(extension)); return FilenameUtils.concat(getRootDirectoryPath(), fileName.toString()); } }
package aQute.bnd.build; import java.io.File; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.jar.Manifest; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import aQute.bnd.header.Attrs; import aQute.bnd.header.OSGiHeader; import aQute.bnd.header.Parameters; import aQute.bnd.osgi.Constants; import aQute.bnd.osgi.Jar; import aQute.bnd.osgi.Processor; import aQute.bnd.service.Strategy; import aQute.libg.command.Command; import aQute.libg.generics.Create; /** * A Project Launcher is a base class to be extended by launchers. Launchers are * JARs that launch a framework and install a number of bundles and then run the * framework. A launcher jar must specify a Launcher-Class manifest header. This * class is instantiated and cast to a LauncherPlugin. This plug in is then * asked to provide a ProjectLauncher. This project launcher is then used by the * project to run the code. Launchers must extend this class. */ public abstract class ProjectLauncher extends Processor { private final static Logger logger = LoggerFactory.getLogger(ProjectLauncher.class); private final Project project; private long timeout = 0; private final List<String> classpath = new ArrayList<>(); private List<String> runbundles = Create.list(); private final List<String> runvm = new ArrayList<>(); private final List<String> runprogramargs = new ArrayList<>(); private Map<String,String> runproperties; private Command java; private Parameters runsystempackages; private Parameters runsystemcapabilities; private final List<String> activators = Create.list(); private File storageDir; private boolean trace; private boolean keep; private int framework; private File cwd; private Collection<String> agents = new ArrayList<>(); private Set<NotificationListener> listeners = Collections.newSetFromMap(new IdentityHashMap<>()); protected Appendable out = System.out; protected Appendable err = System.err; protected InputStream in = System.in; public final static int SERVICES = 10111; public final static int NONE = 20123; // MUST BE ALIGNED WITH LAUNCHER public final static int OK = 0; public final static int WARNING = -1; public final static int ERROR = -2; public final static int TIMEDOUT = -3; public final static int UPDATE_NEEDED = -4; public final static int CANCELED = -5; public final static int DUPLICATE_BUNDLE = -6; public final static int RESOLVE_ERROR = -7; public final static int ACTIVATOR_ERROR = -8; public final static int CUSTOM_LAUNCHER = -128; public final static String EMBEDDED_ACTIVATOR = "Embedded-Activator"; public ProjectLauncher(Project project) throws Exception { this.project = project; updateFromProject(); } /** * Collect all the aspect from the project and set the local fields from * them. Should be called * * @throws Exception */ protected void updateFromProject() throws Exception { setCwd(project.getBase()); // pkr: could not use this because this is killing the runtests. // project.refresh(); runbundles.clear(); Collection<Container> run = project.getRunbundles(); for (Container container : run) { File file = container.getFile(); if (file != null && (file.isFile() || file.isDirectory())) { runbundles.add(file.getAbsolutePath()); } else { project.error("Bundle file \"%s\" does not exist, given error is %s", file, container.getError()); } } if (project.getRunBuilds()) { File[] builds = project.getBuildFiles(true); if (builds != null) for (File file : builds) runbundles.add(file.getAbsolutePath()); } Collection<Container> runpath = project.getRunpath(); runsystempackages = new Parameters(project.mergeProperties(Constants.RUNSYSTEMPACKAGES), project); runsystemcapabilities = new Parameters(project.mergeProperties(Constants.RUNSYSTEMCAPABILITIES), project); framework = getRunframework(project.getProperty(Constants.RUNFRAMEWORK)); timeout = Processor.getDuration(project.getProperty(Constants.RUNTIMEOUT), 0); trace = Processor.isTrue(project.getProperty(Constants.RUNTRACE)); runpath.addAll(project.getRunFw()); for (Container c : runpath) { addClasspath(c); } runvm.addAll(project.getRunVM()); runprogramargs.addAll(project.getRunProgramArgs()); runproperties = project.getRunProperties(); storageDir = project.getRunStorage(); setKeep(project.getRunKeep()); } private int getRunframework(String property) { if (Constants.RUNFRAMEWORK_NONE.equalsIgnoreCase(property)) return NONE; else if (Constants.RUNFRAMEWORK_SERVICES.equalsIgnoreCase(property)) return SERVICES; return SERVICES; } public void addClasspath(Container container) throws Exception { if (container.getError() != null) { project.error("Cannot launch because %s has reported %s", container.getProject(), container.getError()); } else { Collection<Container> members = container.getMembers(); for (Container m : members) { String path = m.getFile().getAbsolutePath(); if (!classpath.contains(path)) { Manifest manifest = m.getManifest(); if (manifest != null) { // We are looking for any agents, used if // -javaagent=true is set String agentClassName = manifest.getMainAttributes().getValue("Premain-Class"); if (agentClassName != null) { String agent = path; if (container.getAttributes().get("agent") != null) { agent += "=" + container.getAttributes().get("agent"); } agents.add(path); } Parameters exports = project .parseHeader(manifest.getMainAttributes().getValue(Constants.EXPORT_PACKAGE)); for (Entry<String,Attrs> e : exports.entrySet()) { if (!runsystempackages.containsKey(e.getKey())) runsystempackages.put(e.getKey(), e.getValue()); } // Allow activators on the runpath. They are called // after // the framework is completely initialized wit the // system // context. String activator = manifest.getMainAttributes().getValue(EMBEDDED_ACTIVATOR); if (activator != null) activators.add(activator); } classpath.add(path); } } } } protected void addClasspath(Collection<Container> path) throws Exception { for (Container c : Container.flatten(path)) { addClasspath(c); } } public void addRunBundle(String f) { runbundles.add(f); } public Collection<String> getRunBundles() { return runbundles; } public void addRunVM(String arg) { runvm.add(arg); } public void addRunProgramArgs(String arg) { runprogramargs.add(arg); } public List<String> getRunpath() { return classpath; } public Collection<String> getClasspath() { return classpath; } public Collection<String> getRunVM() { return runvm; } @Deprecated public Collection<String> getArguments() { return getRunProgramArgs(); } public Collection<String> getRunProgramArgs() { return runprogramargs; } public Map<String,String> getRunProperties() { return runproperties; } public File getStorageDir() { return storageDir; } public abstract String getMainTypeName(); public abstract void update() throws Exception; public int launch() throws Exception { prepare(); java = new Command(); // Handle the environment Map<String,String> env = getRunEnv(); for (Map.Entry<String,String> e : env.entrySet()) { java.var(e.getKey(), e.getValue()); } java.add(project.getProperty("java", getJavaExecutable())); String javaagent = project.getProperty(Constants.JAVAAGENT); if (Processor.isTrue(javaagent)) { for (String agent : agents) { java.add("-javaagent:" + agent); } } String jdb = getRunJdb(); if (jdb != null) { int port = 1044; try { port = Integer.parseInt(project.getProperty(Constants.RUNJDB)); } catch (Exception e) { // ok, value can also be ok, or on, or true } String suspend = port > 0 ? "y" : "n"; java.add("-Xrunjdwp:server=y,transport=dt_socket,address=" + Math.abs(port) + ",suspend=" + suspend); } java.add("-cp"); java.add(Processor.join(getClasspath(), File.pathSeparator)); java.addAll(getRunVM()); java.add(getMainTypeName()); java.addAll(getRunProgramArgs()); if (timeout != 0) java.setTimeout(timeout + 1000, TimeUnit.MILLISECONDS); File cwd = getCwd(); if (cwd != null) java.setCwd(cwd); logger.debug("cmd line {}", java); try { int result = java.execute(in, out, err); if (result == Integer.MIN_VALUE) return TIMEDOUT; reportResult(result); return result; } finally { cleanup(); listeners.clear(); } } private String getJavaExecutable() { String javaHome = System.getProperty("java.home"); if (javaHome == null) { return "java"; } File java = new File(javaHome, "bin/java"); return java.getAbsolutePath(); } /** * launch a framework internally. I.e. do not start a separate process. * */ static Pattern IGNORE = Pattern.compile("org(/|\\.)osgi(/|\\.).resource.*"); public int start(ClassLoader parent) throws Exception { prepare(); // Intermediate class loader to not load osgi framework packages // from bnd's loader. Unfortunately, bnd uses some osgi classes // itself that would unnecessarily constrain the framework. ClassLoader fcl = new ClassLoader(parent) { protected Class< ? > loadClass(String name, boolean resolve) throws ClassNotFoundException { if (IGNORE.matcher(name).matches()) throw new ClassNotFoundException(); return super.loadClass(name, resolve); } }; // Load the class that would have gone to the class path // i.e. the framework etc. List<URL> cp = new ArrayList<>(); for (String path : getClasspath()) { cp.add(new File(path).toURI().toURL()); } @SuppressWarnings("resource") URLClassLoader cl = new URLClassLoader(cp.toArray(new URL[0]), fcl); String[] args = getRunProgramArgs().toArray(new String[0]); Class< ? > main = cl.loadClass(getMainTypeName()); return invoke(main, args); } protected int invoke(Class< ? > main, String args[]) throws Exception { throw new UnsupportedOperationException(); } /** * Is called after the process exists. Can you be used to cleanup the * properties file. */ public void cleanup() { // do nothing by default } protected void reportResult(int result) { switch (result) { case OK : logger.debug("Command terminated normal {}", java); break; case TIMEDOUT : project.error("Launch timedout: %s", java); break; case ERROR : project.error("Launch errored: %s", java); break; case WARNING : project.warning("Launch had a warning %s", java); break; default : project.error("Exit code remote process %d: %s", result, java); break; } } public void setTimeout(long timeout, TimeUnit unit) { this.timeout = unit.convert(timeout, TimeUnit.MILLISECONDS); } public long getTimeout() { return this.timeout; } public void cancel() throws Exception { java.cancel(); } public Map<String, ? extends Map<String,String>> getSystemPackages() { return runsystempackages.asMapMap(); } public String getSystemCapabilities() { return runsystemcapabilities.isEmpty() ? null : runsystemcapabilities.toString(); } public Parameters getSystemCapabilitiesParameters() { return runsystemcapabilities; } public void setKeep(boolean keep) { this.keep = keep; } public boolean isKeep() { return keep; } public void setTrace(boolean level) { this.trace = level; } public boolean getTrace() { return this.trace; } /** * Should be called when all the changes to the launchers are set. Will * calculate whatever is necessary for the launcher. * * @throws Exception */ public abstract void prepare() throws Exception; public Project getProject() { return project; } public boolean addActivator(String e) { return activators.add(e); } public Collection<String> getActivators() { return Collections.unmodifiableCollection(activators); } /** * Either NONE or SERVICES to indicate how the remote end launches. NONE * means it should not use the classpath to run a framework. This likely * requires some dummy framework support. SERVICES means it should load the * framework from the claspath. * */ public int getRunFramework() { return framework; } public void setRunFramework(int n) { assert n == NONE || n == SERVICES; this.framework = n; } /** * Add the specification for a set of bundles the runpath if it does not * already is included. This can be used by subclasses to ensure the proper * jars are on the classpath. * * @param defaultSpec The default spec for default jars */ public void addDefault(String defaultSpec) throws Exception { Collection<Container> deflts = project.getBundles(Strategy.HIGHEST, defaultSpec, null); for (Container c : deflts) addClasspath(c); } /** * Create a self executable. */ public Jar executable() throws Exception { throw new UnsupportedOperationException(); } public File getCwd() { return cwd; } public void setCwd(File cwd) { this.cwd = cwd; } public String getRunJdb() { return project.getProperty(Constants.RUNJDB); } public Map<String,String> getRunEnv() { String runenv = project.getProperty(Constants.RUNENV); if (runenv != null) { return OSGiHeader.parseProperties(runenv); } return Collections.emptyMap(); } public static interface NotificationListener { void notify(NotificationType type, String notification); } public static enum NotificationType { ERROR, WARNING, INFO; } public void registerForNotifications(NotificationListener listener) { listeners.add(listener); } public Set<NotificationListener> getNotificationListeners() { return Collections.unmodifiableSet(listeners); } /** * Set the stderr and stdout streams for the output process. The debugged * process must append its output (i.e. write operation in the process under * debug) to the given appendables. * * @param out std out * @param err std err */ public void setStreams(Appendable out, Appendable err) { this.out = out; this.err = err; } /** * Write text to the debugged process as if it came from stdin. * * @param text the text to write * @throws Exception */ public void write(String text) throws Exception { } /** * Get the run sessions. If this return null, then launch on this object * should be used, otherwise each returned object provides a remote session. * * @throws Exception */ public List< ? extends RunSession> getRunSessions() throws Exception { return null; } /** * Utility to calculate the final framework properties from settings */ /** * This method should go to the ProjectLauncher * * @throws Exception */ public void calculatedProperties(Map<String,Object> properties) throws Exception { if (!keep) properties.put(org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN, org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); if (!runsystemcapabilities.isEmpty()) properties.put(org.osgi.framework.Constants.FRAMEWORK_SYSTEMCAPABILITIES_EXTRA, runsystemcapabilities.toString()); if (!runsystempackages.isEmpty()) properties.put(org.osgi.framework.Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, runsystempackages.toString()); } }
package org.jdesktop.swingx; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.io.File; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.plaf.basic.BasicTreeUI; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellEditor; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.AbstractHighlighter; import org.jdesktop.swingx.decorator.ColorHighlighter; import org.jdesktop.swingx.decorator.ComponentAdapter; import org.jdesktop.swingx.decorator.CompoundHighlighter; import org.jdesktop.swingx.decorator.HighlightPredicate; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.decorator.PatternPredicate; import org.jdesktop.swingx.decorator.SearchPredicate; import org.jdesktop.swingx.decorator.HighlightPredicate.DepthHighlightPredicate; import org.jdesktop.swingx.renderer.DefaultListRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.IconValues; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.renderer.WrappingProvider; import org.jdesktop.swingx.renderer.HighlighterClientVisualCheck.FontHighlighter; import org.jdesktop.swingx.test.ActionMapTreeTableModel; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.TreeTableNode; import org.jdesktop.test.AncientSwingTeam; public class JXTreeVisualCheck extends JXTreeUnitTest { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(JXTreeVisualCheck.class .getName()); public static void main(String[] args) { // setSystemLF(true); JXTreeVisualCheck test = new JXTreeVisualCheck(); setLAF("Wind"); try { // test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Renderer.*"); // test.runInteractiveTests("interactive.*RToL.*"); // test.runInteractiveTests("interactive.*Revalidate.*"); // test.runInteractiveTests("interactiveRootExpansionTest"); // test.runInteractiveTests("interactive.*UpdateUI.*"); // test.runInteractiveTests("interactive.*CellHeight.*"); // test.runInteractiveTests("interactive.*RendererSize.*"); test.runInteractive("NextMatch"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue 1483-swingx: getNextMatch must respect StringValue */ public void interactiveNextMatch() { JXTree tree = new JXTree(new FileSystemModel(new File("."))); tree.setCellRenderer(new DefaultTreeRenderer(IconValues.FILE_ICON, StringValues.FILE_NAME)); showWithScrollingInFrame(tree, "nextMatch?"); } public void interactiveDynamicCellHeightTree() { final JXTree tree = new JXTree(AncientSwingTeam.createNamedColorTreeModel()); TreeSelectionListener l = new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { LOG.info("height " + tree.getRowHeight()); // tree.setRowHeight(-1); SwingUtilities.invokeLater(new Runnable() { public void run() { tree.invalidateCellSizeCache(); } }); } }; tree.addTreeSelectionListener(l); tree.setCellRenderer(new DefaultTreeRenderer()); // tree.setLargeModel(true); tree.setRowHeight(0); HighlightPredicate selected = new HighlightPredicate() { @Override public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { return adapter.isSelected(); } }; Highlighter hl = new FontHighlighter(selected, tree.getFont().deriveFont(50f)); tree.addHighlighter(hl); showWithScrollingInFrame(tree, "big font on focus"); } /** * Issue #1231-swingx: tree cell renderer size problems. * * Cache not invalidated on setCellRenderer due to not firing a * propertyChange (it's wrapped). Problem or not is LAF dependent ;-) * The not-firing is clearly a bug. * */ public void interactiveRendererSize() { JXTree tree = new JXTree(); tree.setCellRenderer(new CustomCellRenderer()); tree.expandAll(); showWithScrollingInFrame(tree, "sizing problems in renderer"); } private static class CustomCellRenderer extends DefaultTreeCellRenderer { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { return super.getTreeCellRendererComponent(tree, "XX " + value, selected, expanded, leaf, row, hasFocus); } } /** * Issue #862-swingx: JXTree - add api for selection colors. */ public void interactiveSelectionColors() { final JXTree tree = new JXTree(); // use SwingX renderer which is aware of per-tree selection colors tree.setCellRenderer(new DefaultTreeRenderer()); final Color uiBackground = tree.getSelectionBackground(); final Color uiForeground = tree.getSelectionForeground(); Action toggleSelectionColors = new AbstractAction("toggle selection colors") { public void actionPerformed(ActionEvent e) { if (tree.getSelectionBackground() == uiBackground) { tree.setSelectionBackground(Color.BLUE); tree.setSelectionForeground(Color.RED); } else { tree.setSelectionBackground(uiBackground); tree.setSelectionForeground(uiForeground); } } }; JXFrame frame = wrapWithScrollingInFrame(tree, "selection color property in JXTree"); addAction(frame, toggleSelectionColors); show(frame); } /** * Issue #862-swingx: JXTree - add api for selection colors. * Compare with JList repaint behaviour. */ public void interactiveSelectionColorsList() { final JXList tree = new JXList(new Object[]{"one", "two", "three"}); // use SwingX renderer which is aware of per-tree selection colors tree.setCellRenderer(new DefaultListRenderer()); final Color uiBackground = tree.getSelectionBackground(); final Color uiForeground = tree.getSelectionForeground(); Action toggleSelectionColors = new AbstractAction("toggle selection colors") { public void actionPerformed(ActionEvent e) { if (tree.getSelectionBackground() == uiBackground) { tree.setSelectionBackground(Color.BLUE); tree.setSelectionForeground(Color.RED); } else { tree.setSelectionBackground(uiBackground); tree.setSelectionForeground(uiForeground); } } }; JXFrame frame = wrapWithScrollingInFrame(tree, "selection color property - compare list repaint"); addAction(frame, toggleSelectionColors); show(frame); } /** * Requirements * - no icons, use IconValue.NONE * - don't unwrap user object */ public void interactiveNoIconsNoUnwrap() { TreeModel model = new ActionMapTreeTableModel(new JXTable()); JXTree tree = new JXTree(model); StringValue sv = new StringValue() { public String getString(Object value) { if ((value instanceof TreeTableNode) && ((TreeTableNode) value).getColumnCount() > 0) { value = ((TreeTableNode) value).getValueAt(0); } return StringValues.TO_STRING.getString(value); } }; DefaultTreeRenderer renderer = new DefaultTreeRenderer(IconValues.NONE, sv); ((WrappingProvider) renderer.getComponentProvider()).setUnwrapUserObject(false); tree.setCellRenderer(renderer); JXFrame frame = wrapWithScrollingInFrame(tree, "WrappingProvider: no icons, no unwrapped userObject"); frame.pack(); frame.setSize(400, 200); frame.setVisible(true); } /** * * Requirements: * - striping effect on leaf, extend to full width of tree * - striping relative to parent (not absolute position of row) * * Trick (from forum): set the rendering component's pref width * in the renderer. * * Applied to SwingX: * - use a highlighter for the pref width setting * - use a predicate to decide which striping to turn on * * Problem: difficult to get rid off size cache of BasicTreeUI. * * The sizing of the nodes is cached before the actual expansion. * That is the row index is invalid at the time of messaging the * renderer, so decoration which effects the size (like setting pref * f.i.) is ignored. Except for largeModel and fixed row height. * * Note: as is, it cannot cope with RToL component orientation. */ public void interactiveExpandToWidthHighlighter() { final JXTree tree = new JXTree(); tree.setCellRenderer(new DefaultTreeRenderer()); tree.expandRow(3); tree.setRowHeight(20); tree.setLargeModel(true); tree.setRootVisible(false); tree.setShowsRootHandles(true); int indent = ((BasicTreeUI) tree.getUI()).getLeftChildIndent() + ((BasicTreeUI) tree.getUI()).getRightChildIndent(); int depthOffset = getDepthOffset(tree); HighlightPredicate evenChild = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (!(adapter.getComponent() instanceof JTree)) return false; TreePath path = ((JTree) adapter.getComponent()).getPathForRow(adapter.row); return path == null ? false : (adapter.row - ((JTree) adapter.getComponent()).getRowForPath(path.getParentPath())) % 2 == 0; } }; HighlightPredicate oddChild = new HighlightPredicate() { public boolean isHighlighted(Component renderer, ComponentAdapter adapter) { if (!(adapter.getComponent() instanceof JTree)) return false; TreePath path = ((JTree) adapter.getComponent()).getPathForRow(adapter.row); return path == null ? false : (adapter.row - ((JTree) adapter.getComponent()).getRowForPath(path.getParentPath())) % 2 == 1; } }; final ExtendToWidthHighlighter extendToWidthHighlighter = new ExtendToWidthHighlighter(null, indent, depthOffset); tree.setHighlighters( new CompoundHighlighter( HighlightPredicate.IS_LEAF, extendToWidthHighlighter, new ColorHighlighter(evenChild, HighlighterFactory.BEIGE, null), new ColorHighlighter(oddChild, HighlighterFactory.LINE_PRINTER, null)), new ColorHighlighter(HighlightPredicate.IS_FOLDER, null, Color.RED) ); final JXFrame frame = wrapWithScrollingInFrame(tree, "tree-wide cell renderer"); Action rootVisible = new AbstractActionExt("toggle root visible") { public void actionPerformed(ActionEvent e) { tree.setRootVisible(!tree.isRootVisible()); extendToWidthHighlighter.setDepthOffset(getDepthOffset(tree)); } }; addAction(frame, rootVisible); Action handleVisible = new AbstractActionExt("toggle handles") { public void actionPerformed(ActionEvent e) { tree.setShowsRootHandles(!tree.getShowsRootHandles()); extendToWidthHighlighter.setDepthOffset(getDepthOffset(tree)); } }; addAction(frame, handleVisible); addComponentOrientationToggle(frame); show(frame, 400, 400); } /** * C&p from BasicTreeUI: adjust the depth to root/handle visibility. * @param tree * @return */ protected int getDepthOffset(JTree tree) { if(tree.isRootVisible()) { if(tree.getShowsRootHandles()) { return 1; } } else if(!tree.getShowsRootHandles()) { return -1; } return 0; } /** * Highlighter which sets the preferredWidth of the renderer relative to the * target component's width. Very special requirement for tree rendering: * extend the coloring all the way from the node to the boundary of the tree. * An alternative would be to us a renderer which is layout in such * a way so by default. */ public static class ExtendToWidthHighlighter extends AbstractHighlighter { private int indent; private int depthOffset; public ExtendToWidthHighlighter(HighlightPredicate predicate, int indent, int depthOffset) { super(predicate); this.indent = indent; this.depthOffset = depthOffset; } public void setDepthOffset(int offset) { if (offset == this.depthOffset) return; this.depthOffset = offset; fireStateChanged(); } @Override protected Component doHighlight(Component component, ComponentAdapter adapter) { Dimension dim = component.getPreferredSize(); int width = adapter.getComponent().getWidth() - (adapter.getDepth() + depthOffset) * indent ; dim.width = Math.max(dim.width, width); component.setPreferredSize(dim); return component; } } public void interactiveExpandWithHighlighters() { JXTree tree = new JXTree(); Highlighter searchHighlighter = new ColorHighlighter(new SearchPredicate("\\Qe\\E"), null, Color.RED); tree.addHighlighter(searchHighlighter); showWithScrollingInFrame(tree, "NPE on tree expand with highlighter"); } /** * visually check if invokesStopCellEditing jumps in on focusLost. * */ public void interactiveToggleEditProperties() { final JXTree table = new JXTree(); table.setEditable(true); DefaultTreeCellEditor editor = new DefaultTreeCellEditor(null, null) { @Override public boolean stopCellEditing() { String value = String.valueOf(getCellEditorValue()); if (value.startsWith("s")) { return false; } return super.stopCellEditing(); } }; table.setCellEditor(editor); JXFrame frame = wrapWithScrollingInFrame(table, new JButton("something to focus"), "JXTree: toggle invokesStopEditing "); Action toggleTerminate = new AbstractAction("toggleInvokesStop") { public void actionPerformed(ActionEvent e) { table.setInvokesStopCellEditing(!table.getInvokesStopCellEditing()); } }; addAction(frame, toggleTerminate); frame.setVisible(true); } /** * visualize editing of the hierarchical column, both * in a tree and a xTree switching CO. * using DefaultXTreeCellEditor. */ public void interactiveXTreeEditingRToL() { JTree tree = new JTree(); tree.setEditable(true); JXTree xTree = new JXTree(); xTree.setCellRenderer(new DefaultTreeRenderer()); xTree.setEditable(true); final JXFrame frame = wrapWithScrollingInFrame(xTree, tree, "XEditing: compare JXTree vs. JTree"); addComponentOrientationToggle(frame); addMessage(frame, "JXTree configured with SwingX renderer/treeEditor"); show(frame); } /** * Issue ??: Background highlighters not working on JXTree. * */ public void interactiveUnselectedFocusedBackground() { JXTree xtree = new JXTree(treeTableModel); xtree.setCellRenderer(new DefaultTreeRenderer()); xtree.setBackground(new Color(0xF5, 0xFF, 0xF5)); JTree tree = new JTree(treeTableModel); tree.setBackground(new Color(0xF5, 0xFF, 0xF5)); JXFrame frame = wrapWithScrollingInFrame(xtree, tree, "Unselected focused background: JXTree/JTree" ); addMessage(frame, "xtree uses swingx renderer"); } /** * Issue #503-swingx: JXList rolloverEnabled disables custom cursor. * * Sanity test for JXTree (looks okay). * */ public void interactiveTestRolloverHighlightCustomCursor() { JXTree tree = new JXTree(treeTableModel); tree.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); tree.setRolloverEnabled(true); tree.setHighlighters(createRolloverHighlighter(true)); showWithScrollingInFrame(tree, "foreground rollover, custom cursor " ); } public void interactiveTestDepthHighlighter() { JXTree tree = new JXTree(treeTableModel); tree.setHighlighters(createDepthHighlighters()); showWithScrollingInFrame(tree, "Depth highlighter" ); } public void interactiveTestEditabilityHighlighter() { JXTree tree = new JXTree(treeTableModel); tree.setEditable(true); tree.setHighlighters(new ColorHighlighter(HighlightPredicate.EDITABLE, Color.WHITE, Color.RED)); showWithScrollingInFrame(tree, "Editability highlighter" ); } /** * Issue ??: Background highlighters not working on JXTree. * * Works with SwingX renderer */ public void interactiveTestRolloverHighlightBackground() { JXTree tree = new JXTree(treeTableModel); tree.setRolloverEnabled(true); tree.setCellRenderer(new DefaultTreeRenderer()); tree.setHighlighters(createRolloverHighlighter(false)); JXFrame frame = wrapWithScrollingInFrame(tree, "Rollover - background " ); addMessage(frame, "here we use a SwingX renderer - backgound okay"); show(frame); } private Highlighter createRolloverHighlighter(boolean useForeground) { Color color = new Color(0xF0, 0xF0, 0xE0); //LegacyHighlighter.ledgerBackground.getBackground(); Highlighter highlighter = new ColorHighlighter( HighlightPredicate.ROLLOVER_ROW, useForeground ? null : color, useForeground ? color.darker() : null); return highlighter; } private Highlighter[] createDepthHighlighters() { Highlighter[] highlighters = new Highlighter[2]; highlighters[0] = new ColorHighlighter(new DepthHighlightPredicate(1), Color.WHITE, Color.RED); highlighters[1] = new ColorHighlighter(new DepthHighlightPredicate(2), Color.WHITE, Color.BLUE); return highlighters; } /** * Issue ??: Background highlighters not working on JXTree. * * It's a problem of core DefaultTreeCellRenderer. SwingX renderers are okay. * */ public void interactiveTestHighlighters() { JXTree tree = new JXTree(treeTableModel); String pattern = "o"; tree.setHighlighters(new ColorHighlighter(new PatternPredicate(pattern, 0), Color.YELLOW, Color.RED), HighlighterFactory.createSimpleStriping(HighlighterFactory.LINE_PRINTER)); JXFrame frame = wrapWithScrollingInFrame(tree, "Foreground/background Highlighter: " + pattern); addMessage(frame, "here we use a core default renderer - background highlighter not working!"); show(frame); } public void interactiveTestToolTips() { JXTree tree = new JXTree(treeTableModel); // JW: don't use this idiom - Stackoverflow... // multiple delegation - need to solve or discourage tree.setCellRenderer(createRenderer()); // JW: JTree does not automatically register itself // should JXTree? ToolTipManager toolTipManager = ToolTipManager.sharedInstance(); toolTipManager.registerComponent(tree); showWithScrollingInFrame(tree, "tooltips"); } private TreeCellRenderer createRenderer() { final TreeCellRenderer delegate = new DefaultTreeCellRenderer(); TreeCellRenderer renderer = new TreeCellRenderer() { public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component result = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); ((JComponent) result).setToolTipText(String.valueOf(tree.getPathForRow(row))); return result; } }; return renderer; } /** * test if lineStyle client property is respected by JXTree. * Note that some LFs don't respect anyway (WinLF f.i.) */ public void interactiveTestLineStyle() { JXTree tree = new JXTree(treeTableModel); tree.setDragEnabled(true); tree.putClientProperty("JTree.lineStyle", "None"); showWithScrollingInFrame(tree, "LineStyle Test - none"); } /** * setting tree properties: JXTree is updated properly. */ public void interactiveTestTreeProperties() { final JXTree treeTable = new JXTree(treeTableModel); Action toggleHandles = new AbstractAction("Toggle Handles") { public void actionPerformed(ActionEvent e) { treeTable.setShowsRootHandles(!treeTable.getShowsRootHandles()); } }; Action toggleRoot = new AbstractAction("Toggle Root") { public void actionPerformed(ActionEvent e) { treeTable.setRootVisible(!treeTable.isRootVisible()); } }; treeTable.setRowHeight(22); JXFrame frame = wrapWithScrollingInFrame(treeTable, "Toggle Tree properties "); addAction(frame, toggleRoot); addAction(frame, toggleHandles); show(frame); } /** * Ensure that the root node is expanded if invisible and child added. */ public void interactiveRootExpansionTest() { final DefaultMutableTreeNode root = new DefaultMutableTreeNode("root"); final DefaultTreeModel model = new DefaultTreeModel(root); final JXTree tree = new JXTree(model); tree.setRootVisible(false); assertFalse(tree.isExpanded(new TreePath(root))); Action addChild = new AbstractAction("Add Root Child") { private int counter = 0; public void actionPerformed(ActionEvent e) { root.add(new DefaultMutableTreeNode("Child " + (counter + 1))); model.nodesWereInserted(root, new int[]{counter}); counter++; assertTrue(tree.isExpanded(new TreePath(root))); } }; JXFrame frame = wrapWithScrollingInFrame(tree, "Root Node Expansion Test"); addAction(frame, addChild); show(frame); } }
package com.sensei.search.nodes; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.apache.lucene.search.Query; import proj.zoie.api.DefaultZoieVersion; import proj.zoie.api.IndexReaderFactory; import proj.zoie.api.ZoieIndexReader; import proj.zoie.api.ZoieIndexReader.SubReaderAccessor; import proj.zoie.api.ZoieIndexReader.SubReaderInfo; import proj.zoie.mbean.ZoieSystemAdminMBean; import proj.zoie.impl.indexing.ZoieSystem; import com.browseengine.bobo.api.BoboBrowser; import com.browseengine.bobo.api.BoboIndexReader; import com.browseengine.bobo.api.BrowseException; import com.browseengine.bobo.api.BrowseHit; import com.browseengine.bobo.api.BrowseRequest; import com.browseengine.bobo.api.BrowseResult; import com.browseengine.bobo.api.MultiBoboBrowser; import com.google.protobuf.Message; import com.google.protobuf.TextFormat; import com.linkedin.norbert.javacompat.network.MessageHandler; import com.sensei.search.client.ResultMerger; import com.sensei.search.req.SenseiHit; import com.sensei.search.req.SenseiSystemInfo; import com.sensei.search.req.protobuf.SenseiSysRequestBPO; import com.sensei.search.req.protobuf.SenseiSysRequestBPOConverter; import com.sensei.search.req.protobuf.SenseiSysResultBPO.Result; import com.sensei.search.util.RequestConverter; public class SenseiNodeSysMessageHandler implements MessageHandler { private static final Logger logger = Logger.getLogger(SenseiNodeSysMessageHandler.class); private final Map<Integer,SenseiQueryBuilderFactory> _builderFactoryMap; private final Map<Integer,IndexReaderFactory<ZoieIndexReader<BoboIndexReader>>> _partReaderMap; public SenseiNodeSysMessageHandler(SenseiSearchContext ctx) { _builderFactoryMap = ctx.getQueryBuilderFactoryMap(); _partReaderMap = ctx.getPartitionReaderMap(); } public Message[] getMessages() { return new Message[] { SenseiSysRequestBPO.Request.getDefaultInstance() }; } public Message handleMessage(Message msg) throws Exception { SenseiSysRequestBPO.Request req = (SenseiSysRequestBPO.Request) msg; if (logger.isDebugEnabled()){ String reqString = TextFormat.printToString(req); reqString = reqString.replace('\r', ' ').replace('\n', ' '); } SenseiSystemInfo result = new SenseiSystemInfo(); Set<Integer> partitions = _partReaderMap.keySet(); if (partitions!=null && partitions.size() > 0){ logger.info("serving partitions: "+ partitions.toString()); int numDocs = 0; Date lastModified = new Date(0L); DefaultZoieVersion version = (new DefaultZoieVersion.DefaultZoieVersionFactory()).getZoieVersion("0"); for (int partition : partitions){ try{ ZoieSystem<BoboIndexReader,?,DefaultZoieVersion> zoieSystem = (ZoieSystem<BoboIndexReader,?,DefaultZoieVersion>)_partReaderMap.get(partition); ZoieSystemAdminMBean zoieSystemAdminMBean = zoieSystem.getAdminMBean(); if (lastModified.getTime() < zoieSystemAdminMBean.getLastDiskIndexModifiedTime().getTime()) lastModified = zoieSystemAdminMBean.getLastDiskIndexModifiedTime(); if (version.compareTo(zoieSystem.getVersion()) < 0) version = zoieSystem.getVersion(); List<ZoieIndexReader<BoboIndexReader>> readerList = null; try{ readerList = zoieSystem.getIndexReaders(); if (readerList != null) { for (ZoieIndexReader<BoboIndexReader> reader:readerList) { numDocs += reader.numDocs(); } } } finally{ if (readerList!=null){ zoieSystem.returnIndexReaders(readerList); } } } catch(Exception e){ logger.error(e.getMessage(),e); } } result.setNumDocs(numDocs); result.setLastModified(lastModified.getTime()); result.setVersion(version.toString()); } else{ logger.info("no partitions specified"); } Result returnvalue = SenseiSysRequestBPOConverter.convert(result); logger.info("searching partitions " + partitions.toString()); return returnvalue; } }
package com.thaiopensource.datatype.xsd; import java.util.Hashtable; import org.xml.sax.XMLReader; import com.thaiopensource.datatype.DatatypeFactory; import com.thaiopensource.datatype.Datatype; import com.thaiopensource.datatype.DatatypeReader; import com.thaiopensource.datatype.DatatypeContext; import com.thaiopensource.datatype.DatatypeAssignment; public class DatatypeFactoryImpl implements DatatypeFactory { static private final String xsdns = "http: private final Hashtable typeTable = new Hashtable(); private RegexEngine regexEngine; static private final String LONG_MAX = "9223372036854775807"; static private final String LONG_MIN = "-9223372036854775808"; static private final String INT_MAX = "2147483647"; static private final String INT_MIN = "-2147483648"; static private final String SHORT_MAX = "32767"; static private final String SHORT_MIN = "-32768"; static private final String BYTE_MAX = "127"; static private final String BYTE_MIN = "-128"; static private final String UNSIGNED_LONG_MAX = "18446744073709551615"; static private final String UNSIGNED_INT_MAX = "4294967295"; static private final String UNSIGNED_SHORT_MAX = "65535"; static private final String UNSIGNED_BYTE_MAX = "255"; public DatatypeFactoryImpl() { this(new NullRegexEngine()); } public DatatypeFactoryImpl(RegexEngine regexEngine) { this.regexEngine = regexEngine; typeTable.put("string", new StringDatatype()); typeTable.put("normalizedString", new CdataDatatype()); typeTable.put("token", new TokenDatatype()); typeTable.put("boolean", new BooleanDatatype()); DatatypeBase decimalType = new DecimalDatatype(); typeTable.put("decimal", decimalType); DatatypeBase integerType = new ScaleRestrictDatatype(decimalType, 0); typeTable.put("integer", integerType); typeTable.put("nonPositiveInteger", restrictMax(integerType, "0")); typeTable.put("negativeInteger", restrictMax(integerType, "-1")); typeTable.put("long", restrictMax(restrictMin(integerType, LONG_MIN), LONG_MAX)); typeTable.put("int", restrictMax(restrictMin(integerType, INT_MIN), INT_MAX)); typeTable.put("short", restrictMax(restrictMin(integerType, SHORT_MIN), SHORT_MAX)); typeTable.put("byte", restrictMax(restrictMin(integerType, BYTE_MIN), BYTE_MAX)); DatatypeBase nonNegativeIntegerType = restrictMin(integerType, "0"); typeTable.put("nonNegativeInteger", nonNegativeIntegerType); typeTable.put("unsignedLong", restrictMax(nonNegativeIntegerType, UNSIGNED_LONG_MAX)); typeTable.put("unsignedInt", restrictMax(nonNegativeIntegerType, UNSIGNED_INT_MAX)); typeTable.put("unsignedShort", restrictMax(nonNegativeIntegerType, UNSIGNED_SHORT_MAX)); typeTable.put("unsignedByte", restrictMax(nonNegativeIntegerType, UNSIGNED_BYTE_MAX)); typeTable.put("positiveInteger", restrictMin(integerType, "1")); typeTable.put("double", new DoubleDatatype()); typeTable.put("float", new FloatDatatype()); typeTable.put("Name", new NameDatatype()); typeTable.put("QName", new QNameDatatype()); DatatypeBase ncNameType = new NCNameDatatype(); typeTable.put("NCName", ncNameType); DatatypeBase nmtokenDatatype = new NmtokenDatatype(); typeTable.put("NMTOKEN", nmtokenDatatype); typeTable.put("NMTOKENS", list(nmtokenDatatype)); typeTable.put("ID", new IdDatatype()); DatatypeBase idrefType = new IdrefDatatype(); typeTable.put("IDREF", idrefType); typeTable.put("IDREFS", list(idrefType)); // Partially implemented DatatypeBase entityType = ncNameType; typeTable.put("ENTITY", entityType); typeTable.put("ENTITIES", list(entityType)); typeTable.put("NOTATION", new NameDatatype()); typeTable.put("language", new LanguageDatatype()); // Not implemented yet typeTable.put("anyURI", new StringDatatype()); typeTable.put("base64Binary", new StringDatatype()); typeTable.put("hexBinary", new StringDatatype()); typeTable.put("duration", new StringDatatype()); typeTable.put("dateTime", new StringDatatype()); typeTable.put("time", new StringDatatype()); typeTable.put("date", new StringDatatype()); typeTable.put("gYearMonth", new StringDatatype()); typeTable.put("gYear", new StringDatatype()); typeTable.put("gMonthDay", new StringDatatype()); typeTable.put("gDay", new StringDatatype()); typeTable.put("gMonth", new StringDatatype()); } public Datatype createDatatype(String namespaceURI, String localName) { if (xsdns.equals(namespaceURI)) return createXsdDatatype(localName); return null; } public DatatypeReader createDatatypeReader(String namespaceURI, DatatypeContext context) { if (xsdns.equals(namespaceURI)) return new DatatypeReaderImpl(this, context); return null; } public DatatypeAssignment createDatatypeAssignment(XMLReader xr) { return new DatatypeAssignmentImpl(xr); } DatatypeBase createXsdDatatype(String localName) { return (DatatypeBase)typeTable.get(localName); } RegexEngine getRegexEngine() { return regexEngine; } private DatatypeBase restrictMax(DatatypeBase base, String limit) { return new MaxInclusiveRestrictDatatype(base, base.getValue(limit, null)); } private DatatypeBase restrictMin(DatatypeBase base, String limit) { return new MinInclusiveRestrictDatatype(base, base.getValue(limit, null)); } private DatatypeBase list(DatatypeBase base) { return new MinLengthRestrictDatatype(new ListDatatype(base), 1); } }
package org.xwiki.rendering.internal.renderer.wikimodel; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; import java.util.Map; import org.xwiki.rendering.internal.parser.wikimodel.DefaultXWikiGeneratorListener; import org.xwiki.rendering.listener.Format; import org.xwiki.rendering.listener.HeaderLevel; import org.xwiki.rendering.listener.ListType; import org.xwiki.rendering.listener.Listener; import org.xwiki.rendering.listener.MetaData; import org.xwiki.rendering.listener.reference.ResourceReference; import org.xwiki.rendering.syntax.Syntax; import org.xwiki.rendering.wikimodel.IWemConstants; import org.xwiki.rendering.wikimodel.IWemListener; import org.xwiki.rendering.wikimodel.WikiFormat; import org.xwiki.rendering.wikimodel.WikiParameter; import org.xwiki.rendering.wikimodel.WikiParameters; /** * Map XWiki Listener events on to WikiModel events. * * @version $Id$ * @since 1.5RC1 */ public class WikiModelGeneratorListener implements Listener { private IWemListener wikimodelListener; private int docLevel = 1; private Deque<Context> context = new ArrayDeque<Context>(); private class Context { int headerLevel; } public WikiModelGeneratorListener(IWemListener wikimodelListener) { this.wikimodelListener = wikimodelListener; } private Context getContext() { return this.context.peek(); } private Context pushContext() { Context ctx = new Context(); this.context.push(ctx); return ctx; } private Context popContext() { return this.context.pop(); } @Override public void beginDocument(MetaData metadata) { pushContext(); this.wikimodelListener.beginDocument(WikiParameters.EMPTY); this.wikimodelListener.beginSection(this.docLevel, getContext().headerLevel, WikiParameters.EMPTY); this.docLevel++; getContext().headerLevel++; } @Override public void endDocument(MetaData metadata) { this.wikimodelListener.endSection(this.docLevel, getContext().headerLevel, WikiParameters.EMPTY); this.docLevel this.wikimodelListener.endDocument(WikiParameters.EMPTY); popContext(); } @Override public void beginGroup(Map<String, String> parameters) { this.wikimodelListener.beginDocument(createWikiParameters(parameters)); } @Override public void endGroup(Map<String, String> parameters) { this.wikimodelListener.endDocument(createWikiParameters(parameters)); } @Override public void beginFormat(Format format, Map<String, String> parameters) { switch (format) { case BOLD: this.wikimodelListener.beginFormat(new WikiFormat(IWemConstants.STRONG, createWikiParameters(parameters).toList())); break; case ITALIC: this.wikimodelListener.beginFormat(new WikiFormat(IWemConstants.EM, createWikiParameters(parameters) .toList())); break; case STRIKEDOUT: this.wikimodelListener.beginFormat(new WikiFormat(IWemConstants.STRIKE, createWikiParameters(parameters).toList())); break; case UNDERLINED: this.wikimodelListener.beginFormat(new WikiFormat(IWemConstants.INS, createWikiParameters(parameters) .toList())); break; case MONOSPACE: this.wikimodelListener.beginFormat(new WikiFormat(IWemConstants.MONO, createWikiParameters(parameters) .toList())); break; case SUBSCRIPT: this.wikimodelListener.beginFormat(new WikiFormat(IWemConstants.SUB, createWikiParameters(parameters) .toList())); break; case SUPERSCRIPT: this.wikimodelListener.beginFormat(new WikiFormat(IWemConstants.SUP, createWikiParameters(parameters) .toList())); break; case NONE: this.wikimodelListener.beginFormat(new WikiFormat(createWikiParameters(parameters).toList())); break; default: //Unsupported format break; } } @Override public void endFormat(Format format, Map<String, String> parameters) { switch (format) { case BOLD: this.wikimodelListener.endFormat(new WikiFormat(IWemConstants.STRONG, createWikiParameters(parameters) .toList())); break; case ITALIC: this.wikimodelListener.endFormat(new WikiFormat(IWemConstants.EM, createWikiParameters(parameters) .toList())); break; case STRIKEDOUT: this.wikimodelListener.endFormat(new WikiFormat(IWemConstants.STRIKE, createWikiParameters(parameters) .toList())); break; case UNDERLINED: this.wikimodelListener.endFormat(new WikiFormat(IWemConstants.INS, createWikiParameters(parameters) .toList())); break; case MONOSPACE: this.wikimodelListener.endFormat(new WikiFormat(IWemConstants.MONO, createWikiParameters(parameters) .toList())); break; case SUBSCRIPT: this.wikimodelListener.endFormat(new WikiFormat(IWemConstants.SUB, createWikiParameters(parameters) .toList())); break; case SUPERSCRIPT: this.wikimodelListener.endFormat(new WikiFormat(IWemConstants.SUP, createWikiParameters(parameters) .toList())); break; case NONE: this.wikimodelListener.endFormat(new WikiFormat(createWikiParameters(parameters).toList())); break; default: //Unsupported format break; } } @Override public void beginList(ListType type, Map<String, String> parameters) { this.wikimodelListener.beginList(createWikiParameters(parameters), type == ListType.NUMBERED); } @Override public void beginListItem() { this.wikimodelListener.beginListItem(); } @Override public void beginMacroMarker(String name, Map<String, String> parameters, String content, boolean isInline) { // Don't do anything since there's no notion of Macro marker in WikiModel and anyway // there's nothing to render for a marker... } @Override public void beginParagraph(Map<String, String> parameters) { this.wikimodelListener.beginParagraph(createWikiParameters(parameters)); } @Override public void beginSection(Map<String, String> parameters) { this.wikimodelListener .beginSection(this.docLevel, getContext().headerLevel, createWikiParameters(parameters)); getContext().headerLevel++; } @Override public void beginHeader(HeaderLevel level, String id, Map<String, String> parameters) { this.wikimodelListener.beginHeader(level.getAsInt(), createWikiParameters(parameters)); } @Override public void endList(ListType type, Map<String, String> parameters) { this.wikimodelListener.endList(createWikiParameters(parameters), type == ListType.NUMBERED); } @Override public void endListItem() { this.wikimodelListener.endListItem(); } @Override public void endMacroMarker(String name, Map<String, String> parameters, String content, boolean isInline) { // Don't do anything since there's no notion of Macro marker in WikiModel and anyway // there's nothing to render for a marker... } @Override public void endParagraph(Map<String, String> parameters) { this.wikimodelListener.endParagraph(createWikiParameters(parameters)); } @Override public void endSection(Map<String, String> parameters) { this.wikimodelListener .beginSection(this.docLevel, getContext().headerLevel, createWikiParameters(parameters)); getContext().headerLevel } @Override public void endHeader(HeaderLevel level, String id, Map<String, String> parameters) { this.wikimodelListener.endHeader(level.getAsInt(), createWikiParameters(parameters)); } @Override public void beginLink(ResourceReference reference, boolean freestanding, Map<String, String> parameters) { // TODO wait for WikiModel to support wiki syntax in links } @Override public void endLink(ResourceReference reference, boolean freestanding, Map<String, String> parameters) { // TODO wait for WikiModel to support wiki syntax in links } @Override public void onMacro(String id, Map<String, String> parameters, String content, boolean inline) { if (inline) { this.wikimodelListener.onMacroInline(id, createWikiParameters(parameters), content); } else { this.wikimodelListener.onMacroBlock(id, createWikiParameters(parameters), content); } } @Override public void onNewLine() { // TODO: Decide when to generate a line break and when to generate a new line this.wikimodelListener.onNewLine(); } @Override public void onSpace() { this.wikimodelListener.onSpace(" "); } @Override public void onSpecialSymbol(char symbol) { this.wikimodelListener.onSpecialSymbol("" + symbol); } @Override public void onWord(String word) { this.wikimodelListener.onWord(word); } @Override public void onId(String name) { this.wikimodelListener.onExtensionBlock(DefaultXWikiGeneratorListener.EXT_ID, createWikiParameters(Collections .singletonMap("name", name))); } @Override public void onRawText(String text, Syntax syntax) { // Nothing to do since wikimodel doesn't support raw content. } @Override public void onHorizontalLine(Map<String, String> parameters) { this.wikimodelListener.onHorizontalLine(createWikiParameters(parameters)); } @Override public void onEmptyLines(int count) { this.wikimodelListener.onEmptyLines(count); } @Override public void onVerbatim(String content, boolean inline, Map<String, String> parameters) { if (inline) { // TODO: we're currently not handling any inline verbatim parameters (we don't have support for this in // XWiki Blocks for now). this.wikimodelListener.onVerbatimInline(content, WikiParameters.EMPTY); } else { this.wikimodelListener.onVerbatimBlock(content, createWikiParameters(parameters)); } } @Override public void beginDefinitionList(Map<String, String> parameters) { this.wikimodelListener.beginDefinitionList(createWikiParameters(parameters)); } @Override public void endDefinitionList(Map<String, String> parameters) { this.wikimodelListener.endDefinitionList(createWikiParameters(parameters)); } @Override public void beginDefinitionTerm() { this.wikimodelListener.beginDefinitionTerm(); } @Override public void beginDefinitionDescription() { this.wikimodelListener.beginDefinitionDescription(); } @Override public void endDefinitionTerm() { this.wikimodelListener.endDefinitionTerm(); } @Override public void endDefinitionDescription() { this.wikimodelListener.endDefinitionDescription(); } @Override public void beginQuotation(Map<String, String> parameters) { this.wikimodelListener.beginQuotation(createWikiParameters(parameters)); } @Override public void endQuotation(Map<String, String> parameters) { this.wikimodelListener.endQuotation(createWikiParameters(parameters)); } @Override public void beginQuotationLine() { this.wikimodelListener.beginQuotationLine(); } @Override public void endQuotationLine() { this.wikimodelListener.endQuotationLine(); } @Override public void beginTable(Map<String, String> parameters) { this.wikimodelListener.beginTable(createWikiParameters(parameters)); } @Override public void beginTableCell(Map<String, String> parameters) { this.wikimodelListener.beginTableCell(false, createWikiParameters(parameters)); } @Override public void beginTableHeadCell(Map<String, String> parameters) { this.wikimodelListener.beginTableCell(true, createWikiParameters(parameters)); } @Override public void beginTableRow(Map<String, String> parameters) { this.wikimodelListener.beginTableRow(createWikiParameters(parameters)); } @Override public void endTable(Map<String, String> parameters) { this.wikimodelListener.endTable(createWikiParameters(parameters)); } @Override public void endTableCell(Map<String, String> parameters) { this.wikimodelListener.endTableCell(false, createWikiParameters(parameters)); } @Override public void endTableHeadCell(Map<String, String> parameters) { this.wikimodelListener.endTableCell(true, createWikiParameters(parameters)); } @Override public void endTableRow(Map<String, String> parameters) { this.wikimodelListener.endTableRow(createWikiParameters(parameters)); } @Override public void onImage(ResourceReference reference, boolean freestanding, Map<String, String> parameters) { // Note: This means that any WikiModel listener needs to be overridden with a XWiki specific // version that knows how to handle XWiki image location format. // TODO this.wikimodelListener.onReference("image:" + imageLocation); } @Override public void beginMetaData(MetaData metadata) { // WikiModel has a notion of Property but it's different from XWiki's notion of MetaData. We could map some // specific metadata as WikiModel's property but it's not important since it would be useful only to benefit // from WikiModel's Renderer implementations and such implementation won't use XWiki's metadata anyway. } @Override public void endMetaData(MetaData metadata) { // WikiModel has a notion of Property but it's different from XWiki's notion of MetaData. We could map some // specific metadata as WikiModel's property but it's not important since it would be useful only to benefit // from WikiModel's Renderer implementations and such implementation won't use XWiki's metadata anyway. } private WikiParameters createWikiParameters(Map<String, String> parameters) { List<WikiParameter> wikiParams = new ArrayList<WikiParameter>(); for (Map.Entry<String, String> entry : parameters.entrySet()) { wikiParams.add(new WikiParameter(entry.getKey(), entry.getValue())); } return new WikiParameters(wikiParams); } }
package org.lightmare.deploy; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import org.lightmare.cache.MetaContainer; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; /** * Manager class for application deployment * * @author levan * */ public class LoaderPoolManager { // Amount of deployment thread pool private static final int LOADER_POOL_SIZE = 5; // Name prefix of deployment threads private static final String LOADER_THREAD_NAME = "Ejb-Loader-Thread-"; /** * Gets class loader for existing {@link org.lightmare.deploy.MetaCreator} * instance * * @return {@link ClassLoader} */ protected static ClassLoader getCurrent() { ClassLoader current; MetaCreator creator = MetaContainer.getCreator(); ClassLoader creatorLoader; if (ObjectUtils.notNull(creator)) { // Gets class loader for this deployment creatorLoader = creator.getCurrent(); if (ObjectUtils.notNull(creatorLoader)) { current = creatorLoader; } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } return current; } /** * Implementation of {@link ThreadFactory} interface for application loading * * @author levan * */ private static final class LoaderThreadFactory implements ThreadFactory { /** * Constructs and sets thread name * * @param thread */ private void nameThread(Thread thread) { String name = StringUtils .concat(LOADER_THREAD_NAME, thread.getId()); thread.setName(name); } /** * Sets priority of {@link Thread} instance * * @param thread */ private void setPriority(Thread thread) { thread.setPriority(Thread.MAX_PRIORITY); } /** * Sets {@link ClassLoader} to passed {@link Thread} instance * * @param thread */ private void setContextClassLoader(Thread thread) { ClassLoader parent = getCurrent(); thread.setContextClassLoader(parent); } /** * Configures (sets name, priority and {@link ClassLoader}) passed * {@link Thread} instance * * @param thread */ private void configureThread(Thread thread) { nameThread(thread); setPriority(thread); setContextClassLoader(thread); } @Override public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable); configureThread(thread); return thread; } } // Thread pool for deploying and removal of beans and temporal resources private static ExecutorService LOADER_POOL = Executors.newFixedThreadPool( LOADER_POOL_SIZE, new LoaderThreadFactory()); private static boolean invalid() { return LOADER_POOL == null || LOADER_POOL.isShutdown() || LOADER_POOL.isTerminated(); } /** * Checks and if not valid reopens deploy {@link ExecutorService} instance * * @return {@link ExecutorService} */ protected static ExecutorService getLoaderPool() { if (invalid()) { synchronized (LoaderPoolManager.class) { if (invalid()) { LOADER_POOL = Executors.newFixedThreadPool( LOADER_POOL_SIZE, new LoaderThreadFactory()); } } } return LOADER_POOL; } public static void submit(Runnable runnable) { getLoaderPool().submit(runnable); } public static <T> Future<T> submit(Callable<T> callable) { Future<T> future = getLoaderPool().submit(callable); return future; } /** * Clears existing {@link ExecutorService}s from loader threads */ public static void reload() { synchronized (LoaderPoolManager.class) { if (ObjectUtils.notNull(LOADER_POOL)) { LOADER_POOL.shutdown(); LOADER_POOL = null; } } getLoaderPool(); } }
package org.lightmare.deploy; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.lightmare.cache.MetaContainer; import org.lightmare.libraries.LibraryLoader; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.StringUtils; /** * Manager class for application deployment * * @author levan * */ public class LoaderPoolManager { // Amount of deployment thread pool private static final int LOADER_POOL_SIZE = 5; // Name prefix of deployment threads private static final String LOADER_THREAD_NAME = "Ejb-Loader-Thread-"; // Lock for pool reopening private static final Lock LOCK = new ReentrantLock(); /** * Tries to lock Lock object or waits while locks * * @return <code>boolean</code> */ private static boolean tryLock() { boolean locked = LOCK.tryLock(); while (ObjectUtils.notTrue(locked)) { locked = LOCK.tryLock(); } return locked; } /** * Releases lock */ private static void unlock() { LOCK.unlock(); } /** * Gets class loader for existing {@link org.lightmare.deploy.MetaCreator} * instance * * @return {@link ClassLoader} */ protected static ClassLoader getCurrent() { ClassLoader current; MetaCreator creator = MetaContainer.getCreator(); ClassLoader creatorLoader; if (ObjectUtils.notNull(creator)) { // Gets class loader for this deployment creatorLoader = creator.getCurrent(); if (ObjectUtils.notNull(creatorLoader)) { current = creatorLoader; } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } } else { // Gets default, context class loader for current thread current = LibraryLoader.getContextClassLoader(); } return current; } /** * Implementation of {@link ThreadFactory} interface for application loading * * @author levan * */ private static final class LoaderThreadFactory implements ThreadFactory { /** * Constructs and sets thread name * * @param thread */ private void nameThread(Thread thread) { String name = StringUtils .concat(LOADER_THREAD_NAME, thread.getId()); thread.setName(name); } /** * Sets priority of {@link Thread} instance * * @param thread */ private void setPriority(Thread thread) { thread.setPriority(Thread.MAX_PRIORITY); } /** * Sets {@link ClassLoader} to passed {@link Thread} instance * * @param thread */ private void setContextClassLoader(Thread thread) { ClassLoader parent = getCurrent(); thread.setContextClassLoader(parent); } /** * Configures (sets name, priority and {@link ClassLoader}) passed * {@link Thread} instance * * @param thread */ private void configureThread(Thread thread) { nameThread(thread); setPriority(thread); setContextClassLoader(thread); } @Override public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable); configureThread(thread); return thread; } } // Thread pool for deploying and removal of beans and temporal resources private static ExecutorService LOADER_POOL; /** * Checks if loader {@link ExecutorService} is null or is shut down or is * terminated * * @return <code>boolean</code> */ private static boolean invalid() { return LOADER_POOL == null || LOADER_POOL.isShutdown() || LOADER_POOL.isTerminated(); } private static void initLoaderPool() { if (invalid()) { LOADER_POOL = Executors.newFixedThreadPool(LOADER_POOL_SIZE, new LoaderThreadFactory()); } } /** * Checks and if not valid reopens deploy {@link ExecutorService} instance * * @return {@link ExecutorService} */ protected static ExecutorService getLoaderPool() { if (invalid()) { boolean locked = tryLock(); if (locked) { try { initLoaderPool(); } finally { unlock(); } } } return LOADER_POOL; } /** * Submit passed {@link Runnable} implementation in loader pool * * @param runnable */ public static void submit(Runnable runnable) { ExecutorService pool = getLoaderPool(); pool.submit(runnable); } /** * Submits passed {@link Callable} implementation in loader pool * * @param callable * @return {@link Future}<code><T></code> */ public static <T> Future<T> submit(Callable<T> callable) { ExecutorService pool = getLoaderPool(); Future<T> future = pool.submit(callable); return future; } /** * Clears existing {@link ExecutorService}s from loader threads */ public static void reload() { boolean locked = tryLock(); if (locked) { try { if (ObjectUtils.notNull(LOADER_POOL)) { LOADER_POOL.shutdown(); LOADER_POOL = null; } } finally { unlock(); } } } }
package me.nallar.tickthreading.patcher; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.jar.JarFile; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import me.nallar.tickthreading.Log; import me.nallar.tickthreading.mappings.ClassDescription; import me.nallar.tickthreading.mappings.Mappings; import me.nallar.tickthreading.mappings.MethodDescription; import me.nallar.tickthreading.util.DomUtil; import me.nallar.tickthreading.util.ListUtil; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class PatchManager { private Document configDocument; private Patches patchTypes; // Patch name -> patch method descriptor private Map<String, PatchMethodDescriptor> patches = new HashMap<String, PatchMethodDescriptor>(); public final ClassRegistry classRegistry = new ClassRegistry(); public PatchManager(InputStream configStream, Class<Patches> patchClass) throws IOException, SAXException { loadPatches(patchClass); configDocument = loadConfig(configStream); } public void loadPatches(Class<Patches> patchClass) { try { patchTypes = patchClass.newInstance(); } catch (Exception e) { Log.severe("Failed to instantiate patch class", e); } for (Method method : patchClass.getDeclaredMethods()) { for (Annotation annotation : method.getDeclaredAnnotations()) { if (annotation instanceof Patch) { PatchMethodDescriptor patchMethodDescriptor = new PatchMethodDescriptor(method, (Patch) annotation); patches.put(patchMethodDescriptor.name, patchMethodDescriptor); } } } } public static Document loadConfig(InputStream configInputStream) throws IOException, SAXException { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); return docBuilder.parse(configInputStream); } catch (ParserConfigurationException e) { //This exception is thrown, and no shorthand way of getting a DocumentBuilder without it. //Should not be thrown, as we do not do anything to the DocumentBuilderFactory. Log.severe("Java was bad, you shouldn't see this. DocBuilder instantiation via default docBuilderFactory failed", e); } return null; } public void obfuscate(Mappings mappings) { NodeList classNodes = ((Element) configDocument.getElementsByTagName("minecraftCommon").item(0)).getElementsByTagName("class"); for (Element classElement : DomUtil.elementList(classNodes)) { String className = classElement.getAttribute("id"); ClassDescription deobfuscatedClass = new ClassDescription(className); ClassDescription obfuscatedClass = mappings.map(deobfuscatedClass); classElement.setAttribute("id", obfuscatedClass.name); NodeList patchElements = classElement.getChildNodes(); for (Element patchElement : DomUtil.elementList(patchElements)) { if (!patchElement.getTextContent().isEmpty()) { patchElement.setTextContent(MethodDescription.toListString(mappings.map(MethodDescription.fromListString(deobfuscatedClass.name, patchElement.getTextContent())))); } } } } public Map<String, Integer> getHashes() { Map<String, Integer> hashes = new TreeMap<String, Integer>(); List<Element> modElements = DomUtil.elementList(configDocument.getDocumentElement().getChildNodes()); for (Element modElement : modElements) { for (Element classElement : DomUtil.getElementsByTag(modElement, "class")) { hashes.put(classElement.getAttribute("id"), DomUtil.getHash(classElement)); } } return hashes; } public static boolean shouldPatch(File serverLocation) { try { PatchManager patchManager = new PatchManager(PatchMain.class.getResourceAsStream("/patches.xml"), Patches.class); patchManager.classRegistry.loadJars(new File(serverLocation.getParentFile(), "mods")); patchManager.classRegistry.loadJar(new JarFile(serverLocation)); patchManager.classRegistry.finishModifications(); patchManager.classRegistry.loadPatchHashes(patchManager); return patchManager.classRegistry.shouldPatch(); } catch (Exception e) { Log.severe("Failed to determine whether patches should run", e); } return false; } public void runPatches() { List<Element> modElements = DomUtil.elementList(configDocument.getDocumentElement().getChildNodes()); for (Element modElement : modElements) { for (Element classElement : DomUtil.getElementsByTag(modElement, "class")) { CtClass ctClass; try { ctClass = classRegistry.getClass(classElement.getAttribute("id")); } catch (NotFoundException e) { Log.info("Not patching " + classElement.getAttribute("id") + ", not found or already patched."); continue; } List<Element> patchElements = DomUtil.elementList(classElement.getChildNodes()); boolean patched = false; for (Element patchElement : patchElements) { PatchMethodDescriptor patch = patches.get(patchElement.getTagName()); if (patch == null) { Log.severe("Patch " + patchElement.getTagName() + " was not found."); continue; } try { patch.run(patchElement, ctClass); patched = true; } catch (Exception e) { Log.severe("Failed to patch " + ctClass + " with " + patch.name + " :("); } } if (patched) { try { classRegistry.update(classElement.getAttribute("id"), ctClass.toBytecode()); } catch (Exception e) { Log.severe("Javassist failed to save " + ctClass.getName(), e); } } } } try { classRegistry.save(); } catch (IOException e) { Log.severe("Failed to save patched classes", e); } } public void save(File file) throws TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); Result output = new StreamResult(file); Source input = new DOMSource(configDocument); transformer.transform(input, output); } public static Map<String, String> getAttributes(Node node) { NamedNodeMap attributeMap = node.getAttributes(); HashMap<String, String> attributes = new HashMap<String, String>(attributeMap.getLength()); for (int i = 0; i < attributeMap.getLength(); i++) { Node attr = attributeMap.item(i); if (attr instanceof Attr) { attributes.put(((Attr) attr).getName(), ((Attr) attr).getValue()); } } return attributes; } public class PatchMethodDescriptor { public String name; public List<String> requiredAttributes; public Method patchMethod; public PatchMethodDescriptor(Method method, Patch patch) { this.name = patch.name(); this.requiredAttributes = ListUtil.split(patch.requiredAttributes()); if (this.name == null || this.name.isEmpty()) { this.name = method.getName(); } patchMethod = method; } public void run(Element patchElement, CtClass ctClass) { Log.fine("Patching " + ctClass.getName() + " with " + this.name); if (patchElement.getTextContent().isEmpty()) { run(ctClass); } else { List<MethodDescription> methodDescriptions = MethodDescription.fromListString(ctClass.getName(), patchElement.getTextContent()); Log.fine("Patching methods " + methodDescriptions.toString()); for (MethodDescription methodDescription : methodDescriptions) { try { run(methodDescription.inClass(ctClass)); } catch (Exception e) { Log.severe("Error patching " + methodDescription.getMCPName() + " in " + ctClass, e); } } } } private void run(CtClass clazz) { try { patchMethod.invoke(patchTypes, clazz); } catch (Exception e) { Log.severe("Failed to invoke class patch " + this, e); } } private void run(CtMethod method) { try { patchMethod.invoke(patchTypes, method); } catch (Exception e) { Log.severe("Failed to invoke method patch " + this, e); } } } }
package org.lightmare.ejb.handlers; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.PersistenceUnit; import javax.transaction.UserTransaction; import org.lightmare.cache.ConnectionData; import org.lightmare.cache.InjectionData; import org.lightmare.cache.InterceptorData; import org.lightmare.cache.MetaContainer; import org.lightmare.cache.MetaData; import org.lightmare.ejb.EjbConnector; import org.lightmare.ejb.interceptors.InvocationContextImpl; import org.lightmare.jpa.jta.BeanTransactions; import org.lightmare.utils.ObjectUtils; import org.lightmare.utils.reflect.MetaUtils; /** * Handler class to intercept bean method calls to provide database transactions * * @author Levan * */ public class BeanHandler implements InvocationHandler { private final Object bean; private final Field transactionField; private final Collection<ConnectionData> connections; private final Collection<InjectionData> injects; private final MetaData metaData; public BeanHandler(final MetaData metaData, final Object bean) { this.bean = bean; this.transactionField = metaData.getTransactionField(); this.connections = metaData.getConnections(); this.injects = metaData.getInjects(); this.metaData = metaData; } /** * Sets each injected ejb bean as value to annotated field respectively for * passed {@link InjectionData} object */ private void configureInject(InjectionData inject) throws IOException { MetaData injectMetaData = inject.getMetaData(); if (injectMetaData == null) { String beanName; String mappedName = inject.getMappedName(); if (mappedName == null || mappedName.isEmpty()) { beanName = inject.getName(); } else { beanName = inject.getMappedName(); } injectMetaData = MetaContainer.getSyncMetaData(beanName); injectMetaData.setInterfaceClasses(inject.getInterfaceClasses()); inject.setMetaData(injectMetaData); } EjbConnector ejcConnector = new EjbConnector(); Object injectBean = ejcConnector.connectToBean(injectMetaData); MetaUtils.setFieldValue(inject.getField(), bean, injectBean); } /** * Sets injected ejb bean as values to {@link javax.ejb.EJB} annotated * fields respectively * * @throws IOException */ private void configureInjects() throws IOException { if (ObjectUtils.available(injects)) { for (InjectionData inject : injects) { configureInject(inject); } } } /** * Method to configure (injections {@link javax.ejb.EJB} or * {@link PersistenceUnit} annotated fields and etc.) {@link BeanHandler} * after initialization * * @throws IOException */ public void configure() throws IOException { // TODO Add other configurations configureInjects(); } /** * Sets passed value to beans {@link Field} * * @param field * @param value * @throws IOException */ private void setFieldValue(Field field, Object value) throws IOException { MetaUtils.setFieldValue(field, bean, value); } /** * Invokes passed bean {@link Method} * * @param method * @param arguments * @return {@link Object} * @throws IOException */ private Object invoke(Method method, Object... arguments) throws IOException { return MetaUtils.invoke(method, bean, arguments); } private void setConnection(Field connectionField, EntityManager em) throws IOException { setFieldValue(connectionField, em); } /** * Creates and caches {@link UserTransaction} per thread * * @param em * @return {@link UserTransaction} */ private UserTransaction getTransaction(Collection<EntityManager> ems) { UserTransaction transaction = BeanTransactions.getTransaction(ems); return transaction; } private void setTransactionField(Collection<EntityManager> ems) throws IOException { if (ObjectUtils.notNull(transactionField)) { UserTransaction transaction = getTransaction(ems); setFieldValue(transactionField, transaction); } } private EntityManager createEntityManager(ConnectionData connection) throws IOException { EntityManagerFactory emf = connection.getEmf(); Field connectionField = connection.getConnectionField(); Field unitField = connection.getUnitField(); EntityManager em = null; if (ObjectUtils.notNull(emf)) { em = emf.createEntityManager(); if (ObjectUtils.notNull(unitField)) { setFieldValue(unitField, emf); } setConnection(connectionField, em); } return em; } private Collection<EntityManager> createEntityManagers() throws IOException { Collection<EntityManager> ems = null; if (ObjectUtils.available(connections)) { ems = new ArrayList<EntityManager>(); for (ConnectionData connection : connections) { EntityManager em = createEntityManager(connection); ems.add(em); } } return ems; } /** * Closes {@link EntityManager} if there is not * {@link javax.annotation.Resource} annotation in current bean * * @param transaction * @param em */ private void close(Method method) throws IOException { try { if (ObjectUtils.notNull(method)) { if (transactionField == null) { BeanTransactions.commitTransaction(this, method); } else { BeanTransactions.closeEntityManagers(); } } } finally { BeanTransactions.remove(this, method); } } private void fillInterceptor(InterceptorData interceptorData, Queue<Method> methods, Queue<Object> targets) throws IOException { Class<?> interceptorClass = interceptorData.getInterceptorClass(); Object interceptor = MetaUtils.instantiate(interceptorClass); Method method = interceptorData.getInterceptorMethod(); methods.offer(method); targets.offer(interceptor); } private boolean checkInterceptor(InterceptorData interceptor, Method method) { boolean valid; Method beanMethod = interceptor.getBeanMethod(); if (ObjectUtils.notNull(beanMethod)) { valid = beanMethod.equals(method); } else { valid = Boolean.TRUE; } return valid; } /** * Invokes first method from {@link javax.interceptor.Interceptors} * annotated data * * @param method * @param parameters * @throws IOException */ private void callInterceptors(Method method, Object[] parameters) throws IOException { Collection<InterceptorData> interceptorsCollection = metaData .getInterceptors(); if (ObjectUtils.available(interceptorsCollection)) { Iterator<InterceptorData> interceptors = interceptorsCollection .iterator(); InterceptorData interceptor; Queue<Method> methods = new LinkedList<Method>(); Queue<Object> targets = new LinkedList<Object>(); boolean valid; while (interceptors.hasNext()) { interceptor = interceptors.next(); valid = checkInterceptor(interceptor, method); if (valid) { fillInterceptor(interceptor, methods, targets); } } InvocationContextImpl context = new InvocationContextImpl(methods, targets, parameters); try { context.proceed(); } catch (Exception ex) { throw new IOException(ex); } } } private Object invokeBeanMethod(final Collection<EntityManager> ems, final Method method, Object[] arguments) throws IOException { if (transactionField == null) { BeanTransactions.addTransaction(this, method, ems); } else { setTransactionField(ems); } // Calls interceptors for this method or bean instance callInterceptors(method, arguments); Object value = invoke(method, arguments); return value; } /** * Calls {@link BeanTransactions#rollbackTransaction(BeanHandler, Method))} * is case of {@link Throwable} is thrown at passed {@link Method} execution * time * * @param method * @throws IOException */ private void rollback(Method method) throws IOException { if (ObjectUtils.notNull(method)) { BeanTransactions.rollbackTransaction(this, method); } } @Override public Object invoke(Object proxy, Method method, Object[] arguments) throws Throwable { Collection<EntityManager> ems = createEntityManagers(); Method realMethod = null; try { Class<?> beanClass = metaData.getBeanClass(); String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); realMethod = MetaUtils.getDeclaredMethod(beanClass, methodName, parameterTypes); Object value; value = invokeBeanMethod(ems, realMethod, arguments); return value; } catch (Throwable th) { rollback(realMethod); throw new Throwable(th); } finally { close(realMethod); } } public MetaData getMetaData() { return metaData; } }
package org.lightmare.ejb.handlers; import java.lang.reflect.Method; /** * Handler class to call bean methods for REST services * * @author levan * */ public class RestHandler<T> { private final BeanHandler handler; private final T bean; public RestHandler(BeanHandler handler, T bean) { this.handler = handler; this.bean = bean; } public Object invoke(Method method, Object[] args) throws Throwable { return handler.invoke(bean, method, args); } }
package org.innovateuk.ifs.project.eligibility.saver; import org.innovateuk.ifs.application.forms.hecpcosts.form.HorizonEuropeGuaranteeCostsForm; import org.innovateuk.ifs.finance.resource.ProjectFinanceResource; import org.innovateuk.ifs.finance.resource.cost.*; import org.innovateuk.ifs.finance.service.ProjectFinanceRowRestService; import org.innovateuk.ifs.project.finance.service.ProjectFinanceRestService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.math.BigDecimal; import java.math.BigInteger; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.innovateuk.ifs.commons.rest.RestResult.restSuccess; import static org.innovateuk.ifs.finance.builder.DefaultCostCategoryBuilder.newDefaultCostCategory; import static org.innovateuk.ifs.finance.builder.EquipmentCostBuilder.newEquipment; import static org.innovateuk.ifs.finance.builder.HecpIndirectCostsBuilder.newHecpIndirectCosts; import static org.innovateuk.ifs.finance.builder.HecpIndirectCostsCategoryBuilder.newHecpIndirectCostsCostCategory; import static org.innovateuk.ifs.finance.builder.OtherCostBuilder.newOtherCost; import static org.innovateuk.ifs.finance.builder.OtherGoodsBuilder.newOtherGoods; import static org.innovateuk.ifs.finance.builder.PersonnelCostBuilder.newPersonnelCost; import static org.innovateuk.ifs.finance.builder.PersonnelCostCategoryBuilder.newPersonnelCostCategory; import static org.innovateuk.ifs.finance.builder.ProjectFinanceResourceBuilder.newProjectFinanceResource; import static org.innovateuk.ifs.finance.builder.SubcontractingCostBuilder.newSubContractingCost; import static org.innovateuk.ifs.finance.builder.TravelCostBuilder.newTravelCost; import static org.innovateuk.ifs.finance.resource.category.PersonnelCostCategory.WORKING_DAYS_PER_YEAR; import static org.innovateuk.ifs.util.MapFunctions.asMap; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class FinanceChecksEligibilityHecpCostsSaverTest { private static final long PROJECT_ID = 1L; private static final long ORGANISATION_ID = 2L; @InjectMocks private FinanceChecksEligibilityHecpCostsSaver saver; @Mock private ProjectFinanceRestService projectFinanceRestService; @Mock private ProjectFinanceRowRestService financeRowRestService; @Test public void save() { PersonnelCost workingDays = newPersonnelCost() .withGrossEmployeeCost(BigDecimal.ZERO) .withDescription(WORKING_DAYS_PER_YEAR) .withLabourDays(1) .build(); HecpIndirectCosts hecpIndirectCosts = newHecpIndirectCosts() .withRateType(OverheadRateType.HORIZON_EUROPE_GUARANTEE_TOTAL) .build(); ProjectFinanceResource finance = newProjectFinanceResource().withFinanceOrganisationDetails(asMap( FinanceRowType.PERSONNEL, newPersonnelCostCategory().withCosts(singletonList(workingDays)).build(), FinanceRowType.HECP_INDIRECT_COSTS, newHecpIndirectCostsCostCategory().withCosts(singletonList(hecpIndirectCosts)).build(), FinanceRowType.EQUIPMENT, newDefaultCostCategory().withCosts(emptyList()).build(), FinanceRowType.OTHER_GOODS, newDefaultCostCategory().withCosts(emptyList()).build(), FinanceRowType.SUBCONTRACTING_COSTS, newDefaultCostCategory().withCosts(emptyList()).build(), FinanceRowType.TRAVEL, newDefaultCostCategory().withCosts(emptyList()).build(), FinanceRowType.OTHER_COSTS, newDefaultCostCategory().withCosts(emptyList()).build() )).build(); PersonnelCost newPersonnelCost = newPersonnelCost().build(); Equipment newEquipment = newEquipment().build(); OtherGoods newOtherGoods = newOtherGoods().build(); SubContractingCost newSubcontracting = newSubContractingCost().build(); TravelCost newTravel = newTravelCost().build(); OtherCost newOther = newOtherCost().build(); when(financeRowRestService.create(any(PersonnelCost.class))).thenReturn(restSuccess(newPersonnelCost)); when(financeRowRestService.create(any(Equipment.class))).thenReturn(restSuccess(newEquipment)); when(financeRowRestService.create(any(OtherGoods.class))).thenReturn(restSuccess(newOtherGoods)); when(financeRowRestService.create(any(SubContractingCost.class))).thenReturn(restSuccess(newSubcontracting)); when(financeRowRestService.create(any(TravelCost.class))).thenReturn(restSuccess(newTravel)); when(financeRowRestService.create(any(OtherCost.class))).thenReturn(restSuccess(newOther)); when(projectFinanceRestService.getProjectFinance(PROJECT_ID, ORGANISATION_ID)).thenReturn(restSuccess(finance)); HorizonEuropeGuaranteeCostsForm form = new HorizonEuropeGuaranteeCostsForm(); form.setPersonnel(BigInteger.valueOf(1L)); form.setHecpIndirectCosts(BigInteger.valueOf(2L)); form.setEquipment(BigInteger.valueOf(3L)); form.setOtherGoods(BigInteger.valueOf(4L)); form.setSubcontracting(BigInteger.valueOf(5L)); form.setTravel(BigInteger.valueOf(6L)); form.setOther(BigInteger.valueOf(7L)); saver.save(form, PROJECT_ID, ORGANISATION_ID); verify(financeRowRestService).update(workingDays); verify(financeRowRestService).update(hecpIndirectCosts); verify(financeRowRestService).create(any(PersonnelCost.class)); verify(financeRowRestService).create(any(Equipment.class)); verify(financeRowRestService).create(any(OtherGoods.class)); verify(financeRowRestService).create(any(SubContractingCost.class)); verify(financeRowRestService).create(any(TravelCost.class)); verify(financeRowRestService).create(any(OtherCost.class)); verify(financeRowRestService).update(newPersonnelCost); verify(financeRowRestService).update(newEquipment); verify(financeRowRestService).update(newOtherGoods); verify(financeRowRestService).update(newSubcontracting); verify(financeRowRestService).update(newTravel); verify(financeRowRestService).update(newOther); verifyNoMoreInteractions(financeRowRestService); assertEquals(1L, newPersonnelCost.getTotal(workingDays.getLabourDays()).toBigInteger().longValue()); assertEquals(OverheadRateType.HORIZON_EUROPE_GUARANTEE_TOTAL, hecpIndirectCosts.getRateType()); assertEquals(hecpIndirectCosts.getRate(), (Integer) 2); assertEquals(3L, newEquipment.getTotal().toBigInteger().longValue()); assertEquals(4L, newOtherGoods.getTotal().toBigInteger().longValue()); assertEquals(5L, newSubcontracting.getTotal().toBigInteger().longValue()); assertEquals(6L, newTravel.getTotal().toBigInteger().longValue()); assertEquals(7L, newOther.getTotal().toBigInteger().longValue()); assertEquals(workingDays.getLabourDays(), (Integer) 1); } @Test public void save_zeros() { PersonnelCost workingDays = newPersonnelCost() .withGrossEmployeeCost(BigDecimal.ZERO) .withDescription(WORKING_DAYS_PER_YEAR) .withLabourDays(1) .build(); HecpIndirectCosts hecpIndirectCosts = newHecpIndirectCosts() .withRateType(OverheadRateType.HORIZON_EUROPE_GUARANTEE_TOTAL) .build(); ProjectFinanceResource finance = newProjectFinanceResource().withFinanceOrganisationDetails(asMap( FinanceRowType.PERSONNEL, newPersonnelCostCategory().withCosts(asList(workingDays, newPersonnelCost().build())).build(), FinanceRowType.HECP_INDIRECT_COSTS, newHecpIndirectCostsCostCategory().withCosts(singletonList(hecpIndirectCosts)).build(), FinanceRowType.EQUIPMENT, newDefaultCostCategory().withCosts(newEquipment().build(1)).build(), FinanceRowType.OTHER_GOODS, newDefaultCostCategory().withCosts(newOtherGoods().build(1)).build(), FinanceRowType.SUBCONTRACTING_COSTS, newDefaultCostCategory().withCosts(newSubContractingCost().build(1)).build(), FinanceRowType.TRAVEL, newDefaultCostCategory().withCosts(newTravelCost().build(1)).build(), FinanceRowType.OTHER_COSTS, newDefaultCostCategory().withCosts(newOtherCost().build(1)).build() )).build(); when(projectFinanceRestService.getProjectFinance(PROJECT_ID, ORGANISATION_ID)).thenReturn(restSuccess(finance)); HorizonEuropeGuaranteeCostsForm form = new HorizonEuropeGuaranteeCostsForm(); form.setPersonnel(BigInteger.valueOf(0L)); form.setHecpIndirectCosts(BigInteger.valueOf(0L)); form.setEquipment(BigInteger.valueOf(0L)); form.setOtherGoods(BigInteger.valueOf(0L)); form.setSubcontracting(BigInteger.valueOf(0L)); form.setTravel(BigInteger.valueOf(0L)); form.setOther(BigInteger.valueOf(0L)); saver.save(form, PROJECT_ID, ORGANISATION_ID); verify(financeRowRestService).update(workingDays); verify(financeRowRestService).update(hecpIndirectCosts); verify(financeRowRestService, times(6)).delete(anyLong()); verifyNoMoreInteractions(financeRowRestService); assertEquals(workingDays.getLabourDays(), (Integer) 1); } }
package org.mybatis.jpetstore.domain; import java.io.Serializable; import java.math.BigDecimal; public class Calculate implements Serializable { public void hello() { System.out.println("Hello World"); } } //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck //Description: Adding coments for documentation //Project: JpetStore //Tools used: Jenkins, SonarQube, Rundeck