Example usage for java.util Stack empty

List of usage examples for java.util Stack empty

Introduction

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

Prototype

public boolean empty() 

Source Link

Document

Tests if this stack is empty.

Usage

From source file:com.unboundid.scim.sdk.FilterParser.java

/**
 * Read a filter expression.//  w w  w.  ja  va  2 s . com
 *
 * @return  The SCIM filter.
 */
private SCIMFilter readFilter() {
    final Stack<Node> expressionStack = new Stack<Node>();

    // Employ the shunting-yard algorithm to parse into reverse polish notation,
    // where the operands are filter components and the operators are the
    // logical AND and OR operators. This algorithm ensures that operator
    // precedence and parentheses are respected.
    final List<Node> reversePolish = new ArrayList<Node>();
    for (String word = readWord(); word != null; word = readWord()) {
        if (word.equalsIgnoreCase("and") || word.equalsIgnoreCase("or")) {
            final OperatorNode currentOperator;
            if (word.equalsIgnoreCase("and")) {
                currentOperator = new OperatorNode(SCIMFilterType.AND, markPos);
            } else {
                currentOperator = new OperatorNode(SCIMFilterType.OR, markPos);
            }
            while (!expressionStack.empty() && (expressionStack.peek() instanceof OperatorNode)) {
                final OperatorNode previousOperator = (OperatorNode) expressionStack.peek();
                if (previousOperator.getPrecedence() < currentOperator.getPrecedence()) {
                    break;
                }
                reversePolish.add(expressionStack.pop());
            }
            expressionStack.push(currentOperator);
        } else if (word.equals("(")) {
            expressionStack.push(new LeftParenthesisNode(markPos));
        } else if (word.equals(")")) {
            while (!expressionStack.empty() && !(expressionStack.peek() instanceof LeftParenthesisNode)) {
                reversePolish.add(expressionStack.pop());
            }
            if (expressionStack.empty()) {
                final String msg = String.format(
                        "No opening parenthesis matching closing " + "parenthesis at position %d", markPos);
                throw new IllegalArgumentException(msg);
            }
            expressionStack.pop();
        } else {
            rewind();
            final int pos = currentPos;
            final SCIMFilter filterComponent = readFilterComponent();
            reversePolish.add(new FilterNode(filterComponent, pos));
        }
    }

    while (!expressionStack.empty()) {
        final Node node = expressionStack.pop();
        if (node instanceof LeftParenthesisNode) {
            final String msg = String.format(
                    "No closing parenthesis matching opening " + "parenthesis at position %d", node.getPos());
            throw new IllegalArgumentException(msg);
        }
        reversePolish.add(node);
    }

    // Evaluate the reverse polish notation to create a single complex filter.
    final Stack<FilterNode> filterStack = new Stack<FilterNode>();
    for (final Node node : reversePolish) {
        if (node instanceof OperatorNode) {
            final FilterNode rightOperand = filterStack.pop();
            final FilterNode leftOperand = filterStack.pop();

            final OperatorNode operatorNode = (OperatorNode) node;
            if (operatorNode.getFilterType().equals(SCIMFilterType.AND)) {
                final SCIMFilter filter = SCIMFilter.createAndFilter(
                        Arrays.asList(leftOperand.getFilterComponent(), rightOperand.getFilterComponent()));
                filterStack.push(new FilterNode(filter, leftOperand.getPos()));
            } else {
                final SCIMFilter filter = SCIMFilter.createOrFilter(
                        Arrays.asList(leftOperand.getFilterComponent(), rightOperand.getFilterComponent()));
                filterStack.push(new FilterNode(filter, leftOperand.getPos()));
            }
        } else {
            filterStack.push((FilterNode) node);
        }
    }

    if (filterStack.size() == 0) {
        final String msg = String.format("Empty filter expression");
        throw new IllegalArgumentException(msg);
    } else if (filterStack.size() > 1) {
        final String msg = String.format("Unexpected characters at position %d", expressionStack.get(1).pos);
        throw new IllegalArgumentException(msg);
    }

    return filterStack.get(0).filterComponent;
}

From source file:org.alfresco.repo.model.filefolder.FileFolderServiceImpl.java

/**
 * A deep version of listSimple.   Which recursively walks down the tree from a given starting point, returning 
 * the node refs of files or folders found along the way.
 * <p>/*from  www  .  ja  v  a 2  s .  c  o m*/
 * The folder filter is called for each sub-folder to determine whether to search in that sub-folder, should a subfolder be excluded 
 * then all its chidren are excluded as well.
 * 
 * @param contextNodeRef the starting point.
 * @param files return nodes of type files.
 * @param folders return nodes of type folders.
 * @param folderFilter filter controls which folders to search.  If null then all subfolders are searched.
 * @return list of node references
 */
/* <p>
 * MER: I've added this rather than changing listSimple to minimise the risk of breaking 
 * the existing code.   This is a quick performance improvement between using 
 * XPath which is awful or adding new methods to the NodeService/DB   This is also a dangerous method in that it can return a 
 * lot of data and take a long time.
 */
private List<NodeRef> listSimpleDeep(NodeRef contextNodeRef, boolean files, boolean folders,
        SubFolderFilter folderFilter) {
    if (logger.isDebugEnabled()) {
        logger.debug("searchSimpleDeep contextNodeRef:" + contextNodeRef);
    }

    // To hold the results.
    List<NodeRef> result = new ArrayList<NodeRef>();

    // Build a list of folder types
    Set<QName> folderTypeQNames = buildFolderTypes();
    Set<QName> fileTypeQNames = (files ? buildFileTypes() : new HashSet<QName>(0));

    if (!folders && !files) {
        return Collections.emptyList();

    }

    // Shortcut
    if (folderTypeQNames.size() == 0) {
        return Collections.emptyList();
    }

    Stack<NodeRef> toSearch = new Stack<NodeRef>();
    toSearch.push(contextNodeRef);

    // Now we need to walk down the folders.
    while (!toSearch.empty()) {
        NodeRef currentDir = toSearch.pop();

        List<ChildAssociationRef> folderAssocRefs = nodeService.getChildAssocs(currentDir, folderTypeQNames);

        for (ChildAssociationRef folderRef : folderAssocRefs) {
            // We have some child folders
            boolean include = true;
            if (folderFilter != null) {
                include = folderFilter.isEnterSubfolder(folderRef);
                if (include) {
                    // yes search in these subfolders
                    toSearch.push(folderRef.getChildRef());
                }
            } else {
                // No filter - Add the folders in the currentDir
                toSearch.push(folderRef.getChildRef());
            }

            if (folders && include) {
                result.add(folderRef.getChildRef());
            }
        }

        if (files) {
            // Add the files in the current dir
            List<ChildAssociationRef> fileAssocRefs = nodeService.getChildAssocs(currentDir, fileTypeQNames);
            for (ChildAssociationRef fileRef : fileAssocRefs) {
                result.add(fileRef.getChildRef());
            }
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("searchSimpleDeep finished size:" + result.size());
    }

    // Done
    return result;
}

From source file:org.lockss.plugin.igiglobal.TestIgiGlobalBooksArticleIteratorFactory.java

public void testCreateArticleFiles() throws Exception {
    PluginTestUtil.crawlSimAu(sau);// w w w  . ja va  2  s  . c o  m
    // Order doesn't matter on these. We're just loading a bunch of URLs into a UrlCacher
    // Notice that in some cases we have an abstract and the matchingPDF
    // In other cases we're missing one of the pieces
    // This is to test edge cases in the ArticleIterator
    String[] urls = { BASE_URL + "gateway/chapter/full-text-pdf/55656",
            BASE_URL + "gateway/chapter/full-text-pdf/12345", BASE_URL + "gateway/chapter/full-text-html/54321",
            BASE_URL + "gateway/chapter/11111", BASE_URL + "gateway/chapter/55656",
            BASE_URL + "gateway/chapter/54321", BASE_URL + "gateway/book/464", BASE_URL, BASE_URL + "gateway" };
    CachedUrl cuPdf = null;
    CachedUrl cuHtml = null;
    for (CachedUrl cu : AuUtil.getCuIterable(sau)) {
        //
        // The only thing we seem to be doing with the content that was created in the SimulatedAU 
        // Is to pick up one PDF cu and one HTML cu
        // Only the HTML CU is used and then only to put content in to other html URLs in the UrlCacher
        //
        if (cuPdf == null && cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_PDF)) {
            cuPdf = cu;
        } else if (cuHtml == null && cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_HTML)) {
            cuHtml = cu;
        }
        if (cuPdf != null && cuHtml != null) {
            break;
        }
    }
    // add a URL with content to the "real" au
    // oddly, they'll all be html...the PDF URLs have an thml frameset so this is okay
    for (String url : urls) {
        UrlData ud = new UrlData(cuHtml.getUnfilteredInputStream(), cuHtml.getProperties(), url);
        UrlCacher uc = au.makeUrlCacher(ud);
        uc.storeContent();
    }

    Stack<String[]> expStack = new Stack<String[]>();
    // fulltextcu
    // FULL_TEXT_PDF
    // ABSTRACT 
    String[] af1 = { BASE_URL + "gateway/chapter/11111", null, BASE_URL + "gateway/chapter/11111" };

    String[] af2 = { BASE_URL + "gateway/chapter/full-text-html/54321", null,
            BASE_URL + "gateway/chapter/54321" };

    String[] af3 = { BASE_URL + "gateway/chapter/full-text-pdf/12345",
            BASE_URL + "gateway/chapter/full-text-pdf/12345", null };

    String[] af4 = { BASE_URL + "gateway/chapter/full-text-pdf/55656",
            BASE_URL + "gateway/chapter/full-text-pdf/55656", BASE_URL + "gateway/chapter/55656" };

    expStack.push(af4);
    expStack.push(af3);
    expStack.push(af2);
    expStack.push(af1);

    for (SubTreeArticleIterator artIter = createSubTreeIter(); artIter.hasNext();) {
        ArticleFiles af = artIter.next();
        String[] act = { af.getFullTextUrl(), af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF_LANDING_PAGE),
                af.getRoleUrl(ArticleFiles.ROLE_ABSTRACT) };
        String[] exp = expStack.pop();
        if (act.length == exp.length) {
            for (int i = 0; i < act.length; i++) {
                assertEquals(ARTICLE_FAIL_MSG + " Expected: " + exp[i] + " Actual: " + act[i], exp[i], act[i]);
            }
        } else
            fail(ARTICLE_FAIL_MSG + " length of expected and actual ArticleFiles content not the same:"
                    + exp.length + "!=" + act.length);
    }
    if (!expStack.empty()) {
        fail("Test stack is not empty:");
    }
}

From source file:org.apache.zeppelin.sap.universe.UniverseUtil.java

private String parseWhere(String where, Map<String, UniverseNodeInfo> nodeInfos) throws UniverseException {
    List<String> out = new ArrayList<>();
    Stack<String> stack = new Stack<>();

    where = where.replaceAll("\\s*", "");

    Set<String> operationSymbols = new HashSet<>(OPERATIONS.keySet());
    operationSymbols.add(LEFT_BRACE);/*from   ww w. ja  v a2  s. c o  m*/
    operationSymbols.add(RIGHT_BRACE);

    int index = 0;

    boolean findNext = true;
    while (findNext) {
        int nextOperationIndex = where.length();
        String nextOperation = "";
        for (String operation : operationSymbols) {
            int i = where.indexOf(operation, index);
            if (i >= 0 && i < nextOperationIndex) {
                nextOperation = operation;
                nextOperationIndex = i;
            }
        }
        if (nextOperationIndex == where.length()) {
            findNext = false;
        } else {
            if (index != nextOperationIndex) {
                out.add(where.substring(index, nextOperationIndex));
            }
            if (nextOperation.equals(LEFT_BRACE)) {
                stack.push(nextOperation);
            } else if (nextOperation.equals(RIGHT_BRACE)) {
                while (!stack.peek().equals(LEFT_BRACE)) {
                    out.add(stack.pop());
                    if (stack.empty()) {
                        throw new UniverseException("Unmatched brackets");
                    }
                }
                stack.pop();
            } else {
                while (!stack.empty() && !stack.peek().equals(LEFT_BRACE)
                        && (OPERATIONS.get(nextOperation) >= OPERATIONS.get(stack.peek()))) {
                    out.add(stack.pop());
                }
                stack.push(nextOperation);
            }
            index = nextOperationIndex + nextOperation.length();
        }
    }
    if (index != where.length()) {
        out.add(where.substring(index));
    }
    while (!stack.empty()) {
        out.add(stack.pop());
    }
    StringBuffer result = new StringBuffer();
    if (!out.isEmpty())
        result.append(out.remove(0));
    while (!out.isEmpty())
        result.append(" ").append(out.remove(0));

    // result contains the reverse polish notation
    return convertWhereToXml(result.toString(), nodeInfos);
}

From source file:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePatternNode.java

/**
 * //w w w.  j ava 2 s .c o m
 * @param edge
 */
public void copyVirtualChild(NavigationTreePatternEdge edge) {
    NavigationTreePatternNode childCopy = edge.n2.deepCopy();
    // marking childCopy and its subtree as virtual:
    Stack<NavigationTreePatternNode> st = new Stack<NavigationTreePatternNode>();
    st.push(childCopy);
    while (!st.empty()) {
        NavigationTreePatternNode pn = st.pop();
        // Parameters.logger.info("Set virtual node: " + pn.tag);
        pn.virtual = true;
        pn.nodeCode = NavigationTreePatternNode.globalNodeCounter.getAndIncrement();
        // virtual nodes obtained by navigation cannot store ID
        pn.storesID = false;
        Iterator<NavigationTreePatternEdge> pnChildren = pn.edges.iterator();
        while (pnChildren.hasNext()) {
            NavigationTreePatternEdge pnEdge = pnChildren.next();
            st.push(pnEdge.n2);
        }
    }
    addEdge(childCopy, edge.isParent(), edge.isNested(), edge.isOptional());
}

From source file:fr.inria.oak.paxquery.common.xml.navigation.NavigationTreePatternNode.java

/**
 * Returns true if this node is the top returning node of the tree pattern.
 * Assumes that the node returns at least an ID, so we don't check for that.
 * Also assumes that the node selects on the tag and does not return it.
 * @return isTopReturningNode//from  w w  w  . j  ava  2 s  .  co m
 */
public boolean isTopReturningNode() {
    if (this.isTopReturningNode == 0) {
        return false;
    }
    if (this.isTopReturningNode == 1) {
        return true;
    }
    // otherwise, it is -1, and we need to look
    if (this.parentEdge == null) {
        return true;
    }
    NavigationTreePatternNode n2 = this.parentEdge.n1;
    Stack<NavigationTreePatternNode> sn = new Stack<NavigationTreePatternNode>();
    sn.push(n2);
    while (!sn.empty()) {
        NavigationTreePatternNode n3 = sn.pop();
        if (n3 == null) {
            this.isTopReturningNode = 1;
            return true;
        }
        if (n3.storesID || n3.storesValue || (n3.storesContent)) {
            this.isTopReturningNode = 0;
            return false;
        }
        if (n3.parentEdge != null) {
            sn.push(n3.parentEdge.n1);
        }
    }
    this.isTopReturningNode = 1;
    return true;
}

From source file:org.apache.zeppelin.sap.universe.UniverseUtil.java

private String convertWhereToXml(String rpn, Map<String, UniverseNodeInfo> nodeInfos) throws UniverseException {
    StringTokenizer tokenizer = new StringTokenizer(rpn, " ");

    Stack<String> stack = new Stack();

    while (tokenizer.hasMoreTokens()) {
        StringBuilder tmp = new StringBuilder();
        String token = tokenizer.nextToken();
        if (!OPERATIONS.keySet().contains(token)) {
            stack.push(token.trim());//ww  w .  j a va 2  s .  c  o  m
        } else {
            String rightOperand = revertReplace(stack.pop());
            String operator = token.replaceAll("^#|#$", "");

            if (token.equalsIgnoreCase(MARKER_NOT_NULL) || token.equalsIgnoreCase(MARKER_NULL)) {
                UniverseNodeInfo rightOperandInfo = nodeInfos.get(rightOperand);
                stack.push(String.format(COMPARISON_FILTER, rightOperandInfo.getId(),
                        rightOperandInfo.getNodePath(), operator));
                continue;
            }

            if (token.equalsIgnoreCase(MARKER_FILTER)) {
                UniverseNodeInfo rightOperandInfo = nodeInfos.get(rightOperand);
                stack.push(String.format(PREDEFINED_FILTER_TEMPLATE, rightOperandInfo.getNodePath(),
                        rightOperandInfo.getId()));
                continue;
            }

            String leftOperand = stack.empty() ? null : revertReplace(stack.pop());

            if (token.equalsIgnoreCase(MARKER_AND) || token.equalsIgnoreCase(MARKER_OR)) {
                if (rightOperand.matches("^\\[.*\\]$")) {
                    UniverseNodeInfo rightOperandInfo = nodeInfos.get(rightOperand);
                    if (rightOperandInfo == null) {
                        throw new UniverseException(
                                String.format("Not found information about: \"%s\"", rightOperand));
                    }
                    rightOperand = String.format(PREDEFINED_FILTER_TEMPLATE, rightOperandInfo.getNodePath(),
                            rightOperandInfo.getId());
                }
                if (leftOperand.matches("^\\[.*\\]$")) {
                    UniverseNodeInfo leftOperandInfo = nodeInfos.get(leftOperand);
                    if (leftOperandInfo == null) {
                        throw new UniverseException(
                                String.format("Not found information about: \"%s\"", leftOperand));
                    }
                    leftOperand = String.format(PREDEFINED_FILTER_TEMPLATE, leftOperandInfo.getNodePath(),
                            leftOperandInfo.getId());
                }
                tmp.append(String.format("<%s>\n", operator));
                tmp.append(leftOperand);
                tmp.append("\n");
                tmp.append(rightOperand);
                tmp.append("\n");
                tmp.append(String.format("</%s>\n", operator));
                stack.push(tmp.toString());
                continue;
            }

            UniverseNodeInfo leftOperandInfo = nodeInfos.get(leftOperand);
            if (leftOperandInfo == null) {
                throw new UniverseException(String.format("Not found information about: \"%s\"", leftOperand));
            }
            if (token.equalsIgnoreCase(MARKER_IN) || token.equalsIgnoreCase(MARKER_NOT_IN)) {
                String listValues = rightOperand.replaceAll("^\\(|\\)$", "").trim();
                boolean startItem = false;
                List<String> values = new ArrayList<>();
                StringBuilder value = new StringBuilder();
                boolean isNumericList = false;
                if (listValues.charAt(0) != '\'') {
                    isNumericList = true;
                }
                if (isNumericList) {
                    String[] nums = listValues.split(",");
                    for (String num : nums) {
                        values.add(num.trim());
                    }
                } else {
                    for (int i = 0; i < listValues.length(); i++) {
                        char c = listValues.charAt(i);
                        if (c == '\'' && (i == 0 || listValues.charAt(i - 1) != '\\')) {
                            startItem = !startItem;
                            if (!startItem) {
                                values.add(value.toString());
                                value = new StringBuilder();
                            }
                            continue;
                        }
                        if (startItem) {
                            value.append(c);
                        }
                    }
                }

                if (!values.isEmpty()) {
                    tmp.append(String.format(COMPRASION_START_TEMPLATE, leftOperandInfo.getNodePath(), operator,
                            leftOperandInfo.getId()));
                    tmp.append(CONST_OPERAND_START_TEMPLATE);
                    String type = isNumericList ? "Numeric" : "String";
                    for (String v : values) {
                        tmp.append(String.format(CONST_OPERAND_VALUE_TEMPLATE, type, v));
                    }
                    tmp.append(CONST_OPERAND_END_TEMPLATE);
                    tmp.append(COMPRASION_END_TEMPLATE);
                    stack.push(tmp.toString());
                }
                continue;
            }

            // EqualTo, LessThanOrEqualTo, NotEqualTo, LessThan, GreaterThanOrEqualTo, GreaterThan
            UniverseNodeInfo rightOperandInfo = null;
            if (rightOperand.startsWith("[") && rightOperand.endsWith("]")) {
                rightOperandInfo = nodeInfos.get(rightOperand);
                if (rightOperandInfo == null) {
                    throw new UniverseException(
                            String.format("Not found information about: \"%s\"", rightOperand));
                }
            }
            if (OPERATIONS.containsKey(token)) {
                if (rightOperandInfo != null) {
                    tmp.append(String.format(COMPRASION_START_TEMPLATE, leftOperandInfo.getNodePath(), operator,
                            leftOperandInfo.getId()));
                    tmp.append(String.format(OBJECT_OPERAND_TEMPLATE, rightOperandInfo.getId(),
                            rightOperandInfo.getNodePath()));
                    tmp.append(COMPRASION_END_TEMPLATE);
                } else {
                    String type = rightOperand.startsWith("'") ? "String" : "Numeric";
                    String value = rightOperand.replaceAll("^'|'$", "");
                    tmp.append(String.format(COMPRASION_START_TEMPLATE, leftOperandInfo.getNodePath(), operator,
                            leftOperandInfo.getId()));
                    tmp.append(CONST_OPERAND_START_TEMPLATE);
                    tmp.append(String.format(CONST_OPERAND_VALUE_TEMPLATE, type, value));
                    tmp.append(CONST_OPERAND_END_TEMPLATE);
                    tmp.append(COMPRASION_END_TEMPLATE);
                }
                stack.push(tmp.toString());
                continue;
            }
            throw new UniverseException(String.format("Incorrect syntax after: \"%s\"", leftOperand));
        }
    }

    return stack.pop();
}

From source file:org.netxilia.server.rest.HomeResource.java

/**
 * build the HTML tags for a tree like view
 * //from w w  w . ja  v  a 2 s .  com
 * @param foldersSheet
 * @param treeview
 * @throws NetxiliaBusinessException
 * @throws NetxiliaResourceException
 */
private DefaultMutableTreeNode buildWorkbookTree(IWorkbook workbook, ISheet foldersSheet,
        Set<SheetFullName> sheetNames) throws NetxiliaResourceException, NetxiliaBusinessException {
    DefaultMutableTreeNode workbookNode = new DefaultMutableTreeNode(
            new TreeViewData(workbook.getId().getKey(), workbook.getName(), "workbook"));

    Stack<DefaultMutableTreeNode> stockNodes = new Stack<DefaultMutableTreeNode>();
    stockNodes.push(workbookNode);

    Set<SheetFullName> alreadyInsertedSheets = new HashSet<SheetFullName>();
    if (foldersSheet != null) {
        Matrix<CellData> folderCells = foldersSheet.receiveCells(AreaReference.ALL).getNonBlocking();
        for (List<CellData> row : folderCells.getRows()) {
            int level = 0;
            String nodeName = null;
            for (CellData cell : row) {
                if (cell.getValue() != null) {
                    nodeName = cell.getValue().getStringValue();
                    if (nodeName != null && nodeName.length() > 0) {
                        level = cell.getReference().getColumnIndex();
                        break;
                    }
                }
            }

            if (nodeName == null) {
                // empty line - ignored
                continue;
            }

            // first level for folders is 1 (under the root node)
            level = level + 1;
            SheetFullName sheetName = new SheetFullName(workbook.getName(), nodeName);
            boolean isSheet = sheetNames.contains(sheetName);
            if (isSheet) {
                alreadyInsertedSheets.add(sheetName);
            }
            DefaultMutableTreeNode crt = new DefaultMutableTreeNode(new TreeViewData(sheetName.toString(),
                    sheetName.getSheetName(), isSheet ? "sheet" : "folder"));
            while (!stockNodes.empty()) {
                DefaultMutableTreeNode node = stockNodes.peek();
                if (level > node.getLevel()) {
                    // make sure is the direct child
                    node.add(crt);
                    break;
                }
                stockNodes.pop();
            }
            stockNodes.push(crt);
        }
    }
    // add the sheets not already added
    for (SheetFullName sheetName : sheetNames) {
        if (alreadyInsertedSheets.contains(sheetName)) {
            continue;
        }
        DefaultMutableTreeNode sheetNode = new DefaultMutableTreeNode(
                new TreeViewData(sheetName.toString(), sheetName.getSheetName(), "sheet"));
        workbookNode.add(sheetNode);
    }

    return workbookNode;
}

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

private void parseTemplates(SpanManager sm, List<Span> resolvedTemplateSpans,
        List<ResolvedTemplate> resolvedTemplates, ParsedPage pp) {

    sm.manageList(resolvedTemplateSpans);

    int pos = -2;
    Stack<Integer> templateOpenTags = new Stack<Integer>();
    while ((pos = sm.indexOf("{{", pos + 2)) != -1) {
        if (sm.length() > pos + 3 && sm.charAt(pos + 2) == '{' && sm.charAt(pos + 3) != '{') {
            pos++;/*from ww w  .  j  a va  2 s .  co  m*/
        }
        templateOpenTags.push(pos);
    }

    while (!templateOpenTags.empty()) {
        int templateOpenTag = templateOpenTags.pop();
        int templateCloseTag = sm.indexOf("}}", templateOpenTag);
        if (templateCloseTag == -1) {
            continue;
        }

        int templateOptionTag = sm.indexOf("|", templateOpenTag, templateCloseTag);
        int templateNameEnd;
        List<String> templateOptions;

        if (templateOptionTag != -1) {
            templateNameEnd = templateOptionTag;
            templateOptions = tokenize(sm, templateOptionTag + 1, templateCloseTag, "|");
        } else {
            templateNameEnd = templateCloseTag;
            templateOptions = new ArrayList<String>();
        }

        Span ts = new Span(templateOpenTag, templateCloseTag + 2);

        Template t = new Template(ts,
                encodeWikistyle(sm.substring(templateOpenTag + 2, templateNameEnd).trim()), templateOptions);

        if (calculateSrcSpans) {
            t.setSrcSpan(new SrcSpan(sm.getSrcPos(templateOpenTag), sm.getSrcPos(templateCloseTag + 2)));
        }

        t.setPos(ts);

        ResolvedTemplate rt = templateParser.parseTemplate(t, pp);

        resolvedTemplateSpans.add(ts);
        resolvedTemplates.add(rt);

        sm.replace(ts, rt.getPreParseReplacement());
    }

    if (resolvedTemplateSpans.isEmpty()) {
        sm.removeManagedList(resolvedTemplateSpans);
    }
}

From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java

/**
 * There is not much differences between links an images, so they are parsed
 * in a single step//  w  ww  .j a v a  2  s.c o m
 */
private void parseImagesAndInternalLinks(SpanManager sm, List<Span> linkSpans, List<Link> links) {

    sm.manageList(linkSpans);

    int pos = -1;
    Stack<Integer> linkOpenTags = new Stack<Integer>();
    while ((pos = sm.indexOf("[[", pos + 1)) != -1) {
        linkOpenTags.push(pos);
    }

    Span lastLinkSpan = new Span(sm.length() + 1, sm.length() + 1);
    Link.type linkType = Link.type.INTERNAL;

    while (!linkOpenTags.empty()) {
        int linkStartTag = linkOpenTags.pop();
        int linkEndTag = sm.indexOf("]]", linkStartTag);
        if (linkEndTag == -1) {
            continue;
        }

        int linkOptionTag = sm.indexOf("|", linkStartTag, linkEndTag);

        int linkTextStart;
        String linkTarget;

        if (linkOptionTag != -1) {
            linkTextStart = linkOptionTag + 1;
            linkTarget = sm.substring(new Span(linkStartTag + 2, linkOptionTag).trim(sm));
        } else {
            linkTextStart = linkStartTag + 2;
            linkTarget = sm.substring(new Span(linkStartTag + 2, linkEndTag).trim(sm));
        }

        // is is a regular link ?
        if (linkTarget.indexOf(lineSeparator) != -1) {
            continue;
        }
        linkTarget = encodeWikistyle(linkTarget);

        // so it is a Link or image!!!
        List<String> parameters;

        String namespace = getLinkNameSpace(linkTarget);
        if (namespace != null) {
            if (imageIdentifers.indexOf(namespace) != -1) {
                if (linkOptionTag != -1) {
                    int temp;
                    while ((temp = sm.indexOf("|", linkTextStart, linkEndTag)) != -1) {
                        linkTextStart = temp + 1;
                    }

                    parameters = tokenize(sm, linkOptionTag + 1, linkEndTag, "|");

                    // maybe there is an external link at the end of the
                    // image description...
                    if (sm.charAt(linkEndTag + 2) == ']' && sm.indexOf("[", linkTextStart, linkEndTag) != -1) {
                        linkEndTag++;
                    }
                } else {
                    parameters = null;
                }
                linkType = Link.type.IMAGE;
            } else {
                //Link has namespace but is not image
                linkType = Link.type.UNKNOWN;
                parameters = null;
            }
        } else {
            if (linkType == Link.type.INTERNAL && lastLinkSpan.hits(new Span(linkStartTag, linkEndTag + 2))) {
                continue;
            }
            parameters = null;
            linkType = Link.type.INTERNAL;
        }

        Span posSpan = new Span(linkTextStart, linkEndTag).trim(sm);
        linkSpans.add(posSpan);

        Link l = new Link(null, posSpan, linkTarget, linkType, parameters);
        links.add(l);

        if (calculateSrcSpans) {
            l.setSrcSpan(new SrcSpan(sm.getSrcPos(linkStartTag), sm.getSrcPos(linkEndTag + 2)));
        }

        sm.delete(posSpan.getEnd(), linkEndTag + 2);
        sm.delete(linkStartTag, posSpan.getStart());

        // removing line separators in link text
        int lsinlink;
        while ((lsinlink = sm.indexOf(lineSeparator, posSpan)) != -1) {
            sm.replace(lsinlink, lsinlink + lineSeparator.length(), " ");
        }

        lastLinkSpan = posSpan;
    }
}