Example usage for java.io InputStreamReader read

List of usage examples for java.io InputStreamReader read

Introduction

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

Prototype

public int read(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:org.cybergarage.round.Node.java

public boolean postMessage(JSONObject reqObj) {
    try {/*  w w w.  ja  v a  2 s. c o  m*/
        URL url = new URL("http", host, port, "/rpc");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(reqObj.toString());
        out.close();

        int statusCode = conn.getResponseCode();
        if (statusCode != 200)
            return false;

        InputStream in = conn.getInputStream();

        InputStreamReader reader = new InputStreamReader(in);
        StringBuilder builder = new StringBuilder();
        char[] buf = new char[1024];
        int nRead;
        while (0 <= (nRead = reader.read(buf))) {
            builder.append(buf, 0, nRead);
        }
        reader.close();

        String resStr = builder.toString();
        this.resObj = new JSONObject(resStr);
    } catch (Exception e) {
        return false;
    }

    return true;
}

From source file:org.radeox.test.filter.balance.BalanceTest.java

/**
 * @return//from w  w  w  .j  a v a2  s  .c  o  m
 * @throws IOException
 */
private String getSAK12828Pattern() throws IOException {
    InputStreamReader in = null;
    StringBuilder sb = new StringBuilder();
    try {
        in = new InputStreamReader(this.getClass().getResourceAsStream("SAK12828.html"));
        char[] b = new char[4096];

        int i = 0;
        while ((i = in.read(b)) > 0) {
            sb.append(b, 0, i);
        }
    } catch (IOException e) {
        throw e;
    } finally {
        in.close();
    }
    return sb.toString();
}

From source file:org.jenkinsci.plugins.exportparams.serializer.JSONSerializer.java

/**
 * Gets serialized string with properties format.
 * @inheritDoc//from w  w  w  . ja v  a2  s.c  om
 *
 * @param env the env.
 * @return serialized string.
 */
public String serialize(EnvVars env) {
    Collection<Parameter> params = new ArrayList<Parameter>();
    for (String key : env.keySet()) {
        Parameter param = new Parameter();
        param.key = key;
        param.value = env.get(key);
        params.add(param);
    }
    JSON json = net.sf.json.JSONSerializer.toJSON(params);
    String buf = null;
    if (json != null) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        OutputStreamWriter osw;
        try {
            osw = new OutputStreamWriter(os, CharEncoding.UTF_8);
        } catch (UnsupportedEncodingException ueex) {
            osw = new OutputStreamWriter(os);
        }

        try {
            json.write(osw);
            osw.flush();
            ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
            InputStreamReader reader = new InputStreamReader(is, CharEncoding.UTF_8);
            StringBuilder builder = new StringBuilder();

            char[] charBuf = new char[1024];
            int numRead;

            while (0 <= (numRead = reader.read(charBuf))) {
                builder.append(charBuf, 0, numRead);
            }
            buf = builder.toString();
            is.close();

        } catch (Exception ex) {
            buf = null;
        } finally {
            try {
                os.close();
            } catch (Exception ex) {
                os = null;
            }
        }
    }
    return buf;
}

From source file:com.capstone.transit.trans_it.PlacesAutoCompleteAdapter.java

private ArrayList<String> autocomplete(String input) {
    ArrayList<String> resultList = null;

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {//from w  w w.  ja v  a  2  s. c  o  m
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?key=" + API_KEY);
        //sb.append("&components=country:ca");
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));

        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Error processing Places API URL", e);
        return resultList;
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to Places API", e);
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results
        resultList = new ArrayList<String>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
}

From source file:edu.ucla.cs.nopainnogame.WatchActivity.java

public void setFileData(String userName, String fileSuffix, String today, int value) {
    String filename = userName + fileSuffix;
    FileOutputStream fos;//from w  ww.  j ava  2s .c o  m
    InputStream is;
    int numBytes = 0;
    //String test = "";//for debugging
    try {
        is = openFileInput(filename);
        numBytes = is.available();
        InputStreamReader ir = new InputStreamReader(is);
        char[] buf = new char[numBytes];
        ir.read(buf);
        fos = openFileOutput(filename, Context.MODE_PRIVATE);
        String data = today + " " + value + "\n";
        data = data + String.valueOf(buf);
        fos.write(data.getBytes());
        //fos.write(test.getBytes());//for debugging
        fos.flush();
        ir.close();
        is.close();
        fos.close();
    } catch (FileNotFoundException fe) {
        System.err.println("Error: User file not found.");
        fe.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.vdispatcher.GetBaseInformation.java

@Override
public void run() {
    StringBuilder result = new StringBuilder();
    URL url = null;/*from   ww w  . jav a2  s.  c  o m*/
    HttpURLConnection conn = null;
    try {
        url = new URL(BASE_URL);
        conn = (HttpURLConnection) url.openConnection();

        InputStreamReader in = new InputStreamReader(conn.getInputStream());
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            result.append(buff, 0, read);
        }

        JSONObject jsonObject = new JSONObject(result.toString());
        JSONArray data = jsonObject.getJSONArray("data");
        for (int i = 1; i < data.length(); i++) {
            bases.add(Base.fromJSONArray(data.getJSONArray(i)));
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:cz.vutbr.fit.xzelin15.dp.consumer.WSDynamicClientFactory.java

private String transferWSDL(String wsdlURL, String userPassword, WiseProperties wiseProperties)
        throws WiseConnectionException {
    String filePath = null;//from  w w w .java  2s.c  o m
    try {
        URL endpoint = new URL(wsdlURL);
        // Create the connection
        HttpURLConnection conn = (HttpURLConnection) endpoint.openConnection();
        conn.setDoOutput(false);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept",
                "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
        // set Connection close, otherwise we get a keep-alive
        // connection
        // that gives us fragmented answers.
        conn.setRequestProperty("Connection", "close");
        // BASIC AUTH
        if (userPassword != null) {
            conn.setRequestProperty("Authorization",
                    "Basic " + (new BASE64Encoder()).encode(userPassword.getBytes()));
        }
        // Read response
        InputStream is = null;
        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
        } else {
            is = conn.getErrorStream();
            InputStreamReader isr = new InputStreamReader(is);
            StringWriter sw = new StringWriter();
            char[] buf = new char[200];
            int read = 0;
            while (read != -1) {
                read = isr.read(buf);
                sw.write(buf);
            }
            throw new WiseConnectionException("Remote server's response is an error: " + sw.toString());
        }
        // saving file
        File file = new File(wiseProperties.getProperty("wise.tmpDir"),
                new StringBuffer("Wise").append(IDGenerator.nextVal()).append(".xml").toString());
        OutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
        IOUtils.copyStream(fos, is);
        fos.close();
        is.close();
        filePath = file.getPath();
    } catch (WiseConnectionException wce) {
        throw wce;
    } catch (Exception e) {
        throw new WiseConnectionException("Wsdl download failed!", e);
    }
    return filePath;
}

From source file:org.mulgara.store.jxunit.SparqlQueryJX.java

/**
 * Execute a query against a SPARQL endpoint.
 * @param endpoint The URL of the endpoint.
 * @param query The query to execute.// w  ww . jav  a  2  s. co  m
 * @param defGraph The default graph to execute the query against,
 *        or <code>null</code> if not set.
 * @return A string representation of the result from the server.
 * @throws IOException If there was an error communicating with the server.
 * @throws UnsupportedEncodingException The SPARQL endpoint used an encoding not understood by this system.
 * @throws HttpClientException An unexpected response was returned from the SPARQL endpoint.
 */
String executeQuery(String endpoint, String query, URI defGraph)
        throws IOException, UnsupportedEncodingException, HttpClientException {
    String request = endpoint + "?";
    if (defGraph != null && (0 != defGraph.toString().length()))
        request += "default-graph-uri=" + defGraph.toString() + "&";
    request += "query=" + URLEncoder.encode(query, UTF8);
    requestUrl = request;

    HttpClient client = new DefaultHttpClient();
    client.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    HttpGet get = new HttpGet(request);
    get.setHeader("Accept", "application/rdf+xml");

    StringBuilder result = new StringBuilder();
    try {
        HttpResponse response = client.execute(get);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HttpStatus.SC_OK) {
            String msg = "Bad result from SPARQL endpoint: " + status;
            System.err.println(msg);
            throw new HttpClientException(msg);
        }

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStreamReader resultStream = new InputStreamReader(entity.getContent());
            char[] buffer = new char[BUFFER_SIZE];
            int len;
            while ((len = resultStream.read(buffer)) >= 0)
                result.append(buffer, 0, len);
            resultStream.close();
        } else {
            String msg = "No data in response from SPARQL endpoint";
            System.out.println(msg);
            throw new HttpClientException(msg);
        }
    } catch (UnsupportedEncodingException e) {
        System.err.println("Unsupported encoding returned from SPARQL endpoint: " + e.getMessage());
        throw e;
    } catch (IOException ioe) {
        System.err.println("Error communicating with SPARQL endpoint: " + ioe.getMessage());
        throw ioe;
    }
    return result.toString();
}

From source file:com.autburst.picture.server.HttpRequest.java

private String convertStreamToString(InputStream is) throws IOException {
    /*/*from w w w .j  a va  2  s.c o  m*/
     * To convert the InputStream to String we use the
     * BufferedReader.readLine() method. We iterate until the BufferedReader
     * return null which means there's no more data to read. Each line will
     * appended to a StringBuilder and returned as String.
     */
    // BufferedReader reader = new BufferedReader(new
    // InputStreamReader(is));
    // StringBuilder sb = new StringBuilder();
    //
    // String line = null;
    // try {
    // while ((line = reader.readLine()) != null) {
    // sb.append(line);
    // }
    // } catch (IOException e) {
    // e.printStackTrace();
    // } finally {
    // try {
    // is.close();
    // } catch (IOException e) {
    // e.printStackTrace();
    // }
    // }
    // return sb.toString();
    try {
        InputStreamReader in = new InputStreamReader(is);
        StringWriter sw = new StringWriter();
        char[] buffer = new char[1024];
        for (int n; (n = in.read(buffer)) != -1;)
            sw.write(buffer, 0, n);

        return sw.toString();
    } catch (IOException e) {
        throw new IOException(e.getMessage());
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:damian.hashmap.MyActivity.java

public String loadJSONFromAsset() {
    String json = "{}";
    InputStreamReader is = null;
    try {/*from   w ww .  j  av a 2s .  com*/
        is = new InputStreamReader(getAssets().open("person.json"), "UTF-8");

        char[] buffer = new char[BUFFER_SIZE];

        StringBuilder stringBuilder = new StringBuilder();

        int r = is.read(buffer);
        while (r != -1) {

            stringBuilder.append(buffer, 0, r);
            r = is.read(buffer);
        }

        json = new String(stringBuilder.toString());

    } catch (IOException ex) {
        Log.e(TAG, "Error reading questions file", ex);
        return "{}";
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                Log.e(TAG, "Error closing questions file", e);
            }
        }
    }
    return json;

}