List of usage examples for java.util Formatter Formatter
public Formatter(OutputStream os)
From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java
/** * Encodes characters in the query or fragment part of the URI. * * <p>Unfortunately, an incoming URI sometimes has characters disallowed by the spec. HttpClient * insists that the outgoing proxied request has a valid URI because it uses Java's {@link URI}. * To be more forgiving, we must escape the problematic characters. See the URI class for the * spec./* w ww. j a v a 2 s . co m*/ * * @param in example: name=value&foo=bar#fragment */ protected static CharSequence encodeUriQuery(CharSequence in) { //Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things. StringBuilder outBuf = null; Formatter formatter = null; for (int i = 0; i < in.length(); i++) { char c = in.charAt(i); boolean escape = true; if (c < 128) { if (asciiQueryChars.get((int) c)) { escape = false; } } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii escape = false; } if (!escape) { if (outBuf != null) outBuf.append(c); } else { //escape if (outBuf == null) { outBuf = new StringBuilder(in.length() + 5 * 3); outBuf.append(in, 0, i); formatter = new Formatter(outBuf); } //leading %, 0 padded, width 2, capital hex formatter.format("%%%02X", (int) c);//TODO } } return outBuf != null ? outBuf : in; }
From source file:org.apache.poi.ss.format.CellNumberFormatter.java
/** {@inheritDoc} */ public void formatValue(StringBuffer toAppendTo, Object valueObject) { double value = ((Number) valueObject).doubleValue(); value *= scale;//ww w . j a v a 2s .co m // the '-' sign goes at the front, always, so we pick it out boolean negative = value < 0; if (negative) value = -value; // Split out the fractional part if we need to print a fraction double fractional = 0; if (slash != null) { if (improperFraction) { fractional = value; value = 0; } else { fractional = value % 1.0; //noinspection SillyAssignment value = (long) value; } } Set<StringMod> mods = new TreeSet<>(); StringBuffer output = new StringBuffer(desc); if (exponent != null) { writeScientific(value, output, mods); } else if (improperFraction) { writeFraction(value, null, fractional, output, mods); } else { StringBuffer result = new StringBuffer(); Formatter f = new Formatter(result); f.format(LOCALE, printfFmt, value); if (numerator == null) { writeFractional(result, output); writeInteger(result, output, integerSpecials, mods, integerCommas); } else { writeFraction(value, result, fractional, output, mods); } } // Now strip out any remaining '#'s and add any pending text ... ListIterator<Special> it = specials.listIterator(); Iterator<StringMod> changes = mods.iterator(); StringMod nextChange = (changes.hasNext() ? changes.next() : null); int adjust = 0; BitSet deletedChars = new BitSet(); // records chars already deleted while (it.hasNext()) { Special s = it.next(); int adjustedPos = s.pos + adjust; if (!deletedChars.get(s.pos) && output.charAt(adjustedPos) == '#') { output.deleteCharAt(adjustedPos); adjust--; deletedChars.set(s.pos); } while (nextChange != null && s == nextChange.special) { int lenBefore = output.length(); int modPos = s.pos + adjust; int posTweak = 0; switch (nextChange.op) { case StringMod.AFTER: // ignore adding a comma after a deleted char (which was a '#') if (nextChange.toAdd.equals(",") && deletedChars.get(s.pos)) break; posTweak = 1; //noinspection fallthrough case StringMod.BEFORE: output.insert(modPos + posTweak, nextChange.toAdd); break; case StringMod.REPLACE: int delPos = s.pos; // delete starting pos in original coordinates if (!nextChange.startInclusive) { delPos++; modPos++; } // Skip over anything already deleted while (deletedChars.get(delPos)) { delPos++; modPos++; } int delEndPos = nextChange.end.pos; // delete end point in original if (nextChange.endInclusive) delEndPos++; int modEndPos = delEndPos + adjust; // delete end point in current if (modPos < modEndPos) { if (nextChange.toAdd == "") output.delete(modPos, modEndPos); else { char fillCh = nextChange.toAdd.charAt(0); for (int i = modPos; i < modEndPos; i++) output.setCharAt(i, fillCh); } deletedChars.set(delPos, delEndPos); } break; default: throw new IllegalStateException("Unknown op: " + nextChange.op); } adjust += output.length() - lenBefore; if (changes.hasNext()) nextChange = changes.next(); else nextChange = null; } } // Finally, add it to the string if (negative) toAppendTo.append('-'); toAppendTo.append(output); }
From source file:com.insprise.common.lang.StringUtilities.java
/** * Returns a properly formatted string representation of the given table (a list of lists of strings). * <p><code><pre>{@code List<List<Object>> lists = new ArrayList<List<Object>>(); * List<Object> list = new ArrayList<Object>(); * list.add("ID");/*from w ww. jav a 2 s . c o m*/ * list.add("Name"); * list.add("Remarks"); * lists.add(list); * * list = new ArrayList<Object>(); * list.add("A"); * list.add("Jack"); * list.add("Employee group"); * list.add("8"); * lists.add(list); * * System.out.println(StringUtilities.displayTable(lists, true, 10)); * * [Results] * +----+------+------------+-------+ * | ID | Name | Remarks | Score | * +----+------+------------+-------+ * | A | Jack | Employee | 8 | * | | | group | | * +----+------+------------+-------+}</pre></code> * @param table * @param firstRowHeadRead is the first row the head read? * if set to <code>true</code>, a line separator will be inserted after the first line. * @param maxColumnLength the max. length of a column. If the data is longer, it will be wrapped. * @return a properly formatted string representation of the given table (a list of lists of strings). */ public static String displayTable(List<List<Object>> table, boolean firstRowHeadRead, int maxColumnLength) { List<Integer> lengths = new ArrayList<Integer>(); // first, find column length. for (int r = 0; r < table.size(); r++) { // for each row for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col String s = null; if (table.get(r).get(c) != null) { s = table.get(r).get(c).toString(); } Integer oldLength = null; if (lengths.size() > c) { oldLength = lengths.get(c); } else { lengths.add(null); } if (s != null) { if (oldLength == null) { lengths.set(c, Math.min(s.length(), maxColumnLength)); } else { lengths.set(c, Math.min(maxColumnLength, Math.max(s.length(), oldLength))); } } else if (oldLength == null || oldLength == 0) { lengths.set(c, 0); } } } StringBuilder sb = new StringBuilder("\n"); // always starts with a new line to avoid misplacement. Formatter formatter = new Formatter(sb); // ------ starts print separator line. for (int i = 0; i < lengths.size(); i++) { sb.append("+-"); // margin is 2. int colLength = lengths.get(i); for (int j = 0; j < colLength + 1; j++) { sb.append("-"); } } sb.append("+"); // ------ finishes print separator line. HashMap<Integer, String[]> wraps = new HashMap<Integer, String[]>(); // used to contain wraps. for (int r = 0; r < table.size(); r++) { // for each row int rowHeight = 1; wraps.clear(); for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col int colLength = lengths.get(c); if (c == 0) { sb.append("\n"); // first col. } sb.append(c == 0 && (!firstRowHeadRead || (firstRowHeadRead && r != 0)) ? "> " : "| "); String s = null; if (table.get(r).get(c) != null) { s = table.get(r).get(c).toString(); } if (s == null) { formatter.format("%-" + colLength + "s", ""); } else { if (s.length() > colLength) { String[] wrap = wrap(s, colLength, true); rowHeight = Math.max(rowHeight, wrap.length); wraps.put(c, wrap); formatter.format("%-" + colLength + "s", wrap[0]); } else { formatter.format("%-" + (colLength == 0 ? 1 : colLength) + "s", s); } } sb.append(" "); // margin. if (c == table.get(r).size() - 1) { // last row sb.append("|"); } } for (int k = 1; k < rowHeight; k++) { // rowHeight > 1 for (int c = 0; table.get(r) != null && c < table.get(r).size(); c++) { // for each col int colLength = lengths.get(c); if (c == 0) { sb.append("\n"); // first col. } sb.append("| "); String s = null; String[] wrap = wraps.get(c); if (wrap != null && wrap.length > k) { s = wrap[k]; } if (s == null) { formatter.format("%-" + (colLength == 0 ? 1 : colLength) + "s", ""); } else { formatter.format("%-" + colLength + "s", s); } sb.append(" "); // margin. if (c == table.get(r).size() - 1) { // last row sb.append("|"); } } } // end for // rowHeight > 1. if (firstRowHeadRead && r == 0) { // ------ starts print separator line. sb.append("\n"); for (int i = 0; i < lengths.size(); i++) { sb.append("+-"); // margin is 2. int colLength = lengths.get(i); for (int j = 0; j < colLength + 1; j++) { sb.append("-"); } } sb.append("+"); // ------ finishes print separator line. } } // end for each row // ------ starts print separator line. sb.append("\n"); for (int i = 0; i < lengths.size(); i++) { sb.append("+-"); // margin is 2. int colLength = lengths.get(i); for (int j = 0; j < colLength + 1; j++) { sb.append("-"); } } sb.append("+"); // ends // ------ finishes print separator line. return sb.toString(); }
From source file:umontreal.iro.lecuyer.charts.XYLineChart.java
public String toLatex(double width, double height) { double xunit = 0, yunit = 0; double[] save = new double[4]; if (dataset.getSeriesCollection().getSeriesCount() == 0) throw new IllegalArgumentException("Empty chart"); //Calcul des parametres d'echelle et de decalage double XScale = computeXScale(XAxis.getTwinAxisPosition()); double YScale = computeYScale(YAxis.getTwinAxisPosition()); // taille d'une unite en x et en cm dans l'objet "tikzpicture" xunit = width / ((Math.max(XAxis.getAxis().getRange().getUpperBound(), XAxis.getTwinAxisPosition()) * XScale)/* ww w . ja v a 2s .co m*/ - (Math.min(XAxis.getAxis().getRange().getLowerBound(), XAxis.getTwinAxisPosition()) * XScale)); // taille d'une unite en y et en cm dans l'objet "tikzpicture" yunit = height / ((Math.max(YAxis.getAxis().getRange().getUpperBound(), YAxis.getTwinAxisPosition()) * YScale) - (Math.min(YAxis.getAxis().getRange().getLowerBound(), YAxis.getTwinAxisPosition()) * YScale)); Formatter formatter = new Formatter(Locale.US); /*Entete du document*/ if (latexDocFlag) { formatter.format("\\documentclass[12pt]{article}%n%n"); formatter.format("\\usepackage{tikz}%n\\usetikzlibrary{plotmarks}%n\\begin{document}%n%n"); } if (chart.getTitle() != null) formatter.format("%% PGF/TikZ picture from SSJ: %s%n", chart.getTitle().getText()); else formatter.format("%% PGF/TikZ picture from SSJ %n"); formatter.format("%% XScale = %s, YScale = %s, XShift = %s, YShift = %s%n", XScale, YScale, XAxis.getTwinAxisPosition(), YAxis.getTwinAxisPosition()); formatter.format("%% Therefore, thisFileXValue = (originalSeriesXValue+XShift)*XScale%n"); formatter.format("%% and thisFileYValue = (originalSeriesYValue+YShift)*YScale%n%n"); if (chart.getTitle() != null) formatter.format("\\begin{figure}%n"); formatter.format("\\begin{center}%n"); formatter.format("\\begin{tikzpicture}[x=%scm, y=%scm]%n", xunit, yunit); formatter.format("\\footnotesize%n"); if (grid) formatter.format("\\draw[color=lightgray] (%s, %s) grid[xstep = %s, ystep=%s] (%s, %s);%n", (Math.min(XAxis.getAxis().getRange().getLowerBound(), XAxis.getTwinAxisPosition()) - XAxis.getTwinAxisPosition()) * XScale, (Math.min(YAxis.getAxis().getRange().getLowerBound(), YAxis.getTwinAxisPosition()) - YAxis.getTwinAxisPosition()) * YScale, xstepGrid * XScale, ystepGrid * YScale, (Math.max(XAxis.getAxis().getRange().getUpperBound(), XAxis.getTwinAxisPosition()) - XAxis.getTwinAxisPosition()) * XScale, (Math.max(YAxis.getAxis().getRange().getUpperBound(), YAxis.getTwinAxisPosition()) - YAxis.getTwinAxisPosition()) * YScale); setTick0Flags(); formatter.format("%s", XAxis.toLatex(XScale)); formatter.format("%s", YAxis.toLatex(YScale)); formatter.format("%s", dataset.toLatex(XScale, YScale, XAxis.getTwinAxisPosition(), YAxis.getTwinAxisPosition(), XAxis.getAxis().getLowerBound(), XAxis.getAxis().getUpperBound(), YAxis.getAxis().getLowerBound(), YAxis.getAxis().getUpperBound())); formatter.format("\\end{tikzpicture}%n"); formatter.format("\\end{center}%n"); if (chart.getTitle() != null) { formatter.format("\\caption{"); formatter.format(chart.getTitle().getText()); formatter.format("}%n\\end{figure}%n"); } if (latexDocFlag) formatter.format("\\end{document}%n"); return formatter.toString(); }
From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java
/** * Calculates the cluster novelty feature for each cluster generated * on a specific run date and stores them in the database. * * @param log_date the run date//from ww w . j a v a2 s.c o m * @throws Exception if there is an error calculating or storing the feature * values */ public void updateNoveltyFeature(Date log_date) throws Exception { Map<Integer, String> windowvals = new TreeMap<Integer, String>(); String[] windowsstr = properties.getProperty(NOVELTY_WINDOWSKEY).split(","); String[] windowfields = properties.getProperty(NOVELTY_WINFIELDSKEY).split(","); if (windowfields.length != windowsstr.length) { throw new Exception("Number of novelty window values and fields do not match."); } for (int i = 0; i < windowsstr.length; i++) { windowvals.put(Integer.parseInt(windowsstr[i]), windowfields[i]); } //We start from largest window to smallest so we can cache the prevDates results for later use List<Integer> windowkeys = new ArrayList<Integer>(windowvals.keySet()); Collections.reverse(windowkeys); for (int window : windowkeys) { Map<Integer, Double> novelty = calculateNoveltyFeature(log_date, window); for (int clusterid : novelty.keySet()) { StringBuffer querybuf = new StringBuffer(); Formatter formatter = new Formatter(querybuf); formatter.format(properties.getProperty(NOVELTY_QUERY3KEY), df.format(log_date), windowvals.get(window), String.valueOf(novelty.get(clusterid)), String.valueOf(clusterid), df.format(log_date)); dbi.executeQueryNoResult(querybuf.toString()); formatter.close(); } } }
From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java
/** * Calculates the previous cluster ratio feature for each cluster generated * on a specific run date and stores them in the database. * * @param log_date the run date// ww w . j av a 2 s . c om * @throws SQLException if the feature values can not be stored in the database */ public void updatePrevClusterRatios(Date log_date) throws SQLException { Hashtable<Integer, List<Double>> ratios = this.calculatePrevClusterRatios(log_date, Integer.parseInt(properties.getProperty(PREVCLUSTER_WINDOWKEY))); for (int clusterid : ratios.keySet()) { List<Double> ratiovals = ratios.get(clusterid); StringBuffer querybuf = new StringBuffer(); Formatter formatter = new Formatter(querybuf); formatter.format(properties.getProperty(PREVCLUSTER_QUERY4KEY), df.format(log_date), ratiovals.get(0).toString(), ratiovals.get(1).toString(), Integer.toString(clusterid)); dbi.executeQueryNoResult(querybuf.toString()); formatter.close(); } }
From source file:org.apache.abdera.util.AbstractStreamWriter.java
public StreamWriter writeElementText(String format, Object... args) { new Formatter(this).format(format, args); return this; }
From source file:edu.stanford.muse.index.EmailDocument.java
public String getSignature() { StringBuilder sb = new StringBuilder(); StringBuilder timeSB = new StringBuilder(); Formatter formatter = new Formatter(timeSB); if (this.date != null) { GregorianCalendar cc = new GregorianCalendar(); cc.setTime(this.date); formatter.format("%02d:%02d", new Object[] { Integer.valueOf(cc.get(11)), Integer.valueOf(cc.get(12)) }); sb.append("Date: " + cc.get(5) + " " + CalendarUtil.getDisplayMonth(cc) + " " + cc.get(1) + " " + timeSB + "\n"); }/*from w w w . j a v a2 s . c o m*/ formatter.close(); sb.append("From: " + this.getFromString() + "\n"); sb.append("To: " + this.getToString() + "\n"); String cc1 = this.getCcString(); if (!Util.nullOrEmpty(cc1)) { sb.append("Cc: " + cc1 + "\n"); } String bcc = this.getBccString(); if (!Util.nullOrEmpty(bcc)) { sb.append("Bcc: " + bcc + "\n"); } if (this.description == null) { this.description = "<None>"; } sb.append("Subject: " + this.description + "\n"); sb.append("\n"); return sb.toString(); }
From source file:org.owasp.appsensor.block.proxy.servlet.ProxyServlet.java
/** * Encodes characters in the query or fragment part of the URI. * * <p>Unfortunately, an incoming URI sometimes has characters disallowed by the spec. HttpClient * insists that the outgoing proxied request has a valid URI because it uses Java's {@link URI}. * To be more forgiving, we must escape the problematic characters. See the URI class for the * spec./* w ww.j ava 2s .c o m*/ * * @param in example: name=value&foo=bar#fragment */ @SuppressWarnings("resource") protected static CharSequence encodeUriQuery(CharSequence in) { //Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things. StringBuilder outBuf = null; Formatter formatter = null; for (int i = 0; i < in.length(); i++) { char c = in.charAt(i); boolean escape = true; if (c < 128) { if (asciiQueryChars.get((int) c)) { escape = false; } } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii escape = false; } if (!escape) { if (outBuf != null) outBuf.append(c); } else { //escape if (outBuf == null) { outBuf = new StringBuilder(in.length() + 5 * 3); outBuf.append(in, 0, i); formatter = new Formatter(outBuf); } //leading %, 0 padded, width 2, capital hex formatter.format("%%%02X", (int) c);//TODO } } return outBuf != null ? outBuf : in; }
From source file:umontreal.iro.lecuyer.charts.XYListSeriesCollection.java
public String toLatex(double XScale, double YScale, double XShift, double YShift, double xmin, double xmax, double ymin, double ymax) { // Calcule les bornes reelles du graphique, en prenant en compte la position des axes xmin = Math.min(XShift, xmin); xmax = Math.max(XShift, xmax); ymin = Math.min(YShift, ymin); ymax = Math.max(YShift, ymax); Formatter formatter = new Formatter(Locale.US); XYSeriesCollection tempSeriesCollection = (XYSeriesCollection) seriesCollection; double XEPSILON = (1.0E-4 / XScale) + XShift; double YEPSILON = (1.0E-4 / YScale) + YShift; boolean outOfBounds = false; MathFunction[] spline = null;//from w ww .j av a2s.c om double[] xBounds = getRangeBounds(); double[] yBounds = getDomainBounds(); double x, y; // Smoothing splines, consulter ref: QA278.2 G74, QA278.2 T35, QA278.2 E87 // if(xBounds[0] < xmin || xBounds[1] > xmax || yBounds[0] < ymin || yBounds[1] > ymax) { // // on sait qu'il y a des points qui vont sortir du chart // // initialisation d'une spline pour chaque courbe // spline = new SmoothingCubicSpline[seriesCollection.getSeriesCount()]; // for(int i = 0; i<seriesCollection.getSeriesCount(); i++) // spline[i] = new SmoothingCubicSpline( (seriesCollection.getSeries(i).toArray())[0], // (seriesCollection.getSeries(i).toArray())[1], 0.5); // } // on sait qu'il y a des points qui vont sortir du chart // initialisation d'une spline pour chaque courbe if (true) { spline = new SmoothingCubicSpline[tempSeriesCollection.getSeriesCount()]; for (int i = 0; i < tempSeriesCollection.getSeriesCount(); i++) spline[i] = new SmoothingCubicSpline((tempSeriesCollection.getSeries(i).toArray())[0], (tempSeriesCollection.getSeries(i).toArray())[1], 1); } else { spline = new AffineFit[tempSeriesCollection.getSeriesCount()]; for (int i = 0; i < tempSeriesCollection.getSeriesCount(); i++) spline[i] = new AffineFit((tempSeriesCollection.getSeries(i).toArray())[0], (tempSeriesCollection.getSeries(i).toArray())[1]); } for (int i = tempSeriesCollection.getSeriesCount() - 1; i >= 0; i--) { XYSeries temp = tempSeriesCollection.getSeries(i); if (temp.getItemCount() < 2) throw new IllegalArgumentException( "Unable to plot series " + i + ": this series must have two points at least"); Color color = (Color) renderer.getSeriesPaint(i); String colorString = detectXColorClassic(color); if (colorString == null) { colorString = "color" + i; formatter.format("\\definecolor{%s}{rgb}{%.2f, %.2f, %.2f}%n", colorString, color.getRed() / 255.0, color.getGreen() / 255.0, color.getBlue() / 255.0); } // Cas particulier pour le premier point, on doit savoir si il est dans le chart ou pas if (temp.getX(0).doubleValue() >= xmin && temp.getX(0).doubleValue() <= xmax && temp.getY(0).doubleValue() >= ymin && temp.getY(0).doubleValue() <= ymax) { outOfBounds = false; formatter.format("\\draw [%s, color=%s, mark=%s, style=%s] plot coordinates {%%%n", plotStyle[i], colorString, marksType[i], dashPattern[i]); } else { outOfBounds = true; formatter.format("%% "); } formatter.format("(%.2f,%.4f)", (temp.getX(0).doubleValue() - XShift) * XScale, (temp.getY(0).doubleValue() - YShift) * YScale); formatter.format(" %% (%f, %f)%n", temp.getX(0).doubleValue(), temp.getY(0).doubleValue()); // Cas general for (int j = 1; j < temp.getItemCount(); j++) { double[] result; if (!outOfBounds) { //on est dans le chart result = evalLimitValues(xmin, xmax, ymin, ymax, XEPSILON, YEPSILON, spline[i], temp, j, false); // on regarde si on ne sort pas du chart, si c'est le cas on evalue le point en limite if (result != null) { // le point courant n'est pas dans le chart, on sort donc du chart outOfBounds = true; if (autoCompletion) formatter.format("(%.2f,%.4f) %%%n", (result[0] - XShift) * XScale, (result[1] - YShift) * YScale); formatter.format("}%%%n%% "); } } else { // le point precedent etait hors du chart if (temp.getX(j).doubleValue() >= xmin && temp.getX(j).doubleValue() <= xmax && temp.getY(j).doubleValue() >= ymin && temp.getY(j).doubleValue() <= ymax) { // on rentre dans le chart, il faut evaluer le point en limite j = j - 1; result = evalLimitValues(xmin, xmax, ymin, ymax, XEPSILON, YEPSILON, spline[i], temp, j, true); // ici result ne peut pas etre null formatter.format(";%%%n\\draw [%s, color=%s, mark=%s, style=%s] plot coordinates {%%%n", plotStyle[i], colorString, marksType[i], dashPattern[i]); if (autoCompletion) formatter.format("(%.2f,%.4f) %%%n ", (result[0] - XShift) * XScale, (result[1] - YShift) * YScale); formatter.format("%% "); outOfBounds = false; } else { formatter.format("%% "); // on les donnees sont toujours hors du chart } } /* on affiche les coordonnees du point quoiqu'il arrive, si celui ci est hors du chart alors la balise de commentaire a ete deja place */ formatter.format("(%.2f,%.4f)", (temp.getX(j).doubleValue() - XShift) * XScale, (temp.getY(j).doubleValue() - YShift) * YScale); if (j == temp.getItemCount() - 1) formatter.format("}"); formatter.format(" %% (%f, %f)%n", temp.getX(j).doubleValue(), temp.getY(j).doubleValue()); // formatter.format(" %%%n"); } formatter.format(" node[right] {%s};%n", (String) temp.getKey()); } return formatter.toString(); }