Example usage for java.io Reader read

List of usage examples for java.io Reader read

Introduction

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

Prototype

public int read(char cbuf[]) throws IOException 

Source Link

Document

Reads characters into an array.

Usage

From source file:com.googlecode.esms.provider.Vodafone.java

/**
 * Convert any stream to a string. //from w  w  w. ja v a  2 s. co m
 * @param input Stream to be read.
 * @return String representation of the stream.
 */
private String convertStreamToString(InputStream input) throws IOException {
    if (input != null) {
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        Reader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1)
            writer.write(buffer, 0, n);
        input.close();
        return writer.toString();
    } else {
        return "";
    }
}

From source file:cn.vlabs.umt.common.mail.MessageFormatter.java

private String readTemplate(Locale locale, String templateName) throws TemplateNotFound {
    StringBuffer content = new StringBuffer();
    Reader reader = null;
    String templateFileDir = path;
    try {/*from   w  ww .  j av a  2 s .  c  om*/
        templateFileDir = path + "/" + locale.toString();
        File f = new File(templateFileDir);
        if (!f.exists()) {
            templateFileDir = path + "/en_US";
        }
        templateFileDir = templateFileDir + "/" + templateName;
        reader = new InputStreamReader(new FileInputStream(templateFileDir), "UTF-8");

        int num = 0;
        while ((num = reader.read(buff)) != -1) {
            content.append(buff, 0, num);
        }
    } catch (FileNotFoundException e) {
        throw new TemplateNotFound(templateFileDir);
    } catch (UnsupportedEncodingException e) {
        log.error("????");
        log.debug("?", e);
    } catch (IOException e) {
        log.error("????");
        log.debug("?", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                log.debug("??");
            }
        }
    }
    return content.toString();
}

From source file:com.amazonservices.mws.client.MwsAQCall.java

/**
 * Read stream into string/*from w ww.j av  a  2s.c  om*/
 * 
 * @param postResponse
 *            The response to get the body from.
 * 
 * @return The response body.
 */
private String getResponseBody(HttpResponse postResponse) {
    InputStream input = null;
    try {
        input = postResponse.getEntity().getContent();
        Reader reader = new InputStreamReader(input, MwsUtl.DEFAULT_ENCODING);
        StringBuilder b = new StringBuilder();
        char[] c = new char[1024];
        int len;
        while (0 < (len = reader.read(c))) {
            b.append(c, 0, len);
        }
        return b.toString();
    } catch (Exception e) {
        throw MwsUtl.wrap(e);
    } finally {
        MwsUtl.close(input);
    }
}

From source file:com.bstek.dorado.view.resolver.ViewServiceResolver.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    XmlEscapeWriter writer = new XmlEscapeWriter(getWriter(request, response));

    JsonBuilder jsonBuilder = new JsonBuilder(writer);
    ServletInputStream in = request.getInputStream();
    DoradoContext context = DoradoContext.getCurrent();
    try {//from  ww  w  .  j a  v  a2 s  . c o m
        String contentType = request.getContentType();
        if (contentType != null && contentType.contains(JAVASCRIPT_TOKEN)) {
            Reader reader = new InputStreamReader(in, Constants.DEFAULT_CHARSET);
            StringBuffer buf = new StringBuffer();
            char[] cs = new char[BUFFER_SIZE];
            for (int n; (n = reader.read(cs)) > 0;) {
                buf.append(new String(cs, 0, n));
            }

            ObjectNode objectNode = (ObjectNode) JsonUtils.getObjectMapper().readTree(buf.toString());

            processTask(writer, objectNode, context);
        } else if (contentType != null && contentType.contains(XML_TOKEN)) {
            Document document = getXmlDocumentBuilder(context)
                    .loadDocument(new InputStreamResource(in, request.getRequestURI()));

            writer.append("<?xml version=\"1.0\" encoding=\"" + Constants.DEFAULT_CHARSET + "\"?>\n");
            writer.append("<result>\n");

            Writer escapeWriter = new XmlEscapeWriter(writer);
            for (Element element : DomUtils.getChildElements(document.getDocumentElement())) {
                writer.append("<request>\n");
                writer.append("<response type=\"json\"><![CDATA[\n");
                writer.setEscapeEnabled(true);

                String textContent = DomUtils.getTextContent(element);

                ObjectNode objectNode = (ObjectNode) JsonUtils.getObjectMapper().readTree(textContent);
                try {
                    processTask(escapeWriter, objectNode, context);
                    writer.setEscapeEnabled(false);

                    writer.append("\n]]></response>\n");
                } catch (Exception e) {
                    Throwable t = e;
                    while (t.getCause() != null) {
                        t = t.getCause();
                    }
                    writer.setEscapeEnabled(false);

                    writer.append("\n]]></response>\n");
                    if (t instanceof ClientRunnableException) {
                        writer.append("<exception type=\"runnable\"><![CDATA[");
                        writer.setEscapeEnabled(true);
                        writer.append("(function(){").append(((ClientRunnableException) t).getScript())
                                .append("})");
                    } else {
                        writer.append("<exception><![CDATA[\n");
                        writer.setEscapeEnabled(true);
                        outputException(jsonBuilder, e);
                    }
                    writer.setEscapeEnabled(false);
                    writer.append("\n]]></exception>\n");
                    logger.error(e, e);
                }
                writer.append("</request>\n");
            }

            writer.append("</result>");
        }
    } catch (Exception e) {
        in.close();

        Throwable t = e;
        while (t.getCause() != null) {
            t = t.getCause();
        }

        if (t instanceof ClientRunnableException) {
            response.setContentType("text/runnable");
            writer.append("(function(){").append(((ClientRunnableException) t).getScript()).append("})");
        } else {
            response.setContentType("text/dorado-exception");
            outputException(jsonBuilder, e);
        }

        logger.error(e, e);
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:com.esri.gpt.control.webharvest.client.waf.FtpClientRequest.java

protected String readTextFile(int attempt, String pathName) throws IOException {
    InputStream input = null;//w  w w.  ja va 2  s. c  om
    Reader reader = null;
    try {
        stayOpen();
        StringBuilder sb = new StringBuilder();
        input = client.retrieveFileStream(pathName);
        if (input != null) {
            reader = new InputStreamReader(input, "UTF-8");
            char[] buff = new char[1000];
            int length = 0;
            while ((length = reader.read(buff)) >= 0) {
                sb.append(buff, 0, length);
            }
        }
        return sb.toString();
    } catch (SocketException ex) {
        if (attempt < getNoOfAttempts()) {
            LOG.log(Level.INFO, "Reading text file [attempt: {2}] on: {0} from the path: {1}",
                    new Object[] { host, pathName, attempt + 1 });
            reConnect();
            return readTextFile(attempt + 1, pathName);
        } else {
            throw ex;
        }
    } catch (FTPConnectionClosedException ex) {
        if (attempt < getNoOfAttempts()) {
            LOG.log(Level.INFO, "Reading text file [attempt: {2}] on: {0} from the path: {1}",
                    new Object[] { host, pathName, attempt + 1 });
            reConnect();
            return readTextFile(attempt + 1, pathName);
        } else {
            throw ex;
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ex) {
                LOG.log(Level.FINE, "Error closing reader on: " + host, ex);
            }
        }
        if (input != null) {
            try {
                input.close();
            } catch (IOException ex) {
                LOG.log(Level.FINE, "Error closing input on: " + host, ex);
            }
        }
        try {
            client.completePendingCommand();
        } catch (IOException ex) {
            LOG.log(Level.FINE, "Error completing pending command: " + host, ex);
        }
    }
}

From source file:org.bitpipeline.lib.owm.OwmClient.java

private JSONObject doQuery(String subUrl) throws JSONException, IOException {
    String responseBody = null;/*from  w  ww  .j  a va 2s  .co m*/
    HttpGet httpget = new HttpGet(this.baseOwmUrl + subUrl);
    if (this.owmAPPID != null) {
        httpget.addHeader(OwmClient.APPID_HEADER, this.owmAPPID);
    }

    HttpResponse response = this.httpClient.execute(httpget);
    InputStream contentStream = null;
    try {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine == null) {
            throw new IOException(String.format("Unable to get a response from OWM server"));
        }
        int statusCode = statusLine.getStatusCode();
        if (statusCode < 200 && statusCode >= 300) {
            throw new IOException(
                    String.format("OWM server responded with status code %d: %s", statusCode, statusLine));
        }
        /* Read the response content */
        HttpEntity responseEntity = response.getEntity();
        contentStream = responseEntity.getContent();
        Reader isReader = new InputStreamReader(contentStream);
        int contentSize = (int) responseEntity.getContentLength();
        if (contentSize < 0)
            contentSize = 8 * 1024;
        StringWriter strWriter = new StringWriter(contentSize);
        char[] buffer = new char[8 * 1024];
        int n = 0;
        while ((n = isReader.read(buffer)) != -1) {
            strWriter.write(buffer, 0, n);
        }
        responseBody = strWriter.toString();
        contentStream.close();
    } catch (IOException e) {
        throw e;
    } catch (RuntimeException re) {
        httpget.abort();
        throw re;
    } finally {
        if (contentStream != null)
            contentStream.close();
    }
    return new JSONObject(responseBody);
}

From source file:com.zoffcc.applications.aagtl.FieldnotesUploader.java

public String convertStreamToString(InputStream is) throws IOException {
    /*/*from w w w  .ja v a  2 s .c  om*/
     * To convert the InputStream to String we use the
     * Reader.read(char[] buffer) method. We iterate until the
     * Reader return -1 which means there's no more data to
     * read. We use the StringWriter class to produce the string.
     */
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[HTMLDownloader.large_buffer_size];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"),
                    HTMLDownloader.large_buffer_size);
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:com.agiro.scanner.android.CaptureActivity.java

public void handleDecode(Invoice invoice, Bitmap debugBmp) {
    //    inactivityTimer.onActivity();
    //    playBeepSoundAndVibrate();
    ImageView debugImageView = (ImageView) findViewById(R.id.debug_image_view);
    debugImageView.setImageBitmap(debugBmp);

    Log.v(TAG, "Got invoice " + invoice);
    if (invoice.isComplete()) {
        new Thread(new Runnable() {

            public void run() {
                AppEngineClient aec = new AppEngineClient(CaptureActivity.this, "patrik.akerfeldt@gmail.com");
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("reference", "12345678"));
                try {
                    Writer w = new StringWriter();
                    HttpResponse res = aec.makeRequest("/add", params);
                    Reader reader = new BufferedReader(
                            new InputStreamReader(res.getEntity().getContent(), "UTF-8"));
                    int n;
                    char[] buffer = new char[1024];
                    while ((n = reader.read(buffer)) != -1) {
                        w.write(buffer, 0, n);
                    }/*from w  w  w.j  a v  a 2 s  . com*/
                    Log.e(TAG, "Got: " + w.toString());
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage(), e);
                }

            }
        }).start();
    }

    //TODO: the isValidCC checking should be optional
    //    if (resultMap.containsKey("reference")) {
    //        String str = resultMap.get("reference").toString();
    //        if (StringDecoder.isValidCC(str)) {
    //           new Thread(new Runnable() {
    //            
    //            public void run() {
    //                 AppEngineClient aec = new AppEngineClient(CaptureActivity.this, "patrik.akerfeldt@gmail.com");
    //                 List<NameValuePair> params = new ArrayList<NameValuePair>();
    //                 params.add(new BasicNameValuePair("reference", "12345678"));
    //                 try {
    //                    Writer w = new StringWriter();
    //                  HttpResponse res = aec.makeRequest("/add", params);
    //                  Reader reader = new BufferedReader(new InputStreamReader(res.getEntity().getContent(), "UTF-8"));
    //                  int n;
    //                  char[] buffer = new char[1024];
    //                  while ((n = reader.read(buffer)) != -1) {
    //                  w.write(buffer, 0, n);
    //                  }
    //                  Log.e(TAG, "Got: " + w.toString());
    //               } catch (Exception e) {
    //                  Log.e(TAG, e.getMessage(), e);
    //               }               
    //
    //            }
    //         }).start();
    //          reference = str;
    //        }
    //    }
    //    if (resultMap.containsKey("amount")) {
    //        String str = resultMap.get("amount").toString();
    //        if (StringDecoder.isValidCC(str)) {
    //            str = str.substring(0,str.length()-1);
    //            str = new StringBuffer(str).insert((str.length()-2), ",").toString();
    //            amount = str;
    //        }
    //    }
    //    if (resultMap.containsKey("account")) {
    //        String str = resultMap.get("account").toString();
    //        if (StringDecoder.isValidCC(str)) {
    //          account = str;
    //        }
    //    }
    //    if (resultMap.containsKey("debug")) {
    //        debug = resultMap.get("debug").toString();
    //    }
    populateList(invoice.getReference(), invoice.getCompleteAmount(), invoice.getGiroAccount(),
            "NOT SUPPORTED");
    onContentChanged();
}

From source file:io.lightlink.output.JSONResponseStream.java

public void writeFromReader(Reader reader) {
    write('"');//  ww  w.  j  ava2  s  .co  m
    char[] buffer = new char[16000];
    long count = 0;
    int n = 0;
    try {
        while (-1 != (n = reader.read(buffer))) {

            ByteBuffer bbuffer = CHARSET.encode(CharBuffer.wrap(buffer, 0, n));
            write(bbuffer.array(), bbuffer.remaining());

            count += n;
        }
        write('"');
        reader.close();
    } catch (IOException e) {
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:im.delight.android.webrequest.WebRequest.java

protected String parseResponse(HttpResponse response) throws Exception {
    final Header contentEncoding = response.getFirstHeader("Content-Encoding");
    // if we have a compressed response (GZIP)
    if (contentEncoding != null && contentEncoding.getValue() != null
            && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
        // get the entity and the content length (if any) from the response
        final HttpEntity entity = response.getEntity();
        long contentLength = entity.getContentLength();

        // handle too large or undefined content lengths
        if (contentLength > Integer.MAX_VALUE) {
            throw new Exception("Response too large");
        } else if (contentLength < 0) {
            // use an arbitrary buffer size
            contentLength = 4096;/*from   www  .  j a  v  a  2 s .  co m*/
        }

        // construct a GZIP input stream from the response
        InputStream responseStream = entity.getContent();
        if (responseStream == null) {
            return null;
        }
        responseStream = new GZIPInputStream(responseStream);

        // read from the stream
        Reader reader = new InputStreamReader(responseStream, mCharset);
        CharArrayBuffer buffer = new CharArrayBuffer((int) contentLength);
        try {
            char[] tmp = new char[1024];
            int l;
            while ((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
        } finally {
            reader.close();
        }

        // return the decompressed response text as a string
        return buffer.toString();
    }
    // if we have an uncompressed response
    else {
        // return the response text as a string
        return EntityUtils.toString(response.getEntity(), mCharset);
    }
}