Example usage for org.jfree.chart ChartUtilities saveChartAsPNG

List of usage examples for org.jfree.chart ChartUtilities saveChartAsPNG

Introduction

In this page you can find the example usage for org.jfree.chart ChartUtilities saveChartAsPNG.

Prototype

public static void saveChartAsPNG(File file, JFreeChart chart, int width, int height) throws IOException 

Source Link

Document

Saves a chart to the specified file in PNG format.

Usage

From source file:org.miloss.fgsms.services.rs.impl.reports.AvailabilityByService.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {/* w  ww.  j av  a  2s.  c  o m*/

        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Number of status changes</th><th>Percent Uptime</th><th>Percent Downtime</th></tr>");
        DecimalFormat percentFormat = new DecimalFormat("###.#####");
        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            TimeSeries s1 = new TimeSeries(url, org.jfree.data.time.Millisecond.class);
            try {
                data.append("<tr><td>").append(url).append("</td>");
                List<StatusRecordsExt> records = getStatusRecords(urls.get(i), range, con);
                //special case, no status records available
                if (records == null || records.isEmpty()) {
                    data.append("<td>-</td><td>-</td></tr>");
                    continue;
                }
                double uptime = getUptimePercentage(records, range);
                data.append("<td>").append(records.size() + "").append("</td><td>")
                        .append(percentFormat.format(uptime)).append("</td><td>")
                        .append(percentFormat.format(100 - uptime)).append("</td></tr>");
                TimeSeriesDataItem t = null;
                for (int k = 0; k < records.size(); k++) {
                    if (records.get(k).status) {
                        try {
                            t = new TimeSeriesDataItem(new Millisecond(records.get(k).gcal.getTime()), 1);
                            s1.addOrUpdate(t);
                        } catch (Exception ex) {
                            log.log(Level.WARN, null, ex);
                        }
                    } else {
                        try {
                            t = new TimeSeriesDataItem(new Millisecond(records.get(k).gcal.getTime()), 0);
                            s1.addOrUpdate(t);
                        } catch (Exception ex) {
                            log.log(Level.WARN, null, ex);
                        }
                    }
                    col.addSeries(s1);
                }

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            }

        }
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Status", col,
                true, false, false);

        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 800);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");

        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.ws.ResponseTimeOverTime.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {//from   w w w  .j  a v a  2s. co  m
        PreparedStatement cmd = null;

        ResultSet rs = null;
        JFreeChart chart = null;
        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URI</th><th>Average Response Time (ms)</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }

            try {
                String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
                data.append("<tr><td>").append(url).append("</td>");
                double average = 0;
                try {
                    cmd = con.prepareStatement(
                            "select avg(responsetimems) from rawdata where uri=? and utcdatetime > ? and utcdatetime < ?;");
                    cmd.setString(1, urls.get(i));
                    cmd.setLong(2, range.getStart().getTimeInMillis());
                    cmd.setLong(3, range.getEnd().getTimeInMillis());
                    rs = cmd.executeQuery();

                    if (rs.next()) {
                        average = rs.getDouble(1);

                    }
                } catch (Exception ex) {
                    log.log(Level.WARN, null, ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }

                data.append("<td>").append(format.format(average) + "").append("</td></tr>");

                //ok now get the raw data....
                TimeSeriesContainer tsc = new TimeSeriesContainer();
                try {
                    cmd = con.prepareStatement(
                            "select responsetimems,utcdatetime  from rawdata where uri=? and utcdatetime > ? and utcdatetime < ?;");
                    cmd.setString(1, urls.get(i));
                    cmd.setLong(2, range.getStart().getTimeInMillis());
                    cmd.setLong(3, range.getEnd().getTimeInMillis());
                    rs = cmd.executeQuery();
                    while (rs.next()) {
                        TimeSeries ts2 = tsc.Get(url, Millisecond.class);
                        GregorianCalendar gcal = new GregorianCalendar();
                        gcal.setTimeInMillis(rs.getLong(2));
                        Millisecond m = new Millisecond(gcal.getTime());
                        ts2.addOrUpdate(m, rs.getLong("responsetimems"));
                    }
                } catch (Exception ex) {
                    log.log(Level.WARN, null, ex);
                } finally {
                    DBUtils.safeClose(rs);
                    DBUtils.safeClose(cmd);
                }
                for (int ik = 0; ik < tsc.data.size(); ik++) {
                    col.addSeries(tsc.data.get(ik));
                }

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            }

        }
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Time in ms",
                col, true, false, false);

        data.append("</table>");

        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:org.opensha.sha.calc.IM_EventSet.v03.test.IM_EventSetHazardCurveTest.java

@Test
public void testHazardCurve() throws IOException {
    HazardCurveCalculator calc = new HazardCurveCalculator();

    ArbitrarilyDiscretizedFunc realCurve = CyberShakePlotFromDBControlPanel.createUSGS_PGA_Function();
    ArbitrarilyDiscretizedFunc rLogHazFunction = getLogFunction(realCurve);
    System.out.println("IMR Params: " + imr.getAllParamMetadata());
    System.out.println("Calculating regular curve");
    calc.getHazardCurve(rLogHazFunction, site, imr, erf);
    realCurve = unLogFunction(realCurve, rLogHazFunction);

    runHAZ01A();/*w w  w  . j a va  2  s  .co  m*/
    String fileName = outputDir.getAbsolutePath() + File.separator + HAZ01Writer.HAZ01A_FILE_NAME;
    ScalarIntensityMeasureRelationshipAPI hIMR = new HAZ01A_FakeAttenRel(fileName);
    EqkRupForecastAPI hERF = new HAZ01A_FakeERF(erf);
    hERF.updateForecast();

    ArbitrarilyDiscretizedFunc hCurve = CyberShakePlotFromDBControlPanel.createUSGS_PGA_Function();
    System.out.println("Calculating IM based curve");
    ArbitrarilyDiscretizedFunc hLogHazFunction = getLogFunction(hCurve);
    calc.getHazardCurve(hLogHazFunction, site, hIMR, hERF);
    hCurve = unLogFunction(hCurve, hLogHazFunction);
    //      ArbitrarilyDiscretizedFunc realCurve =
    //         ArbitrarilyDiscretizedFunc.loadFuncFromSimpleFile("/tmp/imEventSetTest/curve.txt");

    ArrayList<ArbitrarilyDiscretizedFunc> curves = new ArrayList<ArbitrarilyDiscretizedFunc>();
    curves.add(realCurve);
    curves.add(hCurve);

    boolean xLog = false;
    boolean yLog = false;
    boolean customAxis = true;
    this.gp.drawGraphPanel(imt, "", curves, xLog, yLog, customAxis, "Curves", this);
    this.gp.setVisible(true);

    this.gp.togglePlot(null);

    this.gp.validate();
    this.gp.repaint();

    ChartUtilities.saveChartAsPNG(new File(outputDir.getAbsolutePath() + File.separator + "curves.png"),
            gp.getCartPanel().getChart(), 800, 600);

    double maxDiff = 0;
    double maxPDiff = 0;

    for (int i = 0; i < hCurve.getNum(); i++) {
        Point2D hPt = hCurve.get(i);
        Point2D rPt = realCurve.get(i);

        assertEquals(hPt.getX(), rPt.getX(), 0);

        if (hPt.getX() >= 10.)
            continue;

        System.out.println("Comparing point: " + i);

        System.out.println("\"Real\" point:\t" + rPt.getX() + ", " + rPt.getY());
        System.out.println("HAZ01A point:\t" + hPt.getX() + ", " + hPt.getY());

        if (hPt.getY() == 0 && rPt.getY() == 0)
            continue;

        double absDiff = Math.abs(hPt.getY() - rPt.getY());
        if (absDiff > maxDiff)
            maxDiff = absDiff;
        double absPDiff = absDiff / rPt.getY() * 100d;
        if (absPDiff > maxPDiff)
            maxPDiff = absPDiff;

        System.out.println("absDiff: " + absDiff + ", abs % diff: " + absPDiff);

        boolean success = absPDiff < TOL_PERCENT;
        if (!success) {
            System.out.println("FAIL!");
        }
        assertTrue(success);
    }

    System.out.println("Max Diff: " + maxDiff);
    System.out.println("Max Diff %: " + maxPDiff);
}

From source file:org.jax.maanova.plot.SaveChartAction.java

/**
 * {@inheritDoc}/*from   w w w. j a v  a  2  s.c o  m*/
 */
public void actionPerformed(ActionEvent e) {
    JFreeChart myChart = this.chart;
    Dimension mySize = this.size;

    if (myChart == null || mySize == null) {
        LOG.severe("Failed to save graph image because of a null value");
        MessageDialogUtilities.errorLater(Maanova.getInstance().getApplicationFrame(),
                "Internal error: Failed to save graph image.", "Image Save Failed");
    } else {
        // use the remembered starting dir
        MaanovaApplicationConfigurationManager configurationManager = MaanovaApplicationConfigurationManager
                .getInstance();
        JMaanovaApplicationState applicationState = configurationManager.getApplicationState();
        FileType rememberedJaxbImageDir = applicationState.getRecentImageExportDirectory();
        File rememberedImageDir = null;
        if (rememberedJaxbImageDir != null && rememberedJaxbImageDir.getFileName() != null) {
            rememberedImageDir = new File(rememberedJaxbImageDir.getFileName());
        }

        // select the image file to save
        JFileChooser fileChooser = new JFileChooser(rememberedImageDir);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setApproveButtonText("Save Graph");
        fileChooser.setDialogTitle("Save Graph as Image");
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.addChoosableFileFilter(PngFileFilter.getInstance());
        fileChooser.setFileFilter(PngFileFilter.getInstance());
        int response = fileChooser.showSaveDialog(Maanova.getInstance().getApplicationFrame());
        if (response == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();

            // tack on the extension if there isn't one
            // already
            if (!PngFileFilter.getInstance().accept(selectedFile)) {
                String newFileName = selectedFile.getName() + "." + PngFileFilter.PNG_EXTENSION;
                selectedFile = new File(selectedFile.getParentFile(), newFileName);
            }

            if (selectedFile.exists()) {
                // ask the user if they're sure they want to overwrite
                String message = "Exporting the graph image to " + selectedFile.getAbsolutePath()
                        + " will overwrite an " + " existing file. Would you like to continue anyway?";
                if (LOG.isLoggable(Level.FINE)) {
                    LOG.fine(message);
                }

                boolean overwriteOk = MessageDialogUtilities
                        .confirmOverwrite(Maanova.getInstance().getApplicationFrame(), selectedFile);
                if (!overwriteOk) {
                    if (LOG.isLoggable(Level.FINE)) {
                        LOG.fine("overwrite canceled");
                    }
                    return;
                }
            }

            try {
                ChartUtilities.saveChartAsPNG(selectedFile, myChart, mySize.width, mySize.height);

                File parentDir = selectedFile.getParentFile();
                if (parentDir != null) {
                    // update the "recent image directory"
                    ObjectFactory objectFactory = new ObjectFactory();
                    FileType latestJaxbImageDir = objectFactory.createFileType();
                    latestJaxbImageDir.setFileName(parentDir.getAbsolutePath());
                    applicationState.setRecentImageExportDirectory(latestJaxbImageDir);
                }
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "failed to save graph image", ex);
            }
        }
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.broker.QueueDepth.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {//  w  ww  . ja  v a2s .  c om
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append("<table class=\"table table-hover\"><tr><th>URI</th><th>Channel</th><th>Depth</th></tr>");

        TimeSeriesCollection col = new TimeSeriesCollection();
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.STATISTICAL)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(getPolicyDisplayName(urls.get(i)));
            double average = 0;
            data.append("<tr><td>").append(url).append("</td>");
            try {
                cmd = con.prepareStatement(
                        "select avg(queuedepth), host, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ? group by canonicalname, host;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                if (rs.next()) {
                    average = rs.getDouble(1);
                }
            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("<td>").append(average + "").append("</td>");

            TimeSeries ts = new TimeSeries(url, Millisecond.class);
            try {
                //ok now get the raw data....
                cmd = con.prepareStatement(
                        "select utcdatetime,queuedepth, canonicalname from brokerhistory where host=? and utcdatetime > ? and utcdatetime < ?;");
                cmd.setString(1, urls.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                while (rs.next()) {

                    //set.addValue(rs.getLong(1), urls.get(i), rs.getString("canonicalname"));
                    GregorianCalendar gcal = new GregorianCalendar();
                    gcal.setTimeInMillis(rs.getLong(1));
                    Millisecond m = new Millisecond(gcal.getTime());
                    //TimeSeriesDataItem t = new TimeSeriesDataItem(m, rs.getLong(2));
                    //ts.add(t);
                    ts.addOrUpdate(m, rs.getLong(2));

                }

            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }

            col.addSeries(ts);

        }
        chart = org.jfree.chart.ChartFactory.createTimeSeriesChart(GetDisplayName(), "Timestamp", "Count", col,
                true, false, false);

        data.append("</table>");
        try {
            //  if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, 400);
            data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
            files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
            // }
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:org.f3.tools.framework.Reporter.java

private String generateImage(String refName, String name, Number changeFactor) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.addValue(changeFactor, 0, 0);
    JFreeChart chart = ChartFactory.createBarChart("", "", "%change", dataset, PlotOrientation.HORIZONTAL,
            false, false, false);/*from www. j ava2  s  .  com*/
    try {
        Color bgcolor = null;
        double value = changeFactor.doubleValue();
        if (value == Double.POSITIVE_INFINITY || value == Double.NEGATIVE_INFINITY) {
            bgcolor = Color.YELLOW;
        } else if (value > 5) {
            bgcolor = Color.GREEN;
        } else if (value >= -5 && value <= 5) {
            bgcolor = Color.WHITE;
        } else {
            bgcolor = Color.RED;
        }
        chart.setBackgroundPaint(bgcolor);
        File dirFile = new File(IMAGE_DIRNAME);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File ofile = new File(dirFile, name);
        ChartUtilities.saveChartAsPNG(ofile, chart, 300, 100);
        return getImageRef(refName, name);
    } catch (IOException ioe) {
        Utils.logger.severe(ioe.getMessage());
    }
    return null;
}

From source file:MSUmpire.DIA.MixtureModelKDESemiParametric.java

public void GeneratePlot(String pngfile) throws IOException {
    String modelfile = FilenameUtils.getFullPath(pngfile) + "/" + FilenameUtils.getBaseName(pngfile)
            + "_ModelPoints.txt";
    FileWriter writer = new FileWriter(modelfile);

    double[] IDObs = new double[IDEmpiricalDist.getN()];
    double[] DecoyObs = new double[DecoyEmpiricalDist.getN()];

    for (int i = 0; i < IDEmpiricalDist.getN(); i++) {
        IDObs[i] = IDEmpiricalDist.getObs(i);
    }//from  w ww . j  a  va 2 s.c  o  m
    for (int i = 0; i < DecoyEmpiricalDist.getN(); i++) {
        DecoyObs[i] = DecoyEmpiricalDist.getObs(i);
    }

    XYSeries model1 = new XYSeries("Incorrect matches");
    XYSeries model2 = new XYSeries("Correct matches");
    XYSeries model3 = new XYSeries("All target hits");

    writer.write("UScore\tModel\tCorrect\tDecoy\n");
    for (int i = 0; i < NoBinPoints; i++) {
        model1.add(model_kde_x[i], decoy_kde_y[i]);
        model2.add(model_kde_x[i], correct_kde_y[i]);
        model3.add(model_kde_x[i], model_kde_y[i]);
        writer.write(model_kde_x[i] + "\t" + model_kde_y[i] + "\t" + correct_kde_y[i] + "\t" + decoy_kde_y[i]
                + "\n");
    }
    writer.close();

    MixtureModelProb = new float[NoBinPoints + 1][3];
    float positiveaccu = 0f;
    float negativeaccu = 0f;

    MixtureModelProb[0][0] = (float) model2.getMaxX() + Float.MIN_VALUE;
    MixtureModelProb[0][1] = 1f;
    MixtureModelProb[0][2] = 1f;

    for (int i = 1; i < NoBinPoints + 1; i++) {
        double positiveNumber = correct_kde_y[NoBinPoints - i];
        double negativeNumber = decoy_kde_y[NoBinPoints - i];
        MixtureModelProb[i][0] = (float) model_kde_x[NoBinPoints - i];
        positiveaccu += positiveNumber;
        negativeaccu += negativeNumber;
        MixtureModelProb[i][2] = 0.999999f * (float) (positiveNumber / (negativeNumber + positiveNumber));
        MixtureModelProb[i][1] = 0.999999f * (float) (positiveaccu / (negativeaccu + positiveaccu));
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(model1);
    dataset.addSeries(model2);
    dataset.addSeries(model3);

    HistogramDataset histogramDataset = new HistogramDataset();
    histogramDataset.setType(HistogramType.SCALE_AREA_TO_1);
    histogramDataset.addSeries("ID hits", IDObs, 100);
    histogramDataset.addSeries("Decoy hits", DecoyObs, 100);
    //histogramDataset.addSeries("Model hits", ModelObs, 100);

    JFreeChart chart = ChartFactory.createHistogram(FilenameUtils.getBaseName(pngfile), "Score", "Hits",
            histogramDataset, PlotOrientation.VERTICAL, true, false, false);
    XYPlot plot = chart.getXYPlot();

    NumberAxis domain = (NumberAxis) plot.getDomainAxis();
    domain.setRange(min, max);
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setForegroundAlpha(0.8f);
    chart.setBackgroundPaint(Color.white);

    XYLineAndShapeRenderer render = new XYLineAndShapeRenderer();

    plot.setDataset(1, dataset);
    plot.setRenderer(1, render);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    try {
        ChartUtilities.saveChartAsPNG(new File(pngfile), chart, 1000, 600);
    } catch (IOException e) {
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.ws.TotalMessageSizeByServiceByMethod.java

/**
 * {@inheritDoc}//w  ww .  jav  a  2 s .  c  o  m
 */
@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    Connection con = Utility.getPerformanceDBConnection();
    try {
        PreparedStatement cmd = null;
        long itemcount = 0;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;
        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(
                "This represents the total combined request and response message size of each service grouped by method.<br />");
        //add description
        data.append(
                "<table class=\"table table-hover\"><tr><th>URL</th><th>Action</th><th>Total Message Size (bytes)</th></tr>");
        for (int i = 0; i < urls.size(); i++) {
            if (!isPolicyTypeOf(urls.get(i), PolicyType.TRANSACTIONAL)) {
                continue;
            }
            //https://github.com/mil-oss/fgsms/issues/112
            if (!UserIdentityUtil.hasReadAccess(currentuser, "getReport", urls.get(i), classification, ctx)) {
                continue;
            }
            String url = Utility.encodeHTML(BaseReportGenerator.getPolicyDisplayName(urls.get(i)));
            try {
                List<String> actions = getSoapActions(urls.get(i), con);

                itemcount = actions.size();
                for (int k = 0; k < actions.size(); k++) {
                    long count = -1;

                    try {
                        cmd = con.prepareStatement(
                                "select SUM(responseSize + requestSize) as messagesSize from RawData where URI=? and "
                                        + "(UTCdatetime > ?) and (UTCdatetime < ?) and soapaction=? and (requestsize>=0) and (responsesize>=0);");
                        cmd.setString(1, urls.get(i));
                        cmd.setLong(2, range.getStart().getTimeInMillis());
                        cmd.setLong(3, range.getEnd().getTimeInMillis());
                        cmd.setString(4, actions.get(k));

                        rs = cmd.executeQuery();

                        try {
                            if (rs.next()) {
                                count = rs.getLong(1);
                            }
                        } catch (Exception ex) {
                            log.log(Level.DEBUG, null, ex);
                        }
                    } catch (Exception ex) {
                        log.log(Level.WARN, null, ex);
                    } finally {
                        DBUtils.safeClose(rs);
                        DBUtils.safeClose(cmd);
                    }

                    data.append("<tr><td>").append(url).append("</td><td>");
                    data.append(Utility.encodeHTML(actions.get(k))).append("</td><td>");
                    if (count >= 0) {
                        data.append(count + " bytes");
                    } else {
                        data.append("N/A");
                    }
                    data.append("</td></tr>");
                    set.addValue(count, actions.get(k), url);
                }
            } catch (Exception ex) {
                data.append("0 bytes</td></tr>");
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            }
        }

        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);
        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(set.getRowCount()));
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }

        data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
        files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:wsattacker.plugin.dos.dosExtension.result.ResultGenerator.java

/**
 * Save Attack Results to CSV-Files! Location is tmp folder
 *///from w ww . j a  va  2s . co m
public void saveResult() {
    String attackName = "DOS";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HHmm"); // yyyy-mm-dd
    Date resultdate = new Date(attackModel.getTsAttackStop());
    String dateString = sdf.format(resultdate);
    String filenameUntampered = dateString + "_" + attackName + "_untamperedRequests.csv";
    String filenameTampered = dateString + "_" + attackName + "_tamperedRequests.csv";
    String filenameTestprobe = dateString + "_" + attackName + "_testprobeRequests.csv";
    String filenameMetadata = dateString + "_" + attackName + "_metaData.txt";
    String filenameImgGraph = dateString + "_" + attackName + "_graph.png";
    String filenameReport = dateString + "_" + attackName + "_results.html";
    String filenameZip = dateString + "_" + attackName + "_results.zip";

    // read tmpDir
    String property = "java.io.tmpdir";
    String tempDir = System.getProperty(property);
    // System.out.println("OS current temporary directory is " + tempDir);
    // make Folders
    File resultDir = new File(tempDir + "/wsattackerdos");
    if (!resultDir.exists()) { // if the directory does not exist, create it
        resultDir.mkdir();
    }
    File file = new File(tempDir + "/wsattackerdos/" + dateString);
    file.mkdir();
    String fullPath = file.getAbsolutePath();

    try {
        File untamperedRequests = new File(fullPath, filenameUntampered);
        saveResponseTimeOfUntamperedRequests(untamperedRequests);

        File tamperedRequests = new File(fullPath, filenameTampered);
        saveResponseTimeOfTamperedRequests(tamperedRequests);

        File testRequests = new File(fullPath, filenameTestprobe);
        saveResponseTimeOfTestRequests(testRequests);

        File metadata = new File(fullPath, filenameMetadata);
        saveMetadata(metadata);

        saveFilelocationToReport(dateString, filenameUntampered, filenameTampered, filenameTestprobe,
                filenameMetadata, filenameImgGraph, filenameReport, filenameZip, fullPath);
    } catch (IOException e) {
        e.printStackTrace();
    }
    // copy image from .jar to resultDir
    URL inputUrl;
    inputUrl = getClass().getResource("/IMG/ok.jpg");
    File dest = new File(fullPath + "/ok.jpg");
    try {
        FileUtils.copyURLToFile(inputUrl, dest);
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Write Image
    try {
        ChartObject chartObject = new ChartObject(attackModel);
        JFreeChart chart = chartObject.createOverlaidChart();
        ChartUtilities.saveChartAsPNG(new File(fullPath + filenameImgGraph), chart, 900, 700);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Create ZipFile in same folder
    Zip.createZip(fullPath, filenameZip);

    // Save Pointers to files
    this.setFullPath(fullPath);
    this.setFilenameReport(filenameReport);

}

From source file:org.utgenome.core.cui.DrawHistogram.java

public void execute() throws Exception {

    InputStream in = null;/*from   ww w .ja v  a  2s  . c om*/
    if ("-".equals(input)) {
        _logger.info("reading from STDIN");
        in = new StandardInputStream();
    } else {
        _logger.info("reading from " + input);
        in = new FileInputStream(input);
    }

    List<Double> data = new ArrayList<Double>();
    BufferedReader dataSetInput = new BufferedReader(new InputStreamReader(in));
    int lineCount = 1;
    try {
        // read data set
        boolean cutOffTail = !Double.isNaN(xMax);
        boolean cutOffHead = !Double.isNaN(xMin);
        for (String line; (line = dataSetInput.readLine()) != null; lineCount++) {

            if (lineCount % 100000 == 0)
                _logger.info(String.format("read %,d data points", lineCount));

            if (line.startsWith("#"))
                continue;
            double v = Double.parseDouble(line);
            if (cutOffTail && v > xMax)
                continue;
            if (cutOffHead && v < xMin)
                continue;

            data.add(v);
        }

        double[] value = new double[data.size()];
        for (int i = 0; i < data.size(); ++i) {
            value[i] = data.get(i);
        }

        // draw histogram
        HistogramDataset dataSet = new HistogramDataset();
        dataSet.setType(HistogramType.FREQUENCY);
        dataSet.addSeries("data", value, numBins);
        JFreeChart chart = ChartFactory.createHistogram(null, null, "Frequency", dataSet,
                PlotOrientation.VERTICAL, false, false, false);

        if (title != null) {
            chart.setTitle(title);
        }

        ValueAxis domainAxis = chart.getXYPlot().getDomainAxis();
        if (cutOffHead) {
            domainAxis.setLowerBound(xMin);
        }
        if (cutOffTail) {
            domainAxis.setUpperBound(xMax);
        }
        if (xLabel != null) {
            domainAxis.setLabel(xLabel);
        }

        if (yLog) {
            LogarithmicAxis logAxis = new LogarithmicAxis("Frequency");
            logAxis.setAllowNegativesFlag(true);
            logAxis.setAutoRangeIncludesZero(true);
            chart.getXYPlot().setRangeAxis(logAxis);
        }

        if (!Double.isNaN(yMin)) {
            chart.getXYPlot().getRangeAxis().setLowerBound(yMin);
        }
        if (!Double.isNaN(yMax)) {
            chart.getXYPlot().getRangeAxis().setUpperBound(yMax);
        }

        File outputFile = new File(output);
        _logger.info("output to " + outputFile);
        ChartUtilities.saveChartAsPNG(outputFile, chart, width, height);

    } catch (Exception e) {
        throw new Exception(String.format("error at line %d: %s", lineCount, e));
    }

}