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

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

Introduction

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

Prototype

public List getItems() 

Source Link

Document

Returns the list of data items for the series (the list contains TimeSeriesDataItem objects and is unmodifiable).

Usage

From source file:com.bpd.jfreechart.StackedAreaChartDemo.java

/**
 * Test program that will display a JFreeChart showing interpolated data points.
 * /*from ww w  .j a  v a  2s  . c  o  m*/
 * @param args <b>"1"</b> to display Series 1. <b>"2"</b> to display Series 2. <b>"0"</b> to
 * display both series.
 */
public static void main(String... args) {
    // Check arguments.
    if (args.length != 1) {
        System.err.println("Usage: java Chart [0|1|2]\n\n  -- 0: Display Series 1.");
        System.err.println("  -- 1: Display Series 2.\n  -- 2: Display both series.");
        return;
    }

    String option = args[0];
    if (!"0".equals(option) && !"1".equals(option) && !"2".equals(option)) {
        System.err.println("Invalid argument: " + option);
        return;
    }

    // Create some sample data.
    List<Point<Number, Number>> list1 = new ArrayList<Point<Number, Number>>();
    list1.add(new Point<Number, Number>(50, 100.0));
    list1.add(new Point<Number, Number>(150, 100));
    list1.add(new Point<Number, Number>(250, 200));
    list1.add(new Point<Number, Number>(350, 400));
    list1.add(new Point<Number, Number>(450, 200));
    list1.add(new Point<Number, Number>(550, 100));

    List<Point<Number, Number>> list2 = new ArrayList<Point<Number, Number>>();
    list2.add(new Point<Number, Number>(50, 100.0));
    list2.add(new Point<Number, Number>(150, 200.0));
    list2.add(new Point<Number, Number>(250, 400.0));
    list2.add(new Point<Number, Number>(350, 600.0));
    list2.add(new Point<Number, Number>(450, 400.0));
    list2.add(new Point<Number, Number>(550, 200.0));

    // Add data to time series.
    TimeSeries series1 = new TimeSeries("Series 1", FixedMillisecond.class);
    for (Point<Number, Number> dataPoint : list1) {
        if ("1".equals(option) || "0".equals(option)) {
            series1.add(new FixedMillisecond(dataPoint.getX().longValue()), dataPoint.getY());
        }
        series1.setDescription("Series 1");
    }

    TimeSeries series2 = new TimeSeries("Series 2", FixedMillisecond.class);
    for (Point<Number, Number> dataPoint : list2) {
        if ("2".equals(option) || "0".equals(option)) {
            series2.add(new FixedMillisecond(dataPoint.getX().longValue()), dataPoint.getY());
        }
        series2.setDescription("Series 2");
    }

    TimeSeriesCollection collection = new TimeSeriesCollection();
    if ("1".equals(option)) {
        collection.addSeries(series1);
    } else if ("2".equals(option)) {
        collection.addSeries(series2);
    } else if ("0".equals(option)) {
        collection.addSeries(series1);
        collection.addSeries(series2);
    }

    TimeTableXYDataset dataset = new TimeTableXYDataset();
    @SuppressWarnings("unchecked")
    List<TimeSeries> timeSeriesList = collection.getSeries();
    for (TimeSeries t : timeSeriesList) {
        for (int index = 0; index < t.getItemCount(); index++) {
            TimeSeriesDataItem dataItem = (TimeSeriesDataItem) t.getItems().get(index);
            dataset.add(t.getTimePeriod(index), dataItem.getValue().doubleValue(), t.getDescription());
        }
    }

    // Create and display chart.
    JFreeChart chart = ChartFactory.createStackedXYAreaChart(null, null, null, dataset,
            PlotOrientation.VERTICAL, false, true, false);

    customizeChart(chart);

    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));

    JFrame frame = new JFrame();
    frame.getContentPane().add(chartPanel);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

From source file:de.xirp.chart.ChartUtil.java

/**
 * Exports the given dataset as CSV.//from w  w  w. j a v a 2s .  co m
 * 
 * @param dataset
 *            The dataset to export.
 * @param robotName
 *            The robot name for which the dataset is exported.
 * @see org.jfree.data.time.TimeSeriesCollection
 */
private static void exportCSV(TimeSeriesCollection dataset, String robotName) {
    for (Object obj : dataset.getSeries()) {
        List<Observed> obs = new ArrayList<Observed>();
        TimeSeries ts = (TimeSeries) obj;
        String observedKey = (String) ts.getKey();
        for (Object obj2 : ts.getItems()) {
            TimeSeriesDataItem tsdi = (TimeSeriesDataItem) obj2;
            Observed o = new Observed();
            o.setObservedKey(observedKey);
            o.setTimestamp(tsdi.getPeriod().getStart().getTime());
            o.setValue(tsdi.getValue().doubleValue());
            obs.add(o);
        }
        exportCSV(obs, robotName);
    }
}

From source file:de.citec.csra.allocation.vis.MovingChart.java

/**
 * Generates an random entry for a particular call made by time for every
 * 1/4th of a second.//from  ww  w. j  a va  2  s .  co m
 *
 * @param e the action event.
 */
@Override
public void actionPerformed(final ActionEvent e) {

    this.plustime.addOrUpdate(new Millisecond(new Date(System.currentTimeMillis() + this.future)), 0);
    List<TimeSeries> ts = this.dataset.getSeries();
    List<TimeSeries> del = new LinkedList<>();
    long now = System.currentTimeMillis();
    marker.setValue(now);
    int active = 0;
    for (TimeSeries t : ts) {
        if (!t.equals(this.plustime)) {
            List<TimeSeriesDataItem> its = t.getItems();
            long last = 0;
            for (TimeSeriesDataItem it : its) {
                long end = it.getPeriod().getLastMillisecond();
                if (end > last) {
                    last = end;
                }
            }
            if (now - last > this.past) {
                del.add(t);
            } else {
                active++;
            }
        }
    }

    synchronized (this.dataset) {
        if (active == 0) {
            for (TimeSeries d : del) {
                this.dataset.removeSeries(d);
            }
            if (del.size() > 0) {
                this.chart.getXYPlot().setRenderer(new XYLineAndShapeRenderer(true, false));
                XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) this.chart.getXYPlot()
                        .getRendererForDataset(dataset);
                r.setSeriesPaint(0, Color.BLACK);
            }
        }
    }
}

From source file:com.hello2morrow.sonargraph.jenkinsplugin.model.TimeSeriesPlot.java

/**
 * Creates a XYDataset from a CSV file.//from   w  w  w . j  a va2s . co  m
 */
@Override
protected XYDataset createXYDataset(SonargraphMetrics metric, int maximumNumberOfDataPoints)
        throws IOException {
    assert metric != null : "Parameter 'metric' of method 'createXYDataset' must not be null";

    //For some reason, the class of the time series is required here, otherwise an exception is thrown that a Date instance is expected.
    @SuppressWarnings("deprecation")
    TimeSeries timeSeries = new TimeSeries(metric.getShortDescription(), FixedMillisecond.class);

    List<IDataPoint> dataset = m_datasetProvider.readMetricValues(metric);
    int size = dataset.size();
    SonargraphLogger.INSTANCE.fine(size + " data points found for metric '" + metric.getStandardName()
            + "' in file '" + m_datasetProvider.getStorageName() + "'");
    List<IDataPoint> reducedSet = reduceDataSet(dataset, maximumNumberOfDataPoints);

    BuildDataPoint point = null;
    for (IDataPoint datapoint : reducedSet) {
        if (datapoint instanceof InvalidDataPoint) {
            // We could create a gap in the graph by adding null:
            // xySeries.add(datapoint.getX(), null);
            continue;
        } else if (datapoint instanceof BuildDataPoint) {
            point = (BuildDataPoint) datapoint;
            if (point.getTimestamp() == 0) {
                continue;
            }

            timeSeries.add(new FixedMillisecond(point.getTimestamp()), point.getY());
        }
    }
    if (point != null) {
        setTimestampOfLastDisplayedPoint(point.getTimestamp());
    }

    TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();
    TimeSeries avgDataset = MovingAverage.createMovingAverage(timeSeries,
            "Avg of " + metric.getShortDescription(), MOVING_AVG_PERIOD, 0);
    setDataSetSize(avgDataset.getItemCount());
    timeSeriesCollection.addSeries(avgDataset);

    //SG-325: We cannot use JFreeChart methods of version 1.0.14
    //        setMinimumValue(avgDataset.getMinY());
    //        setMaximumValue(avgDataset.getMaxY());

    // We only show the average data and omit the original data
    //        timeSeriesCollection.addSeries(timeSeries);
    for (Object item : avgDataset.getItems()) {
        if (item instanceof TimeSeriesDataItem) {
            checkMinMaxYValue(((TimeSeriesDataItem) item).getValue().doubleValue());
        }
    }
    return timeSeriesCollection;
}

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

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

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

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

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

    if (!history.isEmpty()) {

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

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

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

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

            previous = sample;
        }
    }

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

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

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

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

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

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

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

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

    chart.setBackgroundPaint(bgColor);

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

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

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

    return null;
}

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

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

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

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

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

    if (!history.isEmpty()) {

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

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

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

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

            previous = sample;
        }
    }

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

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

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

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

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

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

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

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

    chart.setBackgroundPaint(bgColor);

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

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

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

    return null;
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.ChartHelper.java

/***********************************************************************************************
 * Find the Series index for the specified Slider position in milliseconds.
 *
 * @param millis// w  w w .ja v  a 2 s .  c o  m
 * @param timeseries
 * @param calendar
 *
 * @return int
 */

private static int findTimeSeriesIndexForMillis(final double millis, final TimeSeries timeseries,
        final Calendar calendar) {
    final String SOURCE = "ChartHelper.findTimeSeriesIndexForMillis() ";
    int intIndex;

    intIndex = -1;

    // ToDo Review if this would be better using timeseries.getDataItem(RegularTimePeriod)
    // Let's be careful, in case something goes wrong...
    try {
        final List<TimeSeriesDataItem> listDataItems;
        boolean boolFoundIt;

        listDataItems = timeseries.getItems();
        boolFoundIt = false;

        // Scan the whole Series to find the first Item with the correct time period
        // This avoids having to create a RegularTimePeriod each time?
        for (int intItemIndex = 0; ((!boolFoundIt) && (intItemIndex < listDataItems.size())); intItemIndex++) {
            final TimeSeriesDataItem dataItem;

            dataItem = listDataItems.get(intItemIndex);

            // The Domain Slider should be pointing at a real TimeSeriesDataItem,
            // or at least very close to it...
            boolFoundIt = (dataItem.getPeriod().getFirstMillisecond(calendar) >= (long) millis);

            if (boolFoundIt) {
                intIndex = intItemIndex;

                LOGGER.debug(LOADER_PROPERTIES.isChartDebug(),
                        SOURCE + "[item.index=" + intIndex + "] [series.size=" + listDataItems.size()
                                + "] [item.period.first.millis="
                                + dataItem.getPeriod().getFirstMillisecond(calendar) + "] [slider.millis="
                                + (long) millis + "] [found.it=" + boolFoundIt + "]");
            }
        }
    }

    catch (final IndexOutOfBoundsException exception) {
        LOGGER.error(SOURCE + "IndexOutOfBoundsException");
        intIndex = -1;
    }

    catch (final NullPointerException exception) {
        LOGGER.error(SOURCE + "NullPointerException");
        intIndex = -1;
    }

    return (intIndex);
}

From source file:com.peterbochs.instrument.InstrumentPanel.java

private void runTimer() {
    if (interruptTimer != null) {
        interruptTimer.cancel();/*from   w ww .j a  v  a  2 s  . co m*/
    }

    interruptTimer = new Timer();
    interruptTimer.schedule(new TimerTask() {
        Hashtable<Long, Integer> oldInterruptRecords;

        public void run() {
            try {
                synchronized (allSeries) {
                    ArrayList<Long> list = Collections.list(InterruptSocketServer.interruptRecords.keys());
                    Date d = new Date();
                    // int noOfFrame = getTimeframe() / getSpeed();
                    oldInterruptRecords = (Hashtable<Long, Integer>) InterruptSocketServer.interruptRecords
                            .clone();
                    ((InterruptTableModel) jInterruptTable.getModel()).fireTableDataChanged();

                    for (int x = 0; x < list.size(); x++) {
                        long interuptNoL = list.get(x);
                        int interruptNo = (int) interuptNoL;
                        if (allSeries.get(interruptNo) != null) {
                            TimeSeries series = allSeries.get(interruptNo);
                            List<TimeSeriesDataItem> items = series.getItems();
                            for (int z = items.size() - 1; z >= 0; z--) {
                                RegularTimePeriod pd = items.get(z).getPeriod();
                                Calendar cal1 = Calendar.getInstance();
                                cal1.add(Calendar.MILLISECOND, -1 * getTimeframe());
                                Calendar cal2 = Calendar.getInstance();
                                cal2.setTime(pd.getEnd());
                                if (cal1.after(cal2)) {
                                    series.delete(pd);
                                }
                            }
                            series.add(new Millisecond(d),
                                    InterruptSocketServer.interruptRecords.get(interuptNoL)
                                            - oldInterruptRecords.get(interuptNoL));
                            //                     InterruptSocketServer.interruptRecords.put(interuptNoL, 0);
                        } else {
                            TimeSeries newSeries = new TimeSeries("Int 0x" + Integer.toHexString(interruptNo));
                            interruptDataset.addSeries(newSeries);
                            allSeries.put(interruptNo, newSeries);
                        }
                    }

                    interruptChart.fireChartChanged();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }, 0, getSpeed());
}

From source file:org.codehaus.mojo.chronos.responsetime.ResponsetimeSamples.java

/**
 * /*from  w ww .  jav a2s  .  c om*/
 * @param responsetimedivider
 *            TODO
 * @return the maximum of a moving average of the throughput
 */
public final double getMaxAverageThroughput(int averageduration, int responsetimedivider) {
    TimeSeries series = createMovingThroughput("", responsetimedivider);
    TimeSeries averageseries = MovingAverage.createMovingAverage(series, "", averageduration, 0);
    double max = 0;
    for (Iterator it = averageseries.getItems().iterator(); it.hasNext();) {
        TimeSeriesDataItem item = (TimeSeriesDataItem) it.next();
        if (item.getValue() != null) {
            max = Math.max(max, item.getValue().doubleValue());
        }
    }
    return max;
}