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.tbodt.trp.TheRapidPermuter.java

/**
 * Main method for The Rapid Permuter.//from  w  ww  .  jav a 2  s .  com
 *
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    CommandProcessor.processCommand("\"\": remove(\"\") in([words])").ifPresent(x -> x.forEach(y -> {
    })); // to load all the classes we need

    try {
        cmd = new BasicParser().parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        return;
    }

    if (Arrays.asList(cmd.getOptions()).contains(help)) { // another way commons cli is severely broken
        new HelpFormatter().printHelp("trp", options);
        return;
    }

    if (cmd.hasOption('c'))
        doCommand(cmd.getOptionValue('c'));
    else {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("trp> ");
        String input;
        while ((input = in.readLine()) != null) {
            if (input.equals("exit"))
                return; // exit
            doCommand(input);
            System.out.print("trp> ");
        }
    }
}

From source file:com.anteam.demo.logback.PostDemo.java

public static void main(String[] args) {
    StringEntity stringEntity = new StringEntity("this is the log2.",
            ContentType.create("text/plain", "UTF-8"));
    HttpPost post = new HttpPost("http://10.16.0.207:9000");
    post.setEntity(stringEntity);/*from  w w  w .j a  va2s  .c  o  m*/
    HttpClient httpclient = new DefaultHttpClient();

    // Execute the request
    HttpResponse response = null;
    try {
        response = httpclient.execute(post);
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Examine the response status
    System.out.println(response.getStatusLine());

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

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = null;
        try {
            instream = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // do something useful with the response
            System.out.println(reader.readLine());

        } catch (Exception ex) {
            post.abort();

        } finally {

            try {
                instream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.anteam.demo.httpclient.PostDemo.java

public static void main(String[] args) {
    StringEntity stringEntity = new StringEntity("this is the log2.",
            ContentType.create("text/plain", "UTF-8"));
    HttpPost post = new HttpPost("http://127.0.0.1:9000");
    post.setEntity(stringEntity);/*from w  w w . ja  v a 2  s  .c  o  m*/
    HttpClient httpclient = new DefaultHttpClient();

    // Execute the request
    HttpResponse response = null;
    try {
        response = httpclient.execute(post);
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Examine the response status
    System.out.println(response.getStatusLine());

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

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = null;
        try {
            instream = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // do something useful with the response
            System.out.println(reader.readLine());

        } catch (Exception ex) {
            post.abort();

        } finally {

            try {
                instream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.twentyn.chemicalClassifier.Runner.java

public static void main(String[] args) throws Exception {
    BufferedReader reader = new BufferedReader(new FileReader(args[0]));
    BufferedWriter writer = new BufferedWriter(new FileWriter(args[1]));

    try {//from   w ww. ja va  2 s  .  c  o  m
        Oscar oscar = new Oscar();

        String line = null;
        /* NOTE: this is exactly the wrong way to write a TSV reader.  Caveat emptor.
         * See http://tburette.github.io/blog/2014/05/25/so-you-want-to-write-your-own-CSV-code/
         * and then use org.apache.commons.csv.CSVParser instead.
         */
        while ((line = reader.readLine()) != null) {
            // TSV means split on tabs!  Nothing else will do.
            List<String> fields = Arrays.asList(line.split("\t"));
            // Choke if our invariants aren't satisfied.  We expect ever line to have a name and an InChI.
            if (fields.size() != 2) {
                throw new RuntimeException(
                        String.format("Found malformed line (all lines must have two fields: %s", line));
            }
            String name = fields.get(1);
            List<ResolvedNamedEntity> entities = oscar.findAndResolveNamedEntities(name);

            System.out.println("**********");
            System.out.println("Name: " + name);
            List<String> outputFields = new ArrayList<>(fields.size() + 1);
            outputFields.addAll(fields);
            if (entities.size() == 0) {
                System.out.println("No match");
                outputFields.add("noMatch");
            } else if (entities.size() == 1) {
                ResolvedNamedEntity entity = entities.get(0);
                NamedEntity ne = entity.getNamedEntity();
                if (ne.getStart() != 0 || ne.getEnd() != name.length()) {
                    System.out.println("Partial match");
                    printEntity(entity);
                    outputFields.add("partialMatch");
                } else {
                    System.out.println("Exact match");
                    printEntity(entity);
                    outputFields.add("exactMatch");
                    List<ChemicalStructure> structures = entity.getChemicalStructures(FormatType.STD_INCHI);
                    for (ChemicalStructure s : structures) {
                        outputFields.add(s.getValue());
                    }
                }
            } else { // Multiple matches found!
                System.out.println("Multiple matches");
                for (ResolvedNamedEntity e : entities) {
                    printEntity(e);
                }
                outputFields.add("multipleMatches");
            }

            writer.write(String.join("\t", outputFields));
            writer.newLine();
        }
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:Naive.java

public static void main(String[] args) throws Exception {
    // Basic access authentication setup
    String key = "CHANGEME: YOUR_API_KEY";
    String secret = "CHANGEME: YOUR_API_SECRET";
    String version = "preview1"; // CHANGEME: the API version to use
    String practiceid = "000000"; // CHANGEME: the practice ID to use

    // Find the authentication path
    Map<String, String> auth_prefix = new HashMap<String, String>();
    auth_prefix.put("v1", "oauth");
    auth_prefix.put("preview1", "oauthpreview");
    auth_prefix.put("openpreview1", "oauthopenpreview");

    URL authurl = new URL("https://api.athenahealth.com/" + auth_prefix.get(version) + "/token");

    HttpURLConnection conn = (HttpURLConnection) authurl.openConnection();
    conn.setRequestMethod("POST");

    // Set the Authorization request header
    String auth = Base64.encodeBase64String((key + ':' + secret).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + auth);

    // Since this is a POST, the parameters go in the body
    conn.setDoOutput(true);/*from  www.  j  a va 2s.  c  om*/
    String contents = "grant_type=client_credentials";
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    // Read the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    // Decode from JSON and save the token for later
    String response = sb.toString();
    JSONObject authorization = new JSONObject(response);
    String token = authorization.get("access_token").toString();

    // GET /departments
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("limit", "1");

    // Set up the URL, method, and Authorization header
    URL url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/departments" + "?"
            + urlencode(params));
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject departments = new JSONObject(response);
    System.out.println(departments.toString());

    // POST /appointments/{appointmentid}/notes
    params = new HashMap<String, String>();
    params.put("notetext", "Hello from Java!");

    url = new URL("https://api.athenahealth.com/" + version + "/" + practiceid + "/appointments/1/notes");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Bearer " + token);

    // POST parameters go in the body
    conn.setDoOutput(true);
    contents = urlencode(params);
    wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(contents);
    wr.flush();
    wr.close();

    rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    sb = new StringBuilder();
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    response = sb.toString();
    JSONObject note = new JSONObject(response);
    System.out.println(note.toString());
}

From source file:org.kuali.kfs.rest.AccountingPeriodCloseJob.java

public static void main(String[] args) {
    try {/* ww w.j a  v a2 s. co m*/
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost("http://localhost:8080/kfs-dev/coa/accounting_periods/close");
        request.addHeader("accept", "application/json");
        request.addHeader("content-type", "application/json");
        request.addHeader("authorization", "NSA_this_is_for_you");

        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("\"description\":\"Document: The Next Generation\",");
        sb.append("\"universityFiscalYear\": 2016,");
        sb.append("\"universityFiscalPeriodCode\": \"03\"");
        sb.append("}");
        StringEntity data = new StringEntity(sb.toString());
        request.setEntity(data);

        HttpResponse response = httpClient.execute(request);

        System.out.println("Status Code: " + response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        httpClient.getConnectionManager().shutdown();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:RhymingWords.java

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

    FileReader words = new FileReader("words.txt");

    // do the reversing and sorting
    Reader rhymedWords = reverse(sort(reverse(words)));

    // write new list to standard out
    BufferedReader in = new BufferedReader(rhymedWords);
    String input;/*ww  w.  j av a 2s.co m*/

    while ((input = in.readLine()) != null)
        System.out.println(input);
    in.close();
}

From source file:Indent.java

public static void main(String[] av) {
    Indent c = new Indent();
    switch (av.length) {
    case 0:/*  w w  w  . j  av  a  2 s .com*/
        c.process(new BufferedReader(new InputStreamReader(System.in)));
        break;
    default:
        for (int i = 0; i < av.length; i++)
            try {
                c.process(new BufferedReader(new FileReader(av[i])));
            } catch (FileNotFoundException e) {
                System.err.println(e);
            }
    }
}

From source file:it.codestudio.callbyj.CallByJ.java

/**
 * The main method./*from w  ww  .  j  av  a  2 s . c o m*/
 *
 * @param args the arguments
 */
public static void main(String[] args) {
    options.addOption("aCom", "audio_com", true,
            "Specify serial COM port for audio streaming (3G APPLICATION ...)");
    options.addOption("cCom", "command_com", true,
            "Specify serial COM port for modem AT command (PC UI INTERFACE ...)");
    options.addOption("p", "play_message", false,
            "Play recorded message instead to respond with audio from mic");
    options.addOption("h", "help", false, "Print help for this application");
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String audioCOM = "";
        String commandCOM = "";
        Boolean playMessage = false;
        args = Utils.fitlerNullString(args);
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("aCom")) {
            audioCOM = cmd.getOptionValue("aCom");
            ;
        }
        if (cmd.hasOption("cCom")) {
            commandCOM = cmd.getOptionValue("cCom");
            ;
        }
        if (cmd.hasOption("p")) {
            playMessage = true;
        }
        if (audioCOM != null && commandCOM != null && !audioCOM.isEmpty() && !commandCOM.isEmpty()) {
            comManager = ComManager.getInstance(commandCOM, audioCOM, playMessage);
        } else {
            HelpFormatter f = new HelpFormatter();
            f.printHelp("\r Exaple: CallByJ -aCom COM11 -cCom COM10 \r OptionsTip", options);
            return;
        }
        options = new Options();
        options.addOption("h", "help", false, "Print help for this application");
        options.addOption("p", "pin", true, "Specify pin of device, if present");
        options.addOption("c", "call", true, "Start call to specified number");
        options.addOption("e", "end", false, "End all active call");
        options.addOption("t", "terminate", false, "Terminate application");
        options.addOption("r", "respond", false, "Respond to incoming call");
        comManager.startModemCommandManager();
        while (true) {
            try {
                String[] commands = { br.readLine() };
                commands = Utils.fitlerNullString(commands);
                cmd = parser.parse(options, commands);
                if (cmd.hasOption('h')) {
                    HelpFormatter f = new HelpFormatter();
                    f.printHelp("OptionsTip", options);
                }
                if (cmd.hasOption('p')) {
                    String devicePin = cmd.getOptionValue("p");
                    comManager.insertPin(devicePin);
                }
                if (cmd.hasOption('c')) {
                    String numberToCall = cmd.getOptionValue("c");
                    comManager.sendCommandToModem(ATCommands.CALL, numberToCall);
                }
                if (cmd.hasOption('r')) {
                    comManager.respondToIncomingCall();
                }
                if (cmd.hasOption('e')) {
                    comManager.sendCommandToModem(ATCommands.END_CALL);
                }
                if (cmd.hasOption('t')) {
                    comManager.sendCommandToModem(ATCommands.END_CALL);
                    comManager.terminate();
                    System.out.println("CallByJ closed!");
                    break;
                    //System.exit(0);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        if (comManager != null)
            comManager.terminate();
    }
}

From source file:com.cncounter.test.httpclient.ProxyTunnelDemo.java

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

    ProxyClient proxyClient = new ProxyClient();
    HttpHost target = new HttpHost("www.google.com", 80);
    HttpHost proxy = new HttpHost("localhost", 1080);
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("user", "pwd");
    Socket socket = proxyClient.tunnel(proxy, target, credentials);
    try {/* w w  w .  ja v a2 s .  c  o m*/
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Agent: whatever\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }
    } finally {
        socket.close();
    }
}