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:dk.defxws.fgssolrremote.OperationsImpl.java

private StringBuffer sendToSolr(String solrCommand, String postParameters) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("sendToSolr solrCommand=" + solrCommand + "\nPost parameters=\n" + postParameters);
    String base = config.getIndexBase(indexName);
    URI uri = new URI(base + solrCommand);
    URL url = uri.toURL();/*w ww .j av  a2 s. co  m*/
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    if (postParameters != null) {
        con.setRequestProperty("Content-type", "text/xml; charset=UTF-8");
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        OutputStream out = con.getOutputStream();
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        Reader reader = new StringReader(postParameters);
        char[] buf = new char[1024];
        int read = 0;
        while ((read = reader.read(buf)) >= 0) {
            writer.write(buf, 0, read);
        }
        writer.flush();
        writer.close();
        out.close();
    }

    int responseCode = con.getResponseCode();
    if (logger.isDebugEnabled())
        logger.debug("sendToSolr solrCommand=" + solrCommand + " response Code=" + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    if (logger.isDebugEnabled())
        logger.debug("sendToSolr solrCommand=" + solrCommand + "\n response=" + response);
    return response;
}

From source file:org.ala.preprocess.ColFamilyNamesProcessor.java

/**
 * Copy the raw file into the repository.
 * //from   w w w .  jav a2 s  .  c  o  m
 * @param filePath
 * @param uri
 * @param infosourceUri
 * @param mimeType
 * @return
 * @throws FileNotFoundException
 * @throws Exception
 * @throws IOException
 */
private int copyRawFileToRepo(String filePath, String uri, String infosourceUri, String mimeType)
        throws FileNotFoundException, Exception, IOException {
    InfoSource infoSource = infoSourceDAO.getByUri(infosourceUri);

    Reader ir = new FileReader(filePath);
    DocumentOutputStream dos = repository.getDocumentOutputStream(infoSource.getId(), uri, mimeType);

    //write the file to RAW file in the repository
    OutputStreamWriter w = new OutputStreamWriter(dos.getOutputStream());

    //read into buffer
    char[] buff = new char[1000];
    int read = 0;
    while ((read = ir.read(buff)) > 0) {
        w.write(buff, 0, read);
    }
    w.flush();
    w.close();
    return dos.getId();
}

From source file:com.mirth.connect.server.mule.transformers.ResultMapToXML.java

public Object doTransform(Object source) throws TransformerException {
    if (source instanceof Map) {
        Map data = (Map) source;

        try {/*from   www .  jav  a  2 s . co m*/
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            Element root = document.createElement("result");
            document.appendChild(root);

            for (Iterator iter = data.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                Element child = document.createElement(key);
                String value = new String();
                Object objectValue = data.get(key);
                if (objectValue != null) {
                    if (objectValue instanceof byte[]) {
                        value = new String((byte[]) objectValue);
                    } else if (objectValue instanceof java.sql.Clob) {
                        // convert it to a string
                        java.sql.Clob clobValue = (java.sql.Clob) objectValue;
                        Reader reader = clobValue.getCharacterStream();
                        if (reader == null) {
                            value = "";
                        }
                        StringBuffer sb = new StringBuffer();
                        try {
                            char[] charbuf = new char[(int) clobValue.length()];
                            for (int i = reader.read(charbuf); i > 0; i = reader.read(charbuf)) {
                                sb.append(charbuf, 0, i);
                            }
                        } catch (IOException e) {
                            logger.error("Error reading clob value.\n" + ExceptionUtils.getStackTrace(e));

                        }
                        value = sb.toString();
                    } else if (objectValue instanceof java.sql.Blob) {
                        try {
                            java.sql.Blob blobValue = (java.sql.Blob) objectValue;
                            value = new String(blobValue.getBytes(1, (int) blobValue.length()));
                        } catch (Exception ex) {
                            logger.error("Error reading blob value.\n" + ExceptionUtils.getStackTrace(ex));
                        }
                    } else {
                        value = objectValue.toString();
                    }

                }
                child.appendChild(document.createTextNode(value));
                root.appendChild(child);
            }

            DocumentSerializer docSerializer = new DocumentSerializer();
            return docSerializer.toXML(document);
        } catch (Exception e) {
            throw new TransformerException(
                    org.mule.config.i18n.Message.createStaticMessage("Failed to parse result map"), this);
        }
    } else if (source instanceof String) {
        return source.toString();
    } else {
        throw new TransformerException(
                org.mule.config.i18n.Message.createStaticMessage("Unregistered result type"), this);
    }
}

From source file:me.xiaopan.android.gohttp.StringHttpResponseHandler.java

private String toString(HttpRequest httpRequest, final HttpEntity entity, final String defaultCharset)
        throws IOException, ParseException {
    InputStream inputStream = entity.getContent();
    if (inputStream == null) {
        return "";
    }/*w  w  w .  j av  a 2  s. c om*/
    if (entity.getContentLength() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
    }
    int contentLength = (int) entity.getContentLength();
    if (contentLength < 0) {
        contentLength = 4096;
    }
    String charset = getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    long averageLength = contentLength / httpRequest.getProgressCallbackNumber();
    int callbackNumber = 0;
    Reader reader = new InputStreamReader(inputStream, charset);
    CharArrayBuffer buffer = new CharArrayBuffer(contentLength);
    HttpRequest.ProgressListener progressListener = httpRequest.getProgressListener();
    try {
        char[] tmp = new char[1024];
        int readLength;
        long completedLength = 0;
        while (!httpRequest.isStopReadData() && (readLength = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, readLength);
            completedLength += readLength;
            if (progressListener != null && !httpRequest.isCanceled()
                    && (completedLength >= (callbackNumber + 1) * averageLength
                            || completedLength == contentLength)) {
                callbackNumber++;
                new HttpRequestHandler.UpdateProgressRunnable(httpRequest, contentLength, completedLength)
                        .execute();
            }
        }
    } finally {
        reader.close();
    }
    return buffer.toString();
}

From source file:gtu.youtube.JavaYoutubeDownloader.java

private String getStringFromInputStream(String encoding, InputStream instream)
        throws UnsupportedEncodingException, IOException {
    Writer writer = new StringWriter();

    char[] buffer = new char[1024];
    try {/*from  w w  w  .j  a  v  a  2s  .  co  m*/
        Reader reader = new BufferedReader(new InputStreamReader(instream, encoding));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        instream.close();
    }
    String result = writer.toString();
    return result;
}

From source file:com.silverpeas.jcrutil.BetterRepositoryFactoryBean.java

/**
 * Load a Resource as a String./*from  www .ja v a2s . co m*/
 *
 * @param config the resource
 * @return the String filled with the content of the Resource
 * @throws IOException
 */
protected String getConfiguration(Resource config) throws IOException {
    StringWriter out = new StringWriter();
    Reader reader = null;
    try {
        reader = new InputStreamReader(config.getInputStream(), Charsets.UTF_8);
        char[] buffer = new char[8];
        int c;
        while ((c = reader.read(buffer)) > 0) {
            out.write(buffer, 0, c);
        }
        return out.toString();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.comcast.cqs.util.Util.java

public static String decompress(String compressed) throws IOException {
    if (compressed == null || compressed.equals("")) {
        return compressed;
    }//w  w w.  jav a 2  s. c om
    Reader reader = null;
    StringWriter writer = null;
    try {
        if (!compressed.startsWith("H4sIA")) {
            String prefix = compressed;
            if (compressed.length() > 100) {
                prefix = prefix.substring(0, 99);
            }
            logger.warn("event=content_does_not_appear_to_be_zipped message=" + prefix);
            return compressed;
        }
        byte[] unencodedEncrypted = Base64.decodeBase64(compressed);
        ByteArrayInputStream in = new ByteArrayInputStream(unencodedEncrypted);
        GZIPInputStream gzip = new GZIPInputStream(in);
        reader = new InputStreamReader(gzip, "UTF-8");
        writer = new StringWriter();
        char[] buffer = new char[10240];
        for (int length = 0; (length = reader.read(buffer)) > 0;) {
            writer.write(buffer, 0, length);
        }
    } finally {
        if (writer != null) {
            writer.close();
        }
        if (reader != null) {
            reader.close();
        }
    }
    String decompressed = writer.toString();
    logger.info("event=decompressed from=" + compressed.length() + " to=" + decompressed.length());
    return decompressed;
}

From source file:org.apache.wink.test.mock.MockHttpServletRequestWrapper.java

/**
 * Read data from Input Stream and save it as a String.
 *
 * @param is InputStream to be read/*from   w w  w. ja  v  a2  s .c om*/
 * @return String that was read from the stream
 * @throws UnsupportedEncodingException 
 */
private String readContent() {
    Reader ir;
    try {
        ir = getReader();
    } catch (UnsupportedEncodingException e1) {
        throw new IllegalArgumentException(e1);
    }
    if (ir == null) {
        return null;
    }
    StringBuffer sb = new StringBuffer();

    char[] buffer = new char[1024];
    try {
        int size = 0;
        while ((size = ir.read(buffer)) != -1) {
            sb.append(buffer, 0, size);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    String string = sb.toString();
    return string.trim();
}

From source file:org.cloudsmith.stackhammer.api.client.StackHammerClient.java

/**
 * Parse error from response//from www .j a va 2  s.  co  m
 * 
 * @param response
 * @return request error
 * @throws IOException
 */
protected Diagnostic parseError(int code, InputStream response) throws IOException {
    Reader reader = new InputStreamReader(response, UTF_8);
    StringBuilder bld = new StringBuilder();
    char[] buffer = new char[1024];
    int cnt;
    while ((cnt = reader.read(buffer)) > 0)
        bld.append(buffer, 0, cnt);
    HttpDiagnostic diag = new HttpDiagnostic();
    diag.setMessage(bld.toString());
    diag.setSeverity(Diagnostic.ERROR);
    diag.setHttpCode(code);
    return diag;
}

From source file:com.mhise.util.MHISEUtil.java

public static String _getResponseBody(final HttpEntity entity) throws IOException, ParseException {

    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }/*from   w  ww . j a  v  a 2s  .  com*/

    InputStream instream = entity.getContent();

    if (instream == null) {
        return "";
    }

    if (entity.getContentLength() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException(

                "HTTP entity too large to be buffered in memory");
    }

    String charset = getContentCharSet(entity);

    if (charset == null) {

        charset = HTTP.DEFAULT_CONTENT_CHARSET;

    }

    Reader reader = new InputStreamReader(instream, charset);

    StringBuilder buffer = new StringBuilder();

    try {

        char[] tmp = new char[1024];

        int l;

        while ((l = reader.read(tmp)) != -1) {

            buffer.append(tmp, 0, l);

        }

    } finally {

        reader.close();

    }

    return buffer.toString();

}