Example usage for java.util Deque remove

List of usage examples for java.util Deque remove

Introduction

In this page you can find the example usage for java.util Deque remove.

Prototype

boolean remove(Object o);

Source Link

Document

Removes the first occurrence of the specified element from this deque.

Usage

From source file:Main.java

public static void main(String[] args) {

    Deque<Integer> deque = new ArrayDeque<Integer>(8);

    deque.add(25);//from  w ww  .j ava 2 s. c om
    deque.add(30);
    deque.add(20);
    deque.add(40);

    System.out.println(deque);

    boolean retval = deque.remove(30);
    if (retval == true) {
        System.out.println("element 30 is removed from the deque");
    } else {
        System.out.println("element 30 is not contained in the deque");
    }

    System.out.println(deque);
}

From source file:com.willwinder.universalgcodesender.utils.Settings.java

private static void updateRecent(Deque<String> stack, int maxSize, String element) {
    stack.remove(element);
    stack.push(element);//from   ww  w.j a  v  a  2s.  c om
    while (stack.size() > maxSize)
        stack.removeLast();
}

From source file:com.core.controller.AlgoritmoController.java

public static String busquedaProfundidad(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;
    String result = "Algoritmo de Busqueda Primero en Profundidad";
    result += "\nCantidad de nodos: " + g.getNodos().size();
    result += "\nCantidad de aristas: " + g.getAristas().size();
    pila.push(inicio);//w  ww . jav  a  2  s  .  com
    padresPila.push("#");
    while (true) {
        result += "\nPila: " + Arrays.toString(pila.toArray());
        if (pila.isEmpty()) {
            result += "\nNo se encontro el nodo destino";
            break;
        }
        nodoActual = pila.pop();
        nodoPadre = padresPila.pop();
        explorados.add(nodoActual);
        padresExplorados.add(nodoPadre);
        if (nodoActual.equals(fin)) {
            result += "\nNodo destino alcanzado"; //Mostrar camino
            String nodo = nodoActual;
            String secuenciaResultado = "";
            while (nodo != "#") {
                secuenciaResultado = nodo + " " + secuenciaResultado;
                nodo = padresExplorados.get(explorados.indexOf(nodo));
            }
            result += "\nCamino 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);
            }
        }
    }
    return result;
}

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);/*from  w ww .j a v  a 2  s .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:nl.knaw.huc.di.tag.tagml.importer.TAGMLListener.java

private TAGMarkup removeFromMarkupStack2(String extendedTag, Deque<TAGMarkup> markupStack) {
    Iterator<TAGMarkup> iterator = markupStack.iterator();
    TAGMarkup markup = null;/*from  w w w. j  a v a  2  s .  c  o  m*/
    while (iterator.hasNext()) {
        markup = iterator.next();
        if (markup.getExtendedTag().equals(extendedTag)) {
            break;
        }
        markup = null;
    }
    if (markup != null) {
        markupStack.remove(markup);
        currentTextVariationState().removeOpenMarkup(markup);
    }
    return markup;
}

From source file:no.sesat.search.http.filters.SiteLocatorFilter.java

private static void doChainFilter(final FilterChain chain, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {

    final HttpSession session = request.getSession();

    // fetch the user's deque
    final Deque<ServletRequest> deque = getUsersDeque(session);

    // lock to execute
    final ReentrantLock lock = (ReentrantLock) session.getAttribute(USER_REQUEST_LOCK);

    // deque has a time limit. start counting.
    long timeLeft = WAIT_TIME;

    try {/*from   ww  w .  j av a 2  s.c  o  m*/
        // attempt to join deque
        if (deque.offerFirst(request)) {
            timeLeft = tryLock(request, deque, lock, timeLeft);
        }

        if (lock.isHeldByCurrentThread()) {

            // waiting is over. and we can execute
            chain.doFilter(request, response);

        } else {
            // we failed to execute. return 409 response.
            if (response instanceof HttpServletResponse) {

                LOG.warn(" -- response 409 "
                        + (0 < timeLeft ? "(More then " + REQUEST_QUEUE_SIZE + " requests already in queue)"
                                : "(Timeout: Waited " + WAIT_TIME + " ms)"));

                response.sendError(HttpServletResponse.SC_CONFLICT);
            }
        }
    } finally {

        // take out of deque first
        deque.remove(request);

        // release the lock, waiting up the next request
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}

From source file:org.apache.oozie.workflow.lite.LiteWorkflowValidator.java

/**
 * Basic recursive validation of the workflow:
 * - it is acyclic, no loops/*from   w w  w  .j av  a 2 s. c om*/
 * - names of the actions follow a specific pattern
 * - all nodes have valid transitions
 * - it only has supported action nodes
 * - there is no node that points to itself
 * - counts fork/join nodes
 *
 * @param app The WorkflowApp
 * @param node Current node we're checking
 * @param path The list of nodes that we've visited so far in this call chain
 * @param checkedNodes The list of nodes that we've already checked. For example, if it's a decision node, then the we
 * don't have to re-walk the entire path because it indicates that it've been done before on a separate path
 * @param forkJoinCount Number of fork and join nodes
 * @throws WorkflowException If there is any of the constraints described above is violated
 */
private void performBasicValidation(LiteWorkflowApp app, NodeDef node, Deque<String> path,
        Set<NodeDef> checkedNodes, ForkJoinCount forkJoinCount) throws WorkflowException {
    String nodeName = node.getName();

    checkActionName(node);
    if (node instanceof ActionNodeDef) {
        checkActionNode(node);
    } else if (node instanceof ForkNodeDef) {
        forkJoinCount.forks++;
    } else if (node instanceof JoinNodeDef) {
        forkJoinCount.joins++;
    }
    checkCycle(path, nodeName);

    path.addLast(nodeName);

    List<String> transitions = node.getTransitions();
    // Get all transitions and walk the workflow recursively
    if (!transitions.isEmpty()) {
        for (final String t : transitions) {
            NodeDef transitionNode = app.getNode(t);
            if (transitionNode == null) {
                throw new WorkflowException(ErrorCode.E0708, node.getName(), t);
            }

            if (!checkedNodes.contains(transitionNode)) {
                performBasicValidation(app, transitionNode, path, checkedNodes, forkJoinCount);
                checkedNodes.add(transitionNode);
            }
        }
    }

    path.remove(nodeName);
}

From source file:org.apache.oozie.workflow.lite.LiteWorkflowValidator.java

/**
 * This method recursively validates two things:
 * - fork/join methods are properly paired
 * - there are no multiple "okTo" paths to a given node
 *
 * Important: this method assumes that the workflow is not acyclic - therefore this must run after performBasicValidation()
 *
 * @param app The WorkflowApp//from   w ww  .  j  av  a2s  .c  om
 * @param node Current node we're checking
 * @param currentFork Current fork node (null if we are not under a fork path)
 * @param topDecisionParent The top (eldest) decision node along the path to this node, or null if there isn't one
 * @param okPath false if node (or an ancestor of node) was gotten to via an "error to" transition or via a join node that has
 * already been visited at least once before
 * @param forkJoins Map that contains a mapping of fork-join node pairs.
 * @param nodeAndDecisionParents Map that contains a mapping of nodes and their eldest decision node
 * @throws WorkflowException If there is any of the constraints described above is violated
 */
private void validateForkJoin(LiteWorkflowApp app, NodeDef node, NodeDef currentFork, String topDecisionParent,
        boolean okPath, Deque<String> path, Map<String, String> forkJoins,
        Map<String, Optional<String>> nodeAndDecisionParents) throws WorkflowException {
    final String nodeName = node.getName();

    path.addLast(nodeName);

    /* If we're walking an "okTo" path and the nodes are not Kill/Join/End, we have to make sure that only a single
     * "okTo" path exists to the current node.
     *
     * The "topDecisionParent" represents the eldest decision in the chain that we've gone through. For example, let's assume
     * that D1, D2, D3 are decision nodes and A is an action node.
     *
     * D1-->D2-->D3---> ... (rest of the WF)
     *  |   |    |
     *  |   |    |
     *  |   |    +----> +---+
     *  |   +---------> | A |
     *  +-------------> +---+
     *
     * In this case, there are three "okTo" paths to "A" but it's still a valid workflow because the eldest decision node
     * is D1 and during every run, there is only one possible execution path that leads to A (D1->A, D1->D2->A or
     * (D1->D2->D3->A). In the code, if we encounter a decision node and we already have one, we don't update it. If it's null
     * then we set it to the current decision node we're under.
     *
     * If the "current" and "top" parents are null, it means that we reached the node from two separate "okTo" paths, which is
     * not acceptable.
     *
     * Also, if we have two distinct top decision parents it means that the node is reachable from two decision paths which
     * are not "chained" (like in the example).
     *
     * It's worth noting that the last two examples can only occur in case of fork-join when we start to execute at least
     * two separate paths in parallel. Without fork-join, multiple parents or two null parents would mean that there is a loop
     * in the workflow but that should not happen since it has been validated.
     */
    if (okPath && !(node instanceof KillNodeDef) && !(node instanceof JoinNodeDef)
            && !(node instanceof EndNodeDef)) {
        // using Optional here so we can distinguish between "non-visited" and "visited - no parent" state.
        Optional<String> decisionParentOpt = nodeAndDecisionParents.get(nodeName);
        if (decisionParentOpt == null) {
            nodeAndDecisionParents.put(node.getName(), Optional.fromNullable(topDecisionParent));
        } else {
            String decisionParent = decisionParentOpt.isPresent() ? decisionParentOpt.get() : null;

            if ((decisionParent == null && topDecisionParent == null)
                    || !Objects.equal(decisionParent, topDecisionParent)) {
                throw new WorkflowException(ErrorCode.E0743, nodeName);
            }
        }
    }

    /* Fork-Join validation logic:
     *
     * At each Fork node, we recurse to every possible paths, changing the "currentFork" variable to the Fork node. We stop
     * walking as soon as we encounter a Join node. At the Join node, we update the forkJoin mapping, which maintains
     * the relationship between every fork-join pair (actually it's join->fork mapping). We check whether the join->fork
     * mapping already contains another Fork node, which means that the Join is reachable from at least two distinct
     * Fork nodes, so we terminate the validation.
     *
     * From the Join node, we don't recurse further. Therefore, all recursive calls return back to the point where we called
     * validateForkJoin() from the Fork node in question.
     *
     * At this point, we have to check how many different Join nodes we've found at each different paths. We collect them to
     * a set, then we make sure that we have only a single Join node for all Fork paths. Otherwise the workflow is broken.
     *
     * If we have only a single Join, then we get the transition node from the Join and go on with the recursive validation -
     * this time we use the original "currentFork" variable that we have on the stack. With this approach, nested
     * Fork-Joins are handled correctly.
     */
    if (node instanceof ForkNodeDef) {
        final List<String> transitions = node.getTransitions();

        checkForkTransitions(app, transitions, node);

        for (String t : transitions) {
            NodeDef transition = app.getNode(t);
            validateForkJoin(app, transition, node, topDecisionParent, okPath, path, forkJoins,
                    nodeAndDecisionParents);
        }

        // get the Join node for this ForkNode & validate it (we must have only one)
        Set<String> joins = new HashSet<String>();
        collectJoins(app, forkJoins, nodeName, joins);
        checkJoins(joins, nodeName);

        List<String> joinTransitions = app.getNode(joins.iterator().next()).getTransitions();
        NodeDef next = app.getNode(joinTransitions.get(0));

        validateForkJoin(app, next, currentFork, topDecisionParent, okPath, path, forkJoins,
                nodeAndDecisionParents);
    } else if (node instanceof JoinNodeDef) {
        if (currentFork == null) {
            throw new WorkflowException(ErrorCode.E0742, node.getName());
        }

        // join --> fork mapping
        String forkNode = forkJoins.get(nodeName);
        if (forkNode == null) {
            forkJoins.put(nodeName, currentFork.getName());
        } else if (!forkNode.equals(currentFork.getName())) {
            throw new WorkflowException(ErrorCode.E0758, node.getName(), forkNode + "," + currentFork);
        }
    } else if (node instanceof DecisionNodeDef) {
        List<String> transitions = node.getTransitions();

        // see explanation above - if we already have a topDecisionParent, we don't update it
        String parentDecisionNode = topDecisionParent;
        if (parentDecisionNode == null) {
            parentDecisionNode = nodeName;
        }

        for (String t : transitions) {
            NodeDef transition = app.getNode(t);
            validateForkJoin(app, transition, currentFork, parentDecisionNode, okPath, path, forkJoins,
                    nodeAndDecisionParents);
        }
    } else if (node instanceof KillNodeDef) {
        // no op
    } else if (node instanceof EndNodeDef) {
        // We can't end the WF if we're on a Fork path. From the "path" deque, we remove the last node (which
        // is the current "End") and look at last node again so we know where we came from
        if (currentFork != null) {
            path.removeLast();
            String previous = path.peekLast();
            throw new WorkflowException(ErrorCode.E0737, previous, node.getName());
        }
    } else if (node instanceof ActionNodeDef) {
        String transition = node.getTransitions().get(0); // "ok to" transition
        NodeDef okNode = app.getNode(transition);
        validateForkJoin(app, okNode, currentFork, topDecisionParent, true, path, forkJoins,
                nodeAndDecisionParents);

        transition = node.getTransitions().get(1); // "error to" transition
        NodeDef errorNode = app.getNode(transition);
        validateForkJoin(app, errorNode, currentFork, topDecisionParent, false, path, forkJoins,
                nodeAndDecisionParents);
    } else if (node instanceof StartNodeDef) {
        String transition = node.getTransitions().get(0); // start always has only 1 transition
        NodeDef tranNode = app.getNode(transition);
        validateForkJoin(app, tranNode, currentFork, topDecisionParent, okPath, path, forkJoins,
                nodeAndDecisionParents);
    } else {
        throw new WorkflowException(ErrorCode.E0740, node.getClass());
    }

    path.remove(nodeName);
}