List of usage examples for java.util Stack push
public E push(E item)
From source file:com.rabbitmq.client.test.performance.ScalabilityTest.java
public Results run() throws Exception { Connection con = new ConnectionFactory() { {/*from www .ja va 2 s. co m*/ setHost(params.host); setPort(params.port); } }.newConnection(); Channel channel = con.createChannel(); Results r = new Results(params.maxBindingExp); for (int y = 0; y < params.maxBindingExp; y++) { final int maxBindings = pow(params.base, y); String[] routingKeys = new String[maxBindings]; for (int b = 0; b < maxBindings; b++) { routingKeys[b] = UUID.randomUUID().toString(); } Stack<String> queues = new Stack<String>(); int maxQueueExp = Math.min(params.maxQueueExp, params.maxExp - y); System.out.println("---------------------------------"); System.out.println("| bindings = " + maxBindings + ", messages = " + params.messageCount); System.out.println("| Routing"); int q = 0; // create queues & bindings, time routing Measurements creation = new CreationMeasurements(maxQueueExp); float routingTimes[] = new float[maxQueueExp]; for (int x = 0; x < maxQueueExp; x++) { final int maxQueues = pow(params.base, x); for (; q < maxQueues; q++) { AMQP.Queue.DeclareOk ok = channel.queueDeclare(); queues.push(ok.getQueue()); for (int b = 0; b < maxBindings; b++) { channel.queueBind(ok.getQueue(), "amq.direct", routingKeys[b]); } } creation.addDataPoint(x); float routingTime = timeRouting(channel, routingKeys); routingTimes[x] = routingTime; printTime(params.base, x, routingTime); } r.routingTimes[y] = routingTimes; float[] creationTimes = creation.analyse(params.base); r.creationTimes[y] = creationTimes; System.out.println("| Creating"); printTimes(params.base, creationTimes); // delete queues & bindings Measurements deletion = new DeletionMeasurements(maxQueueExp); for (int x = maxQueueExp - 1; x >= 0; x--) { final int maxQueues = (x == 0) ? 0 : pow(params.base, x - 1); for (; q > maxQueues; q--) { channel.queueDelete(queues.pop()); } deletion.addDataPoint(x); } float[] deletionTimes = deletion.analyse(params.base); r.deletionTimes[y] = deletionTimes; System.out.println("| Deleting"); printTimes(params.base, deletionTimes); } channel.close(); con.close(); return r; }
From source file:com.hubspot.jinjava.interpret.JinjavaInterpreter.java
private void resolveBlockStubs(OutputList output, Stack<String> blockNames) { for (BlockPlaceholderOutputNode blockPlaceholder : output.getBlocks()) { if (!blockNames.contains(blockPlaceholder.getBlockName())) { Collection<List<? extends Node>> blockChain = blocks.get(blockPlaceholder.getBlockName()); List<? extends Node> block = Iterables.getFirst(blockChain, null); if (block != null) { List<? extends Node> superBlock = Iterables.get(blockChain, 1, null); context.setSuperBlock(superBlock); OutputList blockValueBuilder = new OutputList(); for (Node child : block) { blockValueBuilder.addNode(child.render(this)); }/*w w w . j a v a 2 s.c o m*/ blockNames.push(blockPlaceholder.getBlockName()); resolveBlockStubs(blockValueBuilder, blockNames); blockNames.pop(); context.removeSuperBlock(); blockPlaceholder.resolve(blockValueBuilder.getValue()); } } if (!blockPlaceholder.isResolved()) { blockPlaceholder.resolve(""); } } }
From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java
/** * Recursively create a path, working down from the leaf to the root. * <p>//from w w w .j a va2s. co m * Borrowed from Apache Sling * * @param path a directory path to create * @throws HttpException * @throws TransferFailedException * @throws AuthorizationException */ protected void mkdirs(String path) throws HttpException, TransferFailedException, AuthorizationException { // Call mkdir on all parent paths, starting at the topmost one final Stack<String> parents = new Stack<String>(); while (path.length() > 0 && !resourceExists(path)) { parents.push(path); path = getParentPath(path); } while (!parents.isEmpty()) { mkdir(parents.pop()); } }
From source file:org.apache.tajo.engine.planner.rewrite.ProjectionPushDownRule.java
@Override public LogicalNode visitInsert(Context context, LogicalPlan plan, LogicalPlan.QueryBlock block, InsertNode node, Stack<LogicalNode> stack) throws PlanningException { stack.push(node); visit(context, plan, block, node.getChild(), stack); stack.pop();//from w ww .j av a2 s .c o m return node; }
From source file:com.google.dart.compiler.metrics.Tracer.java
public void markTimelineImpl(String message) { Stack<TraceEvent> threadPendingEvents = pendingEvents.get(); TraceEvent parent = null;/*www .jav a 2 s . c o m*/ if (!threadPendingEvents.isEmpty()) { parent = threadPendingEvents.peek(); } TraceEvent newEvent = new MarkTimelineEvent(parent); threadPendingEvents.push(newEvent); newEvent.end("message", message); }
From source file:org.apache.jackrabbit.core.nodetype.NodeTypeRegistry.java
/** * Validates the specified <code>NodeTypeDef</code> within the context of * the two other given collections and returns an <code>EffectiveNodeType</code>. * * @param ntd node type definition//from www. j a v a 2 s .c om * @param entCache effective node type cache * @param ntdCache cache of 'known' node type definitions, used to resolve dependencies * @param nsReg namespace registry used for validatingatch names * @param lenient flag governing whether validation can be lenient or has to be strict * @return an effective node type representation of the specified <code>QNodeTypeDefinition</code> * @throws InvalidNodeTypeDefException if the node type is not valid * @throws RepositoryException if another error occurs */ private static EffectiveNodeType validateNodeTypeDef(QNodeTypeDefinition ntd, EffectiveNodeTypeCache entCache, Map<Name, QNodeTypeDefinition> ntdCache, NamespaceRegistry nsReg, boolean lenient) throws InvalidNodeTypeDefException, RepositoryException { /** * the effective (i.e. merged and resolved) node type resulting from * the specified node type definition; * the effective node type will finally be created after the definition * has been verified and checked for conflicts etc.; in some cases it * will be created already at an earlier stage during the validation * of child node definitions */ EffectiveNodeType ent = null; Name name = ntd.getName(); if (name == null) { String msg = "no name specified"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } checkNamespace(name, nsReg); // validate supertypes Name[] supertypes = ntd.getSupertypes(); if (supertypes.length > 0) { for (Name supertype : supertypes) { checkNamespace(supertype, nsReg); /** * simple check for infinite recursion * (won't trap recursion on a deeper inheritance level) */ if (name.equals(supertype)) { String msg = "[" + name + "] invalid supertype: " + supertype + " (infinite recursion))"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } if (!ntdCache.containsKey(supertype)) { String msg = "[" + name + "] invalid supertype: " + supertype; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } } /** * check for circularity in inheritance chain * ('a' extends 'b' extends 'a') */ Stack<Name> inheritanceChain = new Stack<Name>(); inheritanceChain.push(name); checkForCircularInheritance(supertypes, inheritanceChain, ntdCache); } /** * note that infinite recursion through inheritance is automatically * being checked by the following call to getEffectiveNodeType(...) * as it's impossible to register a node type definition which * references a supertype that isn't registered yet... */ /** * build effective (i.e. merged and resolved) node type from supertypes * and check for conflicts */ if (supertypes.length > 0) { try { EffectiveNodeType est = getEffectiveNodeType(supertypes, entCache, ntdCache); // check whether specified node type definition overrides // a supertypes's primaryItem -> illegal (JCR-1947) if (ntd.getPrimaryItemName() != null && est.getPrimaryItemName() != null) { String msg = "[" + name + "] primaryItemName is already specified by a supertype and must therefore not be overridden."; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } } catch (NodeTypeConflictException ntce) { String msg = "[" + name + "] failed to validate supertypes"; log.debug(msg); throw new InvalidNodeTypeDefException(msg, ntce); } catch (NoSuchNodeTypeException nsnte) { String msg = "[" + name + "] failed to validate supertypes"; log.debug(msg); throw new InvalidNodeTypeDefException(msg, nsnte); } } checkNamespace(ntd.getPrimaryItemName(), nsReg); // validate property definitions QPropertyDefinition[] pda = ntd.getPropertyDefs(); for (QPropertyDefinition pd : pda) { /** * sanity check: * make sure declaring node type matches name of node type definition */ if (!name.equals(pd.getDeclaringNodeType())) { String msg = "[" + name + "#" + pd.getName() + "] invalid declaring node type specified"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } checkNamespace(pd.getName(), nsReg); // check that auto-created properties specify a name if (pd.definesResidual() && pd.isAutoCreated()) { String msg = "[" + name + "#" + pd.getName() + "] auto-created properties must specify a name"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } // check that auto-created properties specify a type if (pd.getRequiredType() == PropertyType.UNDEFINED && pd.isAutoCreated()) { String msg = "[" + name + "#" + pd.getName() + "] auto-created properties must specify a type"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } /** * check default values: * make sure type of value is consistent with required property type */ QValue[] defVals = pd.getDefaultValues(); if (defVals != null && defVals.length != 0) { int reqType = pd.getRequiredType(); for (QValue defVal : defVals) { if (reqType == PropertyType.UNDEFINED) { reqType = defVal.getType(); } else { if (defVal.getType() != reqType) { String msg = "[" + name + "#" + pd.getName() + "] type of default value(s) is not consistent with required property type"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } } } } else { // no default values specified if (!lenient) { // auto-created properties must have a default value if (pd.isAutoCreated()) { String msg = "[" + name + "#" + pd.getName() + "] auto-created property must have a default value"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } } } // check that default values satisfy value constraints QValueConstraint[] constraints = pd.getValueConstraints(); if (constraints != null && constraints.length > 0) { if (defVals != null && defVals.length > 0) { // check value constraints on every value for (QValue defVal : defVals) { // constraints are OR-ed together boolean satisfied = false; ConstraintViolationException cve = null; for (QValueConstraint constraint : constraints) { try { constraint.check(defVal); // at least one constraint is satisfied satisfied = true; break; } catch (ConstraintViolationException e) { cve = e; } } if (!satisfied) { // report last exception we encountered String msg = "[" + name + "#" + pd.getName() + "] default value does not satisfy value constraint"; log.debug(msg); throw new InvalidNodeTypeDefException(msg, cve); } } } /** * ReferenceConstraint: * the specified node type must be registered, with one notable * exception: the node type just being registered */ if (pd.getRequiredType() == PropertyType.REFERENCE || pd.getRequiredType() == PropertyType.WEAKREFERENCE) { for (QValueConstraint constraint : constraints) { Name ntName = NameFactoryImpl.getInstance().create(constraint.getString()); if (!name.equals(ntName) && !ntdCache.containsKey(ntName)) { String msg = "[" + name + "#" + pd.getName() + "] invalid " + (pd.getRequiredType() == PropertyType.REFERENCE ? "REFERENCE" : "WEAKREFERENCE") + " value constraint '" + ntName + "' (unknown node type)"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } } } } } // validate child-node definitions QNodeDefinition[] cnda = ntd.getChildNodeDefs(); for (QNodeDefinition cnd : cnda) { /** * sanity check: * make sure declaring node type matches name of node type definition */ if (!name.equals(cnd.getDeclaringNodeType())) { String msg = "[" + name + "#" + cnd.getName() + "] invalid declaring node type specified"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } checkNamespace(cnd.getName(), nsReg); // check that auto-created child-nodes specify a name if (cnd.definesResidual() && cnd.isAutoCreated()) { String msg = "[" + name + "#" + cnd.getName() + "] auto-created child-nodes must specify a name"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } // check that auto-created child-nodes specify a default primary type if (cnd.getDefaultPrimaryType() == null && cnd.isAutoCreated()) { String msg = "[" + name + "#" + cnd.getName() + "] auto-created child-nodes must specify a default primary type"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } // check default primary type Name dpt = cnd.getDefaultPrimaryType(); checkNamespace(dpt, nsReg); boolean referenceToSelf = false; EffectiveNodeType defaultENT = null; if (dpt != null) { // check if this node type specifies itself as default primary type if (name.equals(dpt)) { referenceToSelf = true; } /** * the default primary type must be registered, with one notable * exception: the node type just being registered */ if (!name.equals(dpt) && !ntdCache.containsKey(dpt)) { String msg = "[" + name + "#" + cnd.getName() + "] invalid default primary type '" + dpt + "'"; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } /** * build effective (i.e. merged and resolved) node type from * default primary type and check for conflicts */ try { if (!referenceToSelf) { defaultENT = getEffectiveNodeType(dpt, entCache, ntdCache); } else { /** * the default primary type is identical with the node * type just being registered; we have to instantiate it * 'manually' */ ent = EffectiveNodeType.create(ntd, entCache, ntdCache); defaultENT = ent; } if (cnd.isAutoCreated()) { /** * check for circularity through default primary types * of auto-created child nodes (node type 'a' defines * auto-created child node with default primary type 'a') */ Stack<Name> definingNTs = new Stack<Name>(); definingNTs.push(name); checkForCircularNodeAutoCreation(defaultENT, definingNTs, entCache, ntdCache); } } catch (NodeTypeConflictException ntce) { String msg = "[" + name + "#" + cnd.getName() + "] failed to validate default primary type"; log.debug(msg); throw new InvalidNodeTypeDefException(msg, ntce); } catch (NoSuchNodeTypeException nsnte) { String msg = "[" + name + "#" + cnd.getName() + "] failed to validate default primary type"; log.debug(msg); throw new InvalidNodeTypeDefException(msg, nsnte); } } // check required primary types Name[] reqTypes = cnd.getRequiredPrimaryTypes(); if (reqTypes != null && reqTypes.length > 0) { for (Name rpt : reqTypes) { // skip nt:base required types if (NameConstants.NT_BASE.equals(rpt)) { continue; } checkNamespace(rpt, nsReg); referenceToSelf = false; /** * check if this node type specifies itself as required * primary type */ if (name.equals(rpt)) { referenceToSelf = true; } /** * the required primary type must be registered, with one * notable exception: the node type just being registered */ if (!name.equals(rpt) && !ntdCache.containsKey(rpt)) { String msg = "[" + name + "#" + cnd.getName() + "] invalid required primary type: " + rpt; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } /** * check if default primary type satisfies the required * primary type constraint */ if (defaultENT != null && !defaultENT.includesNodeType(rpt)) { String msg = "[" + name + "#" + cnd.getName() + "] default primary type does not satisfy required primary type constraint " + rpt; log.debug(msg); throw new InvalidNodeTypeDefException(msg); } /** * build effective (i.e. merged and resolved) node type from * required primary type constraint and check for conflicts */ try { if (!referenceToSelf) { getEffectiveNodeType(rpt, entCache, ntdCache); } else { /** * the required primary type is identical with the * node type just being registered; we have to * instantiate it 'manually' */ if (ent == null) { ent = EffectiveNodeType.create(ntd, entCache, ntdCache); } } } catch (NodeTypeConflictException ntce) { String msg = "[" + name + "#" + cnd.getName() + "] failed to validate required primary type constraint"; log.debug(msg); throw new InvalidNodeTypeDefException(msg, ntce); } catch (NoSuchNodeTypeException nsnte) { String msg = "[" + name + "#" + cnd.getName() + "] failed to validate required primary type constraint"; log.debug(msg); throw new InvalidNodeTypeDefException(msg, nsnte); } } } } /** * now build effective (i.e. merged and resolved) node type from * this node type definition; this will potentially detect more * conflicts or problems */ if (ent == null) { try { ent = EffectiveNodeType.create(ntd, entCache, ntdCache); } catch (NodeTypeConflictException ntce) { String msg = "[" + name + "] failed to resolve node type definition"; log.debug(msg); throw new InvalidNodeTypeDefException(msg, ntce); } catch (NoSuchNodeTypeException nsnte) { String msg = "[" + name + "] failed to resolve node type definition"; log.debug(msg); throw new InvalidNodeTypeDefException(msg, nsnte); } } return ent; }
From source file:com.gargoylesoftware.htmlunit.activex.javascript.msxml.XMLHTTPRequest.java
/** * Sends an HTTP request to the server and receives a response. * @param body the body of the message being sent with the request. *//* w w w.jav a 2 s. c om*/ @JsxFunction public void send(final Object body) { if (webRequest_ == null) { setState(STATE_DONE, Context.getCurrentContext()); return; } if (sent_) { throw Context.reportRuntimeError("Unspecified error (request already sent)."); } sent_ = true; prepareRequest(body); // quite strange but IE seems to fire state loading twice setState(STATE_OPENED, Context.getCurrentContext()); final WebClient client = getWindow().getWebWindow().getWebClient(); final AjaxController ajaxController = client.getAjaxController(); final HtmlPage page = (HtmlPage) getWindow().getWebWindow().getEnclosedPage(); final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_); if (synchron) { doSend(Context.getCurrentContext()); } else { // Create and start a thread in which to execute the request. final Scriptable startingScope = getWindow(); final ContextFactory cf = client.getJavaScriptEngine().getContextFactory(); final ContextAction action = new ContextAction() { @Override public Object run(final Context cx) { // KEY_STARTING_SCOPE maintains a stack of scopes @SuppressWarnings("unchecked") Stack<Scriptable> stack = (Stack<Scriptable>) cx .getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE); if (null == stack) { stack = new Stack<>(); cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack); } stack.push(startingScope); try { doSend(cx); } finally { stack.pop(); } return null; } }; final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().createJavascriptXMLHttpRequestJob(cf, action); if (LOG.isDebugEnabled()) { LOG.debug("Starting XMLHTTPRequest thread for asynchronous request"); } jobID_ = getWindow().getWebWindow().getJobManager().addJob(job, page); } }
From source file:com.sun.socialsite.pojos.PropDefinition.java
protected void init(PropDefinition profileDef, InputStream input) throws SocialSiteException { try {/*from ww w. j ava2 s . c o m*/ XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader parser = factory.createXMLStreamReader(input); String ns = null; // TODO: namespace for ProfileDef // hold the current things we're working on Map<String, DisplaySectionDefinition> sdefs = new LinkedHashMap<String, DisplaySectionDefinition>(); Stack<PropertyDefinitionHolder> propertyHolderStack = new Stack<PropertyDefinitionHolder>(); List<AllowedValue> allowedValues = null; PropertyDefinition pdef = null; for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) { switch (event) { case XMLStreamConstants.START_ELEMENT: log.debug("START ELEMENT -- " + parser.getLocalName()); if ("display-section".equals(parser.getLocalName())) { propertyHolderStack.push(new DisplaySectionDefinition(parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"))); } else if ("property".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); pdef = new PropertyDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"), parser.getAttributeValue(ns, "type")); } else if ("object".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); propertyHolderStack.push(new PropertyObjectDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"))); } else if ("collection".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); propertyHolderStack.push(new PropertyObjectCollectionDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey"))); } else if ("allowed-values".equals(parser.getLocalName())) { allowedValues = new ArrayList<AllowedValue>(); } else if ("value".equals(parser.getLocalName())) { AllowedValue allowedValue = new AllowedValue(parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")); allowedValues.add(allowedValue); } else if ("default-value".equals(parser.getLocalName())) { pdef.setDefaultValue(parser.getText()); } break; case XMLStreamConstants.END_ELEMENT: log.debug("END ELEMENT -- " + parser.getLocalName()); if ("display-section".equals(parser.getLocalName())) { DisplaySectionDefinition sdef = (DisplaySectionDefinition) propertyHolderStack.pop(); sdefs.put(sdef.getName(), sdef); } else if ("property".equals(parser.getLocalName())) { PropertyDefinitionHolder holder = propertyHolderStack.peek(); holder.getPropertyDefinitions().add(pdef); propertyDefs.put(pdef.getName(), pdef); pdef = null; } else if ("object".equals(parser.getLocalName())) { PropertyObjectDefinition odef = (PropertyObjectDefinition) propertyHolderStack.pop(); PropertyDefinitionHolder holder = propertyHolderStack.peek(); holder.getPropertyObjectDefinitions().add(odef); // add to list of all property object defs propertyObjectDefs.put(odef.getName(), odef); odef = null; } else if ("collection".equals(parser.getLocalName())) { PropertyObjectCollectionDefinition cdef = (PropertyObjectCollectionDefinition) propertyHolderStack .pop(); PropertyDefinitionHolder holder = propertyHolderStack.peek(); holder.getPropertyObjectCollectionDefinitions().add(cdef); // add to list of all property object defs propertyObjectCollectionDefs.put(cdef.getName(), cdef); cdef = null; } else if ("allowed-values".equals(parser.getLocalName())) { pdef.setAllowedValues(allowedValues); allowedValues = null; } break; case XMLStreamConstants.CHARACTERS: break; case XMLStreamConstants.CDATA: break; } // end switch } // end while parser.close(); profileDef.sectionDefs = sdefs; } catch (Exception ex) { throw new SocialSiteException("ERROR parsing profile definitions", ex); } }
From source file:org.apache.hadoop.hbase.filter.ParseFilter.java
/** * Parses the filterString and constructs a filter using it * <p>/* w w w .j a v a 2 s . com*/ * @param filterStringAsByteArray filter string given by the user * @return filter object we constructed */ public Filter parseFilterString(byte[] filterStringAsByteArray) throws CharacterCodingException { // stack for the operators and parenthesis Stack<ByteBuffer> operatorStack = new Stack<ByteBuffer>(); // stack for the filter objects Stack<Filter> filterStack = new Stack<Filter>(); Filter filter = null; for (int i = 0; i < filterStringAsByteArray.length; i++) { if (filterStringAsByteArray[i] == ParseConstants.LPAREN) { // LPAREN found operatorStack.push(ParseConstants.LPAREN_BUFFER); } else if (filterStringAsByteArray[i] == ParseConstants.WHITESPACE || filterStringAsByteArray[i] == ParseConstants.TAB) { // WHITESPACE or TAB found continue; } else if (checkForOr(filterStringAsByteArray, i)) { // OR found i += ParseConstants.OR_ARRAY.length - 1; reduce(operatorStack, filterStack, ParseConstants.OR_BUFFER); operatorStack.push(ParseConstants.OR_BUFFER); } else if (checkForAnd(filterStringAsByteArray, i)) { // AND found i += ParseConstants.AND_ARRAY.length - 1; reduce(operatorStack, filterStack, ParseConstants.AND_BUFFER); operatorStack.push(ParseConstants.AND_BUFFER); } else if (checkForSkip(filterStringAsByteArray, i)) { // SKIP found i += ParseConstants.SKIP_ARRAY.length - 1; reduce(operatorStack, filterStack, ParseConstants.SKIP_BUFFER); operatorStack.push(ParseConstants.SKIP_BUFFER); } else if (checkForWhile(filterStringAsByteArray, i)) { // WHILE found i += ParseConstants.WHILE_ARRAY.length - 1; reduce(operatorStack, filterStack, ParseConstants.WHILE_BUFFER); operatorStack.push(ParseConstants.WHILE_BUFFER); } else if (filterStringAsByteArray[i] == ParseConstants.RPAREN) { // RPAREN found if (operatorStack.empty()) { throw new IllegalArgumentException("Mismatched parenthesis"); } ByteBuffer argumentOnTopOfStack = operatorStack.peek(); while (!(argumentOnTopOfStack.equals(ParseConstants.LPAREN_BUFFER))) { filterStack.push(popArguments(operatorStack, filterStack)); if (operatorStack.empty()) { throw new IllegalArgumentException("Mismatched parenthesis"); } argumentOnTopOfStack = operatorStack.pop(); } } else { // SimpleFilterExpression found byte[] filterSimpleExpression = extractFilterSimpleExpression(filterStringAsByteArray, i); i += (filterSimpleExpression.length - 1); filter = parseSimpleFilterExpression(filterSimpleExpression); filterStack.push(filter); } } // Finished parsing filterString while (!operatorStack.empty()) { filterStack.push(popArguments(operatorStack, filterStack)); } filter = filterStack.pop(); if (!filterStack.empty()) { throw new IllegalArgumentException("Incorrect Filter String"); } return filter; }
From source file:net.dv8tion.jda.entities.impl.MessageImpl.java
@Override public String getStrippedContent() { if (strippedContent == null) { String tmp = getContent(); //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(tmp); while (matcher.find()) { tokens.add(new FormatToken(key, matcher.start())); }//from ww w . ja v a 2s .com } //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(tmp.substring(currIndex, formatToken.start)); } currIndex = formatToken.start + formatToken.format.length(); } if (currIndex < tmp.length()) { out.append(tmp.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; }