List of usage examples for org.jfree.data.time TimeSeriesCollection TimeSeriesCollection
public TimeSeriesCollection()
From source file:org.miloss.fgsms.services.rs.impl.reports.ws.ResponseTimeOverTime.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 {/*www . j av 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 Response Time (ms)</th></tr>"); TimeSeriesCollection col = new TimeSeriesCollection(); for (int i = 0; i < urls.size(); i++) { if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) { continue; } //https://github.com/mil-oss/fgsms/issues/112 if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) { continue; } try { 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(responsetimems) from rawdata 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(format.format(average) + "").append("</td></tr>"); //ok now get the raw data.... TimeSeriesContainer tsc = new TimeSeriesContainer(); try { cmd = con.prepareStatement( "select responsetimems,utcdatetime from rawdata 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()) { TimeSeries ts2 = tsc.Get(url, Millisecond.class); GregorianCalendar gcal = new GregorianCalendar(); gcal.setTimeInMillis(rs.getLong(2)); Millisecond m = new Millisecond(gcal.getTime()); ts2.addOrUpdate(m, rs.getLong("responsetimems")); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } for (int ik = 0; ik < tsc.data.size(); ik++) { col.addSeries(tsc.data.get(ik)); } } catch (Exception ex) { log.log(Level.ERROR, "Error opening or querying the database.", ex); } } chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Time in ms", 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:org.miloss.fgsms.services.rs.impl.reports.os.MemoryUsageReport.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 a v a 2 s . co 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 Memory Usage (bytes)</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))); try { data.append("<tr><td>").append(url).append("</td>"); double average = 0; try { cmd = con.prepareStatement( "select avg(memoryused) 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 memoryused,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)); } } catch (Exception ex) { log.log(Level.WARN, null, ex); } finally { DBUtils.safeClose(rs); DBUtils.safeClose(cmd); } col.addSeries(ts); } catch (Exception ex) { log.log(Level.ERROR, "Error opening or querying the database.", ex); } } chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Bytes", 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:net.pickapack.chart.LinePlotFrame.java
/** * Create a line plot frame./*from w w w . ja v a2 s. co m*/ * * @param linePlot the line plot * @param width the width * @param height the height */ public LinePlotFrame(LinePlot linePlot, int width, int height) { super(linePlot.getTitle()); this.linePlot = linePlot; this.numSubPlots = linePlot.getSubLinePlots().size(); CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis("Time")); this.dataSets = new ArrayList<TimeSeriesCollection>(); this.dataSinks = new ArrayList<Map<SubLinePlotLine, Function<Double>>>(); for (SubLinePlot subLinePlot : linePlot.getSubLinePlots()) { TimeSeriesCollection dataSetsPerSubPlot = new TimeSeriesCollection(); this.dataSets.add(dataSetsPerSubPlot); HashMap<SubLinePlotLine, Function<Double>> dataSinksPerSubPlot = new HashMap<SubLinePlotLine, Function<Double>>(); this.dataSinks.add(dataSinksPerSubPlot); for (SubLinePlotLine subLinePlotLine : subLinePlot.getLines()) { TimeSeries timeSeries = new TimeSeries(subLinePlotLine.getTitle()); dataSetsPerSubPlot.addSeries(timeSeries); dataSinksPerSubPlot.put(subLinePlotLine, subLinePlotLine.getGetValueCallback()); } NumberAxis rangeAxis = new NumberAxis(subLinePlot.getTitleY()); rangeAxis.setAutoRangeIncludesZero(false); XYPlot subplot = new XYPlot(dataSetsPerSubPlot, null, rangeAxis, new StandardXYItemRenderer()); subplot.setBackgroundPaint(Color.lightGray); subplot.setDomainGridlinePaint(Color.white); subplot.setRangeGridlinePaint(Color.white); plot.add(subplot); } JFreeChart chart = new JFreeChart(linePlot.getTitle(), plot); chart.setBorderPaint(Color.black); chart.setBorderVisible(true); chart.setBackgroundPaint(Color.white); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); ValueAxis axis = plot.getDomainAxis(); axis.setAutoRange(true); axis.setFixedAutoRange(3600000.0); JPanel content = new JPanel(new BorderLayout()); ChartPanel chartPanel = new ChartPanel(chart); content.add(chartPanel); chartPanel.setPreferredSize(new java.awt.Dimension(width, height)); chartPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); setContentPane(content); DataSink dataSink = new DataSink(); new Thread(dataSink).start(); }
From source file:com.view.TimeSeriesChartView.java
public JFreeChart getVendorTimeSeriesChart(Excel theExcel, String vendor) { int vendorCode = Integer.parseInt(vendor); ArrayList<Receiving> theReceiving = theExcel.getSheetReceiving(); // HashMap<Month, Integer> item1Map = new HashMap<>(); // HashMap<Month, Integer> item2Map = new HashMap<>(); // HashMap<Month, Integer> item3Map = new HashMap<>(); Set vendorItem = new HashSet(); for (int i = 0; i < theReceiving.size(); i++) { vendorItem.add(theReceiving.get(i).getItem()); }//from w w w .j a va 2 s . c o m TimeSeries data[] = new TimeSeries[vendorItem.size()]; HashMap<Month, Integer> itemMap[] = new HashMap[vendorItem.size()]; for (int i = 0; i < vendorItem.size(); i++) { String itemName = "item" + i; data[i] = new TimeSeries(itemName); itemMap[i] = new HashMap<>(); } Calendar cal = Calendar.getInstance(); for (int i = 0; i < theReceiving.size(); i++) { cal.setTime(theReceiving.get(i).getDate()); int month = cal.get(Calendar.MONTH) + 1; int year = cal.get(Calendar.YEAR); int quantity = 0; if (theReceiving.get(i).getVendor() == vendorCode) { quantity = theReceiving.get(i).getQuantity(); Month theMonth = new Month(month, year); int itemNum = theReceiving.get(i).getItem() - 1; itemMap[itemNum].put(theMonth, updateItemMap(itemMap[itemNum], theMonth, quantity)); } } TimeSeriesCollection my_data_series = new TimeSeriesCollection(); for (int i = 0; i < vendorItem.size(); i++) { for (Map.Entry<Month, Integer> entry : itemMap[i].entrySet()) { data[i].add(entry.getKey(), entry.getValue()); } my_data_series.addSeries(data[i]); } JFreeChart chart = ChartFactory.createTimeSeriesChart("Receiving", "Month", "Quantity", my_data_series, true, true, false); chart.setBackgroundPaint(Color.YELLOW); XYPlot plot = (XYPlot) chart.getPlot(); plot.setBackgroundPaint(Color.WHITE); plot.setDomainGridlinePaint(Color.GREEN); plot.setRangeGridlinePaint(Color.orange); plot.setAxisOffset(new RectangleInsets(50, 0, 20, 5)); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); DateAxis axis = (DateAxis) plot.getDomainAxis(); axis.setDateFormatOverride(new SimpleDateFormat("MM.yyyy")); return chart; }
From source file:ws.moor.bt.gui.charts.PiecesStats.java
private TimeSeriesCollection getTimeSeriesCollection() { TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(validSource.getTimeSeries()); dataset.addSeries(pendingSource.getTimeSeries()); dataset.addSeries(hashFailed.getTimeSeries()); return dataset; }
From source file:com.sigueros.charts.LinearRegressionExample.java
/** * Creates a sample dataset for Columns data */// w w w .j a v a2 s .com private TimeSeriesCollection createDatasetColumns() { final TimeSeries columnsData = new TimeSeries("Columns"); for (int i = 0; i < getData().length; i++) { columnsData.add(new Year((int) getData()[i][0]), getData()[i][1]); } TimeSeriesCollection dataColumnsCollection = new TimeSeriesCollection(); dataColumnsCollection.addSeries(columnsData); return dataColumnsCollection; }
From source file:greenapi.ui.charts.LineChartPanelSupport.java
@Override public JFreeChart createChart() { this.timeSeries = new TimeSeriesCollection(); this.dataset = new TranslatingXYDataset(this.timeSeries); JFreeChart chart = ChartFactory.createTimeSeriesChart(this.getTitle(), null, this.getAxisLabel(), this.dataset, true, true, false); chart.setBackgroundPaint(getBackground()); XYPlot xyPlot = chart.getXYPlot();//from ww w . ja v a 2 s. co m xyPlot.setOrientation(PlotOrientation.VERTICAL); xyPlot.setBackgroundPaint(Color.WHITE); xyPlot.setDomainGridlinePaint(Color.BLACK.darker()); xyPlot.setRangeGridlinePaint(Color.BLACK.darker()); xyPlot.setAxisOffset(new RectangleInsets(5.0D, 5.0D, 5.0D, 5.0D)); xyPlot.setDomainCrosshairLockedOnData(true); xyPlot.setRangeCrosshairVisible(true); chart.setAntiAlias(true); return chart; }
From source file:com.o4s.sarGrapher.graph.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//from ww w .j a va 2s . c om * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { TimeSeriesCollection dataset = new TimeSeriesCollection(); String title = ""; String ytitle = ""; int width = 400; int height = 300; String graphType = "LINE"; Boolean useSSH = false; HttpSession session = request.getSession(); if (session != null && session.getAttribute("jsch") != null) { useSSH = true; } for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) { String name = e.nextElement().toString(); String val = request.getParameter(name); if (val == null) continue; // seems unnecessary but for code clarity else if (name.equals("title")) title = val; else if (name.equals("ytitle")) ytitle = val; else if (name.equals("width")) width = Integer.parseInt(val); else if (name.equals("height")) height = Integer.parseInt(val); else if (name.equals("useSSH")) useSSH = true; else if (name.equals("type")) graphType = val; else { String[] fflds = val.split(":"); String fn = fflds[0]; String[] flds = fflds[1].split(","); if (fn == null) { Logger.getLogger(graph.class.getName()).log(Level.SEVERE, "Unable to find filename from: {0}={1}", new Object[] { name, val }); return; } CSV c = null; if (useSSH) { CSVs cs = new CSVs(); c = cs.get(fn); } if (c == null) { Logger.getLogger(graph.class.getName()).log(Level.SEVERE, "Unable to find CSV: {0}", fn); return; } ArrayList ds = new ArrayList(); for (int i = 0; i < flds.length; i++) ds.add(new TimeSeries(name + "." + flds[i])); try { c.open(); do { try { if (!c.next()) break; } catch (Exception ex) { // Missing field if (ex.getMessage().startsWith("Missing fields")) break; Logger.getLogger(graph.class.getName()).log(Level.SEVERE, null, ex); } String heure = (String) c.get("heure"); for (int i = 0; i < flds.length; i++) { Double fv; val = (String) c.get(flds[i]); if (val != null) { fv = Double.parseDouble(val); } else { // try to replace variable String str = flds[i]; for (String s : c.getFields()) { str = str.replaceAll(s, c.get(s).toString()); } Expression exp = new ExpressionBuilder(str).build(); ValidationResult v = exp.validate(); String errorMsg = ""; if (!v.isValid()) { for (String s : v.getErrors()) { errorMsg += (errorMsg.isEmpty() ? "" : ",") + s; } if (!errorMsg.isEmpty()) { Logger.getLogger(graph.class.getName()).log(Level.SEVERE, "Syntax ERROR or missing variables: {0}", errorMsg); } } fv = exp.evaluate(); } //dataset.addValue(fv,flds[i],heure); Date dt = new SimpleDateFormat("HH:mm:ss").parse(heure); ((TimeSeries) ds.get(i)).addOrUpdate(new Minute(dt), fv); } } while (true); } catch (Exception ex) { Logger.getLogger(graph.class.getName()).log(Level.SEVERE, null, ex); } for (int i = 0; i < flds.length; i++) dataset.addSeries((TimeSeries) ds.get(i)); } } //JFreeChart barChart = ChartFactory.createBarChart(title, "", "Unit vendue", dataset, PlotOrientation.VERTICAL, true, true, false); //JFreeChart barChart = ChartFactory.createTimeSeriesChart(title, title, dataDir, dataset);// .createStackedBarChart(title, "", "", dataset); // JFreeChart timechart = ChartFactory.createTimeSeriesChart( // title, // Title // "Heure", // X-axis Label // "", // Y-axis Label // dataset, // Dataset // true, // Show legend // true, // Use tooltips // false // Generate URLs // ); // Plot p=timechart.getPlot(); XYItemRenderer r; if (graphType.equals("AREA")) { r = new XYAreaRenderer(); } else if (graphType.equals("BAR")) { r = new XYBarRenderer(); } else if (graphType.equals("STACK")) { r = new StackedXYAreaRenderer(); } else { r = new StandardXYItemRenderer(); } final DateAxis domainAxis = new DateAxis("Heure"); domainAxis.setVerticalTickLabels(false); domainAxis.setDateFormatOverride(new SimpleDateFormat("HH:mm")); domainAxis.setLowerMargin(0.01); domainAxis.setUpperMargin(0.01); final ValueAxis rangeAxis = new NumberAxis(ytitle); final XYPlot plot = new XYPlot(dataset, domainAxis, rangeAxis, r); final JFreeChart chart = new JFreeChart(title, plot); // JFreeChart timechart=null; // if( graphType.equals("AREA") ){ // timechart = ChartFactory.createXYAreaChart(title, "Heure", "", dataset, PlotOrientation.VERTICAL, true, true, false); // } else if( graphType.equals("BAR") ){ // timechart = ChartFactory.createXYBarChart(title, "Heure", true, "", dataset, PlotOrientation.VERTICAL, true, true, false); // } else { // timechart = ChartFactory.createXYLineChart(title, "Heure", "", dataset, PlotOrientation.VERTICAL, true, true, false); // } response.setContentType("image/png"); OutputStream out = response.getOutputStream(); ChartUtilities.writeChartAsPNG(out, chart, width, height); }
From source file:uk.co.petertribble.jkstat.gui.KstatSetChart.java
private void init(List<String> statistics) { dataset = new TimeSeriesCollection(); tsmap = new HashMap<String, TimeSeries>(); kMap = new HashMap<Kstat, ChartableKstat>(); for (Kstat ks : kss.getKstats()) { kMap.put(ks, new ChartableKstat(jkstat, ks)); for (String statistic : KstatUtil.numericStatistics(jkstat, ks)) { String s = ks.getTriplet() + ":" + statistic; tsmap.put(s, new TimeSeries(s)); }//from w ww . j a v a 2 s . co m for (String statistic : statistics) { dataset.addSeries(tsmap.get(ks.getTriplet() + ":" + statistic)); } } if (jkstat instanceof SequencedJKstat) { readAll(((SequencedJKstat) jkstat).newInstance()); } else { setMaxAge(maxage); updateAccessory(); } String ylabel = showdelta ? KstatResources.getString("CHART.RATE") : KstatResources.getString("CHART.VALUE"); chart = ChartFactory.createTimeSeriesChart(kss.toString() == null ? "statistic" : kss.toString(), KstatResources.getString("CHART.TIME"), ylabel, dataset, true, true, false); setAxes(); if (!(jkstat instanceof SequencedJKstat)) { startLoop(); } }
From source file:org.squale.squaleweb.util.graph.AreaMaker.java
/** * Constructeur avec le titre du diagramme et les titres des axes * /*from w w w . j a va 2 s .c om*/ * @param pTitle titre du diagramme (peut etre <code>null</code>) * @param pTimeAxisLabel titre de l'axe temporel (peut etre <code>null</code>) * @param pValueAxisLabel titre de l'axe des valeurs (peut etre <code>null</code>) */ public AreaMaker(String pTitle, String pTimeAxisLabel, String pValueAxisLabel) { mDataSet = new TimeSeriesCollection(); mTitle = pTitle; mXLabel = pTimeAxisLabel; mYLabel = pValueAxisLabel; mDateFormat = new SimpleDateFormat(DATE_FORMAT); }