Example usage for java.text NumberFormat getInstance

List of usage examples for java.text NumberFormat getInstance

Introduction

In this page you can find the example usage for java.text NumberFormat getInstance.

Prototype

public static NumberFormat getInstance(Locale inLocale) 

Source Link

Document

Returns a general-purpose number format for the specified locale.

Usage

From source file:de.bund.bfr.knime.pmmlite.views.chart.ChartCreator.java

private List<XYDataset> createStrictDataSets(Plotable plotable, String id) throws UnitException {
    List<XYDataset> dataSets = new ArrayList<>();

    for (Map<String, Integer> choiceMap : plotable.getAllChoices(varX.getName())) {
        double[][] dataPoints = plotable.getPoints(varX, varY, choiceMap);

        if (dataPoints == null) {
            dataSets.add(null);/*from w ww  . j  av a2 s. c o m*/
            continue;
        }

        DefaultXYDataset dataSet = new DefaultXYDataset();
        StringBuilder addLegend = new StringBuilder();

        for (Map.Entry<String, Integer> entry : choiceMap.entrySet()) {
            if (!entry.getKey().equals(varX.getName())) {
                Double value = plotable.getVariables().get(entry.getKey()).get(entry.getValue());

                if (value != null) {
                    String s = NumberFormat.getInstance(Locale.US).format(value);

                    addLegend.append(" (" + entry.getKey() + "=" + s + ")");
                }
            }
        }

        dataSet.addSeries(legend.get(id) + addLegend, dataPoints);
        dataSets.add(dataSet);
    }

    return dataSets;
}

From source file:de.bund.bfr.knime.gis.views.canvas.CanvasUtils.java

public static String toString(Object obj) {
    if (obj instanceof Number) {
        return NumberFormat.getInstance(Locale.US).format(obj);
    }//from w  ww. j  av a2 s . com

    return obj != null ? obj.toString() : null;
}

From source file:net.sf.jasperreports.engine.fill.DefaultChartTheme.java

/**
 * Sets all the axis formatting options.  This includes the colors and fonts to use on
 * the axis as well as the color to use when drawing the axis line.
 *
 * @param axis the axis to format/* ww  w.  ja v a 2s. c om*/
 * @param labelFont the font to use for the axis label
 * @param labelColor the color of the axis label
 * @param tickLabelFont the font to use for each tick mark value label
 * @param tickLabelColor the color of each tick mark value label
 * @param tickLabelMask formatting mask for the label.  If the axis is a NumberAxis then
 *                    the mask should be <code>java.text.DecimalFormat</code> mask, and
 *                   if it is a DateAxis then the mask should be a
 *                   <code>java.text.SimpleDateFormat</code> mask.
 * @param verticalTickLabels flag to draw tick labels at 90 degrees
 * @param lineColor color to use when drawing the axis line and any tick marks
 */
protected void configureAxis(Axis axis, JRFont labelFont, Color labelColor, JRFont tickLabelFont,
        Color tickLabelColor, String tickLabelMask, Boolean verticalTickLabels, Color lineColor,
        boolean isRangeAxis, Comparable<?> axisMinValue, Comparable<?> axisMaxValue) {
    axis.setLabelFont(fontUtil.getAwtFont(getFont(labelFont), getLocale()));
    axis.setTickLabelFont(fontUtil.getAwtFont(getFont(tickLabelFont), getLocale()));
    if (labelColor != null) {
        axis.setLabelPaint(labelColor);
    }

    if (tickLabelColor != null) {
        axis.setTickLabelPaint(tickLabelColor);
    }

    if (lineColor != null) {
        axis.setAxisLinePaint(lineColor);
        axis.setTickMarkPaint(lineColor);
    }

    TimeZone timeZone = chartContext.getTimeZone();
    if (axis instanceof DateAxis && timeZone != null) {
        // used when no mask is set
        ((DateAxis) axis).setTimeZone(timeZone);
    }

    // FIXME use locale for formats
    if (tickLabelMask != null) {
        if (axis instanceof NumberAxis) {
            NumberFormat fmt = NumberFormat.getInstance(getLocale());
            if (fmt instanceof DecimalFormat) {
                ((DecimalFormat) fmt).applyPattern(tickLabelMask);
            }
            ((NumberAxis) axis).setNumberFormatOverride(fmt);
        } else if (axis instanceof DateAxis) {
            DateFormat fmt;
            if (tickLabelMask.equals("SHORT") || tickLabelMask.equals("DateFormat.SHORT")) {
                fmt = DateFormat.getDateInstance(DateFormat.SHORT, getLocale());
            } else if (tickLabelMask.equals("MEDIUM") || tickLabelMask.equals("DateFormat.MEDIUM")) {
                fmt = DateFormat.getDateInstance(DateFormat.MEDIUM, getLocale());
            } else if (tickLabelMask.equals("LONG") || tickLabelMask.equals("DateFormat.LONG")) {
                fmt = DateFormat.getDateInstance(DateFormat.LONG, getLocale());
            } else if (tickLabelMask.equals("FULL") || tickLabelMask.equals("DateFormat.FULL")) {
                fmt = DateFormat.getDateInstance(DateFormat.FULL, getLocale());
            } else {
                fmt = new SimpleDateFormat(tickLabelMask, getLocale());
            }

            if (timeZone != null) {
                fmt.setTimeZone(timeZone);
            }

            ((DateAxis) axis).setDateFormatOverride(fmt);
        }
        // ignore mask for other axis types.
    }

    if (verticalTickLabels != null && axis instanceof ValueAxis) {
        ((ValueAxis) axis).setVerticalTickLabels(verticalTickLabels);
    }

    setAxisBounds(axis, isRangeAxis, axisMinValue, axisMaxValue);
}

From source file:com.concursive.connect.web.portal.PortalUtils.java

public static void populateObject(Object bean, ActionRequest request) {
    String nestedAttribute = "_";

    Enumeration en = request.getParameterNames();
    String paramName = null;//  ww w  .j a  v  a  2  s.  c o m
    while (en.hasMoreElements()) {
        paramName = (String) en.nextElement();

        // a form has been submitted and requested to be auto-populated,
        // so we do that here..going through every element and trying
        // to call a setXXX() method on the bean object passed in for the value
        // of the request parameter currently being checked.
        String[] paramValues = request.getParameterValues(paramName);
        if (paramValues.length > 1) {
            ObjectUtils.setParam(bean, paramName, paramValues, nestedAttribute);
        } else {
            ObjectUtils.setParam(bean, paramName, paramValues[0], nestedAttribute);
        }
    }

    // TODO: currently for ticket and ticket history
    //ObjectUtils.invokeMethod(bean, "setRequestItems", new HttpRequestContext(request));
    // Check for valid user
    User thisUser = (User) request.getAttribute(Constants.REQUEST_USER);
    if (thisUser != null) {
        // Populate date/time fields using the user's timezone and locale
        if (thisUser.getTimeZone() != null) {
            ArrayList timeParams = (ArrayList) ObjectUtils.getObject(bean, "TimeZoneParams");
            if (timeParams != null) {
                Calendar cal = Calendar.getInstance();
                Iterator i = timeParams.iterator();
                while (i.hasNext()) {
                    // The property that can be set
                    String name = (String) i.next();
                    // See if it is in the request
                    String value = request.getParameter(name);
                    if (value != null) {
                        // See if time is in request too
                        String hourValue = request.getParameter(name + "Hour");
                        if (hourValue == null) {
                            // Date fields: 1-1 mapping between HTML field and Java property
                            ObjectUtils.setParam(bean, name,
                                    DateUtils.getUserToServerDateTimeString(
                                            TimeZone.getTimeZone(thisUser.getTimeZone()), DateFormat.SHORT,
                                            DateFormat.LONG, value, thisUser.getLocale()));
                        } else {
                            // Date & Time fields: 4-1 mapping between HTML fields and Java property
                            try {
                                Timestamp timestamp = DatabaseUtils.parseDateToTimestamp(value,
                                        thisUser.getLocale());
                                cal.setTimeInMillis(timestamp.getTime());
                                int hour = Integer.parseInt(hourValue);
                                int minute = Integer.parseInt(request.getParameter(name + "Minute"));
                                String ampmString = request.getParameter(name + "AMPM");
                                if (ampmString != null) {
                                    int ampm = Integer.parseInt(ampmString);
                                    if (ampm == Calendar.AM) {
                                        if (hour == 12) {
                                            hour = 0;
                                        }
                                    } else {
                                        if (hour < 12) {
                                            hour += 12;
                                        }
                                    }
                                }
                                cal.set(Calendar.HOUR_OF_DAY, hour);
                                cal.set(Calendar.MINUTE, minute);
                                cal.setTimeZone(TimeZone.getTimeZone(thisUser.getTimeZone()));
                                ObjectUtils.setParam(bean, name, new Timestamp(cal.getTimeInMillis()));
                            } catch (Exception dateE) {
                            }
                        }
                    }
                }
            }
        }

        // Populate number fields using the user's locale
        if (thisUser.getLocale() != null) {
            ArrayList numberParams = (ArrayList) ObjectUtils.getObject(bean, "NumberParams");
            if (numberParams != null) {
                NumberFormat nf = NumberFormat.getInstance(thisUser.getLocale());
                Iterator i = numberParams.iterator();
                while (i.hasNext()) {
                    // The property that can be set
                    String name = (String) i.next();
                    // See if it is in the request
                    String value = (String) request.getParameter(name);
                    if (value != null && !"".equals(value)) {
                        try {
                            // Parse the value
                            ObjectUtils.setParam(bean, name, nf.parse(value).doubleValue());
                        } catch (Exception e) {
                            //e.printStackTrace(System.out);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.optaplanner.benchmark.impl.report.BenchmarkReport.java

private void writeBestScorePerTimeSpentSummaryChart() {
    // Each scoreLevel has it's own dataset and chartFile
    List<List<XYSeries>> seriesListList = new ArrayList<List<XYSeries>>(CHARTED_SCORE_LEVEL_SIZE);
    int solverBenchmarkIndex = 0;
    for (SolverBenchmarkResult solverBenchmarkResult : plannerBenchmarkResult.getSolverBenchmarkResultList()) {
        String solverLabel = solverBenchmarkResult.getNameWithFavoriteSuffix();
        for (SingleBenchmarkResult singleBenchmarkResult : solverBenchmarkResult
                .getSingleBenchmarkResultList()) {
            if (singleBenchmarkResult.isSuccess()) {
                long timeMillisSpent = singleBenchmarkResult.getTimeMillisSpent();
                double[] levelValues = ScoreUtils.extractLevelDoubles(singleBenchmarkResult.getScore());
                for (int i = 0; i < levelValues.length && i < CHARTED_SCORE_LEVEL_SIZE; i++) {
                    if (i >= seriesListList.size()) {
                        seriesListList.add(new ArrayList<XYSeries>(
                                plannerBenchmarkResult.getSolverBenchmarkResultList().size()));
                    }//from w ww  .ja  v  a  2  s .  c o  m
                    List<XYSeries> seriesList = seriesListList.get(i);
                    while (solverBenchmarkIndex >= seriesList.size()) {
                        seriesList.add(new XYSeries(solverLabel));
                    }
                    seriesList.get(solverBenchmarkIndex).add((Long) timeMillisSpent, (Double) levelValues[i]);
                }
            }
        }
        solverBenchmarkIndex++;
    }
    bestScorePerTimeSpentSummaryChartFileList = new ArrayList<File>(seriesListList.size());
    int scoreLevelIndex = 0;
    for (List<XYSeries> seriesList : seriesListList) {
        XYPlot plot = createScalabilityPlot(seriesList, "Time spent", new MillisecondsSpentNumberFormat(locale),
                "Score level " + scoreLevelIndex, NumberFormat.getInstance(locale));
        JFreeChart chart = new JFreeChart(
                "Best score per time spent level " + scoreLevelIndex + " summary (higher left is better)",
                JFreeChart.DEFAULT_TITLE_FONT, plot, true);
        bestScorePerTimeSpentSummaryChartFileList
                .add(writeChartToImageFile(chart, "bestScorePerTimeSpentSummaryLevel" + scoreLevelIndex));
        scoreLevelIndex++;
    }
}

From source file:net.sf.jasperreports.chartthemes.spring.EyeCandySixtiesChartTheme.java

@Override
protected JFreeChart createMeterChart() throws JRException {
    // Start by creating the plot that will hold the meter
    MeterPlot chartPlot = new MeterPlot((ValueDataset) getDataset());
    JRMeterPlot jrPlot = (JRMeterPlot) getPlot();

    // Set the shape
    MeterShapeEnum shape = jrPlot.getShapeValue() == null ? MeterShapeEnum.DIAL : jrPlot.getShapeValue();

    switch (shape) {
    case CHORD://from  w  w  w.ja  va  2 s .c  om
        chartPlot.setDialShape(DialShape.CHORD);
        break;
    case PIE:
        chartPlot.setDialShape(DialShape.PIE);
        break;
    case CIRCLE:
        chartPlot.setDialShape(DialShape.CIRCLE);
        break;
    case DIAL:
    default:
        return createDialChart();
    }

    chartPlot.setDialOutlinePaint(Color.BLACK);
    int meterAngle = jrPlot.getMeterAngleInteger() == null ? 180 : jrPlot.getMeterAngleInteger();
    // Set the size of the meter
    chartPlot.setMeterAngle(meterAngle);

    // Set the spacing between ticks.  I hate the name "tickSize" since to me it
    // implies I am changing the size of the tick, not the spacing between them.
    double tickInterval = jrPlot.getTickIntervalDouble() == null ? 10.0 : jrPlot.getTickIntervalDouble();
    chartPlot.setTickSize(tickInterval);

    JRFont tickLabelFont = jrPlot.getTickLabelFont();
    Integer defaultBaseFontSize = (Integer) getDefaultValue(defaultChartPropertiesMap,
            ChartThemesConstants.BASEFONT_SIZE);
    Font themeTickLabelFont = getFont(
            (JRFont) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_TICK_LABEL_FONT),
            tickLabelFont, defaultBaseFontSize);
    chartPlot.setTickLabelFont(themeTickLabelFont);

    // localizing the default format, can be overridden by display.getMask()
    chartPlot.setTickLabelFormat(NumberFormat.getInstance(getLocale()));

    Color tickColor = jrPlot.getTickColor() == null ? Color.BLACK : jrPlot.getTickColor();
    chartPlot.setTickPaint(tickColor);
    int dialUnitScale = 1;

    Range range = convertRange(jrPlot.getDataRange());
    // Set the meter's range
    if (range != null) {
        chartPlot.setRange(range);
        double bound = Math.max(Math.abs(range.getUpperBound()), Math.abs(range.getLowerBound()));
        dialUnitScale = ChartThemesUtilities.getScale(bound);
        if ((range.getLowerBound() == (int) range.getLowerBound()
                && range.getUpperBound() == (int) range.getUpperBound() && tickInterval == (int) tickInterval)
                || dialUnitScale > 1) {
            chartPlot.setTickLabelFormat(
                    new DecimalFormat("#,##0", DecimalFormatSymbols.getInstance(getLocale())));
        } else if (dialUnitScale == 1) {
            chartPlot.setTickLabelFormat(
                    new DecimalFormat("#,##0.0", DecimalFormatSymbols.getInstance(getLocale())));
        } else if (dialUnitScale <= 0) {
            chartPlot.setTickLabelFormat(
                    new DecimalFormat("#,##0.00", DecimalFormatSymbols.getInstance(getLocale())));
        }
    }
    chartPlot.setTickLabelsVisible(true);

    // Set all the colors we support
    Paint backgroundPaint = jrPlot.getOwnBackcolor() == null ? ChartThemesConstants.TRANSPARENT_PAINT
            : jrPlot.getOwnBackcolor();
    chartPlot.setBackgroundPaint(backgroundPaint);

    GradientPaint gp = new GradientPaint(new Point(), Color.LIGHT_GRAY, new Point(), Color.BLACK, false);

    if (jrPlot.getMeterBackgroundColor() != null) {
        chartPlot.setDialBackgroundPaint(jrPlot.getMeterBackgroundColor());
    } else {
        chartPlot.setDialBackgroundPaint(gp);
    }
    //chartPlot.setForegroundAlpha(1f);
    Paint needlePaint = jrPlot.getNeedleColor() == null ? new Color(191, 48, 0) : jrPlot.getNeedleColor();
    chartPlot.setNeedlePaint(needlePaint);

    JRValueDisplay display = jrPlot.getValueDisplay();
    if (display != null) {
        Color valueColor = display.getColor() == null ? Color.BLACK : display.getColor();
        chartPlot.setValuePaint(valueColor);
        String pattern = display.getMask() != null ? display.getMask() : "#,##0.####";
        if (pattern != null)
            chartPlot.setTickLabelFormat(
                    new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(getLocale())));
        JRFont displayFont = display.getFont();
        Font themeDisplayFont = getFont(
                (JRFont) getDefaultValue(defaultPlotPropertiesMap, ChartThemesConstants.PLOT_DISPLAY_FONT),
                displayFont, defaultBaseFontSize);

        if (themeDisplayFont != null) {
            chartPlot.setValueFont(themeDisplayFont);
        }
    }
    String label = getChart().hasProperties()
            ? getChart().getPropertiesMap().getProperty(DefaultChartTheme.PROPERTY_DIAL_LABEL)
            : null;

    if (label != null) {
        if (dialUnitScale < 0)
            label = new MessageFormat(label)
                    .format(new Object[] { String.valueOf(Math.pow(10, dialUnitScale)) });
        else if (dialUnitScale < 3)
            label = new MessageFormat(label).format(new Object[] { "1" });
        else
            label = new MessageFormat(label)
                    .format(new Object[] { String.valueOf((int) Math.pow(10, dialUnitScale - 2)) });

    }

    // Set the units - this is just a string that will be shown next to the
    // value
    String units = jrPlot.getUnits() == null ? label : jrPlot.getUnits();
    if (units != null && units.length() > 0)
        chartPlot.setUnits(units);

    chartPlot.setTickPaint(Color.BLACK);

    // Now define all of the intervals, setting their range and color
    List<JRMeterInterval> intervals = jrPlot.getIntervals();
    if (intervals != null && intervals.size() > 0) {
        int size = Math.min(3, intervals.size());

        int colorStep = 0;
        if (size > 3)
            colorStep = 255 / (size - 3);

        for (int i = 0; i < size; i++) {
            JRMeterInterval interval = intervals.get(i);
            Color color = i < 3 ? (Color) ChartThemesConstants.AEGEAN_INTERVAL_COLORS.get(i)
                    : new Color(255 - colorStep * (i - 3), 0 + colorStep * (i - 3), 0);

            interval.setBackgroundColor(color);
            interval.setAlpha(1.0d);
            chartPlot.addInterval(convertInterval(interval));
        }
    }

    // Actually create the chart around the plot
    JFreeChart jfreeChart = new JFreeChart(evaluateTextExpression(getChart().getTitleExpression()), null,
            chartPlot, getChart().getShowLegend() == null ? false : getChart().getShowLegend());

    // Set all the generic options
    configureChart(jfreeChart, getPlot());

    return jfreeChart;

}

From source file:de.bund.bfr.knime.pmmlite.views.chart.ChartCreator.java

private List<XYDataset> createStrictFunctionDataSets(Plotable plotable, String id, double minX, double maxX)
        throws ParseException, UnitException {
    List<XYDataset> dataSets = new ArrayList<>();

    for (Map<String, Integer> choiceMap : plotable.getAllChoices(varX.getName())) {
        double[][] modelPoints = plotable.getFunctionPoints(varX, varY, minX, maxX, choiceMap);

        if (modelPoints == null) {
            dataSets.add(null);//from  w  ww . j ava 2 s.  c o  m
            continue;
        }

        double[][] modelErrors = null;

        if (showConfidence || showPrediction) {
            modelErrors = plotable.getFunctionErrors(varX, varY, minX, maxX, showPrediction, choiceMap);
        }

        StringBuilder addLegend = new StringBuilder();

        for (Map.Entry<String, Integer> entry : choiceMap.entrySet()) {
            if (!entry.getKey().equals(varX.getName())) {
                Double value = plotable.getVariables().get(entry.getKey()).get(entry.getValue());

                if (value != null) {
                    String s = NumberFormat.getInstance(Locale.US).format(value);

                    addLegend.append(" (" + entry.getKey() + "=" + s + ")");
                }
            }
        }

        if (modelErrors != null) {
            YIntervalSeriesCollection dataSet = new YIntervalSeriesCollection();
            YIntervalSeries series = new YIntervalSeries(legend.get(id));

            for (int j = 0; j < modelPoints[0].length; j++) {
                double error = Double.isNaN(modelErrors[1][j]) ? 0.0 : modelErrors[1][j];

                series.add(modelPoints[0][j], modelPoints[1][j], modelPoints[1][j] - error,
                        modelPoints[1][j] + error);
            }

            dataSet.addSeries(series);
            dataSets.add(dataSet);
        } else {
            DefaultXYDataset dataSet = new DefaultXYDataset();

            dataSet.addSeries(legend.get(id) + addLegend, modelPoints);

            dataSets.add(dataSet);
        }
    }

    return dataSets;
}

From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java

public Integer convertToInteger(final String numericalValueFormatted, final String parameterName,
        final Locale clientApplicationLocale) {

    if (clientApplicationLocale == null) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final String defaultMessage = new StringBuilder(
                "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.")
                        .toString();/*from   w  ww  . jav  a 2s.  c  om*/
        final ApiParameterError error = ApiParameterError
                .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }

    try {
        Integer number = null;

        if (StringUtils.isNotBlank(numericalValueFormatted)) {

            String source = numericalValueFormatted.trim();

            final NumberFormat format = NumberFormat.getInstance(clientApplicationLocale);
            final DecimalFormat df = (DecimalFormat) format;
            final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
            df.setParseBigDecimal(true);

            // http://bugs.sun.com/view_bug.do?bug_id=4510618
            final char groupingSeparator = symbols.getGroupingSeparator();
            if (groupingSeparator == '\u00a0') {
                source = source.replaceAll(" ", Character.toString('\u00a0'));
            }

            final Number parsedNumber = df.parse(source);

            final double parsedNumberDouble = parsedNumber.doubleValue();
            final int parsedNumberInteger = parsedNumber.intValue();

            if (source.contains(Character.toString(symbols.getDecimalSeparator()))) {
                throw new ParseException(source, 0);
            }

            if (!Double.valueOf(parsedNumberDouble)
                    .equals(Double.valueOf(Integer.valueOf(parsedNumberInteger)))) {
                throw new ParseException(source, 0);
            }

            number = parsedNumber.intValue();
        }

        return number;
    } catch (final ParseException e) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final ApiParameterError error = ApiParameterError.parameterError(
                "validation.msg.invalid.integer.format",
                "The parameter " + parameterName + " has value: " + numericalValueFormatted
                        + " which is invalid integer value for provided locale of ["
                        + clientApplicationLocale.toString() + "].",
                parameterName, numericalValueFormatted, clientApplicationLocale);
        error.setValue(numericalValueFormatted);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}

From source file:io.hummer.util.test.GenericTestResult.java

public String getPlottableAverages(List<?> levels, String[] xValueNames, String indexColumn, ResultType type,
        String... additionalCommands) {
    StringBuilder b = new StringBuilder();
    NumberFormat f = NumberFormat.getInstance(Locale.US);
    f.setMinimumFractionDigits(3);//from   www.  ja v a 2 s.c o  m
    f.setMaximumFractionDigits(3);
    f.setGroupingUsed(false);

    List<String> commandsList = Arrays.asList(additionalCommands);

    for (int i = 0; i < levels.size(); i++) {
        String index = "" + levels.get(i);
        if (indexColumn != null) {
            index = "" + getMean(indexColumn.replaceAll("<level>", "" + levels.get(i)));
        }

        int modulo = commandsList.contains(CMD_ONLY_EVERY_2ND_XTICS) ? 2
                : commandsList.contains(CMD_ONLY_EVERY_3RD_XTICS) ? 3 : 1;
        if (i % modulo == 0) {
            b.append(index);
        } else {
            b.append("_");
        }

        for (int j = 0; j < xValueNames.length; j++) {
            b.append("\t");
            String nameString = xValueNames[j];
            nameString = nameString.replaceAll("<level>", "" + levels.get(i));
            if (nameString.equals(xValueNames[j]))
                nameString = nameString + levels.get(i);

            String[] actualNames = nameString.split(":");
            for (String name : actualNames) {

                Double theValue = 0.0;
                if (name.endsWith(".min")) {

                    theValue = getMinimum(name.substring(0, name.length() - ".min".length()));

                } else if (name.endsWith(".max")) {

                    theValue = getMaximum(name.substring(0, name.length() - ".max".length()));

                } else {
                    List<Double> values = getValues(name);
                    if (type == ResultType.MEAN) {
                        Number mean = getMean(values);
                        theValue = mean.doubleValue();
                    } else if (type == ResultType.THROUGHPUT) {
                        theValue = getThroughput(name);
                    }
                    if (values.size() <= 0) {
                        theValue = Double.NaN;
                    }
                }
                if (theValue > 1000000) {
                    b.append(theValue.longValue());
                } else {
                    String val = f.format(theValue);
                    if ((theValue).isNaN()) {
                        //val = "0";
                        val = "NaN";
                    }
                    while (val.length() < 10)
                        val = " " + val;
                    b.append(val);
                }

            }

        }
        b.append("\n");
    }
    return b.toString();
}

From source file:dk.netarkivet.common.webinterface.HTMLUtils.java

/**
 * Parses a integer request parameter and checks that it lies within a given interval. If it doesn't, forwards to an
 * error page and throws ForwardedToErrorPage.
 *
 * @param context The context this call happens in
 * @param param A parameter to parse./*from   w  w w . j a v  a2 s  .  c  om*/
 * @param minValue The minimum allowed value
 * @param maxValue The maximum allowed value
 * @return The value x parsed from the string, if minValue <= x <= maxValue
 * @throws ForwardedToErrorPage if the parameter doesn't exist, is not a parseable integer, or doesn't lie within
 * the limits.
 */
public static int parseAndCheckInteger(PageContext context, String param, int minValue, int maxValue)
        throws ForwardedToErrorPage {
    // Note that we may not want to be to strict here
    // as otherwise information could be lost.
    ArgumentNotValid.checkNotNull(context, "context");
    ArgumentNotValid.checkNotNull(param, "param");

    Locale loc = HTMLUtils.getLocaleObject(context);
    forwardOnEmptyParameter(context, param);
    int value;
    String paramValue = context.getRequest().getParameter(param);
    try {
        value = NumberFormat.getInstance(loc).parse(paramValue).intValue();
        if (value < minValue || value > maxValue) {
            forwardWithErrorMessage(context, I18N, "errormsg;parameter.0.outside.range.1.to.2.3", param,
                    paramValue, minValue, maxValue);
            throw new ForwardedToErrorPage("Parameter '" + param + "' should be between " + minValue + " and "
                    + maxValue + " but is " + paramValue);
        }
        return value;
    } catch (ParseException e) {
        forwardWithErrorMessage(context, I18N, "errormsg;parameter.0.not.an.integer.1", param, paramValue);
        throw new ForwardedToErrorPage("Invalid value " + paramValue + " for integer parameter '" + param + "'",
                e);
    }
}