Example usage for java.util Deque push

List of usage examples for java.util Deque push

Introduction

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

Prototype

void push(E e);

Source Link

Document

Pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.

Usage

From source file:org.apache.asterix.metadata.utils.TypeUtil.java

/**
 * Merges typed index fields with specified recordType, allowing indexed fields to be optional.
 * I.e. the type { "personId":int32, "name": string, "address" : { "street": string } } with typed indexes
 * on age:int32, address.state:string will be merged into type { "personId":int32, "name": string,
 * "age": int32? "address" : { "street": string, "state": string? } } Used by open indexes to enforce
 * the type of an indexed record//from   w  w w. j av a  2s .  c  om
 */
public static Pair<ARecordType, ARecordType> createEnforcedType(ARecordType recordType, ARecordType metaType,
        List<Index> indexes) throws AlgebricksException {
    ARecordType enforcedRecordType = recordType;
    ARecordType enforcedMetaType = metaType;
    for (Index index : indexes) {
        if (!index.isSecondaryIndex() || !index.isEnforcingKeyFileds()) {
            continue;
        }
        if (index.hasMetaFields()) {
            throw new AlgebricksException("Indexing an open field is only supported on the record part");
        }
        for (int i = 0; i < index.getKeyFieldNames().size(); i++) {
            Deque<Pair<ARecordType, String>> nestedTypeStack = new ArrayDeque<>();
            List<String> splits = index.getKeyFieldNames().get(i);
            ARecordType nestedFieldType = enforcedRecordType;
            boolean openRecords = false;
            String bridgeName = nestedFieldType.getTypeName();
            int j;
            // Build the stack for the enforced type
            for (j = 1; j < splits.size(); j++) {
                nestedTypeStack.push(new Pair<>(nestedFieldType, splits.get(j - 1)));
                bridgeName = nestedFieldType.getTypeName();
                nestedFieldType = (ARecordType) enforcedRecordType.getSubFieldType(splits.subList(0, j));
                if (nestedFieldType == null) {
                    openRecords = true;
                    break;
                }
            }
            if (openRecords) {
                // create the smallest record
                enforcedRecordType = new ARecordType(splits.get(splits.size() - 2),
                        new String[] { splits.get(splits.size() - 1) },
                        new IAType[] { AUnionType.createUnknownableType(index.getKeyFieldTypes().get(i)) },
                        true);
                // create the open part of the nested field
                for (int k = splits.size() - 3; k > (j - 2); k--) {
                    enforcedRecordType = new ARecordType(splits.get(k), new String[] { splits.get(k + 1) },
                            new IAType[] { AUnionType.createUnknownableType(enforcedRecordType) }, true);
                }
                // Bridge the gap
                Pair<ARecordType, String> gapPair = nestedTypeStack.pop();
                ARecordType parent = gapPair.first;

                IAType[] parentFieldTypes = ArrayUtils.addAll(parent.getFieldTypes().clone(),
                        new IAType[] { AUnionType.createUnknownableType(enforcedRecordType) });
                enforcedRecordType = new ARecordType(bridgeName,
                        ArrayUtils.addAll(parent.getFieldNames(), enforcedRecordType.getTypeName()),
                        parentFieldTypes, true);
            } else {
                //Schema is closed all the way to the field
                //enforced fields are either null or strongly typed
                Map<String, IAType> recordNameTypesMap = TypeUtil.createRecordNameTypeMap(nestedFieldType);
                // if a an enforced field already exists and the type is correct
                IAType enforcedFieldType = recordNameTypesMap.get(splits.get(splits.size() - 1));
                if (enforcedFieldType != null && enforcedFieldType.getTypeTag() == ATypeTag.UNION
                        && ((AUnionType) enforcedFieldType).isUnknownableType()) {
                    enforcedFieldType = ((AUnionType) enforcedFieldType).getActualType();
                }
                if (enforcedFieldType != null && !ATypeHierarchy.canPromote(enforcedFieldType.getTypeTag(),
                        index.getKeyFieldTypes().get(i).getTypeTag())) {
                    throw new AlgebricksException("Cannot enforce field " + index.getKeyFieldNames().get(i)
                            + " to have type " + index.getKeyFieldTypes().get(i));
                }
                if (enforcedFieldType == null) {
                    recordNameTypesMap.put(splits.get(splits.size() - 1),
                            AUnionType.createUnknownableType(index.getKeyFieldTypes().get(i)));
                }
                enforcedRecordType = new ARecordType(nestedFieldType.getTypeName(),
                        recordNameTypesMap.keySet().toArray(new String[recordNameTypesMap.size()]),
                        recordNameTypesMap.values().toArray(new IAType[recordNameTypesMap.size()]),
                        nestedFieldType.isOpen());
            }

            // Create the enforced type for the nested fields in the schema, from the ground up
            if (!nestedTypeStack.isEmpty()) {
                while (!nestedTypeStack.isEmpty()) {
                    Pair<ARecordType, String> nestedTypePair = nestedTypeStack.pop();
                    ARecordType nestedRecType = nestedTypePair.first;
                    IAType[] nestedRecTypeFieldTypes = nestedRecType.getFieldTypes().clone();
                    nestedRecTypeFieldTypes[nestedRecType
                            .getFieldIndex(nestedTypePair.second)] = enforcedRecordType;
                    enforcedRecordType = new ARecordType(nestedRecType.getTypeName() + "_enforced",
                            nestedRecType.getFieldNames(), nestedRecTypeFieldTypes, nestedRecType.isOpen());
                }
            }
        }
    }
    return new Pair<>(enforcedRecordType, enforcedMetaType);
}

From source file:org.decojer.cavaj.utils.SwitchTypes.java

/**
 * Is used for string-switches. Execute switch case BB to create the case value map: string to
 * BB.//from  ww w  .  j a v  a  2s .  c  om
 *
 * @param caseBb
 *            case BB
 * @param stringReg
 *            string register
 * @param hash
 *            hash for string
 * @param defaultCase
 *            default case
 * @param string2bb
 *            case value map: string to BB
 * @return {@code true} - success
 */
private static boolean executeBbStringHashCond(final BB caseBb, final int stringReg, final int hash,
        final BB defaultCase, final Map<String, BB> string2bb) {
    final Deque<Object> stack = Queues.newArrayDeque();
    String str = null;
    for (int i = 0; i < caseBb.getOps(); ++i) {
        final Op op = caseBb.getOp(i);
        switch (op.getOptype()) {
        case LOAD:
            stack.push(((LOAD) op).getReg());
            break;
        case PUSH:
            stack.push(((PUSH) op).getValue());
            break;
        case INVOKE:
            final M m = ((INVOKE) op).getM();
            if (!"equals".equals(m.getName()) || !"(Ljava/lang/Object;)Z".equals(m.getDescriptor())) {
                return false;
            }
            final Object value = stack.pop();
            if (!(value instanceof String)) {
                return false;
            }
            if (value.hashCode() != hash) {
                return false;
            }
            final Object reg = stack.pop();
            if ((Integer) reg != stringReg) {
                return false;
            }
            stack.push(true);
            str = (String) value;
            break;
        case JCND:
            final Object equalsResult = stack.pop();
            if (!(equalsResult instanceof Boolean)) {
                return false;
            }
            boolean dir = ((Boolean) equalsResult).booleanValue();
            if (((JCND) op).getCmpType() == CmpType.T_EQ) {
                dir = !dir;
            }
            string2bb.put(str, dir ? caseBb.getTrueSucc() : caseBb.getFalseSucc());
            final E out = dir ? caseBb.getFalseOut() : caseBb.getTrueOut();
            if (out == null) {
                assert false;
                return false;
            }
            if (out.getRelevantEnd() == defaultCase) {
                return true;
            }
            return executeBbStringHashCond(out.getEnd(), stringReg, hash, defaultCase, string2bb);
        default:
            return false;
        }
    }
    return false;
}

From source file:com.hazelcast.stabilizer.Utils.java

public static byte[] zip(List<File> roots) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Deque<File> queue = new LinkedList<File>();
    ZipOutputStream zout = new ZipOutputStream(out);

    Set<String> names = new HashSet<String>();

    try {/*from w w w . ja v a  2  s  .  c o m*/
        for (File root : roots) {
            URI base = root.isDirectory() ? root.toURI() : root.getParentFile().toURI();
            queue.push(root);
            while (!queue.isEmpty()) {
                File file = queue.pop();
                if (file.getName().equals(".DS_Store")) {
                    continue;
                }

                //                    log.finest("Zipping: " + file.getAbsolutePath());

                if (file.isDirectory()) {
                    String name = base.relativize(file.toURI()).getPath();
                    name = name.endsWith("/") ? name : name + "/";

                    if (names.add(name)) {
                        zout.putNextEntry(new ZipEntry(name));
                    }

                    for (File kid : file.listFiles()) {
                        queue.push(kid);
                    }
                } else {
                    String name = base.relativize(file.toURI()).getPath();
                    zout.putNextEntry(new ZipEntry(name));
                    copy(file, zout);
                    zout.closeEntry();
                }
            }
        }
    } finally {
        zout.close();
    }

    return out.toByteArray();
}

From source file:com.cinchapi.concourse.lang.Parser.java

/**
 * Convert a valid and well-formed list of {@link Symbol} objects into a
 * Queue in postfix notation./*from   w  w  w . ja v  a  2 s.  c om*/
 * <p>
 * NOTE: This method will group non-conjunctive symbols into
 * {@link Expression} objects.
 * </p>
 * 
 * @param symbols
 * @return the symbols in postfix notation
 */
public static Queue<PostfixNotationSymbol> toPostfixNotation(List<Symbol> symbols) {
    Deque<Symbol> stack = new ArrayDeque<Symbol>();
    Queue<PostfixNotationSymbol> queue = new LinkedList<PostfixNotationSymbol>();
    symbols = groupExpressions(symbols);
    for (Symbol symbol : symbols) {
        if (symbol instanceof ConjunctionSymbol) {
            while (!stack.isEmpty()) {
                Symbol top = stack.peek();
                if (symbol == ConjunctionSymbol.OR
                        && (top == ConjunctionSymbol.OR || top == ConjunctionSymbol.AND)) {
                    queue.add((PostfixNotationSymbol) stack.pop());
                } else {
                    break;
                }
            }
            stack.push(symbol);
        } else if (symbol == ParenthesisSymbol.LEFT) {
            stack.push(symbol);
        } else if (symbol == ParenthesisSymbol.RIGHT) {
            boolean foundLeftParen = false;
            while (!stack.isEmpty()) {
                Symbol top = stack.peek();
                if (top == ParenthesisSymbol.LEFT) {
                    foundLeftParen = true;
                    break;
                } else {
                    queue.add((PostfixNotationSymbol) stack.pop());
                }
            }
            if (!foundLeftParen) {
                throw new SyntaxException(
                        MessageFormat.format("Syntax error in {0}: Mismatched parenthesis", symbols));
            } else {
                stack.pop();
            }
        } else {
            queue.add((PostfixNotationSymbol) symbol);
        }
    }
    while (!stack.isEmpty()) {
        Symbol top = stack.peek();
        if (top instanceof ParenthesisSymbol) {
            throw new SyntaxException(
                    MessageFormat.format("Syntax error in {0}: Mismatched parenthesis", symbols));
        } else {
            queue.add((PostfixNotationSymbol) stack.pop());
        }
    }
    return queue;
}

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);
    padresPila.push("#");
    while (true) {
        result += "\nPila: " + Arrays.toString(pila.toArray());
        if (pila.isEmpty()) {
            result += "\nNo se encontro el nodo destino";
            break;
        }//from   ww  w  . j ava2  s.co  m
        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);
    padresPila.push("#");
    while (true) {
        result.agregarPaso("Pila: " + Arrays.toString(pila.toArray()));
        if (pila.isEmpty()) {
            result.agregarPaso("No se encontro el nodo destino");
            break;
        }/*from  w w  w  .  j  a v  a2s.co  m*/
        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:com.google.uzaygezen.core.MapNode.java

/**
 * For testing purposes only./*w  w  w.  j a va  2  s . co m*/
 * 
 * @return the full preorder list of nodes of this subtree
 */
public List<MapNode<K, V>> preorder() {
    List<MapNode<K, V>> list = Lists.newArrayList();
    Deque<MapNode<K, V>> stack = new ArrayDeque<MapNode<K, V>>();
    stack.push(this);
    MapNode<K, V> node;
    while ((node = stack.poll()) != null) {
        list.add(node);
        for (MapNode<K, V> child : node.children.values()) {
            stack.push(child);
        }
    }
    return list;
}

From source file:com.google.uzaygezen.core.MapNode.java

/**
 * For testing purposes only.//www.  ja  v  a  2s .c  o  m
 * 
 * @return the number of nodes in the subtree rooted in this node and the
 * number of leaves.
 */
int[] subtreeSizeAndLeafCount() {
    Deque<MapNode<K, V>> stack = new ArrayDeque<MapNode<K, V>>();
    stack.push(this);
    MapNode<K, V> node;
    int size = 0;
    int leafCount = 0;
    while ((node = stack.poll()) != null) {
        ++size;
        if (node.children.isEmpty()) {
            ++leafCount;
        }
        for (MapNode<K, V> child : node.children.values()) {
            stack.push(child);
        }
    }
    return new int[] { size, leafCount };
}

From source file:com.proofpoint.event.client.EventFieldMetadata.java

private void writeObject(JsonGenerator jsonGenerator, Object value, Deque<Object> objectStack)
        throws IOException {
    checkForCycles(value, objectStack);// www . ja  v  a2  s .co  m
    objectStack.push(value);
    jsonGenerator.writeStartObject();
    for (EventFieldMetadata field : nestedType.getFields()) {
        field.writeField(jsonGenerator, value, objectStack);
    }
    jsonGenerator.writeEndObject();
    objectStack.pop();
}

From source file:io.jmnarloch.spring.cloud.zuul.trie.AbstractTrie.java

private T put(N root, String key, T value) {

    N node = root;/* w w w.  j a  v  a2  s  .c  o m*/
    final Deque<N> stack = new LinkedList<N>();
    stack.push(node);
    N next;
    int index = 0;

    while (index < key.length()) {
        final char c = getChar(key, index);
        next = node.getNext(c);
        if (next == null) {
            next = createTrieNode();
            node.setNext(c, next);
        }
        node = next;
        stack.push(node);
        index++;
    }
    final boolean replaced = node.hasValue();
    final T old = node.getValue();
    node.setValue(value);
    if (replaced) {
        return old;
    }

    while (!stack.isEmpty()) {
        node = stack.pop();
        node.setSize(node.getSize() + 1);
    }
    return null;
}