Example usage for org.jfree.data.time TimeSeries addOrUpdate

List of usage examples for org.jfree.data.time TimeSeries addOrUpdate

Introduction

In this page you can find the example usage for org.jfree.data.time TimeSeries addOrUpdate.

Prototype

public TimeSeriesDataItem addOrUpdate(RegularTimePeriod period, Number value) 

Source Link

Document

Adds or updates an item in the times series and sends a SeriesChangeEvent to all registered listeners.

Usage

From source file:edu.fullerton.viewerplugin.TsPlot.java

private void addTimeSeries(ChanDataBuffer dbuf, boolean compact, TimeSeriesCollection mtds)
        throws LdvTableException {
    String legend = getLegend(dbuf, compact);
    TimeSeries ts;
    ts = new TimeSeries(legend, Millisecond.class);
    SimpleTimeZone utctz = new SimpleTimeZone(0, "UTC");

    float rate = dbuf.getChanInfo().getRate();
    double msPerSample = 1000 / rate;
    long startMs = TimeAndDate.gps2utc(dbuf.getTimeInterval().getStartGps()) * 1000;
    float[] data = dbuf.getData();
    for (int i = 0; i < dbuf.getDataLength(); i++) {
        long curMs = Math.round(msPerSample * i + startMs);
        Date t = new Date(curMs);
        ts.addOrUpdate(new Millisecond(t, utctz), data[i]);
        if (msPerSample >= 1000) {
            // this plots trend data as stair steps
            long endMs = Math.round(curMs + msPerSample - 1);
            Date t1 = new Date(endMs);
            ts.addOrUpdate(new Millisecond(t1, utctz), data[i]);
        }//w w w .  j  av a2s  .co  m
    }

    mtds.addSeries(ts);
    if (addLinFit) {
        TimeSeries linTs = LinFit(ts);
        mtds.addSeries(linTs);
    }

}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.DiskIOReport.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {//from   w w  w  .ja v  a 2 s . c  o  m
        PreparedStatement cmd = null;
        ResultSet rs = null;
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Average Free Disk Space (all paritions)</th><th>Average Write KB/s</th><th>Average Read KB/s</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            double average = 0;
            data.append("<tr><td>").append(url).append("</td>");
            try {

                cmd = con.prepareStatement(
                        "select avg(freespace) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td>");
            average = 0;

            try {
                cmd = con.prepareStatement(
                        "select avg(writekbs) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td>");
            average = 0;
            try {
                cmd = con.prepareStatement(
                        "select avg(readkbs) from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);
                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("<td>").append(average + "").append("</td></tr>");

            //ok now get the raw data....
            TimeSeriesContainer tsc = new TimeSeriesContainer();
            try {
                cmd = con.prepareStatement(
                        "select readkbs, writekbs,freespace, utcdatetime, driveidentifier from rawdatadrives where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                while (rs.next()) {

                    TimeSeries ts = tsc.Get(url + " " + rs.getString("driveidentifier") + " Read",
                            Millisecond.class);
                    TimeSeries ts2 = tsc.Get(url + " " + rs.getString("driveidentifier") + " Write",
                            Millisecond.class);
                    //TimeSeries ts2 = tsc.Get(urls.get(i) + " " + rs.getString("driveidentifier") , Millisecond.class);
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(4));
                    Millisecond m = new Millisecond(gcal.getTime());

                    ts.addOrUpdate(m, rs.getLong("readKBs"));

                    ts2.addOrUpdate(m, rs.getLong("writeKBs"));

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            for (int ik = 0; ik < tsc.data.size(); ik++) {
                col.addSeries(tsc.data.get(ik));
            }

        }
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Rate", col,
                true, false, false);

        data.append("</table>");
        try {
            // if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            // }
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }

}

From source file:net.sourceforge.subsonic.controller.StatusChartController.java

public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String type = request.getParameter("type");
    int index = Integer.parseInt(request.getParameter("index"));

    List<TransferStatus> statuses = Collections.emptyList();
    if ("stream".equals(type)) {
        statuses = statusService.getAllStreamStatuses();
    } else if ("download".equals(type)) {
        statuses = statusService.getAllDownloadStatuses();
    } else if ("upload".equals(type)) {
        statuses = statusService.getAllUploadStatuses();
    }/*from w w w .jav a  2  s. co  m*/

    if (index < 0 || index >= statuses.size()) {
        return null;
    }
    TransferStatus status = statuses.get(index);

    TimeSeries series = new TimeSeries("Kbps", Millisecond.class);
    TransferStatus.SampleHistory history = status.getHistory();
    long to = System.currentTimeMillis();
    long from = to - status.getHistoryLengthMillis();
    Range range = new DateRange(from, to);

    if (!history.isEmpty()) {

        TransferStatus.Sample previous = history.get(0);

        for (int i = 1; i < history.size(); i++) {
            TransferStatus.Sample sample = history.get(i);

            long elapsedTimeMilis = sample.getTimestamp() - previous.getTimestamp();
            long bytesStreamed = Math.max(0L, sample.getBytesTransfered() - previous.getBytesTransfered());

            double kbps = (8.0 * bytesStreamed / 1024.0) / (elapsedTimeMilis / 1000.0);
            series.addOrUpdate(new Millisecond(new Date(sample.getTimestamp())), kbps);

            previous = sample;
        }
    }

    // Compute moving average.
    series = MovingAverage.createMovingAverage(series, "Kbps", 20000, 5000);

    // Find min and max values.
    double min = 100;
    double max = 250;
    for (Object obj : series.getItems()) {
        TimeSeriesDataItem item = (TimeSeriesDataItem) obj;
        double value = item.getValue().doubleValue();
        if (item.getPeriod().getFirstMillisecond() > from) {
            min = Math.min(min, value);
            max = Math.max(max, value);
        }
    }

    // Add 10% to max value.
    max *= 1.1D;

    // Subtract 10% from min value.
    min *= 0.9D;

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);
    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false);
    XYPlot plot = (XYPlot) chart.getPlot();

    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
    Paint background = new GradientPaint(0, 0, Color.lightGray, 0, IMAGE_HEIGHT, Color.white);
    plot.setBackgroundPaint(background);

    XYItemRenderer renderer = plot.getRendererForDataset(dataset);
    renderer.setSeriesPaint(0, Color.blue.darker());
    renderer.setSeriesStroke(0, new BasicStroke(2f));

    // Set theme-specific colors.
    Color bgColor = getBackground(request);
    Color fgColor = getForeground(request);

    chart.setBackgroundPaint(bgColor);

    ValueAxis domainAxis = plot.getDomainAxis();
    domainAxis.setRange(range);
    domainAxis.setTickLabelPaint(fgColor);
    domainAxis.setTickMarkPaint(fgColor);
    domainAxis.setAxisLinePaint(fgColor);

    ValueAxis rangeAxis = plot.getRangeAxis();
    rangeAxis.setRange(new Range(min, max));
    rangeAxis.setTickLabelPaint(fgColor);
    rangeAxis.setTickMarkPaint(fgColor);
    rangeAxis.setAxisLinePaint(fgColor);

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, IMAGE_HEIGHT);

    return null;
}

From source file:org.madsonic.controller.StatusChartController.java

public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    String type = request.getParameter("type");
    int index = Integer.parseInt(request.getParameter("index"));

    List<TransferStatus> statuses = Collections.emptyList();
    if ("stream".equals(type)) {
        statuses = statusService.getAllStreamStatuses();
    } else if ("download".equals(type)) {
        statuses = statusService.getAllDownloadStatuses();
    } else if ("upload".equals(type)) {
        statuses = statusService.getAllUploadStatuses();
    }//from ww w  . jav a  2  s.c  o m

    if (index < 0 || index >= statuses.size()) {
        return null;
    }
    TransferStatus status = statuses.get(index);

    TimeSeries series = new TimeSeries("Kbps", Millisecond.class);
    TransferStatus.SampleHistory history = status.getHistory();
    long to = System.currentTimeMillis();
    long from = to - status.getHistoryLengthMillis();
    Range range = new DateRange(from, to);

    if (!history.isEmpty()) {

        TransferStatus.Sample previous = history.get(0);

        for (int i = 1; i < history.size(); i++) {
            TransferStatus.Sample sample = history.get(i);

            long elapsedTimeMilis = sample.getTimestamp() - previous.getTimestamp();
            long bytesStreamed = Math.max(0L, sample.getBytesTransfered() - previous.getBytesTransfered());

            double kbps = (8.0 * bytesStreamed / 1024.0) / (elapsedTimeMilis / 1000.0);
            series.addOrUpdate(new Millisecond(new Date(sample.getTimestamp())), kbps);

            previous = sample;
        }
    }

    // Compute moving average.
    series = MovingAverage.createMovingAverage(series, "Kbps", 20000, 5000);

    // Find min and max values.
    double min = 100;
    double max = 250;
    for (Object obj : series.getItems()) {
        TimeSeriesDataItem item = (TimeSeriesDataItem) obj;
        double value = item.getValue().doubleValue();
        if (item.getPeriod().getFirstMillisecond() > from) {
            min = Math.min(min, value);
            max = Math.max(max, value);
        }
    }

    // Add 10% to max value.
    max *= 1.1D;

    // Subtract 10% from min value.
    min *= 0.9D;

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);
    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, false, false, false);
    XYPlot plot = (XYPlot) chart.getPlot();

    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
    Paint background = new GradientPaint(0, 0, Color.lightGray, 0, IMAGE_HEIGHT, Color.white);
    plot.setBackgroundPaint(background);

    XYItemRenderer renderer = plot.getRendererForDataset(dataset);
    renderer.setSeriesPaint(0, Color.gray.darker());
    renderer.setSeriesStroke(0, new BasicStroke(2f));

    // Set theme-specific colors.
    Color bgColor = getBackground(request);
    Color fgColor = getForeground(request);

    chart.setBackgroundPaint(bgColor);

    ValueAxis domainAxis = plot.getDomainAxis();
    domainAxis.setRange(range);
    domainAxis.setTickLabelPaint(fgColor);
    domainAxis.setTickMarkPaint(fgColor);
    domainAxis.setAxisLinePaint(fgColor);

    ValueAxis rangeAxis = plot.getRangeAxis();
    rangeAxis.setRange(new Range(min, max));
    rangeAxis.setTickLabelPaint(fgColor);
    rangeAxis.setTickMarkPaint(fgColor);
    rangeAxis.setAxisLinePaint(fgColor);

    ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, IMAGE_WIDTH, IMAGE_HEIGHT);

    return null;
}

From source file:org.matsim.contrib.drt.analysis.DynModeTripsAnalyser.java

public static void analyseWaitTimes(String fileName, List<DynModeTrip> trips, int binsize_s) {
    Collections.sort(trips);//from   w  w  w  .ja va  2s.c  o  m
    if (trips.size() == 0)
        return;
    int startTime = ((int) (trips.get(0).getDepartureTime() / binsize_s)) * binsize_s;
    int endTime = ((int) (trips.get(trips.size() - 1).getDepartureTime() / binsize_s) + binsize_s) * binsize_s;
    Map<Double, List<DynModeTrip>> splitTrips = splitTripsIntoBins(trips, startTime, endTime, binsize_s);

    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(2);
    format.setGroupingUsed(false);

    SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");

    BufferedWriter bw = IOUtils.getBufferedWriter(fileName + ".csv");
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    TimeSeriesCollection datasetrequ = new TimeSeriesCollection();
    TimeSeries averageWaitC = new TimeSeries("average");
    TimeSeries medianWait = new TimeSeries("median");
    TimeSeries p_5Wait = new TimeSeries("5th percentile");
    TimeSeries p_95Wait = new TimeSeries("95th percentile");
    TimeSeries requests = new TimeSeries("Ride requests");

    try {
        bw.write("timebin;trips;average_wait;min;p_5;p_25;median;p_75;p_95;max");
        for (Entry<Double, List<DynModeTrip>> e : splitTrips.entrySet()) {
            long rides = 0;
            double averageWait = 0;
            double min = 0;
            double p_5 = 0;
            double p_25 = 0;
            double median = 0;
            double p_75 = 0;
            double p_95 = 0;
            double max = 0;
            if (!e.getValue().isEmpty()) {
                DescriptiveStatistics stats = new DescriptiveStatistics();
                for (DynModeTrip t : e.getValue()) {
                    stats.addValue(t.getWaitTime());
                }
                rides = stats.getN();
                averageWait = stats.getMean();
                min = stats.getMin();
                p_5 = stats.getPercentile(5);
                p_25 = stats.getPercentile(25);
                median = stats.getPercentile(50);
                p_75 = stats.getPercentile(75);
                p_95 = stats.getPercentile(95);
                max = stats.getMax();

            }
            Minute h = new Minute(sdf2.parse(Time.writeTime(e.getKey())));

            medianWait.addOrUpdate(h, Double.valueOf(median));
            averageWaitC.addOrUpdate(h, Double.valueOf(averageWait));
            p_5Wait.addOrUpdate(h, Double.valueOf(p_5));
            p_95Wait.addOrUpdate(h, Double.valueOf(p_95));
            requests.addOrUpdate(h, rides * 3600. / binsize_s);// normalised [req/h]
            bw.newLine();
            bw.write(Time.writeTime(e.getKey()) + ";" + rides + ";" + format.format(averageWait) + ";"
                    + format.format(min) + ";" + format.format(p_5) + ";" + format.format(p_25) + ";"
                    + format.format(median) + ";" + format.format(p_75) + ";" + format.format(p_95) + ";"
                    + format.format(max));

        }
        bw.flush();
        bw.close();
        dataset.addSeries(averageWaitC);
        dataset.addSeries(medianWait);
        dataset.addSeries(p_5Wait);
        dataset.addSeries(p_95Wait);
        datasetrequ.addSeries(requests);
        JFreeChart chart = chartProfile(splitTrips.size(), dataset, "Waiting times", "Wait time (s)");
        JFreeChart chart2 = chartProfile(splitTrips.size(), datasetrequ, "Ride requests per hour",
                "Requests per hour (req/h)");
        ChartSaveUtils.saveAsPNG(chart, fileName, 1500, 1000);
        ChartSaveUtils.saveAsPNG(chart2, fileName + "_requests", 1500, 1000);

    } catch (IOException | ParseException e) {

        e.printStackTrace();
    }

}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.CpuUsageReport.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {
    Connection con = Utility.getPerformanceDBConnection();
    try {/*www  . ja  va  2s.  c  o m*/
        PreparedStatement cmd = null;
        ResultSet rs = null;
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append("<table class=\"table table-hover\"><tr><th>URI</th><th>Average CPU Usage %</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)
                    && !isPolicyTypeOf(urls.get(i), PolicyType.PROCESS)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            data.append("<tr><td>").append(url).append("</td>");
            double average = 0;
            try {
                cmd = con.prepareStatement(
                        "select avg(percentcpu) from rawdatamachineprocess where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();
                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td></tr>");
            TimeSeries ts = new TimeSeries(url, Millisecond.class);
            try {
                //ok now get the raw data....
                cmd = con.prepareStatement(
                        "select percentcpu,utcdatetime from rawdatamachineprocess where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();
                while (rs.next()) {
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(2));
                    Millisecond m = new Millisecond(gcal.getTime());
                    ts.addOrUpdate(m, rs.getDouble(1));

                }
                col.addSeries(ts);

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

        }
        data.append("</table>");

        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Percent",
                col, true, false, false);

        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            // }
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.ThreadCount.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {//from  w  ww .java  2 s  . co m
        PreparedStatement cmd = null;
        ResultSet rs = null;
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append("<table class=\"table table-hover\"><tr><th>URI</th><th>Average Thread Count</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.MACHINE)
                    && !isPolicyTypeOf(urls.get(i), PolicyType.PROCESS)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            data.append("<tr><td>").append(url).append("</td>");
            double average = 0;
            try {

                cmd = con.prepareStatement(
                        "select avg(threads) from rawdatamachineprocess where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();
                if (rs.next()) {
                    average = rs.getDouble(1);
                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td></tr>");
            TimeSeries ts = new TimeSeries(urls.get(i), Millisecond.class);
            try {
                //ok now get the raw data....
                cmd = con.prepareStatement(
                        "select threads,utcdatetime from rawdatamachineprocess where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                while (rs.next()) {
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(2));
                    Millisecond m = new Millisecond(gcal.getTime());

                    ts.addOrUpdate(m, rs.getLong(1));
                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            col.addSeries(ts);
        }

        data.append("</table>");
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Count", col,
                true, false, false);

        try {
            //if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            // }
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.OpenFilesByProcess.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {//from  www.ja  va  2s. c o m
        PreparedStatement cmd = null;
        ResultSet rs = null;
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Average Open File Handles Count</th></tr>");
        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.PROCESS)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            data.append("<tr><td>").append(url).append("</td>");
            double average = 0;
            try {
                cmd = con.prepareStatement(
                        "select avg(openfiles) from rawdatamachineprocess where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());

                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            data.append("<td>").append(average + "").append("</td></tr>");
            TimeSeries ts = new TimeSeries(url, Millisecond.class);
            try {
                //ok now get the raw data....
                cmd = con.prepareStatement(
                        "select utcdatetime, openfiles from rawdatamachineprocess where uri=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());

                rs = cmd.executeQuery();

                while (rs.next()) {

                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(1));
                    Millisecond m = new Millisecond(gcal.getTime());
                    ts.addOrUpdate(m, rs.getLong(2));

                }
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            col.addSeries(ts);

        }

        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Count", col,
                true, false, false);

        data.append("</table>");
        try {
            // if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            //}
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:gsn.vsensor.ChartVirtualSensor.java

/**
 * This method adds the specified stream elements to the timeSeries of the
 * appropriate plot.//from   w  w  w.j  ava 2  s  .c om
 * 
 * @param streamElement
 */
public synchronized void addData(StreamElement streamElement) {
    for (int i = 0; i < streamElement.getFieldNames().length; i++) {
        TimeSeries timeSeries = dataForTheChart.get(streamElement.getFieldNames()[i]);
        if (timeSeries == null) {
            dataForTheChart.put(streamElement.getFieldNames()[i],
                    timeSeries = new TimeSeries(streamElement.getFieldNames()[i],
                            org.jfree.data.time.FixedMillisecond.class));
            if (isTimeBased) {
                timeSeries.setMaximumItemAge(historySize);
            } else {
                timeSeries.setMaximumItemCount(historySize);
            }
            dataCollectionForTheChart.addSeries(timeSeries);
        }
        try {
            timeSeries.addOrUpdate(new FixedMillisecond(new Date(streamElement.getTimeStamp())),
                    Double.parseDouble(streamElement.getData()[i].toString()));
        } catch (SeriesException e) {
            logger.warn(e.getMessage(), e);
        }

    }
    changed = true;
}

From source file:WeatherFrame.java

private void OpenMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:     
    TimeSeries timeSeries = new TimeSeries("Data");
    weatherList ww = new weatherList();

    int returnVal = fc.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {

        File[] file = fc.getSelectedFiles();
        //This is where a real application would open the file.

        XmlReader filereader = new XmlReader();

        for (int i = 0; i < file.length; i++)
            filereader.ReadFile(file[i].getAbsoluteFile().toString(), ww);
        ww.sortList();/* w ww.  j  a v  a2s. com*/
        for (int i = 0; i < ww.getWeatherData().size(); i++) {
            //  System.out.println(ww.weatherData.get(i).getDateTime());
            timeSeries.addOrUpdate(new Day(ww.getWeatherData().get(i).getDateTime()),
                    ww.getWeatherData().get(i).getTemperature());
        }
        TempSet.addSeries(timeSeries);
    } else {
        System.out.println("Open command cancelled by user.\n");
    }
}