List of usage examples for org.jfree.chart ChartUtilities writeChartAsPNG
public static void writeChartAsPNG(OutputStream out, JFreeChart chart, int width, int height) throws IOException
From source file:org.openmrs.web.servlet.ShowGraphServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) *///from w w w .j a v a2s. c o m @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { JFreeChart chart = getChart(request); // get the height and width of the graph String widthString = request.getParameter("width"); String heightString = request.getParameter("height"); Integer width; Integer height; if (widthString != null && widthString.length() > 0) { width = Integer.parseInt(widthString); } else { width = 500; } if (heightString != null && heightString.length() > 0) { height = Integer.parseInt(heightString); } else { height = 300; } // get the requested mime type of the graph String mimeType = request.getParameter("mimeType"); if (mimeType == null) { mimeType = PNG_MIME_TYPE; } // Modify response to disable caching response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); // Write chart out to response as image try { if (JPG_MIME_TYPE.equalsIgnoreCase(mimeType)) { response.setContentType(JPG_MIME_TYPE); ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, width, height); } else if (PNG_MIME_TYPE.equalsIgnoreCase(mimeType)) { response.setContentType(PNG_MIME_TYPE); ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart, width, height); } else { throw new APIException("unsupported.mime.type", (Object[]) null); } } catch (IOException e) { // if its tomcat and the user simply navigated away from the page, don't throw an error if (e.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) { // do nothing } else { log.error("Error class name: " + e.getClass().getName()); log.error("Unable to write chart", e); } } } // Add error handling above and remove this try/catch catch (Exception e) { log.error("An unknown expected exception was thrown while rendering a graph", e); } }
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 .jav a 2 s .com*/ 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: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(); }/* w w w .j a v a2 s . 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:net.sqs2.omr.result.export.chart.ChartImageWriter.java
public void savePieChart(OutputStream outputStream, DefaultPieDataset dataSet) { String title = ""; boolean showLegend = true; boolean tooltips = true; boolean urls = false; JFreeChart chart = ChartFactory.createPieChart(title, dataSet, showLegend, tooltips, urls); PiePlot piePlot = (PiePlot) chart.getPlot(); // chart.getLegend().setLegendItemGraphicEdge(RectangleEdge.RIGHT); // chart.getLegend().setLegendItemGraphicLocation(RectangleAnchor.RIGHT); chart.getLegend().setPosition(RectangleEdge.RIGHT); setSectionPaint(dataSet, piePlot);// w ww. j ava 2s . co m try { ChartUtilities.writeChartAsPNG(outputStream, chart, this.width, this.height); } catch (IOException ioEx) { ioEx.printStackTrace(); } }
From source file:org.psystems.dicom.browser.server.stat.StatClientRequestsChartServlet2.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("image/png"); OutputStream outputStream = response.getOutputStream(); CategoryDataset dataset = createDataset(); JFreeChart chart = getChart(dataset); int width = 800; int height = 250; ChartUtilities.writeChartAsPNG(outputStream, chart, width, height); }
From source file:com.himtech.googlechart.GglPieChart.java
@RequestMapping(value = "/piechartJfree", method = RequestMethod.GET) public void drawPieChartJfree(ModelMap model, HttpServletResponse response) { response.setContentType("image/png"); PieDataset dataSet = createDataSet(); JFreeChart pieChart = createChart(dataSet, "Server Details"); //model.addAttribute("pieUrl", pieChart.toString()); try {/*from w w w .j av a 2s . co m*/ ChartUtilities.writeChartAsPNG(response.getOutputStream(), pieChart, 750, 400); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.bitplan.vzjava.Plot.java
/** * save me as a png file/*from w ww . ja v a 2s .c o m*/ * * @param file * @param width * @param height * @throws Exception */ public void saveAsPng(File file, int width, int height) throws Exception { FileOutputStream outputstream = new FileOutputStream(file); ChartUtilities.writeChartAsPNG(outputstream, getChart(), width, height); outputstream.close(); }
From source file:org.geoserver.wms.ncwms.GetTimeSeriesResponse.java
@SuppressWarnings("rawtypes") private void writeChart(GetFeatureInfoRequest request, FeatureCollectionType results, OutputStream output, String mimeType) throws IOException { final TimeSeries series = new TimeSeries("time", Millisecond.class); String valueAxisLabel = "Value"; String title = "Time series"; final String timeaxisLabel = "Date / time"; final List collections = results.getFeature(); if (collections.size() > 0) { SimpleFeatureCollection fc = (SimpleFeatureCollection) collections.get(0); title += " of " + fc.getSchema().getName().getLocalPart(); valueAxisLabel = fc.getSchema().getDescription().toString(); try (SimpleFeatureIterator fi = fc.features()) { while (fi.hasNext()) { SimpleFeature f = fi.next(); Date date = (Date) f.getAttribute("date"); Double value = (Double) f.getAttribute("value"); series.add(new Millisecond(date), value); }/* w ww .j av a 2s. c o m*/ } } XYDataset dataset = new TimeSeriesCollection(series); JFreeChart chart = ChartFactory.createTimeSeriesChart(title, timeaxisLabel, valueAxisLabel, dataset, false, false, false); XYPlot plot = (XYPlot) chart.getPlot(); plot.setRenderer(new XYLineAndShapeRenderer()); if (mimeType.startsWith("image/png")) { ChartUtilities.writeChartAsPNG(output, chart, IMAGE_WIDTH, IMAGE_HEIGHT); } else if (mimeType.equals("image/jpg") || mimeType.equals("image/jpeg")) { ChartUtilities.writeChartAsJPEG(output, chart, IMAGE_WIDTH, IMAGE_HEIGHT); } }
From source file:edu.ku.brc.specify.toycode.mexconabio.CollectionStats.java
/** * @param response/* w w w . j av a 2 s . c o m*/ * @param type * @param alphaList * @param title * @param xTitle * @param yTitle */ protected void createChart(final CollStatInfo csi, final Vector<Pair<String, Integer>> list, final String xTitle, final String yTitle) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for (Pair<String, Integer> p : list) { dataset.addValue(p.second, p.first, ""); } //if (StringUtils.isEmpty(csi.getInstName())) //{ // csi.setInstName(getProviderNameFromInstCode(csi.getProviderId())); //} JFreeChart chart = ChartFactory.createBarChart(csi.getTitle(), xTitle, yTitle, dataset, PlotOrientation.VERTICAL, true, true, false); //chart.getCategoryPlot().setRenderer(new CustomColorBarChartRenderer()); chart.setBackgroundPaint(new Color(228, 243, 255)); try { Integer hashCode = csi.hashCode(); csi.setChartFileName(hashCode + ".png"); DataOutputStream dos = new DataOutputStream( new FileOutputStream(new File("reports/charts/" + csi.getChartFileName()))); ChartUtilities.writeChartAsPNG(dos, chart, 700, 600); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.lsug.quota.portlet.ServerQuotaPortlet.java
@Override public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException { String type = ParamUtil.getString(resourceRequest, "type", "currentSize"); StringBundler sb = new StringBundler(5); JFreeChart jFreeChart = null;/* ww w. j a v a 2 s .c o m*/ if (type.equals("currentSize")) { long classNameId = PortalUtil.getClassNameId(Company.class.getName()); String orderByCol = "quotaUsed"; String orderByType = "desc"; OrderByComparator orderByComparator = QuotaUtil.getQuotaOrderByComparator(orderByCol, orderByType); DefaultPieDataset pieDataset = new DefaultPieDataset(); try { List<Quota> listCompanyQuota = QuotaLocalServiceUtil.getQuotaByClassNameId(classNameId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, orderByComparator); for (Quota quota : listCompanyQuota) { if (quota.isEnabled()) { pieDataset.setValue(CompanyLocalServiceUtil.getCompany(quota.getClassPK()).getWebId(), quota.getQuotaUsed()); } } } catch (Exception e) { LOGGER.error(e); throw new PortletException(e); } sb.append(QuotaUtil.getResource(resourceRequest, "server-current-used-size-diagram-title")); jFreeChart = getCurrentSizeJFreeChart(sb.toString(), pieDataset); } OutputStream outputStream = null; resourceResponse.setContentType(ContentTypes.IMAGE_PNG); try { outputStream = resourceResponse.getPortletOutputStream(); ChartUtilities.writeChartAsPNG(outputStream, jFreeChart, 400, 200); } finally { if (outputStream != null) { outputStream.close(); } } }