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:org.jfree.data.time.TimeSeriesTest.java

/**
 * Test that the addOrUpdate() method won't allow multiple time period
 * classes./*w w  w .  ja v  a  2 s.c om*/
 */
@Test
public void testAddOrUpdate3() {
    TimeSeries s1 = new TimeSeries("S1");
    s1.addOrUpdate(new Year(2010), 1.1);
    assertEquals(Year.class, s1.getTimePeriodClass());

    boolean pass = false;
    try {
        s1.addOrUpdate(new Month(1, 2009), 0.0);
    } catch (SeriesException e) {
        pass = true;
    }
    assertTrue(pass);
}

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

private TimeSeries LinFit(TimeSeries ts) {
    TimeSeries ret = new TimeSeries("lin fit", Millisecond.class);
    SimpleTimeZone utctz = new SimpleTimeZone(0, "UTC");
    int n = ts.getItemCount();
    double[] x = new double[n];
    double[] y = new double[n];
    TimeSeriesDataItem it;//www .  j av a 2s .  c  o  m
    for (int i = 0; i < n; i++) {
        it = ts.getDataItem(i);
        x[i] = it.getPeriod().getFirstMillisecond() + 0.;
        y[i] = it.getValue().doubleValue();
    }
    LinearRegression lr = new LinearRegression(x, y);
    double b = lr.getIntercept();
    double m = lr.getSlope();
    double fit, t;
    for (int i = 0; i < n; i++) {
        it = ts.getDataItem(i);
        t = it.getPeriod().getFirstMillisecond() + 0.;
        fit = m * t + b;

        ret.addOrUpdate(it.getPeriod(), fit);
    }

    return ret;
}

From source file:org.jfree.data.time.TimeSeriesTest.java

/**
 * Test the add branch of the addOrUpdate() method.
 *///  w  w  w .  j ava  2  s. c o  m
@Test
public void testAddOrUpdate2() {
    TimeSeries s1 = new TimeSeries("S1");
    s1.setMaximumItemCount(2);
    s1.addOrUpdate(new Year(2010), 1.1);
    s1.addOrUpdate(new Year(2011), 2.2);
    s1.addOrUpdate(new Year(2012), 3.3);
    assertEquals(2, s1.getItemCount());
    assertEquals(2.2, s1.getMinY(), EPSILON);
    assertEquals(3.3, s1.getMaxY(), EPSILON);
}

From source file:org.jfree.data.time.TimeSeriesTest.java

/**
 * Some more checks for the addOrUpdate() method.
 *///from  w w  w . ja va  2s .c o  m
@Test
public void testAddOrUpdate4() {
    TimeSeries ts = new TimeSeries("S");
    TimeSeriesDataItem overwritten = ts.addOrUpdate(new Year(2009), 20.09);
    assertNull(overwritten);
    overwritten = ts.addOrUpdate(new Year(2009), 1.0);
    assertEquals(new Double(20.09), overwritten.getValue());
    assertEquals(new Double(1.0), ts.getValue(new Year(2009)));

    // changing the overwritten record shouldn't affect the series
    overwritten.setValue(null);
    assertEquals(new Double(1.0), ts.getValue(new Year(2009)));

    TimeSeriesDataItem item = new TimeSeriesDataItem(new Year(2010), 20.10);
    overwritten = ts.addOrUpdate(item);
    assertNull(overwritten);
    assertEquals(new Double(20.10), ts.getValue(new Year(2010)));
    // changing the item that was added should not change the series
    item.setValue(null);
    assertEquals(new Double(20.10), ts.getValue(new Year(2010)));
}

From source file:org.jfree.data.time.TimeSeriesTest.java

/**
 * Some checks for the addOrUpdate() method.
 *//*from  w w  w.j a  v a 2s  . com*/
@Test
public void testAddOrUpdate() {
    TimeSeries s1 = new TimeSeries("S1", Year.class);
    s1.setMaximumItemCount(2);
    s1.addOrUpdate(new Year(2000), 100.0);
    assertEquals(1, s1.getItemCount());
    s1.addOrUpdate(new Year(2001), 101.0);
    assertEquals(2, s1.getItemCount());
    s1.addOrUpdate(new Year(2001), 102.0);
    assertEquals(2, s1.getItemCount());
    s1.addOrUpdate(new Year(2002), 103.0);
    assertEquals(2, s1.getItemCount());
}

From source file:org.jfree.data.time.TimeSeriesTest.java

/**
 * Another test of the clone() method.//from   w  ww  . j a  v  a2 s .c o  m
 */
@Test
public void testClone2() throws CloneNotSupportedException {
    TimeSeries s1 = new TimeSeries("S1", Year.class);
    s1.add(new Year(2007), 100.0);
    s1.add(new Year(2008), null);
    s1.add(new Year(2009), 200.0);
    TimeSeries s2 = (TimeSeries) s1.clone();
    assertTrue(s1.equals(s2));

    // check independence
    s2.addOrUpdate(new Year(2009), 300.0);
    assertFalse(s1.equals(s2));
    s1.addOrUpdate(new Year(2009), 300.0);
    assertTrue(s1.equals(s2));
}

From source file:org.miloss.fgsms.services.rs.impl.reports.broker.QueueDepth.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 {/*  ww  w .  ja  va 2  s  . c  om*/
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        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>Channel</th><th>Depth</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(getPolicyDisplayName(urls.get(i)));
            double average = 0;
            data.append("<tr><td>").append(url).append("</td>");
            try {
                cmd = con.prepareStatement(
                        "select avg(queuedepth), 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.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("<td>").append(average + "").append("</td>");

            TimeSeries ts = new TimeSeries(url, Millisecond.class);
            try {
                //ok now get the raw data....
                cmd = con.prepareStatement(
                        "select utcdatetime,queuedepth, 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();

                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());
                    //TimeSeriesDataItem t = new TimeSeriesDataItem(m, rs.getLong(2));
                    //ts.add(t);
                    ts.addOrUpdate(m, rs.getLong(2));

                }

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", 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.jtotus.gui.graph.GraphPrinter.java

public void drawSeries(GraphPacket packet) {
    TimeSeries series = null;

    if (seriesMap.containsKey(packet.seriesTitle)) { //Series Exists
        series = seriesMap.get(packet.seriesTitle);
    } else {/*from w ww.  j av  a2s .c  om*/
        series = this.createTimeSeries(packet);
        //FIXME: is it prefereable to add series after points are added ?
        TimeSeriesCollection collection = (TimeSeriesCollection) this.fetchPlot(packet.plotName).getDataset();
        collection.addSeries(series);
    }

    Iterator<StockUnit> iter = packet.results.iterator();
    while (iter.hasNext()) {
        //update if already existing series
        StockUnit unit = iter.next();
        if (unit.annotation != null) {
            final XYTextAnnotation annotation = new XYTextAnnotation(unit.annotation,
                    this.localDateToDay(unit.date).getMiddleMillisecond(), unit.value);
            annotation.setFont(new Font("SansSerif", Font.PLAIN, 9));
            this.fetchPlot(packet.plotName).addAnnotation(annotation);
        }

        series.addOrUpdate(this.localDateToDay(unit.date), unit.value);
    }
}

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

/**
 * Generate a JFreeChart TimeSeries object from a ChanDataBuffer
 * Note:  the time axis is in UTC.  For GPS or delta T use XY series.
 * @param dbuf - ldvw data buffer//from  w  w w  .  ja  va  2s  .c om
 * @param legend - plot legend for this series
 * @return JFreeChart time series for adding to a plot
 */
public TimeSeries getTimeSeries(ChanDataBuffer dbuf, String legend, int sum) throws LdvTableException {
    sum = sum < 1 ? 1 : sum;
    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 += sum) {
        float td = 0.f;
        int nsum = 0;
        for (int j = 0; j < sum && i + j < dbuf.getDataLength(); j++) {
            td += data[i + j];
            nsum++;
        }
        td /= nsum;

        long curMs = Math.round(msPerSample * i + startMs);
        Date t = new Date(curMs);
        ts.addOrUpdate(new Millisecond(t, utctz), td);
        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), td);
        }
    }
    return ts;
}

From source file:view.PrograssCharts.java

/**
 * Creates new form PrograssCharts//  w  ww .  ja  v a 2s.c o m
 */
public PrograssCharts(java.awt.Frame parent, boolean modal) {
    super(parent, modal);
    try {
        initComponents();
        setSize(1400, 800);
        jPanel1.setVisible(false);
        jPanel2.setVisible(false);

        new Thread(new Runnable() {

            @Override
            public void run() {
                loading1();
                loading2();
                run();

            }
        }).start();

        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        DefaultCategoryDataset dataset1 = new DefaultCategoryDataset();
        dataset.setValue(QuestionLab.cat1, "gfdg", "Collectns");
        dataset.setValue(QuestionLab.cat2, "gfdg", "Data");
        dataset.setValue(QuestionLab.cat3, "gfdg", "Dev");
        dataset.setValue(QuestionLab.cat4, "gfdg", "Excep");
        dataset.setValue(QuestionLab.cat5, "gfdg", "File");
        dataset.setValue(QuestionLab.cat6, "gfdg", "FlowCon");
        dataset.setValue(QuestionLab.cat7, "gfdg", "Format");
        dataset.setValue(QuestionLab.cat8, "gfdg", "GC");
        dataset.setValue(QuestionLab.cat9, "gfdg", "IC");
        dataset.setValue(QuestionLab.cat10, "gfdg", "VarArgs");
        dataset.setValue(QuestionLab.cat11, "gfdg", "Fundamt");
        dataset.setValue(QuestionLab.cat12, "gfdg", "Modif");
        dataset.setValue(QuestionLab.cat13, "gfdg", "OOP");
        dataset.setValue(QuestionLab.cat14, "gfdg", "Vari");
        dataset.setValue(QuestionLab.cat15, "gfdg", "String");
        dataset.setValue(QuestionLab.cat16, "gfdg", "Threads");
        dataset.setValue(QuestionLab.cat17, "gfdg", "WC");
        JFreeChart freeChart = ChartFactory.createBarChart("Exam Prograss by Subjects", "Subject", "Marks",
                dataset, PlotOrientation.VERTICAL, false, true, false);
        //JFreeChart freeChart1 = ChartFactory.createBarChart("Income", " Name", "Incomesss", dataset1, PlotOrientation.VERTICAL, false, true, false);
        TimeSeries pop = new TimeSeries("Population", Day.class);

        //JFreeChart chart=ChartFactory.create
        CategoryPlot plot = freeChart.getCategoryPlot();
        plot.setRangeGridlinePaint(Color.BLUE);
        ChartFrame frame = new ChartFrame("Exam Prograss", freeChart);

        //        frame.setVisible(true);
        //        frame.setSize(550, 450);
        // JPanel jPanel1 = new JPanel();
        jPanel1.setLayout(new java.awt.BorderLayout());

        ChartPanel CP = new ChartPanel(freeChart);
        CP.setPreferredSize(new Dimension(785, 440));
        CP.setMouseWheelEnabled(true);

        jPanel1.add(CP);
        jPanel1.revalidate();

        ArrayList<Exam> setChartValue = ServerConnector.getServerConnector().getExamController()
                .getPreviousMarks(PracticeExamLogIn.studentNic);
        for (Exam exam : setChartValue) {
            //dataset1.setValue(exam.getMarks(), "gfdg9", exam.getDate());
            pop.addOrUpdate(new Day(exam.getDate()), exam.getMarks());
            System.out.println("mar" + exam.getMarks());
            System.out.println("date" + exam.getDate());
        }
        TimeSeriesCollection myDataset = new TimeSeriesCollection();
        myDataset.addSeries(pop);
        JFreeChart myChart = ChartFactory.createTimeSeriesChart("Population Your Marks", "Date", "Population",
                myDataset, true, true, false);
        //try {
        //ChartUtilities.saveChartAsJPEG(new File("C:\\chart.jpg"), chart, 500, 300);
        //} catch (IOException e) {
        //System.err.println("Problem occurred creating chart.");
        //}

        //JFreeChart chart=ChartFactory.create
        CategoryPlot plot1 = freeChart.getCategoryPlot();
        plot1.setRangeGridlinePaint(Color.BLUE);
        //ChartFrame frame1 = new ChartFrame("Exam Prograss", freeChart1);

        //        frame.setVisible(true);
        //        frame.setSize(550, 450);
        // JPanel jPanel1 = new JPanel();
        jPanel2.setLayout(new java.awt.BorderLayout());

        ChartPanel CP1 = new ChartPanel(myChart);
        CP1.setPreferredSize(new Dimension(785, 440));
        CP1.setMouseWheelEnabled(true);

        jPanel2.add(CP1);
        jPanel2.revalidate();

    } catch (RemoteException | ClassNotFoundException | SQLException | NotBoundException
            | MalformedURLException ex) {
        Logger.getLogger(PrograssCharts.class.getName()).log(Level.SEVERE, null, ex);
    }

}