Example usage for org.jfree.chart ChartRenderingInfo ChartRenderingInfo

List of usage examples for org.jfree.chart ChartRenderingInfo ChartRenderingInfo

Introduction

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

Prototype

public ChartRenderingInfo(EntityCollection entities) 

Source Link

Document

Constructs a new instance.

Usage

From source file:org.squale.squaleweb.applicationlayer.action.results.project.ProjectResultsAction.java

/**
 * Prsente les rsultats rsums du projet.
 * // w w  w. j a  va  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) {

    ActionForward forward = null;
    ActionErrors errors = new ActionErrors();
    Long currentAuditId = null, previousAuditId = null;
    try {
        forward = init(pMapping, pRequest, pForm);
        if (null == forward) {
            if (getSummary(pRequest, pForm)) {
                // Rcupration des donnes permettant la gnration du Kiviat du projet
                // On rcupre le projet
                ComponentDTO project = (ComponentDTO) pRequest.getSession()
                        .getAttribute(BaseDispatchAction.PROJECT_DTO);
                AuditDTO audit = (AuditDTO) pRequest.getSession()
                        .getAttribute(BaseDispatchAction.CURRENT_AUDIT_DTO);
                AuditDTO previousAudit = (AuditDTO) pRequest.getSession()
                        .getAttribute(BaseDispatchAction.CURRENT_AUDIT_DTO);
                if (project != null && audit != null) {
                    // Rcupration du paramtre : tous les facteurs ou seuls les facteurs ayant une note ?
                    ProjectSummaryForm projectSummaryForm = (ProjectSummaryForm) pForm;
                    boolean pAllFactors = projectSummaryForm.isAllFactors();
                    // On met cette valeur en session
                    pRequest.getSession().setAttribute(ALL_FACTORS, new Boolean(pAllFactors));
                    // Prparation de l'appel  la couche mtier
                    IApplicationComponent ac = AccessDelegateHelper.getInstance("Graph");
                    Long projectId = new Long(project.getID());
                    currentAuditId = new Long(audit.getID());

                    Object[] paramsKiviat = { projectId, currentAuditId, String.valueOf(pAllFactors) };

                    // Recherche des donnes utiles  la gnration du Kiviat
                    // Recherche des donnes Kiviat
                    KiviatMaker maker = new KiviatMaker();
                    Object[] kiviatObject = (Object[]) ac.execute("getProjectKiviatGraph", paramsKiviat);
                    Map projectsValues = (Map) kiviatObject[0];
                    Boolean displayCheckBoxFactors = (Boolean) kiviatObject[1];
                    projectSummaryForm.setDisplayCheckBoxFactors(displayCheckBoxFactors);

                    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());
                    // Sauvegarde de l'image du Kiviat au format png dans un espace temporaire
                    String fileNameKiviat = ServletUtilities.saveChartAsPNG(chartKiviat,
                            KiviatMaker.DEFAULT_WIDTH, KiviatMaker.DEFAULT_HEIGHT, infoKiviat,
                            pRequest.getSession());
                    GraphMaker projectKiviatChart = new GraphMaker(pRequest, fileNameKiviat, infoKiviat);

                    // Pour l'export pdf en attendant de mettre les graphe dans les formulaires
                    pRequest.getSession().removeAttribute("kiviatChart");
                    pRequest.getSession().setAttribute("kiviatChart", chartKiviat
                            .createBufferedImage(KiviatMaker.DEFAULT_WIDTH, KiviatMaker.DEFAULT_HEIGHT));

                    ((ProjectSummaryForm) pForm).setKiviat(projectKiviatChart);
                    ((ProjectSummaryForm) pForm).setTags(project.getTags());
                }
                forward = pMapping.findForward("summary");
            } else { // Aucun audit, redirige vers la page courante
                forward = pMapping.findForward("noAudits");
            }
        }
    } catch (Exception e) {
        // Factorisation du traitement des exceptions
        handleException(e, errors, pRequest);
    }
    if (!errors.isEmpty()) {
        // Enregistrement des messages
        saveMessages(pRequest, errors);
        // Routage vers la page d'erreur
        forward = pMapping.findForward("total_failure");
    }
    // Mise en place du traceur historique
    updateHistTracker(WebMessages.getString(pRequest, "tracker.synthesis"), "project.do?action=summary",
            TrackerStructure.UNDEFINED, pRequest, true);
    // Indique que l'on vient d'une vue synthse et pas d'une vue composant
    changeWay(pRequest, "false");
    return forward;
}

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

/**
 * Return rendering information for the chart.
 *///from   w  w  w .jav  a  2 s .  co  m
public static final ChartRenderingInfo getAreaTestCountRenderingInfo() {
    return new ChartRenderingInfo(new StandardEntityCollection());
}

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

/**
 * Create the GraphMaker for a manual practice
 * /*from  ww w. j  av  a  2  s.c o m*/
 * @param pRequest The http request
 * @param result The list of results to display
 * @return an object GraphMaker
 * @throws IOException exception happen
 */
private GraphMaker manualMarkGraph(HttpServletRequest pRequest, Object[] result) throws IOException {
    GraphMaker histoChart = null;
    if (((Map) result[1]).size() > 0 || ((Map) result[3]).size() > 0) {
        HistoMaker histoMaker = new HistoMaker();
        //Add the curve for the historic of mark
        histoMaker.addCurve((String) result[0], (Map) result[1]);
        //Add the curve for the validity period
        histoMaker.addCurve(WebMessages.getString(pRequest, "reviewManualMark.validity"), (Map) result[3]);
        JFreeChart chartKiviat = histoMaker.getChart(true);
        ChartRenderingInfo infoHisto = new ChartRenderingInfo(new StandardEntityCollection());
        // save the graph as png in a temporary space
        String fileNameHisto = ServletUtilities.saveChartAsPNG(chartKiviat, HistoMaker.DEFAULT_WIDTH,
                HistoMaker.DEFAULT_HEIGHT, infoHisto, pRequest.getSession());
        histoChart = new GraphMaker(pRequest, fileNameHisto, infoHisto);
    }
    return histoChart;
}

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

public int doStartTag() {
    chart = null;//from  ww  w.j  a v a 2s  .c om
    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>();
        if (principalComponentAnalysisFinding != null) {
            pcaResults = principalComponentAnalysisFinding.getResultEntries();
            for (PCAresultEntry pcaEntry : pcaResults) {
                sampleIds.add(pcaEntry.getSampleId());
                pcaResultMap.put(pcaEntry.getSampleId(), pcaEntry);
            }

            Collection<SampleResultset> validatedSampleResultset = ClinicalDataValidator
                    .getValidatedSampleResultsetsFromSampleIDs(sampleIds, clinicalFactors);

            if (validatedSampleResultset != null) {
                String id;
                PCAresultEntry entry;

                for (SampleResultset rs : validatedSampleResultset) {
                    id = rs.getBiospecimen().getSpecimenName();
                    entry = pcaResultMap.get(id);
                    PrincipalComponentAnalysisDataPoint pcaPoint = new PrincipalComponentAnalysisDataPoint(id,
                            entry.getPc1(), entry.getPc2(), entry.getPc3());
                    String diseaseName = rs.getDisease().getValueObject();
                    if (diseaseName != null) {
                        pcaPoint.setDiseaseName(diseaseName);
                    } else {
                        pcaPoint.setDiseaseName(DiseaseType.NON_TUMOR.name());
                    }
                    GenderDE genderDE = rs.getGenderCode();
                    if (genderDE != null && genderDE.getValue() != null) {
                        String gt = genderDE.getValueObject().trim();
                        if (gt != null) {
                            GenderType genderType = GenderType.valueOf(gt);
                            if (genderType != null) {
                                pcaPoint.setGender(genderType);
                            }
                        }
                    }
                    Long survivalLength = rs.getSurvivalLength();
                    if (survivalLength != null) {
                        //survival length is stored in days in the DB so divide by 30 to get the 
                        //approx survival in months
                        double survivalInMonths = survivalLength.doubleValue() / 30.0;
                        pcaPoint.setSurvivalInMonths(survivalInMonths);
                    }
                    pcaData.add(pcaPoint);
                }
            }

            PCAcomponent pone = PCAcomponent.PC1;
            PCAcomponent ptwo = PCAcomponent.PC2;
            //check the components to see which graph to get
            if (components.equalsIgnoreCase("PC1vsPC2")) {
                pone = PCAcomponent.PC2;
                ptwo = PCAcomponent.PC1;
                //chart = (JFreeChart) CaIntegratorChartFactory.getPrincipalComponentAnalysisGraph(pcaData,PCAcomponent.PC2,PCAcomponent.PC1,PCAcolorByType.valueOf(PCAcolorByType.class,colorBy));
            }
            if (components.equalsIgnoreCase("PC1vsPC3")) {
                pone = PCAcomponent.PC3;
                ptwo = PCAcomponent.PC1;
                //chart = (JFreeChart) CaIntegratorChartFactory.getPrincipalComponentAnalysisGraph(pcaData,PCAcomponent.PC3,PCAcomponent.PC1,PCAcolorByType.valueOf(PCAcolorByType.class,colorBy));
            }
            if (components.equalsIgnoreCase("PC2vsPC3")) {
                pone = PCAcomponent.PC2;
                ptwo = PCAcomponent.PC3;
                //chart = (JFreeChart) CaIntegratorChartFactory.getPrincipalComponentAnalysisGraph(pcaData,PCAcomponent.PC3,PCAcomponent.PC2,PCAcolorByType.valueOf(PCAcolorByType.class,colorBy));
            }

            PrincipalComponentAnalysisPlot plot = new RBTPrincipalComponentAnalysisPlot(pcaData, pone, ptwo,
                    PCAcolorByType.valueOf(PCAcolorByType.class, colorBy));
            if (plot != null) {
                chart = (JFreeChart) plot.getChart();
            }

            RembrandtImageFileHandler imageHandler = new RembrandtImageFileHandler(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\" alt=\"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:Gui.admin.NouveauStatistique.java

private void StatistiquesBouttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_StatistiquesBouttonActionPerformed

    int size = tablemesEvaluation.getRowCount();

    List<Double> notes = new ArrayList<Double>();
    List<Integer> ids = new ArrayList<Integer>();
    List<String> noms = new ArrayList<String>();
    EvaluationDAO evaluationDAO = new EvaluationDAO();
    System.out.println("ouh ouh  " + size);
    //System.out.println(evaluationDAO.getMoyenneByAdherent(8));
    int idadh;/*www  .  j  av  a 2 s. c om*/
    float ess;
    for (int i = 0; i < size; i++) {

        System.out.println(tablemesEvaluation.getValueAt(i, 4).toString());
        idadh = Integer.parseInt(tablemesEvaluation.getValueAt(i, 1).toString());
        String nom = (tablemesEvaluation.getValueAt(i, 2).toString());
        // notes.add((new Double (tablemesEvaluation.getValueAt(i,2).toString())));
        System.out.println(" id adherent " + idadh);
        // System.out.println("moyenne "+);
        ess = evaluationDAO.getMoyenneByAdherent(idadh);
        System.out.println(ess);
        // notes.add((new Double (evaluationDAO.getMoyenneByAdherent((int) tablemesEvaluation.getValueAt(i,1)))));
        notes.add((new Double(ess)));
        ids.add((int) tablemesEvaluation.getValueAt(i, 1));
        noms.add(nom);

    }

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (int i = 0; i < size; i++) {

        dataset.setValue(new Double(notes.get(i)), "notes", new String(noms.get(i)));

    }

    //dataset.setValue(evaluationTable);

    JFreeChart chart = ChartFactory.createBarChart3D("Notes Adhrents", "Noms des adhrents", "Notes",
            dataset, PlotOrientation.VERTICAL, true, true, false);
    CategoryPlot p = chart.getCategoryPlot();
    p.setRangeGridlinePaint(Color.black);
    ChartFrame frame = new ChartFrame(" les notes des adhrents", chart);
    frame.setVisible(true);
    frame.setSize(700, 800);
    ValueMarker marker = new ValueMarker(15);
    marker.setLabel(" seuil de l'valuation ");
    marker.setLabelAnchor(RectangleAnchor.CENTER);
    marker.setPaint(Color.YELLOW);
    p.addRangeMarker(marker);
    p.setRangeGridlinePaint(Color.RED);

    try {

    }

    catch (Exception e) {
    }

    /*
    String note =noteTxt.getText();
    String idAdherent=idAdherentEvaluText.getText();
            
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    dataset.setValue(new Double(note), "notes", new Double(idAdherent));
    //dataset.setValue(evaluationTable);
            
    JFreeChart chart = ChartFactory.createBarChart3D("Notes Adhrents", "Id Adhrents", "Notes", dataset, PlotOrientation.VERTICAL, false, true, false);
    CategoryPlot p= chart.getCategoryPlot();
    p.setRangeGridlinePaint(Color.black);
    ChartFrame frame = new ChartFrame(" les notes des adhrents", chart);
    frame.setVisible(true);
    frame.setSize(450,350);
    */
    try {

        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("statistiques.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

    }

    catch (Exception e) {
    }
}

From source file:gov.nih.nci.cma.web.graphing.GEPlot.java

public String generateLog2Chart(String xAxisLabel, String yAxisLabel, HttpSession session, PrintWriter pw) {
    String log2Filename = "";

    JFreeChart log2Chart = null;//from  ww  w  .j av a 2 s  .  c o m
    try {

        log2Chart = ChartFactory.createBarChart(null, xAxisLabel, // domain axis label
                yAxisLabel, log2Dataset, // data
                PlotOrientation.VERTICAL, // orientation
                true, // include legend
                true, // tooltips?
                false // URLs?
        );
        log2Chart.setBackgroundPaint(java.awt.Color.white);
        // lets start some customization to retro fit w/jcharts lookand feel
        CategoryPlot plot = log2Chart.getCategoryPlot();
        CategoryAxis axis = plot.getDomainAxis();
        axis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
        axis.setLowerMargin(0.02); // two percent
        axis.setCategoryMargin(0.20); // 20 percent
        axis.setUpperMargin(0.02); // two percent
        StatisticalBarRenderer renderer = new StatisticalBarRenderer();

        // BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setItemMargin(0.01); // one percent
        renderer.setDrawBarOutline(true);
        renderer.setOutlinePaint(Color.BLACK);
        renderer.setBaseToolTipGenerator(new CategoryToolTipGenerator() {

            public String generateToolTip(CategoryDataset dataset, int series, int item) {
                String stdDev = (String) stdDevMap
                        .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item));

                return "Probeset : " + dataset.getRowKey(series) + "<br/>Intensity : "
                        + new DecimalFormat("0.0000").format(dataset.getValue(series, item)) + "<br/>"
                        + "<br/>Std. Dev.: " + stdDev + "<br/>";
            }

        });

        // LegendTitle lg = chart.getLegend();
        plot.setRenderer(renderer);

        // lets generate a custom legend - assumes theres only one source?
        //LegendItemCollection lic = log2Chart.getLegend().getSources()[0].getLegendItems();
        //legendHtml = LegendCreator.buildLegend(lic, "Probesets");
        log2Chart.removeLegend();
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        log2Filename = ServletUtilities.saveChartAsPNG(log2Chart, imgW, 400, info, session);
        ChartUtilities.writeImageMap(pw, log2Filename, info, new CustomOverlibToolTipTagFragmentGenerator(),
                new StandardURLTagFragmentGenerator());

    } catch (Exception e) {
        System.out.println("Exception - " + e.toString());
        e.printStackTrace(System.out);
    }
    return log2Filename;
}

From source file:gov.nih.nci.rembrandt.web.taglib.ClinicalPlotTag.java

public int doStartTag() {
    chart = null;//from w  w w.j a  v a  2 s.  c om
    clinicalData.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  Clinical Data points
        //ClinicalFinding clinicalFinding = (ClinicalFinding)businessTierCache.getSessionFinding(session.getId(),taskId);
        ReportBean clincalReportBean = presentationTierCache.getReportBean(session.getId(), taskId);
        Resultant clinicalResultant = clincalReportBean.getResultant();
        ResultsContainer resultsContainer = clinicalResultant.getResultsContainer();
        SampleViewResultsContainer sampleViewContainer = null;
        if (resultsContainer instanceof DimensionalViewContainer) {
            DimensionalViewContainer dimensionalViewContainer = (DimensionalViewContainer) resultsContainer;
            sampleViewContainer = dimensionalViewContainer.getSampleViewResultsContainer();
        }
        if (sampleViewContainer != null) {
            Collection<ClinicalFactorType> clinicalFactors = new ArrayList<ClinicalFactorType>();
            clinicalFactors.add(ClinicalFactorType.AgeAtDx);
            //clinicalFactors.add(ClinicalFactorType.Survival);
            Collection<SampleResultset> samples = sampleViewContainer.getSampleResultsets();

            if (samples != null) {
                int numDxvsKa = 0;
                int numDxvsSl = 0;
                for (SampleResultset rs : samples) {
                    //String id = rs.getBiospecimen().getValueObject();
                    String id = rs.getSampleIDDE().getValueObject();
                    ClinicalDataPoint clinicalDataPoint = new ClinicalDataPoint(id);

                    String diseaseName = rs.getDisease().getValueObject();
                    if (diseaseName != null) {
                        clinicalDataPoint.setDiseaseName(diseaseName);
                    } else {
                        clinicalDataPoint.setDiseaseName(DiseaseType.NON_TUMOR.name());
                    }

                    Long sl = rs.getSurvivalLength();
                    double survivalDays = -1.0;
                    double survivalMonths = -1.0;
                    if (sl != null) {
                        survivalDays = sl.doubleValue();
                        survivalMonths = survivalDays / 30.0;
                        //if ((survivalMonths > 0.0)&&(survivalMonths < 1000.0)) {
                        clinicalDataPoint.setSurvival(survivalDays);
                        //}
                    }

                    Long dxAge = rs.getAge();
                    if (dxAge != null) {
                        clinicalDataPoint.setAgeAtDx(dxAge.doubleValue());
                    }

                    KarnofskyClinicalEvalDE ka = rs.getKarnofskyClinicalEvalDE();
                    if (ka != null) {
                        String kaStr = ka.getValueObject();
                        if (kaStr != null) {
                            if (kaStr.contains("|")) {
                                kaStr = kaStr.trim();
                                String[] kaStrArray = kaStr.split("\\|");
                                for (int i = 0; i < kaStrArray.length; i++) {
                                    if (i == 0) {
                                        //first score is baseline just use this for now
                                        //later we will need to use all score in a series for each patient
                                        double kaVal = Double.parseDouble(kaStrArray[i].trim());
                                        clinicalDataPoint.setKarnofskyScore(kaVal);
                                    }
                                }
                            } else {
                                double kaVal = Double.parseDouble(kaStr);
                                clinicalDataPoint.setKarnofskyScore(kaVal);
                            }

                        }
                    }

                    if ((dxAge != null) && (ka != null)) {
                        numDxvsKa++;
                    }

                    if ((dxAge != null) && (sl != null)) {
                        numDxvsSl++;
                    }

                    //                        Object dx = rs.getAgeGroup();
                    //                            if(sl !=null && dx !=null){
                    //                                clinicalDataPoint.setSurvival(new Double(sl.toString()));
                    //                                clinicalDataPoint.setAgeAtDx(new Double(dx.toString()));
                    //                            }
                    //                        Object ks = rs.getKarnofskyClinicalEvalDE();
                    //                        Object dx = rs.getAgeGroup();
                    //                            if(ks !=null && dx !=null){
                    //                                clinicalDataPoint.setNeurologicalAssessment(new Double(ks.toString()));
                    //                                clinicalDataPoint.setAgeAtDx(new Double(dx.toString()));
                    //                            }

                    clinicalData.add(clinicalDataPoint);
                }
            }
        }

        System.out.println("Done creating points!");

        //-------------------------------------------------------------
        //GET THE CLINICAL DATA AND POPULATE THE clinicalData list
        //Note the ClinicalFinding is currently an empty class
        //----------------------------------------------------------

        //check the components to see which graph to get
        if (components.equalsIgnoreCase("SurvivalvsAgeAtDx")) {
            chart = (JFreeChart) CaIntegratorChartFactory.getClinicalGraph(clinicalData,
                    ClinicalFactorType.SurvivalLength, "Survival Length (Months)", ClinicalFactorType.AgeAtDx,
                    "Age At Diagnosis (Years)");
        }
        if (components.equalsIgnoreCase("KarnofskyScorevsAgeAtDx")) {
            chart = (JFreeChart) CaIntegratorChartFactory.getClinicalGraph(clinicalData,
                    ClinicalFactorType.KarnofskyAssessment, "Karnofsky Score", ClinicalFactorType.AgeAtDx,
                    "Age At Diagnosis (Years)");
        }

        RembrandtImageFileHandler imageHandler = new RembrandtImageFileHandler(session.getId(), "png", 600,
                500);
        //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();

        ChartUtilities.writeChartAsPNG(new FileOutputStream(finalPath), chart, 600, 500, info);

        /*   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("\\", "/");
        finalURLpath = finalURLpath.replace("\\", "/");
        long randomness = System.currentTimeMillis(); //prevent image caching
        out.print("<img id=\"geneChart\" alt=\"geneChart\" name=\"geneChart\" src=\"" + finalURLpath + "?"
                + randomness + "\" usemap=\"#" + mapName + "\" border=\"0\" />");

        //out.print("<img id=\"geneChart\" name=\"geneChart\" src=\""+finalURLpath+"\" usemap=\"#"+mapName + "\" border=\"0\" />");

    } 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.gephi.statistics.plugin.DegreeDistribution.java

/**
 *
 * @return The undirected version of this report.
 *//*  w ww .j a  v a 2 s  .c o m*/
private String getUndirectedReport() {
    double max = 0;
    XYSeries series2 = new XYSeries("Series 2");
    for (int i = 1; i < combinedDistribution[1].length; i++) {
        if (combinedDistribution[1][i] > 0) {
            series2.add((Math.log(combinedDistribution[0][i]) / Math.log(Math.E)),
                    (Math.log(combinedDistribution[1][i]) / Math.log(Math.E)));
            max = (float) Math.max((Math.log(combinedDistribution[0][i]) / Math.log(Math.E)), max);
        }
    }
    double a = combinedAlpha;
    double b = combinedBeta;

    XYSeries series1 = new XYSeries(combinedAlpha + " ");
    series1.add(0, a);
    series1.add(max, a + b * max);

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

    JFreeChart chart = ChartFactory.createXYLineChart("Degree Distribution", "Degree", "Occurrence", dataset,
            PlotOrientation.VERTICAL, true, false, false);
    XYPlot plot = (XYPlot) chart.getPlot();
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setSeriesLinesVisible(0, true);
    renderer.setSeriesShapesVisible(0, false);
    renderer.setSeriesLinesVisible(1, false);
    renderer.setSeriesShapesVisible(1, true);
    renderer.setSeriesShape(1, new java.awt.geom.Ellipse2D.Double(0, 0, 1, 1));
    plot.setBackgroundPaint(java.awt.Color.WHITE);
    plot.setDomainGridlinePaint(java.awt.Color.GRAY);
    plot.setRangeGridlinePaint(java.awt.Color.GRAY);

    plot.setRenderer(renderer);

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

    } catch (IOException e) {
        System.out.println(e.toString());
    }

    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>" + "Degree Power Law: -" + combinedAlpha + "\n <BR>"
            + imageFile + "</BODY> </HTML>";
    return report;
}

From source file:fr.paris.lutece.plugins.stock.modules.billetterie.web.StatisticJspBean.java

/**
 * write in the http response the statistic graph of all response submit who
 * verify the date filter.//from w  w  w . j  a va 2s .  co m
 *
 * @param request the http request
 * @param response The http response
 */
public void doGenerateGraph(HttpServletRequest request, HttpServletResponse response) {
    Locale locale = getLocale();
    String strFistResponseDateFilter = request.getParameter(PARAMETER_FIRST_RESPONSE_DATE_FILTER);
    String strLastResponseDateFilter = request.getParameter(PARAMETER_LAST_RESPONSE_DATE_FILTER);
    String strTimesUnit = request.getParameter(PARAMETER_TIMES_UNIT);
    String strTypeData = request.getParameter(PARAMETER_TYPE_DATA);

    List<ResultStatistic> listeResultStatistic = null;

    if (strTypeData.equals(CONSTANT_PRODUCT_TYPE)) {
        listeResultStatistic = _serviceStatistic.getProductStatistic(strTimesUnit, strFistResponseDateFilter,
                strLastResponseDateFilter);
    } else {
        listeResultStatistic = _serviceStatistic.getPurchaseStatistic(strTimesUnit, strFistResponseDateFilter,
                strLastResponseDateFilter);
    }

    String strNumberOfResponseAxisX = AppPropertiesService.getProperty(PROPERTY_NUMBER_RESPONSE_AXIS_X);
    int nNumberOfResponseAxisX = 10;

    try {
        nNumberOfResponseAxisX = Integer.parseInt(strNumberOfResponseAxisX);
    } catch (NumberFormatException ne) {
        AppLogService.error(ne);
    }

    List<ResultStatistic> listStatisticGraph = new ArrayList<ResultStatistic>();
    ResultStatistic statisticFormSubmit;

    if (listeResultStatistic.size() != 0) {
        for (int cpt = 0; cpt < nNumberOfResponseAxisX; cpt++) {
            statisticFormSubmit = new ResultStatistic();
            statisticFormSubmit.setNumberResponse(0);
            statisticFormSubmit.setStatisticDate(StatisticService
                    .addStatisticInterval(listeResultStatistic.get(0).getStatisticDate(), strTimesUnit, cpt));
            listStatisticGraph.add(statisticFormSubmit);
        }
    }

    for (ResultStatistic statisticFormSubmitGraph : listStatisticGraph) {
        for (ResultStatistic resultStatistic : listeResultStatistic) {
            if (StatisticService.sameDate(statisticFormSubmitGraph.getStatisticDate(),
                    resultStatistic.getStatisticDate(), strTimesUnit)) {
                statisticFormSubmitGraph.setNumberResponse(resultStatistic.getNumberResponse());
            }
        }
    }

    String strLabelAxisX = I18nService.getLocalizedString(PROPERTY_LABEL_AXIS_X, locale);
    String strLabelAxisY;

    if (strTypeData.equals(CONSTANT_PRODUCT_TYPE)) {
        strLabelAxisY = I18nService.getLocalizedString(PROPERTY_LABEL_AXIS_Y_PRODUCT, locale);
    } else {
        strLabelAxisY = I18nService.getLocalizedString(PROPERTY_LABEL_AXIS_Y_PURCHASE, locale);
    }

    try {
        JFreeChart chart = StatisticService.createXYGraph(listStatisticGraph, strLabelAxisX, strLabelAxisY,
                strTimesUnit);

        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        BufferedImage chartImage = chart.createBufferedImage(600, 200, info);
        response.setContentType(CONTENT_TYPE_IMAGE_PNG);

        PngEncoder encoder = new PngEncoder(chartImage, false, 0, 9);
        response.getOutputStream().write(encoder.pngEncode());
        response.getOutputStream().flush();
        response.getOutputStream().close();
    } catch (Exception e) {
        AppLogService.error(e);
    }
}

From source file:gov.nih.nci.cma.web.graphing.GEPlot.java

public String generateGeometricMeanIntensityChart(String xAxisLabel, String yAxisLabel, HttpSession session,
        PrintWriter pw) {//from  w  ww.  j  a v a 2 s  . c o m
    String gmfilename = "";

    JFreeChart gmChart = null;
    try {

        gmChart = ChartFactory.createBarChart(null, xAxisLabel, // domain axis label
                yAxisLabel, gmDataset, // data
                PlotOrientation.VERTICAL, // orientation
                true, // include legend
                true, // tooltips?
                false // URLs?
        );
        gmChart.setBackgroundPaint(java.awt.Color.white);
        // lets start some customization to retro fit w/jcharts lookand feel
        CategoryPlot plot = gmChart.getCategoryPlot();
        CategoryAxis axis = plot.getDomainAxis();
        axis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
        axis.setLowerMargin(0.02); // two percent
        axis.setCategoryMargin(0.20); // 20 percent
        axis.setUpperMargin(0.02); // two percent
        //StatisticalBarRenderer renderer = new StatisticalBarRenderer();
        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        // BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setItemMargin(0.01); // one percent
        renderer.setDrawBarOutline(true);
        renderer.setOutlinePaint(Color.BLACK);
        renderer.setBaseToolTipGenerator(new CategoryToolTipGenerator() {

            public String generateToolTip(CategoryDataset dataset, int series, int item) {
                String stdDev = (String) stdDevMap
                        .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item));

                return "Probeset : " + dataset.getRowKey(series) + "<br/>Intensity : "
                        + new DecimalFormat("0.0000").format(dataset.getValue(series, item)) + "<br/>"
                        + "<br/>Std. Dev.: " + stdDev + "<br/>";
            }

        });

        plot.setRenderer(renderer);

        gmChart.removeLegend();
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        //gmfilename = ServletUtilities.saveChartAsPNG(gmChart, imgW, 400, info, session);
        gmfilename = ServletUtilities.saveChartAsPNG(gmChart, imgW, 400, info, session);
        ChartUtilities.writeImageMap(pw, gmfilename, info, new CustomOverlibToolTipTagFragmentGenerator(),
                new StandardURLTagFragmentGenerator());

    } catch (Exception e) {
        System.out.println("Exception - " + e.toString());
        e.printStackTrace(System.out);
    }
    return gmfilename;
}