Example usage for org.jfree.data.time TimeSeriesCollection addSeries

List of usage examples for org.jfree.data.time TimeSeriesCollection addSeries

Introduction

In this page you can find the example usage for org.jfree.data.time TimeSeriesCollection addSeries.

Prototype

public void addSeries(TimeSeries series) 

Source Link

Document

Adds a series to the collection and sends a DatasetChangeEvent to all registered listeners.

Usage

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 {//from w  w w  . ja v a2s .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.infoglue.deliver.util.charts.TimeSeriesDiagram.java

/**
 * Creates a dataset, consisting of two series of monthly data.
 *
 * @return the dataset.//from  w  w  w  .j  a v a  2s. co m
 */
private XYDataset createDataset() throws Exception {
    TimeSeriesCollection timeSeriesDataset = new TimeSeriesCollection();

    Document document = new DOMBuilder().getDocument(this.xmlData);
    this.writeDebug(document);

    Element headerElement = (Element) document.selectSingleNode("//chartHeader");
    this.header = headerElement.getText();
    Element axisYHeaderElement = (Element) document.selectSingleNode("//axisYHeader");
    this.axisYHeader = axisYHeaderElement.getText();
    Element axisXHeaderElement = (Element) document.selectSingleNode("//axisXHeader");
    this.axisXHeader = axisXHeaderElement.getText();
    Element timeGranularityElement = (Element) document.selectSingleNode("//timeGranularity");
    this.timeGranulariry = timeGranularityElement.getText();
    Element dateFormatElement = (Element) document.selectSingleNode("//dateFormat");
    this.dateFormat = dateFormatElement.getText();

    List series = document.selectNodes("//Series");

    Iterator seriesIterator = series.iterator();
    while (seriesIterator.hasNext()) {
        Element serieElement = (Element) seriesIterator.next();
        String serieName = serieElement.attributeValue("name");

        TimeSeries s1 = null;
        if (this.timeGranulariry.equalsIgnoreCase("Month"))
            s1 = new TimeSeries(serieName, Month.class);
        else if (this.timeGranulariry.equalsIgnoreCase("Week"))
            s1 = new TimeSeries(serieName, Week.class);

        List items = serieElement.selectNodes("Item");
        Iterator itemsIterator = items.iterator();
        while (itemsIterator.hasNext()) {
            Element itemElement = (Element) itemsIterator.next();
            Element yearElement = (Element) itemElement.selectSingleNode("yearId");
            Element timeElement = (Element) itemElement.selectSingleNode("timeId");
            Element valueElement = (Element) itemElement.selectSingleNode("value");
            String year = yearElement.getText();
            String time = timeElement.getText();
            String value = valueElement.getText();

            if (this.timeGranulariry.equalsIgnoreCase("Month"))
                s1.add(new Month(new Integer(time).intValue(), new Integer(year).intValue()), new Float(value));
            else if (this.timeGranulariry.equalsIgnoreCase("Week"))
                s1.add(new Week(new Integer(time).intValue(), new Integer(year).intValue()), new Float(value));
        }

        timeSeriesDataset.addSeries(s1);
        //timeSeriesDataset.addSeries(s2);

        timeSeriesDataset.setDomainIsPointsInTime(true);

    }

    return timeSeriesDataset;

}

From source file:net.brewspberry.front.JFreeGraphServlet.java

/**
 * This method creates a TimeSeriesCollection from raw String values
 * //from w  w  w.  j av  a 2s  .  c om
 * @param data
 * @return
 * @throws NumberFormatException
 * @throws ParseException
 */
public TimeSeriesCollection createDataset(List<String[]> data, boolean timeLimited, boolean fromDB)
        throws NumberFormatException, ParseException {

    TimeSeriesCollection dataSet = new TimeSeriesCollection();

    int compteur = data.size();
    List<TimeSeries> serie = new ArrayList<TimeSeries>();

    logger.fine("Compteur " + compteur + " length :" + data.get(0).length);

    // On cree autant de series qu'il y a de sondes
    for (int k = 0; k <= (data.get(0).length - 5) / 2; k++) {
        serie.add(new TimeSeries("PROBE" + k));
        logger.fine("Added timeSeries PROBE" + k);
    }

    /*
     * For each line like [2015-07-21 12:34:56, 12345, 54321]
     */
    for (int i = 0; i < compteur; i++) {

        /*
         * for each temperature value
         */
        int increment;
        if (fromDB) {
            increment = 1;
        } else {
            increment = 2;
        }
        for (int j = 5; j < data.get(i).length; j += increment) {

            Date dataDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(data.get(i)[0]);

            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(dataDate);
            Calendar cal2 = Calendar.getInstance();
            cal2.add(Calendar.MINUTE, graphHorizontalTimeLengthInMinutes);
            logger.fine("Array size : " + data.get(i).length + " & compteur=" + j);

            if (timeLimited) {
                if (cal1.after(cal2)) {
                    if (data.get(i)[j] != null) {
                        // Adds [time, temperature] to the corresponding (i)
                        // serie

                        logger.fine("Adding temperature" + data.get(i)[j] + " to serie nbr" + (j - 5) / 2);
                        serie.get((j - 5) / 2).addOrUpdate(new Second(dataDate),
                                Double.parseDouble(data.get(i)[j]));
                    }
                }
            } else {
                if (data.get(i)[j] != null) {

                    serie.get((j - 5)).addOrUpdate(new Second(dataDate), Double.parseDouble(data.get(i)[j]));
                }
            }
        }
    }

    // Adds each serie to the dataset
    for (int l = 0; l < serie.size(); l++) {
        logger.fine("serie size : " + serie.get(l).getItemCount());

        dataSet.addSeries(serie.get(l));
    }

    logger.fine("dataSet size : " + dataSet.getSeriesCount());

    return dataSet;

}

From source file:beproject.MainGUI.java

void getTimeLineData(TimeSeriesCollection t) throws SQLException {
    Statement stmt = Initializer.inConn2.createStatement();
    ResultSet rs1 = stmt.executeQuery("select max(ts) from tweets");
    rs1.first();/*from   w w w .j ava 2s . c o m*/
    Timestamp ts1 = rs1.getTimestamp(1);
    for (String tmp : ScheduledMoviesList.getMovieNames()) {
        TimeSeries t1 = new TimeSeries(tmp, Hour.class);
        Timestamp ts = (Timestamp) ts1.clone();
        for (int i = 0; i < 6; i++) {
            Date d1 = new java.util.Date(ts.getTime());
            Date d2 = new java.util.Date(ts.getTime() + 3600000);
            ResultSet rs = stmt
                    .executeQuery("select count(*) from tweets where moviename='" + tmp + "' and ts between '"
                            + Regression.sdf.format(d1) + "' and '" + Regression.sdf.format(d2) + "'");
            rs.first();
            //if(!rs.first())
            //  t1.addOrUpdate(new Hour(d1), 0);
            //else
            t1.addOrUpdate(new Hour(d1), rs.getInt(1));
            ts.setTime(ts.getTime() - 3600000);
        }
        t.addSeries(t1);
    }

}

From source file:se.technipelago.weather.chart.Generator.java

private XYDataset createHistoryDataset(final Date begin, final Date end, final String column,
        final String label) throws SQLException {
    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    PreparedStatement stmt = null;
    ResultSet result = null;//  ww  w  . ja  v a  2 s . co m
    long spanDays = (end.getTime() - begin.getTime()) / 1000 / 60 / 60 / 24;
    try {
        final java.sql.Timestamp sqlBegin = new java.sql.Timestamp(begin.getTime());
        final java.sql.Timestamp sqlEnd = new java.sql.Timestamp(end.getTime());
        if (spanDays < 100) {
            stmt = conn.prepareStatement("SELECT ts, " + column + " FROM archive WHERE " + column
                    + " IS NOT NULL AND ts BETWEEN ? AND ? ORDER BY ts");
        } else if (spanDays < 1000) {
            stmt = conn.prepareStatement("SELECT date_format(ts, '%Y-%m-%d %H:00:00') AS day, AVG(" + column
                    + ") AS value FROM archive WHERE " + column
                    + " IS NOT NULL AND ts BETWEEN ? AND ? GROUP BY 1");
        } else {
            stmt = conn.prepareStatement("SELECT date_format(ts, '%Y-%m-%d') AS day, AVG(" + column
                    + ") AS value FROM archive WHERE " + column
                    + " IS NOT NULL AND ts BETWEEN ? AND ? GROUP BY 1");
        }
        stmt.setTimestamp(1, sqlBegin);
        stmt.setTimestamp(2, sqlEnd);
        result = stmt.executeQuery();

        final TimeSeries s1 = new TimeSeries(label, FixedMillisecond.class);
        while (result.next()) {
            final java.sql.Timestamp ts = result.getTimestamp(1);
            final long timestamp = ts.getTime();
            s1.add(new FixedMillisecond(timestamp), result.getFloat(2));
        }
        dataset.addSeries(s1);
    } finally {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                log.log(Level.SEVERE, "Failed to close ResultSet", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ex) {
                log.log(Level.WARNING, "Failed to close select statement", ex);
            }
        }
    }

    return dataset;
}

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 {/*  w  w w  .  jav a  2s.c om*/
        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: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 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 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:de.fau.amos.ChartRenderer.java

/**
 * //w w w .  jav  a 2  s .c  o m
 * Creates TimeSeriesCollection that provides the basis for a Chart. Is used for forecast.
 * 
 * @param sYear Selected year.
 * @param plantId Selected plant.
 * @param method Is not used.
 * @param units Is not used.
 * @return Returns TimeSeriesCollection that provides the basis for a Chart.
 */
private TimeSeriesCollection createForecastCollection(String sYear, String plantId, String method,
        String units) {

    int year = 0;
    try {
        year = Integer.parseInt(sYear);
    } catch (NumberFormatException e) {
        return new TimeSeriesCollection();
    }

    TimeSeriesCollection collection = new TimeSeriesCollection();

    /*
     * get planned tnf
     */
    TimeSeries planned = new TimeSeries("Planned");

    double lastYearKwhPerTnf = 0;
    ResultSet rs = SQL.queryToResultSet(
            "select round((select sum(value)from measures where date_trunc('year',measure_time)='" + (year - 1)
                    + "-1-1')/(select sum(amount)from productiondata "
                    + "inner join controlpoints on productiondata.controlpoint_id=controlpoints.controlpoints_id "
                    + "where date_trunc('year',measure_time)='" + (year - 1) + "-1-1' AND plant_id='" + plantId
                    + "'),4);");

    if (rs != null) {
        try {
            if (rs.next()) {
                lastYearKwhPerTnf = rs.getDouble(1);
            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    String months = "";
    for (int i = 1; i <= 12; i++) {
        months += "sum(m_" + i + ")";
        if (i != 12) {
            months += ", ";
        }
    }

    rs = SQL.queryToResultSet(

            "select " + months + " from planning_values where planning_year='" + year + "' AND plant_id='"
                    + plantId + "';");

    if (rs != null) {
        try {
            while (rs.next()) {
                for (int i = 1; i <= 12; i++) {
                    planned.add(new Month((i), year),
                            rs.getDouble(i) / (lastYearKwhPerTnf != 0 ? lastYearKwhPerTnf : 1));
                }

            }
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    collection.addSeries(planned);

    TimeSeries is = new TimeSeries("Is");
    int passedMonths = 0;
    double lastVal = 0;
    rs = SQL.queryToResultSet(

            "select * from (select round((select sum(am) from(select sum(amount)as am,date_trunc('month',measure_time)as zeit "
                    + "from productiondata inner join controlpoints on productiondata.controlpoint_id=controlpoints.controlpoints_id "
                    + "where productiondata.measure_time >= '" + year
                    + "-01-01 00:00:00' AND productiondata.measure_time < '" + (year + 1) + "-01-01 00:00:00' "
                    + "AND reference_point='t' AND plant_id='" + plantId
                    + "' group by measure_time)as wat where zeit=gruppenZeit group by zeit order by zeit),4), "
                    + "gruppenZeit from(select sum(wert) as gruppenWert,control_point_name, zeit1 as gruppenZeit from("
                    + "select sum(value)as wert,control_point_name,date_trunc('month',measure_time)as zeit1 from measures inner join controlpoints "
                    + "on measures.controlpoint_id=controlpoints.controlpoints_id where measure_time >= '"
                    + year + "-01-01 00:00:00' AND measure_time < '" + (year + 1)
                    + "-01-01 00:00:00' AND plant_id='" + plantId
                    + "' group by measure_time,control_point_name)as data group by zeit1,control_point_name) "
                    + "as groupedByTime group by gruppenZeit)as result order by gruppenZeit;");
    if (rs != null) {
        try {
            while (rs.next()) {
                passedMonths++;
                lastVal = rs.getDouble(1) / (lastYearKwhPerTnf != 0 ? lastYearKwhPerTnf : 1);
                is.add(new Month((passedMonths), year), lastVal);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    collection.addSeries(is);

    TimeSeries forecast = new TimeSeries("Forecast");

    if (passedMonths != 0) {

        forecast.add(new Month(passedMonths, year), lastVal);
    }
    passedMonths++;

    double factor = calculateDifferenz(planned, is);

    for (int i = passedMonths; i <= 12; i++) {
        forecast.add(new Month((i), year), planned.getValue(i - 1).doubleValue() * factor);
    }
    collection.addSeries(forecast);
    return collection;
}

From source file:org.miloss.fgsms.services.rs.impl.reports.broker.ConsumersByQueueOrTopic.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 .  j av  a 2  s  .  c o m*/
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(
                "This represents the average number of consumers for all channels (topics/queues/etc) on a specific message broker.<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Channel</th><th>Average Consumer Count</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.STATISTICAL)) {
                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)));
            try {
                data.append("<tr><td>").append(Utility.encodeHTML(urls.get(i))).append("</td>");
                double average = 0;
                try {
                    cmd = con.prepareStatement(
                            "select avg(activeconsumercount), host, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ? group by canonicalname, host;");
                    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 {
                    //ok now get the raw data....
                    cmd = con.prepareStatement(
                            "select utcdatetime,activeconsumercount, canonicalname from brokerhistory where host=? 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();
                    TimeSeries ts = new TimeSeries(urls.get(i), Millisecond.class);
                    while (rs.next()) {

                        //set.addValue(rs.getLong(1), urls.get(i), rs.getString("canonicalname"));
                        GregorianCalendar gcal = new GregorianCalendar();
                        gcal.setTimeInMillis(rs.getLong(1));
                        Millisecond m = new Millisecond(gcal.getTime());

                        ts.addOrUpdate(m, rs.getLong(2));

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

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

        }
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Count", 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:lucee.runtime.tag.Chart.java

private XYDataset createTimeSeriesCollection() {
    TimeZone tz = ThreadLocalPageContext.getTimeZone();
    final TimeSeriesCollection coll = new TimeSeriesCollection(tz);

    //final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    Iterator<ChartSeriesBean> it = _series.iterator();
    //int seriesCount=_series.size();
    Iterator itt;/* ww  w  . j  a  v  a 2 s  .c  o  m*/
    List datas;
    ChartSeriesBean csb;
    ChartDataBean cdb;
    int count = 0;
    smallest = Double.MAX_VALUE;
    biggest = Double.MIN_VALUE;
    String label;
    boolean hasLabels = false;
    while (it.hasNext()) {
        count++;
        csb = it.next();
        label = csb.getSeriesLabel();
        if (StringUtil.isEmpty(label))
            label = "" + count;
        else
            hasLabels = true;
        datas = csb.getDatas();
        if (sortxaxis)
            Collections.sort(datas);
        itt = datas.iterator();
        TimeSeries ts = new TimeSeries(label, Second.class);
        while (itt.hasNext()) {
            cdb = (ChartDataBean) itt.next();
            if (smallest > cdb.getValue())
                smallest = cdb.getValue();
            if (biggest < cdb.getValue())
                biggest = cdb.getValue();
            //if(seriesCount>1)
            ts.addOrUpdate(new Second(
                    DateCaster.toDateSimple(cdb.getItem(), DateCaster.CONVERTING_TYPE_NONE, false, tz, null)),
                    cdb.getValue());

            //else dataset.addValue(cdb.getValue(), cdb.getItem(),"");

        }
        coll.addSeries(ts);
    }
    if (!hasLabels)
        showlegend = false;
    return coll;
}