List of usage examples for org.jfree.data.time TimeSeries TimeSeries
public TimeSeries(Comparable name, Class timePeriodClass)
From source file:eu.hydrologis.jgrass.charting.impl.JGrassXYTimeLineChart.java
/** * A line chart creator basing on series made up two values per row. More series, independing * one from the other are supported.// ww w . j av a 2 s . c o m * * @param chartValues - a hashmap containing as keys the name of the series and as values the * double[][] representing the data. In this case the x value is assumed to ge a date. * Important: the data matrix has to be passed as two rows (not two columns) */ public JGrassXYTimeLineChart(LinkedHashMap<String, double[][]> chartValues, Class<RegularTimePeriod> timeClass) { try { chartSeries = new TimeSeries[chartValues.size()]; constructor = timeClass.getConstructor(Date.class); final Iterator<String> it = chartValues.keySet().iterator(); int count = 0; while (it.hasNext()) { final String key = it.next(); final double[][] values = chartValues.get(key); chartSeries[count] = new TimeSeries(key, timeClass); for (int i = 0; i < values[0].length; i++) { // important: the data matrix has to be passed as two rows (not // two columns) double val = values[1][i]; if (isNovalue(val)) continue; chartSeries[count].add(constructor.newInstance(new Date((long) values[0][i])), val); } count++; } lineDataset = new TimeSeriesCollection(); for (int i = 0; i < chartSeries.length; i++) { lineDataset.addSeries(chartSeries[i]); } lineDataset.setXPosition(TimePeriodAnchor.MIDDLE); } catch (Exception e) { ChartPlugin.log("ChartPlugin problem", e); //$NON-NLS-1$ } }
From source file:edu.ucla.stat.SOCR.chart.demo.XYBarChartDemo2.java
protected IntervalXYDataset createDataset(boolean isDemo) { if (isDemo) { TimeSeries series1 = new TimeSeries("Series 1", Day.class); series1.add(new Day(1, 1, 2003), 54.3); series1.add(new Day(2, 1, 2003), 20.3); series1.add(new Day(3, 1, 2003), 43.4); series1.add(new Day(4, 1, 2003), -12.0); TimeSeries series2 = new TimeSeries("Series 2", Day.class); series2.add(new Day(1, 1, 2003), 8.0); series2.add(new Day(2, 1, 2003), 16.0); series2.add(new Day(3, 1, 2003), 21.0); series2.add(new Day(4, 1, 2003), 5.0); TimeSeriesCollection dataset = new TimeSeriesCollection(); //dataset.setDomainIsPointsInTime(false); dataset.addSeries(series1);/*from w w w .j a v a 2s . co m*/ dataset.addSeries(series2); return dataset; } else { setArrayFromTable(); String[][] x = new String[xyLength][independentVarLength]; double[][] y = new double[xyLength][dependentVarLength]; int[][] skipy = new int[xyLength][dependentVarLength]; for (int index = 0; index < independentVarLength; index++) for (int i = 0; i < xyLength; i++) x[i][index] = indepValues[i][index]; for (int index = 0; index < dependentVarLength; index++) for (int i = 0; i < xyLength; i++) { if (depValues[i][index] == null || depValues[i][index].length() == 0) skipy[i][index] = 1; else y[i][index] = Double.parseDouble(depValues[i][index]); } // create the dataset... TimeSeriesCollection collection = new TimeSeriesCollection(); TimeSeries series; for (int ind = 0; ind < independentVarLength; ind++) { int start_ind = independentHeaders[ind].lastIndexOf(":"); if (start_ind < 0) start_ind = 0; String serieName = independentHeaders[ind].substring(0, start_ind); if (serieName.length() == 0) serieName = "Serie" + ind; series = new TimeSeries(serieName, Day.class); //TimeSeries("Executions", "Year", "Count", Year.class); for (int i = 0; i < xyLength; i++) { if (x[i][ind] != null && skipy[i][ind] != 1) { series.add(DateParser.parseDay(x[i][ind]), y[i][ind]); } } //collection.setDomainIsPointsInTime(false); collection.addSeries(series); } return collection; } }
From source file:eu.hydrologis.jgrass.charting.impl.JGrassXYTimeBarChart.java
/** * A line chart creator basing on series made up two values per row. More series, independing * one from the other are supported./* w w w.j a va2 s . com*/ * * @param chartValues - a hashmap containing as keys the name of the series and as values the * double[][] representing the data. In this case the x value is assumed to ge a date. * Important: the data matrix has to be passed as two rows (not two columns) * @param barWidth TODO */ public JGrassXYTimeBarChart(LinkedHashMap<String, double[][]> chartValues, Class<RegularTimePeriod> timeClass, double barWidth) { try { chartSeries = new TimeSeries[chartValues.size()]; constructor = timeClass.getConstructor(Date.class); final Iterator<String> it = chartValues.keySet().iterator(); int count = 0; while (it.hasNext()) { final String key = it.next(); final double[][] values = chartValues.get(key); chartSeries[count] = new TimeSeries(key, timeClass); for (int i = 0; i < values[0].length; i++) { // important: the data matrix has to be passed as two rows (not // two columns) chartSeries[count].add(constructor.newInstance(new Date((long) values[0][i])), values[1][i]); } count++; } lineDataset = new TimeSeriesCollection(); for (int i = 0; i < chartSeries.length; i++) { lineDataset.addSeries(chartSeries[i]); } lineDataset.setXPosition(TimePeriodAnchor.MIDDLE); if (barWidth != -1) dataset = new XYBarDataset(lineDataset, barWidth); } catch (Exception e) { ChartPlugin.log("ChartPlugin", e); //$NON-NLS-1$ } }
From source file:nu.nethome.home.items.web.GraphServlet.java
/** * This is the main enterence point of the class. This is called when a http request is * routed to this servlet.//from www. j a v a 2 s.co m */ public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ServletOutputStream p = res.getOutputStream(); Date startTime = null; Date stopTime = null; // Analyse arguments String fileName = req.getParameter("file"); if (fileName != null) fileName = getFullFileName(fromURL(fileName)); String startTimeString = req.getParameter("start"); String stopTimeString = req.getParameter("stop"); try { if (startTimeString != null) { startTime = m_Format.parse(startTimeString); } if (stopTimeString != null) { stopTime = m_Format.parse(stopTimeString); } } catch (ParseException e1) { e1.printStackTrace(); } String look = req.getParameter("look"); if (look == null) look = ""; TimeSeries timeSeries = new TimeSeries("Data", Minute.class); // Calculate time window Calendar cal = Calendar.getInstance(); Date currentTime = cal.getTime(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); Date startOfDay = cal.getTime(); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); Date startOfWeek = cal.getTime(); cal.set(Calendar.DAY_OF_MONTH, 1); Date startOfMonth = cal.getTime(); cal.set(Calendar.MONTH, Calendar.JANUARY); Date startOfYear = cal.getTime(); // if (startTime == null) startTime = startOfWeek; if (stopTime == null) stopTime = currentTime; if (startTime == null) startTime = new Date(stopTime.getTime() - 1000L * 60L * 60L * 24L * 2L); try { // Open the data file File logFile = new File(fileName); Scanner fileScanner = new Scanner(logFile); Long startTimeMs = startTime.getTime(); Long month = 1000L * 60L * 60L * 24L * 30L; boolean doOptimize = true; boolean justOptimized = false; try { while (fileScanner.hasNext()) { try { // Get next log entry String line = fileScanner.nextLine(); if (line.length() > 21) { // Adapt the time format String minuteTime = line.substring(0, 16).replace('.', '-'); // Parse the time stamp Minute min = Minute.parseMinute(minuteTime); // Ok, this is an ugly optimization. If the current time position in the file // is more than a month (30 days) ahead of the start of the time window, we // quick read two weeks worth of data, assuming that there is 4 samples per hour. // This may lead to scanning past start of window if there are holes in the data // series. if (doOptimize && ((startTimeMs - min.getFirstMillisecond()) > month)) { for (int i = 0; (i < (24 * 4 * 14)) && fileScanner.hasNext(); i++) { fileScanner.nextLine(); } justOptimized = true; continue; } // Detect if we have scanned past the window start position just after an optimization scan. // If this is the case it may be because of the optimization. In that case we have to switch // optimization off and start over. if ((min.getFirstMillisecond() > startTimeMs) && doOptimize && justOptimized) { logFile = new File(fileName); fileScanner = new Scanner(logFile); doOptimize = false; continue; } justOptimized = false; // Check if value is within time window if ((min.getFirstMillisecond() > startTimeMs) && (min.getFirstMillisecond() < stopTime.getTime())) { // Parse the value double value = Double.parseDouble((line.substring(20)).replace(',', '.')); // Add the entry timeSeries.add(min, value); doOptimize = false; } } } catch (SeriesException se) { // Bad entry, for example due to duplicates at daylight saving time switch } catch (NumberFormatException nfe) { // Bad number format in a line, try to continue } } } catch (Exception e) { System.out.println(e.toString()); } finally { fileScanner.close(); } } catch (FileNotFoundException f) { System.out.println(f.toString()); } // Create a collection for plotting TimeSeriesCollection data = new TimeSeriesCollection(); data.addSeries(timeSeries); JFreeChart chart; int xSize = 750; int ySize = 450; // Customize colors and look of the Graph. if (look.equals("mobtemp")) { // Look for the mobile GUI chart = ChartFactory.createTimeSeriesChart(null, null, null, data, false, false, false); XYPlot plot = chart.getXYPlot(); ValueAxis timeAxis = plot.getDomainAxis(); timeAxis.setAxisLineVisible(false); ValueAxis valueAxis = plot.getRangeAxis(0); valueAxis.setAxisLineVisible(false); xSize = 175; ySize = 180; } else { // Create a Chart with time range as heading SimpleDateFormat localFormat = new SimpleDateFormat(); String heading = localFormat.format(startTime) + " - " + localFormat.format(stopTime); chart = ChartFactory.createTimeSeriesChart(heading, null, null, data, false, false, false); Paint background = new Color(0x9D8140); chart.setBackgroundPaint(background); TextTitle title = chart.getTitle(); // fix title Font titleFont = title.getFont(); titleFont = titleFont.deriveFont(Font.PLAIN, (float) 14.0); title.setFont(titleFont); title.setPaint(Color.darkGray); XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(background); plot.setDomainGridlinePaint(Color.darkGray); ValueAxis timeAxis = plot.getDomainAxis(); timeAxis.setAxisLineVisible(false); ValueAxis valueAxis = plot.getRangeAxis(0); valueAxis.setAxisLineVisible(false); plot.setRangeGridlinePaint(Color.darkGray); XYItemRenderer renderer = plot.getRenderer(0); renderer.setSeriesPaint(0, Color.darkGray); xSize = 750; ySize = 450; } try { res.setContentType("image/png"); res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"); res.setHeader("Pragma", "no-cache"); res.setStatus(HttpServletResponse.SC_OK); ChartUtilities.writeChartAsPNG(p, chart, xSize, ySize); } catch (IOException e) { System.err.println("Problem occurred creating chart."); } p.flush(); p.close(); return; }
From source file:org.jfree.chart.demo.MovingAverageDemo.java
/** * Creates a dataset, one series containing unit trust prices, the other a moving average. * * @return the dataset.//from w w w. j a v a2s .co m */ public XYDataset createDataset() { final TimeSeries s1 = new TimeSeries("L&G European Index Trust", Month.class); s1.add(new Month(2, 2001), 181.8); s1.add(new Month(3, 2001), 167.3); s1.add(new Month(4, 2001), 153.8); s1.add(new Month(5, 2001), 167.6); s1.add(new Month(6, 2001), 158.8); s1.add(new Month(7, 2001), 148.3); s1.add(new Month(8, 2001), 153.9); s1.add(new Month(9, 2001), 142.7); s1.add(new Month(10, 2001), 123.2); s1.add(new Month(11, 2001), 131.8); s1.add(new Month(12, 2001), 139.6); s1.add(new Month(1, 2002), 142.9); s1.add(new Month(2, 2002), 138.7); s1.add(new Month(3, 2002), 137.3); s1.add(new Month(4, 2002), 143.9); s1.add(new Month(5, 2002), 139.8); s1.add(new Month(6, 2002), 137.0); s1.add(new Month(7, 2002), 132.8); // **************************************************************************** // * JFREECHART DEVELOPER GUIDE * // * The JFreeChart Developer Guide, written by David Gilbert, is available * // * to purchase from Object Refinery Limited: * // * * // * http://www.object-refinery.com/jfreechart/guide.html * // * * // * Sales are used to provide funding for the JFreeChart project - please * // * support us so that we can continue developing free software. * // **************************************************************************** final TimeSeries s2 = MovingAverage.createMovingAverage(s1, "Six Month Moving Average", 6, 0); final TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); return dataset; }
From source file:com.joey.software.memoryToolkit.MemoryUsagePanel.java
/** * Creates a new application.// w w w . j a v a 2s . co m * * @param historyCount * the history count (in milliseconds). */ public MemoryUsagePanel(int historyCount, int interval) { super(new BorderLayout()); // create two series that automatically discard data more than 30 // seconds old... this.total = new TimeSeries("Total Memory", Millisecond.class); this.total.setMaximumItemCount(historyCount); this.free = new TimeSeries("Free Memory", Millisecond.class); this.free.setMaximumItemCount(historyCount); this.used = new TimeSeries("Used Memory", Millisecond.class); this.used.setMaximumItemCount(historyCount); this.max = new TimeSeries("Used Memory", Millisecond.class); this.max.setMaximumItemCount(historyCount); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(this.total); dataset.addSeries(this.free); dataset.addSeries(this.used); dataset.addSeries(this.max); DateAxis domain = new DateAxis("Time"); NumberAxis range = new NumberAxis("Memory"); domain.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12)); range.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12)); domain.setLabelFont(new Font("SansSerif", Font.PLAIN, 14)); range.setLabelFont(new Font("SansSerif", Font.PLAIN, 14)); XYItemRenderer renderer = new XYLineAndShapeRenderer(true, false); renderer.setSeriesPaint(0, Color.red); renderer.setSeriesPaint(1, Color.green); renderer.setSeriesPaint(2, Color.black); renderer.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL)); XYPlot plot = new XYPlot(dataset, domain, range, renderer); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); domain.setAutoRange(true); domain.setLowerMargin(0.0); domain.setUpperMargin(0.0); domain.setTickLabelsVisible(true); range.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); JFreeChart chart = new JFreeChart("JVM Memory Usage", new Font("SansSerif", Font.BOLD, 24), plot, true); chart.setBackgroundPaint(Color.white); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4), BorderFactory.createLineBorder(Color.black))); add(chartPanel); gen = new DataGenerator(interval); }
From source file:org.jfree.chart.demo.TimeSeriesChartDemo1.java
/** * Creates a dataset, consisting of two series of monthly data. * * @return The dataset.//w w w . j a va 2 s . co m */ private static XYDataset createDataset() { TimeSeries s1 = new TimeSeries("L&G European Index Trust", Month.class); s1.add(new Month(2, 2001), 181.8); s1.add(new Month(3, 2001), 167.3); s1.add(new Month(4, 2001), 153.8); s1.add(new Month(5, 2001), 167.6); s1.add(new Month(6, 2001), 158.8); s1.add(new Month(7, 2001), 148.3); s1.add(new Month(8, 2001), 153.9); s1.add(new Month(9, 2001), 142.7); s1.add(new Month(10, 2001), 123.2); s1.add(new Month(11, 2001), 131.8); s1.add(new Month(12, 2001), 139.6); s1.add(new Month(1, 2002), 142.9); s1.add(new Month(2, 2002), 138.7); s1.add(new Month(3, 2002), 137.3); s1.add(new Month(4, 2002), 143.9); s1.add(new Month(5, 2002), 139.8); s1.add(new Month(6, 2002), 137.0); s1.add(new Month(7, 2002), 132.8); TimeSeries s2 = new TimeSeries("L&G UK Index Trust", Month.class); s2.add(new Month(2, 2001), 129.6); s2.add(new Month(3, 2001), 123.2); s2.add(new Month(4, 2001), 117.2); s2.add(new Month(5, 2001), 124.1); s2.add(new Month(6, 2001), 122.6); s2.add(new Month(7, 2001), 119.2); s2.add(new Month(8, 2001), 116.5); s2.add(new Month(9, 2001), 112.7); s2.add(new Month(10, 2001), 101.5); s2.add(new Month(11, 2001), 106.1); s2.add(new Month(12, 2001), 110.3); s2.add(new Month(1, 2002), 111.7); s2.add(new Month(2, 2002), 111.0); s2.add(new Month(3, 2002), 109.6); s2.add(new Month(4, 2002), 113.2); s2.add(new Month(5, 2002), 111.6); s2.add(new Month(6, 2002), 108.8); s2.add(new Month(7, 2002), 101.6); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(s1); dataset.addSeries(s2); dataset.setDomainIsPointsInTime(true); return dataset; }
From source file:net.sourceforge.openforecast.examples.ForecastingChartDemo.java
/** * Creates a dataset, consisting of two series of monthly data. * @return the dataset.//from ww w . ja v a 2 s .c om */ public XYDataset createDataset() { TimeSeries observations = new TimeSeries("Quarterly Sales", Quarter.class); observations.add(new Quarter(1, 1990), 362.0); observations.add(new Quarter(2, 1990), 385.0); observations.add(new Quarter(3, 1990), 432.0); observations.add(new Quarter(4, 1990), 341.0); observations.add(new Quarter(1, 1991), 382.0); observations.add(new Quarter(2, 1991), 409.0); observations.add(new Quarter(3, 1991), 498.0); observations.add(new Quarter(4, 1991), 387.0); observations.add(new Quarter(1, 1992), 473.0); observations.add(new Quarter(2, 1992), 513.0); observations.add(new Quarter(3, 1992), 582.0); observations.add(new Quarter(4, 1992), 474.0); observations.add(new Quarter(1, 1993), 544.0); observations.add(new Quarter(2, 1993), 582.0); observations.add(new Quarter(3, 1993), 681.0); observations.add(new Quarter(4, 1993), 557.0); observations.add(new Quarter(1, 1994), 628.0); observations.add(new Quarter(2, 1994), 707.0); observations.add(new Quarter(3, 1994), 773.0); observations.add(new Quarter(4, 1994), 592.0); observations.add(new Quarter(1, 1995), 627.0); observations.add(new Quarter(2, 1995), 725.0); observations.add(new Quarter(3, 1995), 854.0); observations.add(new Quarter(4, 1995), 661.0); fc = new TimeSeries("Forecast values", Quarter.class); fc.add(new Quarter(1, 1990), 0.0); fc.add(new Quarter(2, 1990), 0.0); fc.add(new Quarter(3, 1990), 0.0); fc.add(new Quarter(4, 1990), 0.0); fc.add(new Quarter(1, 1991), 0.0); fc.add(new Quarter(2, 1991), 0.0); fc.add(new Quarter(3, 1991), 0.0); fc.add(new Quarter(4, 1991), 0.0); fc.add(new Quarter(1, 1992), 0.0); fc.add(new Quarter(2, 1992), 0.0); fc.add(new Quarter(3, 1992), 0.0); fc.add(new Quarter(4, 1992), 0.0); fc.add(new Quarter(1, 1993), 0.0); fc.add(new Quarter(2, 1993), 0.0); fc.add(new Quarter(3, 1993), 0.0); fc.add(new Quarter(4, 1993), 0.0); fc.add(new Quarter(1, 1994), 0.0); fc.add(new Quarter(2, 1994), 0.0); fc.add(new Quarter(3, 1994), 0.0); fc.add(new Quarter(4, 1994), 0.0); fc.add(new Quarter(1, 1995), 0.0); fc.add(new Quarter(2, 1995), 0.0); fc.add(new Quarter(3, 1995), 0.0); fc.add(new Quarter(4, 1995), 0.0); fc.add(new Quarter(1, 1996), 0.0); fc.add(new Quarter(2, 1996), 0.0); fc.add(new Quarter(3, 1996), 0.0); fc.add(new Quarter(4, 1996), 0.0); fc.add(new Quarter(1, 1997), 0.0); fc.add(new Quarter(2, 1997), 0.0); fc.add(new Quarter(3, 1997), 0.0); fc.add(new Quarter(4, 1997), 0.0); fc.add(new Quarter(1, 1998), 0.0); fc.add(new Quarter(2, 1998), 0.0); fc.add(new Quarter(3, 1998), 0.0); fc.add(new Quarter(4, 1998), 0.0); DataSet initDataSet = getDataSet(observations, 0, 100); TimeSeries naiveSeries = getForecastTimeSeries(new NaiveForecastingModel(), initDataSet, 1, 25, "Naive forecast"); TimeSeries ma4Series = getForecastTimeSeries(new MovingAverageModel(4), initDataSet, 4, 28, "4 Period Moving Average"); TimeSeries ma8Series = getForecastTimeSeries(new MovingAverageModel(8), initDataSet, 8, 32, "8 Period Moving Average"); TimeSeries regressionSeries = getForecastTimeSeries(new RegressionModel("t"), initDataSet, 0, 100, "Linear regression"); TimeSeries polyRegressSeries = getForecastTimeSeries(new PolynomialRegressionModel("t", 4), initDataSet, 0, 100, "4th order polynomial regression"); TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(observations); dataset.addSeries(naiveSeries); dataset.addSeries(ma4Series); dataset.addSeries(ma8Series); dataset.addSeries(regressionSeries); dataset.addSeries(polyRegressSeries); return dataset; }
From source file:de.suse.swamp.modules.scheduledjobs.Statistics.java
/** * Generating the graphs that show the amount of running finished wfs over the time. *///from ww w . j a v a 2 s . com protected void generateWorkflowGraph(String templateName, Date startDate, Date endDate) throws Exception { List stats = StatisticStorage.loadStats(templateName, startDate, endDate); // only generate if we have stats: if (stats != null && stats.size() > 0) { TimeSeriesCollection dataset = new TimeSeriesCollection(); TimeSeriesCollection avgdataset = new TimeSeriesCollection(); TimeSeries serie = new TimeSeries("running workflows", Day.class); TimeSeries avgserie = new TimeSeries("average age", Day.class); for (Iterator datait = stats.iterator(); datait.hasNext();) { Dbstatistics statisticItem = (Dbstatistics) datait.next(); serie.addOrUpdate(new Day(statisticItem.getDate()), statisticItem.getRunningcount()); avgserie.addOrUpdate(new Day(statisticItem.getDate()), statisticItem.getAvgage() / (3600 * 24)); } dataset.addSeries(serie); avgdataset.addSeries(avgserie); JFreeChart chart = ChartFactory.createTimeSeriesChart("Running " + templateName + " workflows", "Date", "running workflows", dataset, false, false, false); // modify chart appearance chart.setBackgroundImageAlpha(0.5f); XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.getRangeAxis().setLabelPaint(Color.blue); // add the second line: final NumberAxis axis2 = new NumberAxis("Avg. age in days"); axis2.setLabelPaint(Color.red); plot.setRangeAxis(1, axis2); plot.setDataset(1, avgdataset); plot.mapDatasetToRangeAxis(1, 1); final XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(); renderer2.setDrawOutlines(false); renderer2.setDrawSeriesLineAsPath(true); renderer2.setBaseShapesVisible(false); plot.setRenderer(1, renderer2); File image = new File(statPath + fs + templateName + ".png"); if (image.exists()) image.delete(); try { ChartUtilities.saveChartAsPNG(image, chart, 750, 200); } catch (Exception e) { Logger.ERROR("Error generating graph for " + templateName + ", e: " + e.getMessage()); e.printStackTrace(); throw e; } } }
From source file:org.miloss.fgsms.services.rs.impl.reports.AvailabilityByService.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 av a2 s.c o m*/ 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>Number of status changes</th><th>Percent Uptime</th><th>Percent Downtime</th></tr>"); DecimalFormat percentFormat = new DecimalFormat("###.#####"); TimeSeriesCollection col = new TimeSeriesCollection(); for (int i = 0; i < urls.size(); i++) { //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))); TimeSeries s1 = new TimeSeries(url, org.jfree.data.time.Millisecond.class); try { data.append("<tr><td>").append(url).append("</td>"); List<StatusRecordsExt> records = getStatusRecords(urls.get(i), range, con); //special case, no status records available if (records == null || records.isEmpty()) { data.append("<td>-</td><td>-</td></tr>"); continue; } double uptime = getUptimePercentage(records, range); data.append("<td>").append(records.size() + "").append("</td><td>") .append(percentFormat.format(uptime)).append("</td><td>") .append(percentFormat.format(100 - uptime)).append("</td></tr>"); TimeSeriesDataItem t = null; for (int k = 0; k < records.size(); k++) { if (records.get(k).status) { try { t = new TimeSeriesDataItem(new Millisecond(records.get(k).gcal.getTime()), 1); s1.addOrUpdate(t); } catch (Exception ex) { log.log(Level.WARN, null, ex); } } else { try { t = new TimeSeriesDataItem(new Millisecond(records.get(k).gcal.getTime()), 0); s1.addOrUpdate(t); } catch (Exception ex) { log.log(Level.WARN, null, ex); } } col.addSeries(s1); } } catch (Exception ex) { log.log(Level.ERROR, "Error opening or querying the database.", ex); } } chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Status", col, true, false, false); data.append("</table>"); try { ChartUtilities.saveChartAsPNG(new File( path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart, 1500, 800); 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); } }