/** Check that the equals() method distinguishes the required fields. */ public void testEquals() { MultiplePiePlot p1 = new MultiplePiePlot(); MultiplePiePlot p2 = new MultiplePiePlot(); assertTrue(p1.equals(p2)); assertTrue(p2.equals(p1)); p1.setDataExtractOrder(TableOrder.BY_ROW); assertFalse(p1.equals(p2)); p2.setDataExtractOrder(TableOrder.BY_ROW); assertTrue(p1.equals(p2)); p1.setLimit(1.23); assertFalse(p1.equals(p2)); p2.setLimit(1.23); assertTrue(p1.equals(p2)); p1.setAggregatedItemsKey("Aggregated Items"); assertFalse(p1.equals(p2)); p2.setAggregatedItemsKey("Aggregated Items"); assertTrue(p1.equals(p2)); p1.setAggregatedItemsPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.yellow)); assertFalse(p1.equals(p2)); p2.setAggregatedItemsPaint(new GradientPaint(1.0f, 2.0f, Color.red, 3.0f, 4.0f, Color.yellow)); assertTrue(p1.equals(p2)); p1.setPieChart(ChartFactory.createPieChart("Title", null, true, true, true)); assertFalse(p1.equals(p2)); p2.setPieChart(ChartFactory.createPieChart("Title", null, true, true, true)); assertTrue(p1.equals(p2)); }
/** * 生成JFreeChart * * @return */ public JFreeChart getJFreeChart() { PieDataset dataset = getPieDataset(); // locale.getISO3Language() JFreeChart chart = ChartFactory.createPieChart("2010.8月份销售排行", dataset, true, true, false); return chart; }
private static JFreeChart createChart(PieDataset paramPieDataset) { JFreeChart localJFreeChart = ChartFactory.createPieChart("Legend Wrapper Demo 1", paramPieDataset, false, true, false); PiePlot localPiePlot = (PiePlot) localJFreeChart.getPlot(); localPiePlot.setLabelFont(new Font("SansSerif", 0, 12)); localPiePlot.setNoDataMessage("No data available"); localPiePlot.setCircular(true); localPiePlot.setLabelGap(0.02D); LegendTitle localLegendTitle = new LegendTitle(localJFreeChart.getPlot()); BlockContainer localBlockContainer1 = new BlockContainer(new BorderArrangement()); localBlockContainer1.setFrame(new BlockBorder(1.0D, 1.0D, 1.0D, 1.0D)); LabelBlock localLabelBlock1 = new LabelBlock("Legend Items:", new Font("SansSerif", 1, 12)); localLabelBlock1.setPadding(5.0D, 5.0D, 5.0D, 5.0D); localBlockContainer1.add(localLabelBlock1, RectangleEdge.TOP); LabelBlock localLabelBlock2 = new LabelBlock("Source: http://www.jfree.org"); localLabelBlock2.setPadding(8.0D, 20.0D, 2.0D, 5.0D); localBlockContainer1.add(localLabelBlock2, RectangleEdge.BOTTOM); BlockContainer localBlockContainer2 = localLegendTitle.getItemContainer(); localBlockContainer2.setPadding(2.0D, 10.0D, 5.0D, 2.0D); localBlockContainer1.add(localBlockContainer2); localLegendTitle.setWrapper(localBlockContainer1); localLegendTitle.setPosition(RectangleEdge.RIGHT); localLegendTitle.setHorizontalAlignment(HorizontalAlignment.LEFT); localJFreeChart.addSubtitle(localLegendTitle); ChartUtilities.applyCurrentTheme(localJFreeChart); return localJFreeChart; }
/** * Cria um grafico de pizza com os dados fornecidos * * @param titulo <code>String</code> com o titulo do grafico * @param listaNomesValores {@code List<NomeValor>} lista com os nomes e valores para o grafico * @param legendasAdicionais <code>String...</code> com as legendas adicionais * @param graficoEm3D <code>boolean</code> com <code>true</code> se o grafico é em 3D ou não. */ public GraficoPizza( String titulo, List<NomeValor> listaNomesValores, boolean graficoEm3D, final String... legendasAdicionais) { // Cria um dataSet para inserir os dados que serão passados para a criação do grafico tipo Pie DefaultPieDataset pieDataset = new DefaultPieDataset(); this.graficoEm3D = graficoEm3D; // Adiciona os dados ao dataSet deve somar um total de 100% double valorUmPorCentoVotos = this.valorUmVotoEmPorCento(listaNomesValores); String valor; for (NomeValor nomesValores : listaNomesValores) { valor = String.format("%.2f%%", nomesValores.getValor() * valorUmPorCentoVotos); pieDataset.setValue(nomesValores.getNome() + "(" + valor + ")", nomesValores.getValor()); } // Cria um objeto JFreeChart passando os seguintes parametros if (!this.graficoEm3D) { this.grafico = ChartFactory.createPieChart( titulo, // Titulo do grafico pieDataset, // DataSet true, // Para mostrar ou não a legenda true, // Para mostrar ou não os tooltips false); } else { // em 3D this.grafico = ChartFactory.createPieChart3D( titulo, // Titulo do grafico pieDataset, // DataSet true, // Para mostrar ou não a legenda true, // Para mostrar ou não os tooltips false); } if (this.grafico != null) { LegendTitle legenda = new LegendTitle( new LegendItemSource() { @Override public LegendItemCollection getLegendItems() { LegendItemCollection legenda = new LegendItemCollection(); for (String texto : legendasAdicionais) { legenda.add(new LegendItem(texto)); } return legenda; } }); float larguraBordaLegenda = 0.6F; legenda.setBorder( larguraBordaLegenda, larguraBordaLegenda, larguraBordaLegenda, larguraBordaLegenda); legenda.setPosition(RectangleEdge.BOTTOM); legenda.setHorizontalAlignment(HorizontalAlignment.LEFT); this.grafico.addLegend(legenda); } }
public ChartPanel createChart() { System.out.println("Creating chart..."); // PiePlot plot = new PiePlot( data ); // plot.setLabelFont( new Font("SansSerif", Font.PLAIN, 12) ); // plot.setNoDataMessage("No data available"); // plot.setLabelGap(0.02); JFreeChart chartFree = ChartFactory.createPieChart(title, data, true, true, false); ChartPanel chart = new ChartPanel(chartFree); return chart; }
public MouseListenerDemo1(String s) { super(s); DefaultPieDataset defaultpiedataset = new DefaultPieDataset(); defaultpiedataset.setValue("Java", new Double(43.200000000000003D)); defaultpiedataset.setValue("Visual Basic", new Double(0.0D)); defaultpiedataset.setValue("C/C++", new Double(17.5D)); org.jfree.chart.JFreeChart jfreechart = ChartFactory.createPieChart("Pie Chart Demo 1", defaultpiedataset, true, true, false); ChartPanel chartpanel = new ChartPanel(jfreechart, false, false, false, false, false); chartpanel.addChartMouseListener(this); chartpanel.setPreferredSize(new Dimension(500, 270)); setContentPane(chartpanel); }
/** {@inheritDoc} */ @Override protected JFreeChart createChart() { PieDataset dataSet = createDataset(); JFreeChart chart = ChartFactory.createPieChart(dataDescription, dataSet, drawLegend, true, false); PiePlot plot = (PiePlot) chart.getPlot(); setColors(plot, dataSet); plot.setLabelGenerator(new StandardPieSectionLabelGenerator(labelFormat)); stylePiePlot(plot); return chart; }
/** Draws a pie chart where the label generator returns null. */ @Test public void testDrawWithNullLegendLabels() { DefaultPieDataset dataset = new DefaultPieDataset(); dataset.setValue("L1", 12.0); dataset.setValue("L2", 11.0); JFreeChart chart = ChartFactory.createPieChart("Test", dataset); PiePlot plot = (PiePlot) chart.getPlot(); plot.setLegendLabelGenerator(new NullLegendLabelGenerator()); BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); chart.draw(g2, new Rectangle2D.Double(0, 0, 200, 100), null, null); g2.dispose(); }
private PdfPCell createKPGSPieChartCell(KeyValue[] values, String title) throws IOException, BadElementException { DefaultPieDataset dataset = new DefaultPieDataset(); for (int n = 0; n < values.length; n++) { dataset.setValue(values[n].getKey(), new Double(values[n].getValue()).doubleValue()); } // create chart final JFreeChart chart = ChartFactory.createPieChart( title, // chart title dataset, // data true, // legend false, // tooltips false // urls ); // customize chart PiePlot plot = (PiePlot) chart.getPlot(); plot.setBackgroundPaint(java.awt.Color.WHITE); if (values.length > 0) { if (values[0].getKey().equalsIgnoreCase("?") && values.length > 1) { plot.setExplodePercent(values[1].getKey(), 0.2); } else { plot.setExplodePercent(values[0].getKey(), 0.2); } } plot.setLegendLabelGenerator(new KPGSLegendGenerator()); plot.setLabelGenerator(new KPGSLabelGenerator(values)); plot.setOutlineVisible(false); chart.setAntiAlias(true); LegendTitle legendTitle = (LegendTitle) chart.getSubtitle(0); legendTitle.setFrame(BlockBorder.NONE); legendTitle.setBackgroundPaint(null); ByteArrayOutputStream os = new ByteArrayOutputStream(); ChartUtilities.writeChartAsPNG( os, chart, MedwanQuery.getInstance().getConfigInt("stats.piechartwidth", 640), MedwanQuery.getInstance().getConfigInt("stats.piechartheight", 480)); cell = new PdfPCell(); cell.setColspan(50); cell.setImage(Image.getInstance(os.toByteArray())); cell.setBorder(PdfPCell.NO_BORDER); cell.setPaddingLeft(5); cell.setPaddingRight(5); return cell; }
/** * Creates a chart. * * @param dataset the dataset. * @return A chart. */ private static JFreeChart createChart(PieDataset dataset) { JFreeChart chart = ChartFactory.createPieChart( "Pie Chart Demo 1", // chart title dataset, // data true, // include legend true, false); PiePlot plot = (PiePlot) chart.getPlot(); plot.setSectionOutlinesVisible(false); plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 10)); plot.setNoDataMessage("No data available"); plot.setSimpleLabels(true); return chart; }
/** Creates a JFreeChart */ private void setupChart(ChartType type) { this.type = type; // Create a dataset dataset = new XYSeriesCollection(); JFreeChart chart; // Create a chart if (type == ChartType.PIE_CHART) { pieData = new DefaultPieDataset(); chart = ChartFactory.createPieChart(null, pieData, true, false, false); } else { chart = ChartFactory.createXYLineChart( null, "x", "y", dataset, PlotOrientation.VERTICAL, true, false, false); } // Create a chart panel ChartPanel panel = new ChartPanel(chart); panel.setMinimumSize(new Dimension(100, 100)); panel.setPreferredSize(new Dimension(400, 300)); // Create additional control elements JPanel controlPanel = new JPanel(new GridLayout(1, 3)); clearButton = new JButton("Clear"); saveButton = new JButton("Save"); removeButton = new JButton("Remove"); clearButton.setActionCommand(CMD_CLEAR); saveButton.setActionCommand(CMD_SAVE); removeButton.setActionCommand(CMD_REMOVE); clearButton.addActionListener(this); saveButton.addActionListener(this); removeButton.addActionListener(this); // Add controls to the control panel controlPanel.add(clearButton); controlPanel.add(saveButton); controlPanel.add(removeButton); this.add(panel, BorderLayout.CENTER); this.add(controlPanel, BorderLayout.SOUTH); }
/** * Creates a chart. * * @param dataset the dataset. * @return a chart. */ private static JFreeChart createChart(PieDataset dataset) { JFreeChart chart = ChartFactory.createPieChart( "Pie Chart Demo 4", // chart title dataset, // data true, // include legend true, false); PiePlot plot = (PiePlot) chart.getPlot(); plot.setNoDataMessage("No data available"); plot.setCircular(false); plot.setLabelGap(0.02); plot.setExplodePercent("Section D", 0.50); plot.setLabelLinkStyle(PieLabelLinkStyle.CUBIC_CURVE); return chart; }
public static JFreeChart generatePieChart(JSONArray IndividualPDFChart) { DefaultPieDataset dataSet = new DefaultPieDataset(); for (int i = 0; i < IndividualPDFChart.size(); i++) { JSONObject jsonChart = IndividualPDFChart.getJSONObject(i); dataSet.setValue( jsonChart.getString(PDFConstants.PieData1), Double.parseDouble(jsonChart.getString(PDFConstants.PieData2))); } JFreeChart chart = ChartFactory.createPieChart(PDFConstants.PieChartTitle, dataSet, true, true, false); // PiePlot3D plot = (PiePlot3D) chart.getPlot(); // plot.setStartAngle(290); // plot.setDirection(Rotation.CLOCKWISE); // plot.setForegroundAlpha(0.5f); // return chart; }
public void carregarGrafico() { Caixa caixa; if (this.frame.getCbxResCaixa() != null) { caixa = this.frame.getCbxResCaixa(); } else { this.frame.setGrafico(null); return; } DefaultPieDataset grafico = new DefaultPieDataset(); ArrayList<Object[]> dadosGrafico = this.lancamentoDAO.selectLancamentosGrafico( caixa.getCodCaixa(), DateTools.parseDateToInteger(this.perDataIni), DateTools.parseDateToInteger(this.perDataFim), this.frame.getCkbResumoCaixa()); if (dadosGrafico.isEmpty()) { this.frame.setGrafico(null); return; } for (Object[] item : dadosGrafico) { String conta = (String) item[0]; Double valor = (Double) item[1]; grafico.setValue(conta, valor); } JFreeChart chart = ChartFactory.createPieChart("", grafico); chart.removeLegend(); chart.removeSubtitle(null); this.frame.setGrafico(chart); }
private BufferedImage generarGraficoTorta( String titulo, double[] valores, String[] funciones, int anchoImagen, int altoImagen) { if (valores.length != funciones.length) { return null; } DefaultPieDataset pieDataset = new DefaultPieDataset(); for (int i = 0; i < valores.length; i++) { pieDataset.setValue(funciones[i], valores[i]); } JFreeChart chart = ChartFactory.createPieChart(titulo, pieDataset, true, true, false); chart.setBackgroundPaint(null); chart.getTitle().setPaint(LookAndFeelEntropy.COLOR_FUENTE_TITULO_PANEL); chart.getTitle().setFont(LookAndFeelEntropy.FUENTE_TITULO_GRANDE); chart.setBorderVisible(false); chart.getLegend().setItemFont(LookAndFeelEntropy.FUENTE_REGULAR); chart.getLegend().setBackgroundPaint(LookAndFeelEntropy.COLOR_TABLA_PRIMARIO); PiePlot plot = (PiePlot) chart.getPlot(); plot.setBackgroundPaint(null); plot.setBackgroundImageAlpha(0.0f); plot.setSimpleLabels(true); plot.setOutlineVisible(false); for (int i = 0; i < valores.length; i++) { plot.setSectionPaint( funciones[i], generarColorAleatorio(Color.ORANGE)); // LookAndFeelEntropy.COLOR_FUENTE_TITULO_PANEL)); plot.setExplodePercent(funciones[i], 0.10); } PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator( "{0}: {1} ({2})", new DecimalFormat("0"), new DecimalFormat("0%")); plot.setLabelGenerator(gen); this.lastChart = chart; // Generamos una imagen return chart.createBufferedImage(anchoImagen, altoImagen); }
private JFreeChart getPieChart() { // Load the data, if necessary loadData(); // Create a chart and return it final JFreeChart chart = ChartFactory.createPieChart( getTitle(), getPieDataset(), useLegend(), useTooltips(), useURLs()); // Customize the labels and legend final PiePlot pieplot = (PiePlot) chart.getPlot(); pieplot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({2})")); // pieplot.setSimpleLabels(true); pieplot.setNoDataMessage("No data available"); if (useLegend()) { pieplot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({1})")); chart.getLegend().setPosition(RectangleEdge.RIGHT); // pieplot.setLegendLabelToolTipGenerator(new StandardPieSectionLabelGenerator("{0}: {2}%")); } return chart; }
/** * Default constructor. * * @param title the frame title. */ public XMLPieChartDemo(final String title) { super(title); // create a dataset... PieDataset dataset = null; final URL url = getClass().getResource("/org/jfree/chart/demo/piedata.xml"); try { final InputStream in = url.openStream(); dataset = DatasetReader.readPieDatasetFromXML(in); } catch (IOException ioe) { System.out.println(ioe.getMessage()); } // create the chart... final JFreeChart chart = ChartFactory.createPieChart( "Pie Chart Demo 1", // chart title dataset, // data true, // include legend true, false); // set the background color for the chart... chart.setBackgroundPaint(Color.yellow); final PiePlot plot = (PiePlot) chart.getPlot(); plot.setLabelGenerator( new StandardPieItemLabelGenerator( "{0} = {2}", NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance())); plot.setNoDataMessage("No data available"); // add the chart to a panel... final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); setContentPane(chartPanel); }
public static void main(String[] args) { // Create a simple pie chart DefaultPieDataset pieDataset = new DefaultPieDataset(); pieDataset.setValue("Boom Server", new Integer(30)); pieDataset.setValue("Next Reports", new Integer(33)); pieDataset.setValue("ReMinder", new Integer(37)); JFreeChart chart = ChartFactory.createPieChart("Project Hours", pieDataset, true, true, false); chart.setBackgroundPaint(Color.WHITE); PiePlot plot = (PiePlot) chart.getPlot(); plot.setBackgroundPaint(Color.WHITE); plot.setStartAngle(330); // Specify the colors here Color[] colors = {Color.blue, Color.yellow, Color.green, Color.red, Color.ORANGE}; PieRenderer renderer = new PieRenderer(colors); renderer.setColor(plot, pieDataset); try { ChartUtilities.saveChartAsJPEG(new File("C:chart.jpg"), chart, 500, 300); } catch (Exception e) { System.out.println("Problem occurred creating chart."); } }
public static JFreeChart createPieChart(String chartName, DBSeerDataSet dataset) { StatisticalPackageRunner runner = DBSeerGUI.runner; runner.eval( "[title legends Xdata Ydata Xlabel Ylabel timestamp] = plotter.plot" + chartName + ";"); String title = runner.getVariableString("title"); Object[] legends = (Object[]) runner.getVariableCell("legends"); Object[] xCellArray = (Object[]) runner.getVariableCell("Xdata"); Object[] yCellArray = (Object[]) runner.getVariableCell("Ydata"); String xLabel = runner.getVariableString("Xlabel"); String yLabel = runner.getVariableString("Ylabel"); timestamp = runner.getVariableDouble("timestamp"); DefaultPieDataset pieDataSet = new DefaultPieDataset(); int numLegends = legends.length; int numXCellArray = xCellArray.length; int numYCellArray = yCellArray.length; int dataCount = 0; if (numXCellArray != numYCellArray) { JOptionPane.showMessageDialog( null, "The number of X dataset and Y dataset does not match.", "The number of X dataset and Y dataset does not match.", JOptionPane.ERROR_MESSAGE); return null; } final java.util.List<String> transactionTypeNames = dataset.getTransactionTypeNames(); for (int i = 0; i < numYCellArray; ++i) { double[] xArray = (double[]) xCellArray[i]; runner.eval("yArraySize = size(Ydata{" + (i + 1) + "});"); runner.eval("yArray = Ydata{" + (i + 1) + "};"); double[] yArraySize = runner.getVariableDouble("yArraySize"); double[] yArray = runner.getVariableDouble("yArray"); int xLength = xArray.length; int row = (int) yArraySize[0]; int col = (int) yArraySize[1]; for (int c = 0; c < col; ++c) { if (c < transactionTypeNames.size()) { String name = transactionTypeNames.get(c); if (!name.isEmpty()) { // pieDataSet.setValue(name, new Double(yArray.getRealValue(0, c))); pieDataSet.setValue(name, yArray[c]); } else { // pieDataSet.setValue("Transaction Type " + (c+1), yArray.getRealValue(0, c)); pieDataSet.setValue("Transaction Type " + (c + 1), yArray[c]); } } } } JFreeChart chart = ChartFactory.createPieChart(title, pieDataSet, true, true, false); PiePlot plot = (PiePlot) chart.getPlot(); plot.setLabelGenerator( new StandardPieSectionLabelGenerator( "{0}: {1} ({2})", new DecimalFormat("0"), new DecimalFormat("0%"))); plot.setLegendLabelGenerator( new PieSectionLabelGenerator() { @Override public String generateSectionLabel(PieDataset pieDataset, Comparable comparable) { return (String) comparable; } @Override public AttributedString generateAttributedSectionLabel( PieDataset pieDataset, Comparable comparable) { return null; } }); return chart; }
// -------------------------------------------------------------------------- // --- // --- Service // --- // -------------------------------------------------------------------------- @Override public Element serviceSpecificExec(Element params, ServiceContext context) throws Exception { boolean readOnlyMode = super.exec(params, context) == null; if (readOnlyMode) { return null; } String message = ""; GeonetContext gc = (GeonetContext) context.getHandlerContext(Geonet.CONTEXT_NAME); // gets the total popularity count (=100) Dbms dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB); // wont work if there is no metadata List l = dbms.select("select sum(popularity) as sumpop from metadata").getChildren(); if (l.size() != 1) { message = "cannot get popularity count"; return null; } int cnt = Integer.parseInt(((Element) l.get(0)).getChildText("sumpop")); if (Log.isDebugEnabled(Geonet.SEARCH_LOGGER)) Log.debug(Geonet.SEARCH_LOGGER, "query to get popularity by group:\n" + query); dbms = (Dbms) context.getResourceManager().open(Geonet.Res.MAIN_DB); DefaultPieDataset dataset = new DefaultPieDataset(); List resultSet = dbms.select(query).getChildren(); for (int i = 0; i < resultSet.size(); i++) { Element record = (Element) resultSet.get(i); String popularity = (record).getChildText("popu"); Double d = 0.0; if (popularity.length() > 0) { d = (Double.parseDouble(popularity) / cnt) * 100; } dataset.setValue(record.getChildText("source"), d); // System.out.println(record.getChildText("groupname") + ", " + d); } // create a chart... JFreeChart chart = ChartFactory.createPieChart( null, dataset, true, // legend? true, // tooltips? false // URLs? ); // hard coded values for the moment. should come from a configuration file. chart.setBackgroundPaint(Color.decode("#E7EDF5")); String chartFilename = "popubycatalog_" + System.currentTimeMillis() + ".png"; File statFolder = new File( gc.getHandlerConfig().getMandatoryValue(Geonet.Config.RESOURCES_DIR) + File.separator + "images" + File.separator + "statTmp"); if (!statFolder.exists()) { statFolder.mkdirs(); } File f = new File(statFolder, chartFilename); this.imageMap = org.fao.geonet.services.statistics.ChartFactory.writeChartImage( chart, f, this.chartWidth, this.chartHeight, this.createTooltips, "graphPopuByCatalogImageMap"); // will return some info to the XSLT: // dateFrom, dateTo, graphicType, chartUrl, tooltipImageMap, // message, chartWidth, chartHeight Element elResp = new Element(Jeeves.Elem.RESPONSE); Element elchartUrl = new Element("popuByCatalogUrl") .setText(context.getBaseUrl() + "/images/statTmp/" + chartFilename); Element elTooltipImageMap = new Element("tooltipImageMap").addContent(this.createTooltips ? this.imageMap : ""); Element elMessage = new Element("message").setText(message); Element elChartWidth = new Element("chartWidth").setText("" + this.chartWidth); Element elChartHeight = new Element("chartHeight").setText("" + this.chartHeight); elResp.addContent(elchartUrl); elResp.addContent(elTooltipImageMap); elResp.addContent(elMessage); elResp.addContent(elChartWidth); elResp.addContent(elChartHeight); return elResp; }
private String generateAvailSLATime( DocumentHTML document, HttpServletRequest request, AcordoNivelServicoDTO acordoNivelServicoDTO, Integer idAcordoNivelServico, UsuarioDTO usuarioDto) throws IOException, ParseException { SlaAvaliacaoDTO slaAvaliacaoDto = (SlaAvaliacaoDTO) document.getBean(); ControleGenerateSLAPorAcordoNivelServico controleGenerateSLAPorAcordoNivelServico = new ControleGenerateSLAPorAcordoNivelServico(); ControleGenerateSLAPorAcordoNivelServicoEmAndamento controleGenerateSLAPorAcordoNivelServicoEmAndamento = new ControleGenerateSLAPorAcordoNivelServicoEmAndamento(); List lst = controleGenerateSLAPorAcordoNivelServico.execute( idAcordoNivelServico, slaAvaliacaoDto.getDataInicio(), slaAvaliacaoDto.getDataFim()); double qtdeDentroPrazo = 0; double qtdeForaPrazo = 0; if (lst != null && lst.size() > 0) { for (Iterator itSLA = lst.iterator(); itSLA.hasNext(); ) { Object[] objs = (Object[]) itSLA.next(); if (((String) objs[0]).indexOf("Fora") > -1 || ((String) objs[0]).indexOf("Out") > -1) { qtdeForaPrazo = (Double) objs[2]; } else { qtdeDentroPrazo = (Double) objs[2]; } } } double qtdeDentroPrazoPerc = (qtdeDentroPrazo / (qtdeDentroPrazo + qtdeForaPrazo)) * 100; double qtdeForaPrazoPerc = (qtdeForaPrazo / (qtdeDentroPrazo + qtdeForaPrazo)) * 100; final DefaultValueDataset dataset = new DefaultValueDataset(new Double(qtdeDentroPrazoPerc)); // create the chart... final ThermometerPlot plot = new ThermometerPlot(dataset); final JFreeChart chart = new JFreeChart( UtilI18N.internacionaliza(request, "sla.avaliacao.avaliacaogeral"), // chart title JFreeChart.DEFAULT_TITLE_FONT, plot, // plot false); // include legend plot.setSubrangeInfo(ThermometerPlot.NORMAL, 90.000001, 100); plot.setSubrangeInfo(ThermometerPlot.WARNING, 80.000001, 90); plot.setSubrangeInfo(ThermometerPlot.CRITICAL, 0, 80); plot.setThermometerStroke(new BasicStroke(2.0f)); plot.setThermometerPaint(Color.lightGray); String nomeImgAval = CITCorporeUtil.caminho_real_app + "/tempFiles/" + usuarioDto.getIdUsuario() + "/avalSLA_" + acordoNivelServicoDTO.getIdAcordoNivelServico() + ".png"; String nomeImgAvalRel = br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/tempFiles/" + usuarioDto.getIdUsuario() + "/avalSLA_" + acordoNivelServicoDTO.getIdAcordoNivelServico() + ".png"; File arquivo = new File(nomeImgAval); if (arquivo.exists()) { arquivo.delete(); } else { String nomeDir = CITCorporeUtil.caminho_real_app + "/tempFiles/" + usuarioDto.getIdUsuario() + "/"; File dirTemp = new File(nomeDir); dirTemp.mkdirs(); arquivo.createNewFile(); } ChartUtilities.saveChartAsPNG(arquivo, chart, 500, 200); List lst2 = controleGenerateSLAPorAcordoNivelServicoEmAndamento.execute(idAcordoNivelServico); qtdeDentroPrazo = 0; qtdeForaPrazo = 0; if (lst2 != null && lst2.size() > 0) { for (Iterator itSLA = lst2.iterator(); itSLA.hasNext(); ) { Object[] objs = (Object[]) itSLA.next(); if (((String) objs[0]).indexOf("Fora") > -1 || ((String) objs[0]).indexOf("Out") > -1) { qtdeForaPrazo = (Double) objs[2]; } else { qtdeDentroPrazo = (Double) objs[2]; } } } qtdeDentroPrazoPerc = (qtdeDentroPrazo / (qtdeDentroPrazo + qtdeForaPrazo)) * 100; qtdeForaPrazoPerc = (qtdeForaPrazo / (qtdeDentroPrazo + qtdeForaPrazo)) * 100; DefaultPieDataset datasetPie = new DefaultPieDataset(); datasetPie.setValue( UtilI18N.internacionaliza(request, "sla.avaliacao.noprazo") + " (" + UtilFormatacao.formatDouble(qtdeDentroPrazo, 0) + ")", new Double(qtdeDentroPrazoPerc)); datasetPie.setValue( UtilI18N.internacionaliza(request, "sla.avaliacao.foraprazo") + " (" + UtilFormatacao.formatDouble(qtdeForaPrazo, 0) + ")", new Double(qtdeForaPrazoPerc)); JFreeChart chartX = ChartFactory.createPieChart( UtilI18N.internacionaliza(request, "sla.avaliacao.emandamento"), // chart title datasetPie, // data true, // include legend true, false); PiePlot plotPie = (PiePlot) chartX.getPlot(); plotPie.setLabelFont(new Font("SansSerif", Font.PLAIN, 6)); plotPie.setNoDataMessage(UtilI18N.internacionaliza(request, "sla.avaliacao.naohadados")); plotPie.setCircular(true); plotPie.setLabelGap(0); String nomeImgAval2 = CITCorporeUtil.caminho_real_app + "/tempFiles/" + usuarioDto.getIdUsuario() + "/avalSLA2_" + idAcordoNivelServico + ".png"; String nomeImgAvalRel2 = br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/tempFiles/" + usuarioDto.getIdUsuario() + "/avalSLA2_" + idAcordoNivelServico + ".png"; File arquivo2 = new File(nomeImgAval2); if (arquivo2.exists()) { arquivo2.delete(); } ChartUtilities.saveChartAsPNG(arquivo2, chartX, 200, 200); String table = ""; table += "<tr>"; table += "<td style='border:1px solid black; vertical-align:middle;'>"; // table += // UtilHTML.encodeHTML(UtilStrings.retiraApostrofe(acordoNivelServicoDTO.getTituloSLA())); table += "<br>" + geraTabelaMeses( acordoNivelServicoDTO.getTituloSLA(), idAcordoNivelServico, request, usuarioDto); table += "</td>"; table += "<td style='border:1px solid black; vertical-align:middle;'>"; if (acordoNivelServicoDTO.getTipo() != null && acordoNivelServicoDTO.getTipo().equalsIgnoreCase("T")) { table += "<img src='" + br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/imagens/relogio.png' border='0' title='" + UtilI18N.internacionaliza(request, "sla.avaliacao.tempo") + "'/>"; table += UtilI18N.internacionaliza(request, "sla.avaliacao.tempo"); } else if (acordoNivelServicoDTO.getTipo() != null && acordoNivelServicoDTO.getTipo().equalsIgnoreCase("D")) { table += "<img src='" + br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/imagens/disponibilidade.png' border='0' title='" + UtilI18N.internacionaliza(request, "sla.avaliacao.disponibilidade") + "'/>"; table += UtilI18N.internacionaliza(request, "sla.avaliacao.disponibilidade"); } else if (acordoNivelServicoDTO.getTipo() != null && acordoNivelServicoDTO.getTipo().equalsIgnoreCase("V")) { table += "<img src='" + br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/imagens/outrasfontes.png' border='0' title='" + UtilI18N.internacionaliza(request, "sla.avaliacao.outrasfontes") + "'/>"; table += UtilI18N.internacionaliza(request, "sla.avaliacao.outrasfontes"); } table += "</td>"; table += "<td style='border:1px solid black; vertical-align:middle;'>"; if (acordoNivelServicoDTO.getDataFim() != null && acordoNivelServicoDTO.getDataFim().before(UtilDatas.getDataAtual())) { table += "<img src='" + br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/imagens/bolavermelha.png' border='0' title='" + UtilI18N.internacionaliza(request, "sla.avaliacao.inativo") + "'/>"; table += UtilI18N.internacionaliza(request, "sla.avaliacao.inativo"); } else { table += "<img src='" + br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/imagens/bolaverde.png' border='0' title='" + UtilI18N.internacionaliza(request, "sla.avaliacao.ativo") + "'/>"; table += UtilI18N.internacionaliza(request, "sla.avaliacao.ativo"); } table += "</td>"; table += "<td style='border:1px solid black'>"; table += "<img src='" + nomeImgAvalRel + "' border='0'/>"; table += "</td>"; table += "<td style='border:1px solid black'>"; table += "<img src='" + nomeImgAvalRel2 + "' border='0'/>"; table += "</td>"; table += "</tr>"; return table; }
public void avalia( DocumentHTML document, HttpServletRequest request, HttpServletResponse response) throws Exception { UsuarioDTO usuarioDto = WebUtil.getUsuario(request); if (usuarioDto == null) { document.alert(UtilI18N.internacionaliza(request, "citcorpore.comum.sessaoExpirada")); document.executeScript( "window.location = '" + Constantes.getValue("SERVER_ADDRESS") + request.getContextPath() + "'"); return; } AcordoNivelServicoService acordoNivelServicoService = (AcordoNivelServicoService) ServiceLocator.getInstance().getService(AcordoNivelServicoService.class, null); RequisitoSLAService requisitoSLAService = (RequisitoSLAService) ServiceLocator.getInstance().getService(RequisitoSLAService.class, null); Collection colAcordos = acordoNivelServicoService.findAcordosSemVinculacaoDireta(); Collection colReqs = requisitoSLAService.list(); ControleGenerateSLAPorRequisitoSLA controleGenerateSLAPorRequisitoSLA = new ControleGenerateSLAPorRequisitoSLA(); ControleGenerateSLAPorRequisitoSLAEmAndamento controleGenerateSLAPorRequisitoSLAEmAndamento = new ControleGenerateSLAPorRequisitoSLAEmAndamento(); String table = "<table border='1'>"; if (colAcordos != null && colAcordos.size() > 0) { table += "<tr>"; table += "<td>"; table += "<b>" + UtilI18N.internacionaliza(request, "sla.avaliacao.acordo") + "</b>"; table += "</td>"; table += "</tr>"; table += "<tr>"; table += "<td>"; table += " "; table += "</td>"; table += "</tr>"; for (Iterator it = colAcordos.iterator(); it.hasNext(); ) { AcordoNivelServicoDTO acordoNivelServicoDTO = (AcordoNivelServicoDTO) it.next(); table += "<tr>"; table += "<td colspan='5' style='background-color:gray'>"; table += UtilI18N.internacionaliza(request, "citcorpore.comum.acordo") + ": <b>" + acordoNivelServicoDTO.getTituloSLA() + "</b>"; table += "</td>"; table += "</tr>"; if (acordoNivelServicoDTO.getTipo().equalsIgnoreCase("T")) { table += generateSLATime( document, request, acordoNivelServicoDTO, acordoNivelServicoDTO.getIdAcordoNivelServico(), usuarioDto); table += generateAvailSLATime( document, request, acordoNivelServicoDTO, acordoNivelServicoDTO.getIdAcordoNivelServico(), usuarioDto); } else if (acordoNivelServicoDTO.getTipo().equalsIgnoreCase("D")) { table += generateAvailSLAAvailability( document, request, response, acordoNivelServicoDTO, acordoNivelServicoDTO.getIdAcordoNivelServico(), usuarioDto); } } } if (colReqs != null && colReqs.size() > 0) { table += "<tr>"; table += "<td>"; table += " "; table += "</td>"; table += "</tr>"; table += "<tr>"; table += "<td>"; table += "<b>" + UtilI18N.internacionaliza(request, "sla.avaliacao.requisito") + "</b>"; table += "</td>"; table += "</tr>"; for (Iterator it = colReqs.iterator(); it.hasNext(); ) { RequisitoSLADTO requisitoSLADTO = (RequisitoSLADTO) it.next(); List lst = controleGenerateSLAPorRequisitoSLA.execute(requisitoSLADTO.getIdRequisitoSLA()); double qtdeDentroPrazo = 0; double qtdeForaPrazo = 0; if (lst != null && lst.size() > 0) { for (Iterator itSLA = lst.iterator(); itSLA.hasNext(); ) { Object[] objs = (Object[]) itSLA.next(); if (((String) objs[0]).indexOf("Fora") > -1 || ((String) objs[0]).indexOf("Out") > -1) { qtdeForaPrazo = (Double) objs[2]; } else { qtdeDentroPrazo = (Double) objs[2]; } } } double qtdeDentroPrazoPerc = (qtdeDentroPrazo / (qtdeDentroPrazo + qtdeForaPrazo)) * 100; double qtdeForaPrazoPerc = (qtdeForaPrazo / (qtdeDentroPrazo + qtdeForaPrazo)) * 100; final DefaultValueDataset dataset = new DefaultValueDataset(new Double(qtdeDentroPrazoPerc)); // create the chart... final ThermometerPlot plot = new ThermometerPlot(dataset); final JFreeChart chart = new JFreeChart( UtilI18N.internacionaliza(request, "sla.avaliacao.avaliacaogeral"), // chart title JFreeChart.DEFAULT_TITLE_FONT, plot, // plot false); // include legend plot.setSubrangeInfo(ThermometerPlot.NORMAL, 90.000001, 100); plot.setSubrangeInfo(ThermometerPlot.WARNING, 80.000001, 90); plot.setSubrangeInfo(ThermometerPlot.CRITICAL, 0, 80); plot.setThermometerStroke(new BasicStroke(2.0f)); plot.setThermometerPaint(Color.lightGray); String nomeImgAval = CITCorporeUtil.caminho_real_app + "/tempFiles/" + usuarioDto.getIdUsuario() + "/avalREQSLA_" + requisitoSLADTO.getIdRequisitoSLA() + ".png"; String nomeImgAvalRel = br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/tempFiles/" + usuarioDto.getIdUsuario() + "/avalREQSLA_" + requisitoSLADTO.getIdRequisitoSLA() + ".png"; File arquivo = new File(nomeImgAval); if (arquivo.exists()) { arquivo.delete(); } else { String nomeDir = CITCorporeUtil.caminho_real_app + "/tempFiles/" + usuarioDto.getIdUsuario() + "/"; File dirTemp = new File(nomeDir); dirTemp.mkdirs(); arquivo.createNewFile(); } ChartUtilities.saveChartAsPNG(arquivo, chart, 500, 200); List lst2 = controleGenerateSLAPorRequisitoSLAEmAndamento.execute( requisitoSLADTO.getIdRequisitoSLA()); qtdeDentroPrazo = 0; qtdeForaPrazo = 0; if (lst2 != null && lst2.size() > 0) { for (Iterator itSLA = lst2.iterator(); itSLA.hasNext(); ) { Object[] objs = (Object[]) itSLA.next(); if (((String) objs[0]).indexOf("Fora") > -1 || ((String) objs[0]).indexOf("Out") > -1) { qtdeForaPrazo = (Double) objs[2]; } else { qtdeDentroPrazo = (Double) objs[2]; } } } qtdeDentroPrazoPerc = (qtdeDentroPrazo / (qtdeDentroPrazo + qtdeForaPrazo)) * 100; qtdeForaPrazoPerc = (qtdeForaPrazo / (qtdeDentroPrazo + qtdeForaPrazo)) * 100; DefaultPieDataset datasetPie = new DefaultPieDataset(); datasetPie.setValue( UtilI18N.internacionaliza(request, "sla.avaliacao.noprazo") + " (" + UtilFormatacao.formatDouble(qtdeDentroPrazo, 0) + ")", new Double(qtdeDentroPrazoPerc)); datasetPie.setValue( UtilI18N.internacionaliza(request, "sla.avaliacao.foraprazo") + " (" + UtilFormatacao.formatDouble(qtdeForaPrazo, 0) + ")", new Double(qtdeForaPrazoPerc)); JFreeChart chartX = ChartFactory.createPieChart( UtilI18N.internacionaliza(request, "sla.avaliacao.emandamento"), // chart title datasetPie, // data true, // include legend false, false); PiePlot plotPie = (PiePlot) chartX.getPlot(); plotPie.setLabelFont(new Font("SansSerif", Font.PLAIN, 12)); plotPie.setNoDataMessage(UtilI18N.internacionaliza(request, "sla.avaliacao.naohadados")); plotPie.setCircular(false); plotPie.setLabelGap(0.02); String nomeImgAval2 = CITCorporeUtil.caminho_real_app + "/tempFiles/" + usuarioDto.getIdUsuario() + "/avalREQSLA2_" + requisitoSLADTO.getIdRequisitoSLA() + ".png"; String nomeImgAvalRel2 = br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/tempFiles/" + usuarioDto.getIdUsuario() + "/avalREQSLA2_" + requisitoSLADTO.getIdRequisitoSLA() + ".png"; File arquivo2 = new File(nomeImgAval2); if (arquivo2.exists()) { arquivo2.delete(); } ChartUtilities.saveChartAsPNG(arquivo2, chartX, 200, 200); table += "<tr>"; table += "<td style='border:1px solid black; vertical-align:middle;'>"; table += UtilHTML.encodeHTML(UtilStrings.retiraApostrofe(requisitoSLADTO.getAssunto())); table += "</td>"; table += "<td style='border:1px solid black; vertical-align:middle;'>"; if (requisitoSLADTO.getSituacao() != null && requisitoSLADTO.getSituacao().equalsIgnoreCase("A")) { table += "<img src='" + br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/imagens/bolaverde.png' border='0' title='" + UtilI18N.internacionaliza(request, "requisitosla.ativo") + "'/>"; table += UtilI18N.internacionaliza(request, "requisitosla.ativo"); } else if (requisitoSLADTO.getSituacao() != null && requisitoSLADTO.getSituacao().equalsIgnoreCase("P")) { table += "<img src='" + br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/imagens/bolavermelha.png' border='0' title='" + UtilI18N.internacionaliza(request, "requisitosla.planejamento") + "'/>"; table += UtilI18N.internacionaliza(request, "requisitosla.planejamento"); } else if (requisitoSLADTO.getSituacao() != null && requisitoSLADTO.getSituacao().equalsIgnoreCase("R")) { table += "<img src='" + br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/imagens/bolavermelha.png' border='0' title='" + UtilI18N.internacionaliza(request, "requisitosla.emrevisao") + "'/>"; table += UtilI18N.internacionaliza(request, "requisitosla.emrevisao"); } else { table += "<img src='" + br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS") + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO") + "/imagens/bolavermelha.png' border='0' title='" + UtilI18N.internacionaliza(request, "requisitosla.inativo") + "'/>"; table += UtilI18N.internacionaliza(request, "requisitosla.inativo"); } table += "</td>"; table += "<td style='border:1px solid black'>"; table += "<img src='" + nomeImgAvalRel + "' border='0'/>"; table += "</td>"; table += "<td style='border:1px solid black'>"; table += "<img src='" + nomeImgAvalRel2 + "' border='0'/>"; table += "</td>"; table += "</tr>"; } } table += "</table>"; document.getElementById("divInfo").setInnerHTML(table); }
@Override public JPanel getChart(int type, Object parameter1, Object parameter2) throws ApplicationException { // TODO Methode ausfertigen JFreeChart chart = null; switch (type) { case VISUALISIERUNG_ANTEIL_TESTATABNAHMEN: { /* Parameter 1 muss String sein, Parameter 2 muss NULL sein.*/ if (!(parameter1 instanceof String && parameter2 == null)) { throw new ApplicationException( "Die übergebenen Basisparameter passen nicht zum Visualisierungstyp."); } String semester = (String) parameter1; DefaultCategoryDataset dataset = new DefaultCategoryDataset(); /* Iteration über alle Studienrichtungen. */ for (Studienrichtung studr : this.getAllStudienrichtung()) { /* Anzahl der Studenten die sich für ein Praktikum eines Moduls in einem bestimmten Semester angemeldet haben. */ String sql = "SELECT M.MKUERZEL AS Modul, Count(*) AS Anmeldungen" + " FROM MODUL M, PRAKTIKUMSTEILNAHME P, STUDENT S" + " WHERE P.MATRIKEL = S.MATRIKEL" + " AND M.MKUERZEL = P.MKUERZEL" + " AND M.PR > 0" + " AND P.SEMESTER = '" + semester + "'" + " AND S.SKUERZEL = '" + studr.getKuerzel() + "'" + " GROUP BY M.MKUERZEL"; ResultSet resultSet = null; try { resultSet = executeQuery(sql); while (resultSet.next()) { /* Speichern der Anzahl der ANmeldungen zu einem * Modul */ String modul = resultSet.getString("Modul"); int anmeldungen = resultSet.getInt("Anmeldungen"); /* Anzahl der Bestandenen Praktikas eines Moduls in einem bestimmten Semester*/ sql = "SELECT M.MKUERZEL AS Modul, Count(*) AS Bestanden" + " FROM MODUL M, PRAKTIKUMSTEILNAHME P, STUDENT S" + " WHERE P.MATRIKEL = S.MATRIKEL" + " AND M.MKUERZEL = P.MKUERZEL" + " AND M.MKUERZEL = '" + modul + "'" + " AND M.PR > 0" + " AND P.SEMESTER = '" + semester + "'" + " AND S.SKUERZEL = '" + studr.getKuerzel() + "'" + " AND P.TESTAT > 0" + " GROUP BY M.MKUERZEL"; int bestanden = 0; ResultSet resultSet1 = executeQuery(sql); if (resultSet1.next()) { bestanden = resultSet1.getInt("Bestanden"); } /* Berechnung des Prozentualen Anteils von bestanden zu teilgenommen */ double wert = (bestanden == 0) ? 0 : (double) bestanden / (double) anmeldungen * 100; /* Dataset die Werte übergeben % - Wert, Modulname, Studienrichtung */ dataset.addValue(wert, modul, studr.getKuerzel()); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } } /* Neues Balken Diagramm erzeugen mit folgenden Werte: * Titel, X-Achse Beschreibung, Y-Achse Beschreibung, Daten, * Vertical/Horizontal, Legende, Tooltip, URL. */ chart = ChartFactory.createBarChart( semester, "Praktikumsmodule nach Studienrichtung", "Erfolgreiche Teilnahme in %", dataset, PlotOrientation.VERTICAL, true, true, false); } break; case VISUALISIERUNG_AUFTEILUNG_ANMELDUNGEN: { if (!(parameter1 instanceof Studienrichtung && parameter2 instanceof String)) { throw new ApplicationException( "Die übergebenen Basisparameter passen nicht zum Visualisierungstyp."); } Studienrichtung studienrichtung = (Studienrichtung) parameter1; String semester = (String) parameter2; DefaultPieDataset dataset = new DefaultPieDataset(); String sql = "SELECT M.MKUERZEL AS Modul, Count(*) AS Anmeldungen" + " FROM MODUL M, PRAKTIKUMSTEILNAHME P, STUDENT S" + " WHERE P.MATRIKEL = S.MATRIKEL" + " AND M.MKUERZEL = P.MKUERZEL" + " AND M.PR > 0" + " AND P.SEMESTER = '" + semester + "'" + " AND S.SKUERZEL = '" + studienrichtung.getKuerzel() + "'" + " GROUP BY M.MKUERZEL"; try { ResultSet resultSet = executeQuery(sql); int i = 0; while (resultSet.next()) { int tmpAnmelungen = resultSet.getInt("Anmeldungen"); String tmpModul = resultSet.getString("Modul"); /* SchlüsselText zusammenbauen */ String key = tmpModul + ": " + tmpAnmelungen + " Anmeldungen"; dataset.insertValue(i, key, tmpAnmelungen); i++; } } catch (SQLException ex) { System.out.println(ex.getMessage()); } /* PieChart erstellen: Titel, Daten, Legende, ToolTip, URL */ chart = ChartFactory.createPieChart( studienrichtung.toString() + " (" + semester + ")", dataset, true, true, false); } break; case VISUALISIERUNG_ENTWICKLUNG_ANMELDUNGEN: { if (!(parameter1 instanceof Modul && parameter2 == null)) { throw new ApplicationException( "Die übergebenen Basisparameter passen nicht zum Visualisierungstyp."); } Modul modul = (Modul) parameter1; DefaultCategoryDataset dataset = new DefaultCategoryDataset(); /* Anmeldungen/Testate zu einem Modul in allen Semestern*/ String sql = "SELECT count(*) AS Anmeldungen, P.SEMESTER, SUM(P.TESTAT) AS Testatvergaben" + " FROM PRAKTIKUMSTEILNAHME P" + " WHERE P.MKUERZEL = '" + modul.getKuerzel() + "'" + " GROUP BY P.SEMESTER"; try { ResultSet resultSet = executeQuery(sql); while (resultSet.next()) { String semester = resultSet.getString("Semester"); int anmeldungen = resultSet.getInt("Anmeldungen"); int testate = resultSet.getInt("Testatvergaben"); dataset.addValue(anmeldungen, "Anmeldungen", semester); dataset.addValue(testate, "Testatvergaben", semester); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } chart = ChartFactory.createLineChart( modul.getName() + " (" + modul.getKuerzel() + ")", "Semester", "Studierende", dataset, PlotOrientation.VERTICAL, true, true, false); } break; case VISUALISIERUNG_ANMELDUNGEN_TESTATE: { if (!(parameter1 instanceof Studienrichtung && parameter2 instanceof String)) { throw new ApplicationException( "Die übergebenen Basisparameter passen nicht zum Visualisierungstyp."); } Studienrichtung studienrichtung = (Studienrichtung) parameter1; String semester = (String) parameter2; DefaultCategoryDataset dataset = new DefaultCategoryDataset(); String sql = "SELECT count(*) AS Anmeldungen, SUM(P.TESTAT) AS Testatvergaben, P.MKUERZEL AS Modul" + " FROM PRAKTIKUMSTEILNAHME P, KATEGORIEUMFANG K" + " WHERE P.SEMESTER = '" + semester + "'" + " AND P.MKUERZEL = K.MKUERZEL" + " AND K.SKUERZEL = '" + studienrichtung.getKuerzel() + "'" + " GROUP BY P.MKUERZEL"; try { ResultSet resultSet = executeQuery(sql); while (resultSet.next()) { String modulName = resultSet.getString("Modul"); int anmeldungen = resultSet.getInt("Anmeldungen"); int testatvergaben = resultSet.getInt("Testatvergaben"); dataset.addValue(anmeldungen, "Anmeldungen", modulName); dataset.addValue(testatvergaben, "Testatvergaben", modulName); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } chart = ChartFactory.createBarChart( studienrichtung.getName() + " (" + studienrichtung.getKuerzel() + ")", "Modul", "Studierende", dataset, PlotOrientation.VERTICAL, true, true, false); } break; default: { throw new ApplicationException("Der Visualisierungstyp ist nicht definiert."); } } return new ChartPanel(chart); }
public JFreeChart getChart() { JFreeChart chart = null; try { Font font = new Font("宋体", 0, 20); // 字体 QuestionStatisticsModel qsm = ss.statistics(qid); DefaultPieDataset pieds = null; // 饼图的数据集 DefaultCategoryDataset cateds = null; // 种类数据集 if (chartType < 2) { pieds = new DefaultPieDataset(); for (OptionStatisticsModel os : qsm.getOsms()) { pieds.setValue(os.getOptionLabel(), os.getCount()); } } else { cateds = new DefaultCategoryDataset(); for (OptionStatisticsModel os : qsm.getOsms()) { cateds.setValue(os.getCount(), os.getOptionLabel(), ""); } } switch (chartType) { case CHARTTYPE_PIE_2D: chart = ChartFactory.createPieChart(qsm.getQuestion().getTitle(), pieds, true, false, false); break; case CHARTTYPE_PIE_3D: chart = ChartFactory.createPieChart3D(qsm.getQuestion().getTitle(), pieds, true, true, true); // 设置前景色透明度 chart.getPlot().setForegroundAlpha(0.6f); break; case CHARTTYPE_BAR_2D_H: // 平面条形图 chart = ChartFactory.createBarChart( qsm.getQuestion().getTitle(), "", "", cateds, PlotOrientation.HORIZONTAL, true, true, true); break; case CHARTTYPE_BAR_2D_V: // 平面条形图 chart = ChartFactory.createBarChart( qsm.getQuestion().getTitle(), "", "", cateds, PlotOrientation.VERTICAL, true, true, true); case CHARTTYPE_BAR_3D_H: // 平面条形图 chart = ChartFactory.createBarChart3D( qsm.getQuestion().getTitle(), "", "", cateds, PlotOrientation.HORIZONTAL, true, true, true); case CHARTTYPE_BAR_3D_V: // 平面条形图 chart = ChartFactory.createBarChart3D( qsm.getQuestion().getTitle(), "", "", cateds, PlotOrientation.VERTICAL, true, true, true); break; // case CHARTTYPE_LINE_2D: // 平面条形图 chart = ChartFactory.createLineChart( qsm.getQuestion().getTitle(), "", "", cateds, PlotOrientation.VERTICAL, true, true, true); break; case CHARTTYPE_LINE_3D: // 平面条形图 chart = ChartFactory.createLineChart3D( qsm.getQuestion().getTitle(), "", "", cateds, PlotOrientation.HORIZONTAL, true, true, true); break; } chart.getTitle().setFont(font); chart.getLegend().setItemFont(font); // 设置饼图特效 if (chart.getPlot() instanceof PiePlot) { PiePlot pieplot = (PiePlot) chart.getPlot(); pieplot.setLabelFont(font); pieplot.setExplodePercent(0, 0.1); pieplot.setStartAngle(-15); pieplot.setDirection(Rotation.CLOCKWISE); pieplot.setNoDataMessage("No data to display"); // pieplot.setForegroundAlpha(0.5f); // pieplot.setBackgroundImageAlpha(0.3f); } // 设置非饼图效果 else { chart.getCategoryPlot().getRangeAxis().setLabelFont(font); chart.getCategoryPlot().getRangeAxis().setTickLabelFont(font); chart.getCategoryPlot().getDomainAxis().setLabelFont(font); chart.getCategoryPlot().getDomainAxis().setTickLabelFont(font); } } catch (Exception e) { e.printStackTrace(); } return chart; }
/* (non-Javadoc) * @see com.lily.dap.service.report2.impl.chart.ChartStrategy#outputChart(java.lang.String, int, int, java.util.Map, java.util.List, java.io.OutputStream) */ public void outputChart( String type, int height, int width, Map<String, String> paramMap, Map<String, Object> variableMap, List<Map<String, Object>> dataList, OutputStream os) throws IOException { String nameField = ChartUtils.evaluateParam(paramMap.get("namefield"), variableMap); String valueField = ChartUtils.evaluateParam(paramMap.get("valuefield"), variableMap); DefaultPieDataset dataset = createDataset(dataList, nameField, valueField); String title = ChartUtils.evaluateParam(paramMap.get("title"), variableMap); boolean legend = paramMap.get("legend") == null ? true : "true" .equals( ChartUtils.evaluateParam(paramMap.get("legend"), variableMap).toLowerCase()); JFreeChart chart; if (ChartConstants.TYPE_PIE3D.equals(type)) chart = ChartFactory.createPieChart3D( title, // 图表标题 dataset, // 数据集 legend, // 是否显示图例 false, // 是否生成工具 false // 是否生成URL链接 ); else chart = ChartFactory.createPieChart( title, // 图表标题 dataset, // 数据集 legend, // 是否显示图例 false, // 是否生成工具 false // 是否生成URL链接 ); // 设置标题字体 if (chart.getTitle() != null) chart.getTitle().setFont(titleFont); // 设置图例字体 if (chart.getLegend() != null) chart.getLegend().setItemFont(legendFont); PiePlot pie = (PiePlot) chart.getPlot(); // if (pie instanceof PiePlot3D) { // PiePlot3D pie3d = (PiePlot3D)pie; // } // 设置前景透明度 if (paramMap.get("foregroundAlpha") != null) { float f = Float.parseFloat(ChartUtils.evaluateParam(paramMap.get("foregroundAlpha"), variableMap)); pie.setForegroundAlpha(f); } // 设置标签的最大宽度 if (paramMap.get("maximumlabelwidth") != null) { float f = Float.parseFloat( ChartUtils.evaluateParam(paramMap.get("maximumlabelwidth"), variableMap)); pie.setMaximumLabelWidth(f); } // 设置标饼上标签的标签字体 pie.setLabelFont(labelFont); String labelFormat = paramMap.get("labelformat"); if (labelFormat != null) { /* * 因为labelformat参数可能包含{0}、{1}、{2}这样的字符串,所以要通过检查'{'后面跟的字符是不是数字,来判断labelformat参数是不是表达式 */ int index = labelFormat.indexOf('{'); if (index >= 0) { char ch = labelFormat.charAt(index + 1); if (!CharUtils.isAsciiNumeric(ch)) labelFormat = ChartUtils.evaluateParam(labelFormat, variableMap); } // 设置饼上标签的显示格式,其中,0:数据名称,1:数据值,2:数据占整个百分比 StandardPieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator(labelFormat); pie.setLabelGenerator(generator); } String legendformat = paramMap.get("legendformat"); if (legendformat != null) { /* * 因为legendformat参数可能包含{0}、{1}、{2}这样的字符串,所以要通过检查'{'后面跟的字符是不是数字,来判断legendformat参数是不是表达式 */ int index = legendformat.indexOf('{'); if (index >= 0) { char ch = legendformat.charAt(index + 1); if (!CharUtils.isAsciiNumeric(ch)) legendformat = ChartUtils.evaluateParam(legendformat, variableMap); } // 设置饼上标签的显示格式,其中,0:数据名称,1:数据值,2:数据占整个百分比 StandardPieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator(legendformat); pie.setLegendLabelGenerator(generator); } if (paramMap.get("color") != null) { int index = 0; String[] colGroups = ChartUtils.evaluateParam(paramMap.get("color"), variableMap).split(","); for (String colVal : colGroups) { Color color = ChartUtils.createColor(colVal.trim()); pie.setSectionPaint(index++, color); } } // 设置饼图是圆形还是椭圆形 if (paramMap.get("circular") != null) { boolean isCircular = "true" .equals( ChartUtils.evaluateParam(paramMap.get("circular"), variableMap).toLowerCase()); pie.setCircular(isCircular); } ChartUtilities.writeChartAsJPEG(os, 1, chart, width, height, null); }
/** JFreeChartオブジェクトを作成する */ private JFreeChart createChartObject(Document doc) { Element root = doc.getDocumentElement(); Element chartInfo = (Element) root.getElementsByTagName("ChartInfo").item(0); String chartTitle = chartInfo.getElementsByTagName("Title").item(0).getFirstChild().getNodeValue(); this.chartType = chartInfo.getElementsByTagName("Type").item(0).getFirstChild().getNodeValue(); String categoryLabel = ((Element) chartInfo.getElementsByTagName("Category").item(0)) .getElementsByTagName("Label") .item(0) .getFirstChild() .getNodeValue(); Element firstSeries = (Element) ((Element) chartInfo.getElementsByTagName("SeriesList").item(0)) .getElementsByTagName("Series") .item(0); String firstSeriesLabel = firstSeries.getElementsByTagName("Label").item(0).getFirstChild().getNodeValue(); // データセットのリストを取得 this.dataSetList = this.getDatasetList(doc); // 棒チャート(Series数に関わらない) if (this.chartType.equals("VerticalBar") || this.chartType.equals("HorizontalBar") || this.chartType.equals("VerticalMultiBar") || this.chartType.equals("HorizontalMultiBar")) { chart = ChartFactory.createBarChart( chartTitle, categoryLabel, firstSeriesLabel, (CategoryDataset) this.dataSetList.get(0), getLayoutFromDoc(doc), false, false, false); } // 3D棒チャート(Series数に関わらない) else if (this.chartType.equals("Vertical3D_Bar") || this.chartType.equals("Horizontal3D_Bar") || this.chartType.equals("VerticalMulti3D_Bar") || this.chartType.equals("HorizontalMulti3D_Bar")) { chart = ChartFactory.createBarChart3D( chartTitle, categoryLabel, firstSeriesLabel, (CategoryDataset) this.dataSetList.get(0), getLayoutFromDoc(doc), false, false, false); } // 積み上げ棒チャート else if ((this.chartType.equals("VerticalStackedBar")) || (this.chartType.equals("HorizontalStackedBar"))) { chart = ChartFactory.createStackedBarChart( chartTitle, categoryLabel, firstSeriesLabel, (CategoryDataset) this.dataSetList.get(0), getLayoutFromDoc(doc), false, false, false); } // 3D積み上げ棒チャート else if ((this.chartType.equals("VerticalStacked3D_Bar")) || (this.chartType.equals("HorizontalStacked3D_Bar"))) { chart = ChartFactory.createStackedBarChart3D( chartTitle, categoryLabel, firstSeriesLabel, (CategoryDataset) this.dataSetList.get(0), getLayoutFromDoc(doc), false, false, false); } // 折れ線チャート(Series数に関わらない) else if ((this.chartType.equals("Line")) || (this.chartType.equals("MultiLine"))) { chart = ChartFactory.createLineChart( chartTitle, categoryLabel, firstSeriesLabel, (CategoryDataset) this.dataSetList.get(0), PlotOrientation.VERTICAL, false, false, false); } // 面チャート(Series数に関わらない) else if ((this.chartType.equals("Area")) || (this.chartType.equals("MultiArea"))) { chart = ChartFactory.createAreaChart( chartTitle, categoryLabel, firstSeriesLabel, (CategoryDataset) this.dataSetList.get(0), PlotOrientation.VERTICAL, false, false, false); } // 積み上げ面チャート else if (this.chartType.equals("StackedArea")) { chart = ChartFactory.createStackedAreaChart( chartTitle, categoryLabel, firstSeriesLabel, (CategoryDataset) this.dataSetList.get(0), PlotOrientation.VERTICAL, false, false, false); } // 円チャート(Series数に関わらない) else if (this.chartType.equals("Pie")) { chart = ChartFactory.createPieChart( chartTitle, (PieDataset) this.dataSetList.get(0), false, false, false); } // 3D円チャート(Series数に関わらない) else if (this.chartType.equals("Pie_3D")) { chart = ChartFactory.createPieChart3D( chartTitle, (PieDataset) this.dataSetList.get(0), false, false, false); } // 複数円チャート(Series数が2以上) else if (this.chartType.equals("MultiPie")) { // 複数円チャート chart = ChartFactory.createMultiplePieChart( chartTitle, (CategoryDataset) this.dataSetList.get(0), TableOrder.BY_ROW, false, false, false); } return chart; }
/** * Initialises the class and internal logger. Uses the supplied arguments to receive data from the * application and add data to the charts dynamically. * * @param title The title of the charts on display. Whether the displayed data is for <code>new * </code> or <code>old</code> links. That is whether the data is for newly discovered links * or existing (old) links already stored within the database. * @param parent The instance of <code>COMPortClient</code> that acts as the data source for the * charts. */ public LinkChart(String title, COMPortClient parent) { super("Charts", true, true, true, true); super.setLayer(1); identifier = title.toLowerCase(); // Obtain an instance of Logger for the class log = LoggerFactory.getLogger(className); owner = parent; // Setup a hashtable to hold the values for up, down and unknown link states Hashtable<String, Integer> linkStats = new Hashtable<String, Integer>(); if (identifier.equals("old")) { this.setTitle("Recognised Link Status on " + owner.getPortName() + ":"); // Get the current figures from the link table linkStats = ((LinkTable) owner.getLinkTable().getModel()).getInitialFigures(); } else if (identifier.equals("new")) { this.setTitle("Discovered Link Status on " + owner.getPortName() + ":"); linkStats = ((LinkTable) owner.getNewLinkTable().getModel()).getInitialFigures(); } else { // If the identifier was set to something other than old or new then it's not right. log.warning("An instance of LinkChart has been created for an unknown purpose."); return; } // Initialise the dataset for the pie chart dpdCurrentData = new DefaultPieDataset(); dpdCurrentData.insertValue(0, "Link Down", linkStats.get("down")); dpdCurrentData.insertValue(1, "Link Up", linkStats.get("up")); dpdCurrentData.insertValue(2, "Link State Unknown", linkStats.get("unknown")); // Initialise the dataset for the line chart dcdPreviousData = new DefaultCategoryDataset(); dcdPreviousData.addValue( linkStats.get("down"), "Link Down", Calendar.getInstance().getTime().toString()); dcdPreviousData.addValue( linkStats.get("up"), "Link Up", Calendar.getInstance().getTime().toString()); dcdPreviousData.addValue( linkStats.get("unknown"), "Link State Unknown", Calendar.getInstance().getTime().toString()); // Set the variables we need for holding the charts JFreeChart jfcCurrentStatus; // This will be displayed as a pie chart JFreeChart jfcPreviousStatus; // This will be displayed as a line chart ChartPanel cpCurrent; // Chartpanels hold the JFreeChart ChartPanel cpPrevious; // Use the factory to create the charts jfcCurrentStatus = ChartFactory.createPieChart("Current Status", dpdCurrentData, true, true, false); jfcPreviousStatus = ChartFactory.createLineChart( "Previous Status", "Time received", "Number of Links", dcdPreviousData, PlotOrientation.VERTICAL, true, true, false); // Add them to the chart panels cpCurrent = new ChartPanel(jfcCurrentStatus); cpPrevious = new ChartPanel(jfcPreviousStatus); // Add the chart panels to the content pane this.add(cpCurrent, BorderLayout.EAST); this.add(cpPrevious, BorderLayout.WEST); // Change the layout to show them next to each other this.setLayout(new GridLayout(1, 2)); // Add a listener to the window this.addInternalFrameListener(new CloseLinkChart(this)); log.finest("Adding frame to the desktop"); // Set the window properties and display it Client.getJNWindow().addToDesktop(this); this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.setSize(650, 400); this.setVisible(true); owner.addChartWindow(title, this); }
@Override protected JFreeChart createChart(String title, Dataset dataset) { JFreeChart chart = ChartFactory.createPieChart(title, (PieDataset) dataset, true, true, false); return chart; }