Example usage for java.io InputStreamReader InputStreamReader

List of usage examples for java.io InputStreamReader InputStreamReader

Introduction

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

Prototype

public InputStreamReader(InputStream in) 

Source Link

Document

Creates an InputStreamReader that uses the default charset.

Usage

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 .j a va2 s.c o  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 {// w ww . j  ava 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 a  v  a 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  . ja v a2s .c o m*/
    }

    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 {/*from   w  w  w  .  ja  va  2 s. c o  m*/
        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);
    }
}

From source file:com.rdio.simple.examples.CommandLine.java

public static void main(String[] args) throws IOException, JSONException {
    ConsumerCredentials consumerCredentials = new ConsumerCredentials();
    RdioClient rdio = new RdioCoreClient(consumerCredentials);

    try {// w  w  w. j  a va2s.  c  o  m
        RdioClient.AuthState authState = rdio.beginAuthentication("oob");
        System.out.println("Go to: " + authState.url);
        System.out.print("Then enter the code: ");
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String verifier = reader.readLine().trim();
        RdioClient.Token accessToken = rdio.completeAuthentication(verifier, authState.requestToken);
        rdio = new RdioCoreClient(consumerCredentials, accessToken);

        try {
            JSONObject response = new JSONObject(rdio.call("getPlaylists"));
            JSONArray playlists = (JSONArray) ((JSONObject) response.get("result")).get("owned");
            for (int i = 0; i < playlists.length(); i++) {
                JSONObject playlist = playlists.getJSONObject(i);
                System.out.println(playlist.getString("shortUrl") + "\t" + playlist.getString("name"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (RdioClient.RdioException e) {
        System.err.println("Rdio Error: " + e.toString());
    }
}

From source file:com.direct.PortalCheckDirect.java

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

    //This API is for Direct Business
    final String apiEndPoint = "https://secure.policecheckexpress.com.au/pce/api/portalCheckDirect/new";
    final String apiToken = "secure Token";
    try {//from w  w  w  .  j ava2s  .  c  om

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(apiEndPoint);

        //filling Portal Check with Sample Data
        DirectPortalCheck directPortalCheck = fillSampleData();
        String parameters = fillParameters(directPortalCheck, apiToken);
        StringEntity input = new StringEntity(parameters);
        input.setContentType("application/json");
        postRequest.setEntity(input);
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String jsonText = readAll(br);
        JSONArray json = new JSONArray("[" + jsonText + "]");
        JSONObject obj = (JSONObject) json.get(0);
        if (!(Boolean) obj.get("error")) {

            System.out.println(obj.get("message"));
            System.out.println("Invitation Id = " + obj.get("id"));
        } else {
            System.out.println("++++++++++++++++++++++++++");
            System.out.println("Error  = " + obj.get("message"));
            System.out.println("++++++++++++++++++++++++++");

        }

        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:web.restful.ClientTest.java

public static void main(String[] args) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/session");
    put.setEntity(new StringEntity("upenkwbq"));// session ID
    client.execute(put);/*from w ww .  ja  va 2  s .c  o m*/
    put.releaseConnection();

    put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/bucket");
    put.setEntity(new StringEntity("Level1/Level1_Bin_1.txt")); // bucket name
    client.execute(put);
    put.releaseConnection();

    put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/method");
    put.setEntity(new StringEntity("chauvenet")); // method name
    client.execute(put);
    put.releaseConnection();

    HttpGet get = new HttpGet("http://localhost:8080/ss16-lab-web/resources/outliers");
    HttpResponse response = client.execute(get);
    HttpEntity en = response.getEntity();
    InputStreamReader i = new InputStreamReader(en.getContent());
    BufferedReader rd = new BufferedReader(i);
    String line = "";
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }
}

From source file:TestRESTPost12.java

public static void main(String[] p) throws Exception {
    String strurl = "http://localhost:8080/testnewmaven8/webresources/service/post";

    //StringEntity str=new StringEntity("<a>hello post</a>",ContentType.create("application/xml" , Consts.UTF_8));

    ////  w  ww .j  a v a2 s.c o m
    StringEntity str = new StringEntity("hello post");
    str.setContentType("APPLICATION/xml");

    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httppost = new HttpPost(strurl);
    httppost.addHeader("Accept", "application/xml charset=UTF-8");
    //httppost.addHeader("content_type", "application/xml, multipart/related");
    httppost.setEntity(str);

    CloseableHttpResponse response = httpclient.execute(httppost);
    // try
    //{
    int statuscode = response.getStatusLine().getStatusCode();
    if (statuscode != 200) {
        System.out.println("http error occured=" + statuscode);
    }

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

    while (br.readLine() != null) {
        System.out.println(br.readLine());
    }
    // }
    /*catch(Exception e)
    {
        System.out.println("exception :"+e);
    }*/

    //httpclient.close();

}

From source file:Standard.java

public static void main(String args[]) throws IOException {
    BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
    String number;//from   www  .  ja  va 2 s  .c om
    int total = 0;

    while ((number = cin.readLine()) != null) {
        try {
            total += Integer.parseInt(number);
        } catch (NumberFormatException e) {
            System.err.println("Invalid number in input");
            System.exit(1);
        }
    }
    System.out.println(total);
}