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:com.charts.IntradayChart.java

public IntradayChart(YStockQuote currentStock) {

    TimeSeries series = new TimeSeries(currentStock.get_name());
    ArrayList<String> fiveDayData = currentStock.get_one_day_data();
    int length = fiveDayData.size();
    for (int i = 17; i < length; i++) {
        String[] data = fiveDayData.get(i).split(",");
        Date time = new Date((long) Integer.parseInt(data[0]) * 1000);
        DateFormat df = new SimpleDateFormat("MM-dd-yyyy-h-m");
        series.addOrUpdate(new Minute(time), Double.parseDouble(data[1]));
    }//from  w  ww .  ja  v  a  2  s . c  o  m
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);
    JFreeChart chart = ChartFactory.createTimeSeriesChart(
            currentStock.get_name() + "(" + currentStock.get_symbol() + ")" + " Intraday", "Date", "Price",
            dataset, true, true, false);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);
    ValueAxis yAxis = (ValueAxis) plot.getRangeAxis();
    DateAxis xAxis = (DateAxis) plot.getDomainAxis();
    xAxis.setTimeline(SegmentedTimeline.newMondayThroughFridayTimeline());
    xAxis.setDateFormatOverride(new SimpleDateFormat("h:m a"));
    xAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
    //xAxis.setVerticalTickLabels(true);
    chartPanel = new ChartPanel(chart);
    chart.setBackgroundPaint(chartPanel.getBackground());
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    chartPanel.setVisible(true);
    chartPanel.revalidate();
    chartPanel.repaint();
}

From source file:org.miloss.fgsms.services.rs.impl.reports.ws.ResponseTimeOverTime.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 {/*w w  w  . j a  va 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 Response Time (ms)</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }

            try {
                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(responsetimems) from rawdata 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(format.format(average) + "").append("</td></tr>");

                //ok now get the raw data....
                TimeSeriesContainer tsc = new TimeSeriesContainer();
                try {
                    cmd = con.prepareStatement(
                            "select responsetimems,utcdatetime  from rawdata 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 ts2 = tsc.Get(url, Millisecond.class);
                        GregorianCalendar gcal = new GregorianCalendar();
                        gcal.setTimeInMillis(rs.getLong(2));
                        Millisecond m = new Millisecond(gcal.getTime());
                        ts2.addOrUpdate(m, rs.getLong("responsetimems"));
                    }
                } 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));
                }

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

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

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

        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.squale.squaleweb.util.graph.AreaMaker.java

/**
 * Ajoute les valeurs d'une courbe//  w w  w.  java  2  s. c om
 * 
 * @param pName nom associ  la future courbe
 * @param pValues Map contenant en cl des date (java.util.Date) et en valeurs des nombres (Number)
 */
public void addCurve(String pName, Map pValues) {
    TimeSeries timeSeries = new TimeSeries(pName);
    Set keys = pValues.keySet();
    Iterator it = keys.iterator();
    double acc = 0;
    while (it.hasNext()) {
        Date date = (Date) it.next();
        Day day = new Day(date);
        // On cumule les rsultats
        acc += ((Number) pValues.get(date)).doubleValue();
        timeSeries.addOrUpdate(day, new Double(acc));
    }
    mDataSet.addSeries(timeSeries);
}

From source file:com.freedomotic.plugins.devices.harvester_chart.HarvesterChart.java

@ListenEventsOn(channel = "app.event.sensor.object.behavior.clicked")
public void onObjectClicked(EventTemplate event) {
    List<String> behavior_list = new ArrayList<String>();
    System.out.println("received event " + event.toString());
    ObjectReceiveClick clickEvent = (ObjectReceiveClick) event;
    //PRINT EVENT CONTENT WITH
    System.out.println(clickEvent.getPayload().toString());
    String objectName = clickEvent.getProperty("object.name");
    String protocol = clickEvent.getProperty("object.protocol");
    String address = clickEvent.getProperty("object.address");

    try {/*w w w  .ja  v  a 2  s  .co m*/
        Statement stat = connection.createStatement();
        System.out.println("Protocol=" + protocol + ",Address=" + address);

        //for (EnvObjectLogic object : EnvObjectPersistence.getObjectByProtocol("wifi_id")){
        //EnvObjectLogic object = EnvObjectPersistence.getObjectByName(objectName);

        for (EnvObjectLogic object : EnvObjectPersistence.getObjectByAddress(protocol, address)) {
            for (BehaviorLogic behavior : object.getBehaviors()) {
                System.out.println(behavior.getName());
            }
        }

        //String query = "select date,value from events where protocol='"+clickEvent.getProperty("object.protocol")+"' and behavior='power' ORDER BY ID DESC LIMIT 1000;";
        String query = "select date,value from events where object='" + objectName
                + "' and behavior='power' ORDER BY ID DESC LIMIT 1000;";
        System.out.println(query);
        //String query = "select datetime(date, 'unixepoch', 'localtime') as TIME,value from events where protocol='remote_receiver' and behavior='button'";

        ResultSet rs = stat.executeQuery(query);
        //JFreeChart chart = ChartFactory.createLineChart("Test", "Id", "Score", dataset, PlotOrientation.VERTICAL, true, true, false); 

        //System.out.println("Wilson Kong Debug:"+rs.getLong("date"));
        final TimeSeries series = new TimeSeries("Data1", Millisecond.class);

        while (rs.next()) {
            Date resultdate = new Date(rs.getLong("date") * 1000);
            Millisecond ms_read = new Millisecond(resultdate);
            series.addOrUpdate(ms_read, rs.getDouble("value"));
            //series.add((Millisecond)rs.getLong("date"),(double)rs.getLong("value"));
        }
        XYDataset xyDataset = new TimeSeriesCollection(series);

        JFreeChart chart = ChartFactory.createTimeSeriesChart("Chart", "TIME", "VALVE", xyDataset, true, // legend
                true, // tooltips
                false // urls
        );
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new java.awt.Dimension(800, 500));
        JFrame f = new JFrame("Chart");
        f.setContentPane(chartPanel);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.pack();
        f.setVisible(true);
        //if (...) {
        //MyFrame myFrame = new MyFrame();
        //bindGuiToPlugin(myFrame);
        //showGui(); //triggers the showing of your frame. Before it calls onShowGui()
        //}
    } catch (SQLException ex) {
        Logger.getLogger(HarvesterChart.class.getName()).log(Level.SEVERE, ex.getLocalizedMessage());
        System.out.println("Wilson Kong Error: " + ex.toString());
        //ex.printStackTrace();
        stop();
    }
}

From source file:de.suse.swamp.modules.scheduledjobs.Statistics.java

/**
 * Generating the graphs that show the amount of running finished wfs over the time.
 *///from   ww  w  .j  a va2s .  c  o m
protected void generateWorkflowGraph(String templateName, Date startDate, Date endDate) throws Exception {
    List stats = StatisticStorage.loadStats(templateName, startDate, endDate);
    // only generate if we have stats: 
    if (stats != null && stats.size() > 0) {
        TimeSeriesCollection dataset = new TimeSeriesCollection();
        TimeSeriesCollection avgdataset = new TimeSeriesCollection();
        TimeSeries serie = new TimeSeries("running workflows", Day.class);
        TimeSeries avgserie = new TimeSeries("average age", Day.class);
        for (Iterator datait = stats.iterator(); datait.hasNext();) {
            Dbstatistics statisticItem = (Dbstatistics) datait.next();
            serie.addOrUpdate(new Day(statisticItem.getDate()), statisticItem.getRunningcount());
            avgserie.addOrUpdate(new Day(statisticItem.getDate()), statisticItem.getAvgage() / (3600 * 24));
        }
        dataset.addSeries(serie);
        avgdataset.addSeries(avgserie);

        JFreeChart chart = ChartFactory.createTimeSeriesChart("Running " + templateName + " workflows", "Date",
                "running workflows", dataset, false, false, false);

        // modify chart appearance
        chart.setBackgroundImageAlpha(0.5f);
        XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);
        plot.getRangeAxis().setLabelPaint(Color.blue);

        // add the second line: 
        final NumberAxis axis2 = new NumberAxis("Avg. age in days");
        axis2.setLabelPaint(Color.red);
        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, avgdataset);
        plot.mapDatasetToRangeAxis(1, 1);

        final XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer();
        renderer2.setDrawOutlines(false);
        renderer2.setDrawSeriesLineAsPath(true);
        renderer2.setBaseShapesVisible(false);
        plot.setRenderer(1, renderer2);

        File image = new File(statPath + fs + templateName + ".png");
        if (image.exists())
            image.delete();
        try {
            ChartUtilities.saveChartAsPNG(image, chart, 750, 200);
        } catch (Exception e) {
            Logger.ERROR("Error generating graph for " + templateName + ", e: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
}

From source file:com.charts.FiveDayChart.java

public FiveDayChart(YStockQuote currentStock) {
    TimeSeries series = new TimeSeries(currentStock.get_name());
    ArrayList<String> fiveDayData = currentStock.get_five_day_data();
    int length = fiveDayData.size();
    for (int i = 22; i < length; i += 5) {
        String[] data = fiveDayData.get(i).split(",");
        Date time = new Date((long) Integer.parseInt(data[0]) * 1000);
        DateFormat df = new SimpleDateFormat("MM-dd-yyyy-h-m");
        series.addOrUpdate(new Minute(time), Double.parseDouble(data[1]));
    }/*from  ww w.  j av a 2 s.  c om*/
    String[] data = fiveDayData.get(length - 1).split(",");
    Date time = new Date((long) Integer.parseInt(data[0]) * 1000);
    DateFormat df = new SimpleDateFormat("MM-dd-yyyy-h-m");
    series.addOrUpdate(new Minute(time), Double.parseDouble(data[1]));

    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);
    JFreeChart chart = ChartFactory.createTimeSeriesChart(
            currentStock.get_name() + "(" + currentStock.get_symbol() + ")" + " Five Day", "Date", "Price",
            dataset, true, true, false);
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);
    ValueAxis yAxis = (ValueAxis) plot.getRangeAxis();

    DateAxis xAxis = (DateAxis) plot.getDomainAxis();
    Date now = new Date();
    SegmentedTimeline segmentedTimeline = SegmentedTimeline.newFifteenMinuteTimeline();
    segmentedTimeline.addBaseTimelineExclusions(segmentedTimeline.getStartTime(), now.getTime());
    Calendar[][] holidays = DayRange.getHolidayDates();
    for (int i = 0; i < holidays[0].length; i++) {
        Calendar day = Calendar.getInstance();
        day.set(Calendar.YEAR, holidays[0][i].get(Calendar.YEAR));
        day.set(Calendar.MONTH, holidays[0][i].get(Calendar.MONTH));
        day.set(Calendar.DAY_OF_MONTH, holidays[0][i].get(Calendar.DAY_OF_MONTH));
        day.set(Calendar.HOUR_OF_DAY, 9);
        segmentedTimeline.addException(day.getTimeInMillis(), day.getTimeInMillis() + 21600000);
    }
    xAxis.setTimeline(segmentedTimeline);
    xAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
    //xAxis.setVerticalTickLabels(true);
    xAxis.setDateFormatOverride(new SimpleDateFormat("MM-dd"));
    xAxis.setAutoTickUnitSelection(false);
    xAxis.setAutoRange(false);

    StandardXYItemRenderer renderer1 = new StandardXYItemRenderer();
    renderer1.setSeriesPaint(0, Color.BLUE);
    TimeSeries movingAverage5 = MovingAverage.createMovingAverage(series, "MA(5)", 30, 0);
    Double currMA5 = (Double) movingAverage5.getDataItem(movingAverage5.getItemCount() - 1).getValue();
    currMA5 = Math.round(currMA5 * 100.0) / 100.0;
    movingAverage5.setKey("MA(5): " + currMA5);
    TimeSeriesCollection collection = new TimeSeriesCollection();
    collection.addSeries(movingAverage5);
    plot.setDataset(1, collection);
    plot.setRenderer(1, renderer1);

    plot.setBackgroundPaint(Color.WHITE);

    chartPanel = new ChartPanel(chart);
    chart.setBackgroundPaint(chartPanel.getBackground());
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    chartPanel.setVisible(true);
    chartPanel.revalidate();
    chartPanel.repaint();
}

From source file:org.tolven.graph.GraphMenuEventHandler.java

private XYDataset createDataset() throws Exception {
    MenuPath elementPath = new MenuPath(getElement());
    MenuStructure dataMS = getAction().getParent();
    MenuPath mdPath = new MenuPath(dataMS.getPath(), elementPath);
    MenuQueryControl ctrl = new MenuQueryControl();
    ctrl.setLimit(5000); // TODO: This is a hard coded hard query limit that should be in a property or something
    ctrl.setMenuStructure(dataMS);/*  www  .  j  a  va2s .  co m*/
    ctrl.setAccountUser(getAccountUser());
    ctrl.setNow(getTolvenNow());
    ctrl.setOffset(0);
    ctrl.setOriginalTargetPath(mdPath);
    ctrl.setRequestedPath(mdPath);
    List<MenuData> menuData = getMenuBean().findMenuData(ctrl);
    Properties menuEventHandlerData = getAction().getMenuEventHandlerDataMap();
    String timeColumn = menuEventHandlerData.getProperty("timeColumn");
    String valueColumn = menuEventHandlerData.getProperty("valueColumn");
    String unitsColumn = menuEventHandlerData.getProperty("unitsColumn");
    String datasetColumn = menuEventHandlerData.getProperty("datasetColumn");
    String[] datasetUnitsArray = getRequest().getParameter("datasetunits").split(",");
    List<String> datasetUnits = new ArrayList<String>();
    for (String string : datasetUnitsArray) {
        datasetUnits.add(string);
    }
    Map<String, String[]> datasetUnitMap = createDatasetUnitsMap();
    Map<String, TimeSeries> timeSeriesMap = new HashMap<String, TimeSeries>();
    for (String[] datasetUnitArray : datasetUnitMap.values()) {
        String dataset = datasetUnitArray[0];
        String unit = datasetUnitArray[1];
        String datasetUnit = dataset + unit;
        if (datasetUnits.contains(datasetUnit)) {
            timeSeriesMap.put(datasetUnit, new TimeSeries(dataset + " (" + unit + ")", Hour.class));
        }
    }
    for (MenuData md : menuData) {
        String dataset = md.getStringField(datasetColumn);
        String units = md.getStringField(unitsColumn);
        String datasetUnit = dataset + units;
        TimeSeries currentTimeSeries = timeSeriesMap.get(datasetUnit);
        if (currentTimeSeries != null) {
            GregorianCalendar cal = new GregorianCalendar();
            cal.setTime(md.getDateField(timeColumn));
            Hour hour = new Hour(cal.getTime());
            currentTimeSeries.addOrUpdate(hour,
                    md.getInternalPQValueField(md.getColumn(valueColumn).getInternal()));

        }
    }
    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();
    for (TimeSeries timeSeries : timeSeriesMap.values()) {
        timeSeriesCollection.addSeries(timeSeries);
    }
    timeSeriesCollection.setDomainIsPointsInTime(true);
    TolvenLogger.info("Done preparing Dataset", GraphMenuEventHandler.class);
    return timeSeriesCollection;
}

From source file:gui.grafica.estadisticas.PanelGrafica.java

/**
 * Creates a dataset, Crea el conjunto de datos a mostrar.
 *
 * @return The dataset.//  ww w. j  a va  2s. c om
 */
private XYDataset createDataset() {
    List series = dataset.getSeries();
    TimeSeries s1 = null;
    if (series == null || series.isEmpty()) {
        s1 = new TimeSeries("");
    } else {
        s1 = (TimeSeries) series.get(0);
    }
    Date fechaInicial;
    Minute hora;
    if (fechaInicio != null) {
        fechaInicial = fechaInicio;
        for (Double valor : listaVelocidad) {
            hora = new Minute(fechaInicial);
            s1.addOrUpdate(hora, valor);
            fechaInicial = UtilFechas.sumarSegundos(fechaInicial, 30);
        }
    }

    dataset.removeAllSeries();
    dataset.addSeries(s1);
    //        dataset.addSeries(s2);

    return dataset;

}

From source file:org.miloss.fgsms.services.rs.impl.reports.os.FreeDiskSpace.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 {// w w w .ja va2s.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 Send Rate</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>");
            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();
                average = 0;
                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>");
            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();
                average = 0;
                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 ts2 = tsc.Get(url + " " + rs.getString("driveidentifier"), Millisecond.class);
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(4));
                    Millisecond m = new Millisecond(gcal.getTime());
                    ts2.addOrUpdate(m, rs.getLong("freespace"));
                }
            } 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));
            }

        }

        data.append("</table>");
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "MBytes", 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.activequant.util.charting.Chart.java

/**
 * method to add a dot chart./* w ww .j ava  2s .  c o  m*/
 * @param title
 * @param dateAndValues
 */
public void addDotSeriesChart(String title, List<Tuple<TimeStamp, Double>> dateAndValues) {

    if (chart != null) {
        //
        final TimeSeries ts = new TimeSeries(title, Millisecond.class);
        for (Tuple<TimeStamp, Double> tuple : dateAndValues) {
            //
            TimeSeriesDataItem item = new TimeSeriesDataItem(new Millisecond(tuple.getObject1().getDate()),
                    tuple.getObject2());
            ts.addOrUpdate(item.getPeriod(), item.getValue());
        }

        datasets.add(ts);
        final TimeSeriesCollection dataset = new TimeSeriesCollection(ts);

        final XYPlot plot1 = chart.getXYPlot();

        final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setShapesVisible(true);
        renderer.setLinesVisible(false);
        plot1.setDataset(datasets.size(), dataset);
        plot1.setRenderer(datasets.size(), renderer);
    }
}