Example usage for java.io BufferedReader BufferedReader

List of usage examples for java.io BufferedReader BufferedReader

Introduction

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

Prototype

public BufferedReader(Reader in) 

Source Link

Document

Creates a buffering character-input stream that uses a default-sized input buffer.

Usage

From source file:com.manning.blogapps.chapter10.examples.AuthPostJava.java

public static void main(String[] args) throws Exception {
    if (args.length < 4) {
        System.out.println("USAGE: authpost <username> <password> <filepath> <url>");
        System.exit(-1);/*from  w  w w  .  j a v  a  2 s . c  om*/
    }
    String credentials = args[0] + ":" + args[1];
    String filepath = args[2];

    URL url = new URL(args[3]);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    conn.setRequestProperty("Authorization",
            "Basic " + new String(Base64.encodeBase64(credentials.getBytes())));

    File upload = new File(filepath);
    conn.setRequestProperty("name", upload.getName());

    String contentType = "application/atom+xml; charset=utf8";
    if (filepath.endsWith(".gif"))
        contentType = "image/gif";
    else if (filepath.endsWith(".jpg"))
        contentType = "image/jpg";
    conn.setRequestProperty("Content-type", contentType);

    BufferedInputStream filein = new BufferedInputStream(new FileInputStream(upload));
    BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());
    byte buffer[] = new byte[8192];
    for (int count = 0; count != -1;) {
        count = filein.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }
    filein.close();
    out.close();

    String s = null;
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    while ((s = in.readLine()) != null) {
        System.out.println(s);
    }
}

From source file:com.wordnik.swaggersocket.samples.NettoSphere.java

public static void main(String[] args) throws IOException {
    ReflectorServletProcessor rsp = new ReflectorServletProcessor();
    rsp.setServletClassName(CXFNonSpringJaxrsServlet.class.getName());

    int p = getHttpPort();
    Config.Builder b = new Config.Builder();
    b.resource("./app").initParam(ApplicationConfig.WEBSOCKET_CONTENT_TYPE, "application/json")
            .initParam(ApplicationConfig.WEBSOCKET_METHOD, "POST")
            .initParam("jaxrs.serviceClasses",
                    SwaggerSocketResource.class.getName() + "," + FileServiceResource.class.getName())
            .initParam("jaxrs.providers", JacksonJsonProvider.class.getName())
            .initParam("com.wordnik.swaggersocket.protocol.lazywrite", "true")
            .initParam("com.wordnik.swaggersocket.protocol.emptyentity", "true")
            .interceptor(new SwaggerSocketProtocolInterceptor()).resource("/*", rsp).port(p).host("127.0.0.1")
            .build();/* www. ja  v  a2s.  c  om*/
    Nettosphere s = new Nettosphere.Builder().config(b.build()).build();
    s.start();
    String a = "";

    logger.info("NettoSphere SwaggerSocket Server started on port {}", p);
    logger.info("Type quit to stop the server");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (!(a.equals("quit"))) {
        a = br.readLine();
    }
    System.exit(-1);
}

From source file:com.hilatest.httpclient.apacheexample.ClientConnectionRelease.java

public final static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();

    HttpGet httpget = new HttpGet("http://www.apache.org/");

    // Execute HTTP request
    System.out.println("executing request " + httpget.getURI());
    HttpResponse response = httpclient.execute(httpget);

    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    System.out.println("----------------------------------------");

    // Get hold of the response entity
    HttpEntity entity = response.getEntity();

    // If the response does not enclose an entity, there is no need
    // to bother about connection release
    if (entity != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
        try {//from w ww  .j  a  v  a2s  . c  o m

            // do something useful with the response
            System.out.println(reader.readLine());

        } catch (IOException ex) {

            // In case of an IOException the connection will be released
            // back to the connection manager automatically
            throw ex;

        } catch (RuntimeException ex) {

            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying 
            // connection and release it back to the connection manager.
            httpget.abort();
            throw ex;

        } finally {

            // Closing the input stream will trigger connection release
            reader.close();

        }
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:com.trendmicro.hdfs.webdav.tool.Get.java

public static void main(String[] args) throws Exception {
    // Process command line 

    Options options = new Options();
    options.addOption("d", "debug", false, "Enable debug logging");

    CommandLine cmd = null;/*from   w ww  .  j ava  2  s  .c  om*/
    try {
        cmd = new PosixParser().parse(options, args);
    } catch (ParseException e) {
        printUsageAndExit(options, -1);
    }
    boolean debug = cmd.hasOption('d');
    args = cmd.getArgs();
    if (args.length < 1) {
        printUsageAndExit(options, -1);
    }

    // Do the fetch

    AuthenticatedURL.Token token = new AuthenticatedURL.Token();
    AuthenticatedURL url = new AuthenticatedURL();
    HttpURLConnection conn = url.openConnection(new URL(args[0]), token);
    if (debug) {
        System.out.println("Token value: " + token);
        System.out.println("Status code: " + conn.getResponseCode() + " " + conn.getResponseMessage());
    }
    if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = reader.readLine();
        while (line != null) {
            System.out.println(line);
            line = reader.readLine();
        }
        reader.close();
    }
    System.out.println();
}

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  ww .j  a  v a  2  s  .co  m
                "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:com.asual.lesscss.LessEngineCli.java

public static void main(String[] args) throws LessException, URISyntaxException {
    Options cmdOptions = new Options();
    cmdOptions.addOption(LessOptions.CHARSET_OPTION, true, "Input file charset encoding. Defaults to UTF-8.");
    cmdOptions.addOption(LessOptions.COMPRESS_OPTION, false, "Flag that enables compressed CSS output.");
    cmdOptions.addOption(LessOptions.CSS_OPTION, false, "Flag that enables compilation of .css files.");
    cmdOptions.addOption(LessOptions.LESS_OPTION, true, "Path to a custom less.js for Rhino version.");
    try {// w ww . j  a v a2  s  .c om
        CommandLineParser cmdParser = new GnuParser();
        CommandLine cmdLine = cmdParser.parse(cmdOptions, args);
        LessOptions options = new LessOptions();
        if (cmdLine.hasOption(LessOptions.CHARSET_OPTION)) {
            options.setCharset(cmdLine.getOptionValue(LessOptions.CHARSET_OPTION));
        }
        if (cmdLine.hasOption(LessOptions.COMPRESS_OPTION)) {
            options.setCompress(true);
        }
        if (cmdLine.hasOption(LessOptions.CSS_OPTION)) {
            options.setCss(true);
        }
        if (cmdLine.hasOption(LessOptions.LESS_OPTION)) {
            options.setLess(new File(cmdLine.getOptionValue(LessOptions.LESS_OPTION)).toURI().toURL());
        }
        LessEngine engine = new LessEngine(options);
        if (System.in.available() != 0) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringWriter sw = new StringWriter();
            char[] buffer = new char[1024];
            int n = 0;
            while (-1 != (n = in.read(buffer))) {
                sw.write(buffer, 0, n);
            }
            String src = sw.toString();
            if (!src.isEmpty()) {
                System.out.println(engine.compile(src, null, options.isCompress()));
                System.exit(0);
            }
        }
        String[] files = cmdLine.getArgs();
        if (files.length == 1) {
            System.out.println(engine.compile(new File(files[0]), options.isCompress()));
            System.exit(0);
        }
        if (files.length == 2) {
            engine.compile(new File(files[0]), new File(files[1]), options.isCompress());
            System.exit(0);
        }

    } catch (IOException ioe) {
        System.err.println("Error opening input file.");
    } catch (ParseException pe) {
        System.err.println("Error parsing arguments.");
    }
    String[] paths = LessEngine.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()
            .split(File.separator);
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("java -jar " + paths[paths.length - 1] + " input [output] [options]", cmdOptions);
    System.exit(1);
}

From source file:Reverse.java

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

    if (args.length != 1) {
        System.err.println("Usage:  java Reverse " + "string_to_reverse");
        System.exit(1);//from   ww  w  .ja  va  2  s  .  c o m
    }

    String stringToReverse = URLEncoder.encode(args[0]);

    URL url = new URL("http://java.sun.com/cgi-bin/backwards");
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());
    out.println("string=" + stringToReverse);
    out.close();

    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String inputLine;

    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

    in.close();
}

From source file:bluevia.examples.MODemo.java

/**
 * @param args/*from   w w w  .  j av  a2  s. c  om*/
 */
public static void main(String[] args) throws IOException {

    BufferedReader iReader = null;
    String apiDataFile = "API-AccessToken.ini";

    String consumer_key;
    String consumer_secret;
    String registrationId;

    OAuthConsumer apiConsumer = null;
    HttpURLConnection request = null;
    URL moAPIurl = null;

    Logger logger = Logger.getLogger("moSMSDemo.class");
    int i = 0;
    int rc = 0;

    Thread mThread = Thread.currentThread();

    try {
        System.setProperty("debug", "1");

        iReader = new BufferedReader(new FileReader(apiDataFile));

        // Private data: consumer info + access token info + phone info
        consumer_key = iReader.readLine();
        consumer_secret = iReader.readLine();
        registrationId = iReader.readLine();

        // Set up the oAuthConsumer
        while (true) {
            try {

                logger.log(Level.INFO, String.format("#%d: %s\n", ++i, "Requesting messages..."));

                apiConsumer = new DefaultOAuthConsumer(consumer_key, consumer_secret);

                apiConsumer.setMessageSigner(new HmacSha1MessageSigner());

                moAPIurl = new URL("https://api.bluevia.com/services/REST/SMS/inbound/" + registrationId
                        + "/messages?version=v1&alt=json");

                request = (HttpURLConnection) moAPIurl.openConnection();
                request.setRequestMethod("GET");

                apiConsumer.sign(request);

                StringBuffer doc = new StringBuffer();
                BufferedReader br = null;

                rc = request.getResponseCode();
                if (rc == HttpURLConnection.HTTP_OK) {
                    br = new BufferedReader(new InputStreamReader(request.getInputStream()));

                    String line = br.readLine();
                    while (line != null) {
                        doc.append(line);
                        line = br.readLine();
                    }

                    System.out.printf("Output message: %s\n", doc.toString());
                    try {
                        JSONObject apiResponse1 = new JSONObject(doc.toString());
                        String aux = apiResponse1.getString("receivedSMS");
                        if (aux != null) {
                            String szMessage;
                            String szOrigin;
                            String szDate;

                            JSONObject smsPool = apiResponse1.getJSONObject("receivedSMS");
                            JSONArray smsInfo = smsPool.optJSONArray("receivedSMS");
                            if (smsInfo != null) {
                                for (i = 0; i < smsInfo.length(); i++) {
                                    szMessage = smsInfo.getJSONObject(i).getString("message");
                                    szOrigin = smsInfo.getJSONObject(i).getJSONObject("originAddress")
                                            .getString("phoneNumber");
                                    szDate = smsInfo.getJSONObject(i).getString("dateTime");
                                    System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate,
                                            szOrigin, szMessage);
                                }
                            } else {
                                JSONObject sms = smsPool.getJSONObject("receivedSMS");
                                szMessage = sms.getString("message");
                                szOrigin = sms.getJSONObject("originAddress").getString("phoneNumber");
                                szDate = sms.getString("dateTime");
                                System.out.printf("#%d %s\n - from %s\n - message:%s\n", i, szDate, szOrigin,
                                        szMessage);
                            }
                        }
                    } catch (JSONException e) {
                        System.err.println("JSON error: " + e.getMessage());
                    }

                } else if (rc == HttpURLConnection.HTTP_NO_CONTENT)
                    System.out.printf("No content\n");
                else
                    System.err.printf("Error: %d:%s\n", rc, request.getResponseMessage());

                request.disconnect();

            } catch (Exception e) {
                System.err.println("Exception: " + e.getMessage());
            }
            mThread.sleep(15000);
        }
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
    }
}

From source file:edu.cmu.lti.oaqa.bio.index.medline.annotated.query.SimpleQueryApp.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("u", null, true, "Solr URI");
    options.addOption("n", null, true, "Max # of results");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    try {/* www.  ja  v a2 s.  c om*/
        CommandLine cmd = parser.parse(options, args);
        String solrURI = null;

        solrURI = cmd.getOptionValue("u");
        if (solrURI == null) {
            Usage("Specify Solr URI");
        }

        SolrServerWrapper solr = new SolrServerWrapper(solrURI);

        int numRet = 10;

        if (cmd.hasOption("n")) {
            numRet = Integer.parseInt(cmd.getOptionValue("n"));
        }

        List<String> fieldList = new ArrayList<String>();
        fieldList.add(UtilConstMedline.ID_FIELD);
        fieldList.add(UtilConstMedline.SCORE_FIELD);
        fieldList.add(UtilConstMedline.ARTICLE_TITLE_FIELD);
        fieldList.add(UtilConstMedline.ENTITIES_DESC_FIELD);
        fieldList.add(UtilConstMedline.ABSTRACT_TEXT_FIELD);

        BufferedReader sysInReader = new BufferedReader(new InputStreamReader(System.in));
        Joiner commaJoiner = Joiner.on(',');

        while (true) {
            System.out.println("Input query: ");
            String query = sysInReader.readLine();
            if (null == query)
                break;

            QueryTransformer qt = new QueryTransformer(query);

            String tranQuery = qt.getQuery();

            System.out.println("Translated query:");
            System.out.println(tranQuery);
            System.out.println("=========================");

            SolrDocumentList res = solr.runQuery(tranQuery, fieldList, numRet);

            System.out.println("Found " + res.getNumFound() + " entries");

            for (SolrDocument doc : res) {
                String id = (String) doc.getFieldValue(UtilConstMedline.ID_FIELD);
                float score = (Float) doc.getFieldValue(UtilConstMedline.SCORE_FIELD);
                String title = (String) doc.getFieldValue(UtilConstMedline.ARTICLE_TITLE_FIELD);
                String titleAbstract = (String) doc.getFieldValue(UtilConstMedline.ABSTRACT_TEXT_FIELD);

                System.out.println(score + " PMID=" + id + " " + titleAbstract);

                String entityDesc = (String) doc.getFieldValue(UtilConstMedline.ENTITIES_DESC_FIELD);
                System.out.println("Entities:");
                for (EntityEntry e : EntityEntry.parseEntityDesc(entityDesc)) {
                    System.out.println(String.format("[%d %d] concept=%s concept_ids=%s", e.mStart, e.mEnd,
                            e.mConcept, commaJoiner.join(e.mConceptIds)));
                }
            }
        }

        solr.close();

    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:org.salever.rcp.remoteSystem.server.util.ClientAbortMethod.java

public final static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    try {//  w w w. j  a  v a  2  s.co m

        String queryString = "wd=?ddd=";
        String decodeUrl = URLEncoder.encode(queryString, "GBK");
        String string = new String(decodeUrl);
        System.out.println("--------------" + string + "--------------------------");
        HttpGet httpget = new HttpGet("http://www.baidu.com/s?" + string);

        System.out.println("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line;
            while ((line = reader.readLine()) != null) {
                // System.out.println(line);
            }
        }
        System.out.println("----------------------------------------");

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}