List of usage examples for java.util Deque pop
E pop();
From source file:msi.gama.kernel.model.GamlModelSpecies.java
@Override public Map<String, ISpecies> getAllSpecies() { if (allSpecies == null) { allSpecies = new TOrderedHashMap(); final Deque<ISpecies> speciesStack = new ArrayDeque<ISpecies>(); speciesStack.push(this); ISpecies currentSpecies;// w ww.j av a2 s .c o m while (!speciesStack.isEmpty()) { currentSpecies = speciesStack.pop(); // scope.getGui().debug("GamlModelSpecies: effectively adding " // + currentSpecies.getName()); allSpecies.put(currentSpecies.getName(), currentSpecies); final List<ISpecies> theMicroSpecies = currentSpecies.getMicroSpecies(); for (final ISpecies microSpec : theMicroSpecies) { if (microSpec.getMacroSpecies().equals(currentSpecies)) { speciesStack.push(microSpec); } } } } return allSpecies; }
From source file:com.cloudera.oryx.rdf.common.tree.DecisionTree.java
@Override public String toString() { StringBuilder result = new StringBuilder(); if (root != null) { Deque<Pair<TreeNode, TreePath>> toPrint = new LinkedList<Pair<TreeNode, TreePath>>(); toPrint.push(new Pair<TreeNode, TreePath>(root, TreePath.EMPTY)); while (!toPrint.isEmpty()) { Pair<TreeNode, TreePath> entry = toPrint.pop(); TreeNode node = entry.getFirst(); TreePath path = entry.getSecond(); int pathLength = path.length(); for (int i = 0; i < pathLength; i++) { if (i == pathLength - 1) { result.append(" +-"); } else { result.append(path.isLeftAt(i) ? " | " : " "); }/*from www . j a v a 2 s. co m*/ } result.append(node).append('\n'); if (node != null && !node.isTerminal()) { DecisionNode decisionNode = (DecisionNode) node; toPrint.push(new Pair<TreeNode, TreePath>(decisionNode.getRight(), path.extendRight())); toPrint.push(new Pair<TreeNode, TreePath>(decisionNode.getLeft(), path.extendLeft())); } } } return result.toString(); }
From source file:com.core.controller.AlgoritmoController.java
public static Solucion busquedaProfundidadConSolucion(Grafo g, String inicio, String fin) { Deque<String> pila = new ArrayDeque<>(); Deque<String> padresPila = new ArrayDeque<>(); List<String> explorados = new ArrayList<>(); List<String> padresExplorados = new ArrayList<>(); String nodoActual, nodoPadre; Solucion result = new Solucion("Algoritmo de Busqueda Primero en Profundidad"); result.agregarPaso("Cantidad de nodos: " + g.getNodos().size()); result.agregarPaso("Cantidad de aristas: " + g.getAristas().size()); pila.push(inicio);// w w w . j a va 2s .c o m padresPila.push("#"); while (true) { result.agregarPaso("Pila: " + Arrays.toString(pila.toArray())); if (pila.isEmpty()) { result.agregarPaso("No se encontro el nodo destino"); break; } nodoActual = pila.pop(); nodoPadre = padresPila.pop(); explorados.add(nodoActual); padresExplorados.add(nodoPadre); if (nodoActual.equals(fin)) { result.agregarPaso("Nodo fin alcanzado"); //Mostrar camino String nodo = nodoActual; String secuenciaResultado = ""; while (nodo != "#") { secuenciaResultado = nodo + " " + secuenciaResultado; nodo = padresExplorados.get(explorados.indexOf(nodo)); } result.agregarPaso("Camino solucion: " + secuenciaResultado); break; } List<String> vecinos = g.nodosVecinos(nodoActual); for (int i = vecinos.size() - 1; i >= 0; i--) { String a = vecinos.get(i); if (!explorados.contains(a)) { if (pila.contains(a)) { pila.remove(a); padresPila.remove(nodoActual); } pila.push(a); padresPila.push(nodoActual); } } } //Verifico la solucion y la guardo en Solucion if (result.getPasos().contains("Nodo fin alcanzado")) { String solucion = result.getPasos().split("Nodo fin alcanzado\n")[1]; System.out.println("Solucion: " + solucion); String[] array = solucion.split(" "); // ArrayUtils.reverse(array); for (String nombreNodo : array) { System.out.println("--------------------------------------"); for (Map.Entry<String, Nodo> n : g.getNodos().entrySet()) { System.out.println("Comparando " + n.getKey() + " con " + nombreNodo); if (n.getKey().equals(nombreNodo)) { System.out.println("Son iguales! Agregando " + nombreNodo + " a la lista"); result.getNodos().add(n.getValue()); } } } System.out.println( "Nodos del resultado final en la lista: " + Arrays.toString(result.getNodos().toArray())); } return result; }
From source file:net.sf.jasperreports.engine.json.expression.member.evaluation.ObjectConstructionExpressionEvaluator.java
private List<JRJsonNode> goAnywhereDown(JRJsonNode jrJsonNode) { List<JRJsonNode> result = new ArrayList<>(); Deque<JRJsonNode> stack = new ArrayDeque<>(); if (log.isDebugEnabled()) { log.debug("initial stack population with: " + jrJsonNode.getDataNode()); }//from w w w .j a va 2 s . c om // populate the stack initially stack.push(jrJsonNode); while (!stack.isEmpty()) { JRJsonNode stackNode = stack.pop(); JsonNode stackDataNode = stackNode.getDataNode(); addChildrenToStack(stackNode, stack); if (log.isDebugEnabled()) { log.debug("processing stack element: " + stackDataNode); } // process the current stack item if (stackDataNode.isObject()) { JRJsonNode childWithKeys = constructNewObjectNodeWithKeys(stackNode); if (childWithKeys != null) { result.add(childWithKeys); } } } return result; }
From source file:com.proofpoint.event.client.EventFieldMetadata.java
private void writeObject(JsonGenerator jsonGenerator, Object value, Deque<Object> objectStack) throws IOException { checkForCycles(value, objectStack);//from w w w .ja va2 s . com objectStack.push(value); jsonGenerator.writeStartObject(); for (EventFieldMetadata field : nestedType.getFields()) { field.writeField(jsonGenerator, value, objectStack); } jsonGenerator.writeEndObject(); objectStack.pop(); }
From source file:net.sf.jasperreports.engine.json.expression.member.evaluation.ArrayIndexExpressionEvaluator.java
private List<JRJsonNode> goAnywhereDown(JRJsonNode jrJsonNode) { List<JRJsonNode> result = new ArrayList<>(); Deque<JRJsonNode> stack = new ArrayDeque<>(); JsonNode initialDataNode = jrJsonNode.getDataNode(); if (log.isDebugEnabled()) { log.debug("initial stack population with: " + initialDataNode); }//from w ww . j av a 2 s . c o m // populate the stack initially stack.push(jrJsonNode); while (!stack.isEmpty()) { JRJsonNode stackNode = stack.pop(); JsonNode stackDataNode = stackNode.getDataNode(); addChildrenToStack(stackNode, stack); // process the current stack item if (stackDataNode.isArray()) { if (log.isDebugEnabled()) { log.debug("processing stack element: " + stackDataNode); } if (expression.getIndex() >= 0 && expression.getIndex() < stackDataNode.size()) { JsonNode nodeAtIndex = stackDataNode.get(expression.getIndex()); JRJsonNode child = stackNode.createChild(nodeAtIndex); if (applyFilter(child)) { result.add(child); } } } } return result; }
From source file:net.minecraftforge.common.ForgeHooks.java
@Nullable public static LootTable loadLootTable(Gson gson, ResourceLocation name, String data, boolean custom, LootTableManager lootTableManager) { Deque<LootTableContext> que = lootContext.get(); if (que == null) { que = Queues.newArrayDeque();/*from w ww . ja v a 2s .c om*/ lootContext.set(que); } LootTable ret = null; try { que.push(new LootTableContext(name, custom)); ret = gson.fromJson(data, LootTable.class); que.pop(); } catch (JsonParseException e) { que.pop(); throw e; } if (!custom) ret = ForgeEventFactory.loadLootTable(name, ret, lootTableManager); if (ret != null) ret.freeze(); return ret; }
From source file:eu.interedition.collatex.tools.CollationServer.java
public void service(Request request, Response response) throws Exception { final Deque<String> path = path(request); if (path.isEmpty() || !"collate".equals(path.pop())) { response.sendError(404);/*from w ww . ja va 2s . c o m*/ return; } final SimpleCollation collation = JsonProcessor.read(request.getInputStream()); if (maxCollationSize > 0) { for (SimpleWitness witness : collation.getWitnesses()) { final int witnessLength = witness.getTokens().stream().filter(t -> t instanceof SimpleToken) .map(t -> (SimpleToken) t).mapToInt(t -> t.getContent().length()).sum(); if (witnessLength > maxCollationSize) { response.sendError(413, "Request Entity Too Large"); return; } } } response.suspend(60, TimeUnit.SECONDS, new EmptyCompletionHandler<>()); collationThreads.submit(() -> { try { final VariantGraph graph = new VariantGraph(); collation.collate(graph); // CORS support response.setHeader("Access-Control-Allow-Origin", Optional.ofNullable(request.getHeader("Origin")).orElse("*")); response.setHeader("Access-Control-Allow-Methods", Optional.ofNullable(request.getHeader("Access-Control-Request-Method")) .orElse("GET, POST, HEAD, OPTIONS")); response.setHeader("Access-Control-Allow-Headers", Optional.ofNullable(request.getHeader("Access-Control-Request-Headers")) .orElse("Content-Type, Accept, X-Requested-With")); response.setHeader("Access-Control-Max-Age", "86400"); response.setHeader("Access-Control-Allow-Credentials", "true"); final String clientAccepts = Optional.ofNullable(request.getHeader(Header.Accept)).orElse(""); if (clientAccepts.contains("text/plain")) { response.setContentType("text/plain"); response.setCharacterEncoding("utf-8"); try (final Writer out = response.getWriter()) { new SimpleVariantGraphSerializer(graph).toDot(out); } response.resume(); } else if (clientAccepts.contains("application/tei+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/tei+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toTEI(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("application/graphml+xml")) { XMLStreamWriter xml = null; try { response.setContentType("application/graphml+xml"); try (OutputStream responseStream = response.getOutputStream()) { xml = XMLOutputFactory.newInstance().createXMLStreamWriter(responseStream); xml.writeStartDocument(); new SimpleVariantGraphSerializer(graph).toGraphML(xml); xml.writeEndDocument(); } finally { if (xml != null) { xml.close(); } } response.resume(); } catch (XMLStreamException e) { e.printStackTrace(); } } else if (clientAccepts.contains("image/svg+xml")) { if (dotPath == null) { response.sendError(204); response.resume(); } else { final StringWriter dot = new StringWriter(); new SimpleVariantGraphSerializer(graph).toDot(dot); final Process dotProc = new ProcessBuilder(dotPath, "-Grankdir=LR", "-Gid=VariantGraph", "-Tsvg").start(); final StringWriter errors = new StringWriter(); CompletableFuture.allOf(CompletableFuture.runAsync(() -> { final char[] buf = new char[8192]; try (final Reader errorStream = new InputStreamReader(dotProc.getErrorStream())) { int len; while ((len = errorStream.read(buf)) >= 0) { errors.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try (final Writer dotProcStream = new OutputStreamWriter(dotProc.getOutputStream(), "UTF-8")) { dotProcStream.write(dot.toString()); } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { response.setContentType("image/svg+xml"); final byte[] buf = new byte[8192]; try (final InputStream in = dotProc.getInputStream(); final OutputStream out = response.getOutputStream()) { int len; while ((len = in.read(buf)) >= 0) { out.write(buf, 0, len); } } catch (IOException e) { throw new CompletionException(e); } }, processThreads), CompletableFuture.runAsync(() -> { try { if (!dotProc.waitFor(60, TimeUnit.SECONDS)) { throw new CompletionException(new RuntimeException( "dot processing took longer than 60 seconds, process was timed out.")); } if (dotProc.exitValue() != 0) { throw new CompletionException(new IllegalStateException(errors.toString())); } } catch (InterruptedException e) { throw new CompletionException(e); } }, processThreads)).exceptionally(t -> { t.printStackTrace(); return null; }).thenRunAsync(response::resume, processThreads); } } else { response.setContentType("application/json"); try (final OutputStream responseStream = response.getOutputStream()) { JsonProcessor.write(graph, responseStream); } response.resume(); } } catch (IOException e) { // FIXME: ignored } }); }
From source file:net.sf.jasperreports.engine.json.expression.member.evaluation.ArrayConstructionExpressionEvaluator.java
private List<JRJsonNode> goAnywhereDown(JRJsonNode jrJsonNode) { List<JRJsonNode> result = new ArrayList<>(); Deque<JRJsonNode> stack = new ArrayDeque<>(); JsonNode initialDataNode = jrJsonNode.getDataNode(); if (log.isDebugEnabled()) { log.debug("initial stack population with: " + initialDataNode); }//from w w w.j a va 2 s.co m // populate the stack initially stack.push(jrJsonNode); while (!stack.isEmpty()) { JRJsonNode stackNode = stack.pop(); JsonNode stackDataNode = stackNode.getDataNode(); addChildrenToStack(stackNode, stack); // process the current stack item if (stackDataNode.isArray()) { if (log.isDebugEnabled()) { log.debug("processing stack element: " + stackDataNode); } ArrayNode newNode = getEvaluationContext().getObjectMapper().createArrayNode(); for (Integer idx : expression.getIndexes()) { if (idx >= 0 && idx < stackDataNode.size()) { JRJsonNode nodeAtIndex = stackNode.createChild(stackDataNode.get(idx)); if (applyFilter(nodeAtIndex)) { newNode.add(nodeAtIndex.getDataNode()); } } } if (newNode.size() > 0) { result.add(stackNode.createChild(newNode)); } } } return result; }
From source file:net.sf.jasperreports.engine.json.expression.member.evaluation.ArraySliceExpressionEvaluator.java
private List<JRJsonNode> goAnywhereDown(JRJsonNode jrJsonNode) { List<JRJsonNode> result = new ArrayList<>(); Deque<JRJsonNode> stack = new ArrayDeque<>(); if (log.isDebugEnabled()) { log.debug("initial stack population with: " + jrJsonNode.getDataNode()); }//from w w w .j a v a 2 s . c om // populate the stack initially stack.push(jrJsonNode); while (!stack.isEmpty()) { JRJsonNode stackNode = stack.pop(); JsonNode stackDataNode = stackNode.getDataNode(); addChildrenToStack(stackNode, stack); // process the current stack item if (stackDataNode.isArray()) { if (log.isDebugEnabled()) { log.debug("processing stack element: " + stackDataNode); } ArrayNode newNode = getEvaluationContext().getObjectMapper().createArrayNode(); Integer start = getSliceStart(stackDataNode.size()); if (start >= stackDataNode.size()) { continue; } Integer end = getSliceEnd(stackDataNode.size()); if (end < 0) { continue; } for (int i = start; i < end; i++) { JRJsonNode nodeAtIndex = stackNode.createChild(stackDataNode.get(i)); if (applyFilter(nodeAtIndex)) { newNode.add(nodeAtIndex.getDataNode()); } } if (newNode.size() > 0) { result.add(stackNode.createChild(newNode)); } } } return result; }