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:it.marcoberri.mbmeteo.action.chart.Get.java

/**
 * Processes requests for both HTTP/*from  ww  w . jav  a  2  s  .com*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);
    final String from = Default.toString(params.get("from") + " 00:00:00", "1970-01-01 00:00:00");
    final String to = Default.toString(params.get("to") + " 23:59:00", "2030-01-01 23:59:00");
    final String field = Default.toString(params.get("field"), "outdoorTemperature");

    request.getSession().setAttribute("from", params.get("from"));
    request.getSession().setAttribute("to", params.get("to"));

    final String cacheKey = getCacheKey(params);

    if (cacheReadEnable) {
        final Query q = ds.find(Cache.class);
        q.filter("cacheKey", cacheKey).filter("servletName", this.getClass().getName());

        final Cache c = (Cache) q.get();

        if (c == null) {
            log.info("cacheKey:" + cacheKey + " on servletName: " + this.getClass().getName() + " not found");
        }

        if (c != null) {
            log.debug("get file from cache id: " + c.getGridId());
            final GridFSDBFile imageForOutput = MongoConnectionHelper.getGridFS()
                    .findOne(new ObjectId(c.getGridId()));
            if (imageForOutput != null) {

                ds.save(c);

                try {
                    response.setHeader("Content-Length", "" + imageForOutput.getLength());
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + imageForOutput.getFilename() + "\"");
                    final OutputStream out = response.getOutputStream();
                    final InputStream in = imageForOutput.getInputStream();
                    final byte[] content = new byte[(int) imageForOutput.getLength()];
                    in.read(content);
                    out.write(content);
                    in.close();
                    out.close();
                    return;
                } catch (final IOException e) {
                    log.error(e);
                }

            } else {
                log.error("file not in db");
            }
        }
    }

    final String titleChart = ChartEnumHelper.getByName(field).getTitle();
    final String umChart = ChartEnumHelper.getByName(field).getUm();
    final Query q = ds.createQuery(Meteolog.class);
    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    q.disableValidation().filter("time >=", dFrom).filter("time <=", dTo);

    final List<Meteolog> meteoLogList = q.asList();
    final TimeSeries series = new TimeSeries(umChart);

    for (Meteolog m : meteoLogList) {
        final Millisecond t = new Millisecond(m.getTime());
        try {
            //violenza di una reflection
            final Method method = m.getClass().getMethod(ChartEnumHelper.getByName(field).getMethod());
            final Number n = (Number) method.invoke(m);
            series.add(t, n);
        } catch (final NoSuchMethodException ex) {
            log.error(ex);
        } catch (final InvocationTargetException ex) {
            log.error(ex);
        } catch (final IllegalAccessException ex) {
            log.error(ex);
        } catch (final SecurityException ex) {
            log.error(ex);
        }

    }

    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(series);

    final JFreeChart chart = ChartFactory.createTimeSeriesChart(titleChart, "", umChart, dataset, false, false,
            false);
    final XYPlot plot = (XYPlot) chart.getPlot();
    final DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy HH:mm"));
    axis.setVerticalTickLabels(true);

    if (field.toUpperCase().indexOf("PRESSURE") != -1) {
        plot.getRangeAxis().setRange(chartPressureMin, chartPressureMax);
    }

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    try {

        if (cacheWriteEnable) {

            final GridFSInputFile gfsFile = MongoConnectionHelper.getGridFS().createFile(f);
            gfsFile.setFilename(f.getName());
            gfsFile.save();

            final Cache c = new Cache();
            c.setServletName(this.getClass().getName());
            c.setCacheKey(cacheKey);
            c.setGridId(gfsFile.getId().toString());

            ds.save(c);

        }

        response.setContentType("image/jpeg");
        response.setHeader("Content-Length", "" + f.length());
        response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
        final OutputStream out = response.getOutputStream();
        final FileInputStream in = new FileInputStream(f.toString());
        final int size = in.available();
        final byte[] content = new byte[size];
        in.read(content);
        out.write(content);
        in.close();
        out.close();
    } catch (final IOException e) {
        log.error(e);
    } finally {
        f.delete();
    }

}

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

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

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

From source file:org.softinica.maven.jmeter.report.analyser.RequestDurationAnalyzer.java

@Override
protected JFreeChart createChart(PageDefinition definition, Input input) {
    Map<String, Map<Long, Long>> allSeries = new HashMap<String, Map<Long, Long>>();
    for (Sample sample : input.getSamples()) {
        Map<Long, Long> duration = allSeries.get(sample.getLabel());
        if (duration == null) {
            duration = new HashMap<Long, Long>();
            allSeries.put(sample.getLabel(), duration);
        }/*from w w  w  .  j  a v  a  2 s. c o  m*/
        duration.put((sample.getTimestamp() + (long) sample.getValue()), (long) sample.getValue());
    }
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    for (String label : allSeries.keySet()) {
        Map<Long, Long> duration = allSeries.get(label);
        TimeSeries series = new TimeSeries(label);
        for (Long key : duration.keySet()) {
            series.addOrUpdate(new Millisecond(new Date(key)), duration.get(key));
        }
        dataset.addSeries(series);
    }

    return ChartFactory.createTimeSeriesChart(definition.getTitle(), "Time", "Duration", dataset);
}

From source file:org.softinica.maven.jmeter.report.analyser.ResponseSizeAnalyzer.java

@Override
protected JFreeChart createChart(PageDefinition definition, Input input) {
    Map<String, Map<Long, Long>> allSeries = new HashMap<String, Map<Long, Long>>();
    for (Sample sample : input.getSamples()) {
        Map<Long, Long> duration = allSeries.get(sample.getLabel());
        if (duration == null) {
            duration = new HashMap<Long, Long>();
            allSeries.put(sample.getLabel(), duration);
        }/*from   w  ww .j a  va  2  s  . c om*/
        duration.put((sample.getTimestamp() + (long) sample.getValue()), (long) sample.getByteCount());
    }
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    for (String label : allSeries.keySet()) {
        Map<Long, Long> duration = allSeries.get(label);
        TimeSeries series = new TimeSeries(label);
        for (Long key : duration.keySet()) {
            series.addOrUpdate(new Millisecond(new Date(key)), duration.get(key));
        }
        dataset.addSeries(series);
    }

    return ChartFactory.createTimeSeriesChart(definition.getTitle(), "Time", "Size(bytes)", dataset);
}

From source file:com.bdb.weather.display.stripchart.StripChart.java

/**
 * Show the specified series./* ww  w.ja va  2  s .com*/
 * 
 * @param seriesName The name of the series
 * @param leftAxis Whether this series is mapped to the left of right axis
 */
public void showSeries(String seriesName, boolean leftAxis) {
    TimeSeries timeSeries = series.get(seriesName);

    if (timeSeries != null) {
        TimeSeriesCollection dataset;
        if (leftAxis) {
            dataset = leftAxisCollection;
        } else {
            dataset = rightAxisCollection;
        }

        dataset.addSeries(timeSeries);
    }
}

From source file:org.softinica.maven.jmeter.report.analyser.ValueByTimestampAnalyzer.java

@Override
protected JFreeChart createChart(PageDefinition definition, Input input) {
    Map<String, Map<Long, Double>> allSeries = new HashMap<String, Map<Long, Double>>();
    for (Sample sample : input.getSamples()) {
        Map<Long, Double> duration = allSeries.get(sample.getLabel());
        if (duration == null) {
            duration = new HashMap<Long, Double>();
            allSeries.put(sample.getLabel(), duration);
        }/*from w w w . j  a va2  s .  co m*/
        duration.put(sample.getTimestamp(), sample.getValue());
    }
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    for (String label : allSeries.keySet()) {
        Map<Long, Double> duration = allSeries.get(label);
        TimeSeries series = new TimeSeries(label);
        for (Long key : duration.keySet()) {
            series.addOrUpdate(new Millisecond(new Date(key)), duration.get(key));
        }
        dataset.addSeries(series);
    }

    return ChartFactory.createTimeSeriesChart(definition.getTitle(), "Time", "Value", dataset);
}

From source file:be.vds.jtbdive.client.view.core.stats.StatChartGenerator.java

private static JFreeChart buildChartForDive(StatQueryObject sqo) {
    Collection<StatSerie> s = sqo.getValues();
    String legend = I18nResourceManager.sharedInstance().getString("dive.times");
    TimeSeriesCollection collection = new TimeSeriesCollection();
    for (StatSerie statSerie : s) {
        TimeSeries ts = new TimeSeries(legend);
        for (StatPoint point : statSerie.getPoints()) {
            Date dd = (Date) point.getX();
            FixedMillisecond day = new FixedMillisecond(dd);
            Object index = ts.getDataItem(day);
            if (null != index) {
                GregorianCalendar gc = new GregorianCalendar();
                gc.setTime(dd);/*from   w ww.ja va  2  s.co  m*/
                gc.add(Calendar.MILLISECOND, 1);
                day = new FixedMillisecond(gc.getTime());
            }

            if (sqo.getStatYAxisParams().getStatYAxis().equals(StatYAxis.DEPTHS)) {
                ts.add(day, UnitsAgent.getInstance().convertLengthFromModel((Double) point.getY()));
            } else if (sqo.getStatYAxisParams().getStatYAxis().equals(StatYAxis.TEMPERATURES)) {
                ts.add(day, UnitsAgent.getInstance().convertTemperatureFromModel((Double) point.getY()));
            } else {
                ts.add(day, point.getY());
            }
        }
        collection.addSeries(ts);
    }

    JFreeChart chart = createLineChart(collection, getXLabel(sqo), getYLabel(sqo));

    if (sqo.getStatYAxisParams().getStatYAxis().equals(StatYAxis.DIVE_TIME)) {
        XYPlot xyp = (XYPlot) chart.getPlot();
        ((NumberAxis) xyp.getRangeAxis()).setNumberFormatOverride(new HoursMinutesNumberFormat());
    }

    return chart;
}

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

/**
 * Creates a sample dataset./* w ww. ja va 2 s  .  co m*/
 *
 * @param name  the dataset name.
 * @param base  the starting value.
 * @param start  the starting period.
 * @param count  the number of values to generate.
 *
 * @return The dataset.
 */
private XYDataset createDataset(OMS_Collection history) {
    TimeSeries TSeries = new TimeSeries("counts");
    // iterate through the collection, and build up a time series
    for (int j = 0; j < history.getSize(); j++) {
        OpenSmMonitorService osm = history.getOMS(j);

        // find the desired port counter, in this instance
        LinkedHashMap<String, OSM_Port> pL = osm.getFabric().getOSM_Ports();
        OSM_Port p = pL.get(OSM_Port.getOSM_PortKey(Port));
        long lValue = p.pfmPort.getCounter(PortCounter);
        TimeStamp ts = p.pfmPort.getCounterTimeStamp();

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

    return dataset;
}

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

private XYDataset createRateDataset(OSM_FabricDeltaCollection deltaHistory, PortCounterName pcn,
        String seriesName) {/*from   www  .java 2s.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
        PFM_PortChange pC = delta.getPortChange(Port);
        long lValue = PFM_PortRate.getChangeRateLong(pC, pcn, PortCounterUnits.MEGABYTES);
        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:gov.llnl.lc.infiniband.opensm.plugin.gui.chart.PortCounterPlotWorker.java

private XYDataset createUtilizationDataset(OSM_FabricDeltaCollection deltaHistory, PortCounterName pcn,
        String seriesName) {/*from w ww .  j  av a2s .c  o  m*/
    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));
        PFM_PortRate pR = new PFM_PortRate(pC);
        TimeStamp ts = pC.getCounterTimeStamp();

        // convert rate to utilization
        double lValue = SMT_AnalysisManager.getInstance().getDeltaAnalysis().getPortUtilization(pR, pcn);

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

    return dataset;
}