Example usage for java.io Writer write

List of usage examples for java.io Writer write

Introduction

In this page you can find the example usage for java.io Writer write.

Prototype

public void write(String str) throws IOException 

Source Link

Document

Writes a string.

Usage

From source file:examples.nntp.PostMessage.java

public static void main(String[] args) {
    String from, subject, newsgroup, filename, server, organization;
    String references;//  w  w w  . j  a va 2  s . c o m
    BufferedReader stdin;
    FileReader fileReader = null;
    SimpleNNTPHeader header;
    NNTPClient client;

    if (args.length < 1) {
        System.err.println("Usage: post newsserver");
        System.exit(1);
    }

    server = args[0];

    stdin = new BufferedReader(new InputStreamReader(System.in));

    try {
        System.out.print("From: ");
        System.out.flush();

        from = stdin.readLine();

        System.out.print("Subject: ");
        System.out.flush();

        subject = stdin.readLine();

        header = new SimpleNNTPHeader(from, subject);

        System.out.print("Newsgroup: ");
        System.out.flush();

        newsgroup = stdin.readLine();
        header.addNewsgroup(newsgroup);

        while (true) {
            System.out.print("Additional Newsgroup <Hit enter to end>: ");
            System.out.flush();

            // Of course you don't want to do this because readLine() may be null
            newsgroup = stdin.readLine().trim();

            if (newsgroup.length() == 0) {
                break;
            }

            header.addNewsgroup(newsgroup);
        }

        System.out.print("Organization: ");
        System.out.flush();

        organization = stdin.readLine();

        System.out.print("References: ");
        System.out.flush();

        references = stdin.readLine();

        if (organization != null && organization.length() > 0) {
            header.addHeaderField("Organization", organization);
        }

        if (references != null && references.length() > 0) {
            header.addHeaderField("References", references);
        }

        header.addHeaderField("X-Newsreader", "NetComponents");

        System.out.print("Filename: ");
        System.out.flush();

        filename = stdin.readLine();

        try {
            fileReader = new FileReader(filename);
        } catch (FileNotFoundException e) {
            System.err.println("File not found. " + e.getMessage());
            System.exit(1);
        }

        client = new NNTPClient();
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

        client.connect(server);

        if (!NNTPReply.isPositiveCompletion(client.getReplyCode())) {
            client.disconnect();
            System.err.println("NNTP server refused connection.");
            System.exit(1);
        }

        if (client.isAllowedToPost()) {
            Writer writer = client.postArticle();

            if (writer != null) {
                writer.write(header.toString());
                Util.copyReader(fileReader, writer);
                writer.close();
                client.completePendingCommand();
            }
        }

        if (fileReader != null) {
            fileReader.close();
        }

        client.logout();

        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.zimbra.cs.db.MySQL.java

public static void main(String args[]) {
    // command line argument parsing
    Options options = new Options();
    CommandLine cl = Versions.parseCmdlineArgs(args, options);

    String outputDir = cl.getOptionValue("o");
    File outFile = new File(outputDir, "versions-init.sql");
    outFile.delete();//from  w  w  w .  j a v  a 2  s.  c o  m

    try {
        String redoVer = com.zimbra.cs.redolog.Version.latest().toString();
        String outStr = "-- AUTO-GENERATED .SQL FILE - Generated by the MySQL versions tool\n" + "USE zimbra;\n"
                + "INSERT INTO zimbra.config(name, value, description) VALUES\n" + "\t('db.version', '"
                + Versions.DB_VERSION + "', 'db schema version'),\n" + "\t('index.version', '"
                + Versions.INDEX_VERSION + "', 'index version'),\n" + "\t('redolog.version', '" + redoVer
                + "', 'redolog version')\n" + ";\nCOMMIT;\n";

        Writer output = new BufferedWriter(new FileWriter(outFile));
        output.write(outStr);
        if (output != null)
            output.close();
    } catch (IOException e) {
        System.out.println("ERROR - caught exception at\n");
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:airnowgrib2tojson.AirNowGRIB2toJSON.java

/**
 * @param args the command line arguments
 *///  w w  w. j  a  v  a  2 s  . co  m
public static void main(String[] args) {

    SimpleDateFormat GMT = new SimpleDateFormat("yyMMddHH");
    GMT.setTimeZone(TimeZone.getTimeZone("GMT-2"));

    System.out.println(GMT.format(new Date()));

    FTPClient ftpClient = new FTPClient();
    FileOutputStream fos = null;

    try {
        //Connecting to AirNow FTP server to get the fresh AQI data  
        ftpClient.connect("ftp.airnowapi.org");
        ftpClient.login("pixelshade", "GZDN8uqduwvk");
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        //downloading .grib2 file
        File of = new File("US-" + GMT.format(new Date()) + "_combined.grib2");
        OutputStream outstr = new BufferedOutputStream(new FileOutputStream(of));
        InputStream instr = ftpClient
                .retrieveFileStream("GRIB2/US-" + GMT.format(new Date()) + "_combined.grib2");
        byte[] bytesArray = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = instr.read(bytesArray)) != -1) {
            outstr.write(bytesArray, 0, bytesRead);
        }

        //Close used resources
        ftpClient.completePendingCommand();
        outstr.close();
        instr.close();

        // logout the user 
        ftpClient.logout();

    } catch (SocketException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            //disconnect from AirNow server
            ftpClient.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    try {
        //Open .grib2 file
        final File AQIfile = new File("US-" + GMT.format(new Date()) + "_combined.grib2");
        final GridDataset gridDS = GridDataset.open(AQIfile.getAbsolutePath());

        //The data type needed - AQI; since it isn't defined in GRIB2 standard,
        //Aerosol type is used instead; look AirNow API documentation for details.
        GridDatatype AQI = gridDS.findGridDatatype("Aerosol_type_msl");

        //Get the coordinate system for selected data type;
        //cut the rectangle to work with - time and height axes aren't present in these files
        //and latitude/longitude go "-1", which means all the data provided.
        GridCoordSystem AQIGCS = AQI.getCoordinateSystem();
        List<CoordinateAxis> AQI_XY = AQIGCS.getCoordinateAxes();
        Array AQIslice = AQI.readDataSlice(0, 0, -1, -1);

        //Variables for iterating through coordinates
        VariableDS var = AQI.getVariable();
        Index index = AQIslice.getIndex();

        //Variables for counting lat/long from the indices provided
        double stepX = (AQI_XY.get(2).getMaxValue() - AQI_XY.get(2).getMinValue()) / index.getShape(1);
        double stepY = (AQI_XY.get(1).getMaxValue() - AQI_XY.get(1).getMinValue()) / index.getShape(0);
        double curX = AQI_XY.get(2).getMinValue();
        double curY = AQI_XY.get(1).getMinValue();

        //Output details
        OutputStream ValLog = new FileOutputStream("USA_AQI.json");
        Writer ValWriter = new OutputStreamWriter(ValLog);

        for (int j = 0; j < index.getShape(0); j++) {
            for (int i = 0; i < index.getShape(1); i++) {
                float val = AQIslice.getFloat(index.set(j, i));

                //Write the AQI value and its coordinates if it's present by i/j indices
                if (!Float.isNaN(val))
                    ValWriter.write("{\r\n\"lat\":" + curX + ",\r\n\"lng\":" + curY + ",\r\n\"AQI\":" + val
                            + ",\r\n},\r\n");

                curX += stepX;
            }
            curY += stepY;
            curX = AQI_XY.get(2).getMinValue();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.tpt.s3.mcdag.bench.MainBench.java

public static void main(String[] args) throws IOException, InterruptedException {

    // Command line options
    Options options = new Options();

    Option input = new Option("i", "input", true, "MC-DAG XML models");
    input.setRequired(true);/*from   w w w .j  a va2 s . c o  m*/
    input.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(input);

    Option output = new Option("o", "output", true, "Folder where results have to be written.");
    output.setRequired(true);
    options.addOption(output);

    Option uUti = new Option("u", "utilization", true, "Utilization.");
    uUti.setRequired(true);
    options.addOption(uUti);

    Option output2 = new Option("ot", "output-total", true, "File where total results are being written");
    output2.setRequired(true);
    options.addOption(output2);

    Option oCores = new Option("c", "cores", true, "Cores given to the test");
    oCores.setRequired(true);
    options.addOption(oCores);

    Option oLvls = new Option("l", "levels", true, "Levels tested for the system");
    oLvls.setRequired(true);
    options.addOption(oLvls);

    Option jobs = new Option("j", "jobs", true, "Number of threads to be launched.");
    jobs.setRequired(false);
    options.addOption(jobs);

    Option debug = new Option("d", "debug", false, "Debug logs.");
    debug.setRequired(false);
    options.addOption(debug);

    /*
     * Parsing of the command line
     */
    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("Benchmarks MultiDAG", options);
        System.exit(1);
        return;
    }

    String inputFilePath[] = cmd.getOptionValues("input");
    String outputFilePath = cmd.getOptionValue("output");
    String outputFilePathTotal = cmd.getOptionValue("output-total");
    double utilization = Double.parseDouble(cmd.getOptionValue("utilization"));
    boolean boolDebug = cmd.hasOption("debug");
    int nbLvls = Integer.parseInt(cmd.getOptionValue("levels"));
    int nbJobs = 1;
    int nbFiles = inputFilePath.length;

    if (cmd.hasOption("jobs"))
        nbJobs = Integer.parseInt(cmd.getOptionValue("jobs"));

    int nbCores = Integer.parseInt(cmd.getOptionValue("cores"));

    /*
     *  While files need to be allocated
     *  run the tests in the pool of threads
     */

    // For dual-criticality systems we call a specific thread
    if (nbLvls == 2) {

        System.out.println(">>>>>>>>>>>>>>>>>>>>> NB levels " + nbLvls);

        int i_files2 = 0;
        String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.'))
                .concat("-schedulability.csv");
        PrintWriter writer = new PrintWriter(outFile, "UTF-8");
        writer.println(
                "Thread; File; FSched (%); FPreempts; FAct; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization");
        writer.close();

        ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs);
        while (i_files2 != nbFiles) {
            BenchThreadDualCriticality bt2 = new BenchThreadDualCriticality(inputFilePath[i_files2], outFile,
                    nbCores, boolDebug);

            executor2.execute(bt2);
            i_files2++;
        }

        executor2.shutdown();
        executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

        int fedTotal = 0;
        int laxTotal = 0;
        int edfTotal = 0;
        int hybridTotal = 0;
        int fedPreempts = 0;
        int laxPreempts = 0;
        int edfPreempts = 0;
        int hybridPreempts = 0;
        int fedActiv = 0;
        int laxActiv = 0;
        int edfActiv = 0;
        int hybridActiv = 0;
        // Read lines in file and do average
        int i = 0;
        File f = new File(outFile);
        @SuppressWarnings("resource")
        Scanner line = new Scanner(f);
        while (line.hasNextLine()) {
            String s = line.nextLine();
            if (i > 0) { // To skip the first line
                try (Scanner inLine = new Scanner(s).useDelimiter("; ")) {
                    int j = 0;

                    while (inLine.hasNext()) {
                        String val = inLine.next();
                        if (j == 2) {
                            fedTotal += Integer.parseInt(val);
                        } else if (j == 3) {
                            fedPreempts += Integer.parseInt(val);
                        } else if (j == 4) {
                            fedActiv += Integer.parseInt(val);
                        } else if (j == 5) {
                            laxTotal += Integer.parseInt(val);
                        } else if (j == 6) {
                            laxPreempts += Integer.parseInt(val);
                        } else if (j == 7) {
                            laxActiv += Integer.parseInt(val);
                        } else if (j == 8) {
                            edfTotal += Integer.parseInt(val);
                        } else if (j == 9) {
                            edfPreempts += Integer.parseInt(val);
                        } else if (j == 10) {
                            edfActiv += Integer.parseInt(val);
                        } else if (j == 11) {
                            hybridTotal += Integer.parseInt(val);
                        } else if (j == 12) {
                            hybridPreempts += Integer.parseInt(val);
                        } else if (j == 13) {
                            hybridActiv += Integer.parseInt(val);
                        }
                        j++;
                    }
                }
            }
            i++;
        }

        // Write percentage
        double fedPerc = (double) fedTotal / nbFiles;
        double laxPerc = (double) laxTotal / nbFiles;
        double edfPerc = (double) edfTotal / nbFiles;
        double hybridPerc = (double) hybridTotal / nbFiles;

        double fedPercPreempts = (double) fedPreempts / fedActiv;
        double laxPercPreempts = (double) laxPreempts / laxActiv;
        double edfPercPreempts = (double) edfPreempts / edfActiv;
        double hybridPercPreempts = (double) hybridPreempts / hybridActiv;

        Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true));
        wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + fedPerc + "; "
                + fedPreempts + "; " + fedActiv + "; " + fedPercPreempts + "; " + laxPerc + "; " + laxPreempts
                + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts + "; "
                + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; "
                + hybridActiv + "; " + hybridPercPreempts + "\n");
        wOutput.close();

    } else if (nbLvls > 2) {
        int i_files2 = 0;
        String outFile = outputFilePath.substring(0, outputFilePath.lastIndexOf('.'))
                .concat("-schedulability.csv");
        PrintWriter writer = new PrintWriter(outFile, "UTF-8");
        writer.println(
                "Thread; File; LSched (%); LPreempts; LAct; ESched (%); EPreempts; EAct; HSched(%); HPreempts; HAct; Utilization");
        writer.close();

        ExecutorService executor2 = Executors.newFixedThreadPool(nbJobs);
        while (i_files2 != nbFiles) {
            BenchThreadNLevels bt2 = new BenchThreadNLevels(inputFilePath[i_files2], outFile, nbCores,
                    boolDebug);

            executor2.execute(bt2);
            i_files2++;
        }

        executor2.shutdown();
        executor2.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

        int laxTotal = 0;
        int edfTotal = 0;
        int hybridTotal = 0;
        int laxPreempts = 0;
        int edfPreempts = 0;
        int hybridPreempts = 0;
        int laxActiv = 0;
        int edfActiv = 0;
        int hybridActiv = 0;
        // Read lines in file and do average
        int i = 0;
        File f = new File(outFile);
        @SuppressWarnings("resource")
        Scanner line = new Scanner(f);
        while (line.hasNextLine()) {
            String s = line.nextLine();
            if (i > 0) { // To skip the first line
                try (Scanner inLine = new Scanner(s).useDelimiter("; ")) {
                    int j = 0;

                    while (inLine.hasNext()) {
                        String val = inLine.next();
                        if (j == 2) {
                            laxTotal += Integer.parseInt(val);
                        } else if (j == 3) {
                            laxPreempts += Integer.parseInt(val);
                        } else if (j == 4) {
                            laxActiv += Integer.parseInt(val);
                        } else if (j == 5) {
                            edfTotal += Integer.parseInt(val);
                        } else if (j == 6) {
                            edfPreempts += Integer.parseInt(val);
                        } else if (j == 7) {
                            edfActiv += Integer.parseInt(val);
                        } else if (j == 8) {
                            hybridTotal += Integer.parseInt(val);
                        } else if (j == 9) {
                            hybridPreempts += Integer.parseInt(val);
                        } else if (j == 10) {
                            hybridActiv += Integer.parseInt(val);
                        }
                        j++;
                    }
                }
            }
            i++;
        }

        // Write percentage
        double laxPerc = (double) laxTotal / nbFiles;
        double edfPerc = (double) edfTotal / nbFiles;
        double hybridPerc = (double) hybridTotal / nbFiles;

        double laxPercPreempts = (double) laxPreempts / laxActiv;
        double edfPercPreempts = (double) edfPreempts / edfActiv;
        double hybridPercPreempts = (double) hybridPreempts / hybridActiv;

        Writer wOutput = new BufferedWriter(new FileWriter(outputFilePathTotal, true));
        wOutput.write(Thread.currentThread().getName() + "; " + utilization + "; " + laxPerc + "; "
                + laxPreempts + "; " + laxActiv + "; " + laxPercPreempts + "; " + edfPerc + "; " + edfPreempts
                + "; " + edfActiv + "; " + edfPercPreempts + "; " + hybridPerc + "; " + hybridPreempts + "; "
                + hybridActiv + "; " + hybridPercPreempts + "\n");
        wOutput.close();

    } else {
        System.err.println("Wrong number of levels");
        System.exit(-1);
    }

    System.out.println("[BENCH Main] Done benchmarking U = " + utilization + " Levels " + nbLvls);
}

From source file:com.zimbra.cs.db.SQLite.java

public static void main(String args[]) {
    // command line argument parsing
    Options options = new Options();
    CommandLine cl = Versions.parseCmdlineArgs(args, options);

    String outputDir = cl.getOptionValue("o");
    File outFile = new File(outputDir, "versions-init.sql");
    outFile.delete();//from ww  w.j a v  a  2  s. c o m

    try {
        String redoVer = com.zimbra.cs.redolog.Version.latest().toString();
        String outStr = "-- AUTO-GENERATED .SQL FILE - Generated by the SQLite versions tool\n"
                + "INSERT INTO config(name, value, description) VALUES\n" + "\t('db.version', '"
                + Versions.DB_VERSION + "', 'db schema version');\n"
                + "INSERT INTO config(name, value, description) VALUES\n" + "\t('index.version', '"
                + Versions.INDEX_VERSION + "', 'index version');\n"
                + "INSERT INTO config(name, value, description) VALUES\n" + "\t('redolog.version', '" + redoVer
                + "', 'redolog version');\n";

        Writer output = new BufferedWriter(new FileWriter(outFile));
        output.write(outStr);
        output.close();
    } catch (IOException e) {
        System.out.println("ERROR - caught exception at\n");
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:com.gomoob.embedded.EmbeddedMongo.java

/**
 * Main entry of the program./*from w w w . ja va  2s . c  o m*/
 * 
 * @param args arguments used to customize starting.
 * 
 * @throws Exception If an error occured while executing the server.
 */
public static void main(String[] args) throws Exception {

    // Creates a default execution context, then the configuration of this context can be changed depending on the 
    // command line parameters received.
    context = new Context();

    // Parse the command line
    parseCommandLine(args);

    boolean terminated = false;

    System.out.println("MONGOD_HOST=" + context.getMongoContext().getNet().getServerAddress().getHostName());
    System.out.println("MONGOD_PORT=" + context.getMongoContext().getNet().getPort());
    System.out.println("SERVER_SOCKET_PORT=" + context.getSocketContext().getServerSocket().getLocalPort());

    Socket socket = null;
    BufferedReader reader = null;
    Writer writer = null;

    while (!terminated) {

        socket = context.getSocketContext().getServerSocket().accept();

        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        writer = new OutputStreamWriter(new DataOutputStream(socket.getOutputStream()));

        System.out.println("Waiting for command...");
        String commandString = reader.readLine();
        System.out.println(commandString);

        ICommand command = parseCommandString(commandString);

        IResponse response = command.run(context);

        writer.write(response.toJSON());

        writer.close();

        // If the current socket is opened close it
        if (!socket.isClosed()) {
            socket.close();
        }

        // If stop is required
        terminated = response.isTerminationRequired();

    }

    context.getSocketContext().getServerSocket().close();
}

From source file:carmen.demo.LocationResolverDemo.java

public static void main(String[] args)
        throws ParseException, FileNotFoundException, IOException, ClassNotFoundException {
    // Parse the command line.
    String[] manditory_args = { "input_file" };
    createCommandLineOptions();/*from  ww  w  . jav  a  2 s  . com*/
    CommandLineUtilities.initCommandLineParameters(args, LocationResolverDemo.options, manditory_args);

    // Get options
    String inputFile = CommandLineUtilities.getOptionValue("input_file");
    String outputFile = null;
    if (CommandLineUtilities.hasArg("output_file")) {
        outputFile = CommandLineUtilities.getOptionValue("output_file");
    }

    logger.info("Creating LocationResolver.");
    LocationResolver resolver = LocationResolver.getLocationResolver();

    Scanner scanner = Utils.createScanner(inputFile);

    Writer writer = null;
    if (outputFile != null) {
        writer = Utils.createWriter(outputFile);
        logger.info("Saving geolocated tweets to: " + outputFile);
    }
    ObjectMapper mapper = new ObjectMapper();
    int numResolved = 0;
    int total = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        @SuppressWarnings("unchecked")
        HashMap<String, Object> tweet = (HashMap<String, Object>) mapper.readValue(line, Map.class);

        total++;
        Location location = resolver.resolveLocationFromTweet(tweet);

        if (location != null) {
            logger.debug("Found location: " + location.toString());
            numResolved++;
        }
        if (writer != null) {
            if (location != null) {
                tweet.put("location", Location.createJsonFromLocation(location));
            }
            mapper.writeValue(writer, tweet);
            writer.write("\n");
        }

    }
    scanner.close();
    if (writer != null)
        writer.close();

    logger.info("Resolved locations for " + numResolved + " of " + total + " tweets.");
}

From source file:com.zimbra.common.calendar.ZoneInfo2iCalendar.java

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

    // command line handling
    CommandLine cl = null;/*from   ww  w. ja  va  2s. co  m*/
    Params params = null;
    try {
        cl = parseArgs(args);
        if (cl.hasOption(OPT_HELP)) {
            usage(null);
            System.exit(0);
        }
        params = initParams(cl);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        System.exit(1);
    }

    // parse tzdata source
    ZoneInfoParser parser = new ZoneInfoParser();
    for (File tzdataFile : params.tzdataFiles) {
        Reader r = null;
        try {
            r = new InputStreamReader(new FileInputStream(tzdataFile), "UTF-8");
            parser.readTzdata(r);
        } catch (ParseException e) {
            System.err.println(e.getMessage());
            System.err.println("Line: " + e.getErrorOffset());
            System.err.println("File: " + tzdataFile.getAbsolutePath());
            e.printStackTrace();
            System.exit(1);
        } finally {
            if (r != null)
                r.close();
        }
    }
    parser.analyze();

    // read extra data file containing primary TZ list and zone match scores
    if (params.extraDataFile != null) {
        Reader r = null;
        try {
            r = new InputStreamReader(new FileInputStream(params.extraDataFile), "UTF-8");
            readExtraData(r);
        } catch (ParseException e) {
            System.err.println(e.getMessage());
            System.err.println("Line: " + e.getErrorOffset());
            System.err.println("File: " + params.extraDataFile.getAbsolutePath());
            e.printStackTrace();
            System.exit(1);
        } finally {
            if (r != null)
                r.close();
        }
    }

    Writer out;
    if (params.outputFile != null) {
        out = new PrintWriter(params.outputFile, "UTF-8");
    } else {
        out = new PrintWriter(new OutputStreamWriter(System.out, "UTF-8"));
    }

    try {
        StringBuilder hdr = new StringBuilder("BEGIN:VCALENDAR");
        hdr.append(CRLF);
        hdr.append("PRODID:Zimbra-Calendar-Provider").append(CRLF);
        hdr.append("VERSION:2.0").append(CRLF);
        hdr.append("METHOD:PUBLISH").append(CRLF);
        out.write(hdr.toString());

        Map<String, VTimeZone> oldTimeZones = makeOldTimeZonesMap(params);
        Set<Zone> zones = new TreeSet<Zone>(new ZoneComparatorByGmtOffset());
        zones.addAll(parser.getZones());
        Set<String> zoneIDs = new TreeSet<String>();
        for (Zone zone : zones) {
            zoneIDs.add(zone.getName());
        }
        for (Zone zone : zones) {
            out.write(getTimeZoneForZone(zone, params, zoneIDs, oldTimeZones));
        }

        StringBuilder footer = new StringBuilder("END:VCALENDAR");
        footer.append(CRLF);
        out.write(footer.toString());
    } finally {
        out.close();
    }
}

From source file:com.xiangzhurui.util.email.SMTPMail.java

public static void main(String[] args) {
    String sender, recipient, subject, filename, server, cc;
    List<String> ccList = new ArrayList<String>();
    BufferedReader stdin;//w  ww .ja  va2  s  .  c o m
    FileReader fileReader = null;
    Writer writer;
    SimpleSMTPHeader header;
    SMTPClient client;

    if (args.length < 1) {
        System.err.println("Usage: mail smtpserver");
        System.exit(1);
    }

    server = args[0];

    stdin = new BufferedReader(new InputStreamReader(System.in));

    try {
        System.out.print("From: ");
        System.out.flush();

        sender = stdin.readLine();

        System.out.print("To: ");
        System.out.flush();

        recipient = stdin.readLine();

        System.out.print("Subject: ");
        System.out.flush();

        subject = stdin.readLine();

        header = new SimpleSMTPHeader(sender, recipient, subject);

        while (true) {
            System.out.print("CC <enter one address per line, hit enter to end>: ");
            System.out.flush();

            cc = stdin.readLine();

            if (cc == null || cc.length() == 0) {
                break;
            }

            header.addCC(cc.trim());
            ccList.add(cc.trim());
        }

        System.out.print("Filename: ");
        System.out.flush();

        filename = stdin.readLine();

        try {
            fileReader = new FileReader(filename);
        } catch (FileNotFoundException e) {
            System.err.println("File not found. " + e.getMessage());
        }

        client = new SMTPClient();
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

        client.connect(server);

        if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
            client.disconnect();
            System.err.println("SMTP server refused connection.");
            System.exit(1);
        }

        client.login();

        client.setSender(sender);
        client.addRecipient(recipient);

        for (String recpt : ccList) {
            client.addRecipient(recpt);
        }

        writer = client.sendMessageData();

        if (writer != null) {
            writer.write(header.toString());
            Util.copyReader(fileReader, writer);
            writer.close();
            client.completePendingCommand();
        }

        if (fileReader != null) {
            fileReader.close();
        }

        client.logout();

        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:examples.mail.java

public final static void main(String[] args) {
    String sender, recipient, subject, filename, server, cc;
    Vector ccList = new Vector();
    BufferedReader stdin;//  www .  j a  v  a2 s.c om
    FileReader fileReader = null;
    Writer writer;
    SimpleSMTPHeader header;
    SMTPClient client;
    Enumeration en;

    if (args.length < 1) {
        System.err.println("Usage: mail smtpserver");
        System.exit(1);
    }

    server = args[0];

    stdin = new BufferedReader(new InputStreamReader(System.in));

    try {
        System.out.print("From: ");
        System.out.flush();

        sender = stdin.readLine();

        System.out.print("To: ");
        System.out.flush();

        recipient = stdin.readLine();

        System.out.print("Subject: ");
        System.out.flush();

        subject = stdin.readLine();

        header = new SimpleSMTPHeader(sender, recipient, subject);

        while (true) {
            System.out.print("CC <enter one address per line, hit enter to end>: ");
            System.out.flush();

            // Of course you don't want to do this because readLine() may be null
            cc = stdin.readLine().trim();

            if (cc.length() == 0)
                break;

            header.addCC(cc);
            ccList.addElement(cc);
        }

        System.out.print("Filename: ");
        System.out.flush();

        filename = stdin.readLine();

        try {
            fileReader = new FileReader(filename);
        } catch (FileNotFoundException e) {
            System.err.println("File not found. " + e.getMessage());
        }

        client = new SMTPClient();
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

        client.connect(server);

        if (!SMTPReply.isPositiveCompletion(client.getReplyCode())) {
            client.disconnect();
            System.err.println("SMTP server refused connection.");
            System.exit(1);
        }

        client.login();

        client.setSender(sender);
        client.addRecipient(recipient);

        en = ccList.elements();

        while (en.hasMoreElements())
            client.addRecipient((String) en.nextElement());

        writer = client.sendMessageData();

        if (writer != null) {
            writer.write(header.toString());
            Util.copyReader(fileReader, writer);
            writer.close();
            client.completePendingCommand();
        }

        fileReader.close();

        client.logout();

        client.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}