Example usage for java.text NumberFormat getNumberInstance

List of usage examples for java.text NumberFormat getNumberInstance

Introduction

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

Prototype

public static NumberFormat getNumberInstance(Locale inLocale) 

Source Link

Document

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

Usage

From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java

/**
 * Starts uploading data.//  w w  w .j  av  a2 s .c om
 */
private void startUploading() {
    if (uploadThread != null) {
        writeToLog("Upload thread active");
        return;
    }

    uploadThread = new Thread(new Runnable() {
        @Override
        public void run() {
            uploadThreadRunning = true;

            while (uploadThreadRunning) {
                //get API key
                retrieveApiKey();

                //get a list of non uploaded measurements
                MeasurementsDBIterator dbIterator = mDatabase.getNonUploadedMeasurements();
                boolean success = true;
                String errorMsg = "";
                int max = 0;

                int count = 0;

                // stop uploading if the upload is working only when the wifi is active 
                if (wifiOnly && !NetUtils.isWifiConnected(getApplicationContext())) {
                    writeToLog("WiFi only and WiFi is not connected.");
                    try {
                        Thread.sleep(newDataCheckInterval);
                    } catch (Exception e) {
                    }

                    continue;
                }

                try {
                    writeToLog("Checking if there are records for upload...");
                    if (dbIterator.getCount() > 0) {

                        httpclient = new DefaultHttpClient();
                        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                                HttpVersion.HTTP_1_0);

                        writeToLog("MeasurementsUploaderService startUploading() - openCellUrl=" + openCellUrl);

                        httppost = new HttpPost(openCellUrl);

                        max = dbIterator.getCount();
                        count = 0;

                        NumberFormat latLonFormat = NumberFormat.getNumberInstance(Locale.US);
                        latLonFormat.setMaximumFractionDigits(10);

                        while (dbIterator.hasNext() && uploadThreadRunning) {
                            //upload measurements as a batch file
                            count = uploadMeasurementsBatch(dbIterator, latLonFormat, count, max);
                            Intent progress = new Intent(OpenCellIDUploadService.BROADCAST_PROGRESS_ACTION);
                            progress.putExtra(OpenCellIDUploadService.XTRA_MAXPROGRESS, max);
                            progress.putExtra(OpenCellIDUploadService.XTRA_PROGRESS, count);
                            sendBroadcast(progress);
                        }

                        // set all measurements as uploaded
                        if (uploadThreadRunning) {
                            mDatabase.setAllMeasurementsUploaded();
                        }

                        // start uploading networks data
                        if (uploadThreadRunning) {
                            uploadNetworks();
                        }

                        writeToLog("Uploaded " + count + " of " + max + " records.");
                        httpclient.getConnectionManager().shutdown();
                        success = true;
                    } else {
                        writeToLog("No records for upload right now.");
                    }

                } catch (Exception e) {
                    writeExceptionToLog(e);
                    success = false;
                    errorMsg = e.getMessage();
                } finally {
                    dbIterator.close();
                }

                Intent progress = new Intent(OpenCellIDUploadService.BROADCAST_PROGRESS_ACTION);
                progress.putExtra(OpenCellIDUploadService.XTRA_MAXPROGRESS, max);
                progress.putExtra(OpenCellIDUploadService.XTRA_PROGRESS, count);
                progress.putExtra(OpenCellIDUploadService.XTRA_DONE, true);
                progress.putExtra(OpenCellIDUploadService.XTRA_SUCCESS, success);

                if (!success) {
                    progress.putExtra(OpenCellIDUploadService.XTRA_FAILURE_MSG, errorMsg);
                }
                sendBroadcast(progress);

                try {
                    Thread.sleep(newDataCheckInterval);
                } catch (Exception e) {
                }
            }
        }
    });
    uploadThread.start();
}

From source file:nl.b3p.commons.taglib.WriteFormattedTag.java

/**
 * Process the start tag./* ww w  .j  av  a2  s. co m*/
 *
 * @exception JspException if a JSP exception has occurred
 */
public int doStartTag() throws JspException {

    // Look up the requested bean
    Object value = null;
    if (name != null) {
        if (TagUtils.getInstance().lookup(pageContext, name, scope) == null) {
            return (SKIP_BODY); // Nothing to output
            // Look up the requested property value
        }
        value = TagUtils.getInstance().lookup(pageContext, name, property, scope);
    }

    // Get locale of this request for date printing
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
    Locale locale = request.getLocale();

    Object valueObject = null;
    if (!(value == null || (value instanceof java.lang.String && ((String) value).trim().length() == 0))) {
        // Find class to use for conversion
        String stringValue = value.toString();
        // omzetten naar juiste object type
        try {
            if (formatClass.equals("java.lang.Boolean")) {
                valueObject = (Object) new java.lang.Boolean(stringValue);
            } else if (formatClass.equals("java.lang.BigDecimal")) {
                valueObject = (Object) new java.math.BigDecimal(stringValue);
            } else if (formatClass.equals("java.lang.BigInteger")) {
                valueObject = (Object) new java.math.BigInteger(stringValue);
            } else if (formatClass.equals("java.lang.Byte")) {
                valueObject = (Object) new java.lang.Byte(stringValue);
            } else if (formatClass.equals("java.lang.Double")) {
                valueObject = (Object) new java.lang.Double(stringValue);
            } else if (formatClass.equals("java.lang.Float")) {
                valueObject = (Object) new java.lang.Float(stringValue);
            } else if (formatClass.equals("java.lang.Integer")) {
                valueObject = (Object) new java.lang.Integer(stringValue);
            } else if (formatClass.equals("java.lang.Long")) {
                valueObject = (Object) new java.lang.Long(stringValue);
            } else if (formatClass.equals("java.lang.Short")) {
                valueObject = (Object) new java.lang.Short(stringValue);
            } else if (formatClass.equals("java.lang.String")) {
                char[] strChars = stringValue.toCharArray();
                StringBuffer newStr = new StringBuffer();
                int strLength = strChars.length;
                if (strLength == 0) {
                    newStr.append("-");
                }
                int i = 0;
                while (i < strLength) {
                    newStr.append(strChars[i]);
                    if (strChars[i] == '\n') {
                        newStr.append("<br>");
                    }
                    i++;
                }
                valueObject = newStr.toString();
            } else if (formatClass.equals("java.util.Date")) {
                valueObject = (Object) FormUtils.StringToDate(stringValue, locale);
            } else if (formatClass.equals("java.util.Date2")) {
                valueObject = (Object) FormUtils.FormStringToDate(stringValue, locale);
            } else if (formatClass.equals("java.util.Date3")) {
                valueObject = (Object) FormUtils.SortStringToDate(stringValue, locale);
            } else if (formatClass.equals("java.sql.Date")) {
                valueObject = (Object) new java.sql.Date(Long.parseLong(stringValue));
            } else if (formatClass.equals("java.sql.Time")) {
                valueObject = (Object) new java.sql.Time(Long.parseLong(stringValue));
            } else if (formatClass.equals("java.sql.Timestamp")) {
                valueObject = (Object) new java.sql.Timestamp(Long.parseLong(stringValue));
            } else {
                valueObject = null;
            }
        } catch (java.lang.NumberFormatException nfe) {
            valueObject = null;
            if (log.isDebugEnabled()) {
                log.debug("NumberFormat Exception: " + nfe);
            }
        } catch (java.lang.IllegalArgumentException iare) {
            valueObject = null;
            if (log.isDebugEnabled()) {
                log.debug("Illegal Argument Exception: " + iare);
            }
        }
    }

    // Gevonden objecttype formatteren
    String output = "";
    Format formatter = null;
    if (valueObject != null && format != null) {
        if (valueObject instanceof Number) {
            if (log.isDebugEnabled()) {
                log.debug("Format using Number");
            }
            try {
                formatter = NumberFormat.getNumberInstance(locale);
                ((DecimalFormat) formatter).applyPattern(format);
            } catch (IllegalArgumentException e) {
                if (log.isDebugEnabled()) {
                    log.debug("writeFormatted Number error: " + e);
                }
            }
        } else if (valueObject instanceof java.util.Date) {
            if (log.isDebugEnabled()) {
                log.debug("Format using Date");
            }
            formatter = new SimpleDateFormat(format);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Format using toString for class: " + valueObject.getClass().getName());
            }
        }
    }
    if (valueObject != null) {
        if (formatter != null && format != null) {
            if (log.isDebugEnabled()) {
                log.debug("Formatter");
            }
            output = formatter.format(valueObject);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("No formatter");
            }
            output = valueObject.toString();
        }
    } else {
        output = "-";
    }
    if (log.isDebugEnabled()) {
        log.debug("Output: " + output);
    }
    TagUtils.getInstance().write(pageContext, output);

    // Continue processing this page
    return (SKIP_BODY);

}

From source file:com.qcadoo.mes.productionScheduling.listeners.OrderTimePredictionListeners.java

@Transactional
public void changeRealizationTime(final ViewDefinitionState view, final ComponentState state,
        final String[] args) {
    FormComponent orderForm = (FormComponent) view.getComponentByReference(L_FORM);

    FieldComponent technologyLookup = (FieldComponent) view.getComponentByReference(OrderFields.TECHNOLOGY);
    FieldComponent plannedQuantityField = (FieldComponent) view
            .getComponentByReference(OrderFields.PLANNED_QUANTITY);
    FieldComponent dateFromField = (FieldComponent) view.getComponentByReference(OrderFields.DATE_FROM);
    FieldComponent dateToField = (FieldComponent) view.getComponentByReference(OrderFields.DATE_TO);
    FieldComponent productionLineLookup = (FieldComponent) view
            .getComponentByReference(OrderFields.PRODUCTION_LINE);

    boolean isGenerated = false;

    if (technologyLookup.getFieldValue() == null) {
        technologyLookup.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE);

        return;/* w  ww .  j  a  va 2 s.c o  m*/
    }

    if (!StringUtils.hasText((String) dateFromField.getFieldValue())) {
        dateFromField.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE);

        return;
    }

    if (!StringUtils.hasText((String) plannedQuantityField.getFieldValue())) {
        plannedQuantityField.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE);

        return;
    }

    if (productionLineLookup.getFieldValue() == null) {
        productionLineLookup.addMessage(L_PRODUCTION_SCHEDULING_ERROR_FIELD_REQUIRED, MessageType.FAILURE);

        return;
    }

    BigDecimal quantity = null;
    Object value = plannedQuantityField.getFieldValue();

    if (value instanceof BigDecimal) {
        quantity = (BigDecimal) value;
    } else {
        try {
            ParsePosition parsePosition = new ParsePosition(0);
            String trimedValue = value.toString().replaceAll(" ", "");
            DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(view.getLocale());
            formatter.setParseBigDecimal(true);
            quantity = new BigDecimal(String.valueOf(formatter.parseObject(trimedValue, parsePosition)));
        } catch (NumberFormatException e) {
            plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidNumericFormat",
                    MessageType.FAILURE);

            return;
        }
    }

    int scale = quantity.scale();

    if (MAX != null && scale > MAX) {
        plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidScale.max", MessageType.FAILURE,
                MAX.toString());
        return;
    }

    int presicion = quantity.precision() - scale;

    if (MAX != null && presicion > MAX) {
        plannedQuantityField.addMessage("qcadooView.validate.field.error.invalidPrecision.max",
                MessageType.FAILURE, MAX.toString());
        return;
    }

    if (BigDecimal.ZERO.compareTo(quantity) >= 0) {
        plannedQuantityField.addMessage("qcadooView.validate.field.error.outOfRange.toSmall",
                MessageType.FAILURE);
        return;
    }

    int maxPathTime = 0;

    Entity technology = dataDefinitionService
            .get(TechnologiesConstants.PLUGIN_IDENTIFIER, TechnologiesConstants.MODEL_TECHNOLOGY)
            .get((Long) technologyLookup.getFieldValue());
    Validate.notNull(technology, "technology is null");

    if (technology.getStringField(TechnologyFields.STATE).equals(TechnologyState.DRAFT.getStringValue())
            || technology.getStringField(TechnologyFields.STATE)
                    .equals(TechnologyState.OUTDATED.getStringValue())) {
        technologyLookup.addMessage("productionScheduling.technology.incorrectState", MessageType.FAILURE);

        return;
    }

    FieldComponent laborWorkTimeField = (FieldComponent) view
            .getComponentByReference(OrderFieldsPS.LABOR_WORK_TIME);
    FieldComponent machineWorkTimeField = (FieldComponent) view
            .getComponentByReference(OrderFieldsPS.MACHINE_WORK_TIME);
    FieldComponent includeTpzField = (FieldComponent) view.getComponentByReference(OrderFieldsPS.INCLUDE_TPZ);
    FieldComponent includeAdditionalTimeField = (FieldComponent) view
            .getComponentByReference(OrderFieldsPS.INCLUDE_ADDITIONAL_TIME);

    Boolean includeTpz = "1".equals(includeTpzField.getFieldValue());
    Boolean includeAdditionalTime = "1".equals(includeAdditionalTimeField.getFieldValue());

    Entity productionLine = dataDefinitionService
            .get(ProductionLinesConstants.PLUGIN_IDENTIFIER, ProductionLinesConstants.MODEL_PRODUCTION_LINE)
            .get((Long) productionLineLookup.getFieldValue());

    final Map<Long, BigDecimal> operationRuns = Maps.newHashMap();

    productQuantitiesService.getProductComponentQuantities(technology, quantity, operationRuns);

    OperationWorkTime workTime = operationWorkTimeService.estimateTotalWorkTimeForTechnology(technology,
            operationRuns, includeTpz, includeAdditionalTime, productionLine, true);

    laborWorkTimeField.setFieldValue(workTime.getLaborWorkTime());
    machineWorkTimeField.setFieldValue(workTime.getMachineWorkTime());

    maxPathTime = orderRealizationTimeService.estimateOperationTimeConsumption(
            technology.getTreeField(TechnologyFields.OPERATION_COMPONENTS).getRoot(), quantity, includeTpz,
            includeAdditionalTime, productionLine);

    if (maxPathTime > OrderRealizationTimeService.MAX_REALIZATION_TIME) {
        state.addMessage("orders.validate.global.error.RealizationTimeIsToLong", MessageType.FAILURE);

        dateToField.setFieldValue(null);
    } else {
        Date startTime = DateUtils.parseDate(dateFromField.getFieldValue());

        if (startTime == null) {
            dateFromField.addMessage("orders.validate.global.error.dateFromIsNull", MessageType.FAILURE);
        } else {
            Date stopTime = shiftsService.findDateToForOrder(startTime, maxPathTime);

            if (stopTime == null) {
                orderForm.addMessage("productionScheduling.timenorms.isZero", MessageType.FAILURE, false);

                dateToField.setFieldValue(null);
            } else {
                dateToField.setFieldValue(orderRealizationTimeService.setDateToField(stopTime));

                startTime = shiftsService.findDateFromForOrder(stopTime, maxPathTime);

                scheduleOperationComponents(technology.getId(), startTime);

                isGenerated = true;
            }

            if (startTime != null) {
                orderForm.addMessage("orders.dateFrom.info.dateFromSetToFirstPossible", MessageType.INFO,
                        false);
            }
        }
    }

    laborWorkTimeField.requestComponentUpdateState();
    machineWorkTimeField.requestComponentUpdateState();
    dateFromField.requestComponentUpdateState();
    dateToField.requestComponentUpdateState();

    orderForm.setEntity(orderForm.getEntity());

    state.performEvent(view, "refresh", new String[0]);

    if (isGenerated) {
        orderForm.addMessage("productionScheduling.info.calculationGenerated", MessageType.SUCCESS);
    }
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.RadarChartExpression.java

private void initializeGrid(final DefaultCategoryDataset defaultDataset) {

    if (gridintervall < 0) {
        final double gridIntervalIncrement = -gridintervall;
        if ((100.0 / gridIntervalIncrement) > 5000) {
            return;
        }/*from  www. jav  a  2s. c  o m*/

        //insert the gridlines (fake data sets)
        double gridline = gridIntervalIncrement;
        final int columns = defaultDataset.getColumnCount();
        final double maxdata = computeMaxValue(defaultDataset);

        final NumberFormat format = NumberFormat
                .getPercentInstance(getRuntime().getResourceBundleFactory().getLocale());
        while (gridline <= 100) {
            final double gridScaled = maxdata * gridline / 100.0;
            final String gridLineText = format.format(gridline / 100.0);
            final GridCategoryItem rowKey = new GridCategoryItem(gridLineText);
            for (int i = 0; i < columns; i++) {
                defaultDataset.addValue(gridScaled, rowKey, defaultDataset.getColumnKey(i));
            }
            gridline = gridline + gridIntervalIncrement;
        }
    } else if (gridintervall > 0) {
        final int columns = defaultDataset.getColumnCount();
        final double maxdata = computeMaxValue(defaultDataset);
        final double gridIntervalIncrement = gridintervall;
        if ((maxdata / gridIntervalIncrement) > 5000) {
            return;
        }

        final NumberFormat format = NumberFormat
                .getNumberInstance(getRuntime().getResourceBundleFactory().getLocale());
        double gridline = 0;
        while (gridline < maxdata) {
            gridline = gridline + gridIntervalIncrement;
            final String gridLineText = format.format(gridline);
            final GridCategoryItem rowKey = new GridCategoryItem(gridLineText);
            for (int i = 0; i < columns; i++) {
                defaultDataset.addValue(gridline, rowKey, defaultDataset.getColumnKey(i));
            }
        }

    }
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java

/**
 * Generates a generic Time Area Chart./*from  ww  w  . j  ava  2  s  .com*/
 *
 * @param title      the title of the Chart.
 * @param valueLabel the Y Axis label.
 * @param data       the data to populate with.
 * @return the generated Chart.
 */
private JFreeChart createTimeAreaChart(String title, String color, String valueLabel, XYDataset data) {
    PlotOrientation orientation = PlotOrientation.VERTICAL;

    DateAxis xAxis = generateTimeAxis();

    NumberAxis yAxis = new NumberAxis(valueLabel);

    NumberFormat formatter = NumberFormat.getNumberInstance(JiveGlobals.getLocale());
    formatter.setMaximumFractionDigits(2);
    formatter.setMinimumFractionDigits(0);
    yAxis.setNumberFormatOverride(formatter);

    XYAreaRenderer renderer = new XYAreaRenderer(XYAreaRenderer.AREA);
    renderer.setOutline(true);

    return createChart(title, data, xAxis, yAxis, orientation, renderer, GraphDefinition.getDefinition(color));
}

From source file:org.apache.ddlutils.platform.SqlBuilder.java

/**
 * Sets the locale that is used for number and date formatting
 * (when printing default values and in generates insert/update/delete
 * statements)./*from   w  ww. ja  v a  2  s .c  o m*/
 *
 * @param localeStr The new locale or <code>null</code> if default formatting
 *                  should be used; Format is "language[_country[_variant]]"
 */
public void setValueLocale(String localeStr) {
    if (localeStr != null) {
        int sepPos = localeStr.indexOf('_');
        String language = null;
        String country = null;
        String variant = null;

        if (sepPos > 0) {
            language = localeStr.substring(0, sepPos);
            country = localeStr.substring(sepPos + 1);
            sepPos = country.indexOf('_');
            if (sepPos > 0) {
                variant = country.substring(sepPos + 1);
                country = country.substring(0, sepPos);
            }
        } else {
            language = localeStr;
        }
        if (language != null) {
            Locale locale = null;

            if (variant != null) {
                locale = new Locale(language, country, variant);
            } else if (country != null) {
                locale = new Locale(language, country);
            } else {
                locale = new Locale(language);
            }

            _valueLocale = localeStr;
            setValueDateFormat(DateFormat.getDateInstance(DateFormat.SHORT, locale));
            setValueTimeFormat(DateFormat.getTimeInstance(DateFormat.SHORT, locale));
            setValueNumberFormat(NumberFormat.getNumberInstance(locale));
            return;
        }
    }
    _valueLocale = null;
    setValueDateFormat(null);
    setValueTimeFormat(null);
    setValueNumberFormat(null);
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.LinkableBar.java

/**
 * Inherited by IChart.//from  w  ww  . ja v  a 2  s. c  om
 * 
 * @param chartTitle the chart title
 * @param dataset the dataset
 * 
 * @return the j free chart
 */

public JFreeChart createChart(DatasetMap datasets) {
    logger.debug("IN");
    CategoryDataset dataset = (CategoryDataset) datasets.getDatasets().get("1");

    CategoryAxis categoryAxis = new CategoryAxis(categoryLabel);
    ValueAxis valueAxis = new NumberAxis(valueLabel);
    if (rangeIntegerValues == true) {
        valueAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }

    org.jfree.chart.renderer.category.BarRenderer renderer = new org.jfree.chart.renderer.category.BarRenderer();

    renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());
    //      renderer.setBaseItemLabelFont(new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
    //      renderer.setBaseItemLabelPaint(styleValueLabels.getColor());

    if (showValueLabels) {
        renderer.setBaseItemLabelsVisible(true);
        renderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
        renderer.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        renderer.setBaseItemLabelPaint(styleValueLabels.getColor());
    }

    if (maxBarWidth != null) {
        renderer.setMaximumBarWidth(maxBarWidth.doubleValue());
    }

    boolean document_composition = false;
    if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION))
        document_composition = true;

    MyCategoryUrlGenerator mycatUrl = new MyCategoryUrlGenerator(rootUrl);
    mycatUrl.setDocument_composition(document_composition);
    mycatUrl.setCategoryUrlLabel(categoryUrlName);
    mycatUrl.setSerieUrlLabel(serieUrlname);
    mycatUrl.setDrillDocTitle(drillDocTitle);
    mycatUrl.setTarget(target);

    renderer.setItemURLGenerator(mycatUrl);

    /*      }
    else{
       renderer.setItemURLGenerator(new StandardCategoryURLGenerator(rootUrl));
    }*/

    CategoryPlot plot = new CategoryPlot((CategoryDataset) dataset, categoryAxis, valueAxis, renderer);
    plot.setOrientation(PlotOrientation.VERTICAL);
    if (horizontalView) {
        plot.setOrientation(PlotOrientation.HORIZONTAL);
    }

    JFreeChart chart = new JFreeChart(name, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);

    TextTitle title = setStyleTitle(name, styleTitle);
    chart.setTitle(title);
    if (subName != null && !subName.equals("")) {
        TextTitle subTitle = setStyleTitle(subName, styleSubTitle);
        chart.addSubtitle(subTitle);
    }

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

    // set the background color for the chart...
    chart.setBackgroundPaint(color);

    // get a reference to the plot for further customisation...
    //CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setDomainGridlinePaint(Color.white);
    plot.setDomainGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    NumberFormat nf = NumberFormat.getNumberInstance(locale);

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    rangeAxis.setNumberFormatOverride(nf);

    if (rangeAxisLocation != null) {
        if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT);
        } else if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_LEFT);
        }
    }

    // disable bar outlines...
    //BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);

    /*   if(currentSeries!=null && colorMap!=null){
       //for each serie selected
       int j=0;   
       for (Iterator iterator = currentSeries.iterator(); iterator.hasNext();) {
    String s = (String) iterator.next();
    Integer position=(Integer)seriesNumber.get(s);
    // check if for that position a value is defined
    if(colorMap.get("color"+position.toString())!=null){
       Color col= (Color)colorMap.get("color"+position);
       renderer.setSeriesPaint(j, col);
    }
    j++;
       }  // close for on series
    } // close case series selcted and color defined
    else{
       if(colorMap!=null){ // if series not selected check color each one
            
    for (Iterator iterator = colorMap.keySet().iterator(); iterator.hasNext();) {
       String key = (String) iterator.next();
       Color col= (Color)colorMap.get(key);
       String keyNum=key.substring(5, key.length());
       int num=Integer.valueOf(keyNum).intValue();
       num=num-1;
       renderer.setSeriesPaint(num, col);
    }
       }
    }*/

    int seriesN = dataset.getRowCount();

    if (orderColorVector != null && orderColorVector.size() > 0) {
        logger.debug("color serie by SERIES_ORDER_COLORS template specification");
        for (int i = 0; i < seriesN; i++) {
            if (orderColorVector.get(i) != null) {
                Color color = orderColorVector.get(i);
                renderer.setSeriesPaint(i, color);
            }
        }
    } else if (colorMap != null) {
        for (int i = 0; i < seriesN; i++) {
            String serieName = (String) dataset.getRowKey(i);
            Color color = (Color) colorMap.get(serieName);
            if (color != null) {
                renderer.setSeriesPaint(i, color);
            }
        }
    }

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
    domainAxis.setLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setLabelPaint(styleYaxesLabels.getColor());
    domainAxis
            .setTickLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setTickLabelPaint(styleYaxesLabels.getColor());

    if (legend == true)
        drawLegend(chart);

    logger.debug("OUT");
    return chart;

}

From source file:org.locationtech.udig.tools.internal.CursorPosition.java

private static String getString(double value) {
    if (Double.isNaN(value)) {
        return Messages.CursorPosition_not_a_number;
    }//from  w  w  w.  j  a va  2 s .  c o m

    if (Double.isInfinite(value)) {
        return Messages.CursorPosition_infinity;
    }

    DecimalFormat format = (DecimalFormat) NumberFormat.getNumberInstance(Locale.getDefault());
    format.setMaximumFractionDigits(4);
    format.setMinimumIntegerDigits(1);
    format.setGroupingUsed(false);
    String string = format.format(value);

    String[] parts = string.split("\\.");
    if (parts.length > 3) {
        string = parts[0];
    }
    return string;
}

From source file:de.robbers.dashclock.stackextension.StackExtension.java

private void publishUpdate() {
    if (mError) {
        return;/*from   ww w  . j a v  a2s  .  c o  m*/
    }
    mStatus = NumberFormat.getNumberInstance(Locale.US).format(mReputation);
    mExpandedTitle = mStatus + " Reputation" + " \u2014 " + mSites.getNameFromApiParameter(mSite);
    mExpandedBody = mExpandedBody == null ? "" : mExpandedBody;

    int icon = mSites.getIcon(mSite);
    String url = mSites.getUrlFromApiParameter(mSite) + "/users/" + mUserId + "?tab=reputation";
    // Publish the extension data update.
    publishUpdate(new ExtensionData().visible(mVisible).icon(icon).status(mStatus).expandedTitle(mExpandedTitle)
            .expandedBody(mExpandedBody).clickIntent(new Intent(Intent.ACTION_VIEW, Uri.parse(url))));
}

From source file:name.gumartinm.weather.information.fragment.overview.OverviewFragment.java

private void updateUI(final Forecast forecastWeatherData) {

    // 1. Update units of measurement.
    final UnitsConversor tempUnitsConversor = new TempUnitsConversor(
            this.getActivity().getApplicationContext());

    // 2. Update number day forecast.
    final SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this.getActivity().getApplicationContext());
    final String keyPreference = this.getResources().getString(R.string.weather_preferences_day_forecast_key);
    final String dayForecast = sharedPreferences.getString(keyPreference, "5");
    final int mDayForecast = Integer.valueOf(dayForecast);

    // 3. Formatters
    final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    tempFormatter.applyPattern("###.##");
    final SimpleDateFormat dayNameFormatter = new SimpleDateFormat("EEE", Locale.US);
    final SimpleDateFormat monthAndDayNumberormatter = new SimpleDateFormat("MMM d", Locale.US);

    // 4. Prepare data for UI.
    final List<OverviewEntry> entries = new ArrayList<OverviewEntry>();
    final OverviewAdapter adapter = new OverviewAdapter(this.getActivity(), R.layout.weather_main_entry_list);
    final Calendar calendar = Calendar.getInstance();
    int count = mDayForecast;
    for (final name.gumartinm.weather.information.model.forecastweather.List forecast : forecastWeatherData
            .getList()) {/*from  ww w.j  a  v a  2 s . com*/

        Bitmap picture;

        if ((forecast.getWeather().size() > 0) && (forecast.getWeather().get(0).getIcon() != null)
                && (IconsList.getIcon(forecast.getWeather().get(0).getIcon()) != null)) {
            final String icon = forecast.getWeather().get(0).getIcon();
            picture = BitmapFactory.decodeResource(this.getResources(),
                    IconsList.getIcon(icon).getResourceDrawable());
        } else {
            picture = BitmapFactory.decodeResource(this.getResources(), R.drawable.weather_severe_alert);
        }

        final Long forecastUNIXDate = (Long) forecast.getDt();
        calendar.setTimeInMillis(forecastUNIXDate * 1000L);
        final Date dayTime = calendar.getTime();
        final String dayTextName = dayNameFormatter.format(dayTime);
        final String monthAndDayNumberText = monthAndDayNumberormatter.format(dayTime);

        Double maxTemp = null;
        if (forecast.getTemp().getMax() != null) {
            maxTemp = (Double) forecast.getTemp().getMax();
            maxTemp = tempUnitsConversor.doConversion(maxTemp);
        }

        Double minTemp = null;
        if (forecast.getTemp().getMin() != null) {
            minTemp = (Double) forecast.getTemp().getMin();
            minTemp = tempUnitsConversor.doConversion(minTemp);
        }

        if ((maxTemp != null) && (minTemp != null)) {
            // TODO i18n?
            final String tempSymbol = tempUnitsConversor.getSymbol();
            entries.add(new OverviewEntry(dayTextName, monthAndDayNumberText,
                    tempFormatter.format(maxTemp) + tempSymbol, tempFormatter.format(minTemp) + tempSymbol,
                    picture));
        }

        count = count - 1;
        if (count == 0) {
            break;
        }
    }

    // 5. Update UI.
    adapter.addAll(entries);
    this.setListAdapter(adapter);
}