Example usage for java.util Stack pop

List of usage examples for java.util Stack pop

Introduction

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

Prototype

public synchronized E pop() 

Source Link

Document

Removes the object at the top of this stack and returns that object as the value of this function.

Usage

From source file:geva.Mapper.GEGrammar.java

String generateNameFromTree(DerivationTree tree) {
    StringBuilder builder = new StringBuilder();
    Stack<DerivationNode> nodeStack = new Stack<DerivationNode>();
    nodeStack.push((DerivationNode) tree.getRoot());
    while (nodeStack.empty() == false) {
        DerivationNode nodes = nodeStack.pop();
        if (nodes != null) {
            if (nodes.getCodonIndex() != -1) {
                builder.append(nodes.getCodonPick());
            }//from ww  w . jav  a  2  s .  c  o  m
            if (nodes.size() != 0) {
                builder.append('[');
                nodeStack.push(null);
                for (int i = nodes.size(); i > 0; i--) {
                    nodeStack.push((DerivationNode) nodes.get(i - 1));
                }
            }
        } else {
            builder.append(']');
        }
    }
    return builder.toString();
}

From source file:org.apache.sling.resourceresolver.impl.CommonResourceResolverFactoryImpl.java

/**
 * @see org.apache.sling.api.resource.ResourceResolverFactory#getThreadResourceResolver()
 *//* www . j a va  2 s.  c o m*/
@Override
public ResourceResolver getThreadResourceResolver() {
    if (!isActive.get()) {
        return null;
    }

    ResourceResolver result = null;
    final Stack<WeakReference<ResourceResolver>> resolverStack = resolverStackHolder.get();
    if (resolverStack != null) {
        while (result == null && !resolverStack.isEmpty()) {
            result = resolverStack.peek().get();
            if (result == null) {
                resolverStack.pop();
            }
        }
    }
    return result;
}

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

/**
 * {@inheritDoc}// w  w w . j a  v  a 2 s  .c  om
 * 
 * @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:org.apache.hadoop.tools.DistCpV1.java

/**
 * Delete the dst files/dirs which do not exist in src
 * /*  ww  w.jav a 2 s  .c  om*/
 * @return total count of files and directories deleted from destination
 * @throws IOException
 */
static private long deleteNonexisting(FileSystem dstfs, FileStatus dstroot, Path dstsorted, FileSystem jobfs,
        Path jobdir, JobConf jobconf, Configuration conf) throws IOException {
    if (dstroot.isFile()) {
        throw new IOException("dst must be a directory when option " + Options.DELETE.cmd
                + " is set, but dst (= " + dstroot.getPath() + ") is not a directory.");
    }

    //write dst lsr results
    final Path dstlsr = new Path(jobdir, "_distcp_dst_lsr");
    try (final SequenceFile.Writer writer = SequenceFile.createWriter(jobconf, Writer.file(dstlsr),
            Writer.keyClass(Text.class), Writer.valueClass(NullWritable.class),
            Writer.compression(SequenceFile.CompressionType.NONE))) {
        //do lsr to get all file statuses in dstroot
        final Stack<FileStatus> lsrstack = new Stack<FileStatus>();
        for (lsrstack.push(dstroot); !lsrstack.isEmpty();) {
            final FileStatus status = lsrstack.pop();
            if (status.isDirectory()) {
                for (FileStatus child : dstfs.listStatus(status.getPath())) {
                    String relative = makeRelative(dstroot.getPath(), child.getPath());
                    writer.append(new Text(relative), NullWritable.get());
                    lsrstack.push(child);
                }
            }
        }
    }

    //sort lsr results
    final Path sortedlsr = new Path(jobdir, "_distcp_dst_lsr_sorted");
    SequenceFile.Sorter sorter = new SequenceFile.Sorter(jobfs, new Text.Comparator(), Text.class,
            NullWritable.class, jobconf);
    sorter.sort(dstlsr, sortedlsr);

    //compare lsr list and dst list  
    long deletedPathsCount = 0;
    try (SequenceFile.Reader lsrin = new SequenceFile.Reader(jobconf, Reader.file(sortedlsr));
            SequenceFile.Reader dstin = new SequenceFile.Reader(jobconf, Reader.file(dstsorted))) {
        //compare sorted lsr list and sorted dst list
        final Text lsrpath = new Text();
        final Text dstpath = new Text();
        final Text dstfrom = new Text();
        final Trash trash = new Trash(dstfs, conf);
        Path lastpath = null;

        boolean hasnext = dstin.next(dstpath, dstfrom);
        while (lsrin.next(lsrpath, NullWritable.get())) {
            int dst_cmp_lsr = dstpath.compareTo(lsrpath);
            while (hasnext && dst_cmp_lsr < 0) {
                hasnext = dstin.next(dstpath, dstfrom);
                dst_cmp_lsr = dstpath.compareTo(lsrpath);
            }

            if (dst_cmp_lsr == 0) {
                //lsrpath exists in dst, skip it
                hasnext = dstin.next(dstpath, dstfrom);
            } else {
                //lsrpath does not exist, delete it
                final Path rmpath = new Path(dstroot.getPath(), lsrpath.toString());
                ++deletedPathsCount;
                if ((lastpath == null || !isAncestorPath(lastpath, rmpath))) {
                    if (!(trash.moveToTrash(rmpath) || dstfs.delete(rmpath, true))) {
                        throw new IOException("Failed to delete " + rmpath);
                    }
                    lastpath = rmpath;
                }
            }
        }
    }
    return deletedPathsCount;
}

From source file:fr.paris.lutece.plugins.upload.web.UploadJspBean.java

/**
 * Deletes a directory recursively.//from  w w  w  .  j a v  a2 s . co m
 *
 * @param directory The directory to delete
 */
private static void deleteDirectory(File directory) {
    // We use a Stack (LIFO) to keep track of the directories to delete
    Stack<File> dirsToDelete = new Stack<File>();

    // The stack is initialized with the main directory
    dirsToDelete.push(directory);

    // Loop until all directories have been deleted
    while (!dirsToDelete.empty()) {
        // Look at the directory on top of the stack (don't remove it!)
        File currentDir = (File) dirsToDelete.peek();

        // Are there any subdirectories?
        File[] subDirs = currentDir.listFiles(dirFilter);

        if (subDirs.length > 0) {
            // If so, add them to the stack
            for (int i = 0; i < subDirs.length; i++) {
                dirsToDelete.push(subDirs[i]);
            }
        } else {
            // If not, delete all files in the directory
            File[] files = currentDir.listFiles(fileFilter);

            for (int i = 0; i < files.length; i++) {
                files[i].delete();
            }

            // Then delete the directory
            currentDir.delete();

            // Then remove the directory from the stack
            dirsToDelete.pop();
        }
    }
}

From source file:FilenameUtils.java

/**
 * Checks a filename to see if it matches the specified wildcard matcher
 * allowing control over case-sensitivity.
 * <p>//from www.  ja  va  2s. c o  m
 * The wildcard matcher uses the characters '?' and '*' to represent a
 * single or multiple wildcard characters.
 * 
 * @param filename  the filename to match on
 * @param wildcardMatcher  the wildcard string to match against
 * @param caseSensitivity  what case sensitivity rule to use, null means case-sensitive
 * @return true if the filename matches the wilcard string
 * @since Commons IO 1.3
 */
public static boolean wildcardMatch(String filename, String wildcardMatcher, IOCase caseSensitivity) {
    if (filename == null && wildcardMatcher == null) {
        return true;
    }
    if (filename == null || wildcardMatcher == null) {
        return false;
    }
    if (caseSensitivity == null) {
        caseSensitivity = IOCase.SENSITIVE;
    }
    filename = caseSensitivity.convertCase(filename);
    wildcardMatcher = caseSensitivity.convertCase(wildcardMatcher);
    String[] wcs = splitOnTokens(wildcardMatcher);
    boolean anyChars = false;
    int textIdx = 0;
    int wcsIdx = 0;
    Stack backtrack = new Stack();

    // loop around a backtrack stack, to handle complex * matching
    do {
        if (backtrack.size() > 0) {
            int[] array = (int[]) backtrack.pop();
            wcsIdx = array[0];
            textIdx = array[1];
            anyChars = true;
        }

        // loop whilst tokens and text left to process
        while (wcsIdx < wcs.length) {

            if (wcs[wcsIdx].equals("?")) {
                // ? so move to next text char
                textIdx++;
                anyChars = false;

            } else if (wcs[wcsIdx].equals("*")) {
                // set any chars status
                anyChars = true;
                if (wcsIdx == wcs.length - 1) {
                    textIdx = filename.length();
                }

            } else {
                // matching text token
                if (anyChars) {
                    // any chars then try to locate text token
                    textIdx = filename.indexOf(wcs[wcsIdx], textIdx);
                    if (textIdx == -1) {
                        // token not found
                        break;
                    }
                    int repeat = filename.indexOf(wcs[wcsIdx], textIdx + 1);
                    if (repeat >= 0) {
                        backtrack.push(new int[] { wcsIdx, repeat });
                    }
                } else {
                    // matching from current position
                    if (!filename.startsWith(wcs[wcsIdx], textIdx)) {
                        // couldnt match token
                        break;
                    }
                }

                // matched text token, move text index to end of matched token
                textIdx += wcs[wcsIdx].length();
                anyChars = false;
            }

            wcsIdx++;
        }

        // full match
        if (wcsIdx == wcs.length && textIdx == filename.length()) {
            return true;
        }

    } while (backtrack.size() > 0);

    return false;
}

From source file:csns.importer.parser.csula.RosterParserImpl.java

/**
 * This parser handles the format under Self Service -> Faculty Center -> My
 * Schedule on GET. A sample record is as follows:
 * "Doe,John M 302043188 3.00 Engr, Comp Sci, & Tech  CS MS". Again, not all
 * fields may be present.//from   ww w  .  j  a  va 2 s.  c o  m
 */
private List<ImportedUser> parse2(String text) {
    List<ImportedUser> students = new ArrayList<ImportedUser>();
    Stack<String> stack = new Stack<String>();

    Scanner scanner = new Scanner(text);
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    while (scanner.hasNext()) {
        String name = "";
        do {
            String token = scanner.next();
            if (!isName(token))
                stack.push(token);
            else {
                name = token;
                while (!stack.isEmpty() && !isDegree(stack.peek()))
                    name = stack.pop() + " " + name;
                break;
            }
        } while (scanner.hasNext());

        String cin = "";
        boolean cinFound = false;
        while (scanner.hasNext()) {
            cin = scanner.next();
            if (isCin(cin)) {
                cinFound = true;
                break;
            } else
                name += " " + cin;
        }

        if (cinFound) {
            ImportedUser student = new ImportedUser();
            student.setCin(cin);
            student.setName(name);
            students.add(student);
        }
    }
    scanner.close();

    return students;
}

From source file:com.qq.tars.maven.gensrc.TarsBuildMojo.java

private void collect(final DependencyNode root, final Set<Artifact> artifacts) {
    Stack<DependencyNode> stack = new Stack<DependencyNode>();
    stack.push(root);/*from w w  w .  j  ava  2  s . com*/
    while (!stack.isEmpty()) {
        DependencyNode node = stack.pop();
        if (node.getState() == DependencyNode.INCLUDED) {
            final Artifact artifact = node.getArtifact();
            if (includedScope(artifact.getScope())) {
                getLog().info("Adding Artefact: " + artifact.toString());
                artifacts.add(artifact);
                // check children 
                if (!node.getChildren().isEmpty()) {
                    stack.addAll(node.getChildren());
                }
            }
        }
    }
}

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.j  av 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.myfaces.custom.fisheye.HtmlFishEyeNavigationMenuRenderer.java

/**
 * @see javax.faces.render.Renderer#encodeEnd(javax.faces.context.FacesContext,
 *      javax.faces.component.UIComponent)
 *//*from  w  w w.ja v  a 2 s.c o m*/
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
    if (component.isRendered()) {
        ResponseWriter writer = context.getResponseWriter();
        Stack menuStack = getChildsMenuStack(context, component);
        String jsMenuVar = DojoUtils.calculateWidgetVarName(component.getClientId(context));

        writer.startElement(HTML.SCRIPT_ELEM, component);
        writer.writeAttribute(HTML.TYPE_ATTR, HTML.SCRIPT_TYPE_TEXT_JAVASCRIPT, null);
        while (!menuStack.isEmpty()) {
            String item = (String) menuStack.pop();
            writer.write(jsMenuVar);
            writer.write(".addChild(");
            writer.write(item);
            writer.write(");\n");
        }
        writer.write(jsMenuVar + ".postCreate(['programmaticdone'],null);\n");
        writer.endElement(HTML.SCRIPT_ELEM);
    }
}