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:com.inmobi.conduit.distcp.tools.mapred.TestCopyCommitter.java

private boolean checkDirectoryPermissions(FileSystem fs, String targetBase, FsPermission sourcePerm)
        throws IOException {
    Path base = new Path(targetBase);

    Stack<Path> stack = new Stack<Path>();
    stack.push(base);/*from  ww w . jav a2  s  .  c o m*/
    while (!stack.isEmpty()) {
        Path file = stack.pop();
        if (!fs.exists(file))
            continue;
        FileStatus[] fStatus = fs.listStatus(file);
        if (fStatus == null || fStatus.length == 0)
            continue;

        for (FileStatus status : fStatus) {
            if (status.isDir()) {
                stack.push(status.getPath());
                Assert.assertEquals(status.getPermission(), sourcePerm);
            }
        }
    }
    return true;
}

From source file:logicProteinHypernetwork.networkStates.NetworkEntityToMinimalNetworkStates.java

/**
 * Calculates all minimally constrained satisfying models using the tableau
 * algorithm and derives the minimal network states.
 * /*from  ww  w  . j  ava2 s.c  om*/
 * @param e
 *            the network entity
 * @param f
 *            the minimal network state formula
 * @param states
 *            the place where all minimal network states are collected
 */
public void calculateAllTableauPaths(final NetworkEntity e, final Formula<NetworkEntity> f,
        final Collection<MinimalNetworkState> states) {
    f.toNegationNormalForm();
    Stack<Collection<Formula<NetworkEntity>>> blocked = new Stack<Collection<Formula<NetworkEntity>>>();
    blocked.push(new ArrayList<Formula<NetworkEntity>>());
    boolean first = true;
    while (!blocked.isEmpty()) {
        Tableau<NetworkEntity> tableau = new Tableau<NetworkEntity>(tableauRules, propositionComparator, false);
        tableau.setFormula(f);

        Collection<Formula<NetworkEntity>> bs = blocked.pop();
        World start = new World(0, propositionComparator);
        for (Formula<NetworkEntity> b : bs) {
            tableau.block(start, b);
        }

        boolean satisfiable = tableau.proofSearch();
        if (!satisfiable && first) {
            System.err.println("Formula not satisfiable for entity " + e
                    + ". This indicates a circular interaction dependency which is not allowed. Until you fix this, we assume that the entity does not have any competitors or dependencies.");
            MinimalNetworkState mns = new MinimalNetworkState();
            mns.setEntity(e);
            mns.addNecessary(e);
            if (e instanceof Interaction) {
                for (Protein p : ((Interaction) e).getProteins())
                    mns.addNecessary(p);
            }
            states.add(mns);

        }
        if (satisfiable) {
            MinimalNetworkState s = ts.transform(tableau);
            s.setEntity(e);
            states.add(s);

            for (LabelledFormula<NetworkEntity> d : tableau.getDisjunctions()) {
                Formula<NetworkEntity> active = tableau.getActiveDisjunct(d).getFormula();
                int index = active.getParent().indexOf(active);
                if (index != 0) {
                    // find other children that are not yet pre-blocked
                    for (Formula<NetworkEntity> child : d.getFormula()) {
                        LabelledFormula<NetworkEntity> lf = tableau.getLabelledFormula(d.getWorld(), child);
                        if (lf != null) {
                            for (Formula<NetworkEntity> el : lf.getEliminationExplanation()) {
                                if (el.indexOf(
                                        tableau.getActiveDisjunct(tableau.getLabelledFormula(d.getWorld(), el))
                                                .getFormula()) == 0) {
                                    Collection<Formula<NetworkEntity>> bs2 = new ArrayList<Formula<NetworkEntity>>(
                                            bs);
                                    bs2.add(tableau.getActiveDisjunct(d).getFormula());
                                    blocked.push(bs2);
                                }
                            }
                        }
                    }
                }
            }
        }
        first = false;
    }
}

From source file:com.consol.citrus.Citrus.java

/**
 * Method to retrieve the full class name for a test.
 * Hierarchy of folders is supported, too.
 *
 * @param startDir directory where to start the search
 * @param testName test name to search for
 * @throws CitrusRuntimeException/*from w  w  w .  j  a v  a  2s. c  om*/
 * @return the class name of the test
 */
private String getClassNameForTest(final String startDir, final String testName) throws FileNotFoundException {
    /* Stack to hold potential sub directories */
    final Stack<File> dirs = new Stack<File>();
    /* start directory */
    final File startdir = new File(startDir);

    if (startdir.isDirectory()) {
        dirs.push(startdir);
    }

    log.info("Starting test search in dir: " + startdir.getAbsolutePath());

    /* walk through the directories */
    while (dirs.size() > 0) {
        File file = dirs.pop();
        File[] found = file.listFiles(new TestCaseFileNameFilter());

        for (int i = 0; i < found.length; i++) {
            /* Subfolder support */
            if (found[i].isDirectory()) {
                dirs.push(found[i]);
            } else {
                if ((testName + XML_FILE_EXTENSION).equalsIgnoreCase(found[i].getName())) {
                    String fileName = found[i].getPath();
                    fileName = fileName.substring(0, (fileName.length() - XML_FILE_EXTENSION.length()));

                    if (fileName.startsWith(File.separator)) {
                        fileName = fileName.substring(File.separator.length());
                    }

                    //replace operating system path separator and translate to class package string
                    fileName = fileName.substring(
                            startDir.startsWith(File.separator) ? startDir.length() - 1 : startDir.length())
                            .replace(File.separatorChar, '.');

                    if (log.isDebugEnabled()) {
                        log.debug("Found test '" + fileName + "'");
                    }

                    return fileName;
                }
            }
        }
    }

    throw new CitrusRuntimeException(
            "Could not find test with name '" + testName + "'. Test directory is: " + startDir);
}

From source file:com.feilong.commons.core.util.CollectionsUtilTest.java

/**
 * TestCollectionsUtilTest.//from ww w  .jav  a 2s  . c  o  m
 */
@Test
public void testCollectionsUtilTest2() {
    Stack<Object> stack = new Stack<Object>();

    stack.add("1");
    stack.add("2");
    stack.add("3");
    stack.add("4");

    if (log.isDebugEnabled()) {
        log.debug("" + stack.firstElement());
        log.debug("" + stack.peek());
        log.debug("" + stack.pop());
        log.debug(JsonUtil.format(stack));
    }

}

From source file:org.apache.jackrabbit.oak.plugins.segment.file.ReversedLinesFileReaderTestParamFile.java

@Test
public void testDataIntegrityWithBufferedReader() throws URISyntaxException, IOException {
    File testFileIso = createFile(folder.newFile(), data);
    reversedLinesFileReader = new ReversedLinesFileReader(testFileIso, buffSize, encoding);

    Stack<String> lineStack = new Stack<String>();

    bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(testFileIso), encoding));
    String line;// w w w.  j ava  2s  .com

    // read all lines in normal order
    while ((line = bufferedReader.readLine()) != null) {
        lineStack.push(line);
    }

    // read in reverse order and compare with lines from stack
    while ((line = reversedLinesFileReader.readLine()) != null) {
        String lineFromBufferedReader = lineStack.pop();
        assertEquals(lineFromBufferedReader, line);
    }

}

From source file:ome.formats.importer.gui.FileQueueChooser.java

/**
 * Get all JLists and JTables if the LAF uses lists/tables
 * /*  w ww  .  ja v a2 s  .  c o m*/
 * @param fileChooser fileChooser
 * @return fileListObjects
 */
public Component[] getFileListObjects(JFileChooser fileChooser) {
    Vector<Component> v = new Vector<Component>();
    Stack<Component> s = new Stack<Component>();
    s.push(fileChooser);
    while (!s.isEmpty()) {
        Component c = (Component) s.pop();

        if (c instanceof Container) {
            Container d = (Container) c;
            for (int i = 0; i < d.getComponentCount(); i++) {

                if (d.getComponent(i) instanceof JTable) {
                    v.add(d.getComponent(i));
                } else
                    s.push(d.getComponent(i));
            }
        }
    }
    Component[] arr = new Component[v.size()];
    for (int i = 0; i < arr.length; i++)
        arr[i] = v.get(i);

    return arr;
}

From source file:edu.umn.cs.spatialHadoop.core.RectangleNN.java

/**
 * Directly unions the given list of polygons using a safe method that tries
 * to avoid geometry exceptions. First, it tries the buffer(0) method. It it
 * fails, it falls back to the tradition union method.
 * @param polys/*from  w  ww  .  j  a v  a2 s .c o m*/
 * @param progress
 * @return
 * @throws IOException 
 */
public static Geometry safeUnion(List<Geometry> polys, Progressable progress) throws IOException {
    if (polys.size() == 1)
        return polys.get(0);
    Stack<Integer> rangeStarts = new Stack<Integer>();
    Stack<Integer> rangeEnds = new Stack<Integer>();
    rangeStarts.push(0);
    rangeEnds.push(polys.size());
    List<Geometry> results = new ArrayList<Geometry>();

    final GeometryFactory geomFactory = new GeometryFactory();

    // Minimum range size that is broken into two subranges
    final int MinimumThreshold = 10;
    // Progress numerator and denominator
    int progressNum = 0, progressDen = polys.size();

    while (!rangeStarts.isEmpty()) {
        int rangeStart = rangeStarts.pop();
        int rangeEnd = rangeEnds.pop();

        try {
            // Union using the buffer operation
            GeometryCollection rangeInOne = (GeometryCollection) geomFactory
                    .buildGeometry(polys.subList(rangeStart, rangeEnd));
            Geometry rangeUnion = rangeInOne.buffer(0);
            results.add(rangeUnion);
            progressNum += rangeEnd - rangeStart;
        } catch (Exception e) {
            LOG.warn("Exception in merging " + (rangeEnd - rangeStart) + " polygons", e);
            // Fall back to the union operation
            if (rangeEnd - rangeStart < MinimumThreshold) {
                LOG.info("Error in union " + rangeStart + "-" + rangeEnd);
                // Do the union directly using the old method (union)
                Geometry rangeUnion = geomFactory.buildGeometry(new ArrayList<Geometry>());
                for (int i = rangeStart; i < rangeEnd; i++) {
                    LOG.info(polys.get(i).toText());
                }
                for (int i = rangeStart; i < rangeEnd; i++) {
                    try {
                        rangeUnion = rangeUnion.union(polys.get(i));
                    } catch (Exception e1) {
                        // Log the error and skip it to allow the method to finish
                        LOG.error("Error computing union", e);
                    }
                }
                results.add(rangeUnion);
                progressNum += rangeEnd - rangeStart;
            } else {
                // Further break the range into two subranges
                rangeStarts.push(rangeStart);
                rangeEnds.push((rangeStart + rangeEnd) / 2);
                rangeStarts.push((rangeStart + rangeEnd) / 2);
                rangeEnds.push(rangeEnd);
                progressDen++;
            }
        }
        if (progress != null)
            progress.progress(progressNum / (float) progressDen);
    }

    // Finally, union all the results
    Geometry finalResult = results.remove(results.size() - 1);
    while (!results.isEmpty()) {
        try {
            finalResult = finalResult.union(results.remove(results.size() - 1));
        } catch (Exception e) {
            LOG.error("Error in union", e);
        }
        progressNum++;
        progress.progress(progressNum / (float) progressDen);
    }
    return finalResult;
}

From source file:net.iponweb.hadoop.streaming.parquet.TextRecordWriterWrapper.java

@Override
public void write(Text key, Text value) throws IOException {

    Group grp = factory.newGroup();

    String[] strK = key.toString().split(TAB, -1);
    String[] strV = value == null ? new String[0] : value.toString().split(TAB, -1);
    String kv_combined[] = (String[]) ArrayUtils.addAll(strK, strV);

    Iterator<PathAction> ai = recorder.iterator();

    Stack<Group> groupStack = new Stack<>();
    groupStack.push(grp);/*from   w w w .j  a  va 2s .c  om*/
    int i = 0;

    try {
        while (ai.hasNext()) {

            PathAction a = ai.next();
            switch (a.getAction()) {
            case GROUPEND:
                grp = groupStack.pop();
                break;

            case GROUPSTART:
                groupStack.push(grp);
                grp = grp.addGroup(a.getName());
                break;

            case FIELD:
                String s = null;
                PrimitiveType.PrimitiveTypeName primType = a.getType();
                String colName = a.getName();

                if (i < kv_combined.length)
                    s = kv_combined[i++];

                if (s == null) {
                    if (a.getRepetition() == Type.Repetition.OPTIONAL) {
                        i++;
                        continue;
                    }
                    s = primType == PrimitiveType.PrimitiveTypeName.BINARY ? "" : "0";
                }

                // If we have 'repeated' field, assume that we should expect JSON-encoded array
                // Convert array and append all values
                int repetition = 1;
                boolean repeated = false;
                ArrayList<String> s_vals = null;
                if (a.getRepetition() == Type.Repetition.REPEATED) {
                    repeated = true;
                    s_vals = new ArrayList<>();
                    ObjectMapper mapper = new ObjectMapper();
                    JsonNode node = mapper.readTree(s);
                    Iterator<JsonNode> itr = node.iterator();
                    repetition = 0;
                    while (itr.hasNext()) {

                        String o;
                        switch (primType) {
                        case BINARY:
                            o = itr.next().getTextValue(); // No array-of-objects!
                            break;
                        case BOOLEAN:
                            o = String.valueOf(itr.next().getBooleanValue());
                            break;
                        default:
                            o = String.valueOf(itr.next().getNumberValue());
                        }

                        s_vals.add(o);
                        repetition++;
                    }
                }

                for (int j = 0; j < repetition; j++) {

                    if (repeated)
                        // extract new s
                        s = s_vals.get(j);

                    try {
                        switch (primType) {

                        case INT32:
                            grp.append(colName, new Double(Double.parseDouble(s)).intValue());
                            break;
                        case INT64:
                        case INT96:
                            grp.append(colName, new Double(Double.parseDouble(s)).longValue());
                            break;
                        case DOUBLE:
                            grp.append(colName, Double.parseDouble(s));
                            break;
                        case FLOAT:
                            grp.append(colName, Float.parseFloat(s));
                            break;
                        case BOOLEAN:
                            grp.append(colName, s.equalsIgnoreCase("true") || s.equals("1"));
                            break;
                        case BINARY:
                            grp.append(colName, Binary.fromString(s));
                            break;
                        default:
                            throw new RuntimeException("Can't handle type " + primType);
                        }
                    } catch (NumberFormatException e) {

                        grp.append(colName, 0);
                    }
                }
            }
        }

        realWriter.write(null, (SimpleGroup) grp);

    } catch (InterruptedException e) {
        Thread.interrupted();
        throw new IOException(e);
    } catch (Exception e) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        e.printStackTrace(new PrintStream(out));
        throw new RuntimeException("Failed on record " + grp + ", schema=" + schema + ", path action="
                + recorder + " exception = " + e.getClass() + ", msg=" + e.getMessage() + ", cause="
                + e.getCause() + ", trace=" + out.toString());
    }

}

From source file:net.bulletin.pdi.xero.step.support.XMLChunkerImpl.java

@Override
public String pullNextXmlChunk() throws KettleException {
    Stack<String> elementStack = xmlChunkerState.getElementStack();
    XMLStreamReader xmlStreamReader = xmlChunkerState.getXmlStreamReader();

    try {/*w w w  .ja  v  a  2  s . c  o  m*/

        while (xmlStreamReader.hasNext()) {

            switch (xmlStreamReader.next()) {

            case XMLStreamConstants.END_DOCUMENT:
                return null;

            case XMLStreamConstants.END_ELEMENT:
                elementStack.pop();
                break;

            case XMLStreamConstants.START_ELEMENT:
                elementStack.push(xmlStreamReader.getLocalName());

                if (actualElementStackHasExpectedElements(xmlChunkerState)) {
                    return pullNextXmlChunkFromTopElementOnStack(xmlChunkerState);
                }

                break;

            }

        }
    } catch (Exception e) {
        throw new KettleException("a problem has arisen reading the xero xml stream", e);
    }

    return null;
}

From source file:com.datastax.hectorjpa.spring.ConsistencyLevelAspect.java

/**
 * Validates any method that has the valid annotation on it and is wired as
 * a spring service/*w w w .j a va2s . c  o m*/
 * 
 * @param jp
 * @throws Throwable
 */
@Around("@annotation(com.datastax.hectorjpa.spring.Consistency)")
public Object setConsistency(ProceedingJoinPoint pjp) throws Throwable {

    logger.debug("Invoking before advice for @Consistency annotation.  Target object is {} on method {}",
            pjp.getTarget(), pjp.getSignature());

    MethodSignature sig = (MethodSignature) pjp.getSignature();

    Object[] args = pjp.getArgs();

    Method signatureMethod = sig.getMethod();

    Class<?>[] signatureTypes = signatureMethod.getParameterTypes();

    // we do this because we want to get the best match from the child
    // classes
    Class<?>[] runtimeArgs = new Class<?>[signatureTypes.length];

    for (int i = 0; i < signatureTypes.length; i++) {

        if (args[i] != null) {
            runtimeArgs[i] = args[i].getClass();
        } else {
            runtimeArgs[i] = signatureTypes[i];
        }
    }

    Class<?> runtimeClass = pjp.getTarget().getClass();

    // check if this is annotated, if not proceed and execute it

    HConsistencyLevel level = consistency(runtimeClass, signatureMethod.getName(), runtimeArgs);

    if (level == null) {
        return pjp.proceed(args);
    }

    Stack<HConsistencyLevel> stack = threadStack.get();

    stack.push(level);
    JPAConsistency.set(level);

    Object result = null;

    try {
        result = pjp.proceed(args);
    } finally {
        stack.pop();

        if (stack.size() > 0) {
            JPAConsistency.set(stack.peek());
        } else {
            JPAConsistency.remove();
        }

    }

    return result;
}