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: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.jav a 2  s . c o 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:com.webcohesion.ofx4j.io.nanoxml.TestNanoXMLOFXReader.java

/**
 * tests whitespace before and after// w w w.  j  a v a2 s. co  m
 */
public void testWhitespaceBeforeAndAfter() throws Exception {
    NanoXMLOFXReader reader = new NanoXMLOFXReader();
    final Map<String, List<String>> headers = new HashMap<String, List<String>>();
    final Stack<Map<String, List<Object>>> aggregateStack = new Stack<Map<String, List<Object>>>();
    TreeMap<String, List<Object>> root = new TreeMap<String, List<Object>>();
    aggregateStack.push(root);

    reader.setContentHandler(getNewDefaultHandler(headers, aggregateStack));
    reader.parse(TestNanoXMLOFXReader.class.getResourceAsStream("whitespace-example.ofx"));
    assertEquals(9, headers.size());
    assertEquals(1, aggregateStack.size());
    assertSame(root, aggregateStack.pop());

    TreeMap<String, List<Object>> OFX = (TreeMap<String, List<Object>>) root.remove("OFX").get(0);
    assertNotNull(OFX);
    assertEquals("E", OFX.remove("S").get(0));
    assertTrue(OFX.isEmpty());
    assertTrue(root.isEmpty());
}

From source file:com.webcohesion.ofx4j.io.nanoxml.TestNanoXMLOFXReader.java

/**
 * tests using sax to parse an OFX doc.//from  ww  w.j  a  va  2s. co  m
 */
public void testSimpleVersion1() throws Exception {
    NanoXMLOFXReader reader = new NanoXMLOFXReader();
    final Map<String, List<String>> headers = new HashMap<String, List<String>>();
    final Stack<Map<String, List<Object>>> aggregateStack = new Stack<Map<String, List<Object>>>();
    TreeMap<String, List<Object>> root = new TreeMap<String, List<Object>>();
    aggregateStack.push(root);

    reader.setContentHandler(getNewDefaultHandler(headers, aggregateStack));
    reader.parse(TestNanoXMLOFXReader.class.getResourceAsStream("simple.ofx"));
    assertEquals(9, headers.size());
    assertEquals(1, aggregateStack.size());
    assertSame(root, aggregateStack.pop());

    TreeMap<String, List<Object>> OFX = (TreeMap<String, List<Object>>) root.remove("OFX").get(0);
    assertNotNull(OFX);
    TreeMap<String, List<Object>> SIGNONMSGSRSV1 = (TreeMap<String, List<Object>>) OFX.remove("SIGNONMSGSRSV1")
            .get(0);
    assertNotNull(SIGNONMSGSRSV1);
    TreeMap<String, List<Object>> SONRS = (TreeMap<String, List<Object>>) SIGNONMSGSRSV1.remove("SONRS").get(0);
    assertNotNull(SONRS);
    TreeMap<String, List<Object>> STATUS = (TreeMap<String, List<Object>>) SONRS.remove("STATUS").get(0);
    assertNotNull(STATUS);
    assertEquals("0", STATUS.remove("CODE").get(0).toString().trim());
    assertEquals("INFO", STATUS.remove("SEVERITY").get(0).toString().trim());
    assertTrue(STATUS.isEmpty());
    assertEquals("20071015021529.000[-8:PST]", SONRS.remove("DTSERVER").get(0).toString().trim());
    assertEquals("ENG", SONRS.remove("LANGUAGE").get(0).toString().trim());
    assertEquals("19900101000000", SONRS.remove("DTACCTUP").get(0).toString().trim());
    assertTrue(SONRS.isEmpty());
    assertTrue(SIGNONMSGSRSV1.isEmpty());
    assertTrue(OFX.isEmpty());
    assertTrue(root.isEmpty());
}

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();
    }//from   w  w  w.j  a v  a 2s  .c om

    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;
}

From source file:com.webcohesion.ofx4j.io.nanoxml.TestNanoXMLOFXReader.java

/**
 * tests for closing tags in v1/*  www.j a v a 2  s  .co m*/
 */
public void testClosingTagsVersion1() throws Exception {
    NanoXMLOFXReader reader = new NanoXMLOFXReader();
    final Map<String, List<String>> headers = new HashMap<String, List<String>>();
    final Stack<Map<String, List<Object>>> aggregateStack = new Stack<Map<String, List<Object>>>();
    TreeMap<String, List<Object>> root = new TreeMap<String, List<Object>>();
    aggregateStack.push(root);

    reader.setContentHandler(getNewDefaultHandler(headers, aggregateStack));
    reader.parse(TestNanoXMLOFXReader.class.getResourceAsStream("closing-tags.ofx"));
    assertEquals(9, headers.size());
    assertEquals(1, aggregateStack.size());
    assertSame(root, aggregateStack.pop());

    TreeMap<String, List<Object>> OFX = (TreeMap<String, List<Object>>) root.remove("OFX").get(0);
    assertNotNull(OFX);
    TreeMap<String, List<Object>> SIGNONMSGSRSV1 = (TreeMap<String, List<Object>>) OFX.remove("SIGNONMSGSRSV1")
            .get(0);
    assertNotNull(SIGNONMSGSRSV1);
    TreeMap<String, List<Object>> SONRS = (TreeMap<String, List<Object>>) SIGNONMSGSRSV1.remove("SONRS").get(0);
    assertNotNull(SONRS);
    TreeMap<String, List<Object>> STATUS = (TreeMap<String, List<Object>>) SONRS.remove("STATUS").get(0);
    assertNotNull(STATUS);
    TreeMap<String, List<Object>> FI = (TreeMap<String, List<Object>>) SONRS.remove("FI").get(0);
    assertNotNull(FI);
    assertEquals("0", STATUS.remove("CODE").get(0).toString().trim());
    assertEquals("INFO", STATUS.remove("SEVERITY").get(0).toString().trim());
    assertTrue(STATUS.isEmpty());
    assertEquals("20100717152132", SONRS.remove("DTSERVER").get(0).toString().trim());
    assertEquals("ENG", SONRS.remove("LANGUAGE").get(0).toString().trim());
    assertEquals("ameritrade.com", FI.remove("ORG").get(0).toString().trim());
    assertTrue(SONRS.isEmpty());
    assertTrue(SIGNONMSGSRSV1.isEmpty());
    assertTrue(OFX.isEmpty());
    assertTrue(root.isEmpty());
}

From source file:it.cnr.icar.eric.server.security.authorization.RegistryAttributeFinderModule.java

/**
 * Handles attributes as defined ebRIM for Any RegistryObject.
 * Used by subject, resource and action attributes handling methods.
 *//*from  w  w w.j a v  a2s . co  m*/
EvaluationResult handleRegistryObjectAttribute(Object obj, Stack<?> attributeStack, URI type,
        EvaluationCtx context) {
    EvaluationResult evaluationResult = null;
    try {
        String attr = (String) attributeStack.pop();
        ServerRequestContext requestContext = AuthorizationServiceImpl.getRequestContext(context);
        log.trace("handleRegistryObjectAttribute: obj=" + obj.toString() + " attrubute = " + attr);

        if (requestContext != null && obj != null) {
            @SuppressWarnings("unused")
            RegistryRequestType registryRequest = requestContext.getCurrentRegistryRequest();

            //Now invoke a get method to get the value for attribute being sought
            Class<? extends Object> clazz = obj.getClass();
            @SuppressWarnings("unused")
            String clazzName = clazz.getName();
            PropertyDescriptor propDesc = new PropertyDescriptor(attr, clazz, getReadMethodName(attr), null);
            Method method = propDesc.getReadMethod();
            Object attrValObj = method.invoke(obj, (java.lang.Object[]) null);

            if (attrValObj instanceof Collection) {
                HashSet<AttributeValue> attrValueObjectIds = new HashSet<AttributeValue>();
                Iterator<?> iter = ((Collection<?>) attrValObj).iterator();
                while (iter.hasNext()) {
                    //??Dangerous assumption that Collection is a Collection of IdentifiableTypes
                    String attrValueObjectId = ((IdentifiableType) iter.next()).getId();
                    attrValueObjectIds.add(makeAttribute(attrValueObjectId, type));
                }
                evaluationResult = makeBag(attrValueObjectIds, type);
            } else {
                //See if more pointer chasing needs to be done or (!attributeStack.empty()) 
                if (!attributeStack.empty()) {
                    String id = (String) attrValObj;
                    RegistryObjectType ro = AuthorizationServiceImpl.getInstance()
                            .getRegistryObject(requestContext, id, false);
                    if (ro == null) {
                        throw new ObjectNotFoundException(id, "RegistryObject");
                    }
                    evaluationResult = handleRegistryObjectAttribute(ro, attributeStack, type, context);
                } else {
                    AttributeValue attrVal = makeAttribute(attrValObj, type);
                    evaluationResult = makeBag(attrVal, type);
                }
            }
        }
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (IntrospectionException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (ParsingException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (RegistryException e) {
        e.printStackTrace();
    }

    return evaluationResult;
}

From source file:com.mirth.connect.connectors.file.FileReceiver.java

private FileInfo[] listFilesRecursively(Set<String> visitedDirectories, Stack<String> directoryStack)
        throws Exception {
    while (!directoryStack.isEmpty()) {
        // Get the current directory
        String fromDir = directoryStack.pop();

        if (!visitedDirectories.contains(fromDir)) {
            visitedDirectories.add(fromDir);

            // Add any subdirectories to the stack
            List<String> directories = listDirectories(fromDir);

            for (int i = directories.size() - 1; i >= 0; i--) {
                directoryStack.push(directories.get(i));
            }/* www  .  j  a va2s.  com*/

            // Return the files from the current directory
            return listFiles(fromDir);
        }
    }

    return null;
}

From source file:com.schibsted.triathlon.operators.GroupByOperatorTest.java

@Test
public void testDeployTwoDataCentersOddNumberOfInstances() throws Exception {
    initializeInstanceInfos(2);/*from ww  w .  j ava  2  s . c o m*/

    List<String> constraint = new ArrayList<String>() {
        {
            add("datacenter");
            add("GROUP_BY");
        }
    };
    TriathlonService triathlonService = new TriathlonServiceImpl();

    String content = IOUtils.toString(this.getClass().getResourceAsStream("group_by_operator_1.json"), "UTF-8");

    ByteBuf buffer = Unpooled.copiedBuffer(content.getBytes());

    Marathon appDefinition = triathlonService.parseJson(Observable.just(buffer)).toBlocking().toFuture().get();
    appDefinition.setInstances(5);

    ConstraintModel constraintModel = ConstraintModel.createConstraintModel(constraint);

    Operator cluster = new GroupByOperator(triathlonService, constraintModel);

    Operator spyCluster = Mockito.spy(cluster);
    doReturn(Observable.just(Unpooled.wrappedBuffer("TEST".getBytes()))).when(spyCluster)
            .getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString());

    Stack<Integer> values = new Stack<>();
    values.push(2);
    values.push(3);

    when(spyCluster.getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString()))
            .thenAnswer(invocation -> {
                Object[] args = invocation.getArguments();
                Observable<ByteBuf> val = Observable
                        .just(Unpooled.wrappedBuffer(((String) args[1]).getBytes()));
                Marathon appDef = triathlonService.parseJson(val).toBlocking().toFuture().get();
                Integer v = values.pop();
                assertEquals(v, appDef.getInstances());
                return val;
            });

    spyCluster.apply(appDefinition).subscribe();
    verify(spyCluster, times(2)).getMarathonCommand(Mockito.any(InstanceInfo.class), Mockito.anyString());
}

From source file:com.marklogic.dom.NodeImpl.java

protected NodeList getElementsByTagNameNSOrNodeName(String namespaceURI, String name, final boolean nodeName) {

    final String tagname = name;
    final String ns = namespaceURI;
    final Node thisNode = this;

    return new NodeList() {
        protected ArrayList<Node> elementList = new ArrayList<Node>();
        protected boolean done = false;

        protected void init() {
            if (done)
                return;
            Stack<Node> childrenStack = new Stack<Node>();
            childrenStack.push(thisNode);
            boolean root = true;
            while (!childrenStack.isEmpty()) {
                Node curr = childrenStack.pop();
                NodeList children = curr.getChildNodes();
                for (int childi = children.getLength() - 1; childi >= 0; childi--)
                    if (children.item(childi).getNodeType() == Node.ELEMENT_NODE)
                        childrenStack.push(children.item(childi));
                if (root) {
                    root = false;//from w w  w  . ja  v  a  2  s  .c  om
                    continue;
                }
                if (nodeName) {
                    if (curr.getNodeName().equals(tagname) || tagname.equals("*"))
                        elementList.add(curr);
                } else {
                    // do nothing if only one of the two is null
                    if ("*".equals(ns) && "*".equals(tagname)) {
                        elementList.add(curr);
                        continue;
                    }
                    if (ns != null) {
                        if ((ns.equals("*") || ns.equals(curr.getNamespaceURI()))
                                && (tagname.equals("*") || tagname.equals(curr.getLocalName())))
                            elementList.add(curr);
                    } else if (tagname.equals("*") || tagname.equals(curr.getLocalName()))
                        elementList.add(curr);
                }
            }
            done = true;
        }

        public int getLength() {
            init();
            return elementList.size();
        }

        public Node item(int index) {
            init();
            return (index < getLength()) ? elementList.get(index) : null;
        }

    };
}

From source file:com.ephesoft.dcma.util.FileUtils.java

/**
 * List the contents of directory.//from   w  w  w. jav  a2s.  c  o  m
 * @param directory {@link File}
 * @param includingDirectory boolean
 * @return List<String> 
 * @throws IOException in case of error
 */
public static List<String> listDirectory(File directory, boolean includingDirectory) throws IOException {

    Stack<String> stack = new Stack<String>();
    List<String> list = new ArrayList<String>();

    // If it's a file, just return itself
    if (directory.isFile()) {
        if (directory.canRead()) {
            list.add(directory.getName());
        }
    } else {

        // Traverse the directory in width-first manner, no-recursively
        String root = directory.getParent();
        stack.push(directory.getName());
        while (!stack.empty()) {
            String current = (String) stack.pop();
            File curDir = new File(root, current);
            String[] fileList = curDir.list();
            if (fileList != null) {
                for (String entry : fileList) {
                    File file = new File(curDir, entry);
                    if (file.isFile()) {
                        if (file.canRead()) {
                            list.add(current + File.separator + entry);
                        } else {
                            throw new IOException("Can't read file: " + file.getPath());
                        }
                    } else if (file.isDirectory()) {
                        if (includingDirectory) {
                            list.add(current + File.separator + entry);
                        }
                        stack.push(current + File.separator + file.getName());
                    } else {
                        throw new IOException("Unknown entry: " + file.getPath());
                    }
                }
            }
        }
    }
    return list;
}