Example usage for org.jfree.data.category DefaultCategoryDataset getRowCount

List of usage examples for org.jfree.data.category DefaultCategoryDataset getRowCount

Introduction

In this page you can find the example usage for org.jfree.data.category DefaultCategoryDataset getRowCount.

Prototype

@Override
public int getRowCount() 

Source Link

Document

Returns the number of rows in the table.

Usage

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

/**
 * {@inheritDoc}/*from ww w .  j  ava 2  s  .  co 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 {

    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>URL</th><th>MTBF (ms)</th><th>Timespan</th><th>XML Duration Value</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 {
            long mtbf = meanTimeBetweenFailures(urls.get(i), range);
            Duration newDuration = df.newDuration(mtbf);
            data.append("<tr><td>").append(url).append("</td><td>");
            if (mtbf == -1 || mtbf == 0) {
                data.append("Never</td><td>0</td><td>0</d></tr>");
            } else {
                data.append(mtbf + "").append("ms</td><td>").append(Utility.durationToString(newDuration))
                        .append("</td><td>").append(newDuration.toString()).append("</td></tr>");
            }
            if (mtbf > 0) {
                set.addValue(mtbf, url, 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 {
        if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(set.getRowCount()));
            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);
    }

}

From source file:org.miloss.fgsms.services.rs.impl.reports.broker.QueueTopicCountByBroker.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 va2 s . c o m
        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 Count</th></tr>");

        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)));
            data.append("<tr><td>").append(url).append("</td>");
            long count = 0;
            try {

                //FIXME could this be simplified?
                cmd = con.prepareStatement(
                        "select canonicalname from brokerhistory where host=?  group by canonicalname;");
                cmd.setString(1, urls.get(i));
                rs = cmd.executeQuery();
                if (rs.next()) {
                    count++;
                }

            } 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(count + "").append("</td></tr>");
            set.addValue(count, urls.get(i), urls.get(i));

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

        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);

        try {
            //  if (set.getRowCount() != 0) {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(set.getRowCount()));
            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:gg.view.movementsbalances.GraphMovementsBalancesTopComponent.java

/**
 * Displays the accounts' movements balances by period
 * @param searchFilters Search filter objects (one per period) for which the movements balances are wanted
 */// w ww .  ja v a  2s .co m
private void displayData(Map<MoneyContainer, Map<SearchCriteria, BigDecimal>> balances) {
    log.info("Movements' balances graph computed and displayed");

    // Display hourglass cursor
    Utilities.changeCursorWaitStatus(true);

    // Create the dataset (that will contain the movements' balances)
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    // Create an empty chart
    JFreeChart chart = ChartFactory.createLineChart("", // chart title
            "", // x axis label
            NbBundle.getMessage(GraphMovementsBalancesTopComponent.class,
                    "GraphMovementsBalancesTopComponent.Amount"), // y axis label
            dataset, // data displayed in the chart
            PlotOrientation.VERTICAL, true, // include legend
            true, // tooltips
            false // urls
    );

    // Chart color
    chart.setBackgroundPaint(jPanelMovementsBalances.getBackground());
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.WHITE);

    // Grid lines
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

    // Set the orientation of the categories on the domain axis (X axis)
    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

    // Add the series on the chart
    for (MoneyContainer moneyContainer : balances.keySet()) {
        if (moneyContainer instanceof Account) {

            SortedSet<SearchCriteria> sortedSearchFilters = new TreeSet<SearchCriteria>(
                    balances.get(moneyContainer).keySet());

            for (SearchCriteria searchCriteria : sortedSearchFilters) {
                BigDecimal accountBalance = balances.get(moneyContainer).get(searchCriteria);
                accountBalance = accountBalance.setScale(2, RoundingMode.HALF_EVEN);

                dataset.addValue(accountBalance, moneyContainer.toString(), searchCriteria.getPeriod());
            }
        }
    }

    // Series' shapes
    LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
    for (int i = 0; i < dataset.getRowCount(); i++) {
        renderer.setSeriesShapesVisible(i, true);
        renderer.setSeriesShape(i, ShapeUtilities.createDiamond(2F));
    }

    // Set the scale of the chart
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setAutoRange(true);
    rangeAxis.setAutoRangeIncludesZero(false);
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    // Create the chart panel that contains the chart
    ChartPanel chartPanel = new ChartPanel(chart);

    // Display the chart
    jPanelMovementsBalances.removeAll();
    jPanelMovementsBalances.add(chartPanel, BorderLayout.CENTER);
    jPanelMovementsBalances.updateUI();

    // Display normal cursor
    Utilities.changeCursorWaitStatus(false);
}

From source file:gg.view.accountsbalances.GraphAccountsBalancesTopComponent.java

/**
 * Displays the accounts' balances by period
 * @param balances Accounts' balances/*from ww w.j  a v a  2  s . co m*/
 */
private void displayData(Map<MoneyContainer, Map<SearchCriteria, BigDecimal>> balances) {
    log.info("Accounts' balances graph computed and displayed");

    // Display hourglass cursor
    Utilities.changeCursorWaitStatus(true);

    // Create the dataset (that will contain the accounts' balances)
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    // Create an empty chart
    JFreeChart chart = ChartFactory.createLineChart("", // chart title
            "", // x axis label
            NbBundle.getMessage(GraphAccountsBalancesTopComponent.class, "AccountsBalancesTopComponent.Amount"), // y axis label
            dataset, // data displayed in the chart
            PlotOrientation.VERTICAL, true, // include legend
            true, // tooltips
            false // urls
    );

    // Chart color
    chart.setBackgroundPaint(jPanelAccountsBalances.getBackground());
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.WHITE);

    // Grid lines
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

    // Set the orientation of the categories on the domain axis (X axis)
    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

    // Add the series on the chart for each account displayed in the table
    for (MoneyContainer moneyContainer : balances.keySet()) {

        if (moneyContainer instanceof Account) {
            Account account = (Account) moneyContainer;
            SortedSet<SearchCriteria> sortedSearchCriteria = new TreeSet<SearchCriteria>(
                    balances.get(account).keySet());

            for (SearchCriteria searchCriteria : sortedSearchCriteria) {
                if (!searchCriteria.hasAccountsFilter() || searchCriteria.getAccounts().contains(account)) {

                    dataset.addValue(balances.get(moneyContainer).get(searchCriteria), account.toString(),
                            searchCriteria.getPeriod());
                }
            }
        }
    }

    // Series' shapes
    LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
    for (int i = 0; i < dataset.getRowCount(); i++) {
        renderer.setSeriesShapesVisible(i, true);
        renderer.setSeriesShape(i, ShapeUtilities.createDiamond(2F));
    }
    // Set the scale of the chart
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setAutoRange(true);
    rangeAxis.setAutoRangeIncludesZero(false);
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    // Create the chart panel that contains the chart
    ChartPanel chartPanel = new ChartPanel(chart);

    // Display the chart
    jPanelAccountsBalances.removeAll();
    jPanelAccountsBalances.add(chartPanel, BorderLayout.CENTER);
    jPanelAccountsBalances.updateUI();

    // Display normal cursor
    Utilities.changeCursorWaitStatus(false);
}

From source file:com.swordlord.gozer.components.wicket.graph.GWStackedBarChartPanel.java

public GWStackedBarChartPanel(String id, IModel<?> model, GStackedBarChart child) {
    super(id, model);

    gchart = child;/*  w  ww  .  j  a va  2s  .c om*/
    DataBindingMember dbMemberRowKey = child.getDataBindingMemberRowKey();
    DataBindingMember dbMemberTargetId = child.getDataBindingMemberTargetId();
    DataBindingMember dbMemberColKey = child.getDataBindingMemberColKey();
    DataBindingMember dbMemberValue = child.getDataBindingMemberValue();
    DataBindingManager dbManager = child.getDataBindingManager();

    DefaultCategoryDataset dcd = new DefaultCategoryDataset();

    List<DataRowBase> rows = dbManager.getRows(dbMemberValue);

    // if the graph has some ordering info in the format of "<field> ASCENDING,<field2> DESCENDING"
    if (child.hasOrdering()) {
        List<Ordering> ordering = child.formatOrdering(child.getOrdering());
        OrderingEx.orderList(rows, ordering);
    }

    for (int j = 0; j < rows.size(); j++) {
        DataRowBase row = rows.get(j);

        String strKey = row.getPropertyAsStringForce(dbMemberRowKey.getRelativePathWithField());

        dcd.setValue(row.getPropertyAsInt(dbMemberValue.getRelativePathWithField()), strKey,
                row.getPropertyAsStringForce(dbMemberColKey.getRelativePathWithField()));

        if (dbMemberTargetId != null) {
            _target.put(strKey, row.getPropertyAsStringForce(dbMemberTargetId.getDataBindingFieldName()));
        }
    }

    JFreeChart chart = ChartFactory.createStackedBarChart(child.getTitle(), child.getCategoryAxisLabel(),
            child.getValueAxisLabel(), dcd, child.getOrientation(), child.getLegend(), false, false);

    // Do this in a more static way!
    StackedBarRenderer.setDefaultBarPainter(new StandardBarPainter());

    //chart.setBackgroundPaint(Color.white);
    if (child.getSubTitle() != null) {
        chart.addSubtitle(new TextTitle(child.getSubTitle()));
    }

    CategoryPlot plot = chart.getCategoryPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDrawingSupplier(child.getDrawingSupplier());

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setVisible(child.getCategoryAxisVisible());

    ValueAxis valueAxis = plot.getRangeAxis();
    valueAxis.setVisible(child.getValueAxisVisible());

    /*
    //CategoryItemRenderer renderer = (CategoryItemRenderer) plot.getRenderer();
    for (int j = 0; j < rowKey.length; j++)
    {
       renderer.setSeriesItemLabelGenerator(j, new LabelGenerator(j, rowKey[j]));
       renderer.setSeriesItemLabelsVisible(j, true);
    }
    */
    StackedBarRenderer renderer = new StackedBarRenderer();

    for (int j = 0; j < dcd.getRowCount(); j++) {
        renderer.setSeriesItemLabelGenerator(j, new StandardCategoryItemLabelGenerator());
        renderer.setSeriesItemLabelsVisible(j, true);
    }

    //renderer.setLegendItemLabelGenerator(new LabelGenerator());
    renderer.setShadowVisible(false);

    plot.setRenderer(renderer);

    ChartImage image = new ChartImage("chart", chart, child.getWidth(800), child.getHeight(800));
    String mapName = child.getCaption();
    add(image);

    DynamicImageMap imageMap = constructImageMap(image, mapName);
    if (!child.isClickable()) {
        imageMap.setVisible(false);
    } else {
        image.add(new AttributeModifier("usemap", new Model<String>("#" + mapName)));
    }
    add(imageMap);
}

From source file:gg.view.categoriesbalances.GraphCategoriesBalancesTopComponent.java

/**
 * Displays the categories/sub-categories' balances by period
 * @param balances Categories' balances//from   w w w  . j av  a  2s  .  c o m
 */
private void displayData(Map<Long, Map<SearchCriteria, BigDecimal>> balances) {
    log.info("Categories' balances graph computed and displayed");

    // Display hourglass cursor
    Utilities.changeCursorWaitStatus(true);

    // Create the dataset (that will contain the categories/sub-categories' balances)
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    // Create an empty chart
    JFreeChart chart = ChartFactory.createLineChart("", // chart title
            "", // x axis label
            NbBundle.getMessage(GraphCategoriesBalancesTopComponent.class,
                    "GraphAccountsBalancesTopComponent.Amount"), // y axis label
            dataset, // data displayed in the chart
            PlotOrientation.VERTICAL, true, // include legend
            true, // tooltips
            false // urls
    );

    // Chart color
    chart.setBackgroundPaint(jPanelCategoriesBalances.getBackground());
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.WHITE);

    // Grid lines
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

    // Set the orientation of the categories on the domain axis (X axis)
    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

    // Add the series on the chart for each category/sub-category displayed in the table
    for (Long categoryId : balances.keySet()) {
        Category category = Wallet.getInstance().getCategoriesWithId().get(categoryId);
        assert (category != null);

        SortedSet<SearchCriteria> sortedSearchCriteria = new TreeSet<SearchCriteria>(
                balances.get(categoryId).keySet());
        for (SearchCriteria searchCriteria : sortedSearchCriteria) {

            if ((!searchCriteria.hasCategoriesFilter() && category.isTopCategory()
                    && !category.getSystemProperty()) || searchCriteria.getCategories().contains(category)) {

                BigDecimal balance = new BigDecimal(0);
                if (balances.get(categoryId) != null && balances.get(categoryId).get(searchCriteria) != null) {
                    balance = balances.get(categoryId).get(searchCriteria);
                }

                dataset.addValue(balance, category.getName(), searchCriteria.getPeriod());
            }
        }
    }

    // Series' shapes
    LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
    for (int i = 0; i < dataset.getRowCount(); i++) {
        renderer.setSeriesShapesVisible(i, true);
        renderer.setSeriesShape(i, ShapeUtilities.createDiamond(2F));
    }
    // Set the scale of the chart
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setAutoRange(true);
    rangeAxis.setAutoRangeIncludesZero(false);
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    // Create the chart panel that contains the chart
    ChartPanel chartPanel = new ChartPanel(chart);

    // Display the chart
    jPanelCategoriesBalances.removeAll();
    jPanelCategoriesBalances.add(chartPanel, BorderLayout.CENTER);
    jPanelCategoriesBalances.updateUI();

    // Display normal cursor
    Utilities.changeCursorWaitStatus(false);
}

From source file:lu.lippmann.cdb.weka.SilhouetteUtil.java

/**
 * //from  ww  w  .jav a2s.  co m
 * @param sils
 * @return
 */
public static JPanel buildSilhouettePanel(final Instances ds, final WekaClusteringResult result) {

    final Map<Integer, List<Double>> sils = computeSilhouette(ds, result);

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    final JFreeChart chart = ChartFactory.createBarChart("Silhouette", "Category", "Value", dataset,
            PlotOrientation.HORIZONTAL, true, true, false);

    int nbClass = sils.keySet().size();

    int id = 0;
    double minValue = 0;

    int counter[][] = new int[nbClass][4];
    for (int i = 0; i < nbClass; i++) {

        final double[] tree = ArrayUtils.toPrimitive(sils.get(i).toArray(new Double[0]));

        for (double val : tree) {
            if (val > 0.75) {
                dataset.addValue(val, "Cluster " + i + " ++", "" + id);
                counter[i][0]++;
            } else if (val > 0.50) {
                dataset.addValue(val, "Cluster " + i + " +", "" + id);
                counter[i][1]++;
            } else if (val > 0.25) {
                dataset.addValue(val, "Cluster " + i + " =", "" + id);
                counter[i][2]++;
            } else {
                dataset.addValue(val, "Cluster " + i + " -", "" + id);
                counter[i][3]++;
            }
            if (val < minValue) {
                minValue = val;
            }
            id++;
        }

    }

    final CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
    categoryplot.setBackgroundPaint(Color.WHITE);
    categoryplot.getDomainAxis().setVisible(false);
    categoryplot.setDomainGridlinesVisible(false);
    categoryplot.setRangeGridlinesVisible(false);
    categoryplot.getRangeAxis().setRange(minValue, 1.0);

    //Add line markers
    ValueMarker target = new ValueMarker(0.75);
    target.setPaint(Color.BLACK);
    target.setLabel("  ++");
    target.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    target.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    categoryplot.addRangeMarker(target);

    target = new ValueMarker(0.5);
    target.setPaint(Color.BLACK);
    target.setLabel("  +");
    target.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    target.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    categoryplot.addRangeMarker(target);

    target = new ValueMarker(0.25);
    target.setPaint(Color.BLACK);
    target.setLabel("  =");
    target.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    target.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    categoryplot.addRangeMarker(target);

    target = new ValueMarker(0);
    target.setPaint(Color.BLACK);
    target.setLabel("  -");
    target.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    target.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    categoryplot.addRangeMarker(target);

    //Remove visual effects on bar
    final BarRenderer barrenderer = (BarRenderer) categoryplot.getRenderer();
    barrenderer.setBarPainter(new StandardBarPainter());

    //set bar colors
    int p = 0;
    final int max = ColorHelper.COLORBREWER_SEQUENTIAL_PALETTES.size();

    for (int i = 0; i < nbClass; i++) {
        final Color[] color = new ArrayList<Color[]>(ColorHelper.COLORBREWER_SEQUENTIAL_PALETTES.values())
                .get((max - i) % max);
        final int nbColors = color.length;
        for (int k = 0; k < counter[i].length; k++) {
            if (counter[i][k] > 0)
                barrenderer.setSeriesPaint(p++, color[(nbColors - k - 3) % nbColors]);
        }
    }

    //remove blank line between bars
    barrenderer.setItemMargin(-dataset.getRowCount());

    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setMouseWheelEnabled(true);
    chartPanel.setPreferredSize(new Dimension(1200, 900));
    chartPanel.setBorder(new TitledBorder("Silhouette plot"));
    chartPanel.setBackground(Color.WHITE);
    chart.setTitle("");
    return chartPanel;

}

From source file:org.miloss.fgsms.services.rs.impl.reports.ws.InvocationsByServiceByMethod.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  ww  .j  a v  a  2  s  .  c  o  m
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append("This represents the invocations for each service by method (action).<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URL</th><th>Action</th><th>Invocations</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)));
            List<String> actions = getSoapActions(urls.get(i), con);

            for (int k = 0; k < actions.size(); k++) {

                long count = 0;
                try {
                    cmd = con.prepareStatement("select count(*) from RawData where URI=? and "
                            + "(UTCdatetime > ?) and (UTCdatetime < ?) and soapaction=?;");
                    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();

                    if (rs.next()) {
                        count = rs.getLong(1);
                    }

                } 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>").append(count + "")
                        .append("</td></tr>");
                if (count > 0) {
                    set.addValue(count, actions.get(k), url);
                }
            }
        }
        data.append("</table>");
        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);

        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:org.miloss.fgsms.services.rs.impl.reports.ws.ThroughputByService.java

/**
 * {@inheritDoc}//from w  w w. j a  va2s. co  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;
        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>URL</th><th>Invocations</th><th>Msg/Day</th><th>Msg/Hour</th><th>Msg/Min</th><th>Msg/Sec</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)));
            long count = 0;
            try {
                cmd = con.prepareStatement("select count(*) 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();

                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);
            }

            double d = range.getEnd().getTimeInMillis() - range.getStart().getTimeInMillis();
            double day = d / 86400000;
            double hours = d / 3600000;
            double min = d / 60000;
            double sec = d / 1000;

            data.append("<tr><td>").append(url).append("</td><td>");
            data.append(count + "");
            data.append("</td><td>").append(format.format((double) ((double) count / day))).append("</td><td>")
                    .append(format.format((double) ((double) count / hours))).append("</td><td>")
                    .append(format.format((double) ((double) count / min))).append("</td><td>")
                    .append(format.format((double) ((double) count / sec))).append("</td></tr>");
            if (count > 0) {
                set.addValue((double) ((double) count / day), url, url);
            }

        }
        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:org.miloss.fgsms.services.rs.impl.reports.ws.InvocationsByService.java

/**
 * {@inheritDoc}/*from   www . j a  v  a 2  s  . co  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;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;

        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append("This represents the invocations for each service by method (action).<br />");
        data.append(
                "<table class=\"table table-hover\"><tr><th>URL</th><th>Action</th><th>Invocations</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);

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

                    try {
                        cmd = con.prepareStatement("select count(*) from RawData where URI=? and "
                                + "(UTCdatetime > ?) and (UTCdatetime < ?) and soapaction=?;");
                        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>").append(count + "")
                            .append("</td></tr>");
                    if (count > 0) {
                        set.addValue(count, actions.get(k), url);
                    }
                }
            } catch (Exception ex) {

                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);
    }
}