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

Source Link

Document

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

Usage

From source file:voldemort.server.protocol.hadoop.RestHadoopFetcher.java

/**
 * Function to copy a file from the given filesystem with a checksum of type
 * 'checkSumType' computed and returned. In case an error occurs during such
 * a copy, we do a retry for a maximum of NUM_RETRIES
 * /*from   w  w w. j a v a2 s  .co  m*/
 * @param rfs RestFilesystem used to copy the file
 * @param source Source path of the file to copy
 * @param dest Destination path of the file on the local machine
 * @param stats Stats for measuring the transfer progress
 * @param checkSumType Type of the Checksum to be computed for this file
 * @return A Checksum (generator) of type checkSumType which contains the
 *         computed checksum of the copied file
 * @throws IOException
 */
private CheckSum copyFileWithCheckSum(RestFileSystem rfs, String source, File dest, CopyStats stats,
        CheckSumType checkSumType) throws Throwable {
    CheckSum fileCheckSumGenerator = null;
    logger.info("Starting copy of " + source + " to " + dest);
    BufferedInputStream input = null;
    OutputStream output = null;

    for (int attempt = 0; attempt < maxAttempts; attempt++) {
        boolean success = true;
        long totalBytesRead = 0;
        boolean fsOpened = false;

        try {
            // Create a per file checksum generator
            if (checkSumType != null) {
                fileCheckSumGenerator = CheckSum.getInstance(checkSumType);
            }

            logger.info("Attempt " + attempt + " at copy of " + source + " to " + dest);

            input = new BufferedInputStream(rfs.openFile(source).getInputStream());
            fsOpened = true;

            output = new BufferedOutputStream(new FileOutputStream(dest));
            byte[] buffer = new byte[bufferSize];
            while (true) {
                int read = input.read(buffer);
                if (read < 0) {
                    break;
                } else {
                    output.write(buffer, 0, read);
                }

                // Update the per file checksum
                if (fileCheckSumGenerator != null) {
                    fileCheckSumGenerator.update(buffer, 0, read);
                }

                // Check if we need to throttle the fetch
                if (throttler != null) {
                    throttler.maybeThrottle(read);
                }

                stats.recordBytes(read);
                if (stats.getBytesSinceLastReport() > reportingIntervalBytes) {
                    NumberFormat format = NumberFormat.getNumberInstance();
                    format.setMaximumFractionDigits(2);
                    logger.info(stats.getTotalBytesCopied() / (1024 * 1024) + " MB copied at "
                            + format.format(stats.getBytesPerSecond() / (1024 * 1024)) + " MB/sec - "
                            + format.format(stats.getPercentCopied()) + " % complete, destination:" + dest);
                    if (this.status != null) {
                        this.status.setStatus(stats.getTotalBytesCopied() / (1024 * 1024) + " MB copied at "
                                + format.format(stats.getBytesPerSecond() / (1024 * 1024)) + " MB/sec - "
                                + format.format(stats.getPercentCopied()) + " % complete, destination:" + dest);
                    }
                    stats.reset();
                }
            }
            // at this point, we are done!
            logger.info("Completed copy of " + source + " to " + dest);
        } catch (Throwable te) {
            success = false;
            if (!fsOpened) {
                logger.error("Error while opening the file stream to " + source, te);
            } else {
                logger.error("Error while copying file " + source + " after " + totalBytesRead + " bytes.", te);
            }
            if (te.getCause() != null) {
                logger.error("Cause of error ", te.getCause());
            }
            te.printStackTrace();

            if (attempt < maxAttempts - 1) {
                logger.info("Will retry copying after " + retryDelayMs + " ms");
                sleepForRetryDelayMs();
            } else {
                logger.info("Fetcher giving up copy after " + maxAttempts + " attempts");
                throw te;
            }
        } finally {
            IOUtils.closeQuietly(output);
            IOUtils.closeQuietly(input);
            if (success) {
                break;
            }
        }
        logger.info("Completed copy of " + source + " to " + dest);
    }
    return fileCheckSumGenerator;
}

From source file:massbank.BatchJobWorker.java

/**
 * Ytt@C???iHTML`?j/*from   w w  w  .  j  a  v a 2 s  . c  o m*/
 * @param time NGXg 
 * @param resultFile t@C
 * @param htmlFile YtpHTMLt@C
 */
private void createHtmlFile(String time, File resultFile, File htmlFile) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    LineNumberReader in = null;
    PrintWriter out = null;
    try {
        in = new LineNumberReader(new FileReader(resultFile));
        out = new PrintWriter(new BufferedWriter(new FileWriter(htmlFile)));

        // wb_?[?o
        String reqIonStr = "Both";
        try {
            if (Integer.parseInt(this.ion) > 0) {
                reqIonStr = "Positive";
            } else if (Integer.parseInt(this.ion) < 0) {
                reqIonStr = "Negative";
            }
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
        out.println("<html>");
        out.println("<head><title>MassBank Batch Service Results</title></head>");
        out.println("<body>");
        out.println(
                "<h1><a href=\"http://www.massbank.jp/\" target=\"_blank\">MassBank</a> Batch Service Results</h1>");
        out.println("<hr>");
        out.println("<h2>Request Date : " + time + "<h2>");
        out.println("Instrument Type : " + this.inst + "<br>");
        out.println("Ion Mode : " + reqIonStr + "<br>");
        out.println("<br><hr>");

        // ?o
        String line;
        long queryCnt = 0;
        boolean readName = false;
        boolean readHit = false;
        boolean readNum = false;
        while ((line = in.readLine()) != null) {
            if (in.getLineNumber() < 4) {
                continue;
            }
            if (!readName) {
                queryCnt++;
                out.println("<h2>Query " + nf.format(queryCnt) + "</h2><br>");
                out.println("Name: " + line.trim() + "<br>");
                readName = true;
            } else if (!readHit) {
                out.println("Hit: " + nf.format(Integer.parseInt(line.trim())) + "<br>");
                readHit = true;
            } else if (!readNum) {
                out.println("<table border=\"1\">");
                out.println("<tr><td colspan=\"6\">Top " + line.trim() + " List</td></tr>");
                out.println(
                        "<tr><th>Accession</th><th>Title</th><th>Formula</th><th>Ion</th><th>Score</th><th>Hit</th></tr>");
                readNum = true;
            } else {
                if (!line.trim().equals("")) {
                    String[] data = formatLine(line);
                    String acc = data[0];
                    String title = data[1];
                    String formula = data[2];
                    String ion = data[3];
                    String score = data[4];
                    String hit = data[5];

                    out.println("<tr>");
                    out.println("<td><a href=\"http://www.massbank.jp/jsp/FwdRecord.jsp?id=" + acc
                            + "\" target=\"_blank\">" + acc + "</td>");
                    out.println("<td>" + title + "</td>");
                    out.println("<td>" + formula + "</td>");
                    out.println("<td>" + ion + "</td>");
                    out.println("<td>" + score + "</td>");
                    out.println("<td align=\"right\">" + hit + "</td>");
                    out.println("</tr>");
                } else {
                    out.println("</table>");
                    out.println("<hr>");
                    readName = false;
                    readHit = false;
                    readNum = false;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:com.clustercontrol.jmx.factory.RunMonitorJmx.java

/**
 * ????//w  w  w . j a va  2s .  c o  m
 */
@Override
public String getMessage(int result) {
    String message;
    if (exception == null) {
        if (Double.isNaN(m_value)) {
            message = NaN;
        } else {
            if (!"".equals(m_message.trim()))
                return m_message;
            String name = "?";
            try {
                JmxMasterInfo jmxMasterInfo = QueryUtil.getJmxMasterInfoPK(jmx.getMasterId());
                name = jmxMasterInfo.getName();
            } catch (MonitorNotFound e) {
                m_log.warn("not found : " + jmx.getMasterId());
            }
            if (m_prevNullchk) {
                message = name + " : ";
                return message;
            }
            message = name + " : " + NumberFormat.getNumberInstance().format(m_value);
        }
    } else {
        String name = "?";
        try {
            JmxMasterInfo jmxMasterInfo = QueryUtil.getJmxMasterInfoPK(jmx.getMasterId());
            name = jmxMasterInfo.getName();
        } catch (MonitorNotFound e) {
            m_log.warn("not found : " + jmx.getMasterId());
        }
        message = name + " : " + MessageConstant.MESSAGE_COULD_NOT_GET_VALUE_JMX.getMessage();
    }
    return message;
}

From source file:com.clustercontrol.process.factory.RunMonitorProcess.java

/**
 * ?????????<BR>/*from w w w  .  jav  a 2s. c o m*/
 * ?????? preCollect ?????
 * 
 * @param facilityId ID
 * @return ???????true
 */
@Override
public boolean collect(String facilityId) {

    if (m_log.isDebugEnabled())
        m_log.debug("collect() : start." + " facilityId = " + m_facilityId + ", monitorId = " + m_monitorId
                + ", monitorType = " + m_monitorTypeId);

    // ?,???
    int count = 0;

    // 
    if (m_now != null) {
        m_nodeDate = m_now.getTime();
    }
    m_value = 0;

    // 
    m_messageOrg = MessageConstant.COMMAND.getMessage() + " : " + m_command + ", "
            + MessageConstant.PARAM.getMessage() + " : " + m_param;

    // ???
    Pattern pCommand = null;
    Pattern pParam = null;
    try {
        // ?????
        if (m_process.getCaseSensitivityFlg()) {
            pCommand = Pattern.compile(m_command, Pattern.CASE_INSENSITIVE);
            pParam = Pattern.compile(m_param, Pattern.CASE_INSENSITIVE);
        }
        // ???
        else {
            pCommand = Pattern.compile(m_command);
            pParam = Pattern.compile(m_param);
        }
    } catch (PatternSyntaxException e) {
        m_log.info("collect() command, parameter PatternSyntax error : " + e.getClass().getSimpleName() + ", "
                + e.getMessage());
        m_message = MessageConstant.MESSAGE_PLEASE_SET_VALUE_WITH_REGEX.getMessage();
        return false;
    }

    @SuppressWarnings("unchecked")
    List<ProcessInfo> procList = (List<ProcessInfo>) preCollectData;

    if (procList == null) {
        // TODO nagatsumas ???OK
        // ??????????????
        return false;
    } else {
        // ??????????
        for (ProcessInfo procInfo : procList) {
            if (pCommand.matcher(procInfo.command).matches()) {
                if (pParam.matcher(procInfo.param).matches()) {
                    count++;
                    // ??
                    m_nodeDate = procInfo.time;
                    // ????
                    if (ProcessProperties.getProperties().isDetailedDisplay()) {
                        m_messageOrg = m_messageOrg + "\n";

                        if (procInfo.pid != null) {
                            // PID???????SNMP????
                            m_messageOrg = m_messageOrg + procInfo.pid + " : ";
                        }

                        m_messageOrg = m_messageOrg + procInfo.command + " " + procInfo.param;
                    }
                }
            }
        }
    }
    // 
    m_value = count;
    m_message = MessageConstant.PROCESS_NUMBER.getMessage() + " : "
            + NumberFormat.getNumberInstance().format(m_value);

    if (m_log.isDebugEnabled())
        m_log.debug("collect() : end." + " facilityId = " + m_facilityId + ", monitorId = " + m_monitorId
                + ", monitorType = " + m_monitorTypeId + ", count = " + count);

    return true;

    //      // ???????
    //      m_message = MessageConstant.MESSAGE_TIME_OUT.getMessage();
    //      return false;
}

From source file:FPSCounterDemo.java

public FPSCounter() {
        setEnable(true);
        nf = NumberFormat.getNumberInstance();
    }

From source file:org.emftrace.quarc.ui.views.RatioView.java

/**
 * create a PieChart for the priorities of the goals
 * @param dataset the used Dataset//w  ww  .  j a  v  a 2  s  .com
 * @return the created Chart
 */
private JFreeChart createChart(PieDataset dataset) {

    JFreeChart chart = ChartFactory.createPieChart3D("priorities of selected goals", // chart
            // title
            dataset, // data
            true, // include legend
            true, false);

    final org.jfree.chart.plot.PiePlot3D plot = (org.jfree.chart.plot.PiePlot3D) chart.getPlot();
    plot.setStartAngle(290);
    plot.setDirection(Rotation.CLOCKWISE);
    plot.setForegroundAlpha(0.5f);
    plot.setNoDataMessage("No data to display");
    plot.setLabelGenerator(new org.jfree.chart.labels.StandardPieSectionLabelGenerator("{0} = {2}",
            NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));

    return chart;
}

From source file:com.cypress.cysmart.BLEServiceFragments.CSCService.java

/**
 * Display live cycling data//from ww w . java2s  .  c o m
 */
private void displayLiveData(final ArrayList<String> csc_data) {
    if (csc_data != null) {
        weightString = mWeightEdittext.getText().toString();
        try {
            Number cycledDist = NumberFormat.getInstance().parse(csc_data.get(0));
            NumberFormat distformatter = NumberFormat.getNumberInstance();
            distformatter.setMinimumFractionDigits(2);
            distformatter.setMaximumFractionDigits(2);
            String distanceRanInt = distformatter.format(cycledDist);
            mDistanceRan.setText(distanceRanInt);
            mCadence.setText(csc_data.get(1));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if (mCurrentTime == 0) {
            mGraphLastXValue = 0;
            mCurrentTime = Utils.getTimeInSeconds();
        } else {
            mPreviosTime = mCurrentTime;
            mCurrentTime = Utils.getTimeInSeconds();
            mGraphLastXValue = mGraphLastXValue + (mCurrentTime - mPreviosTime) / 1000;
        }
        try {
            float val = Float.valueOf(csc_data.get(1));
            mDataSeries.add(mGraphLastXValue, val);
            mChart.repaint();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

From source file:com.opensourcestrategies.activities.reports.ActivitiesChartsService.java

private String createPieChart(DefaultPieDataset dataset, String title)
        throws InfrastructureException, IOException {
    Debug.logInfo("Charting dashboard [" + title + "]", MODULE);
    // set up the chart
    JFreeChart chart = ChartFactory.createPieChart(title, dataset, true, // include legend
            true, // tooltips
            false // urls
    );//from  w ww  . j  a v  a  2s .  c  om
    chart.setBackgroundPaint(Color.white);
    chart.setBorderVisible(true);
    chart.setPadding(new RectangleInsets(5.0, 5.0, 5.0, 5.0));

    // get a reference to the plot for further customization...
    final PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setCircular(true);
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}: {1} / {2}",
            NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));
    plot.setNoDataMessage("No data available");

    Color[] colors = {
            Color.decode("#" + infrastructure.getConfigurationValue(
                    OpentapsConfigurationTypeConstants.ACTIVITIES_DASHBOARD_LEADS_NEW_COLOR)),
            Color.decode("#" + infrastructure.getConfigurationValue(
                    OpentapsConfigurationTypeConstants.ACTIVITIES_DASHBOARD_LEADS_OLD_COLOR)),
            Color.decode("#" + infrastructure.getConfigurationValue(
                    OpentapsConfigurationTypeConstants.ACTIVITIES_DASHBOARD_LEADS_NO_ACTIVITY_COLOR)) };
    for (int i = 0; i < dataset.getItemCount(); i++) {
        Comparable<?> key = dataset.getKey(i);
        plot.setSectionPaint(key, colors[i]);
    }

    // save as a png and return the file name
    return ServletUtilities.saveChartAsPNG(chart, chartWidth, chartHeight, null);
}

From source file:de.tor.tribes.ui.algo.TimeFrameVisualizer.java

private void renderDayMarkers(long pStart, long pEnd, Graphics2D pG2D) {
    Date d = new Date(pStart);
    d = DateUtils.setHours(d, 0);/*from   w  ww . j a v  a  2 s  . c  o  m*/
    d = DateUtils.setMinutes(d, 0);
    d = DateUtils.setSeconds(d, 0);
    d = DateUtils.setMilliseconds(d, 0);

    for (long mark = d.getTime(); mark <= pEnd; mark += DateUtils.MILLIS_PER_HOUR) {
        int markerPos = Math.round((mark - pStart) / DateUtils.MILLIS_PER_MINUTE);
        pG2D.setColor(Color.YELLOW);
        pG2D.fillRect(markerPos, 20, 2, 10);
        pG2D.setColor(Color.WHITE);
        pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 10.0f));
        pG2D.fillRect(markerPos - 5, 15, 12, 10);
        pG2D.setColor(Color.BLACK);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(mark));
        NumberFormat f = NumberFormat.getNumberInstance();
        f.setMinimumIntegerDigits(2);
        f.setMaximumFractionDigits(2);
        pG2D.drawString(f.format(cal.get(Calendar.HOUR_OF_DAY)), markerPos - 5, 23);
    }

    long currentDay = d.getTime();
    while (currentDay < pEnd) {
        currentDay += DateUtils.MILLIS_PER_DAY;
        int markerPos = Math.round((currentDay - pStart) / DateUtils.MILLIS_PER_MINUTE);
        pG2D.setColor(new Color(123, 123, 123));
        pG2D.fillRect(markerPos, 15, 3, 30);
        SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy");
        String dayLabel = f.format(currentDay);
        Rectangle2D labelBounds = pG2D.getFontMetrics().getStringBounds(dayLabel, pG2D);
        pG2D.setColor(Color.YELLOW);
        int labelWidth = (int) labelBounds.getWidth() + 5;
        pG2D.fillRect(markerPos - (int) Math.rint(labelWidth / 2), 15, labelWidth, 10);
        pG2D.setColor(Color.BLACK);
        pG2D.setFont(pG2D.getFont().deriveFont(Font.BOLD, 10.0f));
        pG2D.drawString(dayLabel, markerPos - (int) Math.rint(labelWidth / 2) + 2, 23);
    }
}

From source file:com.mgmtp.perfload.loadprofiles.util.PlotFileCreator.java

/**
 * Create a plot in .csv-format of the given x and y values, starting with a headerline
 * containing the given xText and yText.
 *//*from w ww  . j a va 2 s  .co  m*/
private static void createPlot(final File file, final double[] x, final double[] y, final String xText,
        final String yText) throws IOException {

    PrintWriter pw = null;
    try {
        forceMkdir(file.getParentFile());
        pw = new PrintWriter(file, "UTF-8");

        Format format = NumberFormat.getNumberInstance();
        pw.println(xText + "; " + yText);
        for (int iLine = 0; iLine < x.length; iLine++) {
            pw.println(format.format(x[iLine]) + "; " + format.format(y[iLine]));
        }
    } finally {
        IOUtils.closeQuietly(pw);
    }
}