List of usage examples for java.util Stack pop
public synchronized E pop()
From source file:com.abstratt.mdd.internal.frontend.textuml.TextUMLCompiler.java
/** * Given a position in a compilation unit, finds the contextual namespace. * //from w w w . jav a2 s .c om * @param toParse source of compilation unit * @param line line number, starting from 1 * @param col column number, starting from 1 * @return the name of the contextual namespace */ public String findNamespace(String toParse, final int line, final int col) { Token token = findTokenAt(toParse, line, col, false, true); if (token == null) return null; final Stack<String> segments = new Stack<String>(); for (Node current = token; current != null; current = current.parent()) { current.apply(new AnalysisAdapter() { @Override public void caseAStart(AStart node) { segments.push(TextUMLCore.getSourceMiner().getQualifiedIdentifier( ((APackageHeading) node.getPackageHeading()).getQualifiedIdentifier())); } public void caseASubNamespace(ASubNamespace node) { segments.push(TextUMLCore.getSourceMiner() .getQualifiedIdentifier(((APackageHeading) node.getPackageHeading()))); } @Override public void caseAClassDef(AClassDef node) { segments.push(((AClassHeader) node.getClassHeader()).getIdentifier().getText()); } @Override public void caseAStereotypeDef(AStereotypeDef node) { segments.push(((AStereotypeDefHeader) node.getStereotypeDefHeader()).getIdentifier().getText()); } @Override public void caseAAssociationDef(AAssociationDef node) { final String associationName = ((AAssociationHeader) node.getAssociationHeader()) .getIdentifier().getText(); if (associationName.length() > 0) segments.push(associationName); } }); } if (segments.isEmpty()) return null; StringBuffer result = new StringBuffer(); while (!segments.isEmpty()) { result.append(segments.pop()); result.append(NamedElement.SEPARATOR); } result.delete((result.length() - NamedElement.SEPARATOR.length()), result.length()); return result.toString(); }
From source file:org.netxilia.server.rest.HomeResource.java
/** * build the HTML tags for a tree like view * /*from w w w.j a v a2 s .c om*/ * @param foldersSheet * @param treeview * @throws NetxiliaBusinessException * @throws NetxiliaResourceException */ private DefaultMutableTreeNode buildWorkbookTree(IWorkbook workbook, ISheet foldersSheet, Set<SheetFullName> sheetNames) throws NetxiliaResourceException, NetxiliaBusinessException { DefaultMutableTreeNode workbookNode = new DefaultMutableTreeNode( new TreeViewData(workbook.getId().getKey(), workbook.getName(), "workbook")); Stack<DefaultMutableTreeNode> stockNodes = new Stack<DefaultMutableTreeNode>(); stockNodes.push(workbookNode); Set<SheetFullName> alreadyInsertedSheets = new HashSet<SheetFullName>(); if (foldersSheet != null) { Matrix<CellData> folderCells = foldersSheet.receiveCells(AreaReference.ALL).getNonBlocking(); for (List<CellData> row : folderCells.getRows()) { int level = 0; String nodeName = null; for (CellData cell : row) { if (cell.getValue() != null) { nodeName = cell.getValue().getStringValue(); if (nodeName != null && nodeName.length() > 0) { level = cell.getReference().getColumnIndex(); break; } } } if (nodeName == null) { // empty line - ignored continue; } // first level for folders is 1 (under the root node) level = level + 1; SheetFullName sheetName = new SheetFullName(workbook.getName(), nodeName); boolean isSheet = sheetNames.contains(sheetName); if (isSheet) { alreadyInsertedSheets.add(sheetName); } DefaultMutableTreeNode crt = new DefaultMutableTreeNode(new TreeViewData(sheetName.toString(), sheetName.getSheetName(), isSheet ? "sheet" : "folder")); while (!stockNodes.empty()) { DefaultMutableTreeNode node = stockNodes.peek(); if (level > node.getLevel()) { // make sure is the direct child node.add(crt); break; } stockNodes.pop(); } stockNodes.push(crt); } } // add the sheets not already added for (SheetFullName sheetName : sheetNames) { if (alreadyInsertedSheets.contains(sheetName)) { continue; } DefaultMutableTreeNode sheetNode = new DefaultMutableTreeNode( new TreeViewData(sheetName.toString(), sheetName.getSheetName(), "sheet")); workbookNode.add(sheetNode); } return workbookNode; }
From source file:org.apache.fop.layoutmgr.BlockContainerLayoutManager.java
/** {@inheritDoc} */ @Override/*from w w w. j a v a 2 s . c om*/ public List getNextKnuthElements(LayoutContext context, int alignment, Stack lmStack, Position restartPosition, LayoutManager restartAtLM) { resetSpaces(); // special treatment for position="absolute|fixed" if (isAbsoluteOrFixed()) { return getNextKnuthElementsAbsolute(context); } boolean isRestart = (lmStack != null); boolean emptyStack = (!isRestart || lmStack.isEmpty()); setupAreaDimensions(context); List<ListElement> returnedList; List<ListElement> contentList = new LinkedList<ListElement>(); List<ListElement> returnList = new LinkedList<ListElement>(); if (!breakBeforeServed(context, returnList)) { return returnList; } addFirstVisibleMarks(returnList, context, alignment); if (autoHeight && inlineElementList) { LayoutManager curLM; // currently active LM LayoutManager prevLM = null; // previously active LM LayoutContext childLC; if (isRestart) { if (emptyStack) { assert restartAtLM != null && restartAtLM.getParent() == this; curLM = restartAtLM; } else { curLM = (LayoutManager) lmStack.pop(); } setCurrentChildLM(curLM); } else { curLM = getChildLM(); } while (curLM != null) { childLC = makeChildLayoutContext(context); // get elements from curLM if (!isRestart || emptyStack) { if (isRestart) { curLM.reset(); } returnedList = getNextChildElements(curLM, context, childLC, alignment, null, null, null); } else { returnedList = getNextChildElements(curLM, context, childLC, alignment, lmStack, restartPosition, restartAtLM); // once encountered, irrelevant for following child LMs emptyStack = true; } if (contentList.isEmpty() && childLC.isKeepWithPreviousPending()) { //Propagate keep-with-previous up from the first child context.updateKeepWithPreviousPending(childLC.getKeepWithPreviousPending()); childLC.clearKeepWithPreviousPending(); } if (returnedList.size() == 1 && ElementListUtils.startsWithForcedBreak(returnedList)) { // a descendant of this block has break-before contentList.addAll(returnedList); // "wrap" the Position inside each element // moving the elements from contentList to returnList wrapPositionElements(contentList, returnList); return returnList; } else { if (prevLM != null) { // there is a block handled by prevLM // before the one handled by curLM addInBetweenBreak(contentList, context, childLC); } contentList.addAll(returnedList); if (returnedList.isEmpty()) { //Avoid NoSuchElementException below (happens with empty blocks) continue; } if (ElementListUtils.endsWithForcedBreak(returnedList)) { // a descendant of this block has break-after if (curLM.isFinished() && !hasNextChildLM()) { // there is no other content in this block; // it's useless to add space after before a page break setFinished(true); } wrapPositionElements(contentList, returnList); return returnList; } } // propagate and clear context.updateKeepWithNextPending(childLC.getKeepWithNextPending()); childLC.clearKeepsPending(); prevLM = curLM; curLM = getChildLM(); } wrapPositionElements(contentList, returnList); } else { returnList.add(generateNonInlinedBox()); } addLastVisibleMarks(returnList, context, alignment); addKnuthElementsForBreakAfter(returnList, context); context.updateKeepWithNextPending(getKeepWithNext()); setFinished(true); return returnList; }
From source file:com.ricemap.spateDB.core.RTree.java
protected int search(Shape query_shape, ResultCollector<T> output, int start, int end) throws IOException { Prism query_mbr = query_shape.getMBR(); int resultSize = 0; // Special case for an empty tree if (height == 0) return 0; Stack<Integer> toBeSearched = new Stack<Integer>(); // Start from the given node toBeSearched.push(start);// www . ja va 2s. c o m if (start >= nodeCount) { toBeSearched.push(end); } Prism node_mbr = new Prism(); // Holds one data line from tree data Text line = new Text2(); while (!toBeSearched.isEmpty()) { int searchNumber = toBeSearched.pop(); int mbrsToTest = searchNumber == 0 ? 1 : degree; if (searchNumber < nodeCount) { long nodeOffset = NodeSize * searchNumber; structure.seek(nodeOffset); int dataOffset = structure.readInt(); for (int i = 0; i < mbrsToTest; i++) { node_mbr.readFields(structure); int lastOffset = (searchNumber + i) == nodeCount - 1 ? treeSize : structure.readInt(); if (query_mbr.contains(node_mbr)) { // The node is full contained in the query range. // Save the time and do full scan for this node toBeSearched.push(dataOffset); // Checks if this node is the last node in its level // This can be easily detected because the next node in // the level // order traversal will be the first node in the next // level // which means it will have an offset less than this // node if (lastOffset <= dataOffset) lastOffset = treeSize; toBeSearched.push(lastOffset); } else if (query_mbr.isIntersected(node_mbr)) { // Node partially overlaps with query. Go deep under // this node if (searchNumber < nonLeafNodeCount) { // Search child nodes toBeSearched.push((searchNumber + i) * degree + 1); } else { // Search all elements in this node toBeSearched.push(dataOffset); // Checks if this node is the last node in its level // This can be easily detected because the next node // in the level // order traversal will be the first node in the // next level // which means it will have an offset less than this // node if (lastOffset <= dataOffset) lastOffset = treeSize; toBeSearched.push(lastOffset); } } dataOffset = lastOffset; } } else { int firstOffset, lastOffset; // Search for data items (records) lastOffset = searchNumber; firstOffset = toBeSearched.pop(); data.seek(firstOffset + treeStartOffset); LineReader lineReader = new LineReader(data); while (firstOffset < lastOffset) { firstOffset += lineReader.readLine(line); stockObject.fromText(line); if (stockObject.isIntersected(query_shape)) { resultSize++; if (output != null) output.collect(stockObject); } } } } return resultSize; }
From source file:com.joliciel.jochre.graphics.ShapeImpl.java
@Override public TreeSet<VerticalLineSegment> getVerticalLineSegments() { if (lines == null) { WritableImageGrid mirror = this.graphicsService.getEmptyMirror(this); int[] startingPoint = this.getStartingPoint(); int startX = startingPoint[0]; int startY = startingPoint[1]; // let's imagine // 0 X 0 0 x x // x x x 0 0 x // 0 0 x x x x //as we build the shape, we keep track in memory of all of the vertical line segments that we find //and which vertical line segments touch them to the right and left //a segment can have more than one left segment (if they're broken by a white space) Stack<VerticalLineSegment> lineStack = new Stack<VerticalLineSegment>(); lines = new TreeSet<VerticalLineSegment>(); VerticalLineSegment firstLine = new VerticalLineSegment(startX, startY); lineStack.push(firstLine);// w w w . ja v a 2 s .c o m while (!lineStack.isEmpty()) { VerticalLineSegment line = lineStack.pop(); // Add this line's pixels to the mirror so that we don't touch it again. for (int rely = line.yTop; rely <= line.yBottom; rely++) mirror.setPixel(line.x, rely, 1); // extend the vertical line segment up and down from this point for (int rely = line.yTop - 1; rely >= 0; rely--) { if (this.isPixelBlack(line.x, rely, this.getJochreImage().getSeparationThreshold())) { mirror.setPixel(line.x, rely, 1); line.yTop = rely; } else { break; } } for (int rely = line.yBottom + 1; rely < this.getHeight(); rely++) { if (this.isPixelBlack(line.x, rely, this.getJochreImage().getSeparationThreshold())) { mirror.setPixel(line.x, rely, 1); line.yBottom = rely; } else { break; } } //LOG.debug("Adding line x = " + line.x + ", top = " + line.yTop + ", bottom = " + line.yBottom); lines.add(line); // find any points to the left of this segment int relx = line.x - 1; VerticalLineSegment leftLine = null; for (int rely = line.yTop - 1; rely <= line.yBottom + 1; rely++) { if (this.isPixelBlack(relx, rely, this.getJochreImage().getSeparationThreshold())) { if (leftLine == null) { leftLine = new VerticalLineSegment(relx, rely); } else { leftLine.yBottom = rely; } } else { if (leftLine != null) { if (mirror.getPixel(relx, leftLine.yTop) > 0) { // if we already found this line before - let's find it again. for (VerticalLineSegment lineSegment : lines) { if (lineSegment.x == relx) { if (lineSegment.yTop <= leftLine.yTop && leftLine.yTop <= lineSegment.yBottom) { leftLine = lineSegment; break; } } } } else if (lineStack.contains(leftLine)) { leftLine = lineStack.get(lineStack.indexOf(leftLine)); } else { lineStack.push(leftLine); } line.leftSegments.add(leftLine); leftLine = null; } } } // next rely // add the last line if (leftLine != null) { if (mirror.getPixel(relx, leftLine.yTop) > 0) { // if we already found this line before - let's find it again. for (VerticalLineSegment lineSegment : lines) { if (lineSegment.x == relx) { if (lineSegment.yTop <= leftLine.yTop && leftLine.yTop <= lineSegment.yBottom) { leftLine = lineSegment; break; } } } } else if (lineStack.contains(leftLine)) { leftLine = lineStack.get(lineStack.indexOf(leftLine)); } else { lineStack.push(leftLine); } line.leftSegments.add(leftLine); } // find any points to the right of this segment relx = line.x + 1; VerticalLineSegment rightLine = null; for (int rely = line.yTop - 1; rely <= line.yBottom + 1; rely++) { if (this.isPixelBlack(relx, rely, this.getJochreImage().getSeparationThreshold())) { if (rightLine == null) { rightLine = new VerticalLineSegment(relx, rely); } else { rightLine.yBottom = rely; } } else { if (rightLine != null) { if (mirror.getPixel(relx, rightLine.yTop) > 0) { // if we already found this line before - let's find it again. for (VerticalLineSegment lineSegment : lines) { if (lineSegment.x == relx) { if (lineSegment.yTop <= rightLine.yTop && rightLine.yTop <= lineSegment.yBottom) { rightLine = lineSegment; break; } } } } else if (lineStack.contains(rightLine)) { rightLine = lineStack.get(lineStack.indexOf(rightLine)); } else { lineStack.push(rightLine); } line.rightSegments.add(rightLine); rightLine = null; } } } // next rely // add the last line if (rightLine != null) { if (mirror.getPixel(relx, rightLine.yTop) > 0) { // if we already found this line before - let's find it again. for (VerticalLineSegment lineSegment : lines) { if (lineSegment.x == relx) { if (lineSegment.yTop <= rightLine.yTop && rightLine.yTop <= lineSegment.yBottom) { rightLine = lineSegment; break; } } } } else if (lineStack.contains(rightLine)) { rightLine = lineStack.get(lineStack.indexOf(rightLine)); } else { lineStack.push(rightLine); } line.rightSegments.add(rightLine); } } // next line on stack LOG.debug("Found " + lines.size() + " lines"); } return lines; }
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 ww w.ja va2s.co 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; }
From source file:com.webcohesion.ofx4j.io.nanoxml.TestNanoXMLOFXReader.java
private DefaultHandler getNewDefaultHandler(final Map<String, List<String>> headers, final Stack<Map<String, List<Object>>> aggregateStack) { return new DefaultHandler() { @Override/*w w w .j av a 2 s . c o m*/ public void onHeader(String name, String value) { LOG.debug(name + ":" + value); List<String> list = headers.get(name); if (list == null) { list = new ArrayList<String>(); headers.put(name, list); } list.add(value); } @Override public void onElement(String name, String value) { LOG.debug("onElement " + aggregateStack.size()); char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + name + "=" + value); List<Object> list = aggregateStack.peek().get(name); if (list == null) { list = new ArrayList<Object>(); aggregateStack.peek().put(name, list); } list.add(value); } @Override public void startAggregate(String aggregateName) { LOG.debug("startAggregate " + aggregateName + " " + aggregateStack.size()); char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + aggregateName + " {"); TreeMap<String, List<Object>> aggregate = new TreeMap<String, List<Object>>(); List<Object> list = aggregateStack.peek().get(aggregateName); if (list == null) { list = new ArrayList<Object>(); aggregateStack.peek().put(aggregateName, list); } list.add(aggregate); aggregateStack.push(aggregate); } @Override public void endAggregate(String aggregateName) { LOG.debug("endAggregate " + aggregateName + " " + aggregateStack.size()); aggregateStack.pop(); char[] tabs = new char[aggregateStack.size() * 2]; Arrays.fill(tabs, ' '); LOG.debug(new String(tabs) + "}"); } }; }
From source file:com.ricemap.spateDB.core.RTree.java
/** * Searches the RTree starting from the given start position. This is either * a node number or offset of an element. If it's a node number, it performs * the search in the subtree rooted at this node. If it's an offset number, * it searches only the object found there. It is assumed that the * openQuery() has been called before this function and that endQuery() will * be called afterwards.// ww w . j a v a2 s . c o m * * @param query_mbr * @param output * @param start * - where to start searching * @param end * - where to end searching. Only used when start is an offset of * an object. * @return * @throws IOException */ protected int searchColumnar(Shape query_shape, ResultCollector<Writable> output, int start, int end, String field) throws IOException { if (output == null) { throw new RuntimeException("Output is NULL"); } //build search field int fieldOffset = 0; int fieldSize = -1; FIELD_TYPE fieldType = FIELD_TYPE.NULL; //get fields Field[] fields = stockObject.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].getName().equals(field)) { if (fields[i].getType().equals(Integer.TYPE)) { fieldSize = 4; fieldType = FIELD_TYPE.Integer; } else if (fields[i].getType().equals(Long.TYPE)) { fieldSize = 8; fieldType = FIELD_TYPE.Long; } else if (fields[i].getType().equals(Double.TYPE)) { fieldSize = 8; fieldType = FIELD_TYPE.Double; } else { //throw new RuntimeException("Unsupported type: " + fields[i].getType()); } break; } else { if (fields[i].getType().equals(Integer.TYPE)) { fieldOffset += elementCount * 4; } else if (fields[i].getType().equals(Long.TYPE) || fields[i].getType().equals(Double.TYPE)) { fieldOffset += elementCount * 8; } else { //throw new RuntimeException("Unsupported type: " + fields[i].getType()); } } } Prism query_mbr = query_shape.getMBR(); int resultSize = 0; // Special case for an empty tree if (height == 0) return 0; Stack<Integer> toBeSearched = new Stack<Integer>(); // Start from the given node toBeSearched.push(start); if (start >= nodeCount) { toBeSearched.push(end); } Prism node_mbr = new Prism(); // Holds one data line from tree data Text line = new Text2(); while (!toBeSearched.isEmpty()) { int searchNumber = toBeSearched.pop(); int mbrsToTest = searchNumber == 0 ? 1 : degree; if (searchNumber < nodeCount) { long nodeOffset = NodeSize * searchNumber; structure.seek(nodeOffset); int dataOffset = structure.readInt(); for (int i = 0; i < mbrsToTest; i++) { node_mbr.readFields(structure); int lastOffset = (searchNumber + i) == nodeCount - 1 ? elementCount - 1 : structure.readInt(); if (query_mbr.contains(node_mbr)) { // The node is full contained in the query range. // Save the time and do full scan for this node // Checks if this node is the last node in its level // This can be easily detected because the next node in // the level // order traversal will be the first node in the next // level // which means it will have an offset less than this // node if (lastOffset <= dataOffset) lastOffset = elementCount; data.seek(treeStartOffset + TreeHeaderSize + nodeCount * NodeSize + elementCount * IndexUnitSize + fieldOffset + dataOffset * fieldSize); for (int j = 0; j < lastOffset - dataOffset; j++) { switch (fieldType) { case Integer: output.collect(new IntWritable(data.readInt())); break; case Long: output.collect(new LongWritable(data.readLong())); break; case Double: output.collect(new DoubleWritable(data.readDouble())); break; default: output.collect( new Point3d(data.readDouble(), data.readDouble(), data.readDouble())); break; } resultSize++; } } else if (query_mbr.isIntersected(node_mbr)) { // Node partially overlaps with query. Go deep under // this node if (searchNumber < nonLeafNodeCount) { // Search child nodes toBeSearched.push((searchNumber + i) * degree + 1); } else { // Search all elements in this node //toBeSearched.push(dataOffset); // Checks if this node is the last node in its level // This can be easily detected because the next node // in the level // order traversal will be the first node in the // next level // which means it will have an offset less than this // node if (lastOffset <= dataOffset) lastOffset = elementCount; //toBeSearched.push(lastOffset); data.seek(treeStartOffset + TreeHeaderSize + nodeCount * NodeSize + dataOffset * IndexUnitSize); boolean report[] = new boolean[lastOffset - dataOffset]; Point3d point = new Point3d(); for (int j = 0; j < lastOffset - dataOffset; j++) { point.t = data.readDouble(); point.x = data.readDouble(); point.y = data.readDouble(); if (point.isIntersected(query_shape)) { report[j] = true; } else report[j] = false; } data.seek(treeStartOffset + TreeHeaderSize + nodeCount * NodeSize + elementCount * IndexUnitSize + fieldOffset + dataOffset * fieldSize); for (int j = 0; j < lastOffset - dataOffset; j++) { if (report[j]) { switch (fieldType) { case Integer: output.collect(new IntWritable(data.readInt())); break; case Long: output.collect(new LongWritable(data.readLong())); break; case Double: output.collect(new DoubleWritable(data.readDouble())); break; default: output.collect(new Point3d(data.readDouble(), data.readDouble(), data.readDouble())); break; } resultSize++; } } } } dataOffset = lastOffset; } } else { LOG.error("searchNumber > nodeCount, something is wrong"); int firstOffset, lastOffset; // Search for data items (records) lastOffset = searchNumber; firstOffset = toBeSearched.pop(); data.seek(firstOffset + treeStartOffset); LineReader lineReader = new LineReader(data); while (firstOffset < lastOffset) { firstOffset += lineReader.readLine(line); stockObject.fromText(line); if (stockObject.isIntersected(query_shape)) { resultSize++; if (output != null) output.collect(stockObject); } } } } return resultSize; }
From source file:ch.zhaw.icclab.tnova.expressionsolver.OTFlyEval.java
String evaluateExpression(String exp, Stack<Double> param, double threshold) { String[] literals = exp.split("(?!^)"); //array of characters String tempVal = ""; Stack<String> sTable = new Stack<String>(); for (int i = 0; i < literals.length; i++) { if (literals[i].equals("(")) { if (tempVal.trim().length() != 0) { sTable.push("fn " + tempVal.trim()); logger.info("pushed function [" + tempVal.trim() + "] into stack."); } else { //parsing error this stage is not allowed }//ww w .j a va 2 s .co m tempVal = ""; } else if (literals[i].equals(",")) { if (tempVal.trim().length() != 0) { sTable.push("pm " + tempVal.trim()); logger.info("pushed parameter [" + tempVal.trim() + "] into stack."); } else { //parsing error this stage is not allowed } tempVal = ""; } else if (literals[i].equals(")")) { if (tempVal.trim().length() != 0) { sTable.push("pm " + tempVal.trim()); logger.info("pushed parameter [" + tempVal.trim() + "] into stack."); } logger.info("Proceeding for partial stack evaluation."); tempVal = ""; //proceed to partial evaluation try { String output = partialEvaluation(sTable, param, threshold); //push the result back into stack as a literal sTable.push("pm " + output); logger.info("pushed parameter [" + output + "] into stack for further processing."); } catch (EmptyStackException emex) { logger.warn("Malformed expression and value set received."); if (App.showExceptions) emex.printStackTrace(); return null; } } else tempVal += literals[i]; } //if stack has more than 1 element error, else the only element is the result String result = ""; if (sTable.size() != 1) { //error result = null; } else { result = sTable.pop().split(" ")[1]; } return result; }
From source file:org.sakaiproject.poll.service.impl.PollListManagerImpl.java
@SuppressWarnings("unchecked") public String archive(String siteId, Document doc, Stack stack, String archivePath, List attachments) { log.debug("archive: poll " + siteId); // prepare the buffer for the results log StringBuilder results = new StringBuilder(); // String assignRef = assignmentReference(siteId, SiteService.MAIN_CONTAINER); results.append("archiving " + getLabel() + " context " + Entity.SEPARATOR + siteId + Entity.SEPARATOR + SiteService.MAIN_CONTAINER + ".\n"); // start with an element with our very own (service) name Element element = doc.createElement(PollListManager.class.getName()); ((Element) stack.peek()).appendChild(element); stack.push(element);// w ww. j a va2 s . c o m List pollsList = findAllPolls(siteId); log.debug("got list of " + pollsList.size() + " polls"); for (int i = 0; pollsList.size() > i; i++) { try { Poll poll = (Poll) pollsList.get(i); log.info("got poll " + poll.getId()); // archive this assignment Element el = poll.toXml(doc, stack); // since we aren't archiving votes too, don't worry about archiving the // soft-deleted options -- only "visible". List options = getVisibleOptionsForPoll(poll.getPollId()); for (int q = 0; options.size() > q; q++) { Option opt = (Option) options.get(q); Element el2 = PollUtil.optionToXml(opt, doc, stack); el.appendChild(el2); } element.appendChild(el); } catch (Exception e) { e.printStackTrace(); } } // while stack.pop(); return results.toString(); }