List of usage examples for java.util Stack Stack
public Stack()
From source file:Main.java
/** * Sorts objects in the given collection into different types by Class. * @param <E> the element type//from www. j a v a 2 s . c o m * @param objects a Collection of objects * @param inherit if true, objects are put into all their class's superclasses as well, except * Object - the original Collection can be used in that case * @return a Map from Class to List of objects in that class */ public static <E> Map<Class<?>, List<E>> groupByClass(Collection<E> objects, boolean inherit) { Map<Class<?>, List<E>> retval = new HashMap<Class<?>, List<E>>(); for (E o : objects) { Class<?> c = o.getClass(); if (inherit) { Set<Class<?>> done = new HashSet<Class<?>>(); done.add(Object.class); Stack<Class<?>> todo = new Stack<Class<?>>(); todo.push(c); while (!todo.empty()) { c = todo.pop(); if ((c != null) && !done.contains(c)) { done.add(c); List<E> l = retval.get(c); if (l == null) { l = new ArrayList<E>(); retval.put(c, l); } l.add(o); todo.push(c.getSuperclass()); Class<?>[] classes = c.getInterfaces(); for (int i = 0; i < classes.length; i++) { todo.push(classes[i]); } } } } else { List<E> l = retval.get(c); if (l == null) { l = new ArrayList<E>(); retval.put(c, l); } l.add(o); } } return retval; }
From source file:Main.java
/** * Find element./*from w w w . j a v a 2 s. c o m*/ * * @param topElm * the top elm * @param localName * the local name * @param namespace * the namespace * @return the element */ public static Element findElement(Element topElm, String localName, String namespace) { Stack<Element> stack = new Stack<Element>(); stack.push(topElm); while (!stack.isEmpty()) { Element curElm = stack.pop(); if ((curElm.getLocalName().equals(localName)) && (namespacesAreSame(curElm.getNamespaceURI(), namespace))) { return curElm; } NodeList childNodes = curElm.getChildNodes(); for (int i = 0, ll = childNodes.getLength(); i < ll; i++) { Node item = childNodes.item(i); if (item.getNodeType() == Node.ELEMENT_NODE) { stack.push((Element) item); } } } return null; }
From source file:com.linkedin.urls.PathNormalizer.java
License:asdf
/** * 1. Replaces "/./" with "/" recursively. * 2. "/blah/asdf/.." -> "/blah"/*w ww .j av a 2 s .c o m*/ * 3. "/blah/blah2/blah3/../../blah4" -> "/blah/blah4" * 4. "//" -> "/" * 5. Adds a slash at the end if there isn't one */ private static String sanitizeDotsAndSlashes(String path) { StringBuilder stringBuilder = new StringBuilder(path); Stack<Integer> slashIndexStack = new Stack<Integer>(); int index = 0; while (index < stringBuilder.length() - 1) { if (stringBuilder.charAt(index) == '/') { slashIndexStack.add(index); if (stringBuilder.charAt(index + 1) == '.') { if (index < stringBuilder.length() - 2 && stringBuilder.charAt(index + 2) == '.') { //If it looks like "/../" or ends with "/.." if (index < stringBuilder.length() - 3 && stringBuilder.charAt(index + 3) == '/' || index == stringBuilder.length() - 3) { boolean endOfPath = index == stringBuilder.length() - 3; slashIndexStack.pop(); int endIndex = index + 3; // backtrack so we can detect if this / is part of another replacement index = slashIndexStack.empty() ? -1 : slashIndexStack.pop() - 1; int startIndex = endOfPath ? index + 1 : index; stringBuilder.delete(startIndex + 1, endIndex); } } else if (index < stringBuilder.length() - 2 && stringBuilder.charAt(index + 2) == '/' || index == stringBuilder.length() - 2) { boolean endOfPath = index == stringBuilder.length() - 2; slashIndexStack.pop(); int startIndex = endOfPath ? index + 1 : index; stringBuilder.delete(startIndex, index + 2); // "/./" -> "/" index--; // backtrack so we can detect if this / is part of another replacement } } else if (stringBuilder.charAt(index + 1) == '/') { slashIndexStack.pop(); stringBuilder.deleteCharAt(index); index--; } } index++; } if (stringBuilder.length() == 0) { stringBuilder.append("/"); //Every path has at least a slash } return stringBuilder.toString(); }
From source file:com.netflix.spinnaker.clouddriver.appengine.artifacts.StorageUtils.java
public static void untarStreamToPath(InputStream inputStream, String basePath) throws IOException { class DirectoryTimestamp { public DirectoryTimestamp(File d, long m) { directory = d;/*from ww w .ja v a 2 s .co m*/ millis = m; } public File directory; public long millis; } ; // Directories come in hierarchical order within the stream, but // we need to set their timestamps after their children have been written. Stack<DirectoryTimestamp> directoryStack = new Stack<DirectoryTimestamp>(); File baseDirectory = new File(basePath); baseDirectory.mkdir(); TarArchiveInputStream tarStream = new TarArchiveInputStream(inputStream); for (TarArchiveEntry entry = tarStream.getNextTarEntry(); entry != null; entry = tarStream .getNextTarEntry()) { File target = new File(baseDirectory, entry.getName()); if (entry.isDirectory()) { directoryStack.push(new DirectoryTimestamp(target, entry.getModTime().getTime())); continue; } writeStreamToFile(tarStream, target); target.setLastModified(entry.getModTime().getTime()); } while (!directoryStack.empty()) { DirectoryTimestamp info = directoryStack.pop(); info.directory.setLastModified(info.millis); } tarStream.close(); }
From source file:Main.java
public static String getXPath(Node node) { if (null == node) return null; // declarations Node parent = null;//from w w w . j a v a 2s.c om Stack<Node> hierarchy = new Stack<Node>(); StringBuilder buffer = new StringBuilder(); // push element on stack hierarchy.push(node); parent = node.getParentNode(); while (null != parent && parent.getNodeType() != Node.DOCUMENT_NODE) { // push on stack hierarchy.push(parent); // get parent of parent parent = parent.getParentNode(); } // construct xpath Object obj = null; while (!hierarchy.isEmpty() && null != (obj = hierarchy.pop())) { Node n = (Node) obj; boolean handled = false; // only consider elements if (n.getNodeType() == Node.ELEMENT_NODE) { Element e = (Element) n; // is this the root element? if (buffer.length() == 0) { // root element - simply append element name buffer.append(n.getNodeName()); } else { // child element - append slash and element name buffer.append("/"); buffer.append(n.getNodeName()); if (n.hasAttributes()) { // see if the element has a name or id attribute if (e.hasAttribute("id")) { // id attribute found - use that buffer.append("[@id='" + e.getAttribute("id") + "']"); handled = true; } else if (e.hasAttribute("name")) { // name attribute found - use that buffer.append("[@name='" + e.getAttribute("name") + "']"); handled = true; } } if (!handled) { // no known attribute we could use - get sibling index int prev_siblings = 1; Node prev_sibling = n.getPreviousSibling(); while (null != prev_sibling) { if (prev_sibling.getNodeType() == n.getNodeType()) { if (prev_sibling.getNodeName().equalsIgnoreCase(n.getNodeName())) { prev_siblings++; } } prev_sibling = prev_sibling.getPreviousSibling(); } buffer.append("[" + prev_siblings + "]"); } } } } // return buffer return buffer.toString(); }
From source file:com.trenako.web.infrastructure.SearchRequestUrlParser.java
/** * Parses the {@code path} string, matching the {@code SearchCriteria} property names. * <p>//w ww . j a va2 s .c o m * This method is able to manage paths with wrong sequences, in this case * the values outside the correct sequence are simply ignored. * </p> * * @param path the {@code path} string * @return a {@code Map} with the extracted values */ public static Map<String, String> parseUrl(String path) { Assert.notNull(path, "Path must be not null"); Map<String, String> values = new HashMap<>(); Stack<String> stack = new Stack<>(); String[] tokens = path.split("/"); for (String tk : tokens) { if (SEARCH_CRITERIA_KEYS.contains(tk)) { if (!stack.isEmpty()) { // a different key name was found, but no value was provided // (ie /key1/key2/value2) stack.pop(); } stack.push(tk); } else { if (!stack.isEmpty()) { // match this value with the key name in the stack values.put(stack.pop(), tk); } } } return values; }
From source file:com.instantme.model.PhotoEntryModel.java
public PhotoEntryModel() { data = new Vector(); cursor = new Stack(); }
From source file:Main.java
/** * Removes dot segments according to RFC 3986, section 5.2.4 * * @param uri the original URI// w ww .j ava 2s . c om * @return the URI without dot segments */ private static URI removeDotSegments(URI uri) { String path = uri.getPath(); if ((path == null) || (path.indexOf("/.") == -1)) { // No dot segments to remove return uri; } String[] inputSegments = path.split("/"); Stack<String> outputSegments = new Stack<String>(); for (int i = 0; i < inputSegments.length; i++) { if ((inputSegments[i].length() == 0) || (".".equals(inputSegments[i]))) { // Do nothing } else if ("..".equals(inputSegments[i])) { if (!outputSegments.isEmpty()) { outputSegments.pop(); } } else { outputSegments.push(inputSegments[i]); } } StringBuilder outputBuffer = new StringBuilder(); for (String outputSegment : outputSegments) { outputBuffer.append('/').append(outputSegment); } try { return new URI(uri.getScheme(), uri.getAuthority(), outputBuffer.toString(), uri.getQuery(), uri.getFragment()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
From source file:Main.java
/** * Returns the XPath to retrieve targetElement from rootElement. rootElement may be null, in this case the XPath starts with and includes * the farthest non-null ancestor of targetElement. If rootElement == targetElement, an empty string * is returned. /*from www . j av a 2s. c o m*/ * @param includeElementIndex Indicates if the element indices in the form elementName[n] should * be included in the XPath. * @param namespacesMap Maps namespace ids to namespace URIs. */ public static String getXPath(Element rootElement, Element targetElement, boolean includeElementIndex, Map<String, String> namespacesMap) { Stack<Element> elementPath = new Stack<Element>(); // since we need the mapping the other way round, we invert the map Map<String, String> namespaceUriToIdMap = new HashMap<String, String>(); for (Entry<String, String> entry : namespacesMap.entrySet()) { namespaceUriToIdMap.put(entry.getValue(), entry.getKey()); } // recursively find all ancestors of targetElement (up to, not including, rootElement) { Element currentElement = targetElement; while (currentElement != null && currentElement != rootElement) { elementPath.push(currentElement); Node parent = currentElement.getParentNode(); if (parent instanceof Element) { currentElement = (Element) currentElement.getParentNode(); } else { currentElement = null; } } } // construct XPath StringBuilder builder = new StringBuilder(); while (!elementPath.isEmpty()) { Element currentElement = elementPath.pop(); if (builder.length() > 0) { // don't include "/" at the beginning builder.append("/"); } if (namespacesMap != null) { String namespace = currentElement.getNamespaceURI(); if (namespace != null) { namespace = namespaceUriToIdMap.get(namespace); builder.append(namespace); builder.append(":"); } } builder.append(currentElement.getLocalName()); if (includeElementIndex) { int index = getElementIndex(currentElement); builder.append("["); builder.append(index); builder.append("]"); } } return builder.toString(); }
From source file:com.handcraftedbits.bamboo.plugin.go.parser.GoTestParser.java
@SuppressWarnings("unchecked") public static List<PackageTestResults> parseTests(final InputStream input) throws Exception { final List<String> lines = IOUtils.readLines(input, "UTF-8"); final List<PackageTestResults> packageTestResults = new LinkedList<>(); final Stack<SingleTestResult> testResults = new Stack<>(); for (final String line : lines) { // A test has finished. Parse it out and push it on the stack until we know which package it belongs to. if (line.startsWith("---")) { final Matcher matcher = GoTestParser.patternTestFinish.matcher(line); if (matcher.matches()) { TestStatus status = null; switch (matcher.group(1)) { case "FAIL": { status = TestStatus.FAILED; break; }/*from w ww . j a v a 2s . c o m*/ case "PASS": { status = TestStatus.PASSED; break; } case "SKIP": { status = TestStatus.SKIPPED; break; } } if (status != null) { testResults.push(new SingleTestResult(matcher.group(2), status, Double.parseDouble(matcher.group(3)))); } } } // This is either noise or a finished set of package tests. else { final Matcher matcher = GoTestParser.patternPackageFinish.matcher(line); // We have a finished set of package tests, so create the model for it and clear the stack of tests. if (matcher.matches()) { final PackageTestResults packageResults = new PackageTestResults(matcher.group(2)); // In this case, either the go test run did not specify -v or there are no tests in the // package. We'll create a single "AllTests" test and assign it the correct status. In the // case of no tests existing for the package, the status will be "skipped". if (testResults.empty()) { double duration = 0.0d; final String durationStr = matcher.group(3); TestStatus testStatus = TestStatus.SKIPPED; switch (matcher.group(1)) { case "FAIL": { testStatus = TestStatus.FAILED; break; } case "ok ": { testStatus = TestStatus.PASSED; break; } } // If there are tests in the package, we should be able to extract the duration. if (durationStr.endsWith("s")) { duration = Double.parseDouble(durationStr.substring(0, durationStr.length() - 1)); } packageResults.addTestResult(new SingleTestResult("AllTests", testStatus, duration)); } while (!testResults.empty()) { packageResults.addTestResult(testResults.pop()); } packageTestResults.add(packageResults); } } } IOUtils.closeQuietly(input); return packageTestResults; }