List of usage examples for java.util Queue offer
boolean offer(E e);
From source file:com.naver.wordladder.WordLadder.java
public void printTree() { Queue<Node<String>> queue = new LinkedList<Node<String>>(); List<String> path = new ArrayList<String>(); int shortestPathLength = dictionary.size(); queue.offer(new Node<String>(startString)); Node<String> currentNode; while ((currentNode = queue.poll()) != null) { String str = currentNode.getData(); path.add(str);// w w w . java 2 s. c o m Set<String> oneDistanceWords = getOneDistanceWords(str); for (String oneDistanceWord : oneDistanceWords) { if (path.contains(oneDistanceWord)) { continue; } Node<String> child = new Node<String>(oneDistanceWord); child.setParent(currentNode); child.setLevel(currentNode.getLevel() + 1); if (calculateEditDistance(oneDistanceWord, endString) == 1 && child.getLevel() <= shortestPathLength) { shortestPathLength = child.getLevel(); System.out.println(shortestPathLength); Node<String> leaf = new Node<String>(endString); leaf.setParent(child); leaf.printTree(); } queue.offer(child); } } }
From source file:com.pinterest.deployservice.scm.PhabricatorManager.java
@Override public Queue<CommitBean> getCommits(String repo, String startSha, boolean keepHead) throws Exception { String input = String.format(QUERY_COMMITS_HISTORY_PARAMETER, startSha, DEFAULT_SIZE, repo); Map<String, Object> json = queryCLI(input); @SuppressWarnings("unchecked") Map<String, Object> commitsJson = (Map<String, Object>) json.get("response"); @SuppressWarnings("unchecked") ArrayList<Map<String, Object>> commitsArray = (ArrayList<Map<String, Object>>) commitsJson .get("pathChanges"); if (!commitsArray.isEmpty()) { Queue<CommitBean> CommitBeans = new LinkedList<>(); for (Map<String, Object> commitMap : commitsArray) { if (!keepHead) { keepHead = true;// www. jav a 2s. co m continue; } CommitBeans.offer(toCommitBean(commitMap, repo)); } return CommitBeans; } else { throw new DeployInternalException("Invalid SHA or branch name passed to Phabricator getCommitBeans!"); } }
From source file:org.jasig.portal.io.xml.PortalDataKeyFileProcessor.java
@Override public Object apply(Resource input) { final InputStream fis; try {/*from ww w . ja va 2s .com*/ fis = input.getInputStream(); } catch (IOException e) { if (this.options == null || this.options.isFailOnError()) { throw new RuntimeException("Failed to create InputStream for: " + input, e); } logger.warn("Failed to create InputStream, resource will be ignored: {}", input); return null; } final PortalDataKey portalDataKey; final BufferedXMLEventReader xmlEventReader; try { xmlEventReader = new BufferedXMLEventReader(this.xmlInputFactory.createXMLEventReader(fis), -1); final StartElement rootElement = StaxUtils.getRootElement(xmlEventReader); portalDataKey = new PortalDataKey(rootElement); } catch (Exception e) { if (this.options != null && !this.options.isIngoreNonDataFiles()) { throw new RuntimeException("Failed to parse: " + input, e); } logger.warn("Failed to parse resource, it will be ignored: {}", input); return null; } finally { IOUtils.closeQuietly(fis); } xmlEventReader.reset(); final IPortalDataType portalDataType = this.dataKeyTypes.get(portalDataKey); if (portalDataType == null) { logger.warn("No IPortalDataType configured for {}, the resource will be ignored: {}", portalDataKey, input); return null; } //Allow the PortalDataType to do any necessary post-processing of the input, needed as some types require extra work final String resourceUri = ResourceUtils.getResourceUri(input); final Set<PortalDataKey> processedPortalDataKeys = portalDataType.postProcessPortalDataKey(resourceUri, portalDataKey, xmlEventReader); xmlEventReader.reset(); for (final PortalDataKey processedPortalDataKey : processedPortalDataKeys) { //Add the PortalDataKey and File into the map Queue<Resource> queue = this.dataToImport.get(processedPortalDataKey); if (queue == null) { queue = ConcurrentMapUtils.putIfAbsent(this.dataToImport, processedPortalDataKey, new ConcurrentLinkedQueue<Resource>()); } queue.offer(input); count.incrementAndGet(); } return null; }
From source file:se.sics.gvod.common.GraphUtil.java
private void bfs(int v, int d[]) { Queue<Integer> q = new LinkedList<Integer>(); for (int i = 0; i < n; i++) { d[i] = n; // also means that the node has not been visited }/*from w w w . ja v a 2 s . c o m*/ d[v] = 0; q.offer(v); q.offer(0); // depth of v while (!q.isEmpty()) { int u = q.poll(); int du = q.poll(); // depth of u for (int t = 0; t < neighbors[u].length; t++) { if (d[neighbors[u][t]] == n) { // on the first encounter, add to the queue d[neighbors[u][t]] = du + 1; q.offer(neighbors[u][t]); q.offer(du + 1); } } } }
From source file:org.kuali.rice.krad.uif.lifecycle.ViewLifecycleUtils.java
/** * Get nested elements of the type specified one layer deep; this defers from * getElementsOfTypeShallow because it does NOT include itself as a match if it also matches the * type being requested./*from w w w . j a v a 2 s . co m*/ * * @param element instance to get children for * @param elementType type for element to return * @param <T> type of element that will be returned * @return list of child elements with the given type */ public static <T extends LifecycleElement> List<T> getNestedElementsOfTypeShallow(LifecycleElement element, Class<T> elementType) { if (element == null) { return Collections.emptyList(); } List<T> elements = Collections.emptyList(); @SuppressWarnings("unchecked") Queue<LifecycleElement> elementQueue = RecycleUtils.getInstance(LinkedList.class); try { elementQueue.add(element); while (!elementQueue.isEmpty()) { LifecycleElement currentElement = elementQueue.poll(); if (currentElement == null) { continue; } if (elementType.isInstance(currentElement) && currentElement != element) { if (elements.isEmpty()) { elements = new ArrayList<T>(); } elements.add(elementType.cast(currentElement)); } for (LifecycleElement nestedElement : getElementsForLifecycle(currentElement).values()) { if (!(nestedElement instanceof Component)) { elementQueue.offer(nestedElement); } } } } finally { elementQueue.clear(); RecycleUtils.recycle(elementQueue); } return elements; }
From source file:fungus.MycoGraph.java
public Set<Set<MycoNode>> findConnectedComponents() { Set<Set<MycoNode>> components = new HashSet<Set<MycoNode>>(); Set<MycoNode> unseen = new HashSet<MycoNode>(this.getVertices()); Queue<MycoNode> queue = new LinkedList<MycoNode>(); Set<MycoNode> workingComponent = null; MycoNode current;//w w w.j a v a2s .c o m while ((!unseen.isEmpty()) || (!queue.isEmpty())) { if (queue.isEmpty()) { // Queue an arbitary unvisited node MycoNode n = unseen.iterator().next(); queue.offer(n); unseen.remove(n); // Start new component workingComponent = new HashSet<MycoNode>(); components.add(workingComponent); } current = queue.remove(); workingComponent.add(current); for (MycoNode neighbor : current.getHyphaLink().getNeighbors()) { if (unseen.contains(neighbor)) { queue.offer(neighbor); unseen.remove(neighbor); } } } return components; }
From source file:org.apereo.portal.io.xml.PortalDataKeyFileProcessor.java
@Override public Object apply(Resource input) { final InputStream fis; try {/*from w w w . ja v a2 s . co m*/ fis = input.getInputStream(); } catch (IOException e) { if (this.options == null || this.options.isFailOnError()) { throw new RuntimeException("Failed to create InputStream for: " + input, e); } logger.warn("Failed to create InputStream, resource will be ignored: {}", input); return null; } final PortalDataKey portalDataKey; final BufferedXMLEventReader xmlEventReader; try { xmlEventReader = new BufferedXMLEventReader(this.xmlInputFactory.createXMLEventReader(fis), -1); final StartElement rootElement = StaxUtils.getRootElement(xmlEventReader); portalDataKey = new PortalDataKey(rootElement); } catch (Exception e) { if (this.options != null && !this.options.isIngoreNonDataFiles()) { throw new RuntimeException("Failed to parse: " + input, e); } logger.warn("Failed to parse resource, it will be ignored: {}", input); return null; } finally { IOUtils.closeQuietly(fis); } xmlEventReader.reset(); final IPortalDataType portalDataType = this.dataKeyTypes.get(portalDataKey); if (portalDataType == null) { Iterator<PortalDataKey> iter = dataKeyTypes.keySet().iterator(); StringBuffer potentialKeys = new StringBuffer(); potentialKeys.append("---------------- Potential Keys To Match -------------------"); while (iter.hasNext()) { PortalDataKey key = iter.next(); potentialKeys.append(key + "\n"); } logger.warn("{}No IPortalDataType configured for {}, the resource will be ignored: {}", potentialKeys, portalDataKey, input); return null; } //Allow the PortalDataType to do any necessary post-processing of the input, needed as some types require extra work final String resourceUri = ResourceUtils.getResourceUri(input); final Set<PortalDataKey> processedPortalDataKeys = portalDataType.postProcessPortalDataKey(resourceUri, portalDataKey, xmlEventReader); xmlEventReader.reset(); for (final PortalDataKey processedPortalDataKey : processedPortalDataKeys) { //Add the PortalDataKey and File into the map Queue<Resource> queue = this.dataToImport.get(processedPortalDataKey); if (queue == null) { queue = ConcurrentMapUtils.putIfAbsent(this.dataToImport, processedPortalDataKey, new ConcurrentLinkedQueue<Resource>()); } queue.offer(input); count.incrementAndGet(); } return null; }
From source file:com.google.code.rapid.queue.FileQueueTest.java
private void offer(Queue queue, int count, String string) { System.out.println("Test write " + count + " times " + string.getBytes().length + " Bytes data to queue,"); long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { byte[] b = (string + i).getBytes(); queue.offer(b); }//from w ww . ja v a 2 s .com printTps(System.currentTimeMillis() - start, count); }
From source file:org.apache.streams.rss.provider.RssLinkProvider.java
@Override public StreamsResultSet readCurrent() { Queue<StreamsDatum> result = Queues.newConcurrentLinkedQueue(); synchronized (this.entries) { if (this.entries.isEmpty() && this.doneProviding.get()) { this.keepRunning.set(false); }//from w w w . j a v a2 s . c om while (!this.entries.isEmpty()) { ObjectNode node = this.entries.poll(); try { while (!result.offer(new StreamsDatum(node.get("uri").asText()))) { Thread.yield(); } } catch (Exception e) { LOGGER.error("Problem offering up new StreamsDatum: {}", node.asText()); } } } LOGGER.debug("** ReadCurrent return {} streams datums", result.size()); return new StreamsResultSet(result); }
From source file:de.thomaskrille.dropwizard.environment_configuration.EnvironmentConfigurationFactory.java
private void replaceEnvironmentVariablesForArray(final Queue<JsonNode> q, final ArrayNode node) { for (int i = 0; i < node.size(); i++) { JsonNode element = node.get(i);//w w w . ja v a2s . com if (element.isContainerNode()) { q.offer(element); continue; } if (!element.isValueNode()) { continue; } String replacement = getReplacementForValue(element); if (replacement == null) { continue; } node.set(i, TextNode.valueOf(replacement)); } }