List of usage examples for java.util Stack pop
public synchronized E pop()
From source file:com.bluexml.xforms.generator.forms.Renderable.java
/** * Recursive render./*from w w w .j av a 2 s. com*/ * * @param parentPath * the parent path * @param parents * the parents * @param renderedParents * the rendered parents * @param isInIMultRepeater * TODO * @return the rendered */ private Rendered recursiveRender(String parentPath, Stack<Renderable> parents, Stack<Rendered> renderedParents, boolean isInIMultRepeater) { boolean previous = XFormsGenerator.isRenderingWorkflow(); // logger.debug(this.toString() ); // retrieve path for this renderable in this context Path path = getPath(parentPath, parents, renderedParents); // translate Path object into an absolute path String sPath = null; if (path.pathType == PathType.absolutePath) { sPath = path.path; } else { sPath = parentPath + path.path; } // if (StringUtils.trimToNull(sPath) != null) { // System.out.println("non empty path"); // } // real render Rendered rendered = render(sPath, parents, renderedParents, isInIMultRepeater); // recursive render parents.push(this); boolean childIsInIMultiple = isInIMultRepeater || isInlineMultipleRepeater(); // #1310 if (this instanceof RenderableFormContainer) { XFormsGenerator.setRenderingWorkflow(isInWorkflowForm()); } renderedParents.push(rendered); for (Renderable child : children) { if (child == null) { throw new RuntimeException("A null child was found. You probably forgot to reference a form."); } if (child.shouldRender(parents)) { Rendered renderedChild = child.recursiveRender(sPath, parents, renderedParents, childIsInIMultiple); rendered.addRendered(renderedChild, child); } } // if (this instanceof RenderableFormContainer) { XFormsGenerator.setRenderingWorkflow(previous); } renderedParents.pop(); rendered.renderEnd(); renderEnd(rendered); parents.pop(); return rendered; }
From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java
private void parseTemplates(SpanManager sm, List<Span> resolvedTemplateSpans, List<ResolvedTemplate> resolvedTemplates, ParsedPage pp) { sm.manageList(resolvedTemplateSpans); int pos = -2; Stack<Integer> templateOpenTags = new Stack<Integer>(); while ((pos = sm.indexOf("{{", pos + 2)) != -1) { if (sm.length() > pos + 3 && sm.charAt(pos + 2) == '{' && sm.charAt(pos + 3) != '{') { pos++;/*w ww . ja v a 2s . c om*/ } templateOpenTags.push(pos); } while (!templateOpenTags.empty()) { int templateOpenTag = templateOpenTags.pop(); int templateCloseTag = sm.indexOf("}}", templateOpenTag); if (templateCloseTag == -1) { continue; } int templateOptionTag = sm.indexOf("|", templateOpenTag, templateCloseTag); int templateNameEnd; List<String> templateOptions; if (templateOptionTag != -1) { templateNameEnd = templateOptionTag; templateOptions = tokenize(sm, templateOptionTag + 1, templateCloseTag, "|"); } else { templateNameEnd = templateCloseTag; templateOptions = new ArrayList<String>(); } Span ts = new Span(templateOpenTag, templateCloseTag + 2); Template t = new Template(ts, encodeWikistyle(sm.substring(templateOpenTag + 2, templateNameEnd).trim()), templateOptions); if (calculateSrcSpans) { t.setSrcSpan(new SrcSpan(sm.getSrcPos(templateOpenTag), sm.getSrcPos(templateCloseTag + 2))); } t.setPos(ts); ResolvedTemplate rt = templateParser.parseTemplate(t, pp); resolvedTemplateSpans.add(ts); resolvedTemplates.add(rt); sm.replace(ts, rt.getPreParseReplacement()); } if (resolvedTemplateSpans.isEmpty()) { sm.removeManagedList(resolvedTemplateSpans); } }
From source file:com.udojava.evalex.Expression.java
/** * Check that the expression has enough numbers and variables to fit the * requirements of the operators and functions, also check * for only 1 result stored at the end of the evaluation. */// ww w. j a v a2s.c o m private void validate(List<String> rpn) { /*- * Thanks to Norman Ramsey: * http://http://stackoverflow.com/questions/789847/postfix-notation-validation */ // each push on to this stack is a new function scope, with the value of each // layer on the stack being the count of the number of parameters in that scope Stack<Integer> stack = new Stack<>(); // push the 'global' scope stack.push(0); for (final String token : rpn) { if (operators.containsKey(token)) { if (stack.peek() < 2) { throw new ExpressionException("Missing parameter(s) for operator " + token); } // pop the operator's 2 parameters and add the result stack.set(stack.size() - 1, stack.peek() - 2 + 1); } else if (mainVars.containsKey(token)) { stack.set(stack.size() - 1, stack.peek() + 1); } else if (functions.containsKey(token.toUpperCase(Locale.ROOT))) { LazyFunction f = functions.get(token.toUpperCase(Locale.ROOT)); int numParams = stack.pop(); if (!f.numParamsVaries() && numParams != f.getNumParams()) { throw new ExpressionException("Function " + token + " expected " + f.getNumParams() + " parameters, got " + numParams); } if (stack.size() <= 0) { throw new ExpressionException("Too many function calls, maximum scope exceeded"); } // push the result of the function stack.set(stack.size() - 1, stack.peek() + 1); } else if ("(".equals(token)) { stack.push(0); } else { stack.set(stack.size() - 1, stack.peek() + 1); } } if (stack.size() > 1) { throw new ExpressionException("Too many unhandled function parameter lists"); } else if (stack.peek() > 1) { throw new ExpressionException("Too many numbers or variables"); } else if (stack.peek() < 1) { throw new ExpressionException("Empty expression"); } }
From source file:org.apache.tajo.engine.planner.LogicalPlanner.java
public LogicalNode visitInsert(PlanContext context, Stack<Expr> stack, Insert expr) throws PlanningException { stack.push(expr);/*w ww .j a v a 2s. c om*/ LogicalNode subQuery = super.visitInsert(context, stack, expr); stack.pop(); InsertNode insertNode = context.queryBlock.getNodeFromExpr(expr); insertNode.setOverwrite(expr.isOverwrite()); insertNode.setSubQuery(subQuery); if (expr.hasTableName()) { // INSERT (OVERWRITE) INTO TABLE ... return buildInsertIntoTablePlan(context, insertNode, expr); } else if (expr.hasLocation()) { // INSERT (OVERWRITE) INTO LOCATION ... return buildInsertIntoLocationPlan(context, insertNode, expr); } else { throw new IllegalStateException("Invalid Query"); } }
From source file:org.apache.oodt.cas.cli.construct.StdCmdLineConstructor.java
public Set<CmdLineOptionInstance> construct(CmdLineIterable<ParsedArg> parsedArgs, Set<CmdLineOption> validOptions) throws CmdLineConstructionException { HashSet<CmdLineOptionInstance> optionInstances = new HashSet<CmdLineOptionInstance>(); Stack<CmdLineOptionInstance> groupOptions = new Stack<CmdLineOptionInstance>(); for (ParsedArg arg : parsedArgs) { if (arg.getType().equals(ParsedArg.Type.OPTION)) { // check if option is a valid one CmdLineOption option = getOptionByName(arg.getName(), validOptions); if (option == null) { throw new CmdLineConstructionException("Invalid option: '" + arg.getName() + "'"); }//from w w w . j a v a2s. com // read found option CmdLineOptionInstance specifiedOption = getOption(parsedArgs, option); // Check if we are currently loading subOptions. if (!groupOptions.isEmpty()) { CmdLineOptionInstance currentGroup = groupOptions.peek(); // Check if option is NOT a subOption for current group. if (!isSubOption(currentGroup.getOption(), option)) { // Check if current group was expecting more subOptions. Set<CmdLineOption> requiredSubOptions = verifyGroupHasRequiredSubOptions(currentGroup); if (!requiredSubOptions.isEmpty()) { throw new CmdLineConstructionException( "Missing the following required subOptions for '" + currentGroup.getOption() + "': " + sortOptionsByRequiredStatus(requiredSubOptions)); } else if (currentGroup.getSubOptions().isEmpty()) { throw new CmdLineConstructionException( "Must specify a subOption for group option '" + currentGroup.getOption() + "'"); } else { // pop group and add to list of specified options. optionInstances.add(groupOptions.pop()); } // It is a sub-option... } else { // Add option to current group subOptions. currentGroup.addSubOption(specifiedOption); continue; } } if (option instanceof GroupCmdLineOption) { // Push group as current group. groupOptions.push(specifiedOption); if (!parsedArgs.hasNext()) { throw new CmdLineConstructionException( "Must specify a subOption for group option '" + specifiedOption.getOption() + "'"); } } else if (option.isSubOption()) { throw new CmdLineConstructionException( "Option '" + option + "' is a subOption, but was used at top level Option"); } else { // Option good to go. optionInstances.add(specifiedOption); } } else { throw new CmdLineConstructionException("Invalid argument: '" + arg + "'"); } } while (!groupOptions.isEmpty()) { CmdLineOptionInstance currentGroup = groupOptions.pop(); Set<CmdLineOption> requiredSubOptions = verifyGroupHasRequiredSubOptions(currentGroup); if (!requiredSubOptions.isEmpty()) { throw new CmdLineConstructionException("Missing the following required subOptions for '" + currentGroup.getOption() + "': " + sortOptionsByRequiredStatus(requiredSubOptions)); } else { optionInstances.add(currentGroup); } } return optionInstances; }
From source file:de.tudarmstadt.ukp.wikipedia.parser.mediawiki.ModularParser.java
/** * There is not much differences between links an images, so they are parsed * in a single step//ww w. j a v a2s . c o m */ private void parseImagesAndInternalLinks(SpanManager sm, List<Span> linkSpans, List<Link> links) { sm.manageList(linkSpans); int pos = -1; Stack<Integer> linkOpenTags = new Stack<Integer>(); while ((pos = sm.indexOf("[[", pos + 1)) != -1) { linkOpenTags.push(pos); } Span lastLinkSpan = new Span(sm.length() + 1, sm.length() + 1); Link.type linkType = Link.type.INTERNAL; while (!linkOpenTags.empty()) { int linkStartTag = linkOpenTags.pop(); int linkEndTag = sm.indexOf("]]", linkStartTag); if (linkEndTag == -1) { continue; } int linkOptionTag = sm.indexOf("|", linkStartTag, linkEndTag); int linkTextStart; String linkTarget; if (linkOptionTag != -1) { linkTextStart = linkOptionTag + 1; linkTarget = sm.substring(new Span(linkStartTag + 2, linkOptionTag).trim(sm)); } else { linkTextStart = linkStartTag + 2; linkTarget = sm.substring(new Span(linkStartTag + 2, linkEndTag).trim(sm)); } // is is a regular link ? if (linkTarget.indexOf(lineSeparator) != -1) { continue; } linkTarget = encodeWikistyle(linkTarget); // so it is a Link or image!!! List<String> parameters; String namespace = getLinkNameSpace(linkTarget); if (namespace != null) { if (imageIdentifers.indexOf(namespace) != -1) { if (linkOptionTag != -1) { int temp; while ((temp = sm.indexOf("|", linkTextStart, linkEndTag)) != -1) { linkTextStart = temp + 1; } parameters = tokenize(sm, linkOptionTag + 1, linkEndTag, "|"); // maybe there is an external link at the end of the // image description... if (sm.charAt(linkEndTag + 2) == ']' && sm.indexOf("[", linkTextStart, linkEndTag) != -1) { linkEndTag++; } } else { parameters = null; } linkType = Link.type.IMAGE; } else { //Link has namespace but is not image linkType = Link.type.UNKNOWN; parameters = null; } } else { if (linkType == Link.type.INTERNAL && lastLinkSpan.hits(new Span(linkStartTag, linkEndTag + 2))) { continue; } parameters = null; linkType = Link.type.INTERNAL; } Span posSpan = new Span(linkTextStart, linkEndTag).trim(sm); linkSpans.add(posSpan); Link l = new Link(null, posSpan, linkTarget, linkType, parameters); links.add(l); if (calculateSrcSpans) { l.setSrcSpan(new SrcSpan(sm.getSrcPos(linkStartTag), sm.getSrcPos(linkEndTag + 2))); } sm.delete(posSpan.getEnd(), linkEndTag + 2); sm.delete(linkStartTag, posSpan.getStart()); // removing line separators in link text int lsinlink; while ((lsinlink = sm.indexOf(lineSeparator, posSpan)) != -1) { sm.replace(lsinlink, lsinlink + lineSeparator.length(), " "); } lastLinkSpan = posSpan; } }
From source file:com.rabbitmq.client.test.performance.ScalabilityTest.java
public Results run() throws Exception { Connection con = new ConnectionFactory() { {/*from w w w .ja v a 2 s .c om*/ 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.sencha.gxt.core.rebind.XTemplateParser.java
public TemplateModel parse(String template) throws UnableToCompleteException { // look for parameters or tags (Consider combining into one pattern) TemplateModel model = new TemplateModel(); Stack<ContainerTemplateChunk> stack = new Stack<ContainerTemplateChunk>(); stack.push(model);//from w w w. j a v a2 s .c o m Matcher m = NON_LITERAL_PATTERN.matcher(template); int lastMatchEnd = 0; while (m.find()) { // range of the current non-literal int begin = m.start(), end = m.end(); String currentMatch = template.substring(begin, end); // if there was content since the last non-literal chunk, track it if (lastMatchEnd < begin) { ContentChunk c = literal(template.substring(lastMatchEnd, begin)); stack.peek().children.add(c); log(c); } // move the last match pointer lastMatchEnd = end; // tpl tag starting Matcher tagOpenMatch = TAG_PATTERN.matcher(currentMatch); if (tagOpenMatch.matches()) { ControlChunk c = new ControlChunk(); c.controls = new HashMap<String, String>(); String attrs = tagOpenMatch.group(1).trim(); Matcher attrMatcher = ATTR_PATTERN.matcher(attrs); while (attrMatcher.find()) { // should be if or for String key = attrMatcher.group(1); // must be html-decoded String encodedValue = attrMatcher.group(2) == null ? attrMatcher.group(3) : attrMatcher.group(2); String value = StringEscapeUtils.unescapeXml(encodedValue); c.controls.put(key, value); } stack.peek().children.add(c); stack.push(c); log(c); continue; } // tpl tag ending Matcher tagCloseMatch = TAG_CLOSE_PATTERN.matcher(currentMatch); if (tagCloseMatch.matches()) { TemplateChunk c; try { c = stack.pop(); } catch (EmptyStackException ex) { logger.log(Type.ERROR, "Too many </tpl> tags"); throw new UnableToCompleteException(); } log(c); continue; } // reference (code) Matcher codeMatch = INVOKE_PATTERN.matcher(currentMatch); if (codeMatch.matches()) { ContentChunk c = new ContentChunk(); c.type = ContentType.CODE; c.content = codeMatch.group(1); stack.peek().children.add(c); log(c); continue; } // reference (param) Matcher paramMatch = PARAM_PATTERN.matcher(currentMatch); if (paramMatch.matches()) { ContentChunk c = new ContentChunk(); c.type = ContentType.REFERENCE; c.content = paramMatch.group(1); stack.peek().children.add(c); log(c); continue; } } // handle trailing content if (lastMatchEnd < template.length()) { ContentChunk c = literal(template.substring(lastMatchEnd)); log(c); model.children.add(c); } if (model != stack.peek()) { logger.log(Type.ERROR, "Too few </tpl> tags"); throw new UnableToCompleteException(); } return model; }
From source file:net.servicefixture.fitnesse.FixtureTemplateCreator.java
/** * Adds the tablerow to the test table.//from www . java 2 s .c o m * @param ancestors * * @param string * @param returnType */ private void addTableRowsForType(Stack<Class> ancestors, String prefix, Class type, boolean isSetRow) { if (ReflectionUtils.isLowestLevelType(type)) { writeLine(prefix + "|" + (isSetRow ? ReflectionUtils.getDefaultValue(type) : "") + "|"); return; } //If the type is an abstract type, generate rows for all of its subclasses. if (ReflectionUtils.isAbstractType(type)) { Class[] subClasses = ReflectionUtils.findSubClasses(type); for (int i = 0; i < subClasses.length; i++) { if (isSetRow) { writeLine(prefix + "|" + TreeParser.CLASS_TYPE_PREFIX + subClasses[i].getName() + TreeParser.CLASS_TYPE_SUFFIX + "|"); } else { writeLine(prefix + ".class.name|" + subClasses[i].getName() + "|"); } addTableRowsForType(ancestors, prefix, subClasses[i], isSetRow); } return; } //Handles regular type Map<String, Class> attributes = ReflectionUtils.getAttributes(type); for (Iterator iter = attributes.keySet().iterator(); iter.hasNext();) { String attributeName = (String) iter.next(); Class attributeType = (Class) attributes.get(attributeName); if (ReflectionUtils.isLowestLevelType(attributeType)) { //size is the reserved word for common jexl library, call the getter method instead. if ("size".equals(attributeName) && !isSetRow) { attributeName = "getSize()"; } writeLine(prefix + "." + attributeName + "|" + (isSetRow ? ReflectionUtils.getDefaultValue(attributeType) : "") + "|"); } else { if (ancestors.contains(attributeType)) { writeLine(prefix + "." + attributeName + "|" + (isSetRow ? "${nil.object}" : "") + "|"); } else { ancestors.push(attributeType); addTableRowsForType(ancestors, prefix + "." + attributeName, attributeType, isSetRow); ancestors.pop(); } } } }
From source file:com.aurel.track.admin.customize.category.filter.tree.design.TreeFilterSaverBL.java
/** * Transform a list of QueryExpressions with parenthesis into a tree * @param expressionList//from w w w. ja v a 2s . co m * @param node * @param operationStack */ public static QNode transformExpressionListToTree(List<FieldExpressionInTreeTO> expressionList, Stack<QNode> operationStack) throws Exception { if (expressionList == null || expressionList.isEmpty()) { return null; } QNode root = new QNode(); root.setType(QNode.AND); operationStack.push(root); if (expressionList != null) { Iterator<FieldExpressionInTreeTO> iterator = expressionList.iterator(); boolean first = true; while (iterator.hasNext()) { FieldExpressionInTreeTO fieldExpressionInTree = iterator.next(); if (operationStack.isEmpty()) { throw new Exception("admin.customize.queryFilter.err.closedGtOpened"); } QNode peekNode = operationStack.peek(); if (!first) { //the first operation (the hidden one) is not significant Integer operation = fieldExpressionInTree.getSelectedOperation(); if (operation != null) { if (peekNode.isTypeAlreadySet()) { if (!equalOperation(peekNode, operation)) { throw new Exception( "admin.customize.queryFilter.err.differentOperationsInParenthesis"); } } else { //in the outermost level the second filter expression sets the operation, //inside internal parenthesis the first one setOperation(peekNode, operation.intValue()); peekNode.setTypeAlreadySet(true); } } } else { first = false; if (!iterator.hasNext()) { //it can be also AND, it doesn't have importance because it is a single expression peekNode.setType(QNode.OR); } } int leftParenthesis = fieldExpressionInTree.getParenthesisOpen(); for (int i = 0; i < leftParenthesis; i++) { //unknown node type (AND or OR) QNode qNode = new QNode(); peekNode.addChild(qNode); operationStack.push(qNode); peekNode = operationStack.peek(); } peekNode.addChild(new QNodeExpression(fieldExpressionInTree)); int rightParenthesis = fieldExpressionInTree.getParenthesisClosed(); if (rightParenthesis > 0) { for (int i = 0; i < rightParenthesis; i++) { if (operationStack.isEmpty()) { throw new Exception("admin.customize.queryFilter.err.closedGtOpened"); } operationStack.pop(); } } } //pop the root if (operationStack.isEmpty()) { throw new Exception("admin.customize.queryFilter.err.closedGtOpened"); } operationStack.pop(); if (!operationStack.isEmpty()) { throw new Exception("admin.customize.queryFilter.err.closedLtOpened"); } } return root; }