List of usage examples for java.util.regex Matcher end
public int end()
From source file:org.cleverbus.admin.services.log.LogParser.java
/** * Processes the next log line by either appending it to the last log event, * if it's not a valid log line and last log event wasn't ignored (appendTo != null); * or by parsing it into a new event (parseTo). * * @param line the log line to process * @param parseTo the next log event to parse line into * @param appendTo the log event to append non-event lines to * @param config log parser config//from w ww . ja v a 2 s . co m * @return appendTo event, if the line was appended to it; parseTo event if the line was fully parsed into this event; * or null if the line was ignored */ LogEvent parseLine(String line, LogEvent parseTo, LogEvent appendTo, LogParserConfig config) { Matcher dateMatcher = config.getDatePattern().matcher(line); if (!dateMatcher.lookingAt()) { return parseFailed(line, appendTo); } DateTime eventDate = getDate(dateMatcher.group(1), config); if (eventDate == null) { return parseFailed(line, appendTo); } // line might still not match properties and therefore not be a new log event, // so don't stop just yet, even if the date is wrong boolean skipLogLine = eventDate.isBefore(config.getFromDate()); if (skipLogLine && appendTo == null) { return null; // no point continuing, since this line wouldn't be appended anyway } parseTo.setDate(eventDate); String unmatched = line.substring(0, dateMatcher.start()) + line.substring(dateMatcher.end(), line.length()); // date matches, but is the line a new log event line? Matcher propertiesMatcher = config.getPropertiesPattern().matcher(unmatched); if (!propertiesMatcher.lookingAt()) { return parseFailed(line, appendTo); } if (skipLogLine || !parseEventProperties(propertiesMatcher, parseTo, config)) { return null; } if (unmatched != null && config.getMsg() != null && !unmatched.contains(config.getMsg())) { return null; } unmatched = unmatched.substring(0, propertiesMatcher.start()) + unmatched.substring(propertiesMatcher.end(), unmatched.length()); parseTo.setMessage(unmatched); return parseTo; }
From source file:com.github.lucapino.sheetmaker.renderer.JavaTemplateRenderer.java
private void processTextElement(Graphics2D g2, Element textElement) { int x = Integer.valueOf(textElement.getAttributeValue("X")); int y = Integer.valueOf(textElement.getAttributeValue("Y")); int width = Integer.valueOf(textElement.getAttributeValue("Width")); int height = Integer.valueOf(textElement.getAttributeValue("Height")); String alignment = textElement.getAttributeValue("TextAlignment"); boolean multiline = Boolean.valueOf(textElement.getAttributeValue("Multiline").toLowerCase()); boolean antiAlias = textElement.getAttributeValue("TextQuality").equalsIgnoreCase("antialias"); Font font = parseFont(textElement.getAttributeValue("Font")); logger.info("Using font " + font); // now get the textim4java performance String text = textElement.getAttributeValue("Text"); // if text matches pattern of %VARIABLE%{MODIFIER} logger.info("parsing token {}", text); Matcher matcher = pattern.matcher(text); int start = 0; while (matcher.find(start)) { // apply modification text = text.replace(matcher.group(), applyModifier(matcher.group())); start = matcher.end(); }//from w w w . j av a 2s .c om BufferedImage tmpImage; if (width > 0 && height > 0) { // create a transparent tmpImage tmpImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); } else { FontMetrics fm = g2.getFontMetrics(font); Rectangle outlineBounds = fm.getStringBounds(text, g2).getBounds(); // we need to create a transparent image to paint tmpImage = new BufferedImage(outlineBounds.width, outlineBounds.height, BufferedImage.TYPE_INT_ARGB); } Graphics2D g2d = tmpImage.createGraphics(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); // } g2d.setFont(font); Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor"))); g2d.setColor(textColor); Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .8f); g2d.setComposite(comp); drawString(g2d, text, new Rectangle(0, 0, width, height), Align.valueOf(alignment), 0, multiline); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); tmpImage = processActions(textElement, tmpImage); //// Graphics2D g2d = tmpImage.createGraphics(); // // set current font // g2.setFont(font); //// g2d.setComposite(AlphaComposite.Clear); //// g2d.fillRect(0, 0, width, height); //// g2d.setComposite(AlphaComposite.Src); // // TODO: we have to parse it // int strokeWidth = Integer.valueOf(textElement.getAttributeValue("StrokeWidth")); // // the color of the outline // if (strokeWidth > 0) { //// Color strokeColor = new Color(Integer.valueOf(textElement.getAttributeValue("StrokeColor"))); //// AffineTransform affineTransform; //// affineTransform = g2d.getTransform(); //// affineTransform.translate(width / 2 - (outlineBounds.width / 2), height / 2 //// + (outlineBounds.height / 2)); //// g2d.transform(affineTransform); //// // backup stroke width and color //// Stroke originalStroke = g2d.getStroke(); //// Color originalColor = g2d.getColor(); //// g2d.setColor(strokeColor); //// g2d.setStroke(new BasicStroke(strokeWidth)); //// g2d.draw(shape); //// g2d.setClip(shape); //// // restore stroke width and color //// g2d.setStroke(originalStroke); //// g2d.setColor(originalColor); // } //// // get the text color // Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor"))); // g2.setColor(textColor); //// g2d.setBackground(Color.BLACK); //// g2d.setStroke(new BasicStroke(2)); //// g2d.setColor(Color.WHITE); // // draw the text // // drawString(g2, text, new Rectangle(x, y, width, height), Align.valueOf(alignment), 0, multiline); // g2.drawString(text, x, y); // Rectangle rect = new Rectangle(x, y, width, height); // defines the desired size and position // FontMetrics fm = g2.getFontMetrics(); // FontRenderContext frc = g2.getFontRenderContext(); // TextLayout tl = new TextLayout(text, g2.getFont(), frc); // AffineTransform transform = new AffineTransform(); // transform.setToTranslation(rect.getX(), rect.getY()); // if (Boolean.valueOf(textElement.getAttributeValue("AutoSize").toLowerCase())) { // double scaleY // = rect.getHeight() / (double) (tl.getOutline(null).getBounds().getMaxY() // - tl.getOutline(null).getBounds().getMinY()); // transform.scale(rect.getWidth() / (double) fm.stringWidth(text), scaleY); // } // Shape shape = tl.getOutline(transform); // g2.setClip(shape); // g2.fill(shape.getBounds()); // if (antiAlias) { // we need to restore antialias to none // g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); // } // g2.drawString(text, x, y); // alway resize // BicubicScaleFilter scaleFilter = new BicubicScaleFilter(width, height); // tmpImage = scaleFilter.filter(tmpImage, null); // draw the image to the source g2.drawImage(tmpImage, x, y, width, height, null); try { ScreenImage.writeImage(tmpImage, "/tmp/images/" + textElement.getAttributeValue("Name") + ".png"); } catch (IOException ex) { } }
From source file:com.joliciel.talismane.tokeniser.filters.TokenRegexFilterImpl.java
Pattern getPattern() { if (pattern == null) { // we may need to replace WordLists by the list contents String myRegex = this.regex; if (LOG.isTraceEnabled()) { LOG.trace("Regex: " + myRegex); }// ww w .j av a 2s .c o m if (this.autoWordBoundaries) { Boolean startsWithLetter = null; for (int i = 0; i < myRegex.length() && startsWithLetter == null; i++) { char c = myRegex.charAt(i); if (c == '\\') { i++; c = myRegex.charAt(i); if (c == 'd' || c == 'w') { startsWithLetter = true; } else if (c == 's' || c == 'W' || c == 'b' || c == 'B') { startsWithLetter = false; } else if (c == 'p') { i += 2; // skip the open curly brackets int closeCurlyBrackets = myRegex.indexOf('}', i); int openParentheses = myRegex.indexOf('(', i); int endIndex = closeCurlyBrackets; if (openParentheses > 0 && openParentheses < closeCurlyBrackets) endIndex = openParentheses; if (endIndex > 0) { String specialClass = myRegex.substring(i, endIndex); if (specialClass.equals("WordList")) { startsWithLetter = true; } } } break; } else if (c == '[' || c == '(') { // do nothing } else if (Character.isLetter(c) || Character.isDigit(c)) { startsWithLetter = true; } else { startsWithLetter = false; } } Boolean endsWithLetter = null; for (int i = myRegex.length() - 1; i >= 0 && endsWithLetter == null; i--) { char c = myRegex.charAt(i); char prevC = ' '; if (i >= 1) prevC = myRegex.charAt(i - 1); if (prevC == '\\') { if (c == 'd' || c == 'w') { endsWithLetter = true; } else if (c == 's' || c == 'W' || c == 'b' || c == 'B') { endsWithLetter = false; } else if (c == 'p') { i += 2; // skip the open curly brackets int closeCurlyBrackets = myRegex.indexOf('}', i); int openParentheses = myRegex.indexOf('(', i); int endIndex = closeCurlyBrackets; if (openParentheses < closeCurlyBrackets) endIndex = openParentheses; if (endIndex > 0) { String specialClass = myRegex.substring(i, endIndex); if (specialClass.equals("WordList") || specialClass.equals("Alpha") || specialClass.equals("Lower") || specialClass.equals("Upper") || specialClass.equals("ASCII") || specialClass.equals("Digit")) { startsWithLetter = true; } } } break; } else if (c == ']' || c == ')' || c == '+') { // do nothing } else if (c == '}') { int startIndex = myRegex.lastIndexOf('{') + 1; int closeCurlyBrackets = myRegex.indexOf('}', startIndex); int openParentheses = myRegex.indexOf('(', startIndex); int endIndex = closeCurlyBrackets; if (openParentheses > 0 && openParentheses < closeCurlyBrackets) endIndex = openParentheses; if (endIndex > 0) { String specialClass = myRegex.substring(startIndex, endIndex); if (specialClass.equals("WordList") || specialClass.equals("Alpha") || specialClass.equals("Lower") || specialClass.equals("Upper") || specialClass.equals("ASCII") || specialClass.equals("Digit")) { endsWithLetter = true; } } break; } else if (Character.isLetter(c) || Character.isDigit(c)) { endsWithLetter = true; } else { endsWithLetter = false; } } if (startsWithLetter != null && startsWithLetter) { myRegex = "\\b" + myRegex; } if (endsWithLetter != null && endsWithLetter) { myRegex = myRegex + "\\b"; } if (LOG.isTraceEnabled()) { LOG.trace("After autoWordBoundaries: " + myRegex); } } if (!this.caseSensitive || !this.diacriticSensitive) { StringBuilder regexBuilder = new StringBuilder(); for (int i = 0; i < myRegex.length(); i++) { char c = myRegex.charAt(i); if (c == '\\') { // escape - skip next regexBuilder.append(c); i++; c = myRegex.charAt(i); regexBuilder.append(c); } else if (c == '[') { // character group, don't change it regexBuilder.append(c); while (c != ']' && i < myRegex.length()) { i++; c = myRegex.charAt(i); regexBuilder.append(c); } } else if (c == '{') { // command, don't change it regexBuilder.append(c); while (c != '}' && i < myRegex.length()) { i++; c = myRegex.charAt(i); regexBuilder.append(c); } } else if (Character.isLetter(c)) { Set<String> chars = new TreeSet<String>(); chars.add("" + c); char noAccent = diacriticPattern.matcher(Normalizer.normalize("" + c, Form.NFD)) .replaceAll("").charAt(0); if (!this.caseSensitive) { chars.add("" + Character.toUpperCase(c)); chars.add("" + Character.toLowerCase(c)); chars.add("" + Character.toUpperCase(noAccent)); } if (!this.diacriticSensitive) { chars.add("" + noAccent); if (!this.caseSensitive) { chars.add("" + Character.toLowerCase(noAccent)); } } if (chars.size() == 1) { regexBuilder.append(c); } else { regexBuilder.append('['); for (String oneChar : chars) { regexBuilder.append(oneChar); } regexBuilder.append(']'); } } else { regexBuilder.append(c); } } myRegex = regexBuilder.toString(); if (LOG.isTraceEnabled()) { LOG.trace("After caseSensitive: " + myRegex); } } Matcher matcher = wordListPattern.matcher(myRegex); StringBuilder regexBuilder = new StringBuilder(); int lastIndex = 0; while (matcher.find()) { String[] params = matcher.group(1).split(","); int start = matcher.start(); int end = matcher.end(); regexBuilder.append(myRegex.substring(lastIndex, start)); String wordListName = params[0]; boolean uppercaseOptional = false; boolean diacriticsOptional = false; boolean lowercaseOptional = false; boolean firstParam = true; for (String param : params) { if (firstParam) { /* word list name */ } else if (param.equals("diacriticsOptional")) diacriticsOptional = true; else if (param.equals("uppercaseOptional")) uppercaseOptional = true; else if (param.equals("lowercaseOptional")) lowercaseOptional = true; else throw new TalismaneException( "Unknown parameter in word list " + matcher.group(1) + ": " + param); firstParam = false; } ExternalWordList wordList = externalResourceFinder.getExternalWordList(wordListName); if (wordList == null) throw new TalismaneException("Unknown word list: " + wordListName); StringBuilder sb = new StringBuilder(); boolean firstWord = true; for (String word : wordList.getWordList()) { if (!firstWord) sb.append("|"); word = Normalizer.normalize(word, Form.NFC); if (uppercaseOptional || diacriticsOptional) { String wordNoDiacritics = Normalizer.normalize(word, Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); String wordLowercase = word.toLowerCase(Locale.ENGLISH); String wordLowercaseNoDiacritics = Normalizer.normalize(wordLowercase, Form.NFD) .replaceAll("\\p{InCombiningDiacriticalMarks}+", ""); String wordUppercase = wordNoDiacritics.toUpperCase(Locale.ENGLISH); boolean needsGrouping = false; if (uppercaseOptional && !word.equals(wordLowercase)) needsGrouping = true; if (diacriticsOptional && !word.equals(wordNoDiacritics)) needsGrouping = true; if (lowercaseOptional && !word.equals(wordUppercase)) needsGrouping = true; if (needsGrouping) { for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); boolean grouped = false; if (uppercaseOptional && c != wordLowercase.charAt(i)) grouped = true; if (diacriticsOptional && c != wordNoDiacritics.charAt(i)) grouped = true; if (lowercaseOptional && c != wordUppercase.charAt(i)) grouped = true; if (!grouped) sb.append(c); else { sb.append("["); String group = "" + c; if (uppercaseOptional && group.indexOf(wordLowercase.charAt(i)) < 0) group += (wordLowercase.charAt(i)); if (lowercaseOptional && group.indexOf(wordUppercase.charAt(i)) < 0) group += (wordUppercase.charAt(i)); if (diacriticsOptional && group.indexOf(wordNoDiacritics.charAt(i)) < 0) group += (wordNoDiacritics.charAt(i)); if (uppercaseOptional && diacriticsOptional && group.indexOf(wordLowercaseNoDiacritics.charAt(i)) < 0) group += (wordLowercaseNoDiacritics.charAt(i)); sb.append(group); sb.append("]"); } // does this letter need grouping? } // next letter } else { sb.append(word); } // any options activated? } else { sb.append(word); } firstWord = false; } // next word in list regexBuilder.append(sb.toString()); lastIndex = end; } // next match regexBuilder.append(myRegex.substring(lastIndex)); myRegex = regexBuilder.toString(); this.pattern = Pattern.compile(myRegex, Pattern.UNICODE_CHARACTER_CLASS); } return pattern; }
From source file:com.github.lucapino.sheetmaker.renderer.GmTemplateRenderer.java
private BufferedImage processTextElement(BufferedImage image, Element textElement) throws IOException, IM4JavaException, InterruptedException { int x = Integer.valueOf(textElement.getAttributeValue("X")); int y = Integer.valueOf(textElement.getAttributeValue("Y")); int width = Integer.valueOf(textElement.getAttributeValue("Width")); int height = Integer.valueOf(textElement.getAttributeValue("Height")); String alignment = textElement.getAttributeValue("TextAlignment"); boolean multiline = Boolean.valueOf(textElement.getAttributeValue("Multiline").toLowerCase()); boolean antiAlias = textElement.getAttributeValue("TextQuality").equalsIgnoreCase("antialias"); String textColor = "#" + Integer.toHexString(Integer.valueOf(textElement.getAttributeValue("ForeColor"))).substring(2); // now get the text String text = textElement.getAttributeValue("Text"); // if text matches pattern of %VARIABLE%{MODIFIER} logger.info("parsing token {}", text); Matcher matcher = pattern.matcher(text); int start = 0; while (matcher.find(start)) { // apply modification text = text.replace(matcher.group(), applyModifier(matcher.group())); start = matcher.end(); }//from www . j ava 2s . c o m Stream2BufferedImage s2b = new Stream2BufferedImage(); convert.setOutputConsumer(s2b); IMOperation op = new IMOperation(); op.background("none"); op.size(width, height); op = parseText(op, text, textElement.getAttributeValue("Font"), textColor); op.gravity(gravityMap.get(alignment)); op.addImage("png:-"); convert.createScript("/tmp/images/myscript.sh", op); convert.run(op); BufferedImage tmpImage = s2b.getImage(); // compose over current image CompositeCmd command = new CompositeCmd(); op = new IMOperation(); // the image is alrready resized, so we have to fill only x and y op.geometry(null, null, x, y); // compose putting source image over destination image op.compose("Src_Over"); op.addImage(2); op.addImage("png:-"); s2b = new Stream2BufferedImage(); command.setOutputConsumer(s2b); command.run(op, tmpImage, image); // retrieve image image = s2b.getImage(); // logger.info("Saving image..."); // ScreenImage.writeImage(image, "/tmp/images/image" + textElement.getAttributeValue("Name") + ".png"); // // BufferedImage tmpImage; // if (width > 0 && height > 0) { // // create a transparent tmpImage // tmpImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // } else { //// FontMetrics fm = g2.getFontMetrics(font); //// Rectangle outlineBounds = fm.getStringBounds(text, g2).getBounds(); //// we need to create a transparent image to paint //// tmpImage = new BufferedImage(outlineBounds.width, outlineBounds.height, BufferedImage.TYPE_INT_RGB); // } //// Graphics2D g2d = tmpImage.createGraphics(); //// g2d.setFont(font); // //// g2d.setColor(textColor); //// drawString(g2d, text, new Rectangle(0, 0, width, height), Align.valueOf(alignment), 0, multiline); //// tmpImage = processActions(textElement, tmpImage); ////// Graphics2D g2d = tmpImage.createGraphics(); //// // set current font //// g2.setFont(font); ////// g2d.setComposite(AlphaComposite.Clear); ////// g2d.fillRect(0, 0, width, height); ////// g2d.setComposite(AlphaComposite.Src); //// // TODO: we have to parse it //// int strokeWidth = Integer.valueOf(textElement.getAttributeValue("StrokeWidth")); //// // the color of the outline //// if (strokeWidth > 0) { ////// Color strokeColor = new Color(Integer.valueOf(textElement.getAttributeValue("StrokeColor"))); ////// AffineTransform affineTransform; ////// affineTransform = g2d.getTransform(); ////// affineTransform.translate(width / 2 - (outlineBounds.width / 2), height / 2 ////// + (outlineBounds.height / 2)); ////// g2d.transform(affineTransform); ////// // backup stroke width and color ////// Stroke originalStroke = g2d.getStroke(); ////// Color originalColor = g2d.getColor(); ////// g2d.setColor(strokeColor); ////// g2d.setStroke(new BasicStroke(strokeWidth)); ////// g2d.draw(shape); ////// g2d.setClip(shape); ////// // restore stroke width and color ////// g2d.setStroke(originalStroke); ////// g2d.setColor(originalColor); //// } ////// // get the text color //// Color textColor = new Color(Integer.valueOf(textElement.getAttributeValue("ForeColor"))); //// g2.setColor(textColor); ////// g2d.setBackground(Color.BLACK); ////// g2d.setStroke(new BasicStroke(2)); ////// g2d.setColor(Color.WHITE); //// // draw the text //// //// drawString(g2, text, new Rectangle(x, y, width, height), Align.valueOf(alignment), 0, multiline); //// g2.drawString(text, x, y); //// Rectangle rect = new Rectangle(x, y, width, height); // defines the desired size and position //// FontMetrics fm = g2.getFontMetrics(); //// FontRenderContext frc = g2.getFontRenderContext(); //// TextLayout tl = new TextLayout(text, g2.getFont(), frc); //// AffineTransform transform = new AffineTransform(); //// transform.setToTranslation(rect.getX(), rect.getY()); //// if (Boolean.valueOf(textElement.getAttributeValue("AutoSize").toLowerCase())) { //// double scaleY //// = rect.getHeight() / (double) (tl.getOutline(null).getBounds().getMaxY() //// - tl.getOutline(null).getBounds().getMinY()); //// transform.scale(rect.getWidth() / (double) fm.stringWidth(text), scaleY); //// } //// Shape shape = tl.getOutline(transform); //// g2.setClip(shape); //// g2.fill(shape.getBounds()); // if (antiAlias) { // // we need to restore antialias to none //// g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); // } //// g2.drawString(text, x, y); // // // alway resize //// BicubicScaleFilter scaleFilter = new BicubicScaleFilter(width, height); //// tmpImage = scaleFilter.filter(tmpImage, null); // // draw the image to the source //// g2.drawImage(tmpImage, x, y, width, height, null); //// try { //// ScreenImage.writeImage(tmpImage, "/tmp/images/" + textElement.getAttributeValue("Name") + ".png"); //// } catch (IOException ex) { //// //// } logger.info("{} processed...", textElement.getAttributeValue("Name")); // return processed image return image; }
From source file:me.Wundero.Ray.utils.TextUtils.java
/** * Split the text at a regular expression. If skip, pattern will be skipped. *//*w w w . j a v a 2 s .c o m*/ public static List<Text> split(Text t, Pattern p, boolean skip) { if (!lit(t)) { return Utils.al(t); } List<Text> out = Utils.al(); List<Text> children = t.getChildren(); LiteralText.Builder text = ((LiteralText) t).toBuilder(); String content = text.getContent(); if (!p.matcher(content).find()) { return Utils.al(t); } if (p.matcher(content).matches()) { return skip ? Utils.al() : Utils.al(t); } Matcher m = p.matcher(content); while ((m = m.reset(content)).find()) { int s = m.start(); int e = m.end(); Text.Builder b = Text.builder(content.substring(0, s)).format(text.getFormat()); b = apply(b, text); out.add(b.build()); if (!skip) { b = Text.builder(m.group()).format(text.getFormat()); b = apply(b, text); out.add(b.build()); } content = content.substring(0, e); } if (!content.isEmpty()) { Text.Builder b = Text.builder(content).format(text.getFormat()); b = apply(b, text); out.add(b.build()); } Text.Builder tx = out.get(out.size() - 1).toBuilder(); out.remove(out.size() - 1); for (Text child : children) { List<Text> lt = split(child, p, skip); if (lt.isEmpty()) { out.add(tx.build()); tx = null; } else if (lt.size() == 1) { tx = tx == null ? lt.get(0).toBuilder() : tx.append(lt.get(0)); } else { out.add(tx == null ? lt.get(0) : tx.append(lt.get(0)).build()); for (int i = 1; i < lt.size() - 1; i++) { out.add(lt.get(i)); } tx = tx == null ? lt.get(lt.size() - 1).toBuilder() : lt.get(lt.size() - 1).toBuilder(); } } if (tx != null) { out.add(tx.build()); } return out; }
From source file:org.jfree.eastwood.ChartEngine.java
/** * Creates and returns a new <code>JFreeChart</code> instance that * reflects the specified parameters (which should be equivalent to * a parameter map returned by HttpServletRequest.getParameterMap() for * a valid URI for the Google Chart API. * * @param params the parameters (<code>null</code> not permitted). * @param font the font to use to draw titles, labels and legends. * * @return A chart corresponding to the specification in the supplied * parameters.//from w w w . j a v a 2 s . co m */ public static JFreeChart buildChart(Map params, Font font) { if (params == null) { throw new IllegalArgumentException("Null 'params' argument."); } JFreeChart chart = null; // *** CHART TYPE ** String[] chartType = (String[]) params.get("cht"); int dataType = -1; // 0 = PieDataset; 1 = XYDataset; 2 = special // pie charts: 'p' and 'p3' if (chartType[0].equals("p")) { chart = createPieChart(); dataType = 0; } else if (chartType[0].equals("p3")) { chart = createPieChart3D(); dataType = 0; } // line chart: 'lc' else if (chartType[0].equals("lc")) { chart = createLineChart(); dataType = 1; } // sparkline: 'ls' else if (chartType[0].equals("ls")) { chart = createSparklineChart(); dataType = 1; } // xy chart: 'lxy' else if (chartType[0].equals("lxy")) { chart = createLineChart(); dataType = 3; } // bar charts: 'bhs', 'bhg', 'bhs' and 'bhg' else if (chartType[0].equals("bhs")) { chart = createStackedBarChart(PlotOrientation.HORIZONTAL); dataType = 2; } else if (chartType[0].equals("bhg")) { chart = createBarChart(PlotOrientation.HORIZONTAL); dataType = 2; } else if (chartType[0].equals("bvs")) { chart = createStackedBarChart(PlotOrientation.VERTICAL); dataType = 2; } else if (chartType[0].equals("bvg")) { chart = createBarChart(PlotOrientation.VERTICAL); dataType = 2; } else if (chartType[0].equals("bhs3")) { chart = createStackedBarChart3D(PlotOrientation.HORIZONTAL); dataType = 2; } else if (chartType[0].equals("bhg3")) { chart = createBarChart3D(PlotOrientation.HORIZONTAL); dataType = 2; } else if (chartType[0].equals("bvs3")) { chart = createStackedBarChart3D(PlotOrientation.VERTICAL); dataType = 2; } else if (chartType[0].equals("bvg3")) { chart = createBarChart3D(PlotOrientation.VERTICAL); dataType = 2; } // scatter chart: 's' else if (chartType[0].equals("s")) { chart = createScatterChart(); dataType = 4; } else if (chartType[0].equals("v")) { throw new RuntimeException("Venn diagrams not implemented."); // TODO: fix this. } else { throw new RuntimeException("Unknown chart type: " + chartType[0]); } chart.getPlot().setOutlineVisible(false); // *** CHART AXES *** List axes = new java.util.ArrayList(); String[] axisStr = (String[]) params.get("chxt"); if (axisStr != null) { if (chart.getPlot() instanceof XYPlot) { XYPlot plot = (XYPlot) chart.getPlot(); processAxisStr(plot, axisStr[0], axes); } else if (chart.getPlot() instanceof CategoryPlot) { CategoryPlot plot = (CategoryPlot) chart.getPlot(); if (plot.getOrientation() == PlotOrientation.VERTICAL) { processAxisStrV(plot, axisStr[0], axes); } else { processAxisStrH(plot, axisStr[0], axes); } } } // *** AXIS RANGES *** String[] axisRangeStr = (String[]) params.get("chxr"); if (axisRangeStr != null) { String[] ranges = breakString(axisRangeStr[0], '|'); for (int i = 0; i < ranges.length; i++) { int comma1 = ranges[i].indexOf(','); int comma2 = ranges[i].indexOf(',', comma1 + 1); int axisIndex = Integer.parseInt(ranges[i].substring(0, comma1)); float lowerBound = Float.parseFloat(ranges[i].substring(comma1 + 1, comma2)); float upperBound = Float.parseFloat(ranges[i].substring(comma2 + 1)); Axis axis = (Axis) axes.get(axisIndex); if (axis instanceof GValueAxis) { GValueAxis gaxis = (GValueAxis) axis; gaxis.setLabelAxisStart(lowerBound); gaxis.setLabelAxisEnd(upperBound); } } } // *** AXIS LABELS *** String[] axisLabelStr = (String[]) params.get("chxl"); if (axisLabelStr != null) { Pattern p = Pattern.compile("\\d+:\\|"); Matcher m = p.matcher(axisLabelStr[0]); if (m.find()) { int keyStart = m.start(); int labelStart = m.end(); while (m.find(labelStart)) { String keyStr = axisLabelStr[0].substring(keyStart, labelStart - 2); int axisIndex = Integer.parseInt(keyStr); keyStart = m.start(); String labelStr = axisLabelStr[0].substring(labelStart, keyStart - 1); String[] labels = breakString(labelStr, '|'); GLabelledAxis axis = (GLabelledAxis) axes.get(axisIndex); axis.setTickLabels(Arrays.asList(labels)); labelStart = m.end(); } // process the final item String keyStr = axisLabelStr[0].substring(keyStart, labelStart - 2); String labelStr = axisLabelStr[0].substring(labelStart); int axisIndex = Integer.parseInt(keyStr); if (labelStr.endsWith("|")) { labelStr = labelStr.substring(0, labelStr.length() - 1); } String[] labels = breakString(labelStr, '|'); GLabelledAxis axis = (GLabelledAxis) axes.get(axisIndex); axis.setTickLabels(Arrays.asList(labels)); } else { throw new RuntimeException("No matching pattern!"); } } // ** EXPLICIT AXIS LABEL POSITIONS String[] axisPositionStr = (String[]) params.get("chxp"); if (axisPositionStr != null) { String[] positions = breakString(axisPositionStr[0], '|'); for (int i = 0; i < positions.length; i++) { int c1 = positions[i].indexOf(','); int axisIndex = Integer.parseInt(positions[i].substring(0, c1)); String remainingStr = positions[i].substring(c1 + 1); String[] valueStr = breakString(remainingStr, ','); List tickValues = new java.util.ArrayList(valueStr.length); Axis axis = (Axis) axes.get(axisIndex); if (axis instanceof GValueAxis) { GValueAxis gaxis = (GValueAxis) axes.get(axisIndex); for (int j = 0; j < valueStr.length; j++) { float pos = Float.parseFloat(valueStr[j]); tickValues.add(new Float(pos)); } gaxis.setTickLabelPositions(tickValues); } // FIXME: what about a CategoryAxis? } } // *** CHART TITLE *** String[] titleStr = (String[]) params.get("chtt"); if (titleStr != null) { // process the title String[] s = breakString(titleStr[0], '|'); for (int i = 0; i < s.length; i++) { TextTitle t = new TextTitle(s[i].replace('+', ' ')); t.setPaint(Color.darkGray); // Google seems to use 14pt fonts for titles and 12pt fonts for // all other text. Make sure this relationship remains. t.setFont(font.deriveFont(font.getSize2D() * 14f / 12f)); chart.addSubtitle(t); } // and the font and colour String[] fontStr = (String[]) params.get("chts"); if (fontStr != null) { int c1 = fontStr[0].indexOf(','); String colorStr = null; String fontSizeStr = null; if (c1 != -1) { colorStr = fontStr[0].substring(0, c1); fontSizeStr = fontStr[0].substring(c1 + 1); } else { colorStr = fontStr[0]; } Color color = parseColor(colorStr); int size = 12; if (fontSizeStr != null) { size = Integer.parseInt(fontSizeStr); } for (int i = 0; i < chart.getSubtitleCount(); i++) { Title t = chart.getSubtitle(i); if (t instanceof TextTitle) { TextTitle tt = (TextTitle) t; tt.setPaint(color); tt.setFont(font.deriveFont((float) size)); } } } } // *** CHART DATA *** String[] dataStr = (String[]) params.get("chd"); String scalingStr = null; if (dataStr.length > 0 && dataStr[0].startsWith("t:")) { // Only look at chds when text encoding is used String[] chds = (String[]) params.get("chds"); if (chds != null && chds.length > 0) { scalingStr = chds[0]; } } // we'll also process an optional second dataset that is provided as // an Eastwood extension...this isn't part of the Google Chart API String[] d2Str = (String[]) params.get("ewd2"); // 'p' and 'p3' - create PieDataset if (dataType == 0) { PieDataset dataset = DataUtilities.parsePieDataset(dataStr[0], scalingStr); PiePlot plot = (PiePlot) chart.getPlot(); plot.setDataset(dataset); // ignore d2Str as there is currently no need for a second pie // dataset. } // 'lc' - create XYDataset else if (dataType == 1) { XYPlot plot = (XYPlot) chart.getPlot(); XYDataset dataset = DataUtilities.parseXYDataset(dataStr[0], scalingStr); plot.setDataset(dataset); if (d2Str != null) { // an Eastwood extension XYDataset d2 = DataUtilities.parseXYDataset(d2Str[0], scalingStr); plot.setDataset(1, d2); } } // 'bhs', 'bhg', 'bvs', 'bvg' else if (dataType == 2) { CategoryPlot plot = (CategoryPlot) chart.getPlot(); CategoryDataset dataset = DataUtilities.parseCategoryDataset(dataStr[0], scalingStr); plot.setDataset(dataset); if (d2Str != null) { // an Eastwood extension CategoryDataset d2 = DataUtilities.parseCategoryDataset(d2Str[0], scalingStr); plot.setDataset(1, d2); } } // 'lxy' else if (dataType == 3) { XYPlot plot = (XYPlot) chart.getPlot(); XYDataset dataset = DataUtilities.parseXYDataset2(dataStr[0], scalingStr); plot.setDataset(dataset); if (d2Str != null) { // an Eastwood extension XYDataset d2 = DataUtilities.parseXYDataset2(d2Str[0], scalingStr); plot.setDataset(1, d2); } } else if (dataType == 4) { XYPlot plot = (XYPlot) chart.getPlot(); XYSeriesCollection dataset = DataUtilities.parseScatterDataset(dataStr[0], scalingStr); if (dataset.getSeriesCount() > 1) { dataset.removeSeries(1); } plot.setDataset(dataset); if (d2Str != null) { // an Eastwood extension XYDataset d2 = DataUtilities.parseXYDataset2(d2Str[0], scalingStr); plot.setDataset(1, d2); } } if (chart.getPlot() instanceof XYPlot) { XYPlot plot = (XYPlot) chart.getPlot(); plot.getDomainAxis().setLabelFont(font); plot.getDomainAxis().setTickLabelFont(font); plot.getRangeAxis().setLabelFont(font); plot.getRangeAxis().setTickLabelFont(font); } else if (chart.getPlot() instanceof CategoryPlot) { CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.getDomainAxis().setLabelFont(font); plot.getDomainAxis().setTickLabelFont(font); plot.getRangeAxis().setLabelFont(font); plot.getRangeAxis().setTickLabelFont(font); } // *** CHART COLOURS *** String[] colorStr = (String[]) params.get("chco"); if (colorStr != null) { Color[] colors = parseColors(colorStr[0]); if (dataType == 0) { PiePlot plot = (PiePlot) chart.getPlot(); applyColorsToPiePlot(plot, colors); } else { AbstractRenderer renderer = null; if (chart.getPlot() instanceof CategoryPlot) { CategoryPlot plot = (CategoryPlot) chart.getPlot(); renderer = (AbstractRenderer) plot.getRenderer(); renderer.setBasePaint(colors[0]); } else if (chart.getPlot() instanceof XYPlot) { XYPlot plot = (XYPlot) chart.getPlot(); renderer = (AbstractRenderer) plot.getRenderer(); renderer.setBasePaint(colors[colors.length - 1]); } for (int i = 0; i < colors.length; i++) { renderer.setSeriesPaint(i, colors[i]); } } } else { Plot plot = chart.getPlot(); if (plot instanceof PiePlot) { applyColorsToPiePlot((PiePlot) chart.getPlot(), new Color[] { new Color(255, 153, 0) }); } } // *** CHART LINE STYLES *** String[] lineStr = (String[]) params.get("chls"); if (lineStr != null && chart.getPlot() instanceof XYPlot) { Stroke[] strokes = parseLineStyles(lineStr[0]); XYPlot plot = (XYPlot) chart.getPlot(); XYItemRenderer renderer = plot.getRenderer(); for (int i = 0; i < strokes.length; i++) { renderer.setSeriesStroke(i, strokes[i]); } renderer.setBaseStroke(strokes[strokes.length - 1]); } // *** CHART GRID LINES if (dataType != 0) { String[] gridStr = (String[]) params.get("chg"); if (gridStr != null) { processGridLinesSpec(gridStr[0], chart); } } // *** CHART LABELS if (dataType == 0) { // pie chart String[] labelStr = (String[]) params.get("chl"); if (labelStr != null) { String[] s = breakString(labelStr[0], '|'); List labels = Arrays.asList(s); PiePlot plot = (PiePlot) chart.getPlot(); if (labels.size() > 0) { plot.setLabelGenerator(new GPieSectionLabelGenerator(labels)); plot.setLabelFont(font); plot.setLabelPaint(Color.darkGray); } } } String[] legendStr = (String[]) params.get("chdl"); if (legendStr != null) { // process the title String[] s = breakString(legendStr[0], '|'); List labels = Arrays.asList(s); if (labels.size() > 0) { Plot p = chart.getPlot(); if (p instanceof CategoryPlot) { CategoryPlot plot = (CategoryPlot) chart.getPlot(); BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setLegendItemLabelGenerator(new GSeriesLabelGenerator(labels)); renderer.setBaseSeriesVisibleInLegend(false); for (int i = 0; i < labels.size(); i++) { renderer.setSeriesVisibleInLegend(i, Boolean.TRUE); } } else if (p instanceof XYPlot) { XYPlot plot = (XYPlot) chart.getPlot(); XYItemRenderer renderer = plot.getRenderer(); renderer.setLegendItemLabelGenerator(new GSeriesLabelGenerator(labels)); renderer.setBaseSeriesVisibleInLegend(false); for (int i = 0; i < labels.size(); i++) { renderer.setSeriesVisibleInLegend(i, Boolean.TRUE); } } else if (p instanceof PiePlot) { PiePlot plot = (PiePlot) chart.getPlot(); plot.setLegendLabelGenerator(new GPieSectionLabelGenerator(labels)); } LegendTitle legend = new LegendTitle(chart.getPlot()); RectangleEdge pos = RectangleEdge.RIGHT; String[] chdlp = (String[]) params.get("chdlp"); if (chdlp != null) { if ("b".equals(chdlp[0])) { pos = RectangleEdge.BOTTOM; } else if ("t".equals(chdlp[0])) { pos = RectangleEdge.TOP; } else if ("l".equals(chdlp[0])) { pos = RectangleEdge.LEFT; } } legend.setPosition(pos); legend.setItemFont(font); legend.setItemPaint(Color.darkGray); chart.addSubtitle(legend); } } // *** CHART MARKERS *** String[] markerStr = (String[]) params.get("chm"); if (markerStr != null) { String[] markers = breakString(markerStr[0], '|'); for (int i = 0; i < markers.length; i++) { addMarker(markers[i], chart); } } // *** CHART FILL ***/ String[] fillStr = (String[]) params.get("chf"); if (fillStr != null) { // process the 1 or 2 fill specs int i = fillStr[0].indexOf('|'); if (i == -1) { processFillSpec(fillStr[0], chart); } else { String fs1 = fillStr[0].substring(0, i); String fs2 = fillStr[0].substring(i + 1); processFillSpec(fs1, chart); processFillSpec(fs2, chart); } } // process the 'ewtr' tag, if present processEWTR(params, chart); return chart; }
From source file:com.github.tteofili.p2h.DataSplitTest.java
@Ignore @Test/* w w w . java 2 s . c o m*/ public void testDataSplit() throws Exception { String regex = "\\n\\d(\\.\\d)*\\.?\\u0020[\\w|\\-|\\|\\:]+(\\u0020[\\w|\\-|\\:|\\]+){0,10}\\n"; String prefix = "/path/to/h2v/"; Pattern pattern = Pattern.compile(regex); Path path = Paths.get(getClass().getResource("/papers/raw/").getFile()); File file = path.toFile(); if (file.exists() && file.list() != null) { for (File doc : file.listFiles()) { String s = IOUtils.toString(new FileInputStream(doc)); String docName = doc.getName(); File fileDir = new File(prefix + docName); assert fileDir.mkdir(); Matcher matcher = pattern.matcher(s); int start = 0; String sectionName = "abstract"; while (matcher.find(start)) { String string = matcher.group(0); if (isValid(string)) { String content; if (start == 0) { // abstract content = s.substring(0, matcher.start()); } else { content = s.substring(start, matcher.start()); } File f = new File(prefix + docName + "/" + docName + "_" + sectionName); assert f.createNewFile() : "could not create file" + f.getAbsolutePath(); FileOutputStream outputStream = new FileOutputStream(f); IOUtils.write(content, outputStream); start = matcher.end(); sectionName = string.replaceAll("\n", "").trim(); } else { start = matcher.end(); } } // remaining File f = new File(prefix + docName + "/" + docName + "_" + sectionName); assert f.createNewFile(); FileOutputStream outputStream = new FileOutputStream(f); IOUtils.write(s.substring(start), outputStream); } } }
From source file:com.wavemaker.tools.data.ImportDB.java
private void removeConstructor() { Resources<com.wavemaker.tools.io.File> javafiles = this.javadir.list().files() .include(FilterOn.names().ending(".java")); if (javafiles != null) { try {// ww w . j a v a2 s. c om for (com.wavemaker.tools.io.File file : javafiles) { InputStream is = file.getContent().asInputStream(); String content = IOUtils.toString(is, ServerConstants.DEFAULT_ENCODING); is.close(); String fileName = file.getName(); int len = fileName.length(); fileName = fileName.substring(0, len - 5); String regExp = "public\\s+" + fileName + "\\s*\\([^\\)]*\\)\\s*\\{[^\\}]*\\}"; Pattern pattern = Pattern.compile(regExp); Matcher matcher = pattern.matcher(content); boolean done = false; int indx1, indx2; String str; while (!done) { if (matcher.find()) { indx1 = matcher.start(); indx2 = matcher.end(); str = content.substring(indx1, indx2); content = content.replace(str, ""); matcher = pattern.matcher(content); } else { done = true; } } // FileUtils.writeStringToFile(file, content, ServerConstants.DEFAULT_ENCODING); OutputStream os = file.getContent().asOutputStream(); IOUtils.write(content, os, ServerConstants.DEFAULT_ENCODING); os.close(); } } catch (IOException ioe) { throw new WMRuntimeException(ioe); } } }
From source file:com.zimbra.common.util.TemplateCompiler.java
public static void compile(File ifile, File ofile, String format, String pkg, boolean authoritative, boolean define) throws IOException { BufferedReader in = null;/* w w w. j a v a 2s.com*/ PrintWriter out = null; try { boolean isProperties = format.equals("properties"); in = new BufferedReader(new FileReader(ifile)); out = new PrintWriter(new FileWriter(ofile)); String lines = readLines(in); Matcher matcher = RE_TEMPLATE.matcher(lines); if (matcher.find()) { boolean first = true; do { Map<String, String> attrs = parseAttrs(matcher.group(1)); String templateId = attrs.get("id"); String packageId = pkg; // NOTE: Template ids can be specified absolutely (i.e. // overriding the default package) if the id starts // with a forward slash (/), or if the id contains // a hash mark (#). This allows a template file to // override both types of template files (i.e. a // single template per file or multiple templates // per file). if (templateId != null && (templateId.indexOf('#') != -1 || templateId.startsWith("/"))) { if (templateId.indexOf('#') == -1) templateId += "#"; packageId = templateId.replaceAll("#.*$", "").replaceAll("^/", "").replace('/', '.'); templateId = templateId.replaceAll("^.*#", ""); } String id = templateId != null && !templateId.equals("") ? packageId + "#" + templateId : packageId; // copy to .properties file if (isProperties) { printEscaped(out, id); String body = lines.substring(matcher.start(), matcher.end()); if (body.indexOf('\n') == -1) { out.print(" = "); printEscaped(out, body); } else { out.print(" ="); String[] bodylines = body.split("\n"); for (String bodyline : bodylines) { out.print("\\\n\t"); printEscaped(out, bodyline); } } out.println(); continue; } // compile to JavaScript String body = matcher.group(2); String stripWsAttr = attrs.get(A_XML_SPACE); if (stripWsAttr == null || !stripWsAttr.equals(V_XML_SPACE_PRESERVE)) { body = body.replaceAll(S_GT_LINESEP_LT, "><").trim(); } convertLines(out, id, body, attrs, authoritative); if (first && define) { out.print("AjxPackage.define(\""); out.print(packageId); out.println("\");"); } if (first) { first = false; out.print("AjxTemplate.register(\""); out.print(packageId); out.print("\", "); out.print("AjxTemplate.getTemplate(\""); out.print(id); out.print("\"), "); out.print("AjxTemplate.getParams(\""); out.print(id); out.println("\"));"); } out.println(); } while (matcher.find()); } else { convertLines(out, pkg, lines, null, authoritative); } } finally { if (in != null) { try { in.close(); } catch (Exception e) { // ignore } } if (out != null) { out.close(); } } }
From source file:$.LogParser.java
/** * Processes the next log line by either appending it to the last log event, * if it's not a valid log line and last log event wasn't ignored (appendTo != null); * or by parsing it into a new event (parseTo). */*w w w.j a v a 2 s . c om*/ * @param line the log line to process * @param parseTo the next log event to parse line into * @param appendTo the log event to append non-event lines to * @param config log parser config * @return appendTo event, if the line was appended to it; parseTo event if the line was fully parsed into this event; * or null if the line was ignored */ LogEvent parseLine(String line, LogEvent parseTo, LogEvent appendTo, LogParserConfig config) { Matcher dateMatcher = config.getDatePattern().matcher(line); if (!dateMatcher.lookingAt()) { return parseFailed(line, appendTo); } DateTime eventDate = getDate(dateMatcher.group(1), config); if (eventDate == null) { return parseFailed(line, appendTo); } // line might still not match properties and therefore not be a new log event, // so don't stop just yet, even if the date is wrong boolean skipLogLine = eventDate.isBefore(config.getFromDate()); if (skipLogLine && appendTo == null) { return null; // no point continuing, since this line wouldn't be appended anyway } parseTo.setDate(eventDate); String unmatched = line.substring(0, dateMatcher.start()) + line.substring(dateMatcher.end(), line.length()); // date matches, but is the line a new log event line? Matcher propertiesMatcher = config.getPropertiesPattern().matcher(unmatched); if (!propertiesMatcher.lookingAt()) { return parseFailed(line, appendTo); } if (skipLogLine || !parseEventProperties(propertiesMatcher, parseTo, config)) { return null; } if (unmatched != null && config.getMsg() != null && !unmatched.contains(config.getMsg())) { return null; } unmatched = unmatched.substring(0, propertiesMatcher.start()) + unmatched.substring(propertiesMatcher.end(), unmatched.length()); parseTo.setMessage(unmatched); return parseTo; }