Example usage for java.io BufferedInputStream BufferedInputStream

List of usage examples for java.io BufferedInputStream BufferedInputStream

Introduction

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

Prototype

public BufferedInputStream(InputStream in) 

Source Link

Document

Creates a BufferedInputStream and saves its argument, the input stream in, for later use.

Usage

From source file:io.fluo.webindex.data.Copy.java

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

    if (args.length != 3) {
        log.error("Usage: Copy <pathsFile> <range> <dest>");
        System.exit(1);//from ww w.j  a va2 s .co  m
    }
    final String hadoopConfDir = IndexEnv.getHadoopConfDir();
    final List<String> copyList = IndexEnv.getPathsRange(args[0], args[1]);
    if (copyList.isEmpty()) {
        log.error("No files to copy given {} {}", args[0], args[1]);
        System.exit(1);
    }

    DataConfig dataConfig = DataConfig.load();

    SparkConf sparkConf = new SparkConf().setAppName("webindex-copy");
    try (JavaSparkContext ctx = new JavaSparkContext(sparkConf)) {

        FileSystem hdfs = FileSystem.get(ctx.hadoopConfiguration());
        Path destPath = new Path(args[2]);
        if (!hdfs.exists(destPath)) {
            hdfs.mkdirs(destPath);
        }

        log.info("Copying {} files (Range {} of paths file {}) from AWS to HDFS {}", copyList.size(), args[1],
                args[0], destPath.toString());

        JavaRDD<String> copyRDD = ctx.parallelize(copyList, dataConfig.getNumExecutorInstances());

        final String prefix = DataConfig.CC_URL_PREFIX;
        final String destDir = destPath.toString();

        copyRDD.foreachPartition(iter -> {
            FileSystem fs = IndexEnv.getHDFS(hadoopConfDir);
            iter.forEachRemaining(ccPath -> {
                try {
                    Path dfsPath = new Path(destDir + "/" + getFilename(ccPath));
                    if (fs.exists(dfsPath)) {
                        log.error("File {} exists in HDFS and should have been previously filtered",
                                dfsPath.getName());
                    } else {
                        String urlToCopy = prefix + ccPath;
                        log.info("Starting copy of {} to {}", urlToCopy, destDir);
                        try (OutputStream out = fs.create(dfsPath);
                                BufferedInputStream in = new BufferedInputStream(
                                        new URL(urlToCopy).openStream())) {
                            IOUtils.copy(in, out);
                        }
                        log.info("Created {}", dfsPath.getName());
                    }
                } catch (IOException e) {
                    log.error("Exception while copying {}", ccPath, e);
                }
            });
        });
    }
}

From source file:DruidResponseTime.java

public static void main(String[] args) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
        post.addHeader("content-type", "application/json");
        CloseableHttpResponse res;// ww  w. jav  a  2 s  .  c o m

        if (STORE_RESULT) {
            File dir = new File(RESULT_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }

        int length;

        // Make sure all segments online
        System.out.println("Test if number of records is " + RECORD_NUMBER);
        post.setEntity(new StringEntity("{" + "\"queryType\":\"timeseries\","
                + "\"dataSource\":\"tpch_lineitem\"," + "\"intervals\":[\"1992-01-01/1999-01-01\"],"
                + "\"granularity\":\"all\"," + "\"aggregations\":[{\"type\":\"count\",\"name\":\"count\"}]}"));
        while (true) {
            System.out.print('*');
            res = client.execute(post);
            boolean valid;
            try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) {
                length = in.read(BYTE_BUFFER);
                valid = new String(BYTE_BUFFER, 0, length, "UTF-8").contains("\"count\" : 6001215");
            }
            res.close();
            if (valid) {
                break;
            } else {
                Thread.sleep(5000);
            }
        }
        System.out.println("Number of Records Test Passed");

        for (int i = 0; i < QUERIES.length; i++) {
            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Start running query: " + QUERIES[i]);
            try (BufferedReader reader = new BufferedReader(
                    new FileReader(QUERY_FILE_DIR + File.separator + i + ".json"))) {
                length = reader.read(CHAR_BUFFER);
                post.setEntity(new StringEntity(new String(CHAR_BUFFER, 0, length)));
            }

            // Warm-up Rounds
            System.out.println("Run " + WARMUP_ROUND + " times to warm up cache...");
            for (int j = 0; j < WARMUP_ROUND; j++) {
                res = client.execute(post);
                res.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            int[] time = new int[TEST_ROUND];
            int totalTime = 0;
            System.out.println("Run " + TEST_ROUND + " times to get average time...");
            for (int j = 0; j < TEST_ROUND; j++) {
                long startTime = System.currentTimeMillis();
                res = client.execute(post);
                long endTime = System.currentTimeMillis();
                if (STORE_RESULT && j == 0) {
                    try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent());
                            BufferedWriter writer = new BufferedWriter(
                                    new FileWriter(RESULT_DIR + File.separator + i + ".json", false))) {
                        while ((length = in.read(BYTE_BUFFER)) > 0) {
                            writer.write(new String(BYTE_BUFFER, 0, length, "UTF-8"));
                        }
                    }
                }
                res.close();
                time[j] = (int) (endTime - startTime);
                totalTime += time[j];
                System.out.print(time[j] + "ms ");
            }
            System.out.println();

            // Process Results
            double avgTime = (double) totalTime / TEST_ROUND;
            double stdDev = 0;
            for (int temp : time) {
                stdDev += (temp - avgTime) * (temp - avgTime) / TEST_ROUND;
            }
            stdDev = Math.sqrt(stdDev);
            System.out.println("The average response time for the query is: " + avgTime + "ms");
            System.out.println("The standard deviation is: " + stdDev);
        }
    }
}

From source file:com.jbrisbin.groovy.mqdsl.RabbitMQDsl.java

public static void main(String[] argv) {

    // Parse command line arguments
    CommandLine args = null;/*from  w w w  . j  a  v a 2s.c  om*/
    try {
        Parser p = new BasicParser();
        args = p.parse(cliOpts, argv);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
    }

    // Check for help
    if (args.hasOption('?')) {
        printUsage();
        return;
    }

    // Runtime properties
    Properties props = System.getProperties();

    // Check for ~/.rabbitmqrc
    File userSettings = new File(System.getProperty("user.home"), ".rabbitmqrc");
    if (userSettings.exists()) {
        try {
            props.load(new FileInputStream(userSettings));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    // Load Groovy builder file
    StringBuffer script = new StringBuffer();
    BufferedInputStream in = null;
    String filename = "<STDIN>";
    if (args.hasOption("f")) {
        filename = args.getOptionValue("f");
        try {
            in = new BufferedInputStream(new FileInputStream(filename));
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        in = new BufferedInputStream(System.in);
    }

    // Read script
    if (null != in) {
        byte[] buff = new byte[4096];
        try {
            for (int read = in.read(buff); read > -1;) {
                script.append(new String(buff, 0, read));
                read = in.read(buff);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    } else {
        System.err.println("No script file to evaluate...");
    }

    PrintStream stdout = System.out;
    PrintStream out = null;
    if (args.hasOption("o")) {
        try {
            out = new PrintStream(new FileOutputStream(args.getOptionValue("o")), true);
            System.setOut(out);
        } catch (FileNotFoundException e) {
            log.error(e.getMessage(), e);
        }
    }

    String[] includes = (System.getenv().containsKey("MQDSL_INCLUDE")
            ? System.getenv("MQDSL_INCLUDE").split(String.valueOf(File.pathSeparatorChar))
            : new String[] { System.getenv("HOME") + File.separator + ".mqdsl.d" });

    try {
        // Setup RabbitMQ
        String username = (args.hasOption("U") ? args.getOptionValue("U")
                : props.getProperty("mq.user", "guest"));
        String password = (args.hasOption("P") ? args.getOptionValue("P")
                : props.getProperty("mq.password", "guest"));
        String virtualHost = (args.hasOption("v") ? args.getOptionValue("v")
                : props.getProperty("mq.virtualhost", "/"));
        String host = (args.hasOption("h") ? args.getOptionValue("h")
                : props.getProperty("mq.host", "localhost"));
        int port = Integer.parseInt(
                args.hasOption("p") ? args.getOptionValue("p") : props.getProperty("mq.port", "5672"));

        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        if (null != virtualHost) {
            connectionFactory.setVirtualHost(virtualHost);
        }

        // The DSL builder
        RabbitMQBuilder builder = new RabbitMQBuilder();
        builder.setConnectionFactory(connectionFactory);
        // Our execution environment
        Binding binding = new Binding(args.getArgs());
        binding.setVariable("mq", builder);
        String fileBaseName = filename.replaceAll("\\.groovy$", "");
        binding.setVariable("log",
                LoggerFactory.getLogger(fileBaseName.substring(fileBaseName.lastIndexOf("/") + 1)));
        if (null != out) {
            binding.setVariable("out", out);
        }

        // Include helper files
        GroovyShell shell = new GroovyShell(binding);
        for (String inc : includes) {
            File f = new File(inc);
            if (f.isDirectory()) {
                File[] files = f.listFiles(new FilenameFilter() {
                    @Override
                    public boolean accept(File file, String s) {
                        return s.endsWith(".groovy");
                    }
                });
                for (File incFile : files) {
                    run(incFile, shell, binding);
                }
            } else {
                run(f, shell, binding);
            }
        }

        run(script.toString(), shell, binding);

        while (builder.isActive()) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        }

        if (null != out) {
            out.close();
            System.setOut(stdout);
        }

    } finally {
        System.exit(0);
    }
}

From source file:de.topobyte.osm4j.pbf.executables.EntitySplit.java

public static void main(String[] args) throws IOException {
    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_INPUT, true, false, "input file");
    OptionHelper.add(options, OPTION_OUTPUT_NODES, true, false, "the file to write nodes to");
    OptionHelper.add(options, OPTION_OUTPUT_WAYS, true, false, "the file to write ways to");
    OptionHelper.add(options, OPTION_OUTPUT_RELATIONS, true, false, "the file to write relations to");
    // @formatter:on

    CommandLine line = null;/*from  w w  w .  j  a  va  2 s.co  m*/
    try {
        line = new GnuParser().parse(options, args);
    } catch (ParseException e) {
        System.out.println("unable to parse command line: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    if (line == null) {
        return;
    }

    InputStream in = null;
    if (line.hasOption(OPTION_INPUT)) {
        String inputPath = line.getOptionValue(OPTION_INPUT);
        File file = new File(inputPath);
        FileInputStream fis = new FileInputStream(file);
        in = new BufferedInputStream(fis);
    } else {
        in = new BufferedInputStream(System.in);
    }

    OutputStream outNodes = null, outWays = null, outRelations = null;
    if (line.hasOption(OPTION_OUTPUT_NODES)) {
        String path = line.getOptionValue(OPTION_OUTPUT_NODES);
        FileOutputStream fos = new FileOutputStream(path);
        outNodes = new BufferedOutputStream(fos);
    }
    if (line.hasOption(OPTION_OUTPUT_WAYS)) {
        String path = line.getOptionValue(OPTION_OUTPUT_WAYS);
        FileOutputStream fos = new FileOutputStream(path);
        outWays = new BufferedOutputStream(fos);
    }
    if (line.hasOption(OPTION_OUTPUT_RELATIONS)) {
        String path = line.getOptionValue(OPTION_OUTPUT_RELATIONS);
        FileOutputStream fos = new FileOutputStream(path);
        outRelations = new BufferedOutputStream(fos);
    }

    if (outNodes == null && outWays == null && outRelations == null) {
        System.out.println("You should specify an output for at least one entity");
        System.exit(1);
    }

    EntitySplit task = new EntitySplit(in, outNodes, outWays, outRelations);
    task.execute();
}

From source file:com.ms.commons.file.excel.ExcelParser.java

public static void main(String args[]) {
    HSSFWorkbook workBook = null;/*from w w  w .j av  a  2  s .c om*/
    File file = new File("/home/zxc/back_word/dump_word/33_2013_07_07.xls");
    InputStream excelDocumentStream = null;
    try {
        excelDocumentStream = new FileInputStream(file);
        POIFSFileSystem fsPOI = new POIFSFileSystem(new BufferedInputStream(excelDocumentStream));
        workBook = new HSSFWorkbook(fsPOI);
        ExcelParser parser = new ExcelParser(workBook.getSheetAt(0));
        String[] res;
        while ((res = parser.splitLine()) != null) {
            if (res.length == 7) {
                String resStr = StringUtils.join(res);
                if (resStr.contains("?")) {
                    continue;
                }
            }
            for (int i = 0; i < res.length; i++) {
                System.out.println("Token Found [" + res[i] + "]");
            }
        }
        excelDocumentStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.linkedin.pinotdruidbenchmark.PinotResponseTime.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
        System.err.println(//w w w  . ja  v a 2  s  .c om
                "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    int warmUpRounds = Integer.parseInt(args[2]);
    int testRounds = Integer.parseInt(args[3]);
    File resultDir;
    if (args.length == 4) {
        resultDir = null;
    } else {
        resultDir = new File(args[4]);
        if (!resultDir.exists()) {
            if (!resultDir.mkdirs()) {
                throw new RuntimeException("Failed to create result directory: " + resultDir);
            }
        }
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(resourceUrl);

        for (File queryFile : queryFiles) {
            String query = new BufferedReader(new FileReader(queryFile)).readLine();
            httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));

            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Running query: " + query);
            System.out.println(
                    "--------------------------------------------------------------------------------");

            // Warm-up Rounds
            System.out.println("Run " + warmUpRounds + " times to warm up...");
            for (int i = 0; i < warmUpRounds; i++) {
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            System.out.println("Run " + testRounds + " times to get response time statistics...");
            long[] responseTimes = new long[testRounds];
            long totalResponseTime = 0L;
            for (int i = 0; i < testRounds; i++) {
                long startTime = System.currentTimeMillis();
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                long responseTime = System.currentTimeMillis() - startTime;
                responseTimes[i] = responseTime;
                totalResponseTime += responseTime;
                System.out.print(responseTime + "ms ");
            }
            System.out.println();

            // Store result.
            if (resultDir != null) {
                File resultFile = new File(resultDir, queryFile.getName() + ".result");
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
                        httpResponse.getEntity().getContent());
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) {
                    int length;
                    while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) {
                        bufferedWriter.write(new String(BYTE_BUFFER, 0, length));
                    }
                }
                httpResponse.close();
            }

            // Process response times.
            double averageResponseTime = (double) totalResponseTime / testRounds;
            double temp = 0;
            for (long responseTime : responseTimes) {
                temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime);
            }
            double standardDeviation = Math.sqrt(temp / testRounds);
            System.out.println("Average response time: " + averageResponseTime + "ms");
            System.out.println("Standard deviation: " + standardDeviation);
        }
    }
}

From source file:Manifest.java

public static void main(String[] args) throws Exception {
    // Set the default values of the command-line arguments
    boolean verify = false; // Verify manifest or create one?
    String manifestfile = "MANIFEST"; // Manifest file name
    String digestAlgorithm = "MD5"; // Algorithm for message digests
    String signername = null; // Signer. No sig. by default
    String signatureAlgorithm = "DSA"; // Algorithm for digital sig.
    String password = null; // Private keys are protected
    File keystoreFile = null; // Where are keys stored
    String keystoreType = null; // What kind of keystore
    String keystorePassword = null; // How to access keystore
    List filelist = new ArrayList(); // The files to digest

    // Parse the command-line arguments, overriding the defaults above
    for (int i = 0; i < args.length; i++) {
        if (args[i].equals("-v"))
            verify = true;/*ww w.j  a  va2s .c om*/
        else if (args[i].equals("-m"))
            manifestfile = args[++i];
        else if (args[i].equals("-da") && !verify)
            digestAlgorithm = args[++i];
        else if (args[i].equals("-s") && !verify)
            signername = args[++i];
        else if (args[i].equals("-sa") && !verify)
            signatureAlgorithm = args[++i];
        else if (args[i].equals("-p"))
            password = args[++i];
        else if (args[i].equals("-keystore"))
            keystoreFile = new File(args[++i]);
        else if (args[i].equals("-keystoreType"))
            keystoreType = args[++i];
        else if (args[i].equals("-keystorePassword"))
            keystorePassword = args[++i];

        else if (!verify)
            filelist.add(args[i]);
        else
            throw new IllegalArgumentException(args[i]);
    }

    // If certain arguments weren't supplied, get default values.
    if (keystoreFile == null) {
        File dir = new File(System.getProperty("user.home"));
        keystoreFile = new File(dir, ".keystore");
    }
    if (keystoreType == null)
        keystoreType = KeyStore.getDefaultType();
    if (keystorePassword == null)
        keystorePassword = password;

    if (!verify && signername != null && password == null) {
        System.out.println("Use -p to specify a password.");
        return;
    }

    // Get the keystore we'll use for signing or verifying signatures
    // If no password was provided, then assume we won't be dealing with
    // signatures, and skip the keystore.
    KeyStore keystore = null;
    if (keystorePassword != null) {
        keystore = KeyStore.getInstance(keystoreType);
        InputStream in = new BufferedInputStream(new FileInputStream(keystoreFile));
        keystore.load(in, keystorePassword.toCharArray());
    }

    // If -v was specified or no file were given, verify a manifest
    // Otherwise, create a new manifest for the specified files
    if (verify || (filelist.size() == 0))
        verify(manifestfile, keystore);
    else
        create(manifestfile, digestAlgorithm, signername, signatureAlgorithm, keystore, password, filelist);
}

From source file:com.linkedin.pinotdruidbenchmark.DruidResponseTime.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
        System.err.println(/*from  w  ww. j  av  a 2 s.  c om*/
                "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    int warmUpRounds = Integer.parseInt(args[2]);
    int testRounds = Integer.parseInt(args[3]);
    File resultDir;
    if (args.length == 4) {
        resultDir = null;
    } else {
        resultDir = new File(args[4]);
        if (!resultDir.exists()) {
            if (!resultDir.mkdirs()) {
                throw new RuntimeException("Failed to create result directory: " + resultDir);
            }
        }
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        httpPost.addHeader("content-type", "application/json");

        for (File queryFile : queryFiles) {
            StringBuilder stringBuilder = new StringBuilder();
            try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFile))) {
                int length;
                while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) {
                    stringBuilder.append(new String(CHAR_BUFFER, 0, length));
                }
            }
            String query = stringBuilder.toString();
            httpPost.setEntity(new StringEntity(query));

            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Running query: " + query);
            System.out.println(
                    "--------------------------------------------------------------------------------");

            // Warm-up Rounds
            System.out.println("Run " + warmUpRounds + " times to warm up...");
            for (int i = 0; i < warmUpRounds; i++) {
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            System.out.println("Run " + testRounds + " times to get response time statistics...");
            long[] responseTimes = new long[testRounds];
            long totalResponseTime = 0L;
            for (int i = 0; i < testRounds; i++) {
                long startTime = System.currentTimeMillis();
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                long responseTime = System.currentTimeMillis() - startTime;
                responseTimes[i] = responseTime;
                totalResponseTime += responseTime;
                System.out.print(responseTime + "ms ");
            }
            System.out.println();

            // Store result.
            if (resultDir != null) {
                File resultFile = new File(resultDir, queryFile.getName() + ".result");
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
                        httpResponse.getEntity().getContent());
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) {
                    int length;
                    while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) {
                        bufferedWriter.write(new String(BYTE_BUFFER, 0, length));
                    }
                }
                httpResponse.close();
            }

            // Process response times.
            double averageResponseTime = (double) totalResponseTime / testRounds;
            double temp = 0;
            for (long responseTime : responseTimes) {
                temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime);
            }
            double standardDeviation = Math.sqrt(temp / testRounds);
            System.out.println("Average response time: " + averageResponseTime + "ms");
            System.out.println("Standard deviation: " + standardDeviation);
        }
    }
}

From source file:msgshow.java

public static void main(String argv[]) {
    int optind;//from ww w  .  j a  v  a2 s.c o  m
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum ...] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (optind >= argv.length) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            while (optind < argv.length) {
                int msgnum = Integer.parseInt(argv[optind++]);
                System.out.println("Getting message number: " + msgnum);
                Message m = null;

                try {
                    m = folder.getMessage(msgnum);
                    dumpPart(m);
                } catch (IndexOutOfBoundsException iex) {
                    System.out.println("Message number out of range");
                }
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}

From source file:MainClass.java

public static void main(String argv[]) {
    int msgnum = -1;
    int optind;//  w  w w . j  a v a  2s .co  m
    InputStream msgStream = System.in;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            mbox = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-p")) {
            port = Integer.parseInt(argv[++optind]);
        } else if (argv[optind].equals("-s")) {
            showStructure = true;
        } else if (argv[optind].equals("-S")) {
            saveAttachments = true;
        } else if (argv[optind].equals("-m")) {
            showMessage = true;
        } else if (argv[optind].equals("-a")) {
            showAlert = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
            System.out.println("\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s] [-S] [-a]");
            System.out.println("or     msgshow -m [-v] [-D] [-s] [-S] [-f msg-file]");
            System.exit(1);
        } else {
            break;
        }
    }

    try {
        if (optind < argv.length)
            msgnum = Integer.parseInt(argv[optind]);

        // Get a Properties object
        Properties props = System.getProperties();

        // Get a Session object
        Session session = Session.getInstance(props, null);
        session.setDebug(debug);

        if (showMessage) {
            MimeMessage msg;
            if (mbox != null)
                msg = new MimeMessage(session, new BufferedInputStream(new FileInputStream(mbox)));
            else
                msg = new MimeMessage(session, msgStream);
            dumpPart(msg);
            System.exit(0);
        }

        // Get a Store object
        Store store = null;
        if (url != null) {
            URLName urln = new URLName(url);
            store = session.getStore(urln);
            if (showAlert) {
                store.addStoreListener(new StoreListener() {
                    public void notification(StoreEvent e) {
                        String s;
                        if (e.getMessageType() == StoreEvent.ALERT)
                            s = "ALERT: ";
                        else
                            s = "NOTICE: ";
                        System.out.println(s + e.getMessage());
                    }
                });
            }
            store.connect();
        } else {
            if (protocol != null)
                store = session.getStore(protocol);
            else
                store = session.getStore();

            // Connect
            if (host != null || user != null || password != null)
                store.connect(host, port, user, password);
            else
                store.connect();
        }

        // Open the Folder

        Folder folder = store.getDefaultFolder();
        if (folder == null) {
            System.out.println("No default folder");
            System.exit(1);
        }

        if (mbox == null)
            mbox = "INBOX";
        folder = folder.getFolder(mbox);
        if (folder == null) {
            System.out.println("Invalid folder");
            System.exit(1);
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }
        int totalMessages = folder.getMessageCount();

        if (totalMessages == 0) {
            System.out.println("Empty folder");
            folder.close(false);
            store.close();
            System.exit(1);
        }

        if (verbose) {
            int newMessages = folder.getNewMessageCount();
            System.out.println("Total messages = " + totalMessages);
            System.out.println("New messages = " + newMessages);
            System.out.println("-------------------------------");
        }

        if (msgnum == -1) {
            // Attributes & Flags for all messages ..
            Message[] msgs = folder.getMessages();

            // Use a suitable FetchProfile
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);
            fp.add(FetchProfile.Item.FLAGS);
            fp.add("X-Mailer");
            folder.fetch(msgs, fp);

            for (int i = 0; i < msgs.length; i++) {
                System.out.println("--------------------------");
                System.out.println("MESSAGE #" + (i + 1) + ":");
                dumpEnvelope(msgs[i]);
                // dumpPart(msgs[i]);
            }
        } else {
            System.out.println("Getting message number: " + msgnum);
            Message m = null;

            try {
                m = folder.getMessage(msgnum);
                dumpPart(m);
            } catch (IndexOutOfBoundsException iex) {
                System.out.println("Message number out of range");
            }
        }

        folder.close(false);
        store.close();
    } catch (Exception ex) {
        System.out.println("Oops, got exception! " + ex.getMessage());
        ex.printStackTrace();
        System.exit(1);
    }
    System.exit(0);
}