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.roda.core.util.ZipUtility.java

public static void zip(File directory, ZipOutputStream zout) throws IOException {
    URI base = directory.toURI();
    Deque<File> queue = new LinkedList<>();
    queue.push(directory);
    try {/*  w ww  .j a  v a  2  s  . c o  m*/
        while (!queue.isEmpty()) {
            File dir = queue.pop();
            for (File kid : dir.listFiles()) {
                String name = base.relativize(kid.toURI()).getPath();
                if (kid.isDirectory()) {
                    queue.push(kid);
                    name = name.endsWith("/") ? name : name + "/";
                    zout.putNextEntry(new ZipEntry(name));
                } else {
                    zout.putNextEntry(new ZipEntry(name));
                    copy(kid, zout);
                    zout.closeEntry();
                }
            }
        }
    } finally {
        zout.close();
    }
}

From source file:io.apiman.plugins.keycloak_oauth_policy.ClaimLookup.java

private static void getProperties(Class<?> klazz, String path, Deque<Field> fieldChain) {
    for (Field f : klazz.getDeclaredFields()) {
        f.setAccessible(true);//from  www. j  a  va2 s .  co  m
        JsonProperty jsonProperty = f.getAnnotation(JsonProperty.class);
        if (jsonProperty != null) {
            fieldChain.push(f);
            // If the inspected type has nested @JsonProperty annotations, we need to inspect it
            if (hasJsonPropertyAnnotation(f)) {
                getProperties(f.getType(), f.getName() + ".", fieldChain); // Add "." when traversing into new object.
            } else { // Otherwise, just assume it's simple as the best we can do is #toString
                List<Field> fieldList = new ArrayList<>(fieldChain);
                Collections.reverse(fieldList);
                STANDARD_CLAIMS_FIELD_MAP.put(path + jsonProperty.value(), fieldList);
                fieldChain.pop(); // Pop, as we have now reached end of this chain.
            }
        }
    }
}

From source file:org.interreg.docexplore.util.ZipUtils.java

static int count(File[] files, Deque<File> queue, int nEntries) throws IOException {
    for (File kid : files)
        if (kid.isDirectory())
            queue.push(kid);
        else/*  w w w  .j  a  v  a 2s  .  c  om*/
            nEntries++;
    return nEntries;
}

From source file:org.apache.nifi.processors.standard.util.FTPUtils.java

/**
 * Handles the logic required to change to the given directory RELATIVE TO THE CURRENT DIRECTORY which can include creating new directories needed.
 *
 * This will first attempt to change to the full path of the given directory outright. If that fails, then it will attempt to change from the top of the tree of the given directory all the way
 * down to the final leaf node of the given directory.
 *
 * @param client - the ftp client with an already active connection
 * @param dirPath - the path to change or create directories to
 * @param createDirs - if true will attempt to create any missing directories
 * @param processor - used solely for targeting logging output.
 * @throws IOException if any access problem occurs
 *//*  w  w  w. j  a v  a  2s .  c  o m*/
public static void changeWorkingDirectory(final FTPClient client, final String dirPath,
        final boolean createDirs, final Processor processor) throws IOException {
    final String currentWorkingDirectory = client.printWorkingDirectory();
    final File dir = new File(dirPath);
    logger.debug(processor + " attempting to change directory from " + currentWorkingDirectory + " to "
            + dir.getPath());
    boolean dirExists = false;
    final String forwardPaths = dir.getPath().replaceAll(Matcher.quoteReplacement("\\"),
            Matcher.quoteReplacement("/"));
    //always use forward paths for long string attempt
    try {
        dirExists = client.changeWorkingDirectory(forwardPaths);
        if (dirExists) {
            logger.debug(processor + " changed working directory to '" + forwardPaths + "' from '"
                    + currentWorkingDirectory + "'");
        } else {
            logger.debug(processor + " could not change directory to '" + forwardPaths + "' from '"
                    + currentWorkingDirectory + "' so trying the hard way.");
        }
    } catch (final IOException ioe) {
        logger.debug(processor + " could not change directory to '" + forwardPaths + "' from '"
                + currentWorkingDirectory + "' so trying the hard way.");
    }
    if (!dirExists) { //couldn't navigate directly...begin hard work
        final Deque<String> stack = new LinkedList<>();
        File fakeFile = new File(dir.getPath());
        do {
            stack.push(fakeFile.getName());
        } while ((fakeFile = fakeFile.getParentFile()) != null);

        String dirName = null;
        while ((dirName = stack.peek()) != null) {
            stack.pop();
            //find out if exists, if not make it if configured to do so or throw exception
            dirName = ("".equals(dirName.trim())) ? "/" : dirName;
            boolean exists = false;
            try {
                exists = client.changeWorkingDirectory(dirName);
            } catch (final IOException ioe) {
                exists = false;
            }
            if (!exists && createDirs) {
                logger.debug(processor + " creating new directory and changing to it " + dirName);
                client.makeDirectory(dirName);
                if (!(client.makeDirectory(dirName) || client.changeWorkingDirectory(dirName))) {
                    throw new IOException(
                            processor + " could not create and change to newly created directory " + dirName);
                } else {
                    logger.debug(processor + " successfully changed working directory to " + dirName);
                }
            } else if (!exists) {
                throw new IOException(processor + " could not change directory to '" + dirName + "' from '"
                        + currentWorkingDirectory + "'");
            }
        }
    }
}

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

/**
 * An the appropriate {@link AST} node to the {@code stack} based on
 * {@code operator}./*  w  w w .j a  v  a  2 s  .  c o  m*/
 * 
 * @param stack
 * @param operator
 */
private static void addASTNode(Deque<AST> stack, Symbol operator) {
    AST right = stack.pop();
    AST left = stack.pop();
    if (operator == ConjunctionSymbol.AND) {
        stack.push(AndTree.create(left, right));
    } else {
        stack.push(OrTree.create(left, right));
    }
}

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 *//w  w  w . j  a 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();
}

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

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

From source file:org.interreg.docexplore.util.ZipUtils.java

static int zip(File[] files, Deque<File> queue, URI base, int cnt, int nEntries, float[] progress,
        float progressOffset, float progressAmount, ArchiveOutputStream zout) throws IOException {
    for (File kid : files) {
        String name = base.relativize(kid.toURI()).getPath();
        if (kid.isDirectory()) {
            queue.push(kid);
            name = name.endsWith("/") ? name : name + "/";
            ArchiveEntry entry = zout.createArchiveEntry(kid, name);
            zout.putArchiveEntry(entry);
            zout.closeArchiveEntry();//from  w  w  w  .j av a 2  s . c o m
        } else {
            ArchiveEntry entry = zout.createArchiveEntry(kid, name);
            zout.putArchiveEntry(entry);
            copy(kid, zout);
            zout.closeArchiveEntry();

            cnt++;
            if (progress != null)
                progress[0] = progressOffset + cnt * progressAmount / nEntries;
        }
    }
    return cnt;
}

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

/**
 * Is used for JDK-Bytecode mode string-switches. Execute switch case BB to create the case
 * value map: index to string./*from w w  w.j a  v  a2 s.  c o m*/
 *
 * @param caseBb
 *            case BB
 * @param indexReg
 *            index register
 * @param str
 *            string
 * @param defaultCase
 *            default case
 * @param index2string
 *            case value map: index to string
 * @return {@code true} - success
 */
private static boolean executeBbStringIndex(@Nonnull final BB caseBb, final int indexReg,
        @Nonnull final String str, @Nonnull final BB defaultCase,
        @Nonnull final Map<Integer, String> index2string) {
    assert defaultCase != null; // prevent warning for now, later check more

    final Deque<Object> stack = Queues.newArrayDeque();
    for (int i = 0; i < caseBb.getOps(); ++i) {
        final Op op = caseBb.getOp(i);
        switch (op.getOptype()) {
        case PUSH:
            stack.push(((PUSH) op).getValue());
            break;
        case STORE:
            if (((STORE) op).getReg() != indexReg) {
                return false;
            }
            final Object index = stack.pop();
            if (!(index instanceof Integer)) {
                return false;
            }
            index2string.put((Integer) index, str);
            return true;
        default:
            return false;
        }
    }
    return false;
}

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

/**
 * Convert a valid and well-formed list of {@link Symbol} objects into a
 * an {@link AST}.//  w  ww . j  a va2 s.c o  m
 * <p>
 * NOTE: This method will group non-conjunctive symbols into
 * {@link Expression} objects.
 * </p>
 * 
 * @param symbols
 * @return the symbols in an AST
 */
public static AST toAbstractSyntaxTree(List<Symbol> symbols) {
    Deque<Symbol> operatorStack = new ArrayDeque<Symbol>();
    Deque<AST> operandStack = new ArrayDeque<AST>();
    symbols = groupExpressions(symbols);
    main: for (Symbol symbol : symbols) {
        if (symbol == ParenthesisSymbol.LEFT) {
            operatorStack.push(symbol);
        } else if (symbol == ParenthesisSymbol.RIGHT) {
            while (!operatorStack.isEmpty()) {
                Symbol popped = operatorStack.pop();
                if (popped == ParenthesisSymbol.LEFT) {
                    continue main;
                } else {
                    addASTNode(operandStack, popped);
                }
            }
            throw new SyntaxException(
                    MessageFormat.format("Syntax error in {0}: Mismatched parenthesis", symbols));
        } else if (symbol instanceof Expression) {
            operandStack.add(ExpressionTree.create((Expression) symbol));
        } else {
            operatorStack.push(symbol);
        }
    }
    while (!operatorStack.isEmpty()) {
        addASTNode(operandStack, operatorStack.pop());
    }
    return operandStack.pop();
}