Example usage for org.jfree.chart.entity StandardEntityCollection StandardEntityCollection

List of usage examples for org.jfree.chart.entity StandardEntityCollection StandardEntityCollection

Introduction

In this page you can find the example usage for org.jfree.chart.entity StandardEntityCollection StandardEntityCollection.

Prototype

public StandardEntityCollection() 

Source Link

Document

Constructs a new entity collection (initially empty).

Usage

From source file:net.sourceforge.processdash.ui.web.CGIChartBase.java

private void writeImageHtml(int width, int height, int imgID, ChartRenderingInfo info) throws IOException {
    String tooltip = getParameter("tooltip");
    if (!StringUtils.hasValue(tooltip))
        tooltip = resources.getHTML("More_Detail_Here_Instruction");

    String href = getParameter("href");
    if (StringUtils.hasValue(href)) {
        // create a copy of the entity collection, and place an entity for
        // the entire chart at the beginning of the list.  This will
        // make it appear last in the image map (which is important,
        // because browsers process the image map areas in the order that
        // they appear; having the entire chart area listed first would
        // obscure all of the other image map areas).
        EntityCollection entities = new StandardEntityCollection();
        entities.add(new ChartEntity(info.getChartArea(), tooltip, href));
        if (info.getEntityCollection() != null)
            entities.addAll(info.getEntityCollection());

        // Next: most of our chart entities will not have URLs. URL values
        // don't inherit in the imagemap, so if we want the entire image
        // to have a single URL, we need to assign that URL to every
        // area in the chart.
        for (Iterator i = entities.iterator(); i.hasNext();) {
            ChartEntity ce = (ChartEntity) i.next();
            // check for no-op chart entity - these won't appear in the
            // image map anyway, so they don't need to be adjusted
            if (ce.getToolTipText() == null && ce.getURLText() == null)
                continue;
            // for other entities, add a tooltip and a URL as needed.
            if (!StringUtils.hasValue(ce.getToolTipText()))
                ce.setToolTipText(tooltip);
            if (!StringUtils.hasValue(ce.getURLText()))
                ce.setURLText(href);/*from w  ww  .j  a  v a 2 s . co  m*/
        }

        // install our modified version of the entity collection into
        // the chart info object, so it will be used when generating
        // the image map later.
        info.setEntityCollection(entities);
    }

    // write the image tag
    out.write("<img width=\"" + width + "\" height=\"" + height + "\" src=\"/reports/pngCache?id=" + imgID
            + "\" usemap=\"#IMG" + imgID + '"');

    // imagemaps have hyperlink borders by default, even if we don't
    // have a URL we're pointing to.  Turn that border off.
    if (!StringUtils.hasValue(href) || parameters.containsKey("noBorder"))
        out.write(" border=\"0\"");

    // Our client might want to add attributes to the image tag. Look
    // through the query parameters we received for arbitrary attributes
    // starting with the prefix "img", and copy them into the tag.
    for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) {
        Map.Entry e = (Map.Entry) i.next();
        String attrName = (String) e.getKey();
        if (attrName.startsWith("img") && !attrName.endsWith("_ALL")) {
            out.write(" " + attrName.substring(3) + "=\"");
            out.write(HTMLUtils.escapeEntities(e.getValue().toString()));
            out.write('"');
        }
    }

    out.write(">");

    // finally, write the image map.  Note that we have to strip line
    // break characters from the resulting HTML, otherwise firefox seems
    // to decide that the <map> tag actually takes up space on the page
    String imageMapHtml = ImageMapUtilities.getImageMap("IMG" + imgID, info, getToolTipGenerator(tooltip),
            new StandardURLTagFragmentGenerator());
    for (int i = 0; i < imageMapHtml.length(); i++) {
        char c = imageMapHtml.charAt(i);
        if (c != '\r' && c != '\n')
            out.write(c);
    }
    out.flush();
}

From source file:org.pentaho.platform.uifoundation.chart.CategoryDatasetChartComponent.java

@Override
public Document getXmlContent() {

    // Create a document that describes the result
    Document result = DocumentHelper.createDocument();
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    setXslProperty("baseUrl", requestContext.getContextPath()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty("fullyQualifiedServerUrl", //$NON-NLS-1$
            PentahoSystem.getApplicationContext().getFullyQualifiedServerURL()); //$NON-NLS-2$ //$NON-NLS-3$

    String mapName = "chart" + AbstractChartComponent.chartCount++; //$NON-NLS-1$
    Document chartDefinition = jcrHelper.getSolutionDocument(definitionPath, RepositoryFilePermission.READ);
    if (chartDefinition == null) {
        Element errorElement = result.addElement("error"); //$NON-NLS-1$
        errorElement.addElement("title").setText( //$NON-NLS-1$
                Messages.getInstance().getString("ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART")); //$NON-NLS-1$
        String message = Messages.getInstance().getString("CHARTS.ERROR_0001_CHART_DEFINIION_MISSING", //$NON-NLS-1$
                definitionPath);//from ww  w.j  a  v a 2 s  .c om
        errorElement.addElement("message").setText(message); //$NON-NLS-1$
        error(message);
        return result;
    }
    // create a pie definition from the XML definition
    dataDefinition = createChart(chartDefinition);

    if (dataDefinition == null) {
        Element errorElement = result.addElement("error"); //$NON-NLS-1$
        errorElement.addElement("title").setText( //$NON-NLS-1$
                Messages.getInstance().getString("ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART")); //$NON-NLS-1$
        String message = Messages.getInstance().getString("CHARTS.ERROR_0002_CHART_DATA_MISSING", actionPath); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        errorElement.addElement("message").setText(message); //$NON-NLS-1$
        // System .out.println( result.asXML() );
        return result;
    }

    // create an image for the dial using the JFreeChart engine
    PrintWriter printWriter = new PrintWriter(new StringWriter());
    // we'll dispay the title in HTML so that the dial image does not have
    // to
    // accommodate it
    String chartTitle = ""; //$NON-NLS-1$
    try {
        if (width == -1) {
            width = Integer.parseInt(chartDefinition.selectSingleNode("/chart/width").getText()); //$NON-NLS-1$
        }
    } catch (NumberFormatException ignored) {
        // go with the default
    }
    try {
        if (height == -1) {
            height = Integer.parseInt(chartDefinition.selectSingleNode("/chart/height").getText()); //$NON-NLS-1$
        }
    } catch (NumberFormatException ignored) {
        // go with the default
    }
    if (chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME) != null) { //$NON-NLS-1$
        urlTemplate = chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME) //$NON-NLS-1$
                .getText();
    }

    if (chartDefinition.selectSingleNode("/chart/paramName") != null) { //$NON-NLS-1$
        paramName = chartDefinition.selectSingleNode("/chart/paramName").getText(); //$NON-NLS-1$
    }

    Element root = result.addElement("charts"); //$NON-NLS-1$
    DefaultCategoryDataset chartDataDefinition = (DefaultCategoryDataset) dataDefinition;
    if (chartDataDefinition.getRowCount() > 0) {
        // create temporary file names
        String[] tempFileInfo = createTempFile();
        String fileName = tempFileInfo[AbstractChartComponent.FILENAME_INDEX];
        String filePathWithoutExtension = tempFileInfo[AbstractChartComponent.FILENAME_WITHOUT_EXTENSION_INDEX];

        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        JFreeChartEngine.saveChart(chartDataDefinition, chartTitle, "", filePathWithoutExtension, width, height, //$NON-NLS-1$
                JFreeChartEngine.OUTPUT_PNG, printWriter, info, this);
        applyOuterURLTemplateParam();
        populateInfo(info);
        Element chartElement = root.addElement("chart"); //$NON-NLS-1$
        chartElement.addElement("mapName").setText(mapName); //$NON-NLS-1$
        chartElement.addElement("width").setText(Integer.toString(width)); //$NON-NLS-1$
        chartElement.addElement("height").setText(Integer.toString(height)); //$NON-NLS-1$
        for (int row = 0; row < chartDataDefinition.getRowCount(); row++) {
            for (int column = 0; column < chartDataDefinition.getColumnCount(); column++) {
                Number value = chartDataDefinition.getValue(row, column);
                Comparable rowKey = chartDataDefinition.getRowKey(row);
                Comparable columnKey = chartDataDefinition.getColumnKey(column);
                Element valueElement = chartElement.addElement("value2D"); //$NON-NLS-1$
                valueElement.addElement("value").setText(value.toString()); //$NON-NLS-1$
                valueElement.addElement("row-key").setText(rowKey.toString()); //$NON-NLS-1$
                valueElement.addElement("column-key").setText(columnKey.toString()); //$NON-NLS-1$
            }
        }
        String mapString = ImageMapUtilities.getImageMap(mapName, info);
        chartElement.addElement("imageMap").setText(mapString); //$NON-NLS-1$
        chartElement.addElement("image").setText(fileName); //$NON-NLS-1$
    }
    return result;
}

From source file:org.squale.squaleweb.applicationlayer.action.results.application.ApplicationResultsAction.java

/**
 * Synthse d'une application Si l'application comporte un seul projet, la synthse du projet est alors affiche.
 * Dans le cas contraire, trois onglets sont prsents : un qui donne la rpartition, l'autre donnant les facteurs
 * par projet et le dernier donnant le kiviat.
 * /*from  ww  w. j a v  a 2  s .  c  o  m*/
 * @param pMapping le mapping.
 * @param pForm le formulaire  lire.
 * @param pRequest la requte HTTP.
 * @param pResponse la rponse de la servlet.
 * @return l'action  raliser.
 */
public ActionForward summary(ActionMapping pMapping, ActionForm pForm, HttpServletRequest pRequest,
        HttpServletResponse pResponse) {

    // Cette action est appele dans plusieurs contextes possibles
    // Depuis une action struts avec l'id de l'application ou depuis
    // une page de l'application sans id de l'application (on a alors affaire  l'application courante)
    ActionForward forward;
    try {
        // Add an user access for this application
        addUserAccess(pRequest, ActionUtils.getCurrentApplication(pRequest).getId());
        forward = checkApplication(pMapping, pRequest);
        // Si forward est renseign, l'application contient un seul projet
        // On redirige donc vers le projet adquat
        if (null == forward) {
            // Rcupration des informations concernant les facteurs
            // Rcupration du paramtre : tous les facteurs ou seuls les facteurs ayant une note ?
            ResultListForm resultListForm = (ResultListForm) pForm;
            boolean pAllFactors = resultListForm.isAllFactors();
            // On met cette valeur en session
            pRequest.getSession().setAttribute(ALL_FACTORS, new Boolean(pAllFactors));

            ApplicationForm application = ActionUtils.getCurrentApplication(pRequest);
            // On remet  jour les form en session permettant d'accder aux diffrents types d'audits
            SplitAuditsListForm auditsForm = (SplitAuditsListForm) pRequest.getSession()
                    .getAttribute("splitAuditsListForm");
            if (auditsForm != null) {
                auditsForm.copyValues(application);
                auditsForm.resetAudits(ActionUtils.getCurrentAuditsAsDTO(pRequest));
                pRequest.getSession().setAttribute("splitAuditsListForm", auditsForm);
            }
            List auditsDTO = ActionUtils.getCurrentAuditsAsDTO(pRequest);
            if (auditsDTO != null) {
                ((ResultListForm) pForm).resetAudits(auditsDTO);
            }
            // On efface ce form contenant les erreurs de l'application, car si on passe par ici
            // Ce form ne peut que contenir les informations pour une autre application
            pRequest.getSession().removeAttribute("applicationErrorForm");

            // Prparation de l'appel  la couche mtier
            IApplicationComponent ac = AccessDelegateHelper.getInstance("Results");
            List applications = Arrays
                    .asList(WTransformerFactory.formToObj(ApplicationTransformer.class, application));
            Object[] paramIn = { applications, auditsDTO };
            // Les rsultats sont retourns dans l'ordre impos par la grille
            // on maintient cet ordre pour l'affichage
            List results = (List) ac.execute("getApplicationResults", paramIn);
            pRequest.getSession().removeAttribute(SqualeWebConstants.RESULTS_KEY);
            if (null != results && results.size() > 0) {
                // Transformation des rsultats avant leur affichage par la couche
                // welcom
                WTransformerFactory.objToForm(FactorsResultListTransformer.class, (ResultListForm) pForm,
                        new Object[] { applications, results });
            } else {
                // si aucun resultat => liste vide
                WTransformerFactory.objToForm(FactorsResultListTransformer.class, (ResultListForm) pForm,
                        new Object[] { applications, new ArrayList() });
            }
            // Rcupration des donnes permettant la gnration du Kiviat et du PieChart de l'application
            if (null != auditsDTO && null != auditsDTO.get(0)) {
                // Prparation de l'appel  la couche mtier
                ac = AccessDelegateHelper.getInstance("Graph");
                Long pCurrentAuditId = new Long(((AuditDTO) auditsDTO.get(0)).getID());
                Object[] paramAuditIdKiviat = { pCurrentAuditId, String.valueOf(pAllFactors) };

                // Recherche des donnes Kiviat
                KiviatMaker maker = new KiviatMaker();
                Map projectsValues = (Map) ac.execute("getApplicationKiviatGraph", paramAuditIdKiviat);
                Set keysSet = projectsValues.keySet();
                Iterator it = keysSet.iterator();
                while (it.hasNext()) {
                    String key = (String) it.next();
                    maker.addValues(key, (SortedMap) projectsValues.get(key), pRequest);
                }
                JFreeChart chartKiviat = maker.getChart();
                ChartRenderingInfo infoKiviat = new ChartRenderingInfo(new StandardEntityCollection());
                // Initialisation du kiviat
                String fileNameKiviat = ServletUtilities.saveChartAsPNG(chartKiviat, KiviatMaker.DEFAULT_WIDTH,
                        KiviatMaker.DEFAULT_HEIGHT, infoKiviat, pRequest.getSession());
                GraphMaker applicationKiviatChart = new GraphMaker(pRequest, fileNameKiviat, infoKiviat);

                // Pour l'export en PDF
                pRequest.getSession().removeAttribute("kiviatChart");
                pRequest.getSession().setAttribute("kiviatChart",
                        chartKiviat.createBufferedImage(KiviatMaker.DEFAULT_WIDTH, KiviatMaker.DEFAULT_HEIGHT));

                // Recherche des donnes PieChart
                Object[] paramAuditIdPieChart = { pCurrentAuditId };
                JFreeChart pieChart;
                Object[] maps = (Object[]) ac.execute("getApplicationPieChartGraph", paramAuditIdPieChart);
                String pPreviousAuditId = null;
                // on peut ne pas avoir d'audit prcdent
                if (auditsDTO.size() > 1) {
                    pPreviousAuditId = "" + ((AuditDTO) auditsDTO.get(1)).getID();
                }
                PieChartMaker pieMaker = new PieChartMaker(null, pCurrentAuditId.toString(), pPreviousAuditId);
                pieMaker.setValues((Map) maps[0]);
                pieChart = pieMaker.getChart((Map) maps[1], pRequest);

                ChartRenderingInfo infoPieChart = new ChartRenderingInfo(new StandardEntityCollection());
                // Initialisation du pieChart
                String fileName = ServletUtilities.saveChartAsPNG(pieChart, PieChartMaker.DEFAULT_WIDTH,
                        PieChartMaker.DEFAULT_HEIGHT, infoPieChart, pRequest.getSession());
                GraphMaker applicationPieChart = new GraphMaker(pRequest, fileName, infoPieChart);

                // Met  jour les 2 champs du form avec les 2 graphs calculs
                ((ResultListForm) pForm).setKiviat(applicationKiviatChart);
                ((ResultListForm) pForm).setPieChart(applicationPieChart);

                // Met  jour le form en session
                pRequest.getSession().setAttribute("resultListForm", pForm);

                // Pour l'export en PDF
                pRequest.getSession().removeAttribute("pieChart");
                pRequest.getSession().setAttribute("pieChart", pieChart
                        .createBufferedImage(PieChartMaker.DEFAULT_WIDTH, PieChartMaker.DEFAULT_HEIGHT));
            }
            // Affichage des informations sur la page jsp
            forward = pMapping.findForward("summary");
        }
    } catch (Exception e) {
        ActionErrors errors = new ActionErrors();
        // Traitement factoris des erreurs
        handleException(e, errors, pRequest);
        // Sauvegarde des erreurs
        saveMessages(pRequest, errors);
        // Routage vers la page d'erreur
        forward = pMapping.findForward("total_failure");
    }
    // On est pass par un menu donc on rinitialise le traceur
    resetTracker(pRequest);
    // Indique que l'on vient d'une vue synthse et pas d'une vue composant
    changeWay(pRequest, "false");
    return forward;
}

From source file:gov.nih.nci.ispy.web.taglib.PCAPlotTag.java

public int doStartTag() {
    chart = null;/*from  w ww  . j  av a  2  s .  com*/
    pcaResults = null;
    pcaData.clear();

    ServletRequest request = pageContext.getRequest();
    HttpSession session = pageContext.getSession();
    Object o = request.getAttribute(beanName);
    JspWriter out = pageContext.getOut();
    ServletResponse response = pageContext.getResponse();

    try {
        //retrieve the Finding from cache and build the list of PCAData points
        PrincipalComponentAnalysisFinding principalComponentAnalysisFinding = (PrincipalComponentAnalysisFinding) businessTierCache
                .getSessionFinding(session.getId(), taskId);

        Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
        List<String> sampleIds = new ArrayList<String>();
        Map<String, PCAresultEntry> pcaResultMap = new HashMap<String, PCAresultEntry>();

        pcaResults = principalComponentAnalysisFinding.getResultEntries();
        for (PCAresultEntry pcaEntry : pcaResults) {
            sampleIds.add(pcaEntry.getSampleId());
            pcaResultMap.put(pcaEntry.getSampleId(), pcaEntry);
        }

        //Get the clinical data for the sampleIds
        ClinicalDataService cqs = ClinicalDataServiceFactory.getInstance();
        IdMapperFileBasedService idMapper = IdMapperFileBasedService.getInstance();
        //Map<String, ClinicalData> clinicalDataMap = cqs.getClinicalDataMapForLabtrackIds(sampleIds);              

        PCAresultEntry entry;
        //ClinicalData clinData;
        //PatientData patientData;
        SampleInfo si;
        TimepointType timepoint;
        for (String id : sampleIds) {

            entry = pcaResultMap.get(id);
            ISPYPCADataPoint pcaPoint = new ISPYPCADataPoint(id, entry.getPc1(), entry.getPc2(),
                    entry.getPc3());

            si = idMapper.getSampleInfoForLabtrackId(id);

            //clinData = cqs.getClinicalDataForPatientDID(si.getRegistrantId(), si.getTimepoint());
            //patientData = cqs.getPatientDataForPatientDID(si.getISPYId());
            Set<String> ispyIds = new HashSet<String>();
            ispyIds.add(si.getISPYId());
            ISPYclinicalDataQueryDTO dto = new ISPYclinicalDataQueryDTO();
            dto.setRestrainingSamples(ispyIds);
            Set<PatientData> pdSet = cqs.getClinicalData(dto);
            for (PatientData patientData : pdSet) {
                pcaPoint.setISPY_ID(si.getISPYId());
                timepoint = si.getTimepoint();

                pcaPoint.setTimepoint(timepoint);

                if (patientData != null) {
                    pcaPoint.setClinicalStage(patientData.getClinicalStage());

                    int clinRespVal;
                    Double mriPctChange = null;
                    if (timepoint == TimepointType.T1) {
                        pcaPoint.setClinicalResponse(ClinicalResponseType.NA);
                        pcaPoint.setTumorMRIpctChange(null);
                    } else if (timepoint == TimepointType.T2) {
                        clinRespVal = PatientData.parseValue(patientData.getClinRespT1_T2());
                        //set the clinical respoinse to the T1_T2
                        pcaPoint.setClinicalResponse(ClinicalResponseType.getTypeForValue(clinRespVal));
                        pcaPoint.setTumorMRIpctChange(patientData.getMriPctChangeT1_T2());
                    } else if (timepoint == TimepointType.T3) {
                        //set the clinical response to T1_T3
                        clinRespVal = PatientData.parseValue(patientData.getClinRespT1_T3());
                        pcaPoint.setClinicalResponse(ClinicalResponseType.getTypeForValue(clinRespVal));
                        pcaPoint.setTumorMRIpctChange(patientData.getMriPctChangeT1_T3());
                    } else if (timepoint == TimepointType.T4) {
                        //set the clinical response to T1_T4
                        clinRespVal = PatientData.parseValue(patientData.getClinRespT1_T4());
                        pcaPoint.setClinicalResponse(ClinicalResponseType.getTypeForValue(clinRespVal));
                        pcaPoint.setTumorMRIpctChange(patientData.getMriPctChangeT1_T4());
                    } else {
                        pcaPoint.setClinicalResponse(ClinicalResponseType.UNKNOWN);
                        pcaPoint.setTumorMRIpctChange(null);
                    }
                }

                pcaData.add(pcaPoint);
            }
        }

        //check the components to see which graph to get
        if (components.equalsIgnoreCase("PC1vsPC2")) {
            ISPYPrincipalComponentAnalysisPlot plot = new ISPYPrincipalComponentAnalysisPlot(pcaData,
                    PCAcomponent.PC2, PCAcomponent.PC1,
                    ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
            chart = plot.getChart();
        }
        if (components.equalsIgnoreCase("PC1vsPC3")) {
            ISPYPrincipalComponentAnalysisPlot plot = new ISPYPrincipalComponentAnalysisPlot(pcaData,
                    PCAcomponent.PC3, PCAcomponent.PC1,
                    ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
            chart = plot.getChart();
        }
        if (components.equalsIgnoreCase("PC2vsPC3")) {
            ISPYPrincipalComponentAnalysisPlot plot = new ISPYPrincipalComponentAnalysisPlot(pcaData,
                    PCAcomponent.PC3, PCAcomponent.PC2,
                    ColorByType.valueOf(ColorByType.class, colorBy.toUpperCase()));
            chart = plot.getChart();
        }

        ISPYImageFileHandler imageHandler = new ISPYImageFileHandler(session.getId(), "png", 650, 600);
        //The final complete path to be used by the webapplication
        String finalPath = imageHandler.getSessionTempFolder();
        String finalURLpath = imageHandler.getFinalURLPath();
        /*
         * Create the actual charts, writing it to the session temp folder
        */
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        String mapName = imageHandler.createUniqueMapName();
        //PrintWriter writer = new PrintWriter(new FileWriter(mapName));
        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 650, 600, info);
        //ImageMapUtil.writeBoundingRectImageMap(writer,"PCAimageMap",info,true);
        //writer.close();

        /*   This is here to put the thread into a loop while it waits for the
         *   image to be available.  It has an unsophisticated timer but at 
         *   least it is something to avoid an endless loop.
         **/
        boolean imageReady = false;
        int timeout = 1000;
        FileInputStream inputStream = null;
        while (!imageReady) {
            timeout--;
            try {
                inputStream = new FileInputStream(finalPath);
                inputStream.available();
                imageReady = true;
                inputStream.close();
            } catch (IOException ioe) {
                imageReady = false;
                if (inputStream != null) {
                    inputStream.close();
                }
            }
            if (timeout <= 1) {

                break;
            }
        }

        out.print(ImageMapUtil.getBoundingRectImageMapTag(mapName, false, info));
        finalURLpath = finalURLpath.replace("\\", "/");
        long randomness = System.currentTimeMillis(); //prevent image caching
        out.print("<img id=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?" + randomness
                + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

        //(imageHandler.getImageTag(mapFileName));

    } catch (IOException e) {
        logger.error(e);
    } catch (Exception e) {
        logger.error(e);
    } catch (Throwable t) {
        logger.error(t);
    }

    return EVAL_BODY_INCLUDE;
}

From source file:org.signserver.client.cli.performance.PerformanceTestPDFServlet.java

License:asdf

/**
 * Create and write diagrams to disk./*from  ww w  .  j  av a 2  s .co m*/
 */
private void createDiagram(String statisticsDirectory, ArrayList<String> explanationRow,
        ArrayList<ArrayList<Double>> processedData, int xRow, int y1Row, int y2Row) {
    final XYSeries s1 = new XYSeries(explanationRow.get(y1Row));
    final XYSeries s2 = new XYSeries(explanationRow.get(y2Row));
    for (ArrayList<Double> currentRow : processedData) {
        s1.add(currentRow.get(xRow), currentRow.get(y1Row));
        s2.add(currentRow.get(xRow), currentRow.get(y2Row));
    }
    final XYSeriesCollection dataset1 = new XYSeriesCollection();
    dataset1.addSeries(s1);
    final XYSeriesCollection dataset2 = new XYSeriesCollection();
    dataset2.addSeries(s2);
    final JFreeChart chart = ChartFactory.createXYLineChart("Test result " + xRow + "" + y1Row + "" + y2Row,
            explanationRow.get(xRow), explanationRow.get(y1Row), dataset1, PlotOrientation.VERTICAL, true, true,
            false);
    final XYPlot plot = chart.getXYPlot();
    if (y1Row == COLUMN_INVOCATIONS_PER_SECOND) {
        final NumberAxis axis1 = new LogarithmicAxis(explanationRow.get(y1Row));
        plot.setRangeAxis(0, axis1);
    }
    final NumberAxis axis2 = new NumberAxis(explanationRow.get(y2Row));
    axis2.setAutoRangeIncludesZero(false);
    plot.setRangeAxis(1, axis2);
    plot.setDataset(1, dataset2);
    plot.mapDatasetToRangeAxis(1, 1);
    final StandardXYItemRenderer renderer2 = new StandardXYItemRenderer();
    renderer2.setSeriesPaint(0, Color.BLUE);
    plot.setRenderer(1, renderer2);
    final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
    final File file = new File(
            statisticsDirectory + "PDF Signatures" + "-" + xRow + "" + y1Row + "" + y2Row + ".png");
    int imageWidth = 800;
    int imageHeight = 600;
    try {
        System.out.println("Writing diagram to " + file.getName());
        System.out.flush();
        ChartUtilities.saveChartAsPNG(file, chart, imageWidth, imageHeight, info);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:graph.plotter.PieMenu.java

/**
 * This is the main working button for this class... It creates pie chart analyZing whole data set
 * //from   w w w. j a v  a  2 s .c  om
 * @param evt 
 */
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    try {
        DefaultPieDataset pieDataset = new DefaultPieDataset(); /** Initializing pie dataset*/
        int i;
        i = 0;
        String genre = "a";
        if (Button == 1) { /** For User Input*/
            while (i < cnt) {
                double aa = Double.parseDouble(Table.getModel().getValueAt(i, 1).toString());
                String str = Table.getModel().getValueAt(i, 0).toString();

                pieDataset.setValue(str, new Double(aa));
                i++;
                genre += "a";

            }
        } else {
            try {
                BufferedReader br = new BufferedReader(new FileReader(jTextField3.getText()));
                String Line;
                while ((Line = br.readLine()) != null) {
                    String[] value = Line.split(",");
                    double val = Double.parseDouble(value[1]);
                    pieDataset.setValue(value[0], new Double(val));
                    //                dataset.setValue(new Double(val),genre,value[0]);
                    //                genre+="a";
                    // (value[0]);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(PieMenu.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(PieMenu.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        JFreeChart chart = ChartFactory.createPieChart("Pie Chart", pieDataset, true, true, true);
        PiePlot P = (PiePlot) chart.getPlot();
        P.setLabelLinkPaint(Color.BLACK);
        P.setBackgroundPaint(Color.white);
        ChartFrame frame = new ChartFrame("PieChart", chart);
        jButto1 = new JButton("Save");

        frame.setLayout(new BorderLayout());

        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());

        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = 1;
        gc.gridy = 0;

        panel.add(jButto1, gc);

        frame.add(panel, BorderLayout.SOUTH);

        jButto1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                try {
                    final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
                    final File file1 = new File("Pie_Chart.png");
                    ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
                } catch (Exception ex) {

                }

            }
        });
        frame.setVisible(true);
        frame.setSize(858, 512);

        try {
            final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            final File file1 = new File("Pie_Chart.png");
            ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
        } catch (Exception e) {

        }
    } catch (Exception ex) {

    }
}

From source file:org.pentaho.platform.uifoundation.chart.DialChartComponent.java

@Override
public Document getXmlContent() {

    // Create a document that describes the result
    Document result = DocumentHelper.createDocument();
    IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
    setXslProperty("baseUrl", requestContext.getContextPath()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    setXslProperty("fullyQualifiedServerUrl", //$NON-NLS-1$
            PentahoSystem.getApplicationContext().getFullyQualifiedServerURL()); //$NON-NLS-2$ //$NON-NLS-3$
    String mapName = "chart" + AbstractChartComponent.chartCount++; //$NON-NLS-1$
    Document chartDefinition = jcrHelper.getSolutionDocument(definitionPath, RepositoryFilePermission.READ);

    if (chartDefinition == null) {
        Element errorElement = result.addElement("error"); //$NON-NLS-1$
        errorElement.addElement("title").setText( //$NON-NLS-1$
                Messages.getInstance().getString("ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART")); //$NON-NLS-1$
        String message = Messages.getInstance().getString("CHARTS.ERROR_0001_CHART_DEFINIION_MISSING", //$NON-NLS-1$
                definitionPath);//  ww  w. j  av  a2 s  . c  om
        errorElement.addElement("message").setText(message); //$NON-NLS-1$
        error(message);
        return result;
    }

    dataDefinition = createChart(chartDefinition);

    if (dataDefinition == null) {
        Element errorElement = result.addElement("error"); //$NON-NLS-1$
        errorElement.addElement("title").setText( //$NON-NLS-1$
                Messages.getInstance().getString("ABSTRACTCHARTEXPRESSION.ERROR_0001_ERROR_GENERATING_CHART")); //$NON-NLS-1$
        String message = Messages.getInstance().getString("CHARTS.ERROR_0002_CHART_DATA_MISSING", actionPath); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        errorElement.addElement("message").setText(message); //$NON-NLS-1$
        // System .out.println( result.asXML() );
        return result;
    }

    // create an image for the dial using the JFreeChart engine
    PrintWriter printWriter = new PrintWriter(new StringWriter());
    // we'll dispay the title in HTML so that the dial image does not have
    // to
    // accommodate it
    String chartTitle = ""; //$NON-NLS-1$
    try {
        if (width == -1) {
            width = Integer.parseInt(chartDefinition.selectSingleNode("/chart/width").getText()); //$NON-NLS-1$
        }
        if (height == -1) {
            height = Integer.parseInt(chartDefinition.selectSingleNode("/chart/height").getText()); //$NON-NLS-1$
        }
    } catch (Exception e) {
        // go with the default
    }
    if (chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME) != null) { //$NON-NLS-1$
        urlTemplate = chartDefinition.selectSingleNode("/chart/" + AbstractChartComponent.URLTEMPLATE_NODE_NAME) //$NON-NLS-1$
                .getText();
    }

    if (chartDefinition.selectSingleNode("/chart/paramName") != null) { //$NON-NLS-1$
        paramName = chartDefinition.selectSingleNode("/chart/paramName").getText(); //$NON-NLS-1$
    }

    Element root = result.addElement("charts"); //$NON-NLS-1$
    DefaultValueDataset chartDataDefinition = (DefaultValueDataset) dataDefinition;

    // if (dataDefinition.getRowCount() > 0) {
    // create temporary file names
    String[] tempFileInfo = createTempFile();
    String fileName = tempFileInfo[AbstractChartComponent.FILENAME_INDEX];
    String filePathWithoutExtension = tempFileInfo[AbstractChartComponent.FILENAME_WITHOUT_EXTENSION_INDEX];

    ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
    JFreeChartEngine.saveChart(chartDataDefinition, chartTitle, "", filePathWithoutExtension, width, height, //$NON-NLS-1$
            JFreeChartEngine.OUTPUT_PNG, printWriter, info, this);
    applyOuterURLTemplateParam();
    populateInfo(info);
    Element chartElement = root.addElement("chart"); //$NON-NLS-1$
    chartElement.addElement("mapName").setText(mapName); //$NON-NLS-1$
    chartElement.addElement("width").setText(Integer.toString(width)); //$NON-NLS-1$
    chartElement.addElement("height").setText(Integer.toString(height)); //$NON-NLS-1$
    // for (int row = 0; row < chartDataDefinition.getRowCount(); row++) {
    // for (int column = 0; column < chartDataDefinition.getColumnCount(); column++) {
    // Number value = chartDataDefinition.getValue(row, column);
    // Comparable rowKey = chartDataDefinition.getRowKey(row);
    // Comparable columnKey = chartDataDefinition.getColumnKey(column);
    //                    Element valueElement = chartElement.addElement("value2D"); //$NON-NLS-1$
    //                    valueElement.addElement("value").setText(value.toString()); //$NON-NLS-1$
    //                    valueElement.addElement("row-key").setText(rowKey.toString()); //$NON-NLS-1$
    //                    valueElement.addElement("column-key").setText(columnKey.toString()); //$NON-NLS-1$
    // }
    // }
    String mapString = ImageMapUtilities.getImageMap(mapName, info);
    chartElement.addElement("imageMap").setText(mapString); //$NON-NLS-1$
    chartElement.addElement("image").setText(fileName); //$NON-NLS-1$
    // }
    return result;
}

From source file:org.gephi.statistics.plugin.DegreeDistribution.java

/**
 *
 * @return The directed version of the report.
 *//*from w w w  .ja v  a  2  s  .  c  o  m*/
private String getDirectedReport() {
    double inMax = 0;
    XYSeries inSeries2 = new XYSeries("Series 2");
    for (int i = 1; i < inDistribution[1].length; i++) {
        if (inDistribution[1][i] > 0) {
            inSeries2.add((Math.log(inDistribution[0][i]) / Math.log(Math.E)),
                    (Math.log(inDistribution[1][i]) / Math.log(Math.E)));
            inMax = (float) Math.max((Math.log(inDistribution[0][i]) / Math.log(Math.E)), inMax);
        }
    }
    double inA = inAlpha;
    double inB = inBeta;

    String inImageFile = "";
    String outImageFile = "";
    try {

        XYSeries inSeries1 = new XYSeries(inAlpha + " ");
        inSeries1.add(0, inA);
        inSeries1.add(inMax, inA + inB * inMax);

        XYSeriesCollection inDataset = new XYSeriesCollection();
        inDataset.addSeries(inSeries1);
        inDataset.addSeries(inSeries2);

        JFreeChart inChart = ChartFactory.createXYLineChart("In-Degree Distribution", "In-Degree", "Occurrence",
                inDataset, PlotOrientation.VERTICAL, true, false, false);
        XYPlot inPlot = (XYPlot) inChart.getPlot();
        XYLineAndShapeRenderer inRenderer = new XYLineAndShapeRenderer();
        inRenderer.setSeriesLinesVisible(0, true);
        inRenderer.setSeriesShapesVisible(0, false);
        inRenderer.setSeriesLinesVisible(1, false);
        inRenderer.setSeriesShapesVisible(1, true);
        inRenderer.setSeriesShape(1, new java.awt.geom.Ellipse2D.Double(0, 0, 1, 1));
        inPlot.setBackgroundPaint(java.awt.Color.WHITE);
        inPlot.setDomainGridlinePaint(java.awt.Color.GRAY);
        inPlot.setRangeGridlinePaint(java.awt.Color.GRAY);

        inPlot.setRenderer(inRenderer);

        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

        TempDir tempDir = TempDirUtils.createTempDir();
        final String fileName = "inDistribution.png";
        final File file1 = tempDir.createFile(fileName);
        inImageFile = "<IMG SRC=\"file:" + file1.getAbsolutePath() + "\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\"></IMG>";
        ChartUtilities.saveChartAsPNG(file1, inChart, 600, 400, info);

        double outMax = 0;
        XYSeries outSeries2 = new XYSeries("Series 2");
        for (int i = 1; i < outDistribution[1].length; i++) {
            if (outDistribution[1][i] > 0) {
                outSeries2.add((Math.log(outDistribution[0][i]) / Math.log(Math.E)),
                        (Math.log(outDistribution[1][i]) / Math.log(Math.E)));
                outMax = (float) Math.max((Math.log(outDistribution[0][i]) / Math.log(Math.E)), outMax);
            }
        }
        double outA = outAlpha;
        double outB = outBeta;

        XYSeries outSeries1 = new XYSeries(outAlpha + " ");
        outSeries1.add(0, outA);
        outSeries1.add(outMax, outA + outB * outMax);

        XYSeriesCollection outDataset = new XYSeriesCollection();
        outDataset.addSeries(outSeries1);
        outDataset.addSeries(outSeries2);

        JFreeChart outchart = ChartFactory.createXYLineChart("Out-Degree Distribution", "Out-Degree",
                "Occurrence", outDataset, PlotOrientation.VERTICAL, true, false, false);
        XYPlot outPlot = (XYPlot) outchart.getPlot();
        XYLineAndShapeRenderer outRenderer = new XYLineAndShapeRenderer();
        outRenderer.setSeriesLinesVisible(0, true);
        outRenderer.setSeriesShapesVisible(0, false);
        outRenderer.setSeriesLinesVisible(1, false);
        outRenderer.setSeriesShapesVisible(1, true);
        outRenderer.setSeriesShape(1, new java.awt.geom.Ellipse2D.Double(0, 0, 1, 1));
        outPlot.setBackgroundPaint(java.awt.Color.WHITE);
        outPlot.setDomainGridlinePaint(java.awt.Color.GRAY);
        outPlot.setRangeGridlinePaint(java.awt.Color.GRAY);

        outPlot.setRenderer(outRenderer);

        final ChartRenderingInfo info2 = new ChartRenderingInfo(new StandardEntityCollection());
        final String fileName2 = "outDistribution.png";
        final File file2 = tempDir.createFile(fileName2);
        outImageFile = "<IMG SRC=\"file:" + file2.getAbsolutePath() + "\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\"></IMG>";
        ChartUtilities.saveChartAsPNG(file2, outchart, 600, 400, info2);
    } catch (IOException e) {
        Exceptions.printStackTrace(e);
    }

    String report = "<HTML> <BODY> <h1>Degree Distribution Metric Report </h1> " + "<hr>" + "<br>"
            + "<h2> Parameters: </h2>" + "Network Interpretation:  " + (isDirected ? "directed" : "undirected")
            + "<br>" + "<br> <h2> Results: </h2>" + "In-Degree Power Law: -" + inAlpha + "\n <BR>" + inImageFile
            + "<br>Out-Degree Power Law: -" + outAlpha + "\n <BR>" + outImageFile + "</BODY> </HTML>";

    return report;
}

From source file:com.modeln.build.ctrl.charts.CMnBuildListChart.java

/**
 * Return rendering information for the chart.
 *//*w w w  .  j a  v  a 2 s .c  om*/
public static final ChartRenderingInfo getAverageTestCountRenderingInfo() {
    return new ChartRenderingInfo(new StandardEntityCollection());
}

From source file:graph.plotter.BarMenu.java

/**
 * This is the main working button for this class... It creates bar chart analyZing whole data set
 * /*from  w ww  .  j  av a2s .  com*/
 * @param evt 
 */
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:
    try {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        int i;
        i = 0;
        String genre = " ";
        if (Button == 1)
            while (i < count) {
                double amount = Double.parseDouble(Table.getModel().getValueAt(i, 1).toString());
                String name = Table.getModel().getValueAt(i, 0).toString();
                dataset.setValue(new Double(amount), genre, name);
                i++;
                genre += " ";

            }
        else {
            try {
                BufferedReader br = new BufferedReader(new FileReader(jTextField3.getText()));
                String Line;
                while ((Line = br.readLine()) != null) {
                    String[] value = Line.split(",");
                    double val = Double.parseDouble(value[1]);

                    dataset.setValue(new Double(val), genre, value[0]);
                    genre += " ";
                    System.out.println(value[0]);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(BarMenu.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(BarMenu.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        JFreeChart chart = ChartFactory.createBarChart3D("Amount", "Name", "Amount", dataset,
                PlotOrientation.VERTICAL, false, true, false);
        CategoryPlot p = chart.getCategoryPlot();
        p.setRangeGridlinePaint(Color.white);
        p.setBackgroundPaint(Color.black);
        ChartFrame frame = new ChartFrame("Bar Chart", chart);
        saveButton = new JButton("Save image in Project Folder");

        frame.setLayout(new BorderLayout());

        JPanel panel = new JPanel();
        panel.setLayout(new GridBagLayout());

        GridBagConstraints gc = new GridBagConstraints();
        gc.gridx = 1;
        gc.gridy = 0;

        panel.add(saveButton, gc);

        frame.add(panel, BorderLayout.SOUTH);

        saveButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                try {
                    final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
                    final File file1 = new File("Bar_Chart.png");
                    ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
                } catch (Exception ex) {

                }

            }
        });
        frame.setVisible(true);

        frame.setSize(858, 513);
    } catch (Exception e) {

    }
}