Example usage for java.util Deque peek

List of usage examples for java.util Deque peek

Introduction

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

Prototype

E peek();

Source Link

Document

Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.

Usage

From source file:Main.java

public static void main(String[] args) {

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

    deque.add(1);/*from   w  w w.  jav  a 2  s . co m*/
    deque.add(2);
    deque.add(3);
    deque.add(4);

    int retval = deque.peek();
    System.out.println("Retrieved Element is " + retval);

    System.out.println(deque);
}

From source file:Main.java

public static void main(String[] args) {
    // Create a Deque and use it as stack
    Deque<String> deque = new ArrayDeque<>();
    deque.push("Oracle");
    deque.push("HTML");
    deque.push("CSS");
    deque.push("XML");

    System.out.println("Stack: " + deque);

    // remove all elements from the Deque
    while (deque.peek() != null) {
        System.out.println("Element at  top:  " + deque.peek());
        System.out.println("Popped: " + deque.pop());
        System.out.println("Stack: " + deque);
    }//from ww w  .  j  ava2 s.  c  o  m

    System.out.println("Stack is  empty:  " + deque.isEmpty());
}

From source file:io.apiman.gateway.engine.vertx.polling.fetchers.auth.AbstractOAuth2Base.java

protected static void createOrDescend(JsonObject root, Deque<String> keyPath, String value) {
    // If there are still key-path elements remaining to traverse.
    if (keyPath.size() > 1) {
        // If there's no object already at this key-path create a new JsonObject.
        if (root.getJsonObject(keyPath.peek()) == null) {
            JsonObject newJson = new JsonObject();
            String val = keyPath.pop();
            root.put(val, newJson);
            createOrDescend(newJson, keyPath, value);
        } else { // If there's already an existing object on key-path, grab it and traverse.
            createOrDescend(root.getJsonObject(keyPath.pop()), keyPath, value);
        }/*from www .  java2  s.  co m*/
    } else { // Set the value.
        Boolean boolObj = BooleanUtils.toBooleanObject(value);
        if (boolObj != null) {
            root.put(keyPath.pop(), boolObj);
        } else if (StringUtils.isNumeric(value)) {
            root.put(keyPath.pop(), Long.parseLong(value));
        } else {
            root.put(keyPath.pop(), value);
        }
    }
}

From source file:net.myrrix.common.io.IOUtils.java

/**
 * Attempts to recursively delete a directory. This may not work across symlinks.
 *
 * @param dir directory to delete along with contents
 * @return {@code true} if all files and dirs were deleted successfully
 *///from   w w  w .ja v a 2  s .c  om
public static boolean deleteRecursively(File dir) {
    if (dir == null) {
        return false;
    }
    Deque<File> stack = new ArrayDeque<File>();
    stack.push(dir);
    boolean result = true;
    while (!stack.isEmpty()) {
        File topElement = stack.peek();
        if (topElement.isDirectory()) {
            File[] directoryContents = topElement.listFiles();
            if (directoryContents != null && directoryContents.length > 0) {
                for (File fileOrSubDirectory : directoryContents) {
                    stack.push(fileOrSubDirectory);
                }
            } else {
                result = result && stack.pop().delete();
            }
        } else {
            result = result && stack.pop().delete();
        }
    }
    return result;
}

From source file:PathUtils.java

/**
 * Calculates the relative path between a specified root directory and a target path.
 *
 * @param root   The absolute path of the root directory.
 * @param target The path to the target file or directory.
 * @return The relative path between the specified root directory and the target path.
 * @throws IllegalArgumentException <ul><li>The root file cannot be null.</li><li>The target cannot be
 *                                  null.</li><li>The root file must be a directory.</li><li>The root file must be
 *                                  absolute.</li></ul>
 *//*from w w w. j a va2  s  . c  om*/
public static String relativize(final File root, final File target) throws IllegalArgumentException {
    if (root == null)
        throw new IllegalArgumentException("The root file cannot be null.");
    if (target == null)
        throw new IllegalArgumentException("The target cannot be null.");
    if (!root.isDirectory())
        throw new IllegalArgumentException("The root file must be a directory.");
    if (!root.isAbsolute())
        throw new IllegalArgumentException("The root file must be absolute.");
    if (!target.isAbsolute())
        return target.toString();

    if (root.equals(target))
        return ".";

    // Deconstruct hierarchies
    final Deque<File> rootHierarchy = new ArrayDeque<File>();
    for (File f = root; f != null; f = f.getParentFile())
        rootHierarchy.push(f);
    final Deque<File> targetHierarchy = new ArrayDeque<File>();
    for (File f = target; f != null; f = f.getParentFile())
        targetHierarchy.push(f);

    // Trace common root
    while (rootHierarchy.size() > 0 && targetHierarchy.size() > 0
            && rootHierarchy.peek().equals(targetHierarchy.peek())) {
        rootHierarchy.pop();
        targetHierarchy.pop();
    }
    // Create relative path
    final StringBuilder sb = new StringBuilder(rootHierarchy.size() * 3 + targetHierarchy.size() * 32);
    while (rootHierarchy.size() > 0) {
        sb.append("..");
        rootHierarchy.pop();
        if (rootHierarchy.size() > 0 || targetHierarchy.size() > 0)
            sb.append(File.separator);
    }
    while (targetHierarchy.size() > 0) {
        sb.append(targetHierarchy.pop().getName());
        if (targetHierarchy.size() > 0)
            sb.append(File.separator);
    }
    return sb.toString();
}

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  .j  a  v a2  s  .c  o m*/
 * <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:io.hawt.osgi.jmx.RBACDecorator.java

/**
 * Checks if two {@link ObjectName}s may share RBAC info - if the same configadmin PIDs are examined by Karaf
 * @param realJmxAclPids//from w ww. ja  v  a 2  s . c o  m
 * @param o1
 * @param o2
 * @return
 */
public static boolean mayShareRBACInfo(List<String> realJmxAclPids, ObjectName o1, ObjectName o2) {
    if (o1 == null || o2 == null) {
        return false;
    }

    Deque<String> pids1 = new LinkedList<>();
    List<String> pidCandidates1 = iterateDownPids(nameSegments(o1));
    List<String> pidCandidates2 = iterateDownPids(nameSegments(o2));

    for (String pidCandidate1 : pidCandidates1) {
        pids1.add(getGeneralPid(realJmxAclPids, pidCandidate1));
    }
    for (String pidCandidate2 : pidCandidates2) {
        if (pids1.peek() == null || !pids1.pop().equals(getGeneralPid(realJmxAclPids, pidCandidate2))) {
            return false;
        }
    }

    return pids1.size() == 0;
}

From source file:eu.openanalytics.rsb.rservi.CircularRServiUriSelector.java

private URI getCircular(final Deque<URI> applicationRserviPoolUris) {
    if (applicationRserviPoolUris.size() == 1) {
        return applicationRserviPoolUris.peek();
    }/* w  w  w .  j a v a  2 s .c om*/

    synchronized (applicationRserviPoolUris) {
        final URI uri = applicationRserviPoolUris.poll();
        applicationRserviPoolUris.add(uri);
        return uri;
    }
}

From source file:com.tussle.script.StackedBindings.java

public boolean containsValue(Object o) {
    for (Deque<Object> stack : bindingMap.values())
        if (stack.peek().equals(o))
            return true;
    return false;
}

From source file:brainflow.app.presentation.controls.FileObjectGroupSelector.java

private static String globToRegexPattern(final String glob) throws PatternSyntaxException {
    /* Stack to keep track of the parser mode: */
    /* "--" : Base mode (first on the stack)   */
    /* "[]" : Square brackets mode "[...]"     */
    /* "{}" : Curly braces mode "{...}"        */
    final Deque<String> parserMode = new ArrayDeque<String>();
    parserMode.push("--"); // base mode

    final int globLength = glob.length();
    int index = 0; // index in glob

    /* equivalent REGEX expression to be compiled */
    final StringBuilder t = new StringBuilder();

    while (index < globLength) {
        char c = glob.charAt(index++);

        if (c == '\\') {
            /***********************
             * (1) ESCAPE SEQUENCE */*from   w  ww  .ja v  a2  s  .  c om*/
             ***********************/

            if (index == globLength) {
                /* no characters left, so treat '\' as literal char */
                t.append(Pattern.quote("\\"));
            } else {
                /* read next character */
                c = glob.charAt(index);
                final String s = c + "";

                if (("--".equals(parserMode.peek()) && "\\[]{}?*".contains(s))
                        || ("[]".equals(parserMode.peek()) && "\\[]{}?*!-".contains(s))
                        || ("{}".equals(parserMode.peek()) && "\\[]{}?*,".contains(s))) {
                    /* escape the construct char */
                    index++;
                    t.append(Pattern.quote(s));
                } else {
                    /* treat '\' as literal char */
                    t.append(Pattern.quote("\\"));
                }
            }
        } else if (c == '*') {
            /************************
             * (2) GLOB PATTERN '*' *
             ************************/

            /* create non-capturing group to match zero or more characters */
            t.append(".*");
        } else if (c == '?') {
            /************************
             * (3) GLOB PATTERN '?' *
             ************************/

            /* create non-capturing group to match exactly one character */
            t.append('.');
        } else if (c == '[') {
            /****************************
             * (4) GLOB PATTERN "[...]" *
             ****************************/

            /* opening square bracket '[' */
            /* create non-capturing group to match exactly one character */
            /* inside the sequence */
            t.append('[');
            parserMode.push("[]");

            /* check for negation character '!' immediately after */
            /* the opening bracket '[' */
            if ((index < globLength) && (glob.charAt(index) == '!')) {
                index++;
                t.append('^');
            }
        } else if ((c == ']') && "[]".equals(parserMode.peek())) {
            /* closing square bracket ']' */
            t.append(']');
            parserMode.pop();
        } else if ((c == '-') && "[]".equals(parserMode.peek())) {
            /* character range '-' in "[...]" */
            t.append('-');
        } else if (c == '{') {
            /****************************
             * (5) GLOB PATTERN "{...}" *
             ****************************/

            /* opening curly brace '{' */
            /* create non-capturing group to match one of the */
            /* strings inside the sequence */
            t.append("(?:(?:");
            parserMode.push("{}");
        } else if ((c == '}') && "{}".equals(parserMode.peek())) {
            /* closing curly brace '}' */
            t.append("))");
            parserMode.pop();
        } else if ((c == ',') && "{}".equals(parserMode.peek())) {
            /* comma between strings in "{...}" */
            t.append(")|(?:");
        } else {
            /*************************
             * (6) LITERAL CHARACTER *
             *************************/

            /* convert literal character to a regex string */
            t.append(Pattern.quote(c + ""));
        }
    }
    /* done parsing all chars of the source pattern string */

    /* check for mismatched [...] or {...} */
    if ("[]".equals(parserMode.peek()))
        throw new PatternSyntaxException("Cannot find matching closing square bracket ] in GLOB expression",
                glob, -1);

    if ("{}".equals(parserMode.peek()))
        throw new PatternSyntaxException("Cannot find matching closing curly brace } in GLOB expression", glob,
                -1);

    return t.toString();
}