Example usage for org.jfree.chart ChartUtilities saveChartAsJPEG

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

Introduction

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

Prototype

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

Source Link

Document

Saves a chart to a file in JPEG format.

Usage

From source file:cachedataanalysis.FlowCache.java

public XYSeries exportReportChart() throws IOException {

    File outputHitRate = new File("report/" + name + "_" + policy + "_hitrate.txt");

    FileWriter fw = new FileWriter(outputHitRate);

    XYSeries hitRateCount = new XYSeries(name + "(" + size + " entries)");

    for (int i = 0; i < hitRateRecord.size(); i++) {
        hitRateCount.add(i, hitRateRecord.get(i));
        fw.write(i + "," + hitRateRecord.get(i) + "\n");
        fw.flush();/*from   ww  w. j a  va 2  s. c om*/
    }
    fw.close();

    XYSeriesCollection HitRateData = new XYSeriesCollection();
    HitRateData.addSeries(hitRateCount);
    JFreeChart hitRateStat = ChartFactory.createXYLineChart(
            "Hit Rate variatoion throughout recording in " + name, "Seconds", "HitRate", HitRateData,
            PlotOrientation.VERTICAL, true, true, false);

    ChartUtilities.saveChartAsJPEG(new File("report/" + name + "_hitRate" + size + ".jpg"), hitRateStat, 1500,
            900);

    //-------------------------------

    if (!fullReport) {
        return hitRateCount;
    }

    DefaultPieDataset hitProtoData = new DefaultPieDataset();
    DefaultPieDataset missProtoData = new DefaultPieDataset();

    CategoryTableXYDataset hitProtoDataRec = new CategoryTableXYDataset();
    for (int i = 0; i < hitProtoRec.size(); i++) {
        if (i % 120 != 0) {
            continue;
        }
        HashMap<String, Integer> _map = hitProtoRec.get(i);
        for (String _str : _map.keySet()) {
            hitProtoDataRec.add(i, _map.get(_str), _str);
        }

    }

    CategoryTableXYDataset missProtoDataRec = new CategoryTableXYDataset();
    for (int i = 0; i < missProtoRec.size(); i++) {
        if (i % 120 != 0) {
            continue;
        }
        HashMap<String, Integer> _map = missProtoRec.get(i);
        for (String _str : _map.keySet()) {
            missProtoDataRec.add(i, _map.get(_str), _str);
        }

    }

    XYSeries hitCountData = new XYSeries("Hit");
    XYSeries allCountData = new XYSeries("All");

    for (int i = 0; i < hitCount.size(); i++) {
        hitCountData.add(i, hitCount.get(i));
        //hitRateCount.add(i,(float)hitCount.get(i)/(hitCount.get(i)+allCount.get(i)));
    }

    for (int i = 0; i < allCount.size(); i++) {
        allCountData.add(i, allCount.get(i));

    }

    XYSeriesCollection CountStatData = new XYSeriesCollection();

    CountStatData.addSeries(hitCountData);
    CountStatData.addSeries(allCountData);

    for (String protocol : hitProto.keySet()) {
        hitProtoData.setValue(protocol, hitProto.get(protocol));
    }

    for (String protocol : missProto.keySet()) {
        missProtoData.setValue(protocol, missProto.get(protocol));
    }

    JFreeChart hitStatRec = ChartFactory.createStackedXYAreaChart(
            "Hit Protocol Fraction throughout record in " + name, "Seconds", "Count", hitProtoDataRec);

    JFreeChart missStatRec = ChartFactory.createStackedXYAreaChart(
            "Miss Protocol Fraction throughout record in " + name, "Seconds", "Count", missProtoDataRec);

    JFreeChart hitStat = ChartFactory.createPieChart3D("Protocal Fraction of Hit Flows in " + name,
            hitProtoData, true, true, false);
    JFreeChart missStat = ChartFactory.createPieChart3D("Protocal Fraction of Miss Flows in " + name,
            missProtoData, true, true, false);
    JFreeChart countStat = ChartFactory.createXYAreaChart("Hit Count to All Packet lookup in " + name,
            "Seconds", "Count", CountStatData, PlotOrientation.VERTICAL, true, true, false);

    ChartUtilities.saveChartAsJPEG(new File("report/" + name + "_hitProto" + size + ".jpg"), hitStat, 1500,
            900);
    ChartUtilities.saveChartAsJPEG(new File("report/" + name + "_missProto" + size + ".jpg"), missStat, 1500,
            900);
    ChartUtilities.saveChartAsJPEG(new File("report/" + name + "_hitCount" + size + ".jpg"), countStat, 1500,
            900);

    ChartUtilities.saveChartAsJPEG(new File("report/" + name + "_hitProtoRecord" + size + ".jpg"), hitStatRec,
            1500, 900);
    ChartUtilities.saveChartAsJPEG(new File("report/" + name + "_missProtoRecord" + size + ".jpg"), missStatRec,
            1500, 900);

    return hitRateCount;
}

From source file:it.marcoberri.mbmeteo.action.chart.GetMinOrMax.java

/**
 *
 * @param request//from   w  ww  .  j  a  v a 2  s  . co  m
 * @param response
 * @throws ServletException
 * @throws IOException
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);
    final String from = Default.toString(params.get("from") + " 00:00:00", "1970-01-01 00:00:00");
    final String to = Default.toString(params.get("to") + " 23:59:00", "2030-01-01 23:59:00");
    final String field = Default.toString(params.get("field"), "outdoorTemperature");
    final String period = Default.toString(params.get("period"), "day");
    final String type = Default.toString(params.get("type"), "min");

    request.getSession().setAttribute("from", params.get("from"));
    request.getSession().setAttribute("to", params.get("to"));

    final String cacheKey = getCacheKey(params);

    if (cacheReadEnable) {

        final Query q = ds.find(Cache.class);
        q.filter("cacheKey", cacheKey).filter("servletName", this.getClass().getName());

        final Cache c = (Cache) q.get();

        if (c == null) {
            log.info("cacheKey:" + cacheKey + " on servletName: " + this.getClass().getName() + " not found");
        }

        if (c != null) {
            final GridFSDBFile imageForOutput = MongoConnectionHelper.getGridFS()
                    .findOne(new ObjectId(c.getGridId()));
            if (imageForOutput != null) {
                ds.save(c);

                try {
                    response.setHeader("Content-Length", "" + imageForOutput.getLength());
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + imageForOutput.getFilename() + "\"");
                    final OutputStream out = response.getOutputStream();
                    final InputStream in = imageForOutput.getInputStream();
                    final byte[] content = new byte[(int) imageForOutput.getLength()];
                    in.read(content);
                    out.write(content);
                    in.close();
                    out.close();
                    return;
                } catch (Exception e) {
                    log.error(e);
                }

            } else {
                log.error("file not in db");
            }
        }
    }

    final Query q = ds.createQuery(MapReduceMinMax.class).disableValidation();
    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    final String formatIn = getFormatIn(period);
    final String formatOut = getFormatOut(period);

    final List<Date> datesIn = getRangeDate(dFrom, dTo);
    final HashSet<String> datesInString = new HashSet<String>();

    for (Date d : datesIn) {
        datesInString.add(DateTimeUtil.dateFormat(formatIn, d));
    }

    if (datesIn != null && !datesIn.isEmpty()) {
        q.filter("_id in", datesInString);
    }
    q.order("_id");

    final List<MapReduceMinMax> mapReduceResult = q.asList();

    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    ChartEnumMinMaxHelper chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, type);

    for (MapReduceMinMax m : mapReduceResult) {
        try {
            final Date tmpDate = DateTimeUtil.getDate(formatIn, m.getId().toString());

            if (tmpDate == null) {
                continue;
            }

            final Method method = m.getClass().getMethod(chartEnum.getMethod());
            final Number n = (Number) method.invoke(m);
            dataset.addValue(n, chartEnum.getType(), DateTimeUtil.dateFormat(formatOut, tmpDate));

        } catch (IllegalAccessException ex) {
            log.error(ex);
        } catch (IllegalArgumentException ex) {
            log.error(ex);
        } catch (InvocationTargetException ex) {
            log.error(ex);
        } catch (NoSuchMethodException ex) {
            log.error(ex);
        } catch (SecurityException ex) {
            log.error(ex);
        }
    }

    final JFreeChart chart = ChartFactory.createBarChart(chartEnum.getTitle(), // chart title
            "", // domain axis label
            chartEnum.getUm(), // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            true, // tooltips?
            false // URLs?
    );

    final CategoryPlot xyPlot = (CategoryPlot) chart.getPlot();
    final CategoryAxis domain = xyPlot.getDomainAxis();

    if (field.toUpperCase().indexOf("PRESSURE") != -1) {
        xyPlot.getRangeAxis().setRange(chartPressureMin, chartPressureMax);
    } else {
        xyPlot.getRangeAxis().setAutoRange(true);
    }

    domain.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    try {

        if (cacheWriteEnable) {
            final GridFSInputFile gfsFile = MongoConnectionHelper.getGridFS().createFile(f);
            gfsFile.setFilename(f.getName());
            gfsFile.save();

            final Cache c = new Cache();
            c.setServletName(this.getClass().getName());
            c.setCacheKey(cacheKey);
            c.setGridId(gfsFile.getId().toString());

            ds.save(c);

        }

        response.setContentType("image/jpeg");
        response.setHeader("Content-Length", "" + f.length());
        response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
        final OutputStream out = response.getOutputStream();
        final FileInputStream in = new FileInputStream(f.toString());
        final int size = in.available();
        final byte[] content = new byte[size];
        in.read(content);
        out.write(content);
        in.close();
        out.close();
    } catch (Exception e) {
        log.error(e);
    } finally {
        boolean delete = f.delete();
    }

}

From source file:com.bt.aloha.batchtest.Chart.java

public void saveChart(File file, String title, String xLabel, String yLabel) {
    try {//from ww w .  j av  a 2  s  .  co m
        ChartUtilities.saveChartAsJPEG(file, createChart(title, xLabel, yLabel), 1024, 768);
    } catch (IOException e) {
        log.warn("UNABLE to store chart");
    }
}

From source file:it.marcoberri.mbmeteo.action.chart.GetMinAndMax.java

/**
 * Processes requests for both HTTP/*from  www.  ja v a 2  s .  c o  m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final HashMap<String, String> params = getParams(request.getParameterMap());
    final Integer dimy = Default.toInteger(params.get("dimy"), 600);
    final Integer dimx = Default.toInteger(params.get("dimx"), 800);
    final String from = Default.toString(params.get("from") + " 00:00:00", "1970-01-01 00:00:00");
    final String to = Default.toString(params.get("to") + " 23:59:00", "2030-01-01 23:59:00");
    final String field = Default.toString(params.get("field"), "outdoorTemperature");
    final String period = Default.toString(params.get("period"), "day");

    request.getSession().setAttribute("from", params.get("from"));
    request.getSession().setAttribute("to", params.get("to"));

    final String cacheKey = getCacheKey(params);

    if (cacheReadEnable) {

        final Query q = ds.find(Cache.class);
        q.filter("cacheKey", cacheKey).filter("servletName", this.getClass().getName());

        final Cache c = (Cache) q.get();

        if (c == null) {
            log.info("cacheKey:" + cacheKey + " on servletName: " + this.getClass().getName() + " not found");
        }

        if (c != null) {
            final GridFSDBFile imageForOutput = MongoConnectionHelper.getGridFS()
                    .findOne(new ObjectId(c.getGridId()));
            if (imageForOutput != null) {
                ds.save(c);

                try {
                    response.setHeader("Content-Length", "" + imageForOutput.getLength());
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + imageForOutput.getFilename() + "\"");
                    final OutputStream out = response.getOutputStream();
                    final InputStream in = imageForOutput.getInputStream();
                    final byte[] content = new byte[(int) imageForOutput.getLength()];
                    in.read(content);
                    out.write(content);
                    in.close();
                    out.close();
                    return;
                } catch (Exception e) {
                    log.error(e);
                }

            } else {
                log.error("file not in db");
            }
        }
    }

    final String formatIn = getFormatIn(period);
    final String formatOut = getFormatOut(period);

    final Query q = ds.createQuery(MapReduceMinMax.class).disableValidation();

    final Date dFrom = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", from);
    final Date dTo = DateTimeUtil.getDate("yyyy-MM-dd hh:mm:ss", to);

    final List<Date> datesIn = getRangeDate(dFrom, dTo);
    final HashSet<String> datesInString = new HashSet<String>();

    for (Date d : datesIn) {
        datesInString.add(DateTimeUtil.dateFormat(formatIn, d));
    }

    if (datesIn != null && !datesIn.isEmpty()) {
        q.filter("_id in", datesInString);
    }
    q.order("_id");

    final List<MapReduceMinMax> mapReduceResult = q.asList();
    final TimeSeries serieMin = new TimeSeries("Min");
    final TimeSeries serieMax = new TimeSeries("Max");

    for (MapReduceMinMax m : mapReduceResult) {
        try {

            final Date tmpDate = DateTimeUtil.getDate(formatIn, m.getId().toString());
            if (tmpDate == null) {
                continue;
            }

            final Millisecond t = new Millisecond(tmpDate);

            ChartEnumMinMaxHelper chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, "min");
            Method method = m.getClass().getMethod(chartEnum.getMethod());
            Number n = (Number) method.invoke(m);
            serieMin.add(t, n);

            chartEnum = ChartEnumMinMaxHelper.getByFieldAndType(field, "max");
            method = m.getClass().getMethod(chartEnum.getMethod());
            n = (Number) method.invoke(m);
            serieMax.add(t, n);

        } catch (IllegalAccessException ex) {
            log.error(ex);
        } catch (IllegalArgumentException ex) {
            log.error(ex);
        } catch (InvocationTargetException ex) {
            log.error(ex);
        } catch (NoSuchMethodException ex) {
            log.error(ex);
        } catch (SecurityException ex) {
            log.error(ex);
        }
    }

    final ChartEnumMinMaxHelper chartData = ChartEnumMinMaxHelper.getByFieldAndType(field, "min");

    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(serieMin);
    dataset.addSeries(serieMax);

    final JFreeChart chart = ChartFactory.createTimeSeriesChart("Max/Min", "", chartData.getUm(), dataset, true,
            false, false);
    final XYPlot plot = (XYPlot) chart.getPlot();
    final DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat(formatOut));

    axis.setVerticalTickLabels(true);

    if (field.toUpperCase().indexOf("PRESSURE") != -1) {
        plot.getRangeAxis().setRange(chartPressureMin, chartPressureMax);
    }

    final File f = File.createTempFile("mbmeteo", ".jpg");
    ChartUtilities.saveChartAsJPEG(f, chart, dimx, dimy);

    try {

        if (cacheWriteEnable) {
            final GridFSInputFile gfsFile = MongoConnectionHelper.getGridFS().createFile(f);
            gfsFile.setFilename(f.getName());
            gfsFile.save();

            final Cache c = new Cache();
            c.setServletName(this.getClass().getName());
            c.setCacheKey(cacheKey);
            c.setGridId(gfsFile.getId().toString());

            ds.save(c);

        }

        response.setContentType("image/jpeg");
        response.setHeader("Content-Length", "" + f.length());
        response.setHeader("Content-Disposition", "inline; filename=\"" + f.getName() + "\"");
        final OutputStream out = response.getOutputStream();
        final FileInputStream in = new FileInputStream(f.toString());
        final int size = in.available();
        final byte[] content = new byte[size];
        in.read(content);
        out.write(content);
        in.close();
        out.close();
    } catch (Exception e) {
        log.error(e);
    } finally {
        f.delete();
    }

}

From source file:com.bt.aloha.batchtest.Chart.java

public void saveCombinedChart(File file, String title1, String labelX1, String labelY1, String title2,
        String labelX2, String labelY2) {
    try {// www . j ava  2 s. c o  m
        ChartUtilities.saveChartAsJPEG(file,
                createCombinedChart(title1, labelX1, labelY1, title2, labelX2, labelY2), 1024, 768);
    } catch (IOException e) {
        log.warn("UNABLE to store chart");
    }
}

From source file:ro.nextreports.engine.chart.JFreeChartExporter.java

private void createImage() throws QueryException {
    byte type = chart.getType().getType();
    JFreeChart jfreechart = null;// www. j  a va  2 s .c  o  m
    if (ChartType.LINE == type) {
        jfreechart = createLineChart();
    } else if (ChartType.BAR == type) {
        jfreechart = createBarChart(false, false);
    } else if (ChartType.BAR_COMBO == type) {
        jfreechart = createBarChart(false, false, true);
    } else if (ChartType.HORIZONTAL_BAR == type) {
        jfreechart = createBarChart(true, false);
    } else if (ChartType.STACKED_BAR == type) {
        jfreechart = createBarChart(false, true);
    } else if (ChartType.STACKED_BAR_COMBO == type) {
        jfreechart = createBarChart(false, true, true);
    } else if (ChartType.HORIZONTAL_STACKED_BAR == type) {
        jfreechart = createBarChart(true, true);
    } else if (ChartType.PIE == type) {
        jfreechart = createPieChart();
    } else if (ChartType.BUBBLE == type) {
        jfreechart = createBubbleChart();
    } else if (ChartType.AREA == type) {
        jfreechart = createAreaChart();
    }
    try {
        if ((chartImageName == null) || "".equals(chartImageName.trim())) {
            chartImageName = "chart_" + System.currentTimeMillis() + ".jpg";
        }
        ChartUtilities.saveChartAsJPEG(new File(path + File.separator + chartImageName), jfreechart, width,
                height);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }
}

From source file:rev.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w w  w  .  j  av  a 2 s . c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, SQLException, ClassNotFoundException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        String a = request.getParameter("userMsg");

        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE HTML>\n" + "<head>\n"
                + "<link href=\"css/style.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\"/>\n"
                + "<link href=\"css/slider.css\" rel=\"stylesheet\" type=\"text/css\" media=\"all\"/>\n"
                + "<script type=\"text/javascript\" src=\"js/jquery-1.9.0.min.js\"></script>\n"
                + "<script type=\"text/javascript\" src=\"js/move-top.js\"></script>\n"
                + "<script type=\"text/javascript\" src=\"js/easing.js\"></script>\n"
                + "<script type=\"text/javascript\" src=\"js/jquery.nivo.slider.js\"></script>\n"
                + "<script type=\"text/javascript\">\n" + "    $(window).load(function() {\n"
                + "        $('#slider').nivoSlider();\n" + "    });\n" + "    <%! String n;\n" + "    %>\n"
                + "    <%  \n" + "          \n" + "        n=(String)session.getAttribute(\"uname\"); \n"
                + "        %>\n" + "    </script>\n" + "</head>\n" + "<body>\n" + "   <div class=\"header\">\n"
                + "       <div class=\"headertop_desc\">\n" + "         <div class=\"wrap\">\n"
                + "            <div class=\"nav_list\">\n" + "               \n" + "            </div>\n"
                + "            <div class=\"account_desc\">\n" + "                  <ul>\n"
                + "                     <li><a href=\"available.jsp\">Available movies</a></li>\n"
                + "                     <li><a href=\"takereview.jsp\">Review Movies</a></li>\n"
                + "                     <li><a href=\"rated.jsp\">Movies Rated</a></li>\n"
                + "                                                        <li><a href=\"abc.jsp\">Recommend Me</a></li>\n"
                + "                                                        \n"
                + "                                                        <li><a href=\"contact.html\">Contact</a></li>\n"
                + "                                                        <li><a href=\"logout\">Logout</a></li>\n"
                + "                                                </ul>\n" + "               </div>\n"
                + "            <div class=\"clear\"></div>\n" + "         </div>\n" + "        </div>\n"
                + "             <div class=\"wrap\">\n" + "            <div class=\"header_top\">\n"
                + "               <div class=\"logo\">\n"
                + "                  <a href=\"index.html\"><img src=\"images/logo1.jpg\" alt=\"\" /></a>\n"
                + "               </div>\n" + "               <div class=\"header_top_right\">\n"
                + "                <div class=\"search_box\">\n" + "                          \n"
                + "                       </div>\n" + "                    <div class=\"clear\"></div>\n"
                + "               </div>\n" + "                   \n"
                + "          <div class=\"clear\"></div>\n" + "        </div>\n" + "            \n" + "   \n"
                + "\n" + "\n" + "");

        String line = "this book is too good to sleep";
        Properties props = new Properties();
        props.setProperty("annotators", "tokenize, ssplit, parse, sentiment, lemma");
        StanfordCoreNLP pipeline = new StanfordCoreNLP(props);

        Annotation annotation = new Annotation(a);

        pipeline.annotate(annotation);

        annotation.toShorterString();

        List<CoreMap> sentences = annotation.get(CoreAnnotations.SentencesAnnotation.class);

        if (sentences != null && !sentences.isEmpty()) {
            for (int i = 0; i < sentences.size(); i++) {
                CoreMap sentence = sentences.get(i);
                Tree tree = sentence.get(SentimentCoreAnnotations.SentimentAnnotatedTree.class);
                int sentiment = RNNCoreAnnotations.getPredictedClass(tree);
                String sentimentName = sentence.get(SentimentCoreAnnotations.SentimentClass.class);
                //Class.forName("com.mysql.jdbc.Driver");

                /*String connectionURL = "jdbc:mysql://localhost:3306/review";
                       Connection conn;
                        Statement stmt;
                        ResultSet rs;
                      conn = DriverManager.getConnection (connectionURL,"root","");
                       stmt = conn.createStatement();
                      // rs = stmt.executeQuery("");
                      out.println();
                         
                        
                */

                out.println("The sentence is:");
                sentence.get(CoreAnnotations.TextAnnotation.class);

                //out.println("Sentiment of \n> \""++"\"\nis: " + sentiment+" (i.e., "+sentimentName+")");
                out.println(sentimentName + " " + sentiment);
                if (sentimentName.equalsIgnoreCase("Negative")) {
                    final String negative = "negative";
                    final String positive = "positive";

                    final String nuetral = "nuetral";
                    final String verypositive = "very positive";
                    final String verynegative = " very negative";
                    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

                    //out.println("NOT");
                    dataset.addValue(0, positive, positive);
                    dataset.addValue(sentiment, negative, negative);
                    dataset.addValue(0, nuetral, nuetral);
                    dataset.addValue(0, verynegative, verynegative);
                    dataset.addValue(0, verypositive, verypositive);
                    JFreeChart barChart = ChartFactory.createBarChart("Movie Reviews", "Ratings", "Sentiments",
                            dataset, PlotOrientation.VERTICAL, true, true, false);

                    int width = 640; /* Width of the image */
                    int height = 480; /* Height of the image */
                    File BarChart = new File("/home/rishabh/NetBeansProjects/minor/web/images/k.jpeg");
                    ChartUtilities.saveChartAsJPEG(BarChart, barChart, width, height);
                    out.println("<img src=\"images/BarChart.jpeg\">");

                } else if (sentimentName.equalsIgnoreCase("Positive")) {
                    final String negative = "negative";
                    final String positive = "positive";

                    final String nuetral = "nuetral";
                    final String verypositive = "very positive";
                    final String verynegative = " very negative";
                    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

                    // out.println("Good");
                    dataset.addValue(sentiment, positive, positive);
                    dataset.addValue(0, negative, negative);
                    dataset.addValue(0, nuetral, nuetral);
                    dataset.addValue(0, verynegative, verynegative);
                    dataset.addValue(0, verypositive, verypositive);
                    JFreeChart barChart = ChartFactory.createBarChart("Movie Reviews", "Ratings", "Sentiments",
                            dataset, PlotOrientation.VERTICAL, true, true, false);

                    int width = 640; /* Width of the image */
                    int height = 480; /* Height of the image */
                    File BarChart = new File("/home/rishabh/NetBeansProjects/minor/web/images/k.jpeg");
                    ChartUtilities.saveChartAsJPEG(BarChart, barChart, width, height);
                    out.println("<img src=\"images/BarChart1.jpeg\">");

                } else if (sentimentName.equalsIgnoreCase("Neutral")) {
                    final String negative = "negative";
                    final String positive = "positive";

                    final String nuetral = "nuetral";
                    final String verypositive = "very positive";
                    final String verynegative = " very negative";
                    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

                    //out.println("Good");
                    dataset.addValue(0, positive, positive);
                    dataset.addValue(0, negative, negative);
                    dataset.addValue(sentiment, nuetral, nuetral);
                    dataset.addValue(0, verynegative, verynegative);
                    dataset.addValue(0, verypositive, verypositive);
                    JFreeChart barChart = ChartFactory.createBarChart("Movie Reviews", "Ratings", "Sentiments",
                            dataset, PlotOrientation.VERTICAL, true, true, false);

                    int width = 640; /* Width of the image */
                    int height = 480; /* Height of the image */
                    File BarChart = new File("/home/rishabh/NetBeansProjects/minor/web/images/k.jpeg");
                    ChartUtilities.saveChartAsJPEG(BarChart, barChart, width, height);

                    out.println("<img src=\"images/BarChart2.jpeg\">");
                } else if (sentimentName.equalsIgnoreCase("Very Positive")) {
                    final String negative = "negative";
                    final String positive = "positive";

                    final String nuetral = "nuetral";
                    final String verypositive = "very positive";
                    final String verynegative = " very negative";
                    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

                    //out.println("Good");
                    dataset.addValue(0, positive, positive);
                    dataset.addValue(0, negative, negative);
                    dataset.addValue(0, nuetral, nuetral);
                    dataset.addValue(0, verynegative, verynegative);
                    dataset.addValue(sentiment, verypositive, verypositive);
                    JFreeChart barChart = ChartFactory.createBarChart("Movie Reviews", "Ratings", "Sentiments",
                            dataset, PlotOrientation.VERTICAL, true, true, false);

                    int width = 640; /* Width of the image */
                    int height = 480; /* Height of the image */
                    File BarChart = new File("/home/rishabh/NetBeansProjects/minor/web/images/k.jpeg");
                    ChartUtilities.saveChartAsJPEG(BarChart, barChart, width, height);
                    out.println("<img src=\"images/BarChart4.jpeg\">");

                } else if (sentimentName.equalsIgnoreCase("Very Negative")) {
                    final String negative = "negative";
                    final String positive = "positive";

                    final String nuetral = "nuetral";
                    final String verypositive = "very positive";
                    final String verynegative = " very negative";
                    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

                    //out.println("Good");
                    dataset.addValue(0, positive, positive);
                    dataset.addValue(0, negative, negative);
                    dataset.addValue(0, nuetral, nuetral);
                    dataset.addValue(sentiment, verynegative, verynegative);
                    dataset.addValue(0, verypositive, verypositive);
                    JFreeChart barChart = ChartFactory.createBarChart("Movie Reviews", "Ratings", "Sentiments",
                            dataset, PlotOrientation.VERTICAL, true, true, false);

                    int width = 640; /* Width of the image */
                    int height = 480; /* Height of the image */
                    File BarChart = new File("/home/rishabh/NetBeansProjects/minor/web/images/k.jpeg");
                    ChartUtilities.saveChartAsJPEG(BarChart, barChart, width, height);

                    out.println("<img src=\"images/BarChart3.jpeg\">");
                }

            }
        }

        out.println("<div class=\"footer\">\n" + "        <div class=\"wrap\">\n"
                + "        <div class=\"section group\">\n" + "            <div class=\"col span\">\n"
                + "                  <h4>Information</h4>\n" + "                  <ul>\n"
                + "                  <li><a href=\"#\">About Us</a></li>\n" + "                  \n"
                + "                  <li><a href=\"contact.html\">Contact Us</a></li>\n"
                + "                  </ul>\n" + "               </div>\n"
                + "            <div class=\"col span\">\n" + "               <h4>Know us better</h4>\n"
                + "                  <ul>\n" + "                  <li><a href=\"#\">About Us</a></li>\n"
                + "            \n" + "                  <li><a href=\"contact.html\">Site Map</a></li>\n"
                + "                  <li><a href=\"#\">Search Terms</a></li>\n" + "                  </ul>\n"
                + "            </div>\n" + "            \n" + "            <div class=\"col span\">\n"
                + "               <h4>Contact</h4>\n" + "                  <ul>\n"
                + "                     <li><span>9971825755</span></li>\n"
                + "                     <li><span>8130527232</span></li>\n" + "                  </ul>\n"
                + "                  <div class=\"social-icons\">\n"
                + "                     <h4>Follow Us</h4>\n" + "                          <ul>\n"
                + "                           <li><a href=\"#\" target=\"_blank\"><img src=\"images/facebook.png\" alt=\"\" /></a></li>\n"
                + "                           <li><a href=\"#\" target=\"_blank\"><img src=\"images/twitter.png\" alt=\"\" /></a></li>\n"
                + "                           <li><a href=\"#\" target=\"_blank\"><img src=\"images/skype.png\" alt=\"\" /> </a></li>\n"
                + "                           <li><a href=\"#\" target=\"_blank\"> <img src=\"images/linkedin.png\" alt=\"\" /></a></li>\n"
                + "                           <div class=\"clear\"></div>\n" + "                       </ul>\n"
                + "                      </div>\n" + "            </div>\n" + "         </div>\n"
                + "          <div class=\"copy_right\">\n"
                + "            <p>Company Name  All rights Reseverd </p>\n" + "         </div>\n"
                + "        </div>\n" + "    </div>\n" + "    <script type=\"text/javascript\">\n"
                + "      $(document).ready(function() {\n"
                + "         $().UItoTop({ easingType: 'easeOutQuart' });\n" + "\n" + "      });\n"
                + "   </script>\n" + "    <a href=\"#\" id=\"toTop\"><span id=\"toTopHover\"> </span></a>\n"
                + "</body>\n" + "</html>\n" + "\n" + "");

    }
}

From source file:com.itemanalysis.jmetrik.swing.GraphPanel.java

public void saveAsJPEG(File f) throws IOException {
    ChartUtilities.saveChartAsJPEG(f, chart, width, height);
}

From source file:Util.PacketGenerator.java

public static void GenerateGraph() {
    try {/*from w  w w . j a va  2 s.  c  o  m*/
        for (int j = 6; j <= 6; j++) {
            File real = new File("D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology"
                    + j + "\\Real.csv");
            for (int k = 1; k <= 4; k++) {
                File simu = new File(
                        "D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology" + j
                                + "\\SimulacaoInstancia" + k + ".csv");

                FileInputStream simuFIS = new FileInputStream(simu);
                DataInputStream simuDIS = new DataInputStream(simuFIS);
                BufferedReader simuBR = new BufferedReader(new InputStreamReader(simuDIS));

                FileInputStream realFIS = new FileInputStream(real);
                DataInputStream realDIS = new DataInputStream(realFIS);
                BufferedReader realBR = new BufferedReader(new InputStreamReader(realDIS));

                String lineSimu = simuBR.readLine();
                String lineReal = realBR.readLine();

                XYSeries matrix = new XYSeries("Matriz", false, true);
                while (lineSimu != null && lineReal != null) {

                    lineSimu = lineSimu.replaceAll(",", ".");
                    String[] simuMatriz = lineSimu.split(";");
                    String[] realMatriz = lineReal.split(";");

                    for (int i = 0; i < simuMatriz.length; i++) {
                        try {
                            Integer valorReal = Integer.parseInt(realMatriz[i]);
                            Float valorSimu = Float.parseFloat(simuMatriz[i]);
                            matrix.add(valorReal.doubleValue() / 1000.0, valorSimu.doubleValue() / 1000.0);
                        } catch (NumberFormatException ex) {

                        }
                    }
                    lineSimu = simuBR.readLine();
                    lineReal = realBR.readLine();
                }

                simuFIS.close();
                simuDIS.close();
                simuBR.close();

                realFIS.close();
                realDIS.close();
                realBR.close();

                double maxPlot = Double.max(matrix.getMaxX(), matrix.getMaxY()) * 1.1;
                XYSeries middle = new XYSeries("Referncia");
                ;
                middle.add(0, 0);
                middle.add(maxPlot, maxPlot);
                XYSeries max = new XYSeries("Superior 20%");
                max.add(0, 0);
                max.add(maxPlot, maxPlot * 1.2);
                XYSeries min = new XYSeries("Inferior 20%");
                min.add(0, 0);
                min.add(maxPlot, maxPlot * 0.8);

                XYSeriesCollection dataset = new XYSeriesCollection();
                dataset.addSeries(middle);
                dataset.addSeries(matrix);
                dataset.addSeries(max);
                dataset.addSeries(min);
                JFreeChart chart;
                if (k == 4) {
                    chart = ChartFactory.createXYLineChart("Matriz de Trfego", "Real", "CMO-MT", dataset);
                } else {
                    chart = ChartFactory.createXYLineChart("Matriz de Trfego", "CMO-MT", "Zhao", dataset);
                }
                chart.setBackgroundPaint(Color.WHITE);
                chart.getPlot().setBackgroundPaint(Color.WHITE);
                chart.getTitle().setFont(new Font("Times New Roman", Font.BOLD, 13));

                chart.getLegend().setItemFont(new Font("Times New Roman", Font.TRUETYPE_FONT, 10));

                chart.getXYPlot().getDomainAxis().setLabelFont(new Font("Times New Roman", Font.BOLD, 10));
                chart.getXYPlot().getDomainAxis()
                        .setTickLabelFont(new Font("Times New Roman", Font.TRUETYPE_FONT, 1));
                chart.getXYPlot().getRangeAxis().setLabelFont(new Font("Times New Roman", Font.BOLD, 10));
                chart.getXYPlot().getRangeAxis()
                        .setTickLabelFont(new Font("Times New Roman", Font.TRUETYPE_FONT, 1));

                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();

                renderer.setSeriesLinesVisible(1, false);
                renderer.setSeriesShapesVisible(1, true);

                renderer.setSeriesStroke(0, new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                        10.0f, new float[] { 0.1f }, 0.0f));
                renderer.setSeriesShape(1, new Ellipse2D.Float(-1.5f, -1.5f, 3f, 3f));
                renderer.setSeriesStroke(2, new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                        10.0f, new float[] { 3.0f }, 0.0f));
                renderer.setSeriesStroke(3, new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
                        10.0f, new float[] { 3.0f }, 0.0f));

                renderer.setSeriesPaint(0, Color.BLACK);
                renderer.setSeriesPaint(1, Color.BLACK);
                renderer.setSeriesPaint(2, Color.BLACK);
                renderer.setSeriesPaint(3, Color.BLACK);

                int width = (int) (192 * 1.5f); /* Width of the image */

                int height = (int) (144 * 1.5f); /* Height of the image */

                File XYChart = new File(
                        "D:\\Mestrado\\SketchMatrix\\trunk\\Simulations\\Analise\\Scenario1\\Topology" + j
                                + "\\SimulacaoInstancia" + k + ".jpeg");
                ChartUtilities.saveChartAsJPEG(XYChart, chart, width, height);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}