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._4dconcept.springframework.data.marklogic.core.query.QueryBuilder.java

@Nullable
private Criteria buildCriteria(Object bean, MarklogicPersistentEntity<?> entity) {
    Stack<Criteria> stack = new Stack<>();
    PersistentPropertyAccessor propertyAccessor = entity.getPropertyAccessor(bean);

    entity.doWithProperties((PropertyHandler<MarklogicPersistentProperty>) property -> {
        Object value = propertyAccessor.getProperty(property);
        if (hasContent(value)) {
            if (stack.empty()) {
                stack.push(buildCriteria(property, value));
            } else {
                Criteria criteria = stack.peek();
                if (criteria.getOperator() == null) {
                    Criteria andCriteria = new Criteria(Criteria.Operator.and,
                            new ArrayList<>(Arrays.asList(criteria, buildCriteria(property, value))));
                    stack.pop();/* w ww .j  a v a2 s  .  c o  m*/
                    stack.push(andCriteria);
                } else {
                    Criteria subCriteria = buildCriteria(property, value);
                    if (subCriteria != null) {
                        criteria.add(subCriteria);
                    }
                }
            }
        }
    });

    return stack.empty() ? null : stack.peek();
}

From source file:ParenMatcher.java

public void run() {
    StyledDocument doc = getStyledDocument();
    String text = "";
    int len = doc.getLength();
    try {//from w  w w  .  j a va 2 s.c o m
        text = doc.getText(0, len);
    } catch (BadLocationException ble) {
    }
    java.util.Stack stack = new java.util.Stack();
    for (int j = 0; j < text.length(); j += 1) {
        char ch = text.charAt(j);
        if (ch == '(' || ch == '[' || ch == '{') {
            int depth = stack.size();
            stack.push("" + ch + j); // push a String containg the char and
            // the offset
            AttributeSet aset = matchAttrSet[depth % matchAttrSet.length];
            doc.setCharacterAttributes(j, 1, aset, false);
        }
        if (ch == ')' || ch == ']' || ch == '}') {
            String peek = stack.empty() ? "." : (String) stack.peek();
            if (matches(peek.charAt(0), ch)) { // does it match?
                stack.pop();
                int depth = stack.size();
                AttributeSet aset = matchAttrSet[depth % matchAttrSet.length];
                doc.setCharacterAttributes(j, 1, aset, false);
            } else { // mismatch
                doc.setCharacterAttributes(j, 1, badAttrSet, false);
            }
        }
    }

    while (!stack.empty()) { // anything left in the stack is a mismatch
        String pop = (String) stack.pop();
        int offset = Integer.parseInt(pop.substring(1));
        doc.setCharacterAttributes(offset, 1, badAttrSet, false);
    }
}

From source file:ch.entwine.weblounge.contentrepository.impl.fs.FileSystemContentRepository.java

/**
 * {@inheritDoc}/*w ww  .j a  v a2s .  c  o m*/
 * 
 * @see ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository#listResources()
 */
@Override
protected Collection<ResourceURI> listResources() throws IOException {

    List<ResourceURI> uris = new ArrayList<ResourceURI>();

    // Add all known resource types to the index
    for (ResourceSerializer<?, ?> serializer : getSerializers()) {

        // Temporary path for rebuilt site
        String resourceType = serializer.getType().toLowerCase();
        String resourceDirectory = resourceType + "s";
        String homePath = UrlUtils.concat(repositorySiteRoot.getAbsolutePath(), resourceDirectory);
        File resourcesRootDirectory = new File(homePath);
        if (!resourcesRootDirectory.isDirectory() || resourcesRootDirectory.list().length == 0) {
            logger.debug("No {}s found to index", resourceType);
            continue;
        }

        try {
            Stack<File> u = new Stack<File>();
            u.push(resourcesRootDirectory);
            while (!u.empty()) {
                File dir = u.pop();
                File[] files = dir.listFiles(new FileFilter() {
                    public boolean accept(File path) {
                        if (path.getName().startsWith("."))
                            return false;
                        return path.isDirectory() || path.getName().endsWith(".xml");
                    }
                });
                if (files == null || files.length == 0)
                    continue;
                for (File f : files) {
                    if (f.isDirectory()) {
                        u.push(f);
                    } else {
                        long version = Long.parseLong(f.getParentFile().getName());
                        String id = f.getParentFile().getParentFile().getName();
                        ResourceURI uri = new ResourceURIImpl(resourceType, getSite(), null, id, version);

                        uris.add(uri);
                    }
                }
            }
        } catch (Throwable t) {
            logger.error("Error reading available uris from file system: {}", t.getMessage());
            throw new IOException(t);
        }

    }

    return uris;
}

From source file:net.dv8tion.jda.entities.impl.MessageImpl.java

@Override
public String getStrippedContent() {
    if (strippedContent == null) {
        String tmp = getContent();
        //all the formatting keys to keep track of
        String[] keys = new String[] { "*", "_", "`", "~~" };

        //find all tokens (formatting strings described above)
        TreeSet<FormatToken> tokens = new TreeSet<>((t1, t2) -> Integer.compare(t1.start, t2.start));
        for (String key : keys) {
            Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(tmp);
            while (matcher.find()) {
                tokens.add(new FormatToken(key, matcher.start()));
            }/*from  w  w  w. j  a va2 s .c om*/
        }

        //iterate over all tokens, find all matching pairs, and add them to the list toRemove
        Stack<FormatToken> stack = new Stack<>();
        List<FormatToken> toRemove = new ArrayList<>();
        boolean inBlock = false;
        for (FormatToken token : tokens) {
            if (stack.empty() || !stack.peek().format.equals(token.format)
                    || stack.peek().start + token.format.length() == token.start) {
                //we are at opening tag
                if (!inBlock) {
                    //we are outside of block -> handle normally
                    if (token.format.equals("`")) {
                        //block start... invalidate all previous tags
                        stack.clear();
                        inBlock = true;
                    }
                    stack.push(token);
                } else if (token.format.equals("`")) {
                    //we are inside of a block -> handle only block tag
                    stack.push(token);
                }
            } else if (!stack.empty()) {
                //we found a matching close-tag
                toRemove.add(stack.pop());
                toRemove.add(token);
                if (token.format.equals("`") && stack.empty()) {
                    //close tag closed the block
                    inBlock = false;
                }
            }
        }

        //sort tags to remove by their start-index and iteratively build the remaining string
        Collections.sort(toRemove, (t1, t2) -> Integer.compare(t1.start, t2.start));
        StringBuilder out = new StringBuilder();
        int currIndex = 0;
        for (FormatToken formatToken : toRemove) {
            if (currIndex < formatToken.start) {
                out.append(tmp.substring(currIndex, formatToken.start));
            }
            currIndex = formatToken.start + formatToken.format.length();
        }
        if (currIndex < tmp.length()) {
            out.append(tmp.substring(currIndex));
        }
        //return the stripped text, escape all remaining formatting characters (did not have matching open/close before or were left/right of block
        strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");
    }
    return strippedContent;
}

From source file:org.codehaus.mojo.mrm.impl.DiskFileSystem.java

/**
 * Convert an entry into the corresponding file path.
 *
 * @param entry the entry./*from ww  w  .  ja  v a  2s .c o m*/
 * @return the corresponding file.
 * @since 1.0
 */
private File toFile(Entry entry) {
    Stack<String> stack = new Stack<String>();
    Entry entryRoot = entry.getFileSystem().getRoot();
    while (entry != null && !entryRoot.equals(entry)) {
        String name = entry.getName();
        if ("..".equals(name)) {
            if (!stack.isEmpty()) {
                stack.pop();
            }
        } else if (!".".equals(name)) {
            stack.push(name);
        }
        entry = entry.getParent();
    }
    File file = this.root;
    while (!stack.empty()) {
        file = new File(file, (String) stack.pop());
    }
    return file;
}

From source file:com.joliciel.jochre.graphics.features.InnerEmptyChupchikLowerLeftFeature.java

@Override
public FeatureResult<Boolean> checkInternal(ShapeWrapper shapeWrapper, RuntimeEnvironment env) {
    Shape shape = shapeWrapper.getShape();
    BitSet bitset = shape.getBlackAndWhiteBitSet(shape.getJochreImage().getBlackThreshold());
    boolean[][] grid = new boolean[shape.getWidth()][shape.getHeight()];
    for (int i = 0; i < shape.getWidth(); i++) {
        for (int j = 0; j < shape.getHeight(); j++) {
            if (bitset.get(j * shape.getWidth() + i))
                grid[i][j] = true;//from w w  w  .  ja v a  2s  . c o  m
        }
    }
    int startX = shape.getWidth() / 2;
    int startY = shape.getHeight() / 2;
    while (startY < shape.getHeight() && grid[startX][startY]) {
        startY += 1;
    }

    WritableImageGrid mirror = this.graphicsService.getEmptyMirror(shape);

    boolean foundChupchikOrOpening = false;
    if (startY < shape.getHeight()) {
        Stack<HorizontalLineSegment> whiteLineStack = new Stack<HorizontalLineSegment>();
        Set<HorizontalLineSegment> whiteLineSet = new TreeSet<HorizontalLineSegment>();
        HorizontalLineSegment startLine = new HorizontalLineSegment(startX, startY);
        whiteLineStack.push(startLine);
        while (!whiteLineStack.empty()) {
            HorizontalLineSegment line = whiteLineStack.pop();
            if (line.y == shape.getHeight() - 1) {
                // found opening to the outside world
                if (LOG.isTraceEnabled())
                    LOG.trace("Reached edge: found opening");
                foundChupchikOrOpening = true;
                break;
            }
            if (mirror.getPixel(line.xLeft, line.y) == 1)
                continue;

            // extend this line to the right and left
            for (int i = line.xLeft; i >= 0; i--) {
                if (!grid[i][line.y])
                    line.xLeft = i;
                else
                    break;
            }
            for (int i = line.xRight; i <= startX; i++) {
                if (!grid[i][line.y])
                    line.xRight = i;
                else
                    break;
            }
            if (LOG.isTraceEnabled())
                LOG.trace(line.toString());
            whiteLineSet.add(line);

            for (int i = line.xLeft; i <= line.xRight; i++) {
                mirror.setPixel(i, line.y, 1);
            }

            // find lines below and to the left
            if (line.y < shape.getHeight() - 1) {
                boolean inLine = false;
                int row = line.y + 1;
                int xLeft = 0;
                for (int i = line.xLeft; i <= line.xRight; i++) {
                    if (!inLine && !grid[i][row]) {
                        inLine = true;
                        xLeft = i;
                    } else if (inLine && grid[i][row]) {
                        HorizontalLineSegment newLine = new HorizontalLineSegment(xLeft, row);
                        newLine.xRight = i - 1;
                        whiteLineStack.push(newLine);
                        inLine = false;
                    }
                }
                if (inLine) {
                    HorizontalLineSegment newLine = new HorizontalLineSegment(xLeft, row);
                    newLine.xRight = line.xRight;
                    whiteLineStack.push(newLine);
                }
            }
        }

        if (!foundChupchikOrOpening) {
            //            if (LOG.isDebugEnabled()) {
            //               LOG.trace("List of lines");
            //               for (HorizontalLineSegment line : whiteLineSet) {
            //                  LOG.trace(line.toString());
            //               }
            //            }
            Iterator<HorizontalLineSegment> iLines = whiteLineSet.iterator();
            HorizontalLineSegment bottomLeftLine = iLines.next();
            double threshold = shape.getWidth() / 8;
            if (LOG.isTraceEnabled())
                LOG.trace("Length threshold: " + threshold);
            HorizontalLineSegment nextLine = null;
            List<HorizontalLineSegment> firstFewLines = new ArrayList<HorizontalLineSegment>();
            firstFewLines.add(bottomLeftLine);
            HorizontalLineSegment currentLine = bottomLeftLine;
            while (iLines.hasNext() && firstFewLines.size() < 3) {
                nextLine = iLines.next();
                if (nextLine.y != currentLine.y) {
                    firstFewLines.add(nextLine);
                    currentLine = nextLine;
                }
            }
            boolean mightHaveChupchik = true;
            HorizontalLineSegment prevLine = null;
            for (HorizontalLineSegment line : firstFewLines) {
                if (LOG.isTraceEnabled())
                    LOG.trace("Next line left, " + bottomLeftLine.xLeft + ", length: " + bottomLeftLine.length()
                            + ", threshold: " + threshold);
                if (line.length() > threshold) {
                    mightHaveChupchik = false;
                    break;
                }
                if (prevLine != null) {
                    if (line.xLeft + 2 < prevLine.xLeft) {
                        mightHaveChupchik = false;
                        break;
                    }
                    if (line.length() + 1 < prevLine.length()) {
                        mightHaveChupchik = false;
                        break;
                    }
                }
                prevLine = line;
                threshold = threshold * 1.2;
            }
            if (mightHaveChupchik)
                foundChupchikOrOpening = true;
        }
    }

    FeatureResult<Boolean> outcome = this.generateResult(foundChupchikOrOpening);
    return outcome;
}

From source file:org.apache.cocoon.components.treeprocessor.variables.PreparedVariableResolver.java

public final String resolve(InvokeContext context, Map objectModel) throws PatternException {
    List mapStack = null; // get the stack only when necessary - lazy inside the loop
    int stackSize = 0;

    if (needsMapStack) {
        if (context == null) {
            throw new PatternException("Need an invoke context to resolve " + this);
        }/*from   w w  w .  java 2 s.c o m*/
        mapStack = context.getMapStack();
        stackSize = mapStack.size();
    }

    Stack stack = new Stack();

    for (Iterator i = tokens.iterator(); i.hasNext();) {
        Token token = (Token) i.next();
        Token last;
        switch (token.getType()) {
        case TEXT:
            if (stack.empty()) {
                stack.push(new Token(EXPR, token.getStringValue()));
            } else {
                last = (Token) stack.peek();
                if (last.hasType(EXPR)) {
                    last.merge(token);
                } else {
                    stack.push(new Token(EXPR, token.getStringValue()));
                }
            }
            break;
        case CLOSE:
            Token expr = (Token) stack.pop();
            Token lastButOne = (Token) stack.pop();
            Token result;
            if (expr.hasType(COLON)) { // i.e. nothing was specified after the colon
                stack.pop(); // Pop the OPEN
                result = processModule(lastButOne, EMPTY_TOKEN, objectModel, context, mapStack, stackSize);
            } else if (lastButOne.hasType(COLON)) {
                Token module = (Token) stack.pop();
                stack.pop(); // Pop the OPEN
                result = processModule(module, expr, objectModel, context, mapStack, stackSize);
            } else {
                result = processVariable(expr, mapStack, stackSize);
            }
            if (stack.empty()) {
                stack.push(result);
            } else {
                last = (Token) stack.peek();
                if (last.hasType(EXPR)) {
                    last.merge(result);
                } else {
                    stack.push(result);
                }
            }
            break;
        case OPEN:
        case COLON:
        case ANCHOR_VAR:
        case THREADSAFE_MODULE:
        case STATEFUL_MODULE:
        case ROOT_SITEMAP_VARIABLE:
        default: {
            stack.push(token);
            break;
        }
        }
    }
    if (stack.size() != 1) {
        throw new PatternException("Evaluation error in expression: " + originalExpr);
    }
    return ((Token) stack.pop()).getStringValue();
}

From source file:org.ebayopensource.turmeric.runtime.config.validation.AbstractVerifier.java

protected String calculateXpathRefish(Element elem) {
    Stack<String> ref = new Stack<String>();
    String name;/*from w ww .jav  a  2  s .  com*/
    Element p, e = elem;
    while (e != null) {
        name = e.getName();
        p = e.getParentElement();
        if (p != null) {
            name = getXmlElementRefName(e, p);
        }
        ref.push(name);
        e = p;
    }
    StringBuilder refish = new StringBuilder();
    refish.append("/");
    while (!ref.empty()) {
        refish.append("/").append(ref.pop());
    }
    return refish.toString();
}

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

public String[] searchPrefix(String prefix) {

    Set<String> results = new HashSet<String>();
    if ((prefix == null) || (prefix.length() < 2))
        return results.toArray(new String[results.size()]);

    char[] letters = prefix.toUpperCase().toCharArray();

    long ptr = nodes[0];

    for (char c : letters) {
        ptr = findChild(ptr, c);/*from   w  w  w .  j  a v  a2  s  .  co m*/
        if (-1 == ptr)
            return results.toArray(new String[results.size()]);
    }

    // iteratively (to prevent stack overflow) search each branch of the graph
    Stack<StackEntry> stack = new Stack<StackEntry>(); // a stack of paths to traverse. This prevents the StackOverflowException.
    stack.push(new StackEntry(ptr, prefix.toUpperCase().toCharArray(), ""));

    while (!stack.empty()) {
        StackEntry entry = stack.pop();

        // if current node is a valid word
        if (canTerminate(entry.node)) {
            results.add(String.valueOf(entry.chars) + entry.subword);
        }

        for (Iterator<Long> iter = childIterator(entry.node); iter.hasNext();) {
            long child = iter.next();
            stack.push(new StackEntry(child, entry.chars, entry.subword + getChar(child)));
        }
    }

    return results.toArray(new String[results.size()]);
}

From source file:de.ingrid.external.gemet.GEMETService.java

@Override
public TreeTerm getHierarchyPathToTop(String url, String termId, Locale locale) {
    String language = getGEMETLanguageFilter(locale);

    // get concept and map to TreeTerm
    JSONObject inConcept = gemetClient.getConceptAsJSON(termId, language);
    // we check on null, cause some concepts are buggy in service !
    // (e.g. concept/15041)
    if (inConcept == null) {
        log.error("Problems fetching " + termId + " we return empty TreeTerm !");
        return new TreeTermImpl();
    }//ww  w .  ja v  a 2s  . co  m

    TreeTerm resultTreeTerm = gemetMapper.mapToTreeTerm(inConcept, null, null);

    // set parents up to top. We only produce ONE PATH, so no multiple
    // parents are set !
    // We process "stack" until stack is empty

    Stack<TreeTerm> parentStack = new Stack<TreeTerm>();
    parentStack.add(resultTreeTerm);

    while (!parentStack.empty()) {
        TreeTerm currentTerm = parentStack.pop();
        if (currentTerm.getParents() == null) {
            // no processed parents yet, add first parent found !
            processParentsOfTerm(currentTerm, language, true);
            // check parents for null, may be top node
            if (currentTerm.getParents() != null) {
                parentStack.addAll(currentTerm.getParents());
            }
        }
    }

    return resultTreeTerm;
}