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 final NumberFormat getInstance() 

Source Link

Document

Returns a general-purpose number format for the current default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:com.jbombardier.reports.ReportGenerator.java

private static void generatePathView(File folder, String phase, String distinctPath,
        List<CapturedStatistic> capturedStatistics) {

    HTMLBuilder2 builder = new HTMLBuilder2();

    builder.getHead().css("box.css");
    builder.getHead().css("table.css");

    HTMLBuilder2.Element bodyx = builder.getBody();

    final HTMLBuilder2.Element content = bodyx.div("wide-box");

    TimeSeries series = new TimeSeries(distinctPath);
    TimeSeriesCollection data = new TimeSeriesCollection();
    data.addSeries(series);// w  ww .j a va2s.c o m

    NumberFormat nf = NumberFormat.getInstance();

    try {
        for (CapturedStatistic capturedStatistic : capturedStatistics) {
            if (capturedStatistic.getPath().equals(distinctPath)) {
                series.addOrUpdate(new Second(new Date(capturedStatistic.getTime())),
                        nf.parse(capturedStatistic.getValue()));
            }
        }
    } catch (ParseException nfe) {
        // Skip this one, its not numeric
    }

    if (series.getItemCount() > 0) {
        final String imageName = StringUtils.format("phase-{}-path-{}.png", phase,
                distinctPath.replace('/', '-'));
        content.image(imageName);

        final File file = new File(folder, imageName);
        render(StringUtils.format("phase-{}-path-{}.html", phase, distinctPath.replace('/', '-')), data, file);
    }

    builder.toFile(new File(folder,
            StringUtils.format("phase-{}-path-{}.html", phase, distinctPath.replace('/', '-'))));

}

From source file:com.unicornlabs.kabouter.reporting.PowerReport.java

public static void GeneratePowerReport(Date startDate, Date endDate) {
    try {/*from   www .  j a v  a  2 s  .c o m*/
        Historian theHistorian = (Historian) BusinessObjectManager.getBusinessObject(Historian.class.getName());
        ArrayList<String> powerLogDeviceIds = theHistorian.getPowerLogDeviceIds();

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        File outputFile = new File("PowerReport.pdf");
        outputFile.createNewFile();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();

        document.add(new Paragraph("Power Report for " + startDate.toString() + " to " + endDate.toString()));

        document.newPage();

        DecimalFormat df = new DecimalFormat("#.###");

        for (String deviceId : powerLogDeviceIds) {
            ArrayList<Powerlog> powerlogs = theHistorian.getPowerlogs(deviceId, startDate, endDate);
            double total = 0;
            double max = 0;
            Date maxTime = startDate;
            double average = 0;
            XYSeries series = new XYSeries(deviceId);
            XYDataset dataset = new XYSeriesCollection(series);

            for (Powerlog log : powerlogs) {
                total += log.getPower();
                if (log.getPower() > max) {
                    max = log.getPower();
                    maxTime = log.getId().getLogtime();
                }
                series.add(log.getId().getLogtime().getTime(), log.getPower());
            }

            average = total / powerlogs.size();

            document.add(new Paragraph("\nDevice: " + deviceId));
            document.add(new Paragraph("Average Power Usage: " + df.format(average)));
            document.add(new Paragraph("Maximum Power Usage: " + df.format(max) + " at " + maxTime.toString()));
            document.add(new Paragraph("Total Power Usage: " + df.format(total)));
            //Create a custom date axis to display dates on the X axis
            DateAxis dateAxis = new DateAxis("Date");
            //Make the labels vertical
            dateAxis.setVerticalTickLabels(true);

            //Create the power axis
            NumberAxis powerAxis = new NumberAxis("Power");

            //Set both axes to auto range for their values
            powerAxis.setAutoRange(true);
            dateAxis.setAutoRange(true);

            //Create the tooltip generator
            StandardXYToolTipGenerator ttg = new StandardXYToolTipGenerator("{0}: {2}",
                    new SimpleDateFormat("yyyy/MM/dd HH:mm"), NumberFormat.getInstance());

            //Set the renderer
            StandardXYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES, ttg,
                    null);

            //Create the plot
            XYPlot plot = new XYPlot(dataset, dateAxis, powerAxis, renderer);

            //Create the chart
            JFreeChart myChart = new JFreeChart(deviceId, JFreeChart.DEFAULT_TITLE_FONT, plot, true);

            PdfContentByte pcb = writer.getDirectContent();
            PdfTemplate tp = pcb.createTemplate(480, 360);
            Graphics2D g2d = tp.createGraphics(480, 360, new DefaultFontMapper());
            Rectangle2D r2d = new Rectangle2D.Double(0, 0, 480, 360);
            myChart.draw(g2d, r2d);
            g2d.dispose();
            pcb.addTemplate(tp, 0, 0);

            document.newPage();
        }

        document.close();

        JOptionPane.showMessageDialog(null, "Report Generated.");

        Desktop.getDesktop().open(outputFile);
    } catch (FileNotFoundException fnfe) {
        JOptionPane.showMessageDialog(null,
                "Unable To Open File For Writing, Make Sure It Is Not Currently Open");
    } catch (IOException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.talent.aio.examples.im.client.ui.JFrameMain.java

public static void updateReceivedLabel() {
    if (isNeedUpdateReceivedCount) {
        isNeedUpdateReceivedCount = false;

        NumberFormat numberFormat = NumberFormat.getInstance();
        ClientGroupContext<Object, ImPacket, Object> clientGroupContext = imClientStarter
                .getClientGroupContext();
        GroupStat groupStat = clientGroupContext.getGroupStat();
        instance.receivedLabel.setText(numberFormat.format(groupStat.getReceivedPacket().get()) + "?"
                + numberFormat.format(groupStat.getReceivedBytes().get()) + "B");
    }//  ww  w.  j  a v  a 2 s.  c om
}

From source file:com.googlecode.logVisualizer.chart.HorizontalIntervallBarChartBuilder.java

private JFreeChart createChart(final CategoryDataset dataset) {
    final JFreeChart chart = ChartFactory.createBarChart(getTitle(), xLable, yLable, dataset,
            PlotOrientation.HORIZONTAL, isIncludeLegend(), true, false);
    final CategoryPlot plot = (CategoryPlot) chart.getPlot();
    final CategoryAxis categoryAxis = plot.getDomainAxis();
    final LayeredBarRenderer renderer = new LayeredBarRenderer();

    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinesVisible(false);
    plot.setRangeGridlinePaint(Color.black);
    setBarShadowVisible(chart, false);//from w  w w .j a  v a2s  . com

    plot.getRangeAxis().setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    plot.getRangeAxis().setLowerBound(-35);
    plot.getRangeAxis().setUpperBound(35);

    renderer.setDrawBarOutline(false);
    renderer.setSeriesPaint(0, Color.blue);
    renderer.setSeriesPaint(1, Color.green);
    renderer.setBaseItemLabelsVisible(true);
    renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    renderer.setSeriesPositiveItemLabelPosition(0,
            new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.CENTER));
    renderer.setSeriesPositiveItemLabelPosition(1,
            new ItemLabelPosition(ItemLabelAnchor.OUTSIDE2, TextAnchor.CENTER));
    renderer.setSeriesNegativeItemLabelPosition(0,
            new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9, TextAnchor.CENTER));
    renderer.setSeriesNegativeItemLabelPosition(1,
            new ItemLabelPosition(ItemLabelAnchor.OUTSIDE10, TextAnchor.CENTER));
    renderer.setItemLabelAnchorOffset(9.0);
    renderer.setBaseToolTipGenerator(
            new StandardCategoryToolTipGenerator("{1}, {2}", NumberFormat.getInstance()));
    plot.setRenderer(renderer);
    plot.setRowRenderingOrder(SortOrder.DESCENDING);

    categoryAxis.setCategoryMargin(0.15);
    categoryAxis.setUpperMargin(0.0175);
    categoryAxis.setLowerMargin(0.0175);

    return chart;
}

From source file:org.sentilo.samples.controller.SamplesController.java

@RequestMapping(value = { "/", "/home" })
public String runSamples(final Model model) {

    // All this data must be created in the Catalog Application before start this
    // sample execution. At least the application identity token id and the provider id must be
    // declared in system twice
    String restClientIdentityKey = samplesProperties.getProperty("rest.client.identityKey");
    String providerId = samplesProperties.getProperty("rest.client.provider");

    // For this example we have created a generic component with a status sensor that accepts text
    // type observations, only for test purpose
    String componentId = samplesProperties.getProperty("rest.client.component");
    String sensorId = samplesProperties.getProperty("rest.client.sensor");

    logger.info("Starting samples execution...");

    String observationsValue = null;
    String errorMessage = null;/*from ww  w  .j a va2  s. c  o  m*/

    try {
        // Get some system data from runtime
        Runtime runtime = Runtime.getRuntime();
        NumberFormat format = NumberFormat.getInstance();
        StringBuilder sb = new StringBuilder();
        long maxMemory = runtime.maxMemory();
        long allocatedMemory = runtime.totalMemory();
        long freeMemory = runtime.freeMemory();

        sb.append("free memory: " + format.format(freeMemory / 1024) + "<br/>");
        sb.append("allocated memory: " + format.format(allocatedMemory / 1024) + "<br/>");
        sb.append("max memory: " + format.format(maxMemory / 1024) + "<br/>");
        sb.append("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024)
                + "<br/>");

        // In this case, we're getting CPU status in text mode
        observationsValue = sb.toString();

        logger.info("Observations values: " + observationsValue);

        // Create the sample sensor, only if it doesn't exists in the catalog
        createSensorIfNotExists(restClientIdentityKey, providerId, componentId, sensorId);

        // Publish observations to the sample sensor
        sendObservations(restClientIdentityKey, providerId, componentId, sensorId, observationsValue);
    } catch (Exception e) {
        logger.error("Error publishing sensor observations: " + e.getMessage(), e);
        errorMessage = e.getMessage();
    }

    logger.info("Samples execution ended!");

    model.addAttribute("restClientIdentityKey", restClientIdentityKey);
    model.addAttribute("providerId", providerId);
    model.addAttribute("componentId", componentId);
    model.addAttribute("sensorId", sensorId);
    model.addAttribute("observations", observationsValue);

    ObjectMapper mapper = new ObjectMapper();

    try {
        if (errorMessage != null && errorMessage.length() > 0) {
            Object json = mapper.readValue(errorMessage, Object.class);
            model.addAttribute("errorMsg", mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));
        } else {
            model.addAttribute("successMsg", "Observations sended successfully");
        }
    } catch (Exception e) {
        logger.error("Error parsing JSON: {}", e.getMessage(), e);
        errorMessage += (errorMessage.length() > 0) ? "<br/>" : "" + e.getMessage();
        model.addAttribute("errorMsg", errorMessage);
    }

    return VIEW_SAMPLES_RESPONSE;
}

From source file:com.autentia.intra.bean.contacts.AlbaranBean.java

public String siguienteNumero() {
    int maximo = 0;
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumIntegerDigits(2);/* ww  w.  j  av a2s  . c o  m*/
    String regex = "A\\d+/";
    String anio = nf.format(new Date().getYear() - 100);
    regex = regex.concat(anio);
    List<Albaran> list = albaranDAO.search(null);
    for (Albaran o : list) {
        String numero = o.getName();
        if (numero != null && numero.matches(regex)) {
            int x = Integer.parseInt(numero.substring(1, numero.indexOf('/')));
            if (x > maximo)
                maximo = x;
        }
    }
    nf.setMinimumIntegerDigits(3);
    return "A".concat(nf.format(maximo + 1)).concat("/").concat(anio);
}

From source file:com.espertech.esper.example.servershellclient.ServerShellClientMain.java

public ServerShellClientMain() throws Exception {
    log.info("Loading properties");
    Properties properties = new Properties();
    InputStream propertiesIS = ServerShellClientMain.class.getClassLoader()
            .getResourceAsStream(ServerShellConstants.CONFIG_FILENAME);
    if (propertiesIS == null) {
        throw new RuntimeException(
                "Properties file '" + ServerShellConstants.CONFIG_FILENAME + "' not found in classpath");
    }/*from  ww w .j a v a  2  s  .c  o m*/
    properties.load(propertiesIS);

    // Attached via JMX to running server
    log.info("Attach to server via JMX");
    JMXServiceURL url = new JMXServiceURL(properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL));
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName mBeanName = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME);
    EPServiceProviderJMXMBean proxy = (EPServiceProviderJMXMBean) MBeanServerInvocationHandler
            .newProxyInstance(mbsc, mBeanName, EPServiceProviderJMXMBean.class, true);

    // Connect to JMS
    log.info("Connecting to JMS server");
    String factory = properties.getProperty(ServerShellConstants.JMS_CONTEXT_FACTORY);
    String jmsurl = properties.getProperty(ServerShellConstants.JMS_PROVIDER_URL);
    String connFactoryName = properties.getProperty(ServerShellConstants.JMS_CONNECTION_FACTORY_NAME);
    String user = properties.getProperty(ServerShellConstants.JMS_USERNAME);
    String password = properties.getProperty(ServerShellConstants.JMS_PASSWORD);
    String destination = properties.getProperty(ServerShellConstants.JMS_INCOMING_DESTINATION);
    boolean isTopic = Boolean.parseBoolean(properties.getProperty(ServerShellConstants.JMS_IS_TOPIC));
    JMSContext jmsCtx = JMSContextFactory.createContext(factory, jmsurl, connFactoryName, user, password,
            destination, isTopic);

    // Create statement via JMX
    log.info("Creating a statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.createEPL("select * from SampleEvent where duration > 9.9", "filterStatement",
            new ClientSideUpdateListener());

    // Get producer
    jmsCtx.getConnection().start();
    MessageProducer producer = jmsCtx.getSession().createProducer(jmsCtx.getDestination());

    Random random = new Random();
    String[] ipAddresses = { "127.0.1.0", "127.0.2.0", "127.0.3.0", "127.0.4.0" };
    NumberFormat format = NumberFormat.getInstance();

    // Send messages
    for (int i = 0; i < 1000; i++) {
        String ipAddress = ipAddresses[random.nextInt(ipAddresses.length)];
        double duration = 10 * random.nextDouble();
        String durationStr = format.format(duration);
        String payload = ipAddress + "," + durationStr;

        BytesMessage bytesMessage = jmsCtx.getSession().createBytesMessage();
        bytesMessage.writeBytes(payload.getBytes());
        bytesMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
        producer.send(bytesMessage);

        if (i % 100 == 0) {
            log.info("Sent " + i + " messages");
        }
    }

    // Create statement via JMX
    log.info("Destroing statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.destroy("filterStatement");

    log.info("Shutting down JMS client connection");
    jmsCtx.destroy();

    log.info("Exiting");
    System.exit(-1);
}

From source file:org.apache.camel.dataformat.bindy.BindyAbstractFactory.java

private static NumberFormat getNumberFormat() {
    // Get instance of NumberFormat
    NumberFormat nf = NumberFormat.getInstance();

    // set max number of digits to 3 (thousands)
    nf.setMaximumIntegerDigits(3);//from   ww w . j a v a  2 s.c  o  m
    nf.setMinimumIntegerDigits(3);

    return nf;
}

From source file:ecosim.gui.SummaryPane.java

/**
 *  Private method to build the binning chart.
 *
 *  @return A ChartPanel containing the binning chart.
 *///from  w w  w. j  a v  a  2 s  . co m
private ChartPanel makeBinningChart() {
    final DefaultXYDataset binData = new DefaultXYDataset();
    final NumberFormat nf = NumberFormat.getInstance();
    final NumberAxis xAxis = new NumberAxis("Sequence identity criterion");
    nf.setMinimumFractionDigits(2);
    xAxis.setLowerBound(Binning.binLevels[0]);
    xAxis.setUpperBound(1.0D);
    xAxis.setTickUnit(new NumberTickUnit(0.05D, nf));
    LogAxis yAxis = new LogAxis("Number of bins");
    yAxis.setBase(2.0D);
    yAxis.setNumberFormatOverride(NumberFormat.getInstance());
    yAxis.setTickUnit(new NumberTickUnit(2.0D));
    yAxis.setMinorTickMarksVisible(true);
    yAxis.setAutoRangeMinimumSize(4.0D);
    yAxis.setSmallestValue(1.0D);
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
    for (int i = 0; i < seriesColors.length; i++) {
        renderer.setSeriesPaint(i, seriesColors[i]);
        renderer.setSeriesStroke(i, new BasicStroke(seriesStroke[i]));
    }
    XYPlot plot = new XYPlot(binData, xAxis, yAxis, renderer);
    JFreeChart binChart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, false);
    binChart.setPadding(new RectangleInsets(0.0D, 0.0D, 0.0D, 10.0D));
    LegendTitle legend = new LegendTitle(plot);
    legend.setMargin(new RectangleInsets(1.0D, 1.0D, 1.0D, 1.0D));
    legend.setFrame(new LineBorder());
    legend.setBackgroundPaint(Color.white);
    legend.setPosition(RectangleEdge.BOTTOM);
    plot.addAnnotation(new XYTitleAnnotation(0.001D, 0.999D, legend, RectangleAnchor.TOP_LEFT));
    final ChartPanel pane = new ChartPanel(binChart, false, true, true, false, false);
    // Watch for changes to the Summary object.
    summary.addObserver(new Observer() {
        public void update(Observable o, Object obj) {
            Summary s = (Summary) obj;
            ParameterEstimate estimate = s.getEstimate();
            ArrayList<BinLevel> bins = s.getBins();
            if (bins.size() > 0) {
                double[][] values = new double[2][bins.size()];
                Double low = 1.0d;
                for (int i = 0; i < bins.size(); i++) {
                    BinLevel bin = bins.get(i);
                    values[0][i] = bin.getCrit();
                    values[1][i] = bin.getLevel();
                    if (values[0][i] < low)
                        low = values[0][i];
                }
                binData.addSeries("sequences", values);
                xAxis.setLowerBound(low);
                if (low > 0.95d - MasterVariables.EPSILON) {
                    xAxis.setTickUnit(new NumberTickUnit(0.005D, nf));
                } else if (low > 0.90d - MasterVariables.EPSILON) {
                    xAxis.setTickUnit(new NumberTickUnit(0.010D, nf));
                } else if (low > 0.80d - MasterVariables.EPSILON) {
                    xAxis.setTickUnit(new NumberTickUnit(0.025D, nf));
                }
                if (estimate != null) {
                    double[][] omega = new double[2][bins.size()];
                    double[][] sigma = new double[2][bins.size()];
                    double[] omegaLine = estimate.getOmega();
                    double[] sigmaLine = estimate.getSigma();
                    for (int i = 0; i < bins.size(); i++) {
                        double crit = 1.0D - values[0][i];
                        double snp = s.getLength() * crit;
                        omega[0][i] = values[0][i];
                        sigma[0][i] = values[0][i];
                        omega[1][i] = Math.pow(2.0D, snp * omegaLine[0] + omegaLine[1]);
                        sigma[1][i] = Math.pow(2.0D, snp * sigmaLine[0] + sigmaLine[1]);
                    }
                    if (-1.0D * omegaLine[0] > MasterVariables.EPSILON) {
                        binData.addSeries("omega", omega);
                    }
                    if (-1.0D * sigmaLine[0] > MasterVariables.EPSILON) {
                        binData.addSeries("sigma", sigma);
                    }
                }
                // Repaint the summary pane.
                pane.repaint();
            }
        }
    });
    return pane;
}

From source file:gate.bulstem.BulStemPR.java

@Override
public void execute() throws ExecutionException {

    // get all the tokens from the specified annotation set
    AnnotationSet allTokens = document.getAnnotations(annotationSetName).get(annotationType);

    if (allTokens.size() > 0) {

        // sort out the status reporting stuff
        long startTime = System.currentTimeMillis();
        fireStatusChanged("Running BulStem over " + document.getName());
        fireProgressChanged(0);//from   w w  w  .j a  va  2 s  .c o  m
        int tokenCount = 0;

        for (Annotation token : allTokens) {
            // for each Token annotation...

            // get the string feature
            String tokenString = token.getFeatures().get("string").toString();

            // stem the string feature and change it to lowercase
            String stem = stem(tokenString).toLowerCase();

            // store the new feature
            token.getFeatures().put("stem", stem);

            // report our progress
            fireProgressChanged(tokenCount++ * 100 / allTokens.size());
        }

        // we've finished so report this
        fireProcessFinished();
        fireStatusChanged(document.getName() + " stemmed in "
                + NumberFormat.getInstance().format((double) (System.currentTimeMillis() - startTime) / 1000)
                + " seconds!");
    } else {
        if (failOnMissingInputAnnotations) {
            throw new ExecutionException("No tokens to process in document " + document.getName() + "\n"
                    + "Please run a tokeniser first!");
        } else {
            Utils.logOnce(logger, Level.INFO,
                    "BulStem: no token annotations in input document - see debug log for details.");
            logger.debug("No input annotations in document " + document.getName());
        }
    }
}