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

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

Introduction

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

Prototype

public void add(RegularTimePeriod period, Number value) 

Source Link

Document

Adds a new data item to the series and sends a org.jfree.data.general.SeriesChangeEvent to all registered listeners.

Usage

From source file:ca.myewb.frame.servlet.GraphServlet.java

private JFreeChart getLastLogin(Session s) throws CloneNotSupportedException {

    Integer numCurrentLogins = ((Long) s
            .createQuery("select count(*) from UserModel "
                    + "where currentLogin is not null and currentLogin >= :date")
            .setDate("date", getStartDate()).uniqueResult()).intValue();

    List currentStats = s//from   www . j a  v a  2s . c om
            .createSQLQuery("SELECT DATE(currentLogin) as date, count( * ) as lastLogins "
                    + "FROM users where currentLogin is not null  and currentLogin >= :date "
                    + "GROUP BY DATE( currentLogin )")
            .addScalar("date", Hibernate.DATE).addScalar("lastLogins", Hibernate.INTEGER)
            .setDate("date", getStartDate()).list();

    TimeSeriesCollection theData = new TimeSeriesCollection();
    TimeSeriesCollection theData2 = new TimeSeriesCollection();

    TimeSeries current = new TimeSeries("Num Latest Sign-ins", Day.class);
    theData.addSeries(current);
    TimeSeries current2 = new TimeSeries("Signed-in Users Since", Day.class);
    theData2.addSeries(current2);

    for (Object ds : currentStats) {
        Date date = (Date) ((Object[]) ds)[0];
        Day day = new Day(date);
        Integer integer = (Integer) ((Object[]) ds)[1];
        current.add(day, integer);
        numCurrentLogins -= integer.intValue();
        current2.add(day, numCurrentLogins);

    }

    JFreeChart chart = ChartFactory.createTimeSeriesChart("Sign-in Recency", "Day", "Sign-ins", theData, true,
            true, true);

    XYPlot plot = (XYPlot) chart.getPlot();

    NumberAxis axis2 = new NumberAxis("Users");
    plot.setRangeAxis(1, axis2);
    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);
    plot.setDataset(1, theData2);
    plot.mapDatasetToRangeAxis(1, 1);

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(0);
    renderer.setSeriesStroke(0, new BasicStroke(2.0f));
    renderer.setSeriesStroke(1, new BasicStroke(2.0f));
    renderer = (XYLineAndShapeRenderer) renderer.clone();
    renderer.setSeriesStroke(0, new BasicStroke(2.0f));
    renderer.setSeriesStroke(1, new BasicStroke(2.0f));
    plot.setRenderer(1, renderer);
    return chart;
}

From source file:ca.myewb.frame.servlet.GraphServlet.java

private JFreeChart getDailyIntegratedStats(Session s) throws CloneNotSupportedException {
    JFreeChart chart;/*  ww  w  . ja va 2  s.  c o  m*/
    List<DailyStatsModel> stats = (new SafeHibList<DailyStatsModel>(
            s.createQuery("select ds from DailyStatsModel as ds where day<? and day>=? order by day desc")
                    .setDate(0, new Date()).setDate(1, GraphServlet.getStartDate()))).list();
    TimeSeriesCollection theData = new TimeSeriesCollection();
    TimeSeriesCollection theData2 = new TimeSeriesCollection();

    TimeSeries users = new TimeSeries("Total Users", Day.class);
    theData.addSeries(users);

    TimeSeries regulars = new TimeSeries("Regular Members", Day.class);
    theData2.addSeries(regulars);

    int numUsers = Helpers.getGroup("Org").getNumMembers();
    int numReg = Helpers.getGroup("Regular").getNumMembers();

    for (DailyStatsModel ds : stats) {
        Day theDay = new Day(ds.getDay());
        users.add(theDay, numUsers);
        regulars.add(theDay, numReg);
        numUsers -= (ds.getMailinglistsignups() + ds.getSignups() - ds.getDeletions());
        numReg -= (ds.getRegupgrades() - ds.getRegdowngrades());
    }

    chart = ChartFactory.createTimeSeriesChart("Membership", "Day", "Users", theData, true, true, true);

    XYPlot plot = (XYPlot) chart.getPlot();

    NumberAxis axis2 = new NumberAxis("Regular Members");
    plot.setRangeAxis(1, axis2);
    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);
    plot.setDataset(1, MovingAverage.createMovingAverage(theData2, "", 14, 0));
    plot.mapDatasetToRangeAxis(1, 1);

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(0);
    renderer.setSeriesStroke(0, new BasicStroke(2.0f));
    renderer = (XYLineAndShapeRenderer) renderer.clone();
    renderer.setSeriesStroke(0, new BasicStroke(2.0f));
    plot.setRenderer(1, renderer);
    return chart;
}

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

@Test
public void testFindValueRange2() {
    TimeZone tzone = TimeZone.getTimeZone("Europe/London");
    Calendar calendar = new GregorianCalendar(tzone, Locale.UK);
    calendar.clear();//from  ww w  .  j a  v  a 2 s. co m
    calendar.set(2014, Calendar.FEBRUARY, 23, 6, 0);
    long start = calendar.getTimeInMillis();
    calendar.clear();
    calendar.set(2014, Calendar.FEBRUARY, 24, 18, 0);
    long end = calendar.getTimeInMillis();
    Range range = new Range(start, end);

    TimeSeries ts = new TimeSeries("Time Series");
    assertNull(ts.findValueRange(range, TimePeriodAnchor.START, tzone));
    assertNull(ts.findValueRange(range, TimePeriodAnchor.MIDDLE, tzone));
    assertNull(ts.findValueRange(range, TimePeriodAnchor.END, tzone));

    ts.add(new Day(23, 2, 2014), 5.0);
    assertTrue(ts.findValueRange(range, TimePeriodAnchor.START, tzone).isNaNRange());
    assertEquals(new Range(5.0, 5.0), ts.findValueRange(range, TimePeriodAnchor.MIDDLE, tzone));
    assertEquals(new Range(5.0, 5.0), ts.findValueRange(range, TimePeriodAnchor.END, tzone));

    ts.add(new Day(24, 2, 2014), 6.0);
    assertEquals(new Range(6.0, 6.0), ts.findValueRange(range, TimePeriodAnchor.START, tzone));
    assertEquals(new Range(5.0, 6.0), ts.findValueRange(range, TimePeriodAnchor.MIDDLE, tzone));
    assertEquals(new Range(5.0, 5.0), ts.findValueRange(range, TimePeriodAnchor.END, tzone));

    ts.clear();
    ts.add(new Day(24, 2, 2014), null);
    assertTrue(ts.findValueRange(range, TimePeriodAnchor.START, tzone).isNaNRange());
    assertTrue(ts.findValueRange(range, TimePeriodAnchor.MIDDLE, tzone).isNaNRange());
    assertTrue(ts.findValueRange(range, TimePeriodAnchor.END, tzone).isNaNRange());
}

From source file:ca.myewb.frame.servlet.GraphServlet.java

private JFreeChart getDaily3Stats(Session s) {
    JFreeChart chart;/* w  w w .j a v  a 2 s.  c  o  m*/
    List<DailyStatsModel> stats = (new SafeHibList<DailyStatsModel>(
            s.createQuery("select ds from DailyStatsModel as ds where day<? and day>=? order by day desc")
                    .setDate(0, new Date()).setDate(1, GraphServlet.getStartDate()))).list();
    TimeSeriesCollection theData = new TimeSeriesCollection();

    TimeSeries regUpgrades = new TimeSeries("Regular Upgrades", Day.class);
    theData.addSeries(regUpgrades);

    TimeSeries renewals = new TimeSeries("Regular Renewals", Day.class);
    theData.addSeries(renewals);

    TimeSeries regDowngrades = new TimeSeries("Regular Downgrades", Day.class);
    theData.addSeries(regDowngrades);

    for (DailyStatsModel ds : stats) {
        Day theDay = new Day(ds.getDay());
        regUpgrades.add(theDay, ds.getRegupgrades());
        renewals.add(theDay, ds.getRenewals());
        regDowngrades.add(theDay, ds.getRegdowngrades());
    }

    chart = ChartFactory.createTimeSeriesChart("Regular membership changes (14-day moving avg)", "Day",
            "Occurrences", MovingAverage.createMovingAverage(theData, "", 14, 0), true, true, true);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.getRangeAxis().setUpperBound(10);

    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setSeriesStroke(0, new BasicStroke(2.0f));
    renderer.setSeriesStroke(1, new BasicStroke(2.0f));
    renderer.setSeriesStroke(2, new BasicStroke(2.0f));
    return chart;
}

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

/**
 * Tests the equals method./* w w w.  j  av a 2  s  .  c  om*/
 */
public void testEquals() {
    TimeSeries s1 = new TimeSeries("Time Series 1");
    TimeSeries s2 = new TimeSeries("Time Series 2");
    boolean b1 = s1.equals(s2);
    assertFalse("b1", b1);

    s2.setKey("Time Series 1");
    boolean b2 = s1.equals(s2);
    assertTrue("b2", b2);

    RegularTimePeriod p1 = new Day();
    RegularTimePeriod p2 = p1.next();
    s1.add(p1, 100.0);
    s1.add(p2, 200.0);
    boolean b3 = s1.equals(s2);
    assertFalse("b3", b3);

    s2.add(p1, 100.0);
    s2.add(p2, 200.0);
    boolean b4 = s1.equals(s2);
    assertTrue("b4", b4);

    s1.setMaximumItemCount(100);
    boolean b5 = s1.equals(s2);
    assertFalse("b5", b5);

    s2.setMaximumItemCount(100);
    boolean b6 = s1.equals(s2);
    assertTrue("b6", b6);

    s1.setMaximumItemAge(100);
    boolean b7 = s1.equals(s2);
    assertFalse("b7", b7);

    s2.setMaximumItemAge(100);
    boolean b8 = s1.equals(s2);
    assertTrue("b8", b8);
}

From source file:de.fischer.thotti.reportgen.diagram.ChartGenerator.java

public ChartMetaData generateAllVariantsChart(final String testId) {
    File chartFile;/*from www . j  av a2  s .  co  m*/
    try {
        final List<TestVariant> variants = persistenceHelper.findAllVariants(testId);
        final TimeSeriesCollection collection = new TimeSeriesCollection();

        String svgFilename = String.format("%s.svg", testId);

        chartFile = new File(baseDir, svgFilename);

        for (TestVariant variant : variants) {
            TimeSeries series = new TimeSeries(String.format("Average of %s", variant.getCombinedId()),
                    Day.class);
            TimeSeries mediaSeries = new TimeSeries("Median of " + variant, Day.class);

            List<NDResultEntity> results = persistenceHelper.findAllResultsForVariant(variant);

            SortedSet<NDResultEntity> sortedSet = new TreeSet<NDResultEntity>(
                    new TestVariantModel.DateComparator());

            sortedSet.addAll(results);

            Calendar now = Calendar.getInstance();

            now.add(Calendar.DATE, 1);

            Iterator<Measurement> itr = new AverageDayCombinerIterator(sortedSet.iterator());
            Iterator<DatePoint> medianItr = new MedianIterator(sortedSet.iterator());

            while (itr.hasNext()) {
                Measurement singleResult = itr.next();

                Date startDate = singleResult.getPointInTime();

                double timeInMS = singleResult.getDuration();
                double timeInSecs = convertMilliSecsToSeconds(timeInMS);

                series.add(new Day(startDate), timeInSecs);
            }

            while (medianItr.hasNext()) {
                DatePoint singleResult = medianItr.next();

                Day day = new Day(singleResult.getPointInTime());
                double value = convertMilliSecsToSeconds(singleResult.getValue());

                mediaSeries.add(day, value);
            }

            collection.addSeries(series);
            collection.addSeries(mediaSeries);
        }

        final JFreeChart chart = createChart(testId, collection);

        saveChartAsSVG(chart, svgFilename);

        System.out.println(String.format("Written %s", chartFile.toString()));

        return new ChartMetaData().withFilename(chartFile.getName()).withWidth(DEFAULT_CHAR_WIDTH)
                .withHeight(DEFAULT_CHAR_HEIGHT).withFormat("SVG");

    } catch (Exception ioe) {
        // @todo Throw an better exception!
        ioe.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    return null;
}

From source file:gov.llnl.lc.infiniband.opensm.plugin.gui.chart.PortCounterPlotWorker.java

private XYDataset createDeltaDataset(OSM_FabricDeltaCollection deltaHistory, PortCounterName pcn,
        String seriesName) {/*from w  w w  .  j  av  a 2  s.c om*/
    TimeSeries series = new TimeSeries(seriesName);

    // iterate through the collection, and build up a time series
    for (int j = 0; j < deltaHistory.getSize(); j++) {
        OSM_FabricDelta delta = deltaHistory.getOSM_FabricDelta(j);

        // find the desired port counter, in this instance
        LinkedHashMap<String, PFM_PortChange> pcL = delta.getPortChanges();
        PFM_PortChange pC = pcL.get(OSM_Port.getOSM_PortKey(Port));
        long lValue = pC.getDelta_port_counter(pcn);

        // correct for missing time periods
        int deltaSeconds = delta.getDeltaSeconds();
        long sweepPeriod = delta.getFabric2().getPerfMgrSweepSecs();
        if (sweepPeriod < deltaSeconds) {
            // graph is reported as counts per period, so if the period is too long, interpolate
            lValue *= sweepPeriod;
            lValue /= deltaSeconds;
        }
        TimeStamp ts = pC.getCounterTimeStamp();

        RegularTimePeriod ms = new FixedMillisecond(ts.getTimeInMillis());
        series.add(ms, (double) lValue);
    }
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);

    return dataset;
}

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

/**
 * Some checks for the getDataItem(int) method.
 *//*from ww w.ja v a2 s .  c o  m*/
@Test
public void testGetDataItem1() {
    TimeSeries series = new TimeSeries("S", Year.class);

    // can't get anything yet...just an exception
    boolean pass = false;
    try {
        /*TimeSeriesDataItem item =*/ series.getDataItem(0);
    } catch (IndexOutOfBoundsException e) {
        pass = true;
    }
    assertTrue(pass);

    series.add(new Year(2006), 100.0);
    TimeSeriesDataItem item = series.getDataItem(0);
    assertEquals(new Year(2006), item.getPeriod());
    pass = false;
    try {
        /*item = */series.getDataItem(-1);
    } catch (IndexOutOfBoundsException e) {
        pass = true;
    }
    assertTrue(pass);

    pass = false;
    try {
        /*item = */series.getDataItem(1);
    } catch (IndexOutOfBoundsException e) {
        pass = true;
    }
    assertTrue(pass);
}

From source file:com.agiletec.plugins.jpstats.aps.system.services.stats.StatsDAO.java

/**
 * Gets the hits between two dates//from  www  . j av a  2  s .c o m
 * @param start Calendar
 * @param end Calendar
 * @return a TimeSeries object, used to render the chart
 */
@Override
public TimeSeries getHitsByInterval(Calendar start, Calendar end) {
    Connection conn = null;
    PreparedStatement stat = null;
    ResultSet res = null;
    TimeSeries hitsPage = new TimeSeries("Entando_Chart_v0.0", Day.class);
    String startString = new Timestamp(start.getTimeInMillis()).toString();
    String endString = new Timestamp(end.getTimeInMillis()).toString();
    try {
        conn = this.getConnection();
        stat = conn.prepareStatement(HITS_BY_INTERVAL);
        stat.setString(1, startString);
        stat.setString(2, endString);
        res = stat.executeQuery();
        Day initDay = new Day(start.getTime());
        Day endDay = new Day(end.getTime());
        while (res.next()) {
            Day day = new Day(res.getInt("day_value"), res.getInt("month_value"), res.getInt("year_value"));
            hitsPage.add(day, res.getInt("hits"));
        }
        try {
            hitsPage.add(initDay, 0);
        } catch (Throwable t) {
        }
        try {
            hitsPage.add(endDay, 0);
        } catch (Throwable t) {
        }
    } catch (Throwable t) {
        _logger.error("Error getting hits by interval ", t);
        throw new RuntimeException("Error getting hits by interval ", t);
    } finally {
        closeDaoResources(res, stat, conn);
    }
    return hitsPage;
}

From source file:org.jmxtrans.samples.graphite.GraphiteDataInjector.java

public void generateLoad() throws Exception {
    System.out.println("Inject data on Graphite server " + this.graphiteHost);

    TimeSeries timeSeries = new TimeSeries("shopping-cart.raw");

    DateTime now = new DateTime();
    DateTime end = now.plusDays(1);/*from  www  . java  2s  .c  om*/

    DateTime date = now.minusDays(15);
    DateTime twoDaysAfterBegin = date.plusDays(2);

    int integratedValue = 0;

    MathContext mathContext = new MathContext(1, RoundingMode.CEILING);

    int randomFactor = 0;

    while (date.isBefore(end)) {
        if (timeSeries.getItemCount() % 120 == 0) {
            randomFactor = 10 + random.nextInt(2);
        }
        int weekGrowthFactor = 6 - (now.getWeekOfWeekyear() - date.getWeekOfWeekyear());
        int value = new BigDecimal(randomFactor) // random factor
                .multiply(new BigDecimal(10)) // go to cents of USD
                .multiply(new BigDecimal(weekGrowthFactor))
                .multiply(new BigDecimal(hourlyDistribution[date.getHourOfDay()]))
                .multiply(new BigDecimal(weeklyDistribution[date.getDayOfWeek()]))
                .divide(new BigDecimal(20), mathContext).intValue(); // split hourly value in minutes

        integratedValue += value;
        for (int i1 = 0; i1 < 3; i1++) {
            timeSeries.add(new Minute(date.toDate()), integratedValue);
            date = date.plusMinutes(1);
        }
    }

    TimeSeries ordersPriceInCentsTimeSeries = MovingAverage.createMovingAverage(timeSeries,
            "shopping-cart.OrdersPriceInCents", 60 * 7, 0);

    TimeSeries ordersPriceInCentsSrv1TimeSeries = new TimeSeries("srv1.shopping-cart.OrdersPriceInCents");
    TimeSeries ordersPriceInCentsSrv2TimeSeries = new TimeSeries("srv2.shopping-cart.OrdersPriceInCents");
    int resetValue2ToZeroOffset = 0; // reset value 2 after 3 days of metrics
    for (int i = 0; i < ordersPriceInCentsTimeSeries.getItemCount(); i++) {
        TimeSeriesDataItem dataItem = ordersPriceInCentsTimeSeries.getDataItem(i);
        int value = dataItem.getValue().intValue();
        // value1 is 5% higher to value2 due to a 'weirdness' in the load balancing
        int value1 = Math.min((int) (value * 1.05 / 2), value);

        {
            // simulate srv2 restart
            DateTime currentDate = new DateTime(dataItem.getPeriod().getStart());
            boolean shouldResetValue2 = resetValue2ToZeroOffset == 0
                    && currentDate.getDayOfYear() == twoDaysAfterBegin.getDayOfYear();
            if (shouldResetValue2) {
                resetValue2ToZeroOffset = value - value1;
                System.out.println("reset value2 of " + resetValue2ToZeroOffset + " at " + currentDate);
            }
        }

        int value2 = value - value1 - resetValue2ToZeroOffset;
        // System.out.println("value=" + value + ", value1=" + value1 + ", value2=" + value2);
        ordersPriceInCentsSrv1TimeSeries.add(dataItem.getPeriod(), value1);
        ordersPriceInCentsSrv2TimeSeries.add(dataItem.getPeriod(), value2);
    }

    TimeSeries orderItemsCountTimeSeries = new TimeSeries("shopping-cart.OrderItemsCount");
    TimeSeries orderItemsCountSrv1TimeSeries = new TimeSeries("srv1.shopping-cart.OrderItemsCount");
    TimeSeries orderItemsCountSrv2TimeSeries = new TimeSeries("srv2.shopping-cart.OrderItemsCount");

    for (int i = 0; i < ordersPriceInCentsTimeSeries.getItemCount(); i++) {
        RegularTimePeriod period = ordersPriceInCentsTimeSeries.getDataItem(i).getPeriod();
        int ordersPriceInCents1 = ordersPriceInCentsSrv1TimeSeries.getDataItem(i).getValue().intValue();
        int ordersPriceInCents2 = ordersPriceInCentsSrv2TimeSeries.getDataItem(i).getValue().intValue();

        int value1 = ordersPriceInCents1 / 600;
        int value2 = ordersPriceInCents2 / 600;

        orderItemsCountTimeSeries.add(period, value1 + value2);
        orderItemsCountSrv1TimeSeries.add(period, value1);
        orderItemsCountSrv2TimeSeries.add(period, value2);

    }

    exportMetrics(ordersPriceInCentsTimeSeries, ordersPriceInCentsSrv1TimeSeries,
            ordersPriceInCentsSrv2TimeSeries, ordersPriceInCentsTimeSeries, orderItemsCountTimeSeries,
            orderItemsCountSrv1TimeSeries, orderItemsCountSrv2TimeSeries);

    TimeSeries activeSrv1Visitors = new TimeSeries("srv1.visitors.currentActive");
    TimeSeries activeSrv2Visitors = new TimeSeries("srv1.visitors.currentActive");

}