Example usage for java.io BufferedReader readLine

List of usage examples for java.io BufferedReader readLine

Introduction

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

Prototype

public String readLine() throws IOException 

Source Link

Document

Reads a line of text.

Usage

From source file:com.renren.ntc.sg.util.wxpay.https.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(
            new File("/Users/allenz/Downloads/wx_cert/apiclient_cert.p12"));
    try {/*from   w  w  w. j a va2s .  c  o m*/
        keyStore.load(instream, Constants.mch_id.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Constants.mch_id.toCharArray())
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers");
        System.out.println("executing request" + post.getRequestLine());

        String openid = "oQfDLjmZD7Lgynv6vuoBlWXUY_ic";
        String nonce_str = Sha1Util.getNonceStr();
        String orderId = SUtils.getOrderId();
        String re_user_name = "?";
        String amount = "1";
        String desc = "";
        String spbill_create_ip = "123.56.102.224";

        String txt = TXT.replace("{mch_appid}", Constants.mch_appid);
        txt = txt.replace("{mchid}", Constants.mch_id);
        txt = txt.replace("{openid}", openid);
        txt = txt.replace("{nonce_str}", nonce_str);
        txt = txt.replace("{partner_trade_no}", orderId);
        txt = txt.replace("{check_name}", "FORCE_CHECK");
        txt = txt.replace("{re_user_name}", re_user_name);
        txt = txt.replace("{amount}", amount);
        txt = txt.replace("{desc}", desc);
        txt = txt.replace("{spbill_create_ip}", spbill_create_ip);

        SortedMap<String, String> map = new TreeMap<String, String>();
        map.put("mch_appid", Constants.mch_appid);
        map.put("mchid", Constants.mch_id);
        map.put("openid", openid);
        map.put("nonce_str", nonce_str);
        map.put("partner_trade_no", orderId);
        //FORCE_CHECK| OPTION_CHECK | NO_CHECK
        map.put("check_name", "OPTION_CHECK");
        map.put("re_user_name", re_user_name);
        map.put("amount", amount);
        map.put("desc", desc);
        map.put("spbill_create_ip", spbill_create_ip);

        String sign = SUtils.createSign(map).toUpperCase();
        txt = txt.replace("{sign}", sign);

        post.setEntity(new StringEntity(txt, "utf-8"));

        CloseableHttpResponse response = httpclient.execute(post);
        try {
            HttpEntity entity = response.getEntity();

            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                StringBuffer sb = new StringBuffer();
                while ((text = bufferedReader.readLine()) != null) {
                    sb.append(text);
                }
                String resp = sb.toString();
                LoggerUtils.getInstance().log(String.format("req %s rec %s", txt, resp));
                if (isOk(resp)) {

                    String payment_no = getValue(resp, "payment_no");
                    LoggerUtils.getInstance()
                            .log(String.format("order %s pay OK   payment_no %s", orderId, payment_no));
                }

            }
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:edu.msu.cme.rdp.abundstats.cli.AbundMain.java

public static void main(String[] args) throws IOException {
    File inputFile;//from  w w w.  j a v  a  2 s .  c  o m
    File resultDir = new File(".");
    RPlotter plotter = null;
    boolean isClusterFile = true;
    List<AbundStatsCalculator> statCalcs = new ArrayList();
    double clustCutoffFrom = Double.MIN_VALUE, clustCutoffTo = Double.MAX_VALUE;

    String usage = "Main [options] <cluster file>";
    try {
        CommandLine line = new PosixParser().parse(options, args);

        if (line.hasOption("result-dir")) {
            resultDir = new File(line.getOptionValue("result-dir"));
            if (!resultDir.exists() && !resultDir.mkdirs()) {
                throw new Exception(
                        "Result directory " + resultDir + " does not exist and could not be created");
            }
        }

        if (line.hasOption("R-location")) {
            plotter = new RPlotter();
            plotter.setCommandTemplate(rplotterTemplate);
            plotter.setRPath(line.getOptionValue("R-location"));
            plotter.setOutFileExt(".png");

            if (!new File(plotter.getRPath()).canExecute()) {
                throw new Exception(plotter.getRPath() + " does not exist or is not exectuable");
            }
        }

        if (line.hasOption("lower-cutoff")) {
            clustCutoffFrom = Double.valueOf(line.getOptionValue("lower-cutoff"));
        }

        if (line.hasOption("upper-cutoff")) {
            clustCutoffTo = Double.valueOf(line.getOptionValue("upper-cutoff"));
        }

        if (line.hasOption("jaccard")) {
            statCalcs.add(new Jaccard(true));
        }

        if (line.hasOption("sorensen")) {
            statCalcs.add(new Sorensen(true));
        }

        if (line.hasOption("otu-table")) {
            isClusterFile = false;
        }

        if (statCalcs.isEmpty()) {
            throw new Exception("Must specify at least one stat to compute (jaccard, sorensen)");
        }

        args = line.getArgs();
        if (args.length != 1) {
            throw new Exception("Unexpected number of command line arguments");
        }

        inputFile = new File(args[0]);

    } catch (Exception e) {
        new HelpFormatter().printHelp(usage, options);
        System.err.println("Error: " + e.getMessage());
        return;
    }

    if (isClusterFile) {
        RDPClustParser parser;
        parser = new RDPClustParser(inputFile);

        try {
            if (parser.getClusterSamples().size() == 1) {
                throw new IOException("Cluster file must have more than one sample");
            }

            List<Cutoff> cutoffs = parser.getCutoffs(clustCutoffFrom, clustCutoffTo);
            if (cutoffs.isEmpty()) {
                throw new IOException(
                        "No cutoffs in cluster file in range [" + clustCutoffFrom + "-" + clustCutoffTo + "]");
            }

            for (Cutoff cutoff : cutoffs) {
                List<Sample> samples = new ArrayList();

                for (ClusterSample clustSample : parser.getClusterSamples()) {
                    Sample s = new Sample(clustSample.getName());
                    for (Cluster clust : cutoff.getClusters().get(clustSample.getName())) {
                        s.addSpecies(clust.getNumberOfSeqs());
                    }
                    samples.add(s);
                }

                processSamples(samples, statCalcs, resultDir, cutoff.getCutoff() + "_", plotter);
            }

        } finally {
            parser.close();
        }
    } else {
        List<Sample> samples = new ArrayList();
        BufferedReader reader = new BufferedReader(new FileReader(inputFile));
        String line = reader.readLine();

        if (line == null || line.split("\\s+").length < 2) {
            throw new IOException("Must be 2 or more samples for abundance statistic calculations!");
        }
        int numSamples = line.split("\\s+").length;

        boolean header = true;
        try {
            Integer.valueOf(line.split("\\s+")[0]);
            header = false;
        } catch (Exception e) {
        }

        if (header) {
            for (String s : line.split("\\s+")) {
                samples.add(new Sample(s));
            }
        } else {
            int sample = 0;
            for (String s : line.split("\\s+")) {
                samples.add(new Sample("" + sample));
                samples.get(sample).addSpecies(Integer.valueOf(s));
                sample++;
            }
        }

        int lineno = 2;
        while ((line = reader.readLine()) != null) {
            if (line.trim().equals("")) {
                continue;
            }
            int sample = 0;
            if (line.split("\\s+").length != numSamples) {
                System.err.println(
                        "Line number " + lineno + " didn't have the expected number of samples (contained "
                                + line.split("\\s+").length + ", expected " + numSamples + ")");
            }

            for (String s : line.split("\\s+")) {
                samples.get(sample).addSpecies(Integer.valueOf(s));
                sample++;
            }

            lineno++;
        }

        processSamples(samples, statCalcs, resultDir, inputFile.getName(), plotter);
    }
}

From source file:com.lightboxtechnologies.spectrum.SequenceFileExport.java

public static void main(String[] args) throws Exception {
    final Configuration conf = new Configuration();

    final String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();

    String imageID;//from   ww w .  ja v a 2 s  .c o  m
    String outpath;
    String friendlyname;
    final Set<String> exts = new HashSet<String>();

    if ("-f".equals(otherArgs[0])) {
        if (otherArgs.length != 4) {
            die();
        }

        // load extensions from file
        final Path extpath = new Path(otherArgs[1]);

        InputStream in = null;
        try {
            in = extpath.getFileSystem(conf).open(extpath);

            Reader r = null;
            try {
                r = new InputStreamReader(in);

                BufferedReader br = null;
                try {
                    br = new BufferedReader(r);

                    String line;
                    while ((line = br.readLine()) != null) {
                        exts.add(line.trim().toLowerCase());
                    }

                    br.close();
                } finally {
                    IOUtils.closeQuietly(br);
                }

                r.close();
            } finally {
                IOUtils.closeQuietly(r);
            }

            in.close();
        } finally {
            IOUtils.closeQuietly(in);
        }

        imageID = otherArgs[2];
        friendlyname = otherArgs[3];
        outpath = otherArgs[4];
    } else {
        if (otherArgs.length < 3) {
            die();
        }

        // read extensions from trailing args
        imageID = otherArgs[0];
        friendlyname = otherArgs[1];
        outpath = otherArgs[2];

        // lowercase all file extensions
        for (int i = 2; i < otherArgs.length; ++i) {
            exts.add(otherArgs[i].toLowerCase());
        }
    }

    conf.setStrings("extensions", exts.toArray(new String[exts.size()]));

    final Job job = SKJobFactory.createJobFromConf(imageID, friendlyname, "SequenceFileExport", conf);
    job.setJarByClass(SequenceFileExport.class);
    job.setMapperClass(SequenceFileExportMapper.class);
    job.setNumReduceTasks(0);

    job.setOutputKeyClass(BytesWritable.class);
    job.setOutputValueClass(MapWritable.class);

    job.setInputFormatClass(FsEntryHBaseInputFormat.class);
    FsEntryHBaseInputFormat.setupJob(job, imageID);

    job.setOutputFormatClass(SequenceFileOutputFormat.class);
    SequenceFileOutputFormat.setOutputCompressionType(job, SequenceFile.CompressionType.BLOCK);

    FileOutputFormat.setOutputPath(job, new Path(outpath));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
}

From source file:examples.nntp.ArticleReader.java

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

    if (args.length != 2 && args.length != 3 && args.length != 5) {
        System.out.println(//from  w w  w  .  j a  v  a  2  s  . c  om
                "Usage: MessageThreading <hostname> <groupname> [<article specifier> [<user> <password>]]");
        return;
    }

    String hostname = args[0];
    String newsgroup = args[1];
    // Article specifier can be numeric or Id in form <m.n.o.x@host>
    String articleSpec = args.length >= 3 ? args[2] : null;

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

    if (args.length == 5) { // Optional auth
        String user = args[3];
        String password = args[4];
        if (!client.authenticate(user, password)) {
            System.out.println("Authentication failed for user " + user + "!");
            System.exit(1);
        }
    }

    NewsgroupInfo group = new NewsgroupInfo();
    client.selectNewsgroup(newsgroup, group);

    BufferedReader br;
    String line;
    if (articleSpec != null) {
        br = (BufferedReader) client.retrieveArticleHeader(articleSpec);
    } else {
        long articleNum = group.getLastArticleLong();
        br = client.retrieveArticleHeader(articleNum);
    }
    if (br != null) {
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        br.close();
    }
    if (articleSpec != null) {
        br = (BufferedReader) client.retrieveArticleBody(articleSpec);
    } else {
        long articleNum = group.getLastArticleLong();
        br = client.retrieveArticleBody(articleNum);
    }
    if (br != null) {
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
        br.close();
    }
}

From source file:HelloSmartsheet.java

public static void main(String[] args) {
    HttpURLConnection connection = null;
    StringBuilder response = new StringBuilder();

    //We are using Jackson JSON parser to deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome
    //Feel free to use which ever library you prefer.
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    try {/*w  ww  .jav a  2 s . co  m*/

        System.out.println("STARTING HelloSmartsheet...");
        //Create a BufferedReader to read user input.
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter Smartsheet API access token:");
        String accessToken = in.readLine();
        System.out.println("Fetching list of your sheets...");
        //Create a connection and fetch the list of sheets
        connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection();
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        //Read the response line by line.
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        //Use Jackson to conver the JSON string to a List of Sheets
        List<Sheet> sheets = mapper.readValue(response.toString(), new TypeReference<List<Sheet>>() {
        });
        if (sheets.size() == 0) {
            System.out.println("You don't have any sheets.  Goodbye!");
            return;
        }
        System.out.println("Total sheets: " + sheets.size());
        int i = 1;
        for (Sheet sheet : sheets) {
            System.out.println(i++ + ": " + sheet.name);
        }
        System.out.print("Enter the number of the sheet you want to share: ");

        //Prompt the user to provide the sheet number, the email address, and the access level
        Integer sheetNumber = Integer.parseInt(in.readLine().trim()); //NOTE: for simplicity, error handling and input validation is neglected.
        Sheet chosenSheet = sheets.get(sheetNumber - 1);

        System.out.print("Enter an email address to share " + chosenSheet.getName() + " to: ");
        String email = in.readLine();

        System.out.print("Choose an access level (VIEWER, EDITOR, EDITOR_SHARE, ADMIN) for " + email + ": ");
        String accessLevel = in.readLine();

        //Create a share object
        Share share = new Share();
        share.setEmail(email);
        share.setAccessLevel(accessLevel);

        System.out.println("Sharing " + chosenSheet.name + " to " + email + " as " + accessLevel + ".");

        //Create a connection. Note the SHARE_SHEET_URL uses /sheet as opposed to /sheets (with an 's')
        connection = (HttpURLConnection) new URL(SHARE_SHEET_URL.replace(SHEET_ID, "" + chosenSheet.getId()))
                .openConnection();
        connection.setDoOutput(true);
        connection.addRequestProperty("Authorization", "Bearer " + accessToken);
        connection.addRequestProperty("Content-Type", "application/json");

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        //Serialize the Share object
        writer.write(mapper.writeValueAsString(share));
        writer.close();

        //Read the response and parse the JSON
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }

        Result result = mapper.readValue(response.toString(), Result.class);
        System.out.println("Sheet shared successfully, share ID " + result.result.id);
        System.out.println("Press any key to quit.");
        in.read();

    } catch (IOException e) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(((HttpURLConnection) connection).getErrorStream()));
        String line;
        try {
            response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            Result result = mapper.readValue(response.toString(), Result.class);
            System.out.println(result.message);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    } catch (Exception e) {
        System.out.println("Something broke: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:de.binfalse.jatter.App.java

/**
 * Run jatter's main.// w  w  w .j a v  a2 s  . com
 *
 * @param args
 *          the arguments
 * @throws Exception
 *           the exception
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();

    Option conf = new Option("c", "config", true, "config file path");
    conf.setRequired(false);
    options.addOption(conf);

    Option t = new Option("t", "template", false, "show a config template");
    t.setRequired(false);
    options.addOption(t);

    Option v = new Option("v", "verbose", false, "print information messages");
    v.setRequired(false);
    options.addOption(v);

    Option d = new Option("d", "debug", false, "print debugging messages incl stack traces");
    d.setRequired(false);
    options.addOption(d);

    Option h = new Option("h", "help", false, "show help");
    h.setRequired(false);
    options.addOption(h);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h"))
            throw new RuntimeException("showing the help page");
    } catch (Exception e) {
        help(options, e.getMessage());
        return;
    }

    if (cmd.hasOption("t")) {
        System.out.println();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                App.class.getClassLoader().getResourceAsStream("config.properties.template")));
        while (br.ready())
            System.out.println(br.readLine());
        br.close();
        System.exit(0);
    }

    if (cmd.hasOption("v"))
        LOGGER.setMinLevel(LOGGER.INFO);

    if (cmd.hasOption("d")) {
        LOGGER.setMinLevel(LOGGER.DEBUG);
        LOGGER.setLogStackTrace(true);
    }

    if (!cmd.hasOption("c"))
        help(options, "a config file is required for running jatter");

    startJatter(cmd.getOptionValue("c"));
}

From source file:com.yahoo.semsearch.fastlinking.EntityContextFastEntityLinker.java

/**
 * Context-aware command line entity linker
 * @param args arguments (see -help for further info)
 * @throws Exception//from  w ww.  j  a va2 s .  com
 */
public static void main(String args[]) throws Exception {
    SimpleJSAP jsap = new SimpleJSAP(EntityContextFastEntityLinker.class.getName(),
            "Interactive mode for entity linking",
            new Parameter[] {
                    new FlaggedOption("hash", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'h', "hash",
                            "quasi succint hash"),
                    new FlaggedOption("vectors", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'v',
                            "vectors", "Word vectors file"),
                    new FlaggedOption("labels", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'l',
                            "labels", "File containing query2entity labels"),
                    new FlaggedOption("id2type", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'i',
                            "id2type", "File with the id2type mapping"),
                    new Switch("centroid", 'c', "centroid", "Use centroid-based distances and not LR"),
                    new FlaggedOption("map", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'm', "map",
                            "Entity 2 type mapping "),
                    new FlaggedOption("threshold", JSAP.STRING_PARSER, "-20", JSAP.NOT_REQUIRED, 'd',
                            "threshold", "Score threshold value "),
                    new FlaggedOption("entities", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'e',
                            "entities", "Entities word vectors file"), });

    JSAPResult jsapResult = jsap.parse(args);
    if (jsap.messagePrinted())
        return;

    double threshold = Double.parseDouble(jsapResult.getString("threshold"));
    QuasiSuccinctEntityHash hash = (QuasiSuccinctEntityHash) BinIO.loadObject(jsapResult.getString("hash"));
    EntityContext queryContext;
    if (!jsapResult.getBoolean("centroid")) {
        queryContext = new LREntityContext(jsapResult.getString("vectors"), jsapResult.getString("entities"),
                hash);
    } else {
        queryContext = new CentroidEntityContext(jsapResult.getString("vectors"),
                jsapResult.getString("entities"), hash);
    }
    HashMap<String, ArrayList<EntityRelevanceJudgment>> labels = null;
    if (jsapResult.getString("labels") != null) {
        labels = readTrainingData(jsapResult.getString("labels"));
    }

    String map = jsapResult.getString("map");

    HashMap<String, String> entities2Type = null;

    if (map != null)
        entities2Type = readEntity2IdFile(map);

    EntityContextFastEntityLinker linker = new EntityContextFastEntityLinker(hash, queryContext);

    final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String q;
    for (;;) {
        System.out.print(">");
        q = br.readLine();
        if (q == null) {
            System.err.println();
            break; // CTRL-D
        }
        if (q.length() == 0)
            continue;
        long time = -System.nanoTime();
        try {
            List<EntityResult> results = linker.getResults(q, threshold);
            //List<EntityResult> results = linker.getResultsGreedy( q, 5 );
            //int rank = 0;

            for (EntityResult er : results) {
                if (entities2Type != null) {
                    String name = er.text.toString().trim();
                    String newType = entities2Type.get(name);
                    if (newType == null)
                        newType = "NF";
                    System.out.println(q + "\t span: \u001b[1m [" + er.text + "] \u001b[0m eId: " + er.id
                            + " ( t= " + newType + ")" + "  score: " + er.score + " ( " + er.s.span + " ) ");

                    //System.out.println( newType + "\t" + q + "\t" + StringUtils.remove( q, er.s.span.toString() ) + " \t " + er.text );
                    break;
                    /* } else {
                       System.out.print( "[" + er.text + "(" + String.format("%.2f",er.score) +")] ");
                    System.out.println( "span: \u001b[1m [" + er.text + "] \u001b[0m eId: " + er.id + " ( t= " + typeMapping.get( hash.getEntity( er.id ).type )
                    + "  score: " + er.score + " ( " + er.s.span + " ) " );
                    }
                    rank++;
                    */
                } else {
                    if (labels == null) {
                        System.out.println(q + "\t" + er.text + "\t" + er.score);
                    } else {
                        ArrayList<EntityRelevanceJudgment> jds = labels.get(q);
                        String label = "NF";
                        if (jds != null) {
                            EntityRelevanceJudgment relevanceOfEntity = relevanceOfEntity(er.text, jds);
                            label = relevanceOfEntity.label;
                        }
                        System.out.println(q + "\t" + er.text + "\t" + label + "\t" + er.score);
                        break;
                    }
                }
                System.out.println();
            }
            time += System.nanoTime();
            System.out.println("Time to rank and print the candidates:" + time / 1000000. + " ms");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.datastax.sparql.ConsoleCompiler.java

public static void main(final String[] args) throws IOException {
    //args = "/examples/modern1.sparql";
    final Options options = new Options();
    options.addOption("f", "file", true, "a file that contains a SPARQL query");
    options.addOption("g", "graph", true,
            "the graph that's used to execute the query [classic|modern|crew|kryo file]");
    // TODO: add an OLAP option (perhaps: "--olap spark"?)

    final CommandLineParser parser = new DefaultParser();
    final CommandLine commandLine;

    try {//  www  .  ja  v a  2  s .  c om
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printHelp(1);
        return;
    }

    final InputStream inputStream = commandLine.hasOption("file")
            ? new FileInputStream(commandLine.getOptionValue("file"))
            : System.in;
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    final StringBuilder queryBuilder = new StringBuilder();

    if (!reader.ready()) {
        printHelp(1);
    }

    String line;
    while (null != (line = reader.readLine())) {
        queryBuilder.append(System.lineSeparator()).append(line);
    }

    final String queryString = queryBuilder.toString();
    final Graph graph;

    if (commandLine.hasOption("graph")) {
        switch (commandLine.getOptionValue("graph").toLowerCase()) {
        case "classic":
            graph = TinkerFactory.createClassic();
            break;
        case "modern":
            graph = TinkerFactory.createModern();
            System.out.println("Modern Graph Created");
            break;
        case "crew":
            graph = TinkerFactory.createTheCrew();
            break;
        default:
            graph = TinkerGraph.open();
            System.out.println("Graph Created");
            long startTime = System.nanoTime();
            graph.io(IoCore.gryo()).readGraph(commandLine.getOptionValue("graph"));
            long endTime = System.nanoTime();
            System.out.println("Time taken to load graph from kyro file: " + (endTime - startTime) / 1000000
                    + " mili seconds");
            break;
        }
    } else {

        graph = TinkerFactory.createModern();
    }

    final Traversal<Vertex, ?> traversal = SparqlToGremlinCompiler.convertToGremlinTraversal(graph,
            queryString);

    printWithHeadline("SPARQL Query", queryString);
    printWithHeadline("Traversal (prior execution)", traversal);

    Bytecode traversalByteCode = traversal.asAdmin().getBytecode();

    //JavaTranslator.of(graph.traversal()).translate(traversalByteCode);

    System.out.println("the Byte Code : " + traversalByteCode.toString());
    printWithHeadline("Result", String.join(System.lineSeparator(), JavaTranslator.of(graph.traversal())
            .translate(traversalByteCode).toStream().map(Object::toString).collect(Collectors.toList())));
    printWithHeadline("Traversal (after execution)", traversal);
}

From source file:com.googlecode.shutdownlistener.ShutdownUtility.java

public static void main(String[] args) throws Exception {
    final ShutdownConfiguration config = ShutdownConfiguration.getInstance();

    final String command;
    if (args.length > 0) {
        command = args[0];/*from  ww w .  j a v  a2  s  .c  o m*/
    } else {
        command = config.getStatusCommand();
    }

    System.out.println("Calling " + config.getHost() + ":" + config.getPort() + " with command: " + command);

    final InetAddress hostAddress = InetAddress.getByName(config.getHost());
    final Socket shutdownConnection = new Socket(hostAddress, config.getPort());
    try {
        shutdownConnection.setSoTimeout(5000);
        final BufferedReader reader = new BufferedReader(
                new InputStreamReader(shutdownConnection.getInputStream()));
        final PrintStream writer = new PrintStream(shutdownConnection.getOutputStream());
        try {
            writer.println(command);
            writer.flush();

            while (true) {
                final String line = reader.readLine();
                if (line == null) {
                    break;
                }

                System.out.println(line);
            }
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(writer);
        }
    } finally {
        try {
            shutdownConnection.close();
        } catch (IOException ioe) {
        }
    }

}

From source file:GetMessageExample.java

public static void main(String args[]) throws Exception {
    if (args.length != 3) {
        System.err.println("Usage: java MailExample host username password");
        System.exit(-1);// w w  w.j ava  2  s  .c  om
    }

    String host = args[0];
    String username = args[1];
    String password = args[2];

    // Create empty properties
    Properties props = new Properties();

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    // Get the store
    Store store = session.getStore("pop3");
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");
    folder.open(Folder.READ_ONLY);

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

    // Get directory
    Message message[] = folder.getMessages();
    for (int i = 0, n = message.length; i < n; i++) {
        System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject());

        System.out.println("Read message? [YES to read/QUIT to end]");
        String line = reader.readLine();
        if ("YES".equalsIgnoreCase(line)) {
            System.out.println(message[i].getContent());
        } else if ("QUIT".equalsIgnoreCase(line)) {
            break;
        }
    }

    // Close connection
    folder.close(false);
    store.close();
}