Ejemplo n.º 1
0
  public void onSimulationComplete() {
    // TODO Auto-generated method stub

    this.removeAll();

    synchronized (this) {
      chartPanel = newChart(data);
    }

    this.setLayout(new BorderLayout());
    add(chartPanel, (new BorderLayout()).CENTER);

    chartPanel.updateUI();

    File file;

    try {
      file = new File(outputpath);
    } catch (Exception e) {
      System.err.println("Graph Plugin " + label + " : Invalid output path" + e);
      return;
    }

    try {
      int width = 1920;
      int height = 1200;
      ChartUtilities.saveChartAsPNG(file, chartPanel.getChart(), width, height);
    } catch (Exception e) {
      System.out.println("Problem occurred creating chart." + label);
    }
  }
Ejemplo n.º 2
0
 private void writeChart(final String outFile, final JFreeChart chart) {
   try {
     ChartUtilities.saveChartAsPNG(new File(outFile), chart, 650, 455);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 3
0
  public static void generateHistogram(
      String fileName,
      double[] value,
      int numberOfBins,
      String title,
      String xLabel,
      String yLabel) {
    HistogramDataset dataset = new HistogramDataset();
    dataset.setType(HistogramType.FREQUENCY);
    dataset.addSeries(title, value, numberOfBins);
    String plotTitle = title;
    String xaxis = xLabel;
    String yaxis = yLabel;
    PlotOrientation orientation = PlotOrientation.VERTICAL;
    boolean show = false;
    boolean toolTips = false;
    boolean urls = false;
    JFreeChart chart =
        ChartFactory.createHistogram(
            plotTitle, xaxis, yaxis, dataset, orientation, show, toolTips, urls);
    int width = 500;
    int height = 300;
    try {
      ChartUtilities.saveChartAsPNG(new File(fileName), chart, width, height);
    } catch (IOException e) {

    }
  }
Ejemplo n.º 4
0
 /**
  * Writes a graphic showing the number of departures, arrivals and vehicles en route of all
  * legs/trips with the specified transportation mode to the specified file.
  *
  * @param filename
  * @param legMode
  * @see #getGraphic(String)
  */
 public void writeGraphic(final String filename, final String legMode) {
   try {
     ChartUtilities.saveChartAsPNG(new File(filename), getGraphic(legMode), 1024, 768);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  private static void generateChart(
      String benchmark, DefaultCategoryDataset dataset, int benchmarkCount) {
    JFreeChart chart =
        ChartFactory.createBarChart(
            benchmark,
            "framework",
            "throughput",
            dataset,
            PlotOrientation.HORIZONTAL,
            true,
            false,
            false);

    CategoryPlot plot = chart.getCategoryPlot();
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setItemMargin(0);
    notSoUglyPlease(chart);

    String pngFile = getOutputName(benchmark);

    try {
      int height = 100 + benchmarkCount * 20;
      ChartUtilities.saveChartAsPNG(new File(pngFile), chart, 700, height);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Ejemplo n.º 6
0
  protected void saveImage(String type) {

    // TODO 3 Image size should be dependent on the system graphics or configurable
    int height = 793;
    int width = 1120;

    AdvancedFileChooser fileChooser = new AdvancedFileChooser();

    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    int returnVal = fileChooser.showSaveDialog(chartPanel);

    File filePath = null;
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      filePath = fileChooser.getSelectedFile();
    }

    String tempPath = filePath.getAbsolutePath().toUpperCase();

    try {
      if (type.equals("PNG")) {
        if (!tempPath.endsWith(".PNG")) filePath = new File(tempPath + ".PNG");
        ChartUtilities.saveChartAsPNG(filePath, getChart(), width, height);
      } else if (type.equals("JPEG")) {
        if (!tempPath.endsWith(".JPEG")) filePath = new File(tempPath + ".JPEG");
        ChartUtilities.saveChartAsJPEG(filePath, getChart(), width, height);
      }
    } catch (IOException ie) {

    }
  }
Ejemplo n.º 7
0
  public static void drawPic(String url, String file) throws FileNotFoundException, IOException {
    //		XYSeries xyseries = getXY(url);
    XYSeries xyseries = getXYseries(url);
    XYSeriesCollection xyseriescollection =
        new XYSeriesCollection(); // 再用XYSeriesCollection添加入XYSeries
    // 对象
    xyseriescollection.addSeries(xyseries);

    // 创建主题样式
    StandardChartTheme standardChartTheme = new StandardChartTheme("CN");
    // 设置标题字体
    standardChartTheme.setExtraLargeFont(new Font("隶书", Font.BOLD, 20));
    // 设置图例的字体
    standardChartTheme.setRegularFont(new Font("宋书", Font.PLAIN, 15));
    // 设置轴向的字体
    standardChartTheme.setLargeFont(new Font("宋书", Font.PLAIN, 15));
    // 应用主题样式
    ChartFactory.setChartTheme(standardChartTheme);
    // JFreeChart chart=ChartFactory.createXYAreaChart("xyPoit", "点的标号",
    // "出现次数", xyseriescollection, PlotOrientation.VERTICAL, true, false,
    // false);
    JFreeChart chart =
        ChartFactory.createScatterPlot(
            "决策图", "点密度", "点距离", xyseriescollection, PlotOrientation.VERTICAL, true, false, false);
    //		String file="d:/decision_chart.png";
    try {
      ChartUtilities.saveChartAsPNG(new File(file), chart, 470, 470);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    System.out.println(new java.util.Date() + ": finished drawing the pic in " + file);
  }
  private void scatterPlot(
      Map<Double, Map<String, Tuple<Double, Double>>> inputData, String outFile) {

    String mode1 = travelModes[0];
    String mode2 = travelModes[1];

    XYSeries carFlow = new XYSeries(mode1 + " flow");
    XYSeries bikeFlow = new XYSeries(mode2 + " flow");
    XYSeries carSpeed = new XYSeries(mode1 + " speed");
    XYSeries bikeSpeed = new XYSeries(mode2 + " speed");

    for (double d : inputData.keySet()) {
      carFlow.add(d, inputData.get(d).get(mode1).getFirst());
      carSpeed.add(d, inputData.get(d).get(mode1).getSecond());

      bikeFlow.add(d, inputData.get(d).get(mode2).getFirst());
      bikeSpeed.add(d, inputData.get(d).get(mode2).getSecond());
    }

    // flow vs density
    XYSeriesCollection flowDataset = new XYSeriesCollection();
    flowDataset.addSeries(carFlow);
    flowDataset.addSeries(bikeFlow);

    NumberAxis flowAxis = new NumberAxis("Flow (PCU/h)");
    flowAxis.setRange(0.0, 2100.0);

    XYPlot plot1 = new XYPlot(flowDataset, null, flowAxis, new XYLineAndShapeRenderer(false, true));
    plot1.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);

    // speed vs density
    XYSeriesCollection speedDataset = new XYSeriesCollection();
    speedDataset.addSeries(carSpeed);
    speedDataset.addSeries(bikeSpeed);

    NumberAxis speedAxis = new NumberAxis("Speed (m/s)");
    speedAxis.setRange(0.0, 17.0);

    XYPlot plot2 =
        new XYPlot(speedDataset, null, speedAxis, new XYLineAndShapeRenderer(false, true));
    plot2.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);

    NumberAxis densityAxis = new NumberAxis("Overall density (PCU/km)");
    densityAxis.setRange(0.0, 150.00);

    CombinedDomainXYPlot plot = new CombinedDomainXYPlot(densityAxis);
    plot.setGap(10.);
    plot.add(plot1);
    plot.add(plot2);
    plot.setOrientation(PlotOrientation.VERTICAL);

    JFreeChart chart =
        new JFreeChart("Fundamental diagrams", JFreeChart.DEFAULT_TITLE_FONT, plot, true);

    try {
      ChartUtilities.saveChartAsPNG(new File(outFile), chart, 800, 600);
    } catch (IOException e) {
      throw new RuntimeException("Data is not plotted. Reason " + e);
    }
  }
 public void writeXYsGraphic(final String fileName, final int numberOfBins) {
   JFreeChart chart = this.getTraveledXYsHistogram(numberOfBins);
   try {
     ChartUtilities.saveChartAsPNG(new File(fileName), chart, 1024, 768);
   } catch (IOException e) {
     log.error(
         "got an error while trying to write graphics to file."
             + " Error is not fatal, but output may be incomplete.");
     e.printStackTrace();
   }
 }
  private void createBarchart(
      String title,
      String categoryLabel,
      String valueLabel,
      PlotData[] data,
      String[] dataLabels,
      String filename) {

    DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
    int maxDataLength = 0;

    for (int i = 0; i < dataLabels.length; i++) {
      for (int j = 0; j < data[i].getData().length; j++) {
        dataSet.addValue(data[i].getData()[j], dataLabels[i], data[i].getLabels()[j]);
      }
      if (maxDataLength < data[i].getData().length) {
        maxDataLength = data[i].getData().length;
      }
    }

    JFreeChart chart =
        ChartFactory.createBarChart(
            title,
            categoryLabel,
            valueLabel,
            dataSet,
            PlotOrientation.VERTICAL,
            dataLabels.length > 1, // display legend
            false,
            false);

    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    CategoryAxis xAxis = (CategoryAxis) plot.getDomainAxis();
    xAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);
    xAxis.setMaximumCategoryLabelLines(6);

    // chart.setBackgroundPaint(ChartColor.WHITE);
    int width = 50 + maxDataLength * 170;
    if (maxDataLength < 3) {
      width += 170;
    }
    int height = 400;
    try {
      File file = new File(contextPath + filename);
      ChartUtilities.saveChartAsPNG(file, chart, width, height);
    } catch (IOException e) {
      LOG.warn("createBarchart(): ", e);
    }
  }
Ejemplo n.º 11
0
  // @Test
  public void sprintBurndown() {
    List<BurndownSnapshot> shots = new ArrayList<BurndownSnapshot>();

    shots.add(shot(new Date(2008, 7, 1), 0, 0));
    shots.add(shot(new Date(2008, 7, 2), 0, 0));
    shots.add(shot(new Date(2008, 7, 3), 0, 0));
    shots.add(shot(new Date(2008, 7, 4), 5, 45));
    shots.add(shot(new Date(2008, 7, 5), 10, 40));
    shots.add(shot(new Date(2008, 7, 6), 15, 35));
    shots.add(shot(new Date(2008, 7, 7), 18, 40));
    shots.add(shot(new Date(2008, 7, 8), 25, 33));
    shots.add(shot(new Date(2008, 7, 9), 28, 30));

    DefaultXYDataset data =
        BurndownChart.createSprintBurndownChartDataset(
            shots, new Date(2008, 7, 1), new Date(2008, 7, 31));
    double tick = 1.0;
    double max = BurndownChart.getMaximum(data);

    while (max / tick > 25) {
      tick *= 2;
      if (max / tick <= 25) break;
      tick *= 2.5;
      if (max / tick <= 25) break;
      tick *= 2;
    }
    JFreeChart chart =
        BurndownChart.createSprintBurndownChart(
            data,
            "Date",
            "Work",
            new Date(2008, 7, 1),
            new Date(2008, 7, 31),
            1,
            3,
            max * 1.1,
            tick);

    File file = new File("test-output/sprintBurndownChart.png");
    IO.createDirectory(file.getParentFile());
    try {
      ChartUtilities.saveChartAsPNG(file, chart, 500, 500);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  private void saveCurrentChart() {
    String fileName = new SimpleDateFormat("yyyyMMddhhmmssSS'.png'").format(new Date());
    try {

      NumberAxis domain = (NumberAxis) this.timeseriesPlot.getDomainAxis();
      Range domainRange = domain.getRange();

      NumberAxis range = (NumberAxis) this.timeseriesPlot.getRangeAxis();
      Range rangeRange = range.getRange();

      String annotationString =
          "W:"
              + this.chartData.getSAXWindowSize()
              + ", P:"
              + this.chartData.getSAXPaaSize()
              + ", A:"
              + this.chartData.getSAXAlphabetSize();

      XYTextAnnotation a =
          new XYTextAnnotation(
              annotationString,
              domainRange.getLowerBound() + domainRange.getLength() / 100,
              rangeRange.getLowerBound() + rangeRange.getLength() / 5 * 3.5);

      a.setTextAnchor(TextAnchor.BOTTOM_LEFT);

      a.setPaint(Color.RED);
      a.setOutlinePaint(Color.BLACK);
      a.setOutlineVisible(true);

      a.setFont(new java.awt.Font("SansSerif", java.awt.Font.BOLD, 14));

      // XYPointerAnnotation a = new XYPointerAnnotation("Bam!", domainRange.getLowerBound()
      // + domainRange.getLength() / 10, rangeRange.getLowerBound() + rangeRange.getLength() / 5
      // * 4, 5 * Math.PI / 8);

      this.timeseriesPlot.addAnnotation(a);

      // this.paintTheChart();

      ChartUtilities.saveChartAsPNG(new File(fileName), this.chart, 1400, 425);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 13
0
  public static void generateXYScatterPlot(
      String fileName, double[] x, double[] y, String title, String xLabel, String yLabel) {

    if (x.length != y.length) {
      DebugLib.stopSystemAndReportInconsistency("dimensions of arrays do not match");
    }

    final XYSeries series1 = new XYSeries(title);

    for (int i = 0; i < x.length; i++) {
      series1.add(x[i], y[i]);
    }

    final XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series1);

    final JFreeChart chart =
        ChartFactory.createXYLineChart(
            title, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, true, true, false);

    chart.setBackgroundPaint(Color.white);

    final XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);

    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setSeriesLinesVisible(0, false);
    renderer.setSeriesShapesVisible(1, false);
    plot.setRenderer(renderer);

    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    int width = 500;
    int height = 300;

    try {
      ChartUtilities.saveChartAsPNG(new File(fileName), chart, width, height);
    } catch (IOException e) {

    }
  }
  public static void generate(ClusterTimeSeriesReport report, String reportDir, String fileName)
      throws IOException {
    File root = new File(reportDir);
    if (!root.exists()) {
      if (!root.mkdirs()) {
        log.warn(
            "Could not create root dir : "
                + root.getAbsolutePath()
                + " This might result in reports not being generated");
      } else {
        log.info("Created root file: " + root);
      }
    }
    File chartFile = new File(root, fileName + ".png");
    Utils.backupFile(chartFile);

    ChartUtilities.saveChartAsPNG(chartFile, createChart(report), 1024, 768);

    log.info("Chart saved as " + chartFile);
  }
Ejemplo n.º 15
0
  /**
   * Saves the chart as a PNG format file in the temporary directory and populates the {@link
   * ChartRenderingInfo} object which can be used to generate an HTML image map.
   *
   * @param chart the chart to be saved (<code>null</code> not permitted).
   * @param width the width of the chart.
   * @param height the height of the chart.
   * @param info the ChartRenderingInfo object to be populated (<code>null</code> permitted).
   * @param session the HttpSession of the client (if <code>null</code>, the temporary file is
   *     marked as "one-time" and deleted by the {@link DisplayChart} servlet right after it is
   *     streamed to the client).
   * @return The filename of the chart saved in the temporary directory.
   * @throws IOException if there is a problem saving the file.
   */
  public static String saveChartAsPNG(
      JFreeChart chart, int width, int height, ChartRenderingInfo info, HttpSession session)
      throws IOException {

    if (chart == null) {
      throw new IllegalArgumentException("Null 'chart' argument.");
    }
    ServletUtilities.createTempDir();
    String prefix = ServletUtilities.tempFilePrefix;
    if (session == null) {
      prefix = ServletUtilities.tempOneTimeFilePrefix;
    }
    File tempFile =
        File.createTempFile(prefix, ".png", new File(System.getProperty("java.io.tmpdir")));
    ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
    if (session != null) {
      ServletUtilities.registerChartForDeletion(tempFile, session);
    }
    return tempFile.getName();
  }
Ejemplo n.º 16
0
 public static void main(String args[]) {
   SampleXYDataset2 samplexydataset2 = new SampleXYDataset2();
   JFreeChart jfreechart =
       ChartFactory.createScatterPlot(
           "Scatter Plot Demo",
           "X",
           "Y",
           samplexydataset2,
           PlotOrientation.VERTICAL,
           true,
           true,
           false);
   jfreechart.setBackgroundPaint(Color.white);
   XYPlot xyplot = (XYPlot) jfreechart.getPlot();
   NumberAxis numberaxis = (NumberAxis) xyplot.getDomainAxis();
   numberaxis.setAutoRangeIncludesZero(false);
   try {
     ChartRenderingInfo chartrenderinginfo =
         new ChartRenderingInfo(new StandardEntityCollection());
     File file = new File("scatter100.png");
     ChartUtilities.saveChartAsPNG(file, jfreechart, 600, 400, chartrenderinginfo);
     File file1 = new File("scatter100.html");
     BufferedOutputStream bufferedoutputstream =
         new BufferedOutputStream(new FileOutputStream(file1));
     PrintWriter printwriter = new PrintWriter(bufferedoutputstream);
     printwriter.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"");
     printwriter.println("\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
     printwriter.println(
         "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">");
     printwriter.println("<head><title>JFreeChart Image Map Demo</title></head>");
     printwriter.println("<body><p>");
     ImageMapUtilities.writeImageMap(printwriter, "chart", chartrenderinginfo);
     printwriter.println(
         "<img src=\"scatter100.png\" width=\"600\" height=\"400\" usemap=\"#chart\" alt=\"scatter100.png\"/>");
     printwriter.println("</p></body>");
     printwriter.println("</html>");
     printwriter.close();
   } catch (IOException ioexception) {
     System.out.println(ioexception.toString());
   }
 }
Ejemplo n.º 17
0
  /** Saves the chart image and HTML. */
  public void saveImageAndHTML() {

    final CategoryDataset dataset = createDataset();
    final JFreeChart chart = createChart(dataset);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    *
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
      final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
      final File file1 = new File("multipiechart100.png");
      ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

      // write an HTML page incorporating the image with an image map
      final File file2 = new File("multipiechart100.html");
      final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
      final PrintWriter writer = new PrintWriter(out);
      writer.println("<HTML>");
      writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
      writer.println("<BODY>");
      ChartUtilities.writeImageMap(writer, "chart", info, true);
      writer.println(
          "<IMG SRC=\"multipiechart100.png\" "
              + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
      writer.println("</BODY>");
      writer.println("</HTML>");
      writer.close();

    } catch (IOException e) {
      System.out.println(e.toString());
    }
  }
Ejemplo n.º 18
0
  public String createChart(ArrayList<WaveSegmentArray> arrayOfResponses, String vpdsURL) {
    logger.info(Const.API_QUERYDATA, "Static Graph:: Data Size:" + arrayOfResponses.size());
    XYDataset dataset = createDataset(arrayOfResponses, vpdsURL);
    JFreeChart chart = createJFreeChart(dataset);
    String uuid = UUID.randomUUID().toString();

    try {
      String path = QueryData.class.getProtectionDomain().getCodeSource().getLocation().getPath();
      String decodedPath = URLDecoder.decode(path, "UTF-8");
      ChartUtilities.saveChartAsPNG(
          new File(decodedPath + "/" + Const.BASE_IMAGE_URL + uuid + ".png").getCanonicalFile(),
          chart,
          800,
          800);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return uuid;
  }
Ejemplo n.º 19
0
  public void createGraph(final String filename, final TransitRoute route) {

    HashMap<Id, Integer> stopIndex = new HashMap<Id, Integer>();
    int idx = 0;
    for (TransitRouteStop stop : route.getStops()) {
      stopIndex.put(stop.getStopFacility().getId(), idx);
      idx++;
    }

    HashSet<Id> vehicles = new HashSet<Id>();
    for (Departure dep : route.getDepartures().values()) {
      vehicles.add(dep.getVehicleId());
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    int numSeries = 0;
    double earliestTime = Double.POSITIVE_INFINITY;
    double latestTime = Double.NEGATIVE_INFINITY;

    for (Map.Entry<Id, List<Tuple<Id, Double>>> entry : this.positions.entrySet()) {
      if (vehicles.contains(entry.getKey())) {
        XYSeries series = new XYSeries("t", false, true);
        for (Tuple<Id, Double> pos : entry.getValue()) {
          Integer stopIdx = stopIndex.get(pos.getFirst());
          if (stopIdx != null) {
            double time = pos.getSecond().doubleValue();
            series.add(stopIdx.intValue(), time);
            if (time < earliestTime) {
              earliestTime = time;
            }
            if (time > latestTime) {
              latestTime = time;
            }
          }
        }
        dataset.addSeries(series);
        numSeries++;
      }
    }

    JFreeChart c =
        ChartFactory.createXYLineChart(
            "Route-Time Diagram, Route = " + route.getId(),
            "stops",
            "time",
            dataset,
            PlotOrientation.VERTICAL,
            false, // legend?
            false, // tooltips?
            false // URLs?
            );
    c.setBackgroundPaint(new Color(1.0f, 1.0f, 1.0f, 1.0f));

    XYPlot p = (XYPlot) c.getPlot();

    p.getRangeAxis().setInverted(true);
    p.getRangeAxis().setRange(earliestTime, latestTime);
    XYItemRenderer renderer = p.getRenderer();
    for (int i = 0; i < numSeries; i++) {
      renderer.setSeriesPaint(i, Color.black);
    }

    try {
      ChartUtilities.saveChartAsPNG(new File(filename), c, 1024, 768, null, true, 9);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 20
0
  private String geraTabelaMeses(
      String tituloSLA,
      Integer idAcordoNivelServico,
      HttpServletRequest request,
      UsuarioDTO usuarioDto)
      throws ParseException, IOException {
    ControleGenerateSLAPorAcordoNivelServicoByMesAno
        controleGenerateSLAPorAcordoNivelServicoByMesAno =
            new ControleGenerateSLAPorAcordoNivelServicoByMesAno();
    int m = UtilDatas.getMonth(UtilDatas.getDataAtual());
    int y = UtilDatas.getYear(UtilDatas.getDataAtual());
    int mPesq = (m + 1); // Faz este incremento de 1, pois logo que entrar no laço, faz um -1
    String strTable = "<table width='100%' border='1'>";
    String strHeader = "";
    String strDados = "";
    strHeader += "<tr>";
    strDados += "<tr>";

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (int i = 0; i < 6; i++) {
      mPesq = (mPesq - 1);
      if (mPesq <= 0) {
        mPesq = 12;
        y = y - 1;
      }
      strHeader = strHeader + "<td colspan='2' style='border:1px solid black; text-align:center'>";
      strHeader = strHeader + (mPesq + "/" + y);
      strHeader = strHeader + "</td>";

      List lst =
          controleGenerateSLAPorAcordoNivelServicoByMesAno.execute(idAcordoNivelServico, y, mPesq);
      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 = 0;
      if ((qtdeDentroPrazo + qtdeForaPrazo) > 0) {
        qtdeDentroPrazoPerc = (qtdeDentroPrazo / (qtdeDentroPrazo + qtdeForaPrazo)) * 100;
      }
      double qtdeForaPrazoPerc = 0;
      if ((qtdeDentroPrazo + qtdeForaPrazo) > 0) {
        qtdeForaPrazoPerc = (qtdeForaPrazo / (qtdeDentroPrazo + qtdeForaPrazo)) * 100;
      }
      strDados = strDados + "<td style='border:1px solid black'>";
      strDados = strDados + UtilFormatacao.formatDouble(qtdeDentroPrazoPerc, 2) + "%";
      strDados = strDados + "</td>";
      strDados = strDados + "<td style='border:1px solid black'>";
      strDados = strDados + UtilFormatacao.formatDouble(qtdeForaPrazoPerc, 2) + "%";
      strDados = strDados + "</td>";

      dataset.setValue(
          new Double(qtdeDentroPrazoPerc),
          UtilI18N.internacionaliza(request, "sla.avaliacao.noprazo"),
          "" + (mPesq + "/" + y));
      dataset.setValue(
          new Double(qtdeForaPrazoPerc),
          UtilI18N.internacionaliza(request, "sla.avaliacao.foraprazo"),
          "" + (mPesq + "/" + y));
    }
    strHeader += "</tr>";
    strDados += "</tr>";

    // create the chart...
    JFreeChart chart =
        ChartFactory.createBarChart(
            tituloSLA, // chart title
            UtilI18N.internacionaliza(request, "sla.avaliacao.indicadores"), // domain axis label
            UtilI18N.internacionaliza(request, "sla.avaliacao.resultado"), // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips?
            false // URLs?
            );

    // set the background color for the chart...
    chart.setBackgroundPaint(Color.white);

    // get a reference to the plot for further customisation...
    CategoryPlot plot = chart.getCategoryPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setDomainGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    // set the range axis to display integers only...
    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    // disable bar outlines...
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);

    // set up gradient paints for series...
    GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, new Color(0, 0, 64));
    GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f, 0.0f, new Color(0, 64, 0));

    renderer.setSeriesPaint(0, gp0);
    renderer.setSeriesPaint(1, gp1);

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(
        CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));

    String nomeImgAval =
        CITCorporeUtil.caminho_real_app
            + "/tempFiles/"
            + usuarioDto.getIdUsuario()
            + "/avalSLAXX_"
            + idAcordoNivelServico
            + ".png";
    String nomeImgAvalRel =
        br.com.citframework.util.Constantes.getValue("SERVER_ADDRESS")
            + br.com.citframework.util.Constantes.getValue("CONTEXTO_APLICACAO")
            + "/tempFiles/"
            + usuarioDto.getIdUsuario()
            + "/avalSLAXX_"
            + idAcordoNivelServico
            + ".png";
    File arquivo2 = new File(nomeImgAval);
    if (arquivo2.exists()) {
      arquivo2.delete();
    }
    ChartUtilities.saveChartAsPNG(arquivo2, chart, 500, 200);
    strTable += "<tr>";
    strTable += "<td colspan='12'>";
    strTable += "<img src='" + nomeImgAvalRel + "' border='0'/>";
    strTable += "</td>";
    strTable += "</tr>";

    strTable += strHeader;
    strTable += strDados;

    strTable += "</table>";
    return strTable;
  }
Ejemplo n.º 21
0
  /**
   * Starting point for the demo.
   *
   * @param args ignored.
   */
  public static void main(final String[] args) {

    // create a chart
    final double[][] data =
        new double[][] {
          {56.0, -12.0, 34.0, 76.0, 56.0, 100.0, 67.0, 45.0},
          {37.0, 45.0, 67.0, 25.0, 34.0, 34.0, 100.0, 53.0},
          {43.0, 54.0, 34.0, 34.0, 87.0, 64.0, 73.0, 12.0}
        };
    final CategoryDataset dataset =
        DatasetUtilities.createCategoryDataset("Series ", "Type ", data);

    JFreeChart chart = null;
    final boolean drilldown = true;

    if (drilldown) {
      final CategoryAxis categoryAxis = new CategoryAxis("Category");
      final ValueAxis valueAxis = new NumberAxis("Value");
      final BarRenderer renderer = new BarRenderer();
      renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());
      renderer.setItemURLGenerator(new StandardCategoryURLGenerator("bar_chart_detail.jsp"));
      final CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer);
      plot.setOrientation(PlotOrientation.VERTICAL);
      chart = new JFreeChart("Bar Chart", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    } else {
      chart =
          ChartFactory.createBarChart(
              "Vertical Bar Chart", // chart title
              "Category", // domain axis label
              "Value", // range axis label
              dataset, // data
              PlotOrientation.VERTICAL,
              true, // include legend
              true,
              false);
    }
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    *
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
      final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
      final File file1 = new File("barchart100.png");
      ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

      // write an HTML page incorporating the image with an image map
      final File file2 = new File("barchart100.html");
      final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
      final PrintWriter writer = new PrintWriter(out);
      writer.println("<HTML>");
      writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
      writer.println("<BODY>");
      ChartUtilities.writeImageMap(writer, "chart", info, true);
      writer.println(
          "<IMG SRC=\"barchart100.png\" "
              + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
      writer.println("</BODY>");
      writer.println("</HTML>");
      writer.close();

    } catch (IOException e) {
      System.out.println(e.toString());
    }
  }
Ejemplo n.º 22
0
  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 += "&nbsp;";
      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 += "&nbsp;";
      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);
  }
  /**
   * Generates a chart in PNG format.
   *
   * @param outputFile the output file, it should exist.
   * @param pxWidth the image width in pixels.
   * @param pxHeight the image height in pixels.
   * @param chartTitle the chart title, may be null.
   * @param xAxisTitle the x axis title
   * @param yDataSeriesRange the axis range (null for auto)
   * @param yDataSeriesTitles the Y axis titles.
   * @param timeValuesInSeconds the time values in seconds
   * @param yDataSeries the Y axis value series.
   * @param yDataSeriesColors the Y axis value series drawing colors.
   * @param yDataSeriesTickSuffix TODO explain argument yDataSeriesTickSuffix
   * @param drawBorder draw, or not, the border.
   * @param backgroundColor the chart background color.
   */
  final void generatePngChart(
      File outputFile,
      int pxWidth,
      int pxHeight,
      String chartTitle,
      String xAxisTitle,
      String[] yDataSeriesTitles,
      double[] timeValuesInSeconds,
      double[][] yDataSeriesRange,
      double[][] yDataSeries,
      Color[] yDataSeriesColors,
      String[] yDataSeriesTickSuffix,
      boolean drawBorder,
      Color backgroundColor) {

    // Domain axis
    NumberAxis xAxis = new NumberAxis(xAxisTitle);
    xAxis.setFixedDimension(CHART_AXIS_DIMENSION);
    xAxis.setLabelPaint(Color.black);
    xAxis.setTickLabelPaint(Color.black);

    double maxSeconds = getMaxValue(timeValuesInSeconds);
    TimeAxisResolution xAxisRes = TimeAxisResolution.findTimeUnit(maxSeconds);
    xAxis.setTickUnit(new NumberTickUnit(xAxisRes.tickStep));
    double[] scaledTimeValues = xAxisRes.scale(timeValuesInSeconds);

    String tickSymbol =
        I18N.getString(locale, "running.job.details.chart.timeunit.symbol." + xAxisRes.name());
    xAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + tickSymbol + "'"));

    // First dataset
    String firstDataSetTitle = yDataSeriesTitles[0];
    XYDataset firstDataSet = createXYDataSet(firstDataSetTitle, scaledTimeValues, yDataSeries[0]);
    Color firstDataSetColor = yDataSeriesColors[0];

    // First range axis
    NumberAxis firstYAxis = new NumberAxis(firstDataSetTitle);

    firstYAxis.setFixedDimension(CHART_AXIS_DIMENSION);
    setAxisRange(firstYAxis, yDataSeriesRange[0]);
    firstYAxis.setLabelPaint(firstDataSetColor);
    firstYAxis.setTickLabelPaint(firstDataSetColor);
    String firstAxisTickSuffix = yDataSeriesTickSuffix[0];
    if (firstAxisTickSuffix != null && !firstAxisTickSuffix.isEmpty()) {
      firstYAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + firstAxisTickSuffix + "'"));
    }

    // Create the plot with domain axis and first range axis
    XYPlot plot = new XYPlot(firstDataSet, xAxis, firstYAxis, null);

    XYLineAndShapeRenderer firstRenderer = new XYLineAndShapeRenderer(true, false);
    plot.setRenderer(firstRenderer);

    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);

    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    firstRenderer.setSeriesPaint(0, firstDataSetColor);

    // Now iterate on next axes
    for (int i = 1; i < yDataSeries.length; i++) {
      // Create axis
      String seriesTitle = yDataSeriesTitles[i];
      Color seriesColor = yDataSeriesColors[i];
      NumberAxis yAxis = new NumberAxis(seriesTitle);

      yAxis.setFixedDimension(CHART_AXIS_DIMENSION);
      setAxisRange(yAxis, yDataSeriesRange[i]);

      yAxis.setLabelPaint(seriesColor);
      yAxis.setTickLabelPaint(seriesColor);

      String yAxisTickSuffix = yDataSeriesTickSuffix[i];
      if (yAxisTickSuffix != null && !yAxisTickSuffix.isEmpty()) {
        yAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + yAxisTickSuffix + "'"));
      }

      // Create dataset and add axis to plot
      plot.setRangeAxis(i, yAxis);
      plot.setRangeAxisLocation(i, AxisLocation.BOTTOM_OR_LEFT);
      plot.setDataset(i, createXYDataSet(seriesTitle, scaledTimeValues, yDataSeries[i]));
      plot.mapDatasetToRangeAxis(i, i);
      XYItemRenderer renderer = new StandardXYItemRenderer();
      renderer.setSeriesPaint(0, seriesColor);
      plot.setRenderer(i, renderer);
    }

    // Create the chart
    JFreeChart chart = new JFreeChart(chartTitle, JFreeChart.DEFAULT_TITLE_FONT, plot, false);

    // Customize rendering
    chart.setBackgroundPaint(Color.white);
    chart.setBorderVisible(true);
    chart.setBorderPaint(Color.BLACK);

    // Render image
    try {
      ChartUtilities.saveChartAsPNG(outputFile, chart, pxWidth, pxHeight);
    } catch (IOException e) {
      LOG.error("Chart export failed", e);
    }
  }
 @Test
 public void testHankelFunctionArg() throws IOException {
   JFreeChart chart = ChartBuilder.createArgPlot(function, "Radially Symmetric");
   ChartUtilities.saveChartAsPNG(new File(getPlotPath("arg")), chart, 800, 600);
 }
 @Test
 public void testHankelFunctionModule() throws IOException {
   JFreeChart chart = ChartBuilder.createModulePlot(function, "Hankel");
   ChartUtilities.saveChartAsPNG(new File(getPlotPath("module")), chart, 800, 600);
 }
Ejemplo n.º 26
0
  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;
  }