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:httpclientsample.HttpClientSample.java

/**
 * @param args the command line arguments
 *//*from ww  w.ja  v  a 2s . co m*/
public static void main(String[] args) throws IOException, JSONException {
    /** METHOD GET EXAMPLE **/
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet getRequest = new HttpGet("http://localhost:8000/test/api?id=100");
    getRequest.addHeader("accept", "application/json");

    HttpResponse response = httpClient.execute(getRequest);

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

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

    String output;
    System.out.println("Response:\n");

    while ((output = br.readLine()) != null) {
        JSONObject jsonObj = new JSONObject(output);
        System.out.println("json id : " + jsonObj.get("id"));
    }

    httpClient.getConnectionManager().shutdown();
}

From source file:net.officefloor.tutorial.javascriptapp.JavaScriptAppTest.java

/**
 * Allow running as application to manually test the JavaScript.
 *//*w ww. jav  a 2 s .  co m*/
public static void main(String[] arguments) throws Exception {
    WoofOfficeFloorSource.start();
    System.out.println("Press [enter] to exit");
    new BufferedReader(new InputStreamReader(System.in)).readLine();
    WoofOfficeFloorSource.stop();
}

From source file:cloudclient.Client.java

public static void main(String[] args) throws Exception {
    //Command interpreter
    CommandLineInterface cmd = new CommandLineInterface(args);

    String socket = cmd.getOptionValue("s");
    String Host_IP = socket.split(":")[0];
    int Port = Integer.parseInt(socket.split(":")[1]);
    String workload = cmd.getOptionValue("w");

    try {/*from w w  w .j ava2s .c  o m*/
        // make connection to server socket 
        Socket client = new Socket(Host_IP, Port);

        InputStream inStream = client.getInputStream();
        OutputStream outStream = client.getOutputStream();
        PrintWriter out = new PrintWriter(outStream, true);
        BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

        System.out.println("Send tasks to server...");
        //Start clock
        long startTime = System.currentTimeMillis();

        //Batch sending tasks
        batchSendTask(out, workload);
        client.shutdownOutput();

        //Batch receive responses
        batchReceiveResp(in);

        //End clock
        long endTime = System.currentTimeMillis();
        double totalTime = (endTime - startTime) / 1e3;

        System.out.println("\nDone!");
        System.out.println("Time to execution = " + totalTime + " sec.");

        // close the socket connection
        client.close();

    } catch (IOException ioe) {
        System.err.println(ioe);
    }

}

From source file:JSON.JasonJSON.java

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

    URL Url = new URL("http://api.wunderground.com/api/22b4347c464f868e/conditions/q/Colorado/COS.json");
    //This next URL is still being played with. Some of the formatting is hard to figure out, but Wunderground 
    //writes a perfectly formatted JSON file that is easy to read with Java.
    // URL Url = new URL("https://api.darksky.net/forecast/08959bb1e2c7eae0f3d1fafb5d538032/38.886,-104.7201");

    try {/*from   w  ww . ja va2s.  c  o  m*/

        HttpURLConnection urlCon = (HttpURLConnection) Url.openConnection();

        //          This part will read the data returned thru HTTP and load it into memory
        //          I have this code left over from my CIT260 project.
        InputStream stream = urlCon.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        // The next lines read certain parts of the JSON data and print it out on the screen
        //Creates the JSONObject object and loads the JSON file from the URLConnection
        //Into a StringWriter object. I am printing this out in raw format just so I can see it doing something

        JSONObject json = new JSONObject(result.toString());

        JSONObject coloradoInfo = (JSONObject) json.get("current_observation");

        StringWriter out = new StringWriter();
        json.write(out);
        String jsonTxt = json.toString();
        System.out.print(jsonTxt);

        List<String> list = new ArrayList<>();
        JSONArray array = json.getJSONArray(jsonTxt);
        System.out.print(jsonTxt);

        // for (int i =0;i<array.length();i++){
        //list.add(array.getJSONObject(i).getString("current_observation"));
        //}

        String wunderGround = "Data downloaded from: " +

                coloradoInfo.getJSONObject("image").getString("title") + "\nLink\t\t: "
                + coloradoInfo.getJSONObject("image").getString("link") + "\nCity\t\t: "
                + coloradoInfo.getJSONObject("display_location").getString("city") + "\nState\t\t: "
                + coloradoInfo.getJSONObject("display_location").getString("state_name") + "\nTime\t\t: "
                + coloradoInfo.get("observation_time_rfc822") + "\nTemperature\t\t: "
                + coloradoInfo.get("temperature_string") + "\nWindchill\t\t: "
                + coloradoInfo.get("windchill_string") + "\nRelative Humidity\t: "
                + coloradoInfo.get("relative_humidity") + "\nWind\t\t\t: " + coloradoInfo.get("wind_string")
                + "\nWind Direction\t\t: " + coloradoInfo.get("wind_dir") + "\nBarometer Pressure\t\t: "
                + coloradoInfo.get("pressure_in");

        System.out.println("\nColorado Springs Weather:");
        System.out.println("____________________________________");
        System.out.println(wunderGround);

    } catch (IOException e) {
        System.out.println("***ERROR*******************ERROR********************. " + "\nURL: " + Url.toString()
                + "\nERROR: " + e.toString());
    }

}

From source file:de.bitocean.dspm.examples.Vertex.java

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

    Reader reader = new FileReader(GRAPHML_ACTIVITY_DEPENDENCY_FILE);

    BufferedReader br = new BufferedReader(reader);
    while (br.ready()) {
        System.out.println(br.readLine());
    }//from w ww  .  j  a  va 2  s .  c  om

    Transformer<NodeMetadata, Vertex> vtrans = new Transformer<NodeMetadata, Vertex>() {
        public Vertex transform(NodeMetadata nmd) {
            Vertex v = new Vertex();
            v.id = nmd.getId();
            v.name = nmd.getProperty("name");
            v.expression = nmd.getProperty("expression");
            return v;
        }
    };

    Transformer<EdgeMetadata, Edge> etrans = new Transformer<EdgeMetadata, Edge>() {
        public Edge transform(EdgeMetadata emd) {
            System.out.println(emd.toString());
            Edge e = new Edge();
            try {
                e.source = emd.getSource();
            } catch (Exception ex) {

            }
            e.target = emd.getTarget();
            e.weight = Double.parseDouble(emd.getProperty("weight"));
            return e;
        }
    };

    Transformer<HyperEdgeMetadata, Edge> hetrans = new Transformer<HyperEdgeMetadata, Edge>() {
        public Edge transform(HyperEdgeMetadata emd) {
            Edge e = new Edge();
            try {
                e.source = emd.getProperty("source");
            } catch (Exception ex) {

            }
            e.target = emd.getProperty("target");
            e.weight = Double.parseDouble(emd.getProperty("weight"));
            return e;
        }
    };
    Transformer<GraphMetadata, DirectedSparseGraph<Vertex, Edge>> gtrans = new Transformer<GraphMetadata, DirectedSparseGraph<Vertex, Edge>>() {
        public DirectedSparseGraph<Vertex, Edge> transform(GraphMetadata gmd) {
            return new DirectedSparseGraph<Vertex, Edge>();
        }
    };

    GraphMLReader2<DirectedSparseGraph<Vertex, Edge>, Vertex, Edge> gmlr =
            //new GraphMLReader2<UndirectedSparseGraph<Vertex,Edge>, Vertex, Edge>(fileReader, graphTransformer, vertexTransformer, edgeTransformer, hyperEdgeTransformer)
            new GraphMLReader2<DirectedSparseGraph<Vertex, Edge>, Vertex, Edge>(reader, gtrans, vtrans, etrans,
                    hetrans);

    DirectedSparseGraph<Vertex, Edge> g = gmlr.readGraph();

    System.out.println("Number of vetex: " + g.getVertexCount());
    System.out.println("Number of edges: " + g.getEdgeCount());

    System.out.println("==========================");
    System.out.println("Vertices");
    System.out.println("==========================");
    for (Vertex v : g.getVertices()) {
        System.out.println(v);
    }

    System.out.println("==========================");
    System.out.println("Edges");
    System.out.println("==========================");
    for (Edge e : g.getEdges()) {
        System.out.println(e);
    }

}

From source file:org.fusesource.cloudmix.tests.consumer.Main.java

public static void main(String[] args) {
    if (args.length > 0 && args[0].equals("-debug")) {
        Map<Object, Object> properties = new TreeMap<Object, Object>();
        properties.putAll(System.getProperties());
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            System.out.println(" " + entry.getKey() + " = " + entry.getValue());
        }//from   w  w w  .  ja  va2 s .  co m
    }

    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "META-INF/spring/context.xml");
    applicationContext.start();

    System.out.println("Enter quit to stop");

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String line = reader.readLine();
            if (line == null || line.trim().equalsIgnoreCase("quit")) {
                break;
            }
        }
    } catch (IOException e) {
        System.err.println("Caught: " + e);
        e.printStackTrace(System.err);
    }

    applicationContext.close();
}

From source file:HttpMirror.java

public static void main(String args[]) {
    try {//from www . jav a 2 s .c om
        // Get the port to listen on
        int port = Integer.parseInt(args[0]);
        // Create a ServerSocket to listen on that port.
        ServerSocket ss = new ServerSocket(port);
        // Now enter an infinite loop, waiting for & handling connections.
        for (;;) {
            // Wait for a client to connect. The method will block;
            // when it returns the socket will be connected to the client
            Socket client = ss.accept();

            // Get input and output streams to talk to the client
            BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
            PrintWriter out = new PrintWriter(client.getOutputStream());

            // Start sending our reply, using the HTTP 1.1 protocol
            out.print("HTTP/1.1 200 \r\n"); // Version & status code
            out.print("Content-Type: text/plain\r\n"); // The type of data
            out.print("Connection: close\r\n"); // Will close stream
            out.print("\r\n"); // End of headers

            // Now, read the HTTP request from the client, and send it
            // right back to the client as part of the body of our
            // response. The client doesn't disconnect, so we never get
            // an EOF. It does sends an empty line at the end of the
            // headers, though. So when we see the empty line, we stop
            // reading. This means we don't mirror the contents of POST
            // requests, for example. Note that the readLine() method
            // works with Unix, Windows, and Mac line terminators.
            String line;
            while ((line = in.readLine()) != null) {
                if (line.length() == 0)
                    break;
                out.print(line + "\r\n");
            }

            // Close socket, breaking the connection to the client, and
            // closing the input and output streams
            out.close(); // Flush and close the output stream
            in.close(); // Close the input stream
            client.close(); // Close the socket itself
        } // Now loop again, waiting for the next connection
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java HttpMirror <port>");
    }
}

From source file:RestPostClient.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost("http://localhost:10080/example/json/product/post");

    StringEntity input = new StringEntity("{\"qty\":100,\"name\":\"iPad 4\"}");
    input.setContentType("application/json");
    postRequest.setEntity(input);/*from w  w  w  . j  ava  2 s  .  co  m*/

    HttpResponse response = httpClient.execute(postRequest);

    //if (response.getStatusLine().getStatusCode() != 201) {
    //   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();
}

From source file:org.fusesource.cloudmix.tests.broker.Main.java

public static void main(String[] args) {
    if (verbose || (args.length > 0 && args[0].equals("-debug"))) {
        Map<Object, Object> properties = new TreeMap<Object, Object>();
        properties.putAll(System.getProperties());
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            System.out.println(" " + entry.getKey() + " = " + entry.getValue());
        }//w w w .j av a2 s  . com
    }

    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "META-INF/spring/activemq.xml");
    applicationContext.start();

    System.out.println("Enter quit to stop");

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String line = reader.readLine();
            if (line == null || line.trim().equalsIgnoreCase("quit")) {
                break;
            }
        }
    } catch (IOException e) {
        System.err.println("Caught: " + e);
        e.printStackTrace(System.err);
    }

    applicationContext.close();
}

From source file:com.rest.samples.GetJSON.java

public static void main(String[] args) {
    // TODO code application logic here
    //        String url = "https://api.adorable.io/avatars/list";
    String url = "http://freemusicarchive.org/api/get/albums.json?api_key=60BLHNQCAOUFPIBZ&limit=5";
    try {//ww  w  .  j a va 2s.com
        HttpClient hc = HttpClientBuilder.create().build();
        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/json");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(br);
        if (element.isJsonObject()) {
            JsonObject jsonObject = element.getAsJsonObject();
            Set<Map.Entry<String, JsonElement>> jsonEntrySet = jsonObject.entrySet();
            for (Map.Entry<String, JsonElement> entry : jsonEntrySet) {
                if (entry.getValue().isJsonArray() && entry.getValue().getAsJsonArray().size() > 0) {
                    JsonArray jsonArray = entry.getValue().getAsJsonArray();
                    Set<Map.Entry<String, JsonElement>> internalJsonEntrySet = jsonArray.get(0)
                            .getAsJsonObject().entrySet();
                    for (Map.Entry<String, JsonElement> entrie : internalJsonEntrySet) {
                        System.out.println("--->   " + entrie.getKey() + " --> " + entrie.getValue());

                    }

                } else {
                    System.out.println(entry.getKey() + " --> " + entry.getValue());
                }
            }
        }

        String output;
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}