Example usage for java.io PrintWriter close

List of usage examples for java.io PrintWriter close

Introduction

In this page you can find the example usage for java.io PrintWriter close.

Prototype

public void close() 

Source Link

Document

Closes the stream and releases any system resources associated with it.

Usage

From source file:ca.mcgill.networkdynamics.geoinference.evaluation.CrossValidationScorer.java

public static void main(String[] args) throws Exception {

    if (args.length != 4) {
        System.out.println("java CVS predictions-dir/ " + "cv-gold-dir/ results.txt error-sample.tsv");
        return;/*from   w w  w.  ja v  a 2  s .  c o  m*/
    }

    File predDir = new File(args[0]);
    File cvDir = new File(args[1]);

    TDoubleList errors = new TDoubleArrayList(10_000_000);
    TLongSet locatedUsers = new TLongHashSet(10_000_000);
    TLongSet allUsers = new TLongHashSet(10_000_000);
    TLongObjectMap<TDoubleList> userToErrors = new TLongObjectHashMap<TDoubleList>();

    TLongDoubleMap tweetIdToError = new TLongDoubleHashMap(10_000_000);
    TLongObjectMap<double[]> idToPredLoc = new TLongObjectHashMap<double[]>();

    int tweetsSeen = 0;
    int tweetsLocated = 0;

    BufferedReader cvBr = new BufferedReader(new FileReader(new File(cvDir, "folds.info.tsv")));
    for (String foldLine = null; (foldLine = cvBr.readLine()) != null;) {
        String[] cols = foldLine.split("\t");
        String foldName = cols[0];

        System.out.printf("Scoring results for fold %s%n", foldName);

        File foldPredictionsFile = new File(predDir, foldName + ".results.tsv.gz");

        File goldLocFile = new File(cvDir, foldName + ".gold-locations.tsv");

        if (foldPredictionsFile.exists()) {
            BufferedReader br = Files.openGz(foldPredictionsFile);
            for (String line = null; (line = br.readLine()) != null;) {
                String[] arr = line.split("\t");
                long id = Long.parseLong(arr[0]);
                idToPredLoc.put(id, new double[] { Double.parseDouble(arr[1]), Double.parseDouble(arr[2]) });
            }
            br.close();
        }

        System.out.printf("loaded predictions for %d tweets; " + "scoring predictions%n", idToPredLoc.size());

        BufferedReader br = new BufferedReader(new FileReader(goldLocFile));
        for (String line = null; (line = br.readLine()) != null;) {
            String[] arr = line.split("\t");
            long id = Long.parseLong(arr[0]);
            long userId = Long.parseLong(arr[1]);

            allUsers.add(userId);
            tweetsSeen++;

            double[] predLoc = idToPredLoc.get(id);
            if (predLoc == null)
                continue;

            tweetsLocated++;
            locatedUsers.add(userId);

            double[] goldLoc = new double[] { Double.parseDouble(arr[2]), Double.parseDouble(arr[3]) };

            double dist = Geometry.getDistance(predLoc, goldLoc);
            errors.add(dist);
            tweetIdToError.put(id, dist);

            TDoubleList userErrors = userToErrors.get(userId);
            if (userErrors == null) {
                userErrors = new TDoubleArrayList();
                userToErrors.put(userId, userErrors);
            }
            userErrors.add(dist);

        }
        br.close();
    }

    errors.sort();
    System.out.println("Num errors to score: " + errors.size());

    double auc = 0;
    double userCoverage = 0;
    double tweetCoverage = tweetsLocated / (double) tweetsSeen;
    double medianMaxUserError = Double.NaN;
    double medianMedianUserError = Double.NaN;

    if (errors.size() > 0) {
        auc = computeAuc(errors);
        userCoverage = locatedUsers.size() / ((double) allUsers.size());
        TDoubleList maxUserErrors = new TDoubleArrayList(locatedUsers.size());
        TDoubleList medianUserErrors = new TDoubleArrayList(locatedUsers.size());
        for (TDoubleList userErrors : userToErrors.valueCollection()) {
            userErrors.sort();
            maxUserErrors.add(userErrors.get(userErrors.size() - 1));
            medianUserErrors.add(userErrors.get(userErrors.size() / 2));
        }

        maxUserErrors.sort();
        medianMaxUserError = maxUserErrors.get(maxUserErrors.size() / 2);

        medianUserErrors.sort();
        medianMedianUserError = medianUserErrors.get(medianUserErrors.size() / 2);

        // Compute CDF
        int[] errorsPerKm = new int[MAX_KM];
        for (int i = 0; i < errors.size(); ++i) {
            int error = (int) (Math.round(errors.get(i)));
            errorsPerKm[error]++;
        }

        // The accumulated sum of errors per km
        int[] errorsBelowEachKm = new int[errorsPerKm.length];
        for (int i = 0; i < errorsBelowEachKm.length; ++i) {
            errorsBelowEachKm[i] = errorsPerKm[i];
            if (i > 0)
                errorsBelowEachKm[i] += errorsBelowEachKm[i - 1];
        }

        final double[] cdf = new double[errorsBelowEachKm.length];
        double dSize = errors.size(); // to avoid casting all the time
        for (int i = 0; i < cdf.length; ++i)
            cdf[i] = errorsBelowEachKm[i] / dSize;
    }

    PrintWriter pw = new PrintWriter(new File(args[2]));
    pw.println("AUC\t" + auc);
    pw.println("user coverage\t" + userCoverage);
    pw.println("tweet coverage\t" + tweetCoverage);
    pw.println("median-max error\t" + medianMaxUserError);
    pw.close();

    // Choose a random sampling of 10K tweets to pass on to the authors
    // here.        
    PrintWriter errorsPw = new PrintWriter(args[3]);
    TLongList idsWithErrors = new TLongArrayList(tweetIdToError.keySet());
    idsWithErrors.shuffle(new Random());
    // Choose the first 10K
    for (int i = 0, chosen = 0; i < idsWithErrors.size() && chosen < 10_000; ++i) {

        long id = idsWithErrors.get(i);
        double[] prediction = idToPredLoc.get(id);
        double error = tweetIdToError.get(id);
        errorsPw.println(id + "\t" + error + "\t" + prediction[0] + "\t" + prediction[1]);
        ++chosen;
    }
    errorsPw.close();
}

From source file:com.leonarduk.finance.chart.PieChartFactory.java

/**
 * Starting point for the demo.//from w w w .  j a  v a  2s .  c om
 *
 * @param args
 *            ignored.
 */
public static void main(final String[] args) {
    final PieChartFactory factory = new PieChartFactory("Title");
    factory.put("A", 12.2).put("B", 13.2).put("C", 31.2);

    try {
        // write an HTML page incorporating the image with an image map
        final File file2 = new File("multipiechart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        // ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println(ChartDisplay.saveImageAsPngAndReturnHtmlLink("345", 400, 400, factory.buildChart()));
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

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

}

From source file:BufferedSocketClient.java

public static void main(String args[]) throws Exception {
        int cTosPortNumber = 1777;
        String str;//from   w  ww .  ja  v a2s  .  c  om

        ServerSocket servSocket = new ServerSocket(cTosPortNumber);
        System.out.println("Waiting for a connection on " + cTosPortNumber);

        Socket fromClientSocket = servSocket.accept();
        PrintWriter pw = new PrintWriter(fromClientSocket.getOutputStream(), true);

        BufferedReader br = new BufferedReader(new InputStreamReader(fromClientSocket.getInputStream()));

        while ((str = br.readLine()) != null) {
            System.out.println("The message: " + str);

            if (str.equals("bye")) {
                pw.println("bye");
                break;
            } else {
                str = "Server returns " + str;
                pw.println(str);
            }
        }
        pw.close();
        br.close();

        fromClientSocket.close();
    }

From source file:at.tuwien.ifs.feature.evaluation.SimilarityRetrievalWriter.java

public static void main(String[] args) throws SOMToolboxException, IOException {
    // register and parse all options
    JSAPResult config = OptionFactory.parseResults(args, OPTIONS);
    File inputVectorFile = config.getFile("inputVectorFile");
    String outputDirStr = AbstractOptionFactory.getFilePath(config, "outputDirectory");
    File outputDirBase = new File(outputDirStr);
    outputDirBase.mkdirs();/*from   w ww.  j a v a2s. c  o m*/
    String metricName = config.getString("metric");
    DistanceMetric metric = AbstractMetric.instantiateNice(metricName);

    int neighbours = config.getInt("numberNeighbours");
    int startIndex = config.getInt("startIndex");
    int numberItems = config.getInt("numberItems", -1);

    try {
        SOMLibSparseInputData data = new SOMLibSparseInputData(inputVectorFile.getAbsolutePath());
        int endIndex = data.numVectors();
        if (numberItems != -1) {
            if (startIndex + numberItems > endIndex) {
                System.out.println("Specified number of items (" + numberItems + ") exceeds maximum ("
                        + data.numVectors() + "), limiting to " + (endIndex - startIndex) + ".");
            } else {
                endIndex = startIndex + numberItems;
            }
        }
        StdErrProgressWriter progress = new StdErrProgressWriter(endIndex - startIndex, "processing vector ");
        // SortedSet<InputDistance> distances;
        for (int inputDatumIndex = startIndex; inputDatumIndex < endIndex; inputDatumIndex++) {

            InputDatum inputDatum = data.getInputDatum(inputDatumIndex);
            String inputLabel = inputDatum.getLabel();
            if (inputDatumIndex == -1) {
                throw new IllegalArgumentException(
                        "Input with label '" + inputLabel + "' not found in vector file '" + inputVectorFile
                                + "'; possible labels are: " + StringUtils.toString(data.getLabels(), 15));
            }

            File outputDir = new File(outputDirBase,
                    inputLabel.charAt(2) + "/" + inputLabel.charAt(3) + "/" + inputLabel.charAt(4));
            outputDir.mkdirs();
            File outputFile = new File(outputDir, inputLabel + ".txt");

            boolean fileExistsAndValid = false;
            if (outputFile.exists()) {
                // check if it the valid data
                String linesInvalid = "";
                int validLineCount = 0;
                ArrayList<String> lines = FileUtils.readLinesAsList(outputFile.getAbsolutePath());
                for (String string : lines) {
                    if (string.trim().length() == 0) {
                        continue;
                    }
                    String[] parts = string.split("\t");
                    if (parts.length != 2) {
                        linesInvalid += "Line '" + string + "' invalid - contains " + parts.length
                                + " elements.\n";
                    } else if (!NumberUtils.isNumber(parts[1])) {
                        linesInvalid = "Line '" + string + "' invalid - 2nd part is not a number.\n";
                    } else {
                        validLineCount++;
                    }
                }
                if (validLineCount != neighbours) {
                    linesInvalid = "Not enough valid lines; expected " + neighbours + ", found "
                            + validLineCount + ".\n";
                }
                fileExistsAndValid = true;
                if (org.apache.commons.lang.StringUtils.isNotBlank(linesInvalid)) {
                    System.out.println("File " + outputFile.getAbsolutePath() + " exists, but is not valid:\n"
                            + linesInvalid);
                }
            }

            if (fileExistsAndValid) {
                Logger.getLogger("at.tuwien.ifs.feature.evaluation").finer(
                        "File " + outputFile.getAbsolutePath() + " exists and is valid; not recomputing");
            } else {
                PrintWriter p = new PrintWriter(outputFile);
                SmallestElementSet<InputDistance> distances = data.getNearestDistances(inputDatumIndex,
                        neighbours, metric);
                for (InputDistance inputDistance : distances) {
                    p.println(inputDistance.getInput().getLabel() + "\t" + inputDistance.getDistance());
                }
                p.close();
            }
            progress.progress();
        }

    } catch (IllegalArgumentException e) {
        System.out.println(e.getMessage() + ". Aborting.");
        System.exit(-1);
    }
}

From source file:medcheck.Medcheck.java

/**
 * @param args the command line arguments
 *//*  w ww.  j  a  v a 2 s .  com*/
public static void main(String[] args) {
    String jsonFileLocation = "meddata.json";
    File jsonTxt = new File(jsonFileLocation);

    String xmlFileLocation = "XML Files";
    File xmlDirectory = new File(xmlFileLocation);

    String jsonString = getJSONString(jsonTxt);

    PrintWriter csvWriter;
    try {
        csvWriter = new PrintWriter("meddata.csv", "UTF-8");
    } catch (Exception e) {
        System.out.println("ERROR: " + e.getMessage());
        e.printStackTrace();
        return;
    }

    Drug[] csvArray = convertToDrugArrayFromJSON(jsonString);
    Drug[] xmlArray = convertToDrugArrayFromXML(xmlDirectory);
    String csvString = convertToCsvString(csvArray, xmlArray);
    csvWriter.print(csvString);
    csvWriter.close();
}

From source file:org.jfree.chart.demo.ImageMapDemo7.java

/**
 * Starting point for the demo.//  w w w  .  j  a va2 s .  com
 *
 * @param args  ignored.
 */
public static void main(final String[] args) {

    final XYDataset data = new SampleXYDataset2();
    final JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot Demo", "X", "Y", data,
            PlotOrientation.VERTICAL, true, true, false);
    //        final Legend legend = chart.getLegend();
    //      if (legend instanceof StandardLegend) {
    //        final StandardLegend sl = (StandardLegend) legend;
    //      sl.setDisplaySeriesShapes(true);
    //}
    final NumberAxis domainAxis = (NumberAxis) chart.getXYPlot().getDomainAxis();
    domainAxis.setAutoRangeIncludesZero(false);
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("scatter100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("scatter100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"scatter100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

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

}

From source file:DataCrawler.OpenAIRE.XMLGenerator.java

public static void main(String[] args) {
    String text = "";

    try {//  ww  w .  j  av a  2  s . c  om
        if (args.length < 4) {
            System.out.println("<command> template_file csv_file output_dir log_file [start_id]");
        }

        // InputStream fis = new FileInputStream("E:/Downloads/result-r-00000");
        InputStream fis = new FileInputStream(args[1]);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));

        // String content = new String(Files.readAllBytes(Paths.get("publications_template.xml")));
        String content = new String(Files.readAllBytes(Paths.get(args[0])));
        Document doc = Jsoup.parse(content, "UTF-8", Parser.xmlParser());
        // String outputDirectory = "G:/";
        String outputDirectory = args[2];
        // PrintWriter logWriter = new PrintWriter(new FileOutputStream("publication.log",false));
        PrintWriter logWriter = new PrintWriter(new FileOutputStream(args[3], false));
        Element objectId = null, title = null, publisher = null, dateofacceptance = null, bestlicense = null,
                resulttype = null, originalId = null, originalId2 = null;
        boolean start = true;
        // String startID = "dedup_wf_001::207a098867b64f3b5af505fa3aeecd24";
        String startID = "";
        if (args.length >= 5) {
            start = false;
            startID = args[4];
        }
        String previousText = "";
        while ((text = br.readLine()) != null) {
            /*  For publications:
                0. dri:objIdentifier context
               9. title context
               12. publisher context
               18. dateofacceptance
               19. bestlicense @classname
               21. resulttype  @classname
               26. originalId context  
               (Notice that the prefix is null and will use space to separate two different "originalId")
            */

            if (!previousText.isEmpty()) {
                text = previousText + text;
                start = true;
                previousText = "";
            }

            String[] items = text.split("!");
            for (int i = 0; i < items.length; ++i) {
                items[i] = StringUtils.strip(items[i], "#");
            }
            if (objectId == null)
                objectId = doc.getElementsByTag("dri:objIdentifier").first();
            objectId.text(items[0]);

            if (!start && items[0].equals(startID)) {
                start = true;
            }

            if (title == null)
                title = doc.getElementsByTag("title").first();
            title.text(items[9]);

            if (publisher == null)
                publisher = doc.getElementsByTag("publisher").first();

            if (items.length < 12) {
                previousText = text;
                continue;
            }
            publisher.text(items[12]);

            if (dateofacceptance == null)
                dateofacceptance = doc.getElementsByTag("dateofacceptance").first();
            dateofacceptance.text(items[18]);

            if (bestlicense == null)
                bestlicense = doc.getElementsByTag("bestlicense").first();
            bestlicense.attr("classname", items[19]);

            if (resulttype == null)
                resulttype = doc.getElementsByTag("resulttype").first();
            resulttype.attr("classname", items[21]);

            if (originalId == null || originalId2 == null) {
                Elements elements = doc.getElementsByTag("originalId");
                String[] context = items[26].split(" ");
                if (elements.size() > 0) {
                    if (elements.size() >= 1) {
                        originalId = elements.get(0);
                        if (context.length >= 1) {
                            int indexOfnull = context[0].trim().indexOf("null");
                            String value = "";
                            if (indexOfnull != -1) {
                                if (context[0].trim().length() >= (indexOfnull + 5))
                                    value = context[0].trim().substring(indexOfnull + 5);

                            } else {
                                value = context[0].trim();
                            }
                            originalId.text(value);
                        }
                    }
                    if (elements.size() >= 2) {
                        originalId2 = elements.get(1);
                        if (context.length >= 2) {
                            int indexOfnull = context[1].trim().indexOf("null");
                            String value = "";
                            if (indexOfnull != -1) {
                                if (context[1].trim().length() >= (indexOfnull + 5))
                                    value = context[1].trim().substring(indexOfnull + 5);

                            } else {
                                value = context[1].trim();
                            }
                            originalId2.text(value);
                        }
                    }
                }
            } else {
                String[] context = items[26].split(" ");
                if (context.length >= 1) {
                    int indexOfnull = context[0].trim().indexOf("null");
                    String value = "";
                    if (indexOfnull != -1) {
                        if (context[0].trim().length() >= (indexOfnull + 5))
                            value = context[0].trim().substring(indexOfnull + 5);

                    } else {
                        value = context[0].trim();
                    }
                    originalId.text(value);
                }
                if (context.length >= 2) {
                    int indexOfnull = context[1].trim().indexOf("null");
                    String value = "";
                    if (indexOfnull != -1) {
                        if (context[1].trim().length() >= (indexOfnull + 5))
                            value = context[1].trim().substring(indexOfnull + 5);

                    } else {
                        value = context[1].trim();
                    }
                    originalId2.text(value);
                }
            }
            if (start) {
                String filePath = outputDirectory + items[0].replace(":", "#") + ".xml";
                PrintWriter writer = new PrintWriter(new FileOutputStream(filePath, false));
                logWriter.write(filePath + " > Start" + System.lineSeparator());
                writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + System.lineSeparator());
                writer.write(doc.getElementsByTag("response").first().toString());
                writer.close();
                logWriter.write(filePath + " > OK" + System.lineSeparator());
                logWriter.flush();
            }

        }
        logWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.uga.cs.fluxbuster.FluxbusterCLI.java

/**
 * The main method./*from w w w . j av  a  2s  .c  o  m*/
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    GnuParser parser = new GnuParser();
    Options opts = FluxbusterCLI.initializeOptions();
    CommandLine cli;
    try {
        cli = parser.parse(opts, args);

        if (cli.hasOption('?')) {
            throw new ParseException(null);
        }

        if (validateDate(cli.getOptionValue('d')) && validateDate(cli.getOptionValue('e'))) {

            if (log.isInfoEnabled()) {
                StringBuffer arginfo = new StringBuffer("\n");
                arginfo.append("generate-clusters: " + cli.hasOption('g') + "\n");
                arginfo.append("calc-features: " + cli.hasOption('f') + "\n");
                arginfo.append("calc-similarity: " + cli.hasOption('s') + "\n");
                arginfo.append("classify-clusters: " + cli.hasOption('c') + "\n");
                arginfo.append("start-date: " + cli.getOptionValue('d') + "\n");
                arginfo.append("end-date: " + cli.getOptionValue('e') + "\n");
                log.info(arginfo.toString());
            }

            try {
                boolean clus = true, feat = true, simil = true, clas = true;
                if (cli.hasOption('g') || cli.hasOption('f') || cli.hasOption('s') || cli.hasOption('c')) {
                    if (!cli.hasOption('g')) {
                        clus = false;
                    }
                    if (!cli.hasOption('f')) {
                        feat = false;
                    }
                    if (!cli.hasOption('s')) {
                        simil = false;
                    }
                    if (!cli.hasOption('c')) {
                        clas = false;
                    }
                }

                DBInterfaceFactory.init();
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
                Date logdate = df.parse(cli.getOptionValue('d'));
                long startTime = logdate.getTime() / 1000;
                long endTime = df.parse(cli.getOptionValue('e')).getTime() / 1000;

                if (clus) {
                    ClusterGenerator cg = new ClusterGenerator();
                    List<DomainCluster> clusters = cg.generateClusters(startTime, endTime, true);
                    cg.storeClusters(clusters, logdate);
                }
                if (feat) {
                    FeatureCalculator calc = new FeatureCalculator();
                    calc.updateFeatures(logdate);
                }
                if (simil) {
                    ClusterSimilarityCalculator calc2 = new ClusterSimilarityCalculator();
                    calc2.updateClusterSimilarities(logdate);
                }
                if (clas) {
                    Classifier calc3 = new Classifier();
                    calc3.updateClusterClasses(logdate, 30);
                }
            } catch (Exception e) {
                if (log.isFatalEnabled()) {
                    log.fatal("", e);
                }
            } finally {
                DBInterfaceFactory.shutdown();
            }
        } else {
            throw new ParseException(null);
        }
    } catch (ParseException e1) {
        PrintWriter writer = new PrintWriter(System.out);
        HelpFormatter usageFormatter = new HelpFormatter();
        usageFormatter.printHelp(writer, 80, "fluxbuster", "If none of the options g, f, s, c are specified "
                + "then the program will execute as if all of them "
                + "have been specified.  Otherwise, the program will " + "only execute the options specified.",
                opts, 0, 2, "");
        writer.close();
    }
}

From source file:org.jfree.chart.demo.ImageMapDemo2.java

/**
 * The starting point for the demo.//from w  w  w.  j ava  2  s .  c  o  m
 *
 * @param args  ignored.
 */
public static void main(final String[] args) {

    // create a chart
    final DefaultPieDataset data = new DefaultPieDataset();
    data.setValue("One", new Double(43.2));
    data.setValue("Two", new Double(10.0));
    data.setValue("Three", new Double(27.5));
    data.setValue("Four", new Double(17.5));
    data.setValue("Five", new Double(11.0));
    data.setValue("Six", new Double(19.4));

    JFreeChart chart = null;
    final boolean drilldown = true;

    // create the chart...
    if (drilldown) {
        final PiePlot plot = new PiePlot(data);
        //          plot.setInsets(new Insets(0, 5, 5, 5));
        plot.setToolTipGenerator(new StandardPieItemLabelGenerator());
        plot.setURLGenerator(new StandardPieURLGenerator("pie_chart_detail.jsp"));
        chart = new JFreeChart("Pie Chart Demo 1", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    } else {
        chart = ChartFactory.createPieChart("Pie Chart Demo 1", // chart title
                data, // data
                true, // include legend
                true, false);
    }
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("piechart100.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("piechart100.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo 2</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"piechart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

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

}

From source file:org.jfree.chart.demo.ImageMapDemo4.java

/**
 * Starting point for the demo.//  w w w.  j av a  2 s. c o m
 *
 * @param args  ignored.
 */
public static void main(final String[] args) {

    // create a chart
    final double[][] data = new double[][] { { 56.0, -12.0, 34.0, 76.0, 56.0, 100.0, 67.0, 45.0 },
            { 37.0, 45.0, 67.0, 25.0, 34.0, 34.0, 100.0, 53.0 },
            { 43.0, 54.0, 34.0, 34.0, 87.0, 64.0, 73.0, 12.0 } };
    final CategoryDataset dataset = DatasetUtilities.createCategoryDataset("Series ", "Type ", data);

    JFreeChart chart = null;
    final boolean drilldown = true;

    if (drilldown) {
        final CategoryAxis3D categoryAxis = new CategoryAxis3D("Category");
        final ValueAxis valueAxis = new NumberAxis3D("Value");
        final BarRenderer3D renderer = new BarRenderer3D();
        renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());
        renderer.setItemURLGenerator(new StandardCategoryURLGenerator("bar_chart_detail.jsp"));
        final CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer);
        plot.setOrientation(PlotOrientation.VERTICAL);
        chart = new JFreeChart("Bar Chart", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    } else {
        chart = ChartFactory.createBarChart3D("Bar Chart", // chart title
                "Category", // domain axis label
                "Value", // range axis label
                dataset, // data
                PlotOrientation.VERTICAL, true, // include legend
                true, false);
    }
    chart.setBackgroundPaint(java.awt.Color.white);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // save it to an image
    try {
        final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
        final File file1 = new File("barchart101.png");
        ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);

        // write an HTML page incorporating the image with an image map
        final File file2 = new File("barchart101.html");
        final OutputStream out = new BufferedOutputStream(new FileOutputStream(file2));
        final PrintWriter writer = new PrintWriter(out);
        writer.println("<HTML>");
        writer.println("<HEAD><TITLE>JFreeChart Image Map Demo</TITLE></HEAD>");
        writer.println("<BODY>");
        //            ChartUtilities.writeImageMap(writer, "chart", info);
        writer.println("<IMG SRC=\"barchart100.png\" "
                + "WIDTH=\"600\" HEIGHT=\"400\" BORDER=\"0\" USEMAP=\"#chart\">");
        writer.println("</BODY>");
        writer.println("</HTML>");
        writer.close();

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

}