Example usage for java.util Stack push

List of usage examples for java.util Stack push

Introduction

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

Prototype

public E push(E item) 

Source Link

Document

Pushes an item onto the top of this stack.

Usage

From source file:com.dragoniade.deviantart.ui.PreferencesDialog.java

private boolean testPath(String location, String username) {
    File dest = LocationHelper.getFile(location, username, sample, sample.getImageFilename());

    Stack<File> stack = new Stack<File>();
    Stack<File> toDelete = new Stack<File>();

    stack.push(dest);
    while ((dest = dest.getParentFile()) != null) {
        stack.push(dest);//from   w  ww. j ava  2s.c  o  m
    }

    try {
        while (!stack.isEmpty()) {
            File file = stack.pop();
            if (file.exists()) {
                continue;
            } else {
                if (stack.isEmpty()) {
                    if (!file.createNewFile()) {
                        return false;
                    }
                } else {
                    if (!file.mkdir()) {
                        return false;
                    }
                }

                toDelete.add(file);
            }
        }
    } catch (IOException ex) {
        return false;
    } finally {
        while (!toDelete.isEmpty()) {
            toDelete.pop().delete();
        }
    }
    return true;
}

From source file:alluxio.job.move.MoveDefinition.java

/**
 * Returns {@link URIStatus} for all paths under the specified path, including the path itself.
 *
 * The statuses will be listed in the order they are visited by depth-first search.
 *
 * @param path the target path//from w ww  .  j  a va2 s . c  om
 * @return a list of the {@link URIStatus} for all paths under the given path
 * @throws Exception if an exception occurs
 */
private List<URIStatus> getPathStatuses(AlluxioURI path) throws Exception {
    // Depth-first search to to find all files under path.
    Stack<AlluxioURI> pathsToConsider = new Stack<>();
    pathsToConsider.add(path);
    List<URIStatus> allStatuses = Lists.newArrayList();
    while (!pathsToConsider.isEmpty()) {
        AlluxioURI nextPath = pathsToConsider.pop();
        URIStatus status = mFileSystem.getStatus(nextPath);
        allStatuses.add(status);
        if (status.isFolder()) {
            List<URIStatus> childStatuses = mFileSystem.listStatus(nextPath);
            for (URIStatus childStatus : childStatuses) {
                if (childStatus.isFolder()) {
                    pathsToConsider.push(new AlluxioURI(childStatus.getPath()));
                } else {
                    allStatuses.add(childStatus);
                }
            }
        }
    }
    return ImmutableList.copyOf(allStatuses);
}

From source file:org.apache.fop.layoutmgr.FlowLayoutManager.java

/**
 * Get a sequence of KnuthElements representing the content
 * of the node assigned to the LM.// w ww .j  a  v  a  2 s.  c om
 * @param context   the LayoutContext used to store layout information
 * @param alignment the desired text alignment
 * @param restartPosition   {@link Position} to restart from
 * @param restartLM {@link LayoutManager} to restart from
 * @return the list of KnuthElements
 * @see LayoutManager#getNextKnuthElements(LayoutContext,int)
 */
List getNextKnuthElements(LayoutContext context, int alignment, Position restartPosition,
        LayoutManager restartLM) {

    List<ListElement> elements = new LinkedList<ListElement>();

    boolean isRestart = (restartPosition != null);
    // always reset in case of restart (exception: see below)
    boolean doReset = isRestart;
    LayoutManager currentChildLM;
    Stack<LayoutManager> lmStack = new Stack<LayoutManager>();
    if (isRestart) {
        currentChildLM = restartPosition.getLM();
        if (currentChildLM == null) {
            throw new IllegalStateException("Cannot find layout manager to restart from");
        }
        if (restartLM != null && restartLM.getParent() == this) {
            currentChildLM = restartLM;
        } else {
            while (currentChildLM.getParent() != this) {
                lmStack.push(currentChildLM);
                currentChildLM = currentChildLM.getParent();
            }
            doReset = false;
        }
        setCurrentChildLM(currentChildLM);
    } else {
        currentChildLM = getChildLM();
    }

    while (currentChildLM != null) {
        if (!isRestart || doReset) {
            if (doReset) {
                currentChildLM.reset(); // TODO won't work with forced breaks
            }
            if (addChildElements(elements, currentChildLM, context, alignment, null, null, null) != null) {
                return elements;
            }
        } else {
            if (addChildElements(elements, currentChildLM, context, alignment, lmStack, restartPosition,
                    restartLM) != null) {
                return elements;
            }
            // restarted; force reset as of next child
            doReset = true;
        }
        currentChildLM = getChildLM();
    }

    SpaceResolver.resolveElementList(elements);
    setFinished(true);

    assert !elements.isEmpty();
    return elements;
}

From source file:org.apache.tajo.engine.planner.rewrite.FilterPushDownRule.java

@Override
public LogicalNode visitWindowAgg(FilterPushDownContext context, LogicalPlan plan, LogicalPlan.QueryBlock block,
        WindowAggNode winAggNode, Stack<LogicalNode> stack) throws PlanningException {
    stack.push(winAggNode);
    super.visitWindowAgg(context, plan, block, winAggNode, stack);
    stack.pop();/*from  w w  w  . j  a v a2s. co m*/
    return winAggNode;
}

From source file:hugonicolau.openbrailleinput.wordcorrection.mafsa.MAFSA.java

public Set<SuggestionResult> searchMSD(String transWord, int maxCost, float insertionCost,
        float substitutionCost, float omissionCost, Distance distance) {
    // build first row
    List<Float> row = range(transWord.length() + 1);

    // results/*w  w  w .  j  a  v a  2s. c om*/
    Set<SuggestionResult> results = new HashSet<SuggestionResult>();

    // iteratively (to prevent stack overflow) search each branch of the graph
    // a stack of paths to traverse. This prevents the StackOverflowException.
    Stack<StackLevenshteinEntry> stack = new Stack<StackLevenshteinEntry>();
    for (Iterator<Long> iter = childIterator(nodes[0]); iter.hasNext();) {
        long child = iter.next();
        char c = getChar(child);

        StackLevenshteinEntry entry = new StackLevenshteinEntry(child, transWord.toUpperCase().toCharArray(),
                String.valueOf(c), row);
        stack.push(entry);
    }

    // thread to control time to search for suggestions
    mAreTimeAvailable = true;
    mTimerTask = new TimerTask() {

        @Override
        public void run() {
            //Log.v(BrailleSpellCheckerService.TAG, "Search Interrupted!");
            mAreTimeAvailable = false;
        }
    };
    mTimer = new Timer();
    mTimer.schedule(mTimerTask, 500); //500 ms to find all suggestions

    while (!stack.empty() && mAreTimeAvailable) {
        StackLevenshteinEntry entry = stack.pop();
        List<Float> previousRow = entry.previousRow;

        int columns = entry.chars.length + 1;
        List<Float> currentRow = new LinkedList<Float>();
        currentRow.add(previousRow.get(0) + omissionCost);

        // build one row for the letter, with a column for each letter in the target word, 
        // plus one for the empty string at column 0
        for (int column = 1; column < columns; column++) {
            // cost * braille_distance
            float insertCost = currentRow.get(column - 1) + insertionCost;// * 
            //getInsertionDistance(entry.chars, column-1, getChar(entry.node));
            float omitCost = previousRow.get(column) + omissionCost;
            float substituteCost = previousRow.get(column - 1);

            if (entry.chars[column - 1] != getChar(entry.node))
                substituteCost += substitutionCost
                        * distance.getDistance(entry.chars[column - 1], getChar(entry.node));

            currentRow.add(Math.min(insertCost, Math.min(omitCost, substituteCost)));
        }

        // if last entry in the row indicates the optimal cost is less than the maximum cost,
        // and there is a word in this node, then add it.
        int last = currentRow.size() - 1;
        if (currentRow.get(last) <= maxCost && canTerminate(entry.node)) {
            results.add(new SuggestionResult(entry.subword, currentRow.get(last)));
        }

        // if any entries in the row are less than the maximum cost, then iteratively search each branch
        if (min(currentRow) <= maxCost) {
            for (Iterator<Long> iter = childIterator(entry.node); iter.hasNext();) {
                // get child
                long child = iter.next();

                // build subword
                StackLevenshteinEntry nextEntry = new StackLevenshteinEntry(child, entry.chars,
                        entry.subword + getChar(child), currentRow);

                // search that branch
                stack.push(nextEntry);
            }
        }
    }

    mTimer.cancel();

    // return list of results
    return results;
}

From source file:io.warp10.worf.WorfTemplate.java

public Stack<Pair<String, String[]>> getFieldsStack() throws WorfException {
    Stack<Pair<String, String[]>> stack = new Stack<>();

    for (Map.Entry<Object, Object> configEntry : config.entrySet()) {
        String key = (String) configEntry.getKey();
        String value = (String) configEntry.getValue();

        ////from  ww  w  .  j  av  a 2 s . c o  m
        // extract template value
        //
        Matcher templateMatcher = templatePattern.matcher(value);

        if (templateMatcher.matches()) {
            String template = templateMatcher.group(1);
            String[] templateValues = template.split(":");

            if (templateValues.length != 3) {
                throw new WorfException("Read template error key=" + key + " t=" + value);
            }
            stack.push(new Pair<>(value, templateValues));
        }
    }

    return stack;
}

From source file:org.alfresco.web.app.AlfrescoNavigationHandler.java

/**
 * Adds the current view to the stack (if required).
 * If the current view is already the top of the stack it is not added again
 * to stop the stack from growing and growing.
 * //from w  w w.  j  a v a  2  s .c  om
 * @param context FacesContext
 */
@SuppressWarnings("unchecked")
protected void addCurrentViewToStack(FacesContext context) {
    // if the current viewId is either the dialog or wizard container page
    // we need to save the state of the current dialog or wizard to the stack

    // If the current view is a normal page and it is not the same as the 
    // view currently at the top of the stack (you can't launch a dialog from
    // the same page 2 times in a row so it must mean the user navigated away
    // from the first dialog) just add the viewId to the stack

    // work out what to add to the stack
    String viewId = context.getViewRoot().getViewId();
    String dialogContainer = getDialogContainer(context);
    String wizardContainer = getWizardContainer(context);
    Object objectForStack = null;
    if (viewId.equals(dialogContainer)) {
        DialogManager dlgMgr = Application.getDialogManager();
        objectForStack = dlgMgr.getState();
    } else if (viewId.equals(wizardContainer)) {
        WizardManager wizMgr = Application.getWizardManager();
        objectForStack = wizMgr.getState();
    } else {
        objectForStack = viewId;
    }

    // if the stack is currently empty add the item
    Stack stack = getViewStack(context);
    if (stack.empty()) {
        stack.push(objectForStack);

        if (logger.isDebugEnabled())
            logger.debug("Pushed item to view stack: " + objectForStack);
    } else {
        // if the item to go on to the stack and the top of
        // stack are both Strings and equals to each other
        // don't add anything to the stack to stop it 
        // growing unecessarily
        Object topOfStack = stack.peek();
        if (objectForStack instanceof String && topOfStack instanceof String
                && topOfStack.equals(objectForStack)) {
            if (logger.isDebugEnabled())
                logger.debug("current view is already top of the view stack!");
        } else {
            stack.push(objectForStack);

            if (logger.isDebugEnabled())
                logger.debug("Pushed item to view stack: " + objectForStack);
        }
    }
}

From source file:org.hdiv.urlProcessor.AbstractUrlProcessor.java

/**
 * Removes from <code>url<code> references to relative paths.
 * /*w ww .  j a  v a  2 s.co  m*/
 * @param url
 *            url
 * @param originalRequestUri
 *            originalRequestUri
 * @return returns <code>url</code> without relative paths.
 */
protected String removeRelativePaths(String url, String originalRequestUri) {

    String urlWithoutRelativePath = url;

    if (url.startsWith("..")) {
        Stack stack = new Stack();
        String localUri = originalRequestUri.substring(originalRequestUri.indexOf("/"),
                originalRequestUri.lastIndexOf("/"));
        StringTokenizer localUriParts = new StringTokenizer(localUri.replace('\\', '/'), "/");
        while (localUriParts.hasMoreTokens()) {
            String part = localUriParts.nextToken();
            stack.push(part);
        }

        StringTokenizer pathParts = new StringTokenizer(url.replace('\\', '/'), "/");
        while (pathParts.hasMoreTokens()) {
            String part = pathParts.nextToken();

            if (!part.equals(".")) {
                if (part.equals("..")) {
                    stack.pop();
                } else {
                    stack.push(part);
                }
            }
        }

        StringBuffer flatPathBuffer = new StringBuffer();
        for (int i = 0; i < stack.size(); i++) {
            flatPathBuffer.append("/").append(stack.elementAt(i));
        }

        urlWithoutRelativePath = flatPathBuffer.toString();
    }

    return urlWithoutRelativePath;
}

From source file:org.apache.tajo.plan.ExprAnnotator.java

@Override
public EvalNode visitNot(Context ctx, Stack<Expr> stack, NotExpr expr) throws TajoException {
    stack.push(expr);
    EvalNode child = visit(ctx, stack, expr.getChild());
    stack.pop();// w  w w  . ja  v  a2  s  . c  o m
    return new NotEval(child);
}

From source file:com.galenframework.parser.IndentationStructureParser.java

private void processLine(Stack<IndentationNode> stack, String line, int lineNumber, String source) {
    StructNode newStructNode = new StructNode(line.trim());
    newStructNode.setFileLineNumber(lineNumber);
    newStructNode.setSource(source);//from   w w  w .  ja v  a  2s . co m

    int calculatedIndentation = calculateIndentation(line, lineNumber);

    while (calculatedIndentation <= stack.peek().indentation && stack.peek().parent != null) {
        stack.pop();
    }

    StructNode parent = stack.peek().structNode;

    if (parent.getChildNodes() != null && parent.getChildNodes().size() > 0
            && calculatedIndentation != stack.peek().childIndentation) {
        throw new SyntaxException(new Line(line, lineNumber), "Inconsistent indentation");
    }

    parent.addChildNode(newStructNode);
    stack.peek().childIndentation = calculatedIndentation;

    stack.push(new IndentationNode(calculatedIndentation, newStructNode, parent));
}