List of usage examples for java.util Queue poll
E poll();
From source file:specminers.smartic.MergingBlock.java
public List<State<String>> getNodesByBreadthFirstSearch(Automaton<String> automaton) { LinkedList<State<String>> V = new LinkedList<>(); Queue<State<String>> Q = new LinkedBlockingDeque<>(); V.add(automaton.getInitialState());//from w w w . j a v a 2 s .c om Q.add(automaton.getInitialState()); while (!Q.isEmpty()) { State<String> t = Q.poll(); for (Step<String> delta : automaton.getDelta().get(t)) { State<String> u = delta.getDestination(); if (!V.contains(u)) { V.add(u); Q.add(u); } } } return V; }
From source file:it.geosolutions.geobatch.nrl.ndvi.NDVIIngestAction.java
/** * //from w ww . jav a 2 s. c om */ public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { listenerForwarder.setTask("Check config"); listenerForwarder.started(); NDVIIngestConfiguration configuration = getConfiguration(); if (configuration == null) { throw new IllegalStateException("ActionConfig is null."); } // List<File> ndviFiles = new ArrayList<File>(); Map<File, Calendar[]> inputFiles = new TreeMap<File, Calendar[]>(); while (!events.isEmpty()) { EventObject event = events.poll(); if (event instanceof FileSystemEvent) { FileSystemEvent fse = (FileSystemEvent) event; File source = fse.getSource(); if (!source.exists()) { LOGGER.error("File does not exist: " + source); continue; } Calendar interval[]; try { interval = parseDekDate(source.getName()); } catch (ActionException e) { LOGGER.error("Error parsing source name: " + e.getMessage()); continue; } inputFiles.put(source, interval); } else { throw new ActionException(this, "EventObject not handled " + event); } } ImageMosaicCommand imc = processFiles(inputFiles); LinkedList<EventObject> ret = new LinkedList<EventObject>(); ret.add(new EventObject(imc)); return ret; }
From source file:it.geosolutions.geobatch.opensdi.ndvi.NDVIIngestAction.java
/** * //from w w w. java 2 s. com */ public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { listenerForwarder.progressing(1f, "Check config"); listenerForwarder.started(); NDVIIngestConfiguration configuration = getConfiguration(); if (configuration == null) { throw new IllegalStateException("ActionConfig is null."); } // List<File> ndviFiles = new ArrayList<File>(); Map<File, Calendar[]> inputFiles = new TreeMap<File, Calendar[]>(); while (!events.isEmpty()) { EventObject event = events.poll(); if (event instanceof FileSystemEvent) { FileSystemEvent fse = (FileSystemEvent) event; File source = fse.getSource(); if (!source.exists()) { LOGGER.error("File does not exist: " + source); continue; } Calendar interval[]; try { interval = parseDekDate(source.getName()); } catch (ActionException e) { LOGGER.error("Error parsing source name: " + e.getMessage()); continue; } inputFiles.put(source, interval); } else { throw new ActionException(this, "EventObject not handled " + event); } } listenerForwarder.progressing(10f, "Process file"); ImageMosaicCommand imc = processFiles(inputFiles); LinkedList<EventObject> ret = new LinkedList<EventObject>(); ret.add(new EventObject(imc)); return ret; }
From source file:org.apache.gobblin.example.wikipedia.WikipediaExtractor.java
public WikipediaExtractor(WorkUnitState workUnitState) throws IOException { this.workUnitState = workUnitState; this.rootUrl = readProp(WIKIPEDIA_API_ROOTURL, workUnitState); this.schema = readProp(WIKIPEDIA_AVRO_SCHEMA, workUnitState); this.batchSize = 5; this.requestedTitle = workUnitState.getProp(ConfigurationKeys.DATASET_URN_KEY); this.baseQuery = ImmutableMap.<String, String>builder().put("format", "json").put("action", "query") .put("prop", "revisions").build(); HttpClientConfiguratorLoader httpClientConfiguratorLoader = new HttpClientConfiguratorLoader(workUnitState); this.httpClientConfigurator = httpClientConfiguratorLoader.getConfigurator(); this.httpClientConfigurator.setStatePropertiesPrefix(HTTP_CLIENT_CONFIG_PREFIX).configure(workUnitState); try {/*from w w w. j av a2 s.c om*/ Queue<JsonElement> lastRevision = retrievePageRevisions( ImmutableMap.<String, String>builder().putAll(this.baseQuery).put("rvprop", "ids") .put("titles", this.requestedTitle).put("rvlimit", "1").build()); this.lastRevisionId = lastRevision.isEmpty() ? -1 : parseRevision(lastRevision.poll()); } catch (URISyntaxException use) { throw new IOException(use); } long baseRevision = workUnitState.getWorkunit().getLowWatermark(LongWatermark.class, new Gson()).getValue(); if (baseRevision < 0) { try { baseRevision = createLowWatermarkForBootstrap(workUnitState); } catch (IOException ioe) { baseRevision = this.lastRevisionId; } } this.reader = new WikiResponseReader(baseRevision); workUnitState.setActualHighWatermark(new LongWatermark(this.lastRevisionId)); this.currentBatch = new LinkedList<>(); LOG.info(String.format("Will pull revisions %s to %s for page %s.", this.reader.lastPulledRevision, this.lastRevisionId, this.requestedTitle)); this.maxRevisionsPulled = workUnitState.getPropAsInt(MAX_REVISION_PER_PAGE, DEFAULT_MAX_REVISIONS_PER_PAGE); }
From source file:net.dv8tion.jda.core.audio.AudioConnection.java
private synchronized void setupCombinedExecutor() { if (combinedAudioExecutor == null) { combinedAudioExecutor = Executors.newSingleThreadScheduledExecutor( r -> new Thread(AudioManagerImpl.AUDIO_THREADS, r, threadIdentifier + " Combined Thread")); combinedAudioExecutor.scheduleAtFixedRate(() -> { try { List<User> users = new LinkedList<>(); List<short[]> audioParts = new LinkedList<>(); if (receiveHandler != null && receiveHandler.canReceiveCombined()) { long currentTime = System.currentTimeMillis(); for (Map.Entry<User, Queue<Pair<Long, short[]>>> entry : combinedQueue.entrySet()) { User user = entry.getKey(); Queue<Pair<Long, short[]>> queue = entry.getValue(); if (queue.isEmpty()) continue; Pair<Long, short[]> audioData = queue.poll(); //Make sure the audio packet is younger than 100ms while (audioData != null && currentTime - audioData.getLeft() > queueTimeout) { audioData = queue.poll(); }// w w w. jav a2s .c o m //If none of the audio packets were younger than 100ms, then there is nothing to add. if (audioData == null) { continue; } users.add(user); audioParts.add(audioData.getRight()); } if (!audioParts.isEmpty()) { int audioLength = audioParts.get(0).length; short[] mix = new short[1920]; //960 PCM samples for each channel int sample; for (int i = 0; i < audioLength; i++) { sample = 0; for (short[] audio : audioParts) { sample += audio[i]; } if (sample > Short.MAX_VALUE) mix[i] = Short.MAX_VALUE; else if (sample < Short.MIN_VALUE) mix[i] = Short.MIN_VALUE; else mix[i] = (short) sample; } receiveHandler.handleCombinedAudio(new CombinedAudio(users, mix)); } else { //No audio to mix, provide 20 MS of silence. (960 PCM samples for each channel) receiveHandler.handleCombinedAudio( new CombinedAudio(Collections.emptyList(), new short[1920])); } } } catch (Exception e) { LOG.log(e); } }, 0, 20, TimeUnit.MILLISECONDS); } }
From source file:com.drunkendev.io.recurse.tests.RecursionTest.java
/** * Answer provided by benroth.//from ww w. java 2 s .c om * * Uses a {@link Queue} to hold directory references while traversing until * the queue becomes empty. Uses the {@link java.io.File} API. * * @see <a href="http://stackoverflow.com/a/10814316/140037">Stack-Overflow answer by benroth</a> */ // @Test public void testQueue() { System.out.println("\nTEST: listFiles - Queue"); time(() -> { Queue<File> dirsq = new LinkedList<>(); dirsq.add(startPath.toFile()); int files = 0; int dirs = 0; try { dirs++; // to count the initial dir. while (!dirsq.isEmpty()) { for (File f : dirsq.poll().listFiles()) { if (isPlainDir(f)) { dirsq.add(f); dirs++; } else if (f.isFile()) { files++; } } } System.out.format("Files: %d, dirs: %d. ", files, dirs); } catch (IOException ex) { fail(ex.getMessage()); } }); }
From source file:it.unibo.alchemist.model.implementations.environments.AbstractEnvironment.java
/** * After a node movement, recomputes the neighborhood, also notifying the * running simulation about the modifications. This allows movement actions * to be defined as LOCAL (they should be normally considered GLOBAL). * //from ww w.j a va 2s. c o m * @param node * the node that has been moved */ protected final void updateNeighborhood(final Node<T> node) { /* * The following optimization allows to define as local the context of * reactions which are actually including a move, which should be * normally considered global. This because for each node which is * detached, all the dependencies are updated, ensuring the soundness. */ if (Objects.requireNonNull(rule).isLocallyConsistent()) { final Neighborhood<T> newNeighborhood = rule.computeNeighborhood(Objects.requireNonNull(node), this); final Neighborhood<T> oldNeighborhood = neighCache.put(node.getId(), newNeighborhood); if (oldNeighborhood != null) { final Iterator<Node<T>> iter = oldNeighborhood.iterator(); while (iter.hasNext()) { final Node<T> neighbor = iter.next(); if (!newNeighborhood.contains(neighbor)) { /* * Neighbor lost */ iter.remove(); final Neighborhood<T> neighborsNeighborhood = neighCache.get(neighbor.getId()); neighborsNeighborhood.removeNeighbor(node); ifEngineAvailable(s -> s.neighborRemoved(node, neighbor)); } } } for (final Node<T> n : newNeighborhood) { if (oldNeighborhood == null || !oldNeighborhood.contains(n)) { /* * If it's a new neighbor */ neighCache.get(n.getId()).addNeighbor(node); ifEngineAvailable(s -> s.neighborAdded(node, n)); } } } else { final Queue<Operation> operations = recursiveOperation(node); final TIntSet processed = new TIntHashSet(getNodesNumber()); processed.add(node.getId()); while (!operations.isEmpty()) { final Operation next = operations.poll(); final Node<T> dest = next.destination; final int destId = dest.getId(); if (!processed.contains(destId)) { operations.addAll(recursiveOperation(next.origin, next.destination, next.isAdd)); processed.add(destId); } } } }
From source file:eu.stratosphere.nephele.taskmanager.runtime.RuntimeInputChannelContext.java
@Override public void destroy() { final Queue<Buffer> buffersToRecycle = new ArrayDeque<Buffer>(); synchronized (this.queuedEnvelopes) { this.destroyCalled = true; while (!this.queuedEnvelopes.isEmpty()) { final TransferEnvelope envelope = this.queuedEnvelopes.poll(); if (envelope.getBuffer() != null) { buffersToRecycle.add(envelope.getBuffer()); }// w w w . java2 s . c o m } } while (!buffersToRecycle.isEmpty()) { buffersToRecycle.poll().recycleBuffer(); } }
From source file:org.wso2.carbon.registry.eventing.RegistryEventDispatcher.java
private void addToDigestEntryQueue(Map<String, List<DigestEntry>> digestEntries, String digestType) { Queue<DigestEntry> digestQueue = getDigestQueue(digestType); while (!digestQueue.isEmpty()) { DigestEntry entry = digestQueue.poll(); String endpoint = entry.getEndpoint(); List<DigestEntry> digestEntriesForEndpoint; if (!digestEntries.containsKey(endpoint)) { digestEntriesForEndpoint = new LinkedList<DigestEntry>(); digestEntries.put(endpoint, digestEntriesForEndpoint); } else {//from w w w . j a v a 2s .c om digestEntriesForEndpoint = digestEntries.get(endpoint); } digestEntriesForEndpoint.add(entry); } }
From source file:org.openengsb.labs.paxexam.karaf.container.internal.KarafTestContainer.java
/** * Since we might get quite deep use a simple breath first search algorithm *//*w w w.j a v a 2 s . c o m*/ private File searchKarafBase(File targetFolder) { Queue<File> searchNext = new LinkedList<File>(); searchNext.add(targetFolder); while (!searchNext.isEmpty()) { File head = searchNext.poll(); if (!head.isDirectory()) { continue; } boolean system = false; boolean etc = false; for (File file : head.listFiles()) { if (file.isDirectory() && file.getName().equals("system")) { system = true; } if (file.isDirectory() && file.getName().equals("etc")) { etc = true; } } if (system && etc) { return head; } searchNext.addAll(Arrays.asList(head.listFiles())); } throw new IllegalStateException("No karaf base dir found in extracted distribution."); }