List of usage examples for java.util Stack Stack
public Stack()
From source file:edu.umn.cs.spatialHadoop.core.RectangleNN.java
/** * Directly unions the given list of polygons using a safe method that tries * to avoid geometry exceptions. First, it tries the buffer(0) method. It it * fails, it falls back to the tradition union method. * @param polys/*from ww w. j av a 2s . c om*/ * @param progress * @return * @throws IOException */ public static Geometry safeUnion(List<Geometry> polys, Progressable progress) throws IOException { if (polys.size() == 1) return polys.get(0); Stack<Integer> rangeStarts = new Stack<Integer>(); Stack<Integer> rangeEnds = new Stack<Integer>(); rangeStarts.push(0); rangeEnds.push(polys.size()); List<Geometry> results = new ArrayList<Geometry>(); final GeometryFactory geomFactory = new GeometryFactory(); // Minimum range size that is broken into two subranges final int MinimumThreshold = 10; // Progress numerator and denominator int progressNum = 0, progressDen = polys.size(); while (!rangeStarts.isEmpty()) { int rangeStart = rangeStarts.pop(); int rangeEnd = rangeEnds.pop(); try { // Union using the buffer operation GeometryCollection rangeInOne = (GeometryCollection) geomFactory .buildGeometry(polys.subList(rangeStart, rangeEnd)); Geometry rangeUnion = rangeInOne.buffer(0); results.add(rangeUnion); progressNum += rangeEnd - rangeStart; } catch (Exception e) { LOG.warn("Exception in merging " + (rangeEnd - rangeStart) + " polygons", e); // Fall back to the union operation if (rangeEnd - rangeStart < MinimumThreshold) { LOG.info("Error in union " + rangeStart + "-" + rangeEnd); // Do the union directly using the old method (union) Geometry rangeUnion = geomFactory.buildGeometry(new ArrayList<Geometry>()); for (int i = rangeStart; i < rangeEnd; i++) { LOG.info(polys.get(i).toText()); } for (int i = rangeStart; i < rangeEnd; i++) { try { rangeUnion = rangeUnion.union(polys.get(i)); } catch (Exception e1) { // Log the error and skip it to allow the method to finish LOG.error("Error computing union", e); } } results.add(rangeUnion); progressNum += rangeEnd - rangeStart; } else { // Further break the range into two subranges rangeStarts.push(rangeStart); rangeEnds.push((rangeStart + rangeEnd) / 2); rangeStarts.push((rangeStart + rangeEnd) / 2); rangeEnds.push(rangeEnd); progressDen++; } } if (progress != null) progress.progress(progressNum / (float) progressDen); } // Finally, union all the results Geometry finalResult = results.remove(results.size() - 1); while (!results.isEmpty()) { try { finalResult = finalResult.union(results.remove(results.size() - 1)); } catch (Exception e) { LOG.error("Error in union", e); } progressNum++; progress.progress(progressNum / (float) progressDen); } return finalResult; }
From source file:org.rdv.viz.chart.ChartPanel.java
/** * Constructs a JFreeChart panel./* ww w . j av a2 s .c o m*/ * * @param chart the chart. * @param width the preferred width of the panel. * @param height the preferred height of the panel. * @param minimumDrawWidth the minimum drawing width. * @param minimumDrawHeight the minimum drawing height. * @param maximumDrawWidth the maximum drawing width. * @param maximumDrawHeight the maximum drawing height. * @param useBuffer a flag that indicates whether to use the off-screen * buffer to improve performance (at the expense of * memory). * @param properties a flag indicating whether or not the chart property * editor should be available via the popup menu. * @param save a flag indicating whether or not save options should be * available via the popup menu. * @param print a flag indicating whether or not the print option * should be available via the popup menu. * @param zoom a flag indicating whether or not zoom options should be * added to the popup menu. * @param tooltips a flag indicating whether or not tooltips should be * enabled for the chart. */ public ChartPanel(JFreeChart chart, int width, int height, int minimumDrawWidth, int minimumDrawHeight, int maximumDrawWidth, int maximumDrawHeight, boolean useBuffer, boolean properties, boolean save, boolean print, boolean zoom, boolean tooltips) { this.setChart(chart); this.chartMouseListeners = new EventListenerList(); this.info = new ChartRenderingInfo(); setPreferredSize(new Dimension(width, height)); this.useBuffer = useBuffer; this.refreshBuffer = false; this.minimumDrawWidth = minimumDrawWidth; this.minimumDrawHeight = minimumDrawHeight; this.maximumDrawWidth = maximumDrawWidth; this.maximumDrawHeight = maximumDrawHeight; this.zoomTriggerDistance = DEFAULT_ZOOM_TRIGGER_DISTANCE; // set up popup menu... this.popup = null; if (properties || save || print || zoom) { this.popup = createPopupMenu(properties, save, print, zoom); } enableEvents(AWTEvent.MOUSE_EVENT_MASK); enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK); setDisplayToolTips(tooltips); addMouseListener(this); addMouseMotionListener(this); this.defaultDirectoryForSaveAs = null; this.enforceFileExtensions = true; // initialize ChartPanel-specific tool tip delays with // values the from ToolTipManager.sharedInstance() ToolTipManager ttm = ToolTipManager.sharedInstance(); this.ownToolTipInitialDelay = ttm.getInitialDelay(); this.ownToolTipDismissDelay = ttm.getDismissDelay(); this.ownToolTipReshowDelay = ttm.getReshowDelay(); this.zoomAroundAnchor = false; this.rangeHistory = new Stack<Range>(); }
From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java
/** * Perform a selection query that retrieves all points in the given range. * The range is specified in the two-dimensional array positions. * @param in// ww w. ja v a 2 s.c om * @param query_mbr * @param output * @return number of matched records * @throws IOException */ public static int selectionQuery(FSDataInputStream in, Rectangle query_mbr, ResultCollector<PointValue> output) throws IOException { long treeStartPosition = in.getPos(); int numOfResults = 0; int resolution = in.readInt(); short fillValue = in.readShort(); int cardinality = in.readInt(); long[] timestamps = new long[cardinality]; for (int i = 0; i < cardinality; i++) timestamps[i] = in.readLong(); Vector<Integer> selectedStarts = new Vector<Integer>(); Vector<Integer> selectedEnds = new Vector<Integer>(); StockQuadTree stockQuadTree = getOrCreateStockQuadTree(resolution); // Nodes to be searched. Contains node positions in the array of nodes Stack<Integer> nodes_2b_searched = new Stack<Integer>(); nodes_2b_searched.add(0); // Root node (ID=1) Rectangle node_mbr = new Rectangle(); while (!nodes_2b_searched.isEmpty()) { int node_pos = nodes_2b_searched.pop(); stockQuadTree.getNodeMBR(node_pos, node_mbr); if (query_mbr.contains(node_mbr)) { // Add this node to the selection list and stop this branch if (!selectedEnds.isEmpty() && selectedEnds.lastElement() == stockQuadTree.nodesStartPosition[node_pos]) { // Merge with an adjacent range selectedEnds.set(selectedEnds.size() - 1, stockQuadTree.nodesEndPosition[node_pos]); } else { // add a new range selectedStarts.add(stockQuadTree.nodesStartPosition[node_pos]); selectedEnds.add(stockQuadTree.nodesEndPosition[node_pos]); } numOfResults += stockQuadTree.nodesEndPosition[node_pos] - stockQuadTree.nodesStartPosition[node_pos]; } else if (query_mbr.intersects(node_mbr)) { int first_child_id = stockQuadTree.nodesID[node_pos] * 4 + 0; int first_child_pos = Arrays.binarySearch(stockQuadTree.nodesID, first_child_id); if (first_child_pos < 0) { // No children. Hit a leaf node // Scan and add matching points only java.awt.Point record_coords = new Point(); for (int record_pos = stockQuadTree.nodesStartPosition[node_pos]; record_pos < stockQuadTree.nodesEndPosition[node_pos]; record_pos++) { stockQuadTree.getRecordCoords(record_pos, record_coords); if (query_mbr.contains(record_coords)) { // matched a record. if (!selectedEnds.isEmpty() && selectedEnds.lastElement() == record_pos) { // Merge with an adjacent range selectedEnds.set(selectedEnds.size() - 1, record_pos + 1); } else { // Add a new range of unit width selectedStarts.add(record_pos); selectedEnds.add(record_pos + 1); } numOfResults++; } } } else { // Non-leaf node. Add all children to the list of nodes to search // Add in reverse order to the stack so that results come in sorted order nodes_2b_searched.add(first_child_pos + 3); nodes_2b_searched.add(first_child_pos + 2); nodes_2b_searched.add(first_child_pos + 1); nodes_2b_searched.add(first_child_pos + 0); } } } if (output != null) { PointValue returnValue = new PointValue(); long dataStartPosition = treeStartPosition + getValuesStartOffset(cardinality); // Return all values in the selected ranges for (int iRange = 0; iRange < selectedStarts.size(); iRange++) { int treeStart = selectedStarts.get(iRange); int treeEnd = selectedEnds.get(iRange); long startPosition = dataStartPosition + selectedStarts.get(iRange) * cardinality * 2; in.seek(startPosition); for (int treePos = treeStart; treePos < treeEnd; treePos++) { // Retrieve the coords for the point at treePos stockQuadTree.getRecordCoords(treePos, returnValue); // Read all entries at current position for (int iValue = 0; iValue < cardinality; iValue++) { short value = in.readShort(); if (value != fillValue) { returnValue.value = value; returnValue.timestamp = timestamps[iValue]; output.collect(returnValue); } } } } } return numOfResults; }
From source file:com.gargoylesoftware.htmlunit.javascript.host.xml.XMLHttpRequest.java
/** * Sends the specified content to the server in an HTTP request and receives the response. * @param content the body of the message being sent with the request *//*from w ww .ja v a 2s. c o m*/ @JsxFunction public void send(final Object content) { if (webRequest_ == null) { return; } prepareRequest(content); 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 { if (getBrowserVersion().hasFeature(XHR_FIRE_STATE_OPENED_AGAIN_IN_ASYNC_MODE)) { // quite strange but IE and FF seem both to fire state loading twice // in async mode (at least with HTML of the unit tests) setState(OPENED, Context.getCurrentContext()); } // 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:net.rptools.maptool.client.MapToolLineParser.java
public String parseLine(MapToolVariableResolver res, Token tokenInContext, String line, MapToolMacroContext context) throws ParserException { if (line == null) { return ""; }//from w ww . ja v a 2s . co m line = line.trim(); if (line.length() == 0) { return ""; } Stack<Token> contextTokenStack = new Stack<Token>(); enterContext(context); MapToolVariableResolver resolver = null; boolean resolverInitialized = false; String opts = null; String roll = null; try { // Keep the same variable context for this line resolver = (res == null) ? new MapToolVariableResolver(tokenInContext) : res; resolverInitialized = resolver.initialize(); StringBuilder builder = new StringBuilder(); int start = 0; List<InlineRollMatch> matches = this.locateInlineRolls(line); for (InlineRollMatch match : matches) { builder.append(line.substring(start, match.getStart())); // add everything before the roll start = match.getEnd() + 1; // These variables will hold data extracted from the roll options. Output output; if (MapTool.useToolTipsForUnformatedRolls()) { output = Output.TOOLTIP; } else { output = Output.EXPANDED; } String text = null; // used by the T option HashSet<String> outputOpts = new HashSet<String>(); OutputLoc outputTo = OutputLoc.CHAT; LoopType loopType = LoopType.NO_LOOP; int loopStart = 0, loopEnd = 0, loopStep = 1; int loopCount = 0; String loopSep = null; String loopVar = null, loopCondition = null; List<String> foreachList = new ArrayList<String>(); BranchType branchType = BranchType.NO_BRANCH; Object branchCondition = null; CodeType codeType = CodeType.NO_CODE; String macroName = null; String frameName = null; String frameOpts = null; if (match.getMatch().startsWith("[")) { opts = match.getOpt(); roll = match.getRoll(); if (opts != null) { // Turn the opts string into a list of OptionInfo objects. List<OptionInfo> optionList = null; try { optionList = getRollOptionList(opts); } catch (RollOptionException roe) { throw doError(roe.msg, opts, roll); } // Scan the roll options and prepare variables for later use for (OptionInfo option : optionList) { String error = null; /* * TODO: If you're adding a new option, add a new * case here to collect info from the parameters. If * your option uses parameters, use the * option.getXxxParam() methods to get the text or * parsed values of the parameters. */ switch (option.optionType) { /////////////////////////////////////////////////// // OUTPUT FORMAT OPTIONS /////////////////////////////////////////////////// case HIDDEN: output = Output.NONE; break; case RESULT: output = Output.RESULT; break; case EXPANDED: output = Output.EXPANDED; break; case UNFORMATTED: output = Output.UNFORMATTED; outputOpts.add("u"); break; case TOOLTIP: // T(display_text) output = Output.TOOLTIP; text = option.getStringParam(0); break; /////////////////////////////////////////////////// // VISIBILITY OPTIONS /////////////////////////////////////////////////// case GM: outputOpts.add("g"); break; case SELF: outputOpts.add("s"); break; case WHISPER: outputOpts.add("w"); for (int i = 0; i < option.getParamCount(); i++) { String arg = parseExpression(resolver, tokenInContext, option.getStringParam(i)) .getValue().toString(); if (arg.trim().startsWith("[")) { Object json = JSONMacroFunctions.convertToJSON(arg); if (json instanceof JSONArray) { for (Object name : (JSONArray) json) { outputOpts.add("w:" + name.toString().toLowerCase()); } } } else outputOpts.add("w:" + arg.toLowerCase()); } break; /////////////////////////////////////////////////// // TOOLTIP VISIBILITY OPTIONS /////////////////////////////////////////////////// case GMTT: outputOpts.add("gt"); break; case SELFTT: outputOpts.add("st"); break; /////////////////////////////////////////////////// // LOOP OPTIONS /////////////////////////////////////////////////// case COUNT: // COUNT(num [, sep]) loopType = LoopType.COUNT; error = null; try { loopCount = option.getParsedIntParam(0, resolver, tokenInContext); if (loopCount < 0) error = I18N.getText("lineParser.countNonNeg", loopCount); } catch (ParserException pe) { error = I18N.getText("lineParser.errorProcessingOpt", "COUNT", pe.getMessage()); } loopSep = option.getStringParam(1); if (error != null) throw doError(error, opts, roll); break; case FOR: // FOR(var, start, end [, step [, sep]]) loopType = LoopType.FOR; error = null; try { loopVar = option.getIdentifierParam(0); loopStart = option.getParsedIntParam(1, resolver, tokenInContext); loopEnd = option.getParsedIntParam(2, resolver, tokenInContext); try { loopStep = option.getParsedIntParam(3, resolver, tokenInContext); } catch (ParserException pe) { // Build a more informative error message for this common mistake String msg = pe.getMessage(); msg = msg + " " + I18N.getText("lineParser.nonDefLoopSep"); throw new ParserException(msg); } loopSep = option.getStringParam(4); if (loopStep != 0) loopCount = Math.max(1, (int) Math.ceil( Math.abs((double) (loopEnd - loopStart) / (double) loopStep))); if (loopVar.equalsIgnoreCase("")) error = I18N.getText("lineParser.forVarMissing"); if (loopStep == 0) error = I18N.getText("lineParser.forNoZeroStep"); if ((loopEnd <= loopStart && loopStep > 0) || (loopEnd >= loopStart && loopStep < 0)) loopCount = 0; } catch (ParserException pe) { error = I18N.getText("lineParser.errorProcessingOpt", "FOR", pe.getMessage()); } if (error != null) throw doError(error, opts, roll); break; case FOREACH: // FOREACH(var, list [, outputDelim [, inputDelim]]) loopType = LoopType.FOREACH; error = null; try { loopVar = option.getIdentifierParam(0); String listString = option.getParsedParam(1, resolver, tokenInContext) .toString(); loopSep = option.getStringParam(2); String listDelim = option.getStringParam(3); if (listDelim.trim().startsWith("\"")) { listDelim = parseExpression(resolver, tokenInContext, listDelim).getValue() .toString(); } foreachList = null; if (listString.trim().startsWith("{") || listString.trim().startsWith("[")) { // if String starts with [ or { it is JSON -- try to treat it as a JSON String Object obj = JSONMacroFunctions.convertToJSON(listString); if (obj != null) { foreachList = new ArrayList<String>(); if (obj instanceof JSONArray) { for (Object o : ((JSONArray) obj).toArray()) { foreachList.add(o.toString()); } } else { @SuppressWarnings("unchecked") Set<String> keySet = ((JSONObject) obj).keySet(); foreachList.addAll(keySet); } } } // If we still dont have a list treat it list a string list if (foreachList == null) { foreachList = new ArrayList<String>(); StrListFunctions.parse(listString, foreachList, listDelim); } loopCount = foreachList.size(); if (loopVar.equalsIgnoreCase("")) error = I18N.getText("lineParser.foreachVarMissing"); } catch (ParserException pe) { error = I18N.getText("lineParser.errorProcessingOpt", "FOREACH", pe.getMessage()); } if (error != null) throw doError(error, opts, roll); break; case WHILE: // WHILE(cond [, sep]) loopType = LoopType.WHILE; loopCondition = option.getStringParam(0); loopSep = option.getStringParam(1); break; /////////////////////////////////////////////////// // BRANCH OPTIONS /////////////////////////////////////////////////// case IF: // IF(condition) branchType = BranchType.IF; branchCondition = option.getStringParam(0); break; case SWITCH: // SWITCH(condition) branchType = BranchType.SWITCH; branchCondition = option.getObjectParam(0); break; /////////////////////////////////////////////////// // DIALOG AND FRAME OPTIONS /////////////////////////////////////////////////// case FRAME: codeType = CodeType.CODEBLOCK; frameName = option.getParsedParam(0, resolver, tokenInContext).toString(); frameOpts = option.getParsedParam(1, resolver, tokenInContext).toString(); outputTo = OutputLoc.FRAME; break; case DIALOG: codeType = CodeType.CODEBLOCK; frameName = option.getParsedParam(0, resolver, tokenInContext).toString(); frameOpts = option.getParsedParam(1, resolver, tokenInContext).toString(); outputTo = OutputLoc.DIALOG; break; /////////////////////////////////////////////////// // CODE OPTIONS /////////////////////////////////////////////////// case MACRO: // MACRO("macroName@location") codeType = CodeType.MACRO; macroName = option.getStringParam(0); break; case CODE: codeType = CodeType.CODEBLOCK; break; /////////////////////////////////////////////////// // MISC OPTIONS /////////////////////////////////////////////////// case TOKEN: if (!isMacroTrusted()) { throw new ParserException(I18N.getText("macro.function.roll.noPerm")); } Token newToken = MapTool.getFrame().getCurrentZoneRenderer().getZone().resolveToken( option.getParsedParam(0, resolver, tokenInContext).toString()); if (newToken != null) { contextTokenStack.push(resolver.getTokenInContext()); resolver.setTokenIncontext(newToken); } break; default: // should never happen log.error(I18N.getText("lineParser.badOptionFound", opts, roll)); throw doError("lineParser.badOptionFound", opts, roll); } } } // Now that the options have been dealt with, process the body of the roll. // We deal with looping first, then branching, then deliver the output. StringBuilder expressionBuilder = new StringBuilder(); int iteration = 0; boolean doLoop = true; while (doLoop) { int loopConditionValue; Integer branchConditionValue = null; Object branchConditionParsed = null; // Process loop settings if (iteration > maxLoopIterations) { throw doError("lineParser.tooManyLoops", opts, roll); } if (loopType != LoopType.NO_LOOP) { // We only update roll.count in a loop statement. This allows simple nested // statements to inherit roll.count from the outer statement. resolver.setVariable("roll.count", iteration); } switch (loopType) { /* * TODO: If you're adding a new looping option, add a * new case to handle the iteration */ case NO_LOOP: if (iteration > 0) { // stop after first iteration doLoop = false; } break; case COUNT: if (iteration == loopCount) { doLoop = false; } break; case FOR: if (iteration != loopCount) { resolver.setVariable(loopVar, new BigDecimal(loopStart + loopStep * iteration)); } else { doLoop = false; resolver.setVariable(loopVar, null); } break; case FOREACH: if (iteration != loopCount) { String item = foreachList.get(iteration); resolver.setVariable(loopVar, item); } else { doLoop = false; resolver.setVariable(loopVar, null); } break; case WHILE: // This is a hack to get around a bug with the parser's comparison operators. // The InlineTreeFormatter class in the parser chokes on comparison operators, because they're // not listed in the operator precedence table. // // The workaround is that "non-deterministic" functions fully evaluate their arguments, // so the comparison operators are reduced to a number by the time the buggy code is reached. // The if() function defined in dicelib is such a function, so we use it here to eat // any comparison operators. String hackCondition = (loopCondition == null) ? null : String.format("if(%s, 1, 0)", loopCondition); // Stop loop if the while condition is false try { Result result = parseExpression(resolver, tokenInContext, hackCondition); loopConditionValue = ((Number) result.getValue()).intValue(); if (loopConditionValue == 0) { doLoop = false; } } catch (Exception e) { throw doError(I18N.getText("lineParser.invalidWhile", loopCondition), opts, roll); } break; } // Output the loop separator if (doLoop && iteration != 0 && output != Output.NONE) { expressionBuilder.append(parseExpression(resolver, tokenInContext, loopSep).getValue()); } if (!doLoop) { break; } iteration++; // Extract the appropriate branch to evaluate. // Evaluate the branch condition/expression if (branchCondition != null) { // This is a similar hack to the one used for the loopCondition above. String hackCondition = (branchCondition == null) ? null : branchCondition.toString(); if (branchType == BranchType.IF) { hackCondition = (hackCondition == null) ? null : String.format("if(%s, 1, 0)", hackCondition); } Result result = null; try { result = parseExpression(resolver, tokenInContext, hackCondition); } catch (Exception e) { throw doError(I18N.getText("lineParser.invalidCondition", branchType.toString(), branchCondition.toString()), opts, roll); } branchConditionParsed = result.getValue(); if (branchConditionParsed instanceof Number) { branchConditionValue = ((Number) branchConditionParsed).intValue(); } } // Set up regexes for scanning through the branches. // branchRegex then defines one matcher group for the parseable content of the branch. String rollBranch = roll; String branchRegex, branchSepRegex, branchLastSepRegex; if (codeType != CodeType.CODEBLOCK) { // matches any text not containing a ";" (skipping over strings) String noCodeRegex = "((?:[^\";]|\"[^\"]*\"|'[^']*')*)"; branchRegex = noCodeRegex; branchSepRegex = ";"; branchLastSepRegex = ";?"; // The last clause doesn't have to end with a separator } else { // matches text inside braces "{...}", skipping over strings (one level of {} nesting allowed) String codeRegex = "\\{((?:[^{}\"]|\"[^\"]*\"|'[^']*'|\\{(?:[^}\"]|\"[^\"]*\"|'[^']*')*})*)}"; branchRegex = codeRegex; branchSepRegex = ";"; branchLastSepRegex = ";?"; // The last clause doesn't have to end with a separator } // Extract the branch to use switch (branchType) { /* * TODO: If you're adding a new branching option, add a * new case to extract the branch text */ case NO_BRANCH: { // There's only one branch, so our regex is very simple String testRegex = String.format("^\\s*%s\\s*$", branchRegex); Matcher testMatcher = Pattern.compile(testRegex).matcher(roll); if (testMatcher.find()) { rollBranch = testMatcher.group(1); } else { throw doError("lineParser.errorBodyRoll", opts, roll); } break; } case IF: { // IF can have one or two branches. // When there's only one branch and the condition is false, there's no output. if (branchConditionValue == null) { throw doError(I18N.getText("lineParser.invalidIfCond", branchCondition, branchConditionParsed.toString()), opts, roll); } int whichBranch = (branchConditionValue != 0) ? 0 : 1; String testRegex = String.format("^\\s*%s\\s*(?:%s\\s*%s\\s*%s)?\\s*$", branchRegex, branchSepRegex, branchRegex, branchLastSepRegex); Matcher testMatcher = Pattern.compile(testRegex).matcher(roll); if (testMatcher.find()) { // verifies that roll body is well-formed rollBranch = testMatcher.group(1 + whichBranch); if (rollBranch == null) rollBranch = "''"; // quick-and-dirty way to get no output rollBranch = rollBranch.trim(); } else { throw doError("lineParser.ifError", opts, roll); } break; } case SWITCH: { // We augment the branch regex to detect the "case xxx:" or "default:" prefixes, // and search for a match. An error is thrown if no case match is found. // Regex matches 'default', 'case 123:', 'case "123":', 'case "abc":', but not 'case abc:' branchRegex = "(?:case\\s*\"?((?<!\")(?:\\+|-)?[\\d]+(?!\")|(?<=\")[^\"]*(?=\"))\"?|(default))\\s*:\\s*" + branchRegex; String caseTarget = branchConditionParsed.toString(); String testRegex = String.format("^(?:\\s*%s\\s*%s\\s*)*\\s*%s\\s*%s\\s*$", branchRegex, branchSepRegex, branchRegex, branchLastSepRegex); Matcher testMatcher = Pattern.compile(testRegex).matcher(roll); if (testMatcher.find()) { // verifies that roll body is well-formed String scanRegex = String.format("\\s*%s\\s*(?:%s)?", branchRegex, branchSepRegex); Matcher scanMatcher = Pattern.compile(scanRegex).matcher(roll); boolean foundMatch = false; while (!foundMatch && scanMatcher.find()) { String caseLabel = scanMatcher.group(1); // "case (xxx):" String def = scanMatcher.group(2); // "(default):" String branch = scanMatcher.group(3); if (def != null) { rollBranch = branch.trim(); foundMatch = true; ; } if (caseLabel != null && caseLabel.matches(caseTarget)) { rollBranch = branch.trim(); foundMatch = true; } } if (!foundMatch) { doError(I18N.getText("lineParser.switchNoMatch", caseTarget), opts, roll); } } else { doError("lineParser.switchError", opts, roll); } break; } } // end of switch(branchType) statement // Construct the output. // If a MACRO or CODE block is being used, we default to bare output as in the RESULT style. // The output style NONE is also allowed in these cases. Result result; String output_text; switch (codeType) { case NO_CODE: // If none of the code options are active, any of the formatting options can be used. switch (output) { /* * TODO: If you're adding a new formatting option, * add a new case to build the output */ case NONE: parseExpression(resolver, tokenInContext, rollBranch); break; case RESULT: result = parseExpression(resolver, tokenInContext, rollBranch); output_text = result != null ? result.getValue().toString() : ""; if (!this.isMacroTrusted()) { output_text = output_text.replaceAll( "\u00AB|\u00BB|«|»|«|»|\036|\037", ""); } if (outputOpts.isEmpty()) { expressionBuilder.append(output_text); } else { outputOpts.add("r"); expressionBuilder.append(rollString(outputOpts, output_text)); } break; case TOOLTIP: String tooltip = rollBranch + " = "; output_text = null; result = parseExpression(resolver, tokenInContext, rollBranch); tooltip += result.getDetailExpression(); if (text == null) { output_text = result.getValue().toString(); } else { if (!result.getDetailExpression().equals(result.getValue().toString())) { tooltip += " = " + result.getValue(); } resolver.setVariable("roll.result", result.getValue()); output_text = parseExpression(resolver, tokenInContext, text).getValue() .toString(); } tooltip = tooltip.replaceAll("'", "'"); expressionBuilder.append( output_text != null ? rollString(outputOpts, tooltip, output_text) : ""); break; case EXPANDED: expressionBuilder.append(rollString(outputOpts, rollBranch + " = " + expandRoll(resolver, tokenInContext, rollBranch))); break; case UNFORMATTED: output_text = rollBranch + " = " + expandRoll(resolver, tokenInContext, rollBranch); // Escape quotes so that the result can be used in a title attribute output_text = output_text.replaceAll("'", "'"); output_text = output_text.replaceAll("\"", """); expressionBuilder.append(rollString(outputOpts, output_text)); } // end of switch(output) statement break; // end of case NO_CODE in switch(codeType) statement /* * TODO: If you're adding a new code option, add a new * case to execute the code */ case MACRO: // [MACRO("macroName@location"): args] result = parseExpression(resolver, tokenInContext, macroName); String callName = result.getValue().toString(); result = parseExpression(resolver, tokenInContext, rollBranch); String macroArgs = result.getValue().toString(); output_text = runMacro(resolver, tokenInContext, callName, macroArgs); if (output != Output.NONE) { expressionBuilder.append(output_text); } resolver.setVariable("roll.count", iteration); // reset this because called code might change it break; case CODEBLOCK: output_text = runMacroBlock(resolver, tokenInContext, rollBranch); resolver.setVariable("roll.count", iteration); // reset this because called code might change it if (output != Output.NONE) { expressionBuilder.append(output_text); } break; } } switch (outputTo) { case FRAME: HTMLFrameFactory.show(frameName, true, frameOpts, expressionBuilder.toString()); break; case DIALOG: HTMLFrameFactory.show(frameName, false, frameOpts, expressionBuilder.toString()); break; case CHAT: builder.append(expressionBuilder); break; } // Revert to our previous token if [token(): ] was used if (contextTokenStack.size() > 0) { resolver.setTokenIncontext(contextTokenStack.pop()); } } else if (match.getMatch().startsWith("{")) { roll = match.getRoll(); Result result = parseExpression(resolver, tokenInContext, roll); if (isMacroTrusted()) { builder.append(result != null ? result.getValue().toString() : ""); } else { builder.append(result != null ? result.getValue().toString() .replaceAll("\u00AB|\u00BB|«|»|«|»|\036|\037", "") : ""); } } } builder.append(line.substring(start)); return builder.toString(); } catch (AbortFunctionException e) { // do nothing; this exception will never generate any output // throw doError("macroExecutionAbort", opts == null ? "" : opts, roll == null ? line : roll); throw e; } catch (AssertFunctionException e) { // do nothing; this exception will never generate any output // throw doError("macroExecutionAssert", opts == null ? "" : opts, roll == null ? line : roll); throw e; } catch (ParserException e) { // do nothing, jut pass message back up throw e; } catch (Exception e) { log.info(line, e); throw doError("lineParser.errorBodyRoll", opts == null ? "" : opts, roll == null ? line : roll); } finally { exitContext(); if (resolverInitialized) { // This is the top level call, time to clean up resolver.flush(); } // If we have exited the last context let the html frame we have (potentially) // updated a token. if (contextStackEmpty()) { HTMLFrameFactory.tokenChanged(tokenInContext); } MapTool.getFrame().refresh(); // Repaint incase macros changed anything. } }
From source file:StreamFlusher.java
public InterpreterKleeneVisitor(Environment e) { env = e;/* w w w. j ava 2 s . c om*/ stack = new Stack<Object>(); // only one stack is used symmap = new SymMap(); // see other Constructor options // only one SymMap is used // If another library is ever used, parameterize // which one is loaded here lib = new OpenFstLibraryWrapper(env, symmap); // only one is used hulden = new Hulden(lib, symmap); // only one is used // Mans Hulden's algorithms // add OTHER_ID and OTHER_NONID this way because the representation // of OTHER could change for a new library; do not refer directly // to "OTHER_ID" or "OTHER_NONID" in this file lib.AddOtherId(symmap); lib.AddOtherNonId(symmap); }
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++;//from ww w . 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.sina.scs.transfer.TransferManager.java
/** * Downloads all objects in the virtual directory designated by the * keyPrefix given to the destination directory given. All virtual * subdirectories will be downloaded recursively. * * @param bucketName/* w w w . j a v a 2 s . c o m*/ * The bucket containing the virtual directory * @param keyPrefix * The key prefix for the virtual directory, or null for the * entire bucket. All subdirectories will be downloaded * recursively. * @param destinationDirectory * The directory to place downloaded files. Subdirectories will * be created as necessary. */ public MultipleFileDownload downloadDirectory(String bucketName, String keyPrefix, File destinationDirectory) { if (keyPrefix == null) keyPrefix = ""; List<S3ObjectSummary> objectSummaries = new LinkedList<S3ObjectSummary>(); Stack<String> commonPrefixes = new Stack<String>(); commonPrefixes.add(keyPrefix); long totalSize = 0; // Recurse all virtual subdirectories to get a list of object summaries. // This is a depth-first search. do { String prefix = commonPrefixes.pop(); ObjectListing listObjectsResponse = null; do { if (listObjectsResponse == null) { ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName) .withDelimiter(DEFAULT_DELIMITER).withPrefix(prefix); listObjectsResponse = s3.listObjects(listObjectsRequest); } else { listObjectsResponse = s3.listNextBatchOfObjects(listObjectsResponse); } for (S3ObjectSummary s : listObjectsResponse.getObjectSummaries()) { // Skip any files that are also virtual directories, since // we can't save both a directory and a file of the same // name. if (!s.getKey().equals(prefix) && !listObjectsResponse.getCommonPrefixes().contains(s.getKey() + DEFAULT_DELIMITER)) { objectSummaries.add(s); totalSize += s.getSize(); } else { log.debug("Skipping download for object " + s.getKey() + " since it is also a virtual directory"); } } commonPrefixes.addAll(listObjectsResponse.getCommonPrefixes()); } while (listObjectsResponse.isTruncated()); } while (!commonPrefixes.isEmpty()); /* This is the hook for adding additional progress listeners */ ProgressListenerChain additionalProgressListenerChain = new ProgressListenerChain(); TransferProgressImpl transferProgress = new TransferProgressImpl(); transferProgress.setTotalBytesToTransfer(totalSize); /* * Bind additional progress listeners to this * MultipleFileTransferProgressUpdatingListener to receive * ByteTransferred events from each single-file download implementation. */ ProgressListener multipleFileTransferProgressListener = new MultipleFileTransferProgressUpdatingListener( transferProgress, additionalProgressListenerChain); List<DownloadImpl> downloads = new ArrayList<DownloadImpl>(); String description = "Downloading from " + bucketName + "/" + keyPrefix; final MultipleFileDownloadImpl multipleFileDownload = new MultipleFileDownloadImpl(description, transferProgress, additionalProgressListenerChain, keyPrefix, bucketName, downloads); multipleFileDownload.setMonitor(new MultipleFileTransferMonitor(multipleFileDownload, downloads)); final AllDownloadsQueuedLock allTransfersQueuedLock = new AllDownloadsQueuedLock(); MultipleFileTransferStateChangeListener multipleFileTransferStateChangeListener = new MultipleFileTransferStateChangeListener( allTransfersQueuedLock, multipleFileDownload); for (S3ObjectSummary summary : objectSummaries) { // TODO: non-standard delimiters File f = new File(destinationDirectory, summary.getKey()); File parentFile = f.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { throw new RuntimeException("Couldn't create parent directories for " + f.getAbsolutePath()); } // All the single-file downloads share the same // MultipleFileTransferProgressUpdatingListener and // MultipleFileTransferStateChangeListener downloads .add((DownloadImpl) download( new GetObjectRequest(summary.getBucketName(), summary.getKey()) .withGeneralProgressListener(multipleFileTransferProgressListener), f, multipleFileTransferStateChangeListener)); } if (downloads.isEmpty()) { multipleFileDownload.setState(TransferState.Completed); return multipleFileDownload; } // Notify all state changes waiting for the downloads to all be queued // to wake up and continue. synchronized (allTransfersQueuedLock) { allTransfersQueuedLock.allQueued = true; allTransfersQueuedLock.notifyAll(); } return multipleFileDownload; }
From source file:web.diva.server.model.SomClustering.SomClustImgGenerator.java
public SomClustTreeSelectionResult updateSideTreeSelection(int x, int y, double w, double h) { sideTreeBImg = sideTree.getImage();// ww w. j av a2 s .c o m SomClustTreeSelectionResult result = new SomClustTreeSelectionResult(); Node n = this.getNodeAt(x, y, rowNode); if (n != null) { sideTree.painttree(n, sideTreeBImg.getGraphics(), Color.red); Stack st = new Stack(); Vector v = new Vector(); n.fillMembers(v, st); int[] sel = new int[v.size()]; for (int i = 0; i < v.size(); i++) { sel[i] = ((Integer) v.elementAt(i)); } result.setSelectedIndices(sel); } // try { // byte[] imageData = ChartUtilities.encodeAsPNG(sideTreeBImg); // String base64 = Base64.encodeBase64String(imageData); // base64 = "data:image/png;base64," + base64; SplitedImg si = this.splitImage(sideTreeBImg); result.setTreeImg1Url(si.getImg1Url()); result.setTreeImg(si); System.gc(); return result; // } catch (IOException e) { // System.err.println(e.getLocalizedMessage()); // } // return null; }
From source file:com.sina.cloudstorage.services.scs.transfer.TransferManager.java
/** * Downloads all objects in the virtual directory designated by the * keyPrefix given to the destination directory given. All virtual * subdirectories will be downloaded recursively. * * @param bucketName/*w ww . j av a 2 s . c o m*/ * The bucket containing the virtual directory * @param keyPrefix * The key prefix for the virtual directory, or null for the * entire bucket. All subdirectories will be downloaded * recursively. * @param destinationDirectory * The directory to place downloaded files. Subdirectories will * be created as necessary. */ public MultipleFileDownload downloadDirectory(String bucketName, String keyPrefix, File destinationDirectory) { if (keyPrefix == null) keyPrefix = ""; List<S3ObjectSummary> objectSummaries = new LinkedList<S3ObjectSummary>(); Stack<String> commonPrefixes = new Stack<String>(); commonPrefixes.add(keyPrefix); long totalSize = 0; // Recurse all virtual subdirectories to get a list of object summaries. // This is a depth-first search. do { String prefix = commonPrefixes.pop(); ObjectListing listObjectsResponse = null; do { if (listObjectsResponse == null) { ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName(bucketName) .withDelimiter(DEFAULT_DELIMITER).withPrefix(prefix); listObjectsResponse = s3.listObjects(listObjectsRequest); } else { listObjectsResponse = s3.listNextBatchOfObjects(listObjectsResponse); } for (S3ObjectSummary s : listObjectsResponse.getObjectSummaries()) { // Skip any files that are also virtual directories, since // we can't save both a directory and a file of the same // name. if (!s.getKey().equals(prefix) && !listObjectsResponse.getCommonPrefixes().contains(s.getKey() + DEFAULT_DELIMITER)) { objectSummaries.add(s); totalSize += s.getSize(); } else { log.debug("Skipping download for object " + s.getKey() + " since it is also a virtual directory"); } } for (Map<String, String> cp : listObjectsResponse.getCommonPrefixes()) commonPrefixes.add(cp.get("Prefix")); } while (listObjectsResponse.isTruncated()); } while (!commonPrefixes.isEmpty()); /* This is the hook for adding additional progress listeners */ ProgressListenerChain additionalProgressListenerChain = new ProgressListenerChain(); TransferProgressImpl transferProgress = new TransferProgressImpl(); transferProgress.setTotalBytesToTransfer(totalSize); /* * Bind additional progress listeners to this * MultipleFileTransferProgressUpdatingListener to receive * ByteTransferred events from each single-file download implementation. */ ProgressListener multipleFileTransferProgressListener = new MultipleFileTransferProgressUpdatingListener( transferProgress, additionalProgressListenerChain); List<DownloadImpl> downloads = new ArrayList<DownloadImpl>(); String description = "Downloading from " + bucketName + "/" + keyPrefix; final MultipleFileDownloadImpl multipleFileDownload = new MultipleFileDownloadImpl(description, transferProgress, additionalProgressListenerChain, keyPrefix, bucketName, downloads); multipleFileDownload.setMonitor(new MultipleFileTransferMonitor(multipleFileDownload, downloads)); final AllDownloadsQueuedLock allTransfersQueuedLock = new AllDownloadsQueuedLock(); MultipleFileTransferStateChangeListener multipleFileTransferStateChangeListener = new MultipleFileTransferStateChangeListener( allTransfersQueuedLock, multipleFileDownload); for (S3ObjectSummary summary : objectSummaries) { // TODO: non-standard delimiters File f = new File(destinationDirectory, summary.getKey()); File parentFile = f.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { throw new RuntimeException("Couldn't create parent directories for " + f.getAbsolutePath()); } // All the single-file downloads share the same // MultipleFileTransferProgressUpdatingListener and // MultipleFileTransferStateChangeListener downloads .add((DownloadImpl) download( new GetObjectRequest(summary.getBucketName(), summary.getKey()) .withGeneralProgressListener(multipleFileTransferProgressListener), f, multipleFileTransferStateChangeListener)); } if (downloads.isEmpty()) { multipleFileDownload.setState(TransferState.Completed); return multipleFileDownload; } // Notify all state changes waiting for the downloads to all be queued // to wake up and continue. synchronized (allTransfersQueuedLock) { allTransfersQueuedLock.allQueued = true; allTransfersQueuedLock.notifyAll(); } return multipleFileDownload; }