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:org.springjutsu.validation.rules.ValidationRulesContainer.java

/**
 * Copy rules from parent classes into child classes.
 *///  w  w w .  ja  v  a  2s .  c  om
@SuppressWarnings("unchecked")
protected void initInheritance() {
    Set<Class<?>> inheritanceChecked = new HashSet<Class<?>>();
    for (ValidationEntity entity : validationEntityMap.values()) {

        Stack<Class<?>> classStack = new Stack<Class<?>>();
        classStack.push(entity.getValidationClass());
        for (Class<?> clazz = entity.getValidationClass().getSuperclass(); clazz != null
                && clazz != Object.class; clazz = clazz.getSuperclass()) {
            classStack.push(clazz);
        }

        Set<ValidationRule> inheritableRules = new ListOrderedSet();
        Set<ValidationTemplateReference> inheritableTemplateReferences = new ListOrderedSet();
        Set<ValidationContext> inheritableContexts = new ListOrderedSet();
        Set<String> inheritableExclusionPaths = new HashSet<String>();
        Set<String> inheritableInclusionPaths = new HashSet<String>();

        while (!classStack.isEmpty()) {
            Class<?> clazz = classStack.pop();
            if (supportsClass(clazz) && !inheritanceChecked.contains(clazz)) {
                validationEntityMap.get(clazz).getRules().addAll(inheritableRules);
                validationEntityMap.get(clazz).getValidationContexts().addAll(inheritableContexts);
                validationEntityMap.get(clazz).getExcludedPaths().addAll(inheritableExclusionPaths);
                validationEntityMap.get(clazz).getIncludedPaths().addAll(inheritableInclusionPaths);
                validationEntityMap.get(clazz).getTemplateReferences().addAll(inheritableTemplateReferences);
            }
            if (hasRulesForClass(clazz)) {
                inheritableRules.addAll(validationEntityMap.get(clazz).getRules());
            }
            if (supportsClass(clazz)) {
                inheritableContexts.addAll(validationEntityMap.get(clazz).getValidationContexts());
                inheritableExclusionPaths.addAll(validationEntityMap.get(clazz).getExcludedPaths());
                inheritableInclusionPaths.addAll(validationEntityMap.get(clazz).getIncludedPaths());
            }
            inheritanceChecked.add(clazz);
        }
    }
}

From source file:com.amalto.webapp.core.util.Util.java

public static WSWhereItem makeWhereItem(List<WSWhereItem> conditions) {
    List<Object> conds = new ArrayList<Object>();
    for (int i = 0; i < conditions.size(); i++) {
        WSWhereItem item = conditions.get(i);
        conds.add(item);//  www.j a  va  2 s.c o  m
        if (i < conditions.size() - 1) {
            WSStringPredicate predicate = item.getWhereCondition().getStringPredicate();
            switch (predicate) {
            case NOT:
            case EXACTLY:
            case STRICTAND:
            case NONE:
                predicate = WSStringPredicate.AND;
                break;
            }
            conds.add(predicate);
        }
    }
    Stack<WSStringPredicate> stackOp = new Stack<WSStringPredicate>();
    List<Object> rpn = new ArrayList<Object>();
    for (Object item : conds) {
        if (item instanceof WSWhereItem) {
            rpn.add(item);
        } else {
            WSStringPredicate predicate = (WSStringPredicate) item;
            while (!stackOp.isEmpty()) {
                rpn.add(stackOp.pop());
            }
            stackOp.push(predicate);
        }
    }
    while (!stackOp.isEmpty()) {
        rpn.add(stackOp.pop());
    }
    Stack<WSWhereItem> whereStack = new Stack<WSWhereItem>();
    for (Object o : rpn) {
        if (o instanceof WSWhereItem) {
            whereStack.push((WSWhereItem) o);
        } else if (o instanceof WSStringPredicate) {
            if (WSStringPredicate.OR.equals(o)) {
                WSWhereItem item1 = whereStack.pop();
                WSWhereItem item2 = whereStack.pop();
                WSWhereOr or = new WSWhereOr(new WSWhereItem[] { item2, item1 });
                whereStack.push(new WSWhereItem(null, null, or));
            } else if (WSStringPredicate.AND.equals(o)) {
                WSWhereItem item1 = whereStack.pop();
                WSWhereItem item2 = whereStack.pop();
                WSWhereAnd and = new WSWhereAnd(new WSWhereItem[] { item2, item1 });
                whereStack.push(new WSWhereItem(null, and, null));
            }
        }
    }
    return whereStack.pop();
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.graphconnectivity.algorithm.GraphConnectivityWSD.java

@Override
public Map<Pair<String, POS>, Map<String, Double>> getDisambiguation(Collection<Pair<String, POS>> sods)
        throws SenseInventoryException {
    Graph<String, UnorderedPair<String>> siGraph = inventory.getUndirectedGraph();
    Graph<String, UnorderedPair<String>> dGraph = new UndirectedSparseGraph<String, UnorderedPair<String>>();
    int sodCount = 0;

    if (graphVisualizer != null) {
        graphVisualizer.initializeColorMap(sods.size());
        graphVisualizer.setVertexToolTipTransformer(new VertexToolTipTransformer());
    }/*from   w  ww. j  a v a2 s  .  c  o  m*/

    // Find the senses for the lemmas and add them to a graph
    for (Pair<String, POS> wsdItem : sods) {
        List<String> senses = inventory.getSenses(wsdItem.getFirst(), wsdItem.getSecond());
        if (senses.isEmpty()) {
            logger.warn("unknown subject of disambiguation " + wsdItem);
            // throw new SenseInventoryException(
            // "unknown subject of disambiguation " + wsdItem);
        }

        for (String sense : senses) {
            if (graphVisualizer != null) {
                graphVisualizer.setColor(sense, sodCount);
            }
            dGraph.addVertex(sense);
        }

        sodCount++;
    }
    logger.debug(dGraph.toString());

    if (graphVisualizer != null) {
        graphVisualizer.initialize(dGraph);
    }

    // For each synset v in s, perform a depth-first search on siGraph.
    // Every time we encounter a synset v' from s along a path of length
    //  l, we add to dGraph all intermediate nodes and edges on the path
    // from v to v'.

    // Run DFS on each synset in s
    Collection<String> s = new HashSet<String>(dGraph.getVertices());
    for (String v : s) {
        logger.debug("Beginning DFS from " + v);
        Collection<String> t = new HashSet<String>(s);
        t.remove(v);
        Stack<String> synsetPath = new Stack<String>();
        synsetPath.push(v);
        dfs(v, t, siGraph, dGraph, synsetPath, new Stack<UnorderedPair<String>>(), searchDepth);
    }

    logger.debug(dGraph.toString());

    // Find the best synsets for each word in the sentence
    final Map<Pair<String, POS>, Map<String, Double>> solutions = getDisambiguation(sods, dGraph);

    // Repaint the frame to show the disambiguated senses
    if (graphVisualizer != null) {
        graphVisualizer.refresh();
    }

    return solutions;
}

From source file:com.altoukhov.svsync.fileviews.LocalFileSpace.java

@Override
protected Snapshot scan(List<Pattern> filters) {
    try {//  w w w.  j  av a 2 s  . c  o m
        Map<String, FileSnapshot> files = new LinkedHashMap<>();
        Set<String> dirs = new HashSet<>();

        File root = new File(rootPath);

        if (root.exists()) {

            Stack<File> stack = new Stack<>();
            stack.push(root);
            dirs.add("");

            while (!stack.isEmpty()) {
                File currentFolder = stack.pop();

                for (final File file : currentFolder.listFiles(filter)) {

                    if (file.isFile() && !isExcluded(trimFilePath(file.getAbsolutePath()))
                            && !isFiltered(toRelativePath(file.getAbsolutePath()), filters)) {
                        FileSnapshot fileSnapshot = new FileSnapshot(file.getName(), file.length(),
                                new DateTime(new Date(file.lastModified())),
                                toRelativePath(file.getAbsolutePath()));
                        files.put(fileSnapshot.getRelativePath(), fileSnapshot);
                    } else if (file.isDirectory() && !isExcluded(trimFilePath(file.getAbsolutePath()))
                            && !isFiltered(toRelativePath(file.getAbsolutePath(), true), filters)) {
                        stack.push(file);
                        dirs.add(toRelativePath(file.getAbsolutePath()));
                        System.out.println("Scanning " + file.getAbsolutePath());
                    }
                }
            }
        }
        Snapshot snapshot = new Snapshot(files, dirs);
        return snapshot;
    } catch (SecurityException ex) {
        System.out.println("Failed to scan file space");
        System.out.println(ex.getMessage());
    }

    return null;
}

From source file:gov.medicaid.screening.dao.impl.NurseAnesthetistsLicenseDAOBean.java

/**
 * Parses the full name into a User object.
 *
 * @param fullName the full name displayed on the site
 * @return the parsed name/*ww w. ja  va  2s . c  o  m*/
 */
private User parseName(String fullName) {
    fullName = fullName.substring(0, fullName.indexOf(",")); // remove certificate title
    User user = new User();
    Stack<String> nameParts = new Stack<String>();
    for (String string : fullName.split(" ")) {
        nameParts.push(string);
    }
    user.setLastName(nameParts.pop());
    if (nameParts.size() > 1) {
        user.setMiddleName(nameParts.pop());
    }
    StringBuffer sb = new StringBuffer();
    while (!nameParts.isEmpty()) {
        sb.insert(0, nameParts.pop() + " ");
    }
    user.setFirstName(sb.toString().trim());
    return user;
}

From source file:org.apache.sling.testing.tools.sling.SlingClient.java

/** Create path and all its parent folders, using MKCOL */
public void mkdirs(String path) throws IOException {
    // Call mkdir on all parent paths, starting at the topmost one
    final Stack<String> parents = new Stack<String>();
    path = getParentPath(path);/*from w  ww .  j  a  v a  2s . c  o  m*/
    while (path.length() > 0 && !exists(path)) {
        parents.push(path);
        path = getParentPath(path);
    }

    while (!parents.isEmpty()) {
        mkdir(parents.pop());
    }
}

From source file:com.webcohesion.ofx4j.io.TestBaseOFXReader.java

/**
 * tests using sax to parse an OFX doc./*  w w w .  j  a v a 2s. c  o  m*/
 */
public void testVersion2() throws Exception {
    BaseOFXReader reader = new BaseOFXReader() {
        protected void parseV1FromFirstElement(Reader reader) throws IOException, OFXParseException {
            fail();
        }
    };
    final Map<String, String> headers = new HashMap<String, String>();
    final Stack<Map<String, Object>> aggregateStack = new Stack<Map<String, Object>>();
    TreeMap<String, Object> root = new TreeMap<String, Object>();
    aggregateStack.push(root);

    reader.setContentHandler(new DefaultHandler() {

        @Override
        public void onHeader(String name, String value) {
            LOG.debug(name + ":" + value);
            headers.put(name, value);
        }

        @Override
        public void onElement(String name, String value) {
            char[] tabs = new char[aggregateStack.size() * 2];
            Arrays.fill(tabs, ' ');
            LOG.debug(new String(tabs) + name + "=" + value);

            aggregateStack.peek().put(name, value);
        }

        @Override
        public void startAggregate(String aggregateName) {
            char[] tabs = new char[aggregateStack.size() * 2];
            Arrays.fill(tabs, ' ');
            LOG.debug(new String(tabs) + aggregateName + " {");

            TreeMap<String, Object> aggregate = new TreeMap<String, Object>();
            aggregateStack.peek().put(aggregateName, aggregate);
            aggregateStack.push(aggregate);
        }

        @Override
        public void endAggregate(String aggregateName) {
            aggregateStack.pop();

            char[] tabs = new char[aggregateStack.size() * 2];
            Arrays.fill(tabs, ' ');
            LOG.debug(new String(tabs) + "}");
        }
    });
    reader.parse(BaseOFXReader.class.getResourceAsStream("example-response.ofx2"));
    assertEquals(5, headers.size());
    assertEquals(1, aggregateStack.size());
    assertSame(root, aggregateStack.pop());
}

From source file:com.sencha.gxt.core.rebind.XTemplateParser.java

public TemplateModel parse(String template) throws UnableToCompleteException {
    // look for parameters or tags (Consider combining into one pattern)
    TemplateModel model = new TemplateModel();
    Stack<ContainerTemplateChunk> stack = new Stack<ContainerTemplateChunk>();
    stack.push(model);
    Matcher m = NON_LITERAL_PATTERN.matcher(template);
    int lastMatchEnd = 0;
    while (m.find()) {
        // range of the current non-literal
        int begin = m.start(), end = m.end();
        String currentMatch = template.substring(begin, end);

        // if there was content since the last non-literal chunk, track it
        if (lastMatchEnd < begin) {
            ContentChunk c = literal(template.substring(lastMatchEnd, begin));
            stack.peek().children.add(c);
            log(c);//from  w  ww .j  a  v a2s. c  om
        }

        // move the last match pointer
        lastMatchEnd = end;

        // tpl tag starting
        Matcher tagOpenMatch = TAG_PATTERN.matcher(currentMatch);
        if (tagOpenMatch.matches()) {
            ControlChunk c = new ControlChunk();
            c.controls = new HashMap<String, String>();
            String attrs = tagOpenMatch.group(1).trim();
            Matcher attrMatcher = ATTR_PATTERN.matcher(attrs);
            while (attrMatcher.find()) {
                // should be if or for
                String key = attrMatcher.group(1);
                // must be html-decoded
                String encodedValue = attrMatcher.group(2) == null ? attrMatcher.group(3)
                        : attrMatcher.group(2);
                String value = StringEscapeUtils.unescapeXml(encodedValue);
                c.controls.put(key, value);
            }
            stack.peek().children.add(c);
            stack.push(c);
            log(c);
            continue;
        }

        // tpl tag ending
        Matcher tagCloseMatch = TAG_CLOSE_PATTERN.matcher(currentMatch);
        if (tagCloseMatch.matches()) {
            TemplateChunk c;
            try {
                c = stack.pop();
            } catch (EmptyStackException ex) {
                logger.log(Type.ERROR, "Too many </tpl> tags");
                throw new UnableToCompleteException();
            }
            log(c);
            continue;
        }

        // reference (code)
        Matcher codeMatch = INVOKE_PATTERN.matcher(currentMatch);
        if (codeMatch.matches()) {
            ContentChunk c = new ContentChunk();
            c.type = ContentType.CODE;
            c.content = codeMatch.group(1);
            stack.peek().children.add(c);
            log(c);
            continue;
        }

        // reference (param)
        Matcher paramMatch = PARAM_PATTERN.matcher(currentMatch);
        if (paramMatch.matches()) {
            ContentChunk c = new ContentChunk();
            c.type = ContentType.REFERENCE;
            c.content = paramMatch.group(1);
            stack.peek().children.add(c);
            log(c);
            continue;
        }
    }
    // handle trailing content
    if (lastMatchEnd < template.length()) {
        ContentChunk c = literal(template.substring(lastMatchEnd));
        log(c);
        model.children.add(c);
    }
    if (model != stack.peek()) {
        logger.log(Type.ERROR, "Too few </tpl> tags");
        throw new UnableToCompleteException();
    }
    return model;
}

From source file:org.ow2.proactive_grid_cloud_portal.cli.cmd.AbstractCommand.java

@SuppressWarnings("unchecked")
protected void handleError(String errorMessage, Exception error, ApplicationContext currentContext) {
    Stack resultStack = resultStack(currentContext);
    resultStack.push(error);

    if (error instanceof NotConnectedRestException) {
        throw new CLIException(REASON_UNAUTHORIZED_ACCESS, errorMessage, error);
    }/*w ww  .j  a v a 2s.  co  m*/

    writeLine(currentContext, errorMessage);
    Throwable cause = error.getCause();

    String message = error.getMessage();

    if (cause != null) {
        message = cause.getMessage();
    }

    writeLine(currentContext, "Error message: %s", message);

    if (isDebugModeEnabled(currentContext)) {
        writeLine(currentContext, "Stack trace: %s", getStackTraceAsString((cause == null) ? error : cause));
    } else {
        writeDebugModeUsage(currentContext);
    }
}

From source file:org.apache.fontbox.cff.Type1CharStringParser.java

private List<Object> parse(byte[] bytes, List<byte[]> subrs, List<Object> sequence) throws IOException {
    DataInput input = new DataInput(bytes);
    while (input.hasRemaining()) {
        int b0 = input.readUnsignedByte();
        if (b0 == CALLSUBR) {
            // callsubr command
            Object obj = sequence.remove(sequence.size() - 1);
            if (!(obj instanceof Integer)) {
                LOG.warn("Parameter " + obj + " for CALLSUBR is ignored, integer expected in glyph '"
                        + glyphName + "' of font " + fontName);
                continue;
            }//  w  w  w .  j a va2 s. com
            Integer operand = (Integer) obj;

            if (operand >= 0 && operand < subrs.size()) {
                byte[] subrBytes = subrs.get(operand);
                parse(subrBytes, subrs, sequence);
                Object lastItem = sequence.get(sequence.size() - 1);
                if (lastItem instanceof CharStringCommand
                        && ((CharStringCommand) lastItem).getKey().getValue()[0] == RETURN) {
                    sequence.remove(sequence.size() - 1); // remove "return" command
                }
            } else {
                LOG.warn("CALLSUBR is ignored, operand: " + operand + ", subrs.size(): " + subrs.size()
                        + " in glyph '" + glyphName + "' of font " + fontName);
                // remove all parameters (there can be more than one)
                while (sequence.get(sequence.size() - 1) instanceof Integer) {
                    sequence.remove(sequence.size() - 1);
                }
            }
        } else if (b0 == TWO_BYTE && input.peekUnsignedByte(0) == CALLOTHERSUBR) {
            // callothersubr command (needed in order to expand Subrs)
            input.readByte();

            Integer othersubrNum = (Integer) sequence.remove(sequence.size() - 1);
            Integer numArgs = (Integer) sequence.remove(sequence.size() - 1);

            // othersubrs 0-3 have their own semantics
            Stack<Integer> results = new Stack<Integer>();
            switch (othersubrNum) {
            case 0:
                results.push(removeInteger(sequence));
                results.push(removeInteger(sequence));
                sequence.remove(sequence.size() - 1);
                // end flex
                sequence.add(0);
                sequence.add(new CharStringCommand(TWO_BYTE, CALLOTHERSUBR));
                break;
            case 1:
                // begin flex
                sequence.add(1);
                sequence.add(new CharStringCommand(TWO_BYTE, CALLOTHERSUBR));
                break;
            case 3:
                // allows hint replacement
                results.push(removeInteger(sequence));
                break;
            default:
                // all remaining othersubrs use this fallback mechanism
                for (int i = 0; i < numArgs; i++) {
                    results.push(removeInteger(sequence));
                }
                break;
            }

            // pop must follow immediately
            while (input.peekUnsignedByte(0) == TWO_BYTE && input.peekUnsignedByte(1) == POP) {
                input.readByte(); // B0_POP
                input.readByte(); // B1_POP
                sequence.add(results.pop());
            }

            if (results.size() > 0) {
                LOG.warn("Value left on the PostScript stack in glyph " + glyphName + " of font " + fontName);
            }
        } else if (b0 >= 0 && b0 <= 31) {
            sequence.add(readCommand(input, b0));
        } else if (b0 >= 32 && b0 <= 255) {
            sequence.add(readNumber(input, b0));
        } else {
            throw new IllegalArgumentException();
        }
    }
    return sequence;
}