List of usage examples for java.util Stack peek
public synchronized E peek()
From source file:de.se_rwth.langeditor.util.Misc.java
public static <T> void traverse(T root, Function<T, Collection<? extends T>> childGenerator, Consumer<? super T> enter, Consumer<? super T> exit) { Set<T> previouslyVisited = new HashSet<>(); Stack<T> yetToVisit = new Stack<>(); yetToVisit.push(root);// www. j a va 2s.c om T nextElement; while (!yetToVisit.isEmpty()) { nextElement = yetToVisit.peek(); if (!previouslyVisited.contains(nextElement)) { enter.accept(nextElement); previouslyVisited.add(nextElement); yetToVisit.addAll(childGenerator.apply(nextElement)); } else { exit.accept(yetToVisit.pop()); } } }
From source file:cf.adriantodt.utils.HTML2Discord.java
public static String toPlainText(String discordFormatMessage) { String strippedContent;// ww w . ja va2 s. c o m //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(discordFormatMessage); while (matcher.find()) { tokens.add(new FormatToken(key, matcher.start())); } } //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(discordFormatMessage.substring(currIndex, formatToken.start)); } currIndex = formatToken.start + formatToken.format.length(); } if (currIndex < discordFormatMessage.length()) { out.append(discordFormatMessage.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:com.jetbrains.pluginUtils.xml.JDOMXIncluder.java
protected static List<Content> resolve(Element original, Stack<String> bases) throws XIncludeException { if (!bases.isEmpty()) bases.peek(); if (isIncludeElement(original)) { return resolveXIncludeElement(original, bases); } else {/*from ww w .j a v a2s .c o m*/ Element resolvedElement = resolveNonXIncludeElement(original, bases); List<Content> resultList = new ArrayList<Content>(1); resultList.add(resolvedElement); return resultList; } }
From source file:org.springframework.data.mapping.PropertyPath.java
/** * Creates a new {@link PropertyPath} as subordinary of the given {@link PropertyPath}. * //from ww w. j av a2 s .com * @param source * @param base * @return */ private static PropertyPath create(String source, Stack<PropertyPath> base) { PropertyPath previous = base.peek(); PropertyPath propertyPath = create(source, previous.type, base); previous.next = propertyPath; return propertyPath; }
From source file:com.jetbrains.pluginUtils.xml.JDOMXIncluder.java
private static Element resolveNonXIncludeElement(Element original, Stack<String> bases) throws XIncludeException { if (!bases.isEmpty()) bases.peek(); Element result = new Element(original.getName(), original.getNamespace()); Iterator<Attribute> attributes = original.getAttributes().iterator(); while (attributes.hasNext()) { Attribute a = attributes.next(); result.setAttribute((Attribute) a.clone()); }// ww w.j a va 2 s . c o m for (Content o : (List<Content>) original.getContent()) { if (o instanceof Element) { Element element = (Element) o; if (isIncludeElement(element)) { result.addContent(resolveXIncludeElement(element, bases)); } else { result.addContent(resolveNonXIncludeElement(element, bases)); } } else { result.addContent((Content) o.clone()); } } // end while return result; }
From source file:org.apache.solr.handler.JsonLoader.java
static void addValToField(Stack stack, Object val, boolean inArray, JSONParser parser) throws IOException { Object obj = stack.peek(); if (!(obj instanceof SolrInputField)) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "hymmm [" + parser.getPosition() + "]"); }/*from ww w .j a v a2 s . c om*/ SolrInputField f = inArray ? (SolrInputField) obj : (SolrInputField) stack.pop(); if (val == null) return; float boost = (f.getValue() == null) ? f.getBoost() : 1.0f; f.addValue(val, boost); }
From source file:com.jetbrains.pluginUtils.xml.JDOMXIncluder.java
private static List<Content> resolveXIncludeElement(Element element, Stack<String> bases) throws XIncludeException { String base = ""; if (!bases.isEmpty()) base = bases.peek(); // These lines are probably unnecessary assert isIncludeElement(element); String href = element.getAttributeValue(HREF); assert href != null : "Missing href attribute"; Attribute baseAttribute = element.getAttribute(BASE, Namespace.XML_NAMESPACE); if (baseAttribute != null) { base = baseAttribute.getValue(); }//from w w w. j a v a 2 s . c o m URL remote; if (base != null) { try { URL context = new URL(base); remote = new URL(context, href); } catch (MalformedURLException ex) { throw new XIncludeException(ex); } } else { // base == null try { remote = new URL(href); } catch (MalformedURLException ex) { throw new XIncludeException(ex); } } boolean parse = true; final String parseAttribute = element.getAttributeValue(PARSE); if (parseAttribute != null) { if (parseAttribute.equals(TEXT)) { parse = false; } assert parseAttribute.equals(XML) : parseAttribute + "is not a legal value for the parse attribute"; } if (parse) { assert !bases.contains(remote.toExternalForm()) : "Circular XInclude Reference to " + remote.toExternalForm(); final Element fallbackElement = element.getChild("fallback", element.getNamespace()); List<Content> remoteParsed = parseRemote(bases, remote, fallbackElement); if (!remoteParsed.isEmpty()) { remoteParsed = extractNeededChildren(element, remoteParsed); } for (int i = 0; i < remoteParsed.size(); i++) { Object o = remoteParsed.get(i); if (o instanceof Element) { Element e = (Element) o; List<? extends Content> nodes = resolve(e, bases); remoteParsed.addAll(i, nodes); i += nodes.size(); remoteParsed.remove(i); i--; e.detach(); } } for (Object o : remoteParsed) { if (o instanceof Content) { Content content = (Content) o; content.detach(); } } return remoteParsed; } else { try { String encoding = element.getAttributeValue(ENCODING); String s = IOUtils.toString(remote, encoding); List<Content> resultList = new ArrayList<Content>(1); resultList.add(new Text(s)); return resultList; } catch (IOException e) { throw new XIncludeException(e); } } }
From source file:org.sakaiproject.util.Xml.java
/** * Serialize the properties into XML, adding an element to the doc under the top of the stack element. * //w w w .j ava 2 s . c o m * @param propsToSerialize * The properties to serialize. * @param doc * The DOM doc to contain the XML (or null for a string return). * @param stack * The DOM elements, the top of which is the containing element of the new "resource" element. * @return The newly added element. */ public static Element propertiesToXml(Properties propsToSerialize, Document doc, Stack<Element> stack) { Element properties = doc.createElement("properties"); ((Element) stack.peek()).appendChild(properties); Enumeration<?> props = propsToSerialize.propertyNames(); while (props.hasMoreElements()) { String name = (String) props.nextElement(); String value = propsToSerialize.getProperty(name); Element propElement = doc.createElement("property"); properties.appendChild(propElement); propElement.setAttribute("name", name); // encode to allow special characters in the value Xml.encodeAttribute(propElement, "value", (String) value); propElement.setAttribute("enc", "BASE64"); } return properties; }
From source file:com.sunyue.util.calculator.core.ExpressionConverter.java
/** * Convert an infix expression to a postfix expression. * //from ww w. j a va2s .c om * @param exp * expression parsed by ExpressionParser * @return postfix expression */ public static Object[] convert(Object[] exp) { if (ArrayUtils.isEmpty(exp)) { throw new CalculationException("Expression can not be empty"); } // remember if brackets are coupled int coupled = 0; // out put postfix expression List<Object> out = new ArrayList<Object>(); Stack<Object> opStack = new Stack<Object>(); for (int i = 0; i < exp.length; i++) { if (exp[i] instanceof Operator) { // operator Operator op = (Operator) exp[i]; while (true) { if (opStack.isEmpty()) { opStack.push(op); break; } else { Object obj = opStack.peek(); if (!(obj instanceof Bracket)) { Operator preOp = (Operator) opStack.peek(); if (op.getPriority() <= preOp.getPriority()) { // pop and output operator with not lower // priority out.add(opStack.pop()); } else { // push otherwise opStack.push(op); break; } } else { // push when bracket on top opStack.push(op); break; } } } } else if (Bracket.LEFT_BRACKET.equals(exp[i])) { opStack.push(exp[i]); coupled++; } else if (Bracket.RIGHT_BRACKET.equals(exp[i])) { if (coupled <= 0) { throw new CalculationException("Brackets are not coupled, missing left bracket ("); } while (true) { Object op = opStack.pop(); if (Bracket.LEFT_BRACKET.equals(op)) { // eliminate coupled brackets break; } else { // pop and output until coupled left bracket out.add(op); } } coupled--; } else { // general numbers out.add(exp[i]); } } if (coupled != 0) { throw new CalculationException("Brackets are not coupled, missing right bracket )"); } // output rest elements while (!opStack.isEmpty()) { out.add(opStack.pop()); } return out.toArray(); }
From source file:org.dhatim.delivery.AbstractParser.java
public static XMLReader getXMLReader(ExecutionContext execContext) { Stack<XMLReader> xmlReaderStack = getReaders(execContext); if (!xmlReaderStack.isEmpty()) { return xmlReaderStack.peek(); } else {/*from w w w . ja va 2 s .c o m*/ return null; } }