List of usage examples for org.jfree.chart JFreeChart createBufferedImage
public BufferedImage createBufferedImage(int width, int height)
From source file:Visao.Relatorio.GraficoPerCapta.java
public void create(OutputStream outputStream, JFreeChart chart) throws DocumentException, IOException { Document document = null;/* w w w .ja va 2s . co m*/ PdfWriter writer = null; try { //instantiate document and writer document = new Document(); writer = PdfWriter.getInstance(document, outputStream); //open document document.open(); Image img = Image.getInstance("src\\Imagens\\logo.png"); img.setAlignment(Element.ALIGN_CENTER); document.add(img); //add image int width = 500; int height = 400; BufferedImage bufferedImage = chart.createBufferedImage(width, height); Image image = Image.getInstance(writer, bufferedImage, 1.0f); document.add(image); Font boldFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD); String quebralinha = "\n\nPopulao dos Estados\n\n"; Paragraph preface = new Paragraph(quebralinha, boldFont); preface.setAlignment(Element.ALIGN_CENTER); document.add(preface); PdfPTable table = new PdfPTable(2); PdfPCell pdfWordCell = new PdfPCell(); PdfPCell pdfWordCell1 = new PdfPCell(); Phrase firstLine = new Phrase("UF", new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD)); Phrase secondLine = new Phrase("Populao", new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD)); pdfWordCell.addElement(firstLine); pdfWordCell1.addElement(secondLine); table.addCell(pdfWordCell); table.addCell(pdfWordCell1); table.addCell("SP"); table.addCell(String.valueOf(44396484)); table.addCell("MG"); table.addCell(String.valueOf(20869101)); table.addCell("RJ"); table.addCell(String.valueOf(16550024)); table.addCell("BA"); table.addCell(String.valueOf(15203934)); table.addCell("RS"); table.addCell(String.valueOf(11247972)); table.addCell("PR"); table.addCell(String.valueOf(11163018)); table.addCell("PE"); table.addCell(String.valueOf(9345173)); table.addCell("CE"); table.addCell(String.valueOf(8904459)); table.addCell("PA"); table.addCell(String.valueOf(8175113)); table.addCell("MA"); table.addCell(String.valueOf(6904241)); table.addCell("SC"); table.addCell(String.valueOf(6819190)); table.addCell("GO"); table.addCell(String.valueOf(6610681)); table.addCell("PB"); table.addCell(String.valueOf(3972202)); table.addCell("AM"); table.addCell(String.valueOf(3938336)); table.addCell("ES"); table.addCell(String.valueOf(3929911)); table.addCell("RN"); table.addCell(String.valueOf(3442175)); table.addCell("AL"); table.addCell(String.valueOf(3340932)); table.addCell("MT"); table.addCell(String.valueOf(3270973)); table.addCell("PI"); table.addCell(String.valueOf(3204028)); table.addCell("DF"); table.addCell(String.valueOf(2914830)); table.addCell("MS"); table.addCell(String.valueOf(2651235)); table.addCell("SE"); table.addCell(String.valueOf(2242937)); table.addCell("RO"); table.addCell(String.valueOf(1768204)); table.addCell("TO"); table.addCell(String.valueOf(1515126)); table.addCell("AC"); table.addCell(String.valueOf(803513)); table.addCell("AP"); table.addCell(String.valueOf(766679)); table.addCell("RR"); table.addCell(String.valueOf(505665)); document.add(table); //release resources document.close(); document = null; writer.close(); writer = null; } catch (DocumentException | IOException de) { throw de; } finally { //release resources if (null != document) { try { document.close(); } catch (Exception ex) { } } if (null != writer) { try { writer.close(); } catch (Exception ex) { } } } }
From source file:net.sourceforge.atunes.kernel.controllers.stats.StatsDialogController.java
private void setSongsChart() { DefaultCategoryDataset dataset = getDataSet(HandlerProxy.getRepositoryHandler().getMostPlayedSongs(10)); JFreeChart chart = ChartFactory.createStackedBarChart3D(LanguageTool.getString("SONG_MOST_PLAYED"), null, null, dataset, PlotOrientation.HORIZONTAL, false, false, false); chart.getTitle().setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); chart.setBackgroundPaint(new GradientPaint(0, 0, ColorDefinitions.GENERAL_NON_PANEL_TOP_GRADIENT_COLOR, 0, 200, ColorDefinitions.GENERAL_NON_PANEL_BOTTOM_GRADIENT_COLOR)); chart.setPadding(new RectangleInsets(5, 0, 0, 0)); NumberAxis axis = new NumberAxis(); axis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); axis.setTickLabelFont(new Font(Font.SANS_SERIF, Font.PLAIN, 10)); chart.getCategoryPlot().setRangeAxis(axis); chart.getCategoryPlot().setForegroundAlpha(0.6f); chart.getCategoryPlot().getRenderer().setPaint(Color.GREEN); ((StatsDialog) frameControlled).getSongsChart().setIcon(new ImageIcon(chart.createBufferedImage(710, 250))); }
From source file:net.sourceforge.atunes.kernel.controllers.stats.StatsDialogController.java
private void setAlbumsChart() { DefaultCategoryDataset dataset = getDataSet(HandlerProxy.getRepositoryHandler().getMostPlayedAlbums(10)); JFreeChart chart = ChartFactory.createStackedBarChart3D(LanguageTool.getString("ALBUM_MOST_PLAYED"), null, null, dataset, PlotOrientation.HORIZONTAL, false, false, false); chart.getTitle().setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); chart.setBackgroundPaint(new GradientPaint(0, 0, ColorDefinitions.GENERAL_NON_PANEL_TOP_GRADIENT_COLOR, 0, 200, ColorDefinitions.GENERAL_NON_PANEL_BOTTOM_GRADIENT_COLOR)); chart.setPadding(new RectangleInsets(5, 0, 0, 0)); NumberAxis axis = new NumberAxis(); axis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); axis.setTickLabelFont(new Font(Font.SANS_SERIF, Font.PLAIN, 10)); chart.getCategoryPlot().setRangeAxis(axis); chart.getCategoryPlot().setForegroundAlpha(0.6f); chart.getCategoryPlot().getRenderer().setPaint(Color.GREEN); ((StatsDialog) frameControlled).getAlbumsChart() .setIcon(new ImageIcon(chart.createBufferedImage(710, 250))); }
From source file:net.sourceforge.atunes.kernel.controllers.stats.StatsDialogController.java
private void setArtistsChart() { DefaultCategoryDataset dataset = getDataSet(HandlerProxy.getRepositoryHandler().getMostPlayedArtists(10)); JFreeChart chart = ChartFactory.createStackedBarChart3D(LanguageTool.getString("ARTIST_MOST_PLAYED"), null, null, dataset, PlotOrientation.HORIZONTAL, false, false, false); chart.getTitle().setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); chart.setBackgroundPaint(new GradientPaint(0, 0, ColorDefinitions.GENERAL_NON_PANEL_TOP_GRADIENT_COLOR, 0, 200, ColorDefinitions.GENERAL_NON_PANEL_BOTTOM_GRADIENT_COLOR)); chart.setPadding(new RectangleInsets(5, 0, 0, 0)); NumberAxis axis = new NumberAxis(); axis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); axis.setTickLabelFont(new Font(Font.SANS_SERIF, Font.PLAIN, 10)); chart.getCategoryPlot().setRangeAxis(axis); chart.getCategoryPlot().setForegroundAlpha(0.6f); chart.getCategoryPlot().getRenderer().setPaint(Color.GREEN); ((StatsDialog) frameControlled).getArtistsChart() .setIcon(new ImageIcon(chart.createBufferedImage(710, 250))); }
From source file:org.dcm4chee.dashboard.ui.report.display.DisplayReportDiagramPanel.java
@Override public void onBeforeRender() { super.onBeforeRender(); Connection jdbcConnection = null; try {//from ww w . jav a 2 s . c o m if (report == null) throw new Exception("No report given to render diagram"); jdbcConnection = DatabaseUtils.getDatabaseConnection(report.getDataSource()); ResultSet resultSet = DatabaseUtils.getResultSet(jdbcConnection, report.getStatement(), parameters); ResultSetMetaData metaData = resultSet.getMetaData(); JFreeChart chart = null; resultSet.beforeFirst(); // Line chart - 1 numeric value if (report.getDiagram() == 0) { if (metaData.getColumnCount() != 1) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.1numvalues") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.addValue(resultSet.getDouble(1), metaData.getColumnName(1), String.valueOf(resultSet.getRow())); chart = ChartFactory.createLineChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), new ResourceModel("dashboard.report.reportdiagram.image.row-label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL, true, true, true); // XY Series chart - 2 numeric values } else if (report.getDiagram() == 1) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2numvalues") .wrapOnAssignment(this).getObject()); XYSeries series = new XYSeries(metaData.getColumnName(1) + " / " + metaData.getColumnName(2)); while (resultSet.next()) series.add(resultSet.getDouble(1), resultSet.getDouble(2)); chart = ChartFactory.createXYLineChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(1), metaData.getColumnName(2), new XYSeriesCollection(series), PlotOrientation.VERTICAL, true, true, true); // Category chart - 1 numeric value, 1 comparable value } else if (report.getDiagram() == 2) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.setValue(resultSet.getDouble(1), metaData.getColumnName(1) + " / " + metaData.getColumnName(2), resultSet.getString(2)); chart = new JFreeChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), new CategoryPlot(dataset, new LabelAdaptingCategoryAxis(14, metaData.getColumnName(2)), new NumberAxis(metaData.getColumnName(1)), new CategoryStepRenderer(true))); // Pie chart - 1 numeric value, 1 comparable value (used as category) } else if ((report.getDiagram() == 3) || (report.getDiagram() == 4)) { if (metaData.getColumnCount() != 2) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values") .wrapOnAssignment(this).getObject()); DefaultPieDataset dataset = new DefaultPieDataset(); while (resultSet.next()) dataset.setValue(resultSet.getString(2), resultSet.getDouble(1)); if (report.getDiagram() == 3) // Pie chart 2D chart = ChartFactory .createPieChart(new ResourceModel("dashboard.report.reportdiagram.image.label") .wrapOnAssignment(this).getObject(), dataset, true, true, true); else if (report.getDiagram() == 4) { // Pie chart 3D chart = ChartFactory .createPieChart3D(new ResourceModel("dashboard.report.reportdiagram.image.label") .wrapOnAssignment(this).getObject(), dataset, true, true, true); ((PiePlot3D) chart.getPlot()).setForegroundAlpha( Float.valueOf(new ResourceModel("dashboard.report.reportdiagram.image.alpha") .wrapOnAssignment(this).getObject())); } // Bar chart - 1 numeric value, 2 comparable values (used as category, series) } else if (report.getDiagram() == 5) { if ((metaData.getColumnCount() != 2) && (metaData.getColumnCount() != 3)) throw new Exception( new ResourceModel("dashboard.report.reportdiagram.image.render.error.3values") .wrapOnAssignment(this).getObject()); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); while (resultSet.next()) dataset.setValue(resultSet.getDouble(1), resultSet.getString(2), resultSet.getString(metaData.getColumnCount())); chart = ChartFactory.createBarChart( new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this) .getObject(), metaData.getColumnName(2), metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL, true, true, true); } int[] winSize = DashboardCfgDelegate.getInstance().getWindowSize("reportDiagramImage"); addOrReplace(new JFreeChartImage("diagram", chart, winSize[0], winSize[1])); final JFreeChart downloadableChart = chart; addOrReplace(new Link<Object>("diagram-download") { private static final long serialVersionUID = 1L; @Override public void onClick() { RequestCycle.get().setRequestTarget(new IRequestTarget() { public void respond(RequestCycle requestCycle) { WebResponse wr = (WebResponse) requestCycle.getResponse(); wr.setContentType("image/png"); wr.setHeader("content-disposition", "attachment;filename=diagram.png"); OutputStream os = wr.getOutputStream(); try { ImageIO.write(downloadableChart.createBufferedImage(800, 600), "png", os); os.close(); } catch (IOException e) { log.error(this.getClass().toString() + ": " + "respond: " + e.getMessage()); log.debug("Exception: ", e); } wr.close(); } @Override public void detach(RequestCycle arg0) { } }); } }.add(new Image("diagram-download-image", ImageManager.IMAGE_DASHBOARD_REPORT_DOWNLOAD) .add(new ImageSizeBehaviour()) .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.downloadlink")))); addOrReplace(new Image("diagram-print-image", ImageManager.IMAGE_DASHBOARD_REPORT_PRINT) .add(new ImageSizeBehaviour()) .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.printbutton"))); addOrReplace(new Label("error-message", "").setVisible(false)); addOrReplace(new Label("error-reason", "").setVisible(false)); } catch (Exception e) { log.error("Exception: " + e.getMessage()); addOrReplace(((DynamicDisplayPage) this.getPage()).new PlaceholderLink("diagram-download") .setVisible(false)); addOrReplace(new Image("diagram-print-image").setVisible(false)); addOrReplace(new Image("diagram").setVisible(false)); addOrReplace(new Label("error-message", new ResourceModel("dashboard.report.reportdiagram.statement.error").wrapOnAssignment(this) .getObject()) .add(new AttributeModifier("class", true, new Model<String>("message-error")))); addOrReplace(new Label("error-reason", e.getMessage()) .add(new AttributeModifier("class", true, new Model<String>("message-error")))); log.debug(getClass() + ": ", e); } finally { try { jdbcConnection.close(); } catch (Exception ignore) { } } }
From source file:com.gargoylesoftware.htmlunit.javascript.host.PropertiesTest.java
private void saveChart(final DefaultCategoryDataset dataset) throws IOException { final JFreeChart chart = ChartFactory.createBarChart( "HtmlUnit implemented properties and methods for " + browserVersion_.getNickname(), "Objects", "Count", dataset, PlotOrientation.HORIZONTAL, true, true, false); final CategoryPlot plot = (CategoryPlot) chart.getPlot(); final NumberAxis axis = (NumberAxis) plot.getRangeAxis(); axis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); final LayeredBarRenderer renderer = new LayeredBarRenderer(); plot.setRenderer(renderer);/*from www . j a v a2s . co m*/ plot.setRowRenderingOrder(SortOrder.DESCENDING); renderer.setSeriesPaint(0, new GradientPaint(0, 0, Color.green, 0, 0, new Color(0, 64, 0))); renderer.setSeriesPaint(1, new GradientPaint(0, 0, Color.blue, 0, 0, new Color(0, 0, 64))); renderer.setSeriesPaint(2, new GradientPaint(0, 0, Color.red, 0, 0, new Color(64, 0, 0))); ImageIO.write(chart.createBufferedImage(1200, 2400), "png", new File(getArtifactsDirectory() + "/properties-" + browserVersion_.getNickname() + ".png")); }
From source file:Interfaz.XYLineChart.java
/** Constructor de clase * @param d Dimension// w ww.j a v a 2 s . co m */ public XYLineChart(Dimension d, ArrayList<Restriccion> rest, ArrayList<Coordenada> cor) { //se declara el grafico XY Lineal XYDataset xydataset = xyDataset(rest, cor); JFreeChart jfreechart = ChartFactory.createXYLineChart("Graficas lineales", "X", "Y", xydataset, PlotOrientation.VERTICAL, true, true, false); //personalizacin del grafico XYPlot xyplot = (XYPlot) jfreechart.getPlot(); xyplot.setBackgroundPaint(Color.white); xyplot.setDomainGridlinePaint(Color.BLACK); xyplot.setRangeGridlinePaint(Color.BLACK); // -> Pinta Shapes en los puntos dados por el XYDataset // XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyplot.getRenderer(); // xylineandshaperenderer.setBaseShapesVisible(true); // //--> muestra los valores de cada punto XY // XYItemLabelGenerator xy = new StandardXYItemLabelGenerator(); // xylineandshaperenderer.setBaseItemLabelGenerator( xy ); // xylineandshaperenderer.setBaseItemLabelsVisible(true); // xylineandshaperenderer.setBaseLinesVisible(true); // xylineandshaperenderer.setBaseItemLabelsVisible(true); //fin de personalizacin //se crea la imagen y se asigna a la clase ImageIcon BufferedImage bufferedImage = jfreechart.createBufferedImage(d.width, d.height); this.setImage(bufferedImage); }
From source file:piramide.interaction.reasoner.FuzzyReasonerWizardFacade.java
@Override public void generateMembershipFunctionGraph(boolean isInput, boolean isDevices, String variableName, RegionDistributionInfo[] linguisticTerms, OutputStream destination, int width, int height, Geolocation geo, DecayFunctions decayFunction, Calendar when) { BufferedImage img;//from w w w .ja v a 2s.com if (variableName == null) { img = createErrorMessagesImage("Error generating graph: variableName not provided"); } else if (linguisticTerms == null) { img = createErrorMessagesImage("Error generating graph: linguisticTerms not provided"); } else if (isInput && isDevices && !isValidDeviceVariableName(variableName)) { img = createErrorMessagesImage("Error generating graph: invalid device variable name: " + variableName); } else if (isInput && !isDevices && !isValidUserVariableName(variableName)) { img = createErrorMessagesImage("Error generating graph: invalid user variable name: " + variableName); } else { try { final WarningStore warningStore = new WarningStore(); final net.sourceforge.jFuzzyLogic.rule.Variable variable = processVariable(isInput, isDevices, variableName, linguisticTerms, geo, decayFunction, when, warningStore); final JFreeChart theChart = variable.chart(false); final String[] messages = warningStore.getMessages(); if (messages.length > 0) { final Font font = TextTitle.DEFAULT_FONT; final Font bigBold = new Font(font.getName(), Font.BOLD, font.getSize() + 2); final Font bold = new Font(font.getName(), Font.BOLD, font.getSize()); theChart.addSubtitle(new TextTitle("WARNINGS:", bigBold, Color.RED, Title.DEFAULT_POSITION, Title.DEFAULT_HORIZONTAL_ALIGNMENT, Title.DEFAULT_VERTICAL_ALIGNMENT, Title.DEFAULT_PADDING)); for (String message : messages) theChart.addSubtitle(new TextTitle(message, bold, Color.RED, Title.DEFAULT_POSITION, Title.DEFAULT_HORIZONTAL_ALIGNMENT, Title.DEFAULT_VERTICAL_ALIGNMENT, Title.DEFAULT_PADDING)); } img = theChart.createBufferedImage(width, height); } catch (FuzzyReasonerException e) { e.printStackTrace(); img = createErrorMessagesImage("Error generating graph: " + e.getMessage()); } } try { final ImageEncoder myEncoder = ImageEncoderFactory.newInstance("png"); myEncoder.encode(img, destination); destination.flush(); destination.close(); } catch (IOException e) { // Cry e.printStackTrace(); return; } }
From source file:org.squale.squaleweb.applicationlayer.action.results.application.ApplicationResultsAction.java
/** * Synthse d'une application Si l'application comporte un seul projet, la synthse du projet est alors affiche. * Dans le cas contraire, trois onglets sont prsents : un qui donne la rpartition, l'autre donnant les facteurs * par projet et le dernier donnant le kiviat. * //from www. j a v a2 s . co m * @param pMapping le mapping. * @param pForm le formulaire lire. * @param pRequest la requte HTTP. * @param pResponse la rponse de la servlet. * @return l'action raliser. */ public ActionForward summary(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest, HttpServletResponse pResponse) { // Cette action est appele dans plusieurs contextes possibles // Depuis une action struts avec l'id de l'application ou depuis // une page de l'application sans id de l'application (on a alors affaire l'application courante) ActionForward forward; try { // Add an user access for this application addUserAccess(pRequest, ActionUtils.getCurrentApplication(pRequest).getId()); forward = checkApplication(pMapping, pRequest); // Si forward est renseign, l'application contient un seul projet // On redirige donc vers le projet adquat if (null == forward) { // Rcupration des informations concernant les facteurs // Rcupration du paramtre : tous les facteurs ou seuls les facteurs ayant une note ? ResultListForm resultListForm = (ResultListForm) pForm; boolean pAllFactors = resultListForm.isAllFactors(); // On met cette valeur en session pRequest.getSession().setAttribute(ALL_FACTORS, new Boolean(pAllFactors)); ApplicationForm application = ActionUtils.getCurrentApplication(pRequest); // On remet jour les form en session permettant d'accder aux diffrents types d'audits SplitAuditsListForm auditsForm = (SplitAuditsListForm) pRequest.getSession() .getAttribute("splitAuditsListForm"); if (auditsForm != null) { auditsForm.copyValues(application); auditsForm.resetAudits(ActionUtils.getCurrentAuditsAsDTO(pRequest)); pRequest.getSession().setAttribute("splitAuditsListForm", auditsForm); } List auditsDTO = ActionUtils.getCurrentAuditsAsDTO(pRequest); if (auditsDTO != null) { ((ResultListForm) pForm).resetAudits(auditsDTO); } // On efface ce form contenant les erreurs de l'application, car si on passe par ici // Ce form ne peut que contenir les informations pour une autre application pRequest.getSession().removeAttribute("applicationErrorForm"); // Prparation de l'appel la couche mtier IApplicationComponent ac = AccessDelegateHelper.getInstance("Results"); List applications = Arrays .asList(WTransformerFactory.formToObj(ApplicationTransformer.class, application)); Object[] paramIn = { applications, auditsDTO }; // Les rsultats sont retourns dans l'ordre impos par la grille // on maintient cet ordre pour l'affichage List results = (List) ac.execute("getApplicationResults", paramIn); pRequest.getSession().removeAttribute(SqualeWebConstants.RESULTS_KEY); if (null != results && results.size() > 0) { // Transformation des rsultats avant leur affichage par la couche // welcom WTransformerFactory.objToForm(FactorsResultListTransformer.class, (ResultListForm) pForm, new Object[] { applications, results }); } else { // si aucun resultat => liste vide WTransformerFactory.objToForm(FactorsResultListTransformer.class, (ResultListForm) pForm, new Object[] { applications, new ArrayList() }); } // Rcupration des donnes permettant la gnration du Kiviat et du PieChart de l'application if (null != auditsDTO && null != auditsDTO.get(0)) { // Prparation de l'appel la couche mtier ac = AccessDelegateHelper.getInstance("Graph"); Long pCurrentAuditId = new Long(((AuditDTO) auditsDTO.get(0)).getID()); Object[] paramAuditIdKiviat = { pCurrentAuditId, String.valueOf(pAllFactors) }; // Recherche des donnes Kiviat KiviatMaker maker = new KiviatMaker(); Map projectsValues = (Map) ac.execute("getApplicationKiviatGraph", paramAuditIdKiviat); Set keysSet = projectsValues.keySet(); Iterator it = keysSet.iterator(); while (it.hasNext()) { String key = (String) it.next(); maker.addValues(key, (SortedMap) projectsValues.get(key), pRequest); } JFreeChart chartKiviat = maker.getChart(); ChartRenderingInfo infoKiviat = new ChartRenderingInfo(new StandardEntityCollection()); // Initialisation du kiviat String fileNameKiviat = ServletUtilities.saveChartAsPNG(chartKiviat, KiviatMaker.DEFAULT_WIDTH, KiviatMaker.DEFAULT_HEIGHT, infoKiviat, pRequest.getSession()); GraphMaker applicationKiviatChart = new GraphMaker(pRequest, fileNameKiviat, infoKiviat); // Pour l'export en PDF pRequest.getSession().removeAttribute("kiviatChart"); pRequest.getSession().setAttribute("kiviatChart", chartKiviat.createBufferedImage(KiviatMaker.DEFAULT_WIDTH, KiviatMaker.DEFAULT_HEIGHT)); // Recherche des donnes PieChart Object[] paramAuditIdPieChart = { pCurrentAuditId }; JFreeChart pieChart; Object[] maps = (Object[]) ac.execute("getApplicationPieChartGraph", paramAuditIdPieChart); String pPreviousAuditId = null; // on peut ne pas avoir d'audit prcdent if (auditsDTO.size() > 1) { pPreviousAuditId = "" + ((AuditDTO) auditsDTO.get(1)).getID(); } PieChartMaker pieMaker = new PieChartMaker(null, pCurrentAuditId.toString(), pPreviousAuditId); pieMaker.setValues((Map) maps[0]); pieChart = pieMaker.getChart((Map) maps[1], pRequest); ChartRenderingInfo infoPieChart = new ChartRenderingInfo(new StandardEntityCollection()); // Initialisation du pieChart String fileName = ServletUtilities.saveChartAsPNG(pieChart, PieChartMaker.DEFAULT_WIDTH, PieChartMaker.DEFAULT_HEIGHT, infoPieChart, pRequest.getSession()); GraphMaker applicationPieChart = new GraphMaker(pRequest, fileName, infoPieChart); // Met jour les 2 champs du form avec les 2 graphs calculs ((ResultListForm) pForm).setKiviat(applicationKiviatChart); ((ResultListForm) pForm).setPieChart(applicationPieChart); // Met jour le form en session pRequest.getSession().setAttribute("resultListForm", pForm); // Pour l'export en PDF pRequest.getSession().removeAttribute("pieChart"); pRequest.getSession().setAttribute("pieChart", pieChart .createBufferedImage(PieChartMaker.DEFAULT_WIDTH, PieChartMaker.DEFAULT_HEIGHT)); } // Affichage des informations sur la page jsp forward = pMapping.findForward("summary"); } } catch (Exception e) { ActionErrors errors = new ActionErrors(); // Traitement factoris des erreurs handleException(e, errors, pRequest); // Sauvegarde des erreurs saveMessages(pRequest, errors); // Routage vers la page d'erreur forward = pMapping.findForward("total_failure"); } // On est pass par un menu donc on rinitialise le traceur resetTracker(pRequest); // Indique que l'on vient d'une vue synthse et pas d'une vue composant changeWay(pRequest, "false"); return forward; }
From source file:com.orange.atk.results.logger.documentGenerator.GraphGenerator.java
/** * This function creates the measurement graph by using the JFreeChart * library. The X axis of the graph is in minutes. * //from w w w . j av a2 s . co m * @param plotList * plotlist to save. Xvalues must be stored in milliseconds. * @param associatedName * Name of the list * @param folderWhereResultsAreSaved * folder where results are saved * @param yLabel * Name of the y label * @param pictureFile * name of the file * @param yDivisor * use to divide measurements stored in the plotlist by yDivisor */ public static void generateGraphWithJFreeChart(PlotList plotList, String associatedName, String folderWhereResultsAreSaved, String yLabel, String pictureFile, float yDivisor) { // Create a new XYSeries // XYSeries are used to represent couples of (x,y) values. XYSeries data = new XYSeries(associatedName); int size = plotList.getSize(); if (size == 0) { // no element in graphics, exit //Logger.getLogger(this.getClass() ).warn("Nothing in graph"); return; } // Find the initial value of the time // Due to the fact that getX(i) <= getX(i+1), // min({0<=i<size / getX(i)}) = getX(0) long initialValue = plotList.getX(0); XYSeriesCollection series = new XYSeriesCollection(data); if (!plotList.getunit().equals("")) yLabel += " (" + plotList.getunit() + ")"; // Create a new XY graph. //JFreeChart chart = ChartFactory.createXYLineChart("", "Time", yLabel, series, PlotOrientation.VERTICAL, true, true, false); JFreeChart chart = ChartFactory.createTimeSeriesChart("", "Time (min:sec)", yLabel, series, true, true, false); // Set the graph format XYPlot plot = chart.getXYPlot(); plot.setOrientation(PlotOrientation.VERTICAL); DateAxis axis = (DateAxis) plot.getDomainAxis(); //axis.setTickUnit(new DateTickUnit(DateTickUnit.SECOND, 10)); RelativeDateFormat rdf = new RelativeDateFormat(initialValue); rdf.setSecondFormatter(new DecimalFormat("00")); axis.setDateFormatOverride(rdf); // Fill the JFreeChart object which will be used to create the Graph for (int i = 0; i < size; i++) { // xvalue must be in double xval = ((Long) plotList.getX(i)).doubleValue(); float yval = plotList.getY(i).floatValue() / yDivisor; // Logger.getLogger(this.getClass() ).debug(associatedName + " [" + (((Long) // plotList.getX(i)).floatValue() - initialValue) // / XDIVISOR +"] "+ yval); data.add(xval, yval); } ValueAxis rangeAxis = plot.getRangeAxis(); Long min = plotList.getMin(); Long max = plotList.getMax(); double diff = (max - min) * 0.02; if (diff == 0) diff = max * 0.0001; rangeAxis.setLowerBound((min - diff) / yDivisor); rangeAxis.setUpperBound((max + diff) / yDivisor); // Logger.getLogger(this.getClass() ).debug("(" + (min / yDivisor) * 0.98 + " - " // + (min / yDivisor) * 0.98 + ")"); // Logger.getLogger(this.getClass() ).debug("Bound = " + rangeAxis.getLowerBound() + " - " // + rangeAxis.getUpperBound()); // Logger.getLogger(this.getClass() ).debug("Margin = " + rangeAxis.getLowerMargin() + " - " // + rangeAxis.getUpperMargin()); // Logger.getLogger(this.getClass() ).debug("NB AXIS = " + plot.getRangeAxisCount()); // save the chart in a picture file. BufferedImage bufImage = chart.createBufferedImage(640, 480); File fichier = new File(pictureFile); try { if (!ImageIO.write(bufImage, "png", fichier)) { return; } } catch (IOException e) { e.printStackTrace(); } }