List of usage examples for java.util Queue add
boolean add(E e);
From source file:replicatorg.app.gcode.GCodeParser.java
private void buildMCodes(GCodeCommand gcode, Queue<DriverCommand> commands) throws GCodeException { // If this machine handles multiple active toolheads, we always honor a T code // as being a annotation to send the given command to the given toolheads. Be // aware that appending a T code to an M code will not necessarily generate a // change tool request! Use M6 for that. if (gcode.hasCode('T') && driver instanceof MultiTool && ((MultiTool) driver).supportsSimultaneousTools()) { commands.add(new replicatorg.drivers.commands.SelectTool((int) gcode.getCodeValue('T'))); tool = (int) gcode.getCodeValue('T'); }//from w w w . j a va 2s . c o m // handle unrecognised GCode if (GCodeEnumeration.getGCode("M", (int) gcode.getCodeValue('M')) == null) { String message = "Unrecognized MCode! M" + (int) gcode.getCodeValue('M'); Base.logger.log(Level.SEVERE, message); throw new GCodeException(message); } switch (GCodeEnumeration.getGCode("M", (int) gcode.getCodeValue('M'))) { case M0: // M0 == unconditional halt commands.add(new replicatorg.drivers.commands.WaitUntilBufferEmpty()); commands.add(new replicatorg.drivers.commands.UnconditionalHalt(gcode.getComment())); break; case M1: // M1 == optional halt commands.add(new replicatorg.drivers.commands.WaitUntilBufferEmpty()); commands.add(new replicatorg.drivers.commands.OptionalHalt(gcode.getComment())); break; case M2: // M2 == program end commands.add(new replicatorg.drivers.commands.WaitUntilBufferEmpty()); commands.add(new replicatorg.drivers.commands.ProgramEnd(gcode.getComment())); break; case M30: commands.add(new replicatorg.drivers.commands.WaitUntilBufferEmpty()); commands.add(new replicatorg.drivers.commands.ProgramRewind(gcode.getComment())); break; // spindle on, CW case M3: commands.add( new replicatorg.drivers.commands.SetSpindleDirection(DriverCommand.AxialDirection.CLOCKWISE)); commands.add(new replicatorg.drivers.commands.EnableSpindle()); break; // spindle on, CCW case M4: commands.add(new replicatorg.drivers.commands.SetSpindleDirection( DriverCommand.AxialDirection.COUNTERCLOCKWISE)); commands.add(new replicatorg.drivers.commands.EnableSpindle()); break; // spindle off case M5: commands.add(new replicatorg.drivers.commands.DisableSpindle()); break; // tool change. case M6: int timeout = 65535; if (gcode.hasCode('P')) { timeout = (int) gcode.getCodeValue('P'); } if (gcode.hasCode('T')) { commands.add( new replicatorg.drivers.commands.RequestToolChange((int) gcode.getCodeValue('T'), timeout)); } else { throw new GCodeException("The T parameter is required for tool changes. (M6)"); } break; // coolant A on (flood coolant) case M7: commands.add(new replicatorg.drivers.commands.EnableFloodCoolant()); break; // coolant B on (mist coolant) case M8: commands.add(new replicatorg.drivers.commands.EnableMistCoolant()); break; // all coolants off case M9: commands.add(new replicatorg.drivers.commands.DisableFloodCoolant()); commands.add(new replicatorg.drivers.commands.DisableMistCoolant()); break; // close clamp case M10: if (gcode.hasCode('Q')) commands.add(new replicatorg.drivers.commands.CloseClamp((int) gcode.getCodeValue('Q'))); else throw new GCodeException("The Q parameter is required for clamp operations. (M10)"); break; // open clamp case M11: if (gcode.hasCode('Q')) commands.add(new replicatorg.drivers.commands.OpenClamp((int) gcode.getCodeValue('Q'))); else throw new GCodeException("The Q parameter is required for clamp operations. (M11)"); break; // spindle CW and coolant A on case M13: commands.add( new replicatorg.drivers.commands.SetSpindleDirection(DriverCommand.AxialDirection.CLOCKWISE)); commands.add(new replicatorg.drivers.commands.EnableSpindle()); commands.add(new replicatorg.drivers.commands.EnableFloodCoolant()); break; // spindle CCW and coolant A on case M14: commands.add(new replicatorg.drivers.commands.SetSpindleDirection( DriverCommand.AxialDirection.COUNTERCLOCKWISE)); commands.add(new replicatorg.drivers.commands.EnableSpindle()); commands.add(new replicatorg.drivers.commands.EnableFloodCoolant()); break; // enable drives case M17: { //these braces provide a new level of scope to avoid name clash on axes EnumSet<AxisId> axes = getAxes(gcode); if (axes.isEmpty()) { commands.add(new replicatorg.drivers.commands.EnableDrives()); } else { commands.add(new replicatorg.drivers.commands.EnableAxes(axes)); } } break; // disable drives case M18: { //these braces provide a new level of scope to avoid name clash on axes EnumSet<AxisId> axes = getAxes(gcode); if (axes.isEmpty()) { commands.add(new replicatorg.drivers.commands.DisableDrives()); } else { commands.add(new replicatorg.drivers.commands.DisableAxes(axes)); } } break; // open collet case M21: commands.add(new replicatorg.drivers.commands.OpenCollet()); break; // open collet case M22: commands.add(new replicatorg.drivers.commands.CloseCollet()); break; // M40-M46 = change gear ratios case M40: commands.add(new replicatorg.drivers.commands.ChangeGearRatio(0)); break; case M41: // driver.changeGearRatio(1); commands.add(new replicatorg.drivers.commands.ChangeGearRatio(1)); break; case M42: commands.add(new replicatorg.drivers.commands.ChangeGearRatio(2)); break; case M43: commands.add(new replicatorg.drivers.commands.ChangeGearRatio(3)); break; case M44: commands.add(new replicatorg.drivers.commands.ChangeGearRatio(4)); break; case M45: commands.add(new replicatorg.drivers.commands.ChangeGearRatio(5)); break; case M46: commands.add(new replicatorg.drivers.commands.ChangeGearRatio(6)); break; // read spindle speed case M50: driver.getSpindleRPM(); break; // turn extruder on, forward case M70: // print message if (gcode.hasCode('P')) commands.add(new replicatorg.drivers.commands.DisplayMessage(gcode.getCodeValue('P'), gcode.getComment(), false)); else commands.add(new replicatorg.drivers.commands.DisplayMessage(0, gcode.getComment(), false)); break; case M71: // User-clearable pause // First send message, if any... if (gcode.getComment().length() > 0) { commands.add(new replicatorg.drivers.commands.DisplayMessage(0, gcode.getComment(), true)); } else { commands.add(new replicatorg.drivers.commands.DisplayMessage(0, "Paused, press button\nto continue", true)); } // ...then send user pause command. //commands.add(new replicatorg.drivers.commands.UserPause(gcode.getCodeValue('P'),true,0xff)); break; case M72: // Play a tone or song as stored on the machine commands.add(new replicatorg.drivers.commands.PlaySong(gcode.getCodeValue('P'))); break; case M73: // Manually sets the percent complete info on the bot. commands.add( new replicatorg.drivers.commands.SetBuildPercent(gcode.getCodeValue('P'), gcode.getComment())); break; case M101: commands.add( new replicatorg.drivers.commands.SetMotorDirection(DriverCommand.AxialDirection.CLOCKWISE)); commands.add(new replicatorg.drivers.commands.EnableExtruderMotor()); break; // turn extruder on, reverse case M102: commands.add(new replicatorg.drivers.commands.SetMotorDirection( DriverCommand.AxialDirection.COUNTERCLOCKWISE)); commands.add(new replicatorg.drivers.commands.EnableExtruderMotor()); break; // turn extruder off case M103: commands.add(new replicatorg.drivers.commands.DisableMotor()); break; // custom code for temperature control case M104: if (gcode.hasCode('S')) commands.add(new replicatorg.drivers.commands.SetTemperature(gcode.getCodeValue('S'))); break; // custom code for temperature reading // TODO: This command seems like a hack, it would be better for the driver to poll temperature rather than // have the gcode ask for it. case M105: commands.add(new replicatorg.drivers.commands.ReadTemperature()); break; // turn AutomatedBuildPlatform on case M106: if (driver.hasAutomatedBuildPlatform()) commands.add(new replicatorg.drivers.commands.ToggleAutomatedBuildPlatform(true)); else commands.add(new replicatorg.drivers.commands.EnableFan()); break; // turn AutomatedBuildPlatform off case M107: if (driver.hasAutomatedBuildPlatform()) commands.add(new replicatorg.drivers.commands.ToggleAutomatedBuildPlatform(false)); else commands.add(new replicatorg.drivers.commands.DisableFan()); break; // set max extruder speed, RPM case M108: if (gcode.hasCode('S')) commands.add(new replicatorg.drivers.commands.SetMotorSpeedPWM((int) gcode.getCodeValue('S'))); else if (gcode.hasCode('R')) commands.add(new replicatorg.drivers.commands.SetMotorSpeedRPM(gcode.getCodeValue('R'))); break; // set build platform temperature case M109: case M140: // skeinforge chamber code for HBP if (gcode.hasCode('S')) commands.add(new replicatorg.drivers.commands.SetPlatformTemperature(gcode.getCodeValue('S'))); break; // set build chamber temperature case M110: commands.add(new replicatorg.drivers.commands.SetChamberTemperature(gcode.getCodeValue('S'))); break; // valve open case M126: commands.add(new replicatorg.drivers.commands.OpenValve()); break; // valve close case M127: commands.add(new replicatorg.drivers.commands.CloseValve()); break; // where are we? case M128: commands.add(new replicatorg.drivers.commands.GetPosition()); break; // Instruct the machine to store it's current position to EEPROM case M131: { //these braces provide a new level of scope to avoid name clash on axes EnumSet<AxisId> axes = getAxes(gcode); commands.add(new replicatorg.drivers.commands.StoreHomePositions(axes)); } break; // Instruct the machine to restore it's current position from EEPROM case M132: { //these braces provide a new level of scope to avoid name clash on axes EnumSet<AxisId> axes = getAxes(gcode); commands.add(new replicatorg.drivers.commands.RecallHomePositions(axes)); commands.add(new replicatorg.drivers.commands.WaitUntilBufferEmpty()); } break; //Silently ignore these case M141: // skeinforge chamber plugin chamber temperature code case M142: // skeinforge chamber plugin holding pressure code break; // initialize to default state. case M200: commands.add(new replicatorg.drivers.commands.Initialize()); break; // set servo 1 position case M300: if (gcode.hasCode('S')) { commands.add(new replicatorg.drivers.commands.SetServo(0, gcode.getCodeValue('S'))); } break; // set servo 2 position case M301: if (gcode.hasCode('S')) { commands.add(new replicatorg.drivers.commands.SetServo(1, gcode.getCodeValue('S'))); } break; // Start data capture case M310: commands.add(new replicatorg.drivers.commands.WaitUntilBufferEmpty()); commands.add(new replicatorg.drivers.commands.StartDataCapture(gcode.getComment())); break; // Stop data capture case M311: commands.add(new replicatorg.drivers.commands.WaitUntilBufferEmpty()); commands.add(new replicatorg.drivers.commands.StopDataCapture()); break; // Log a note to the data capture store case M312: commands.add(new replicatorg.drivers.commands.WaitUntilBufferEmpty()); commands.add(new replicatorg.drivers.commands.DataCaptureNote(gcode.getComment())); break; // Acceleration on case M320: commands.add(new replicatorg.drivers.commands.SetAccelerationToggle(true)); break; // Acceleration off case M321: commands.add(new replicatorg.drivers.commands.SetAccelerationToggle(false)); break; default: throw new GCodeException("Unknown M code: M" + (int) gcode.getCodeValue('M')); } }
From source file:it.geosolutions.geobatch.actions.ds2ds.Ds2dsAction.java
/** * Imports data from the source DataStore to the output one * transforming the data as configured.//from ww w .j a v a2 s . c o m */ @Override public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { // return object final Queue<EventObject> outputEvents = new LinkedList<EventObject>(); while (events.size() > 0) { final EventObject ev; try { if ((ev = events.remove()) != null) { listenerForwarder.started(); updateTask("Working on incoming event: " + ev.getSource()); Queue<FileSystemEvent> acceptableFiles = acceptableFiles(unpackCompressedFiles(ev)); if (ev instanceof FileSystemEvent && ((FileSystemEvent) ev).getEventType().equals(FileSystemEventType.POLLING_EVENT)) { String fileType = getFileType((FileSystemEvent) ev); EventObject output = null; if ("feature".equalsIgnoreCase(fileType)) { configuration.getOutputFeature().setTypeName( FilenameUtils.getBaseName(((FileSystemEvent) ev).getSource().getName())); output = buildOutputEvent(); updateImportProgress(1, 1, "Completed"); } else { output = importFile((FileSystemEvent) ev); } outputEvents.add(output); } else { if (acceptableFiles.size() == 0) { failAction("No file to process"); } else { List<ActionException> exceptions = new ArrayList<ActionException>(); for (FileSystemEvent fileEvent : acceptableFiles) { try { String fileType = getFileType(fileEvent); EventObject output = null; if ("feature".equalsIgnoreCase(fileType)) { configuration.getOutputFeature().setTypeName(FilenameUtils .getBaseName(((FileSystemEvent) ev).getSource().getName())); output = buildOutputEvent(); updateImportProgress(1, 1, "Completed"); } else { output = importFile(fileEvent); } if (output != null) { // add the event to the return outputEvents.add(output); } else { if (LOGGER.isWarnEnabled()) { LOGGER.warn("No output produced"); } } } catch (ActionException e) { exceptions.add(e); } } if (acceptableFiles.size() == exceptions.size()) { throw new ActionException(this, exceptions.get(0).getMessage()); } else if (exceptions.size() > 0) { if (LOGGER.isWarnEnabled()) { for (ActionException ex : exceptions) { LOGGER.warn("Error in action: " + ex.getMessage()); } } } } } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error("Encountered a NULL event: SKIPPING..."); } continue; } } catch (ActionException ioe) { failAction("Unable to produce the output, " + ioe.getLocalizedMessage(), ioe); } catch (Exception ioe) { failAction("Unable to produce the output: " + ioe.getLocalizedMessage(), ioe); } } return outputEvents; }
From source file:fr.msch.wissl.server.Library.java
private void listFiles(File dir, Queue<File> acc) throws IOException, InterruptedException { if (stop)/*from w ww .java2s . c o m*/ throw new InterruptedException(); if (!dir.isDirectory()) { throw new IOException(dir.getAbsolutePath() + " is not a directory"); } File[] children = dir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.getAbsolutePath().length() > 254) { return false; } String name = pathname.getName().toLowerCase(); for (String format : Config.getMusicFormats()) { if (name.endsWith(format)) { return true; } } if (pathname.isDirectory()) { return true; } return false; } }); for (File child : children) { if (child.isDirectory()) { listFiles(child, acc); } else { acc.add(child); songsTodo++; } } }
From source file:HashMapComponentGraph.java
/** * Remove an edge. If the removal results in one or more isolated nodes, * these will be removed from the graph implicitly. * //from ww w . j a v a 2 s . c o m * For non-dense and relatively fragmented graphs, this operation will be * cheap. Otherwise, for dense and strongly connected graphs, the operation * could include a full traversal of the graph visiting all present edges, * resulting in an O((n-1)^2) operation, where n is the number of nodes in * the graph. * * @param pair * edge to be removed * @return true if the edge was actually removed, false if the edge did not * exists before call. */ @Override public final boolean removeEdge(Pair<T> pair) { // don't act if edge is not present if (!edgeData.containsKey(pair)) { // System.out.println("Edge NOT present"); return false; } else { edgeData.remove(pair); } // get the node out of the node adjacency hash map ( at this point we // know that the nodes must // exist, because the edge exists Node a = new Node(pair.getFirst()); if (allnodes.containsKey(a)) { a = allnodes.get(a); } else { // not possible throw new IllegalStateException( "ComponentGraph.removeEdge(): Node did not have an adjacency entry. ComponentGraph corrupted."); } Node b = new Node(pair.getSecond()); if (allnodes.containsKey(b)) { b = allnodes.get(b); } else { // this is not possible throw new IllegalStateException( "ComponentGraph.removeEdge(): Node did not have an adjacency entry. ComponentGraph corrupted."); } // if b is fixed, interchange a and b ( now, if b is fixed, both a and b // are fixed) if (nodeClassifier.isDelimitor(b.element)) { Node t = a; a = b; b = t; } // remove references to each node, in each nodes // connected node sets edges.get(a).remove(b); edges.get(b).remove(a); // if no edges left in set, remove the set if (edges.get(a).isEmpty()) edges.remove(a); // if no edges left in set, remove it if (edges.get(b).isEmpty()) edges.remove(b); // Cases // i. Both node are delimiters // do nothing // ii. One node is delimiter: // a). non-delimiter is in a component // do nothing (node could now be alone in its component) // if node contains no other edges, delete it from its component // b). non-delimiter is not in a component (not possible) // do nothing/ report fatal error // iii. No node is delimiter: // a). no node is in a component (not possible) // do nothing/ error // b). one node is in a component (not possible) // do nothing // c). both nodes are in a component // 1. the same component // remove edge, traverse breadth-first from each node to determine // if component should be split. // 2. different components (not possible) // do nothing/ error // both nodes are fixed if (nodeClassifier.isDelimitor(b.element)) { // do nothing // return; // one is fixed } else if (nodeClassifier.isDelimitor(a.element)) { if (component.containsKey(b)) { // only possible option // System.out.println("One fixed node"); Component g = component.get(b); // check for another edge on this node if (!edges.containsKey(b)) { // System.out.println("b did not have any edges"); // remove the node from component component.remove(b); // notify handler componenthandler.nodeRemovedFromComponent(g.element, b.element); // b is now free freenodes.add(b); Set<Node> s = componentNodes.get(g); if (!s.remove(b)) { System.out.println("ALARM"); System.exit(0); } // remove group if empty if (s.isEmpty()) { // System.out.println("groups entry removed"); componentNodes.remove(g); // TODO notify handler } else { System.out.println("Group isn't empty, why??"); // System.exit(0); } } else { // b has edges left, and is part of a group. Were done } // remove edge from component (even if b was not removed from // the group) Set<Pair<T>> sp = componentEdges.get(g); sp.remove(pair); // remove group if empty if (sp.isEmpty()) { // System.out.println("grouppair entry removed " + g ); componentEdges.remove(g); } } else { throw new IllegalStateException( "HashMapComponentGraph.removeEdge(): A connected non-delimiter node was not in a component. ComponentGraph corrupted."); } // return; // none is fixed } else { // if b has edges, interchange a and b // ( now, if b has edges, both a and b have edges) if (edges.containsKey(b)) { Node t = a; a = b; b = t; } // both are in the same group (only possible option) Component oldgroup = component.get(a); if (oldgroup != component.get(b)) { System.out.println("Different groups??!"); System.exit(0); } // both have edges if (edges.containsKey(b)) { final int NONE = 0; final int RED = 1; final int BLUE = 2; // clear node colors in entire group Iterator<Node> i = componentNodes.get(oldgroup).iterator(); while (i.hasNext()) { i.next().color = NONE; } // perform breadth-first traversal, // to determine if group has become disjoint boolean disjoint = true; Queue<Node> queue = new LinkedList<Node>(); Set<Pair<T>> blueEdges = new LinkedHashSet<Pair<T>>(); a.color = RED; b.color = BLUE; queue.add(a); queue.add(b); // traverse while (!queue.isEmpty()) { Node node = queue.poll(); // add nodes neighbors to queue Iterator<Node> neighbors = edges.get(node).iterator(); while (neighbors.hasNext()) { Node neighbor = neighbors.next(); // remember visited edges if (node.color == BLUE) blueEdges.add(new Pair<T>(node.element, neighbor.element)); if (nodeClassifier.isDelimitor(neighbor.element)) { // ignore fixed nodes continue; } else if (neighbor.color == NONE) { neighbor.color = node.color; queue.add(neighbor); continue; } else if (neighbor.color != node.color) { // group is connected disjoint = false; break; } else { // already visited continue; } } // while neighbors } // while queue // handle result of traversal if (disjoint) { // System.out.println("Splitting group"); // new group Component newgroup = new Component(componenthandler.newComponent()); Set<Node> blues = new LinkedHashSet<Node>(); // find all blue nodes Iterator<Node> iter = componentNodes.get(oldgroup).iterator(); while (iter.hasNext()) { Node node = iter.next(); if (node.color == BLUE) { blues.add(node); component.put(node, newgroup); } } // impossible if (blues.isEmpty()) { System.out.println("Why was no blue nodes found?"); System.exit(0); } // remove bodies from old components and add the new // component componentNodes.get(oldgroup).removeAll(blues); componentNodes.put(newgroup, blues); // remove blue edges from the red group and create a new // group with pairs (ng) componentEdges.get(oldgroup).removeAll(blueEdges); componentEdges.get(oldgroup).remove(pair); // the edge that // was to be // removed componentEdges.put(newgroup, blueEdges); // return; } else { // System.out.println("Group still connected"); // we keep group as it is, but remove the pair (edge) Set<Pair<T>> sp = componentEdges.get(oldgroup); sp.remove(pair); // remove group if empty if (sp.isEmpty()) { // System.out.println("grouppair entry removed " + // oldgroup ); componentEdges.remove(oldgroup); } // return; } // a has an edge and b do not } else if (edges.containsKey(a)) { // keep group as it is, but wipe out b component.remove(b); componentNodes.get(oldgroup).remove(b); // b is now a free node freenodes.add(b); // notify handler that b is removed from oldgroup componenthandler.nodeRemovedFromComponent(oldgroup.element, b.element); if (componentNodes.get(oldgroup).isEmpty()) { // never happens System.out.println("How can group be empty?"); componentNodes.remove(oldgroup); } // remove from pairs // System.out.println("removing " + pair +" from group pairs " + // oldgroup); Set<Pair<T>> sp = componentEdges.get(oldgroup); sp.remove(pair); // remove group if empty if (sp.isEmpty()) { // System.out.println("grouppair entry removed " + oldgroup // ); componentEdges.remove(oldgroup); } // non have edges } else { // clear out group entirely component.remove(a); component.remove(b); // both a and b are free nodes now freenodes.add(a); freenodes.add(b); // notify handler that a and b is removed componenthandler.nodeRemovedFromComponent(oldgroup.element, a.element); componenthandler.nodeRemovedFromComponent(oldgroup.element, b.element); // assume that the group is only containing a and b? componentNodes.get(oldgroup).remove(b); componentNodes.get(oldgroup).remove(a); if (componentNodes.get(oldgroup).isEmpty()) { componentNodes.remove(oldgroup); } else { // impossible System.out.println("Hmm still stuff in group but no outgoing edges?" + componentNodes.get(oldgroup) + " a and b is " + a + ", " + b); System.exit(0); } // remove from pairs Set<Pair<T>> sp = componentEdges.get(oldgroup); sp.remove(pair); // remove group if empty if (sp.isEmpty()) { // System.out.println("grouppair entry removed " + oldgroup // ); componentEdges.remove(oldgroup); } } // non have edges } // none is fixed // System.out.println("After remove: " + groups.keySet().size() + // " groups with " + group.size() + " bodies" ); // Iterator<Component<V>> groupiter = // componentNodes.keySet().iterator(); // // Set<Pair<T>> allpairs = new HashSet<Pair<T>>(); // Set<Node> allnodes = new HashSet<Node>(); // while(groupiter.hasNext()){ // Component<V> g = groupiter.next(); // //System.out.println( "Group " + g + " : " + groupPairs.get(g).size() // + " pairs " ); // // Iterator<Pair<T>> pairiter = componentEdges.get(g).iterator(); // while (pairiter.hasNext()) { // Pair<T> thispair = pairiter.next(); // //System.out.println( " pair:"+thispair.hashCode()); // if (allpairs.contains(thispair)) { // System.out.println("Duplicates!!!!"); // System.exit(0); // } // allpairs.add(thispair); // // } // // // Iterator<Node> nodeiter = componentNodes.get(g).iterator(); // while (nodeiter.hasNext()) { // Node node = nodeiter.next(); // //System.out.println( " Node:"+node); // if (allnodes.contains(node)) { // System.out.println("Duplicates!!!!"); // System.exit(0); // } // allnodes.add(node); // // } // // } return true; }
From source file:org.cleverbus.component.externalcall.ExternalCallComponentTest.java
private boolean sendAndVerifyBatch(Message[] messages) throws Exception { boolean lockFailureEncountered = false; HashMap<Message, Future<String>> replies = new HashMap<Message, Future<String>>(); // send messages that have no reply, resend messages that have LockFailureException instead of a reply // verify results and re-send failures - test has timeout set because this is potentially endless Queue<Message> unverifiedMessages = new LinkedList<Message>(Arrays.asList(messages)); while (!unverifiedMessages.isEmpty()) { Message message = unverifiedMessages.poll(); boolean replyAvailable = replies.containsKey(message); if (replyAvailable) { Future<String> reply = replies.get(message); try { reply.get(); // this will throw an exception if it occurred during processing } catch (Exception exc) { if (ExceptionUtils.indexOfType(exc, LockFailureException.class) != -1) { // expected cause - this test verifies that this scenario happens and is handled properly lockFailureEncountered = true; replyAvailable = false; // mark reply unavailable to resend the original message } else { // fail by rethrowing Log.error("Unexpected failure for message {} --", message, exc); throw exc; }// w ww.j a v a2s . c o m } } if (!replyAvailable) { unverifiedMessages.add(message); // mark message as still unverified replies.put(message, requestViaExternalCallAsync(message, "mock:test", "concurrentKey", "external call original body")); } } // check the call is now in DB as OK and with the correct LAST msg timestamp assertExtCallStateInDB(extCallId, ExternalCallStateEnum.OK, messages[messages.length - 1]); return lockFailureEncountered; }
From source file:it.geosolutions.geobatch.action.scripting.ScriptingAction.java
/** * Default execute method...//from www. j a v a2 s .c om */ @SuppressWarnings("unchecked") public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException { try { listenerForwarder.started(); // // // data flow configuration and dataStore name must not be null. // // if (configuration == null) { throw new ActionException(this, "Configuration is null."); } final String scriptName = it.geosolutions.tools.commons.file.Path .findLocation(configuration.getScriptFile(), getConfigDir().getAbsolutePath()); if (scriptName == null) throw new ActionException(this, "Unable to locate the script file name: " + configuration.getScriptFile()); final File script = new File(scriptName); /** * Dynamic class-loading ... */ listenerForwarder.setTask("dynamic class loading ..."); final String moduleFolder = new File(script.getParentFile(), "jars").getAbsolutePath(); if (LOGGER.isInfoEnabled()) { LOGGER.info("Runtime class-loading from moduleFolder -> " + moduleFolder); } final File moduleDirectory = new File(moduleFolder); try { addFile(moduleDirectory.getParentFile()); addFile(moduleDirectory); } catch (IOException e) { throw new ActionException(this, e.getLocalizedMessage(), e); } final String classpath = System.getProperty("java.class.path"); final File[] moduleFiles = moduleDirectory.listFiles(); if (moduleFiles != null) { for (File moduleFile : moduleFiles) { final String name = moduleFile.getName(); if (name.endsWith(".jar")) { if (classpath.indexOf(name) == -1) { try { if (LOGGER.isInfoEnabled()) LOGGER.info("Adding: " + name); addFile(moduleFile); } catch (IOException e) { throw new ActionException(this, e.getLocalizedMessage(), e); } } } } } /** * Evaluating script ... */ listenerForwarder.setTask("evaluating script ..."); // Now, pass a different script context final ScriptContext newContext = new SimpleScriptContext(); final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE); // add variables to the new engineScope // engineScope.put("eventList", events); // engineScope.put("runningContext", getRunningContext()); // add properties as free vars in script final Map<String, Object> props = configuration.getProperties(); if (props != null) { final Set<Entry<String, Object>> set = props.entrySet(); final Iterator<Entry<String, Object>> it = set.iterator(); while (it.hasNext()) { final Entry<String, ?> prop = it.next(); if (prop == null) { continue; } if (LOGGER.isInfoEnabled()) LOGGER.info(" Adding script property: " + prop.getKey() + " : " + prop.getValue()); engineScope.put(prop.getKey(), prop.getValue()); } } // read the script FileReader reader = null; try { reader = new FileReader(script); engine.eval(reader, engineScope); } catch (FileNotFoundException e) { throw new ActionException(this, e.getLocalizedMessage(), e); } finally { IOUtils.closeQuietly(reader); } final Invocable inv = (Invocable) engine; listenerForwarder.setTask("Executing script: " + script.getName()); // check for incoming event list if (events == null) { throw new ActionException(this, "Unable to start the script using a null incoming list of events"); } // call the script final Map<String, Object> argsMap = new HashedMap(); argsMap.put(ScriptingAction.CONFIG_KEY, configuration); argsMap.put(ScriptingAction.TEMPDIR_KEY, getTempDir()); argsMap.put(ScriptingAction.CONFIGDIR_KEY, getConfigDir()); argsMap.put(ScriptingAction.EVENTS_KEY, events); argsMap.put(ScriptingAction.LISTENER_KEY, listenerForwarder); final Map<String, Object> mapOut = (Map<String, Object>) inv.invokeFunction("execute", new Object[] { argsMap }); // checking output final Queue<FileSystemEvent> ret = new LinkedList<FileSystemEvent>(); if (mapOut == null) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Caution returned map from script " + configuration.getScriptFile() + " is null.\nSimulating an empty return list."); } return ret; } final Object obj = mapOut.get(ScriptingAction.RETURN_KEY); if (obj == null) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Caution returned object from script " + configuration.getScriptFile() + " is null.\nPassing an empty list to the next action!"); } return ret; } if (obj instanceof List) { final List<Object> list = (List<Object>) obj; for (final Object out : list) { if (out == null) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Caution returned object from script " + configuration.getScriptFile() + " is null.\nContinue with the next one."); } continue; } if (out instanceof FileSystemEvent) { FileSystemEvent ev = (FileSystemEvent) out; ret.add(ev); } else if (out instanceof File) { ret.add(new FileSystemEvent((File) out, FileSystemEventType.FILE_ADDED)); } else { final File file = new File(out.toString()); if (!file.exists() && LOGGER.isWarnEnabled()) { LOGGER.warn("Caution returned object from script " + configuration.getScriptFile() + " do not points to an existent file!"); } ret.add(new FileSystemEvent(file, FileSystemEventType.FILE_ADDED)); } } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error("Caution returned object from script " + configuration.getScriptFile() + " is not a valid List.\nPassing an empty list to the next action!"); } return ret; } listenerForwarder.setTask("Completed"); listenerForwarder.completed(); return ret; } catch (Exception t) { listenerForwarder.setTask("Completed with errors"); listenerForwarder.failed(t); throw new ActionException(this, t.getMessage(), t); } finally { engine = null; factory = null; } }
From source file:org.apache.http2.impl.client.AuthenticationStrategyImpl.java
public Queue<AuthOption> select(final Map<String, Header> challenges, final HttpHost authhost, final HttpResponse response, final HttpContext context) throws MalformedChallengeException { if (challenges == null) { throw new IllegalArgumentException("Map of auth challenges may not be null"); }// ww w. java 2 s.c o m if (authhost == null) { throw new IllegalArgumentException("Host may not be null"); } if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } Queue<AuthOption> options = new LinkedList<AuthOption>(); AuthSchemeRegistry registry = (AuthSchemeRegistry) context.getAttribute(ClientContext.AUTHSCHEME_REGISTRY); if (registry == null) { this.log.debug("Auth scheme registry not set in the context"); return options; } CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); if (credsProvider == null) { this.log.debug("Credentials provider not set in the context"); return options; } @SuppressWarnings("unchecked") List<String> authPrefs = (List<String>) response.getParams().getParameter(this.prefParamName); if (authPrefs == null) { authPrefs = DEFAULT_SCHEME_PRIORITY; } if (this.log.isDebugEnabled()) { this.log.debug("Authentication schemes in the order of preference: " + authPrefs); } for (String id : authPrefs) { Header challenge = challenges.get(id.toLowerCase(Locale.US)); if (challenge != null) { try { AuthScheme authScheme = registry.getAuthScheme(id, response.getParams()); authScheme.processChallenge(challenge); AuthScope authScope = new AuthScope(authhost.getHostName(), authhost.getPort(), authScheme.getRealm(), authScheme.getSchemeName()); Credentials credentials = credsProvider.getCredentials(authScope); if (credentials != null) { options.add(new AuthOption(authScheme, credentials)); } } catch (IllegalStateException e) { if (this.log.isWarnEnabled()) { this.log.warn("Authentication scheme " + id + " not supported"); // Try again } } } else { if (this.log.isDebugEnabled()) { this.log.debug("Challenge for " + id + " authentication scheme not available"); // Try again } } } return options; }
From source file:edu.uci.ics.hyracks.api.rewriter.ActivityClusterGraphRewriter.java
/** * rewrite an activity cluster internally * //from ww w.j av a 2 s . c o m * @param ac * the activity cluster to be rewritten */ private void rewriteIntraActivityCluster(ActivityCluster ac, Map<IActivity, SuperActivity> invertedActivitySuperActivityMap) { Map<ActivityId, IActivity> activities = ac.getActivityMap(); Map<ActivityId, List<IConnectorDescriptor>> activityInputMap = ac.getActivityInputMap(); Map<ActivityId, List<IConnectorDescriptor>> activityOutputMap = ac.getActivityOutputMap(); Map<ConnectorDescriptorId, Pair<Pair<IActivity, Integer>, Pair<IActivity, Integer>>> connectorActivityMap = ac .getConnectorActivityMap(); ActivityClusterGraph acg = ac.getActivityClusterGraph(); Map<ActivityId, IActivity> startActivities = new HashMap<ActivityId, IActivity>(); Map<ActivityId, SuperActivity> superActivities = new HashMap<ActivityId, SuperActivity>(); Map<ActivityId, Queue<IActivity>> toBeExpendedMap = new HashMap<ActivityId, Queue<IActivity>>(); /** * Build the initial super activities */ for (Entry<ActivityId, IActivity> entry : activities.entrySet()) { ActivityId activityId = entry.getKey(); IActivity activity = entry.getValue(); if (activityInputMap.get(activityId) == null) { startActivities.put(activityId, activity); /** * use the start activity's id as the id of the super activity */ createNewSuperActivity(ac, superActivities, toBeExpendedMap, invertedActivitySuperActivityMap, activityId, activity); } } /** * expand one-to-one connected activity cluster by the BFS order. * after the while-loop, the original activities are partitioned * into equivalent classes, one-per-super-activity. */ Map<ActivityId, SuperActivity> clonedSuperActivities = new HashMap<ActivityId, SuperActivity>(); while (toBeExpendedMap.size() > 0) { clonedSuperActivities.clear(); clonedSuperActivities.putAll(superActivities); for (Entry<ActivityId, SuperActivity> entry : clonedSuperActivities.entrySet()) { ActivityId superActivityId = entry.getKey(); SuperActivity superActivity = entry.getValue(); /** * for the case where the super activity has already been swallowed */ if (superActivities.get(superActivityId) == null) { continue; } /** * expend the super activity */ Queue<IActivity> toBeExpended = toBeExpendedMap.get(superActivityId); if (toBeExpended == null) { /** * Nothing to expand */ continue; } IActivity expendingActivity = toBeExpended.poll(); List<IConnectorDescriptor> outputConnectors = activityOutputMap .get(expendingActivity.getActivityId()); if (outputConnectors != null) { for (IConnectorDescriptor outputConn : outputConnectors) { Pair<Pair<IActivity, Integer>, Pair<IActivity, Integer>> endPoints = connectorActivityMap .get(outputConn.getConnectorId()); IActivity newActivity = endPoints.getRight().getLeft(); SuperActivity existingSuperActivity = invertedActivitySuperActivityMap.get(newActivity); if (outputConn.getClass().getName().contains(ONE_TO_ONE_CONNECTOR)) { /** * expend the super activity cluster on an one-to-one out-bound connection */ if (existingSuperActivity == null) { superActivity.addActivity(newActivity); toBeExpended.add(newActivity); invertedActivitySuperActivityMap.put(newActivity, superActivity); } else { /** * the two activities already in the same super activity */ if (existingSuperActivity == superActivity) { continue; } /** * swallow an existing super activity */ swallowExistingSuperActivity(superActivities, toBeExpendedMap, invertedActivitySuperActivityMap, superActivity, superActivityId, existingSuperActivity); } } else { if (existingSuperActivity == null) { /** * create new activity */ createNewSuperActivity(ac, superActivities, toBeExpendedMap, invertedActivitySuperActivityMap, newActivity.getActivityId(), newActivity); } } } } /** * remove the to-be-expended queue if it is empty */ if (toBeExpended.size() == 0) { toBeExpendedMap.remove(superActivityId); } } } Map<ConnectorDescriptorId, IConnectorDescriptor> connMap = ac.getConnectorMap(); Map<ConnectorDescriptorId, RecordDescriptor> connRecordDesc = ac.getConnectorRecordDescriptorMap(); Map<SuperActivity, Integer> superActivityProducerPort = new HashMap<SuperActivity, Integer>(); Map<SuperActivity, Integer> superActivityConsumerPort = new HashMap<SuperActivity, Integer>(); for (Entry<ActivityId, SuperActivity> entry : superActivities.entrySet()) { superActivityProducerPort.put(entry.getValue(), 0); superActivityConsumerPort.put(entry.getValue(), 0); } /** * create a new activity cluster to replace the old activity cluster */ ActivityCluster newActivityCluster = new ActivityCluster(acg, ac.getId()); newActivityCluster.setConnectorPolicyAssignmentPolicy(ac.getConnectorPolicyAssignmentPolicy()); for (Entry<ActivityId, SuperActivity> entry : superActivities.entrySet()) { newActivityCluster.addActivity(entry.getValue()); acg.getActivityMap().put(entry.getKey(), newActivityCluster); } /** * Setup connectors: either inside a super activity or among super activities */ for (Entry<ConnectorDescriptorId, Pair<Pair<IActivity, Integer>, Pair<IActivity, Integer>>> entry : connectorActivityMap .entrySet()) { ConnectorDescriptorId connectorId = entry.getKey(); Pair<Pair<IActivity, Integer>, Pair<IActivity, Integer>> endPoints = entry.getValue(); IActivity producerActivity = endPoints.getLeft().getLeft(); IActivity consumerActivity = endPoints.getRight().getLeft(); int producerPort = endPoints.getLeft().getRight(); int consumerPort = endPoints.getRight().getRight(); RecordDescriptor recordDescriptor = connRecordDesc.get(connectorId); IConnectorDescriptor conn = connMap.get(connectorId); if (conn.getClass().getName().contains(ONE_TO_ONE_CONNECTOR)) { /** * connection edge between inner activities */ SuperActivity residingSuperActivity = invertedActivitySuperActivityMap.get(producerActivity); residingSuperActivity.connect(conn, producerActivity, producerPort, consumerActivity, consumerPort, recordDescriptor); } else { /** * connection edge between super activities */ SuperActivity producerSuperActivity = invertedActivitySuperActivityMap.get(producerActivity); SuperActivity consumerSuperActivity = invertedActivitySuperActivityMap.get(consumerActivity); int producerSAPort = superActivityProducerPort.get(producerSuperActivity); int consumerSAPort = superActivityConsumerPort.get(consumerSuperActivity); newActivityCluster.addConnector(conn); newActivityCluster.connect(conn, producerSuperActivity, producerSAPort, consumerSuperActivity, consumerSAPort, recordDescriptor); /** * bridge the port */ producerSuperActivity.setClusterOutputIndex(producerSAPort, producerActivity.getActivityId(), producerPort); consumerSuperActivity.setClusterInputIndex(consumerSAPort, consumerActivity.getActivityId(), consumerPort); acg.getConnectorMap().put(connectorId, newActivityCluster); /** * increasing the port number for the producer and consumer */ superActivityProducerPort.put(producerSuperActivity, ++producerSAPort); superActivityConsumerPort.put(consumerSuperActivity, ++consumerSAPort); } } /** * Set up the roots of the new activity cluster */ for (Entry<ActivityId, SuperActivity> entry : superActivities.entrySet()) { List<IConnectorDescriptor> connIds = newActivityCluster.getActivityOutputMap().get(entry.getKey()); if (connIds == null || connIds.size() == 0) { newActivityCluster.addRoot(entry.getValue()); } } /** * set up the blocked2Blocker mapping, which will be updated in the rewriteInterActivityCluster call */ newActivityCluster.getBlocked2BlockerMap().putAll(ac.getBlocked2BlockerMap()); /** * replace the old activity cluster with the new activity cluster */ acg.getActivityClusterMap().put(ac.getId(), newActivityCluster); }
From source file:it.geosolutions.geobatch.actions.commons.ExtractAction.java
/** * Removes TemplateModelEvents from the queue and put */// ww w . j a v a2s . c om public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { listenerForwarder.started(); listenerForwarder.setTask("build the output absolute file name"); // return final Queue<EventObject> ret = new LinkedList<EventObject>(); listenerForwarder.setTask("Building/getting the root data structure"); boolean extractMultipleFile; final int size = events.size(); if (size == 0) { throw new ActionException(this, "Empty file list"); } else if (size > 1) { extractMultipleFile = true; } else { extractMultipleFile = false; } final File dest = conf.getDestination(); if (dest != null && !dest.isDirectory()) { if (!dest.mkdirs()) { throw new ActionException(this, "bad destination (not writeable): " + dest); } } while (!events.isEmpty()) { listenerForwarder.setTask("Generating the output"); final EventObject event = events.remove(); if (event == null) { // TODO LOG continue; } if (event instanceof FileSystemEvent) { File source = ((FileSystemEvent) event).getSource(); try { listenerForwarder.setTask("Extracting file: " + source); final File extracted = Extract.extract(source, getTempDir(), false); if (extracted != null) { if (dest != null) { File newDest = new File(dest, extracted.getName()); listenerForwarder.setTask("moving \'" + extracted + "\' to \'" + newDest + "\'"); FileUtils.moveDirectoryToDirectory(extracted, newDest, true); listenerForwarder.terminated(); ret.add(new FileSystemEvent(newDest, FileSystemEventType.DIR_CREATED)); } else { throw new ActionException(this, "Unable to extracto file: " + source); } } else { final String message = "Unable to extract " + source; if (!getConfiguration().isFailIgnored()) { ActionException ex = new ActionException(this.getClass(), message); listenerForwarder.failed(ex); throw ex; } else { LOGGER.warn(message); } } } catch (Exception e) { final String message = "Unable to copy extracted archive"; if (!getConfiguration().isFailIgnored()) { ActionException ex = new ActionException(this.getClass(), message); listenerForwarder.failed(ex); throw ex; } else { LOGGER.warn(e.getLocalizedMessage()); } } } else { final String message = "Incoming instance is not a FileSystemEvent: " + event; if (!getConfiguration().isFailIgnored()) { ActionException ex = new ActionException(this.getClass(), message); listenerForwarder.failed(ex); throw ex; } else { LOGGER.warn(message); } } // TODO setup task progress } // endwile listenerForwarder.completed(); return ret; }
From source file:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePatternNode.java
/** * Returns the descendants of this node in BFS order * //from www.j a va 2s . c om * @return all the descendant of the node in BFS order * * */ public ArrayList<NavigationTreePatternNode> getBFSOrderedDescendants() { ArrayList<NavigationTreePatternNode> nodes = new ArrayList<NavigationTreePatternNode>(); //BFS uses Queue data structure Queue<NavigationTreePatternNode> q = new LinkedList<NavigationTreePatternNode>(); q.add(this); nodes.add(this); while (!q.isEmpty()) { NavigationTreePatternNode n = q.remove(); for (NavigationTreePatternNode child : n.getChildrenList()) { nodes.add(child); q.add(child); } } return nodes; }