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(char cbuf[], int offset, int length) throws IOException 

Source Link

Document

Reads characters into a portion of an array.

Usage

From source file:org.callimachusproject.xproc.Pipeline.java

private void appendText(InputStreamReader reader, Document doc, Element data) throws IOException {
    char buf[] = new char[bufSize];
    int len = reader.read(buf, 0, bufSize);
    while (len >= 0) {
        data.appendChild(doc.createTextNode(new String(buf, 0, len)));
        len = reader.read(buf, 0, bufSize);
    }/*from   w  w w  .  j  ava 2 s  .c  o m*/
}

From source file:org.qedeq.base.io.IoUtility.java

/**
 * Reads contents of a file into a string buffer.
 *
 * @param   file        This file will be loaded.
 * @param   buffer      Buffer to fill with file contents.
 * @param   encoding    Take this encoding.
 * @throws  IOException File exception occurred.
 *///from   ww w .j a  va 2  s .  co  m
public static void loadFile(final File file, final StringBuffer buffer, final String encoding)
        throws IOException {

    buffer.setLength((int) file.length()); // ensure capacity
    buffer.setLength(0);
    final InputStreamReader in = new InputStreamReader(new FileInputStream(file), encoding);
    final char[] data = new char[10 * 1024];

    try {
        int charsread = 0;
        while (0 < (charsread = in.read(data, 0, data.length))) {
            buffer.append(data, 0, charsread);
        }
    } finally {
        in.close();
    }
}

From source file:org.apache.wink.itest.standard.JAXRSReaderTest.java

/**
 * Tests posting to a Reader parameter./*from  w  w  w . j  a v a2  s  . c o  m*/
 * 
 * @throws HttpException
 * @throws IOException
 */
public void testPostReader() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PostMethod postMethod = new PostMethod(getBaseURI() + "/providers/standard/reader");
    postMethod.setRequestEntity(new StringRequestEntity("abcd", "text/plain", "UTF-8"));
    postMethod.addRequestHeader("Accept", "text/plain");
    try {
        client.executeMethod(postMethod);

        assertEquals(200, postMethod.getStatusCode());
        InputStream is = postMethod.getResponseBodyAsStream();

        InputStreamReader isr = new InputStreamReader(is);
        char[] buffer = new char[1];
        int read = 0;
        int offset = 0;
        while ((read = isr.read(buffer, offset, buffer.length - offset)) != -1) {
            offset += read;
            if (offset >= buffer.length) {
                buffer = ArrayUtils.copyOf(buffer, buffer.length * 2);
            }
        }
        char[] carr = ArrayUtils.copyOf(buffer, offset);

        int checkEOF = is.read();
        assertEquals(-1, checkEOF);
        String str = new String(carr);

        assertEquals("abcd", str);
        assertEquals("text/plain", postMethod.getResponseHeader("Content-Type").getValue());
        Header contentLengthHeader = postMethod.getResponseHeader("Content-Length");
        assertNull(contentLengthHeader == null ? "null" : contentLengthHeader.getValue(), contentLengthHeader);
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:org.apache.wink.itest.standard.JAXRSReaderTest.java

/**
 * @throws HttpException//from   www .  j  a  va 2  s  . c o  m
 * @throws IOException
 */
public void testWithRequestAcceptHeaderWillReturnRequestedContentType() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(getBaseURI() + "/providers/standard/reader");
    putMethod.setRequestEntity(new StringRequestEntity("wxyz", "char/array", "UTF-8"));
    try {
        client.executeMethod(putMethod);
        assertEquals(204, putMethod.getStatusCode());
    } finally {
        putMethod.releaseConnection();
    }

    GetMethod getMethod = new GetMethod(getBaseURI() + "/providers/standard/reader");
    getMethod.addRequestHeader("Accept", "mytype/subtype");
    try {
        client.executeMethod(getMethod);
        assertEquals(200, getMethod.getStatusCode());
        InputStream is = getMethod.getResponseBodyAsStream();

        InputStreamReader isr = new InputStreamReader(is);
        char[] buffer = new char[1];
        int read = 0;
        int offset = 0;
        while ((read = isr.read(buffer, offset, buffer.length - offset)) != -1) {
            offset += read;
            if (offset >= buffer.length) {
                buffer = ArrayUtils.copyOf(buffer, buffer.length * 2);
            }
        }
        char[] carr = ArrayUtils.copyOf(buffer, offset);

        int checkEOF = is.read();
        assertEquals(-1, checkEOF);
        String str = new String(carr);

        assertEquals("wxyz", str);
        assertEquals("mytype/subtype", getMethod.getResponseHeader("Content-Type").getValue());

        Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");
        assertNull(contentLengthHeader == null ? "null" : contentLengthHeader.getValue(), contentLengthHeader);
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:org.apache.wink.itest.standard.JAXRSReaderTest.java

/**
 * Tests putting and then getting a Reader.
 * // ww  w  . j  av a 2s . c om
 * @throws HttpException
 * @throws IOException
 */
public void testPutReader() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(getBaseURI() + "/providers/standard/reader");
    putMethod.setRequestEntity(new StringRequestEntity("wxyz", "char/array", "UTF-8"));
    try {
        client.executeMethod(putMethod);
        assertEquals(204, putMethod.getStatusCode());
    } finally {
        putMethod.releaseConnection();
    }

    GetMethod getMethod = new GetMethod(getBaseURI() + "/providers/standard/reader");
    try {
        client.executeMethod(getMethod);
        assertEquals(200, getMethod.getStatusCode());
        InputStream is = getMethod.getResponseBodyAsStream();

        InputStreamReader isr = new InputStreamReader(is);
        char[] buffer = new char[1];
        int read = 0;
        int offset = 0;
        while ((read = isr.read(buffer, offset, buffer.length - offset)) != -1) {
            offset += read;
            if (offset >= buffer.length) {
                buffer = ArrayUtils.copyOf(buffer, buffer.length * 2);
            }
        }
        char[] carr = ArrayUtils.copyOf(buffer, offset);

        int checkEOF = is.read();
        assertEquals(-1, checkEOF);
        String str = new String(carr);

        assertEquals("wxyz", str);

        String contentType = (getMethod.getResponseHeader("Content-Type") == null) ? null
                : getMethod.getResponseHeader("Content-Type").getValue();
        assertNotNull(contentType, contentType);

        Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");
        assertNull(contentLengthHeader == null ? "null" : contentLengthHeader.getValue(), contentLengthHeader);
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:com.comcast.cns.io.HTTPEndpointSyncPublisher.java

@Override
public void send() throws Exception {

    if ((message == null) || (endpoint == null)) {
        logger.debug("event=send_http_request error_code=MissingParameters endpoint=" + endpoint
                + "\" message=\"" + message + "\"");
        throw new Exception("Message and Endpoint must both be set");
    }/*w  w  w.j  av a2 s  .c  o  m*/

    HttpPost httpPost = new HttpPost(endpoint);

    String msg = null;

    if (message.getMessageStructure() == CNSMessageStructure.json) {
        msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.http);
    } else {
        msg = message.getMessage();
    }

    if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) {
        msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.http);
    }

    logger.debug("event=send_sync_http_request endpoint=" + endpoint + "\" message=\"" + msg + "\"");

    StringEntity stringEntity = new StringEntity(msg);
    httpPost.setEntity(stringEntity);
    composeHeader(httpPost);

    HttpResponse response = httpClient.execute(httpPost);
    int statusCode = response.getStatusLine().getStatusCode();

    HttpEntity entity = response.getEntity();

    // accept all 2xx status codes

    if (statusCode > 200 || statusCode >= 300) {

        if (entity != null) {

            InputStream instream = entity.getContent();
            InputStreamReader responseReader = new InputStreamReader(instream);
            StringBuffer buffer = new StringBuffer();

            char[] arr = new char[1024];
            int size = 0;

            while ((size = responseReader.read(arr, 0, arr.length)) != -1) {
                buffer.append(arr, 0, size);
            }

            instream.close();
        }

        logger.debug("event=http_post_error endpoint=" + endpoint + " error_code=" + statusCode);
        throw new CMBException(new CMBErrorCodes(statusCode, "HttpError"),
                "Unreachable endpoint " + endpoint + " returns status code " + statusCode);

    } else {

        if (entity != null) {
            EntityUtils.consume(entity);
        }
    }
}

From source file:org.apache.wink.itest.standard.JAXRSMultivaluedMapTest.java

/**
 * Tests posting to a MultivaluedMap with application/x-www-form-urlencoded
 * request Content-Type./*  w ww .  j ava2  s. c  om*/
 * 
 * @throws HttpException
 * @throws IOException
 */
public void testPostMultivaluedMap() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PostMethod postMethod = new PostMethod(getBaseURI() + "/providers/standard/multivaluedmap");
    postMethod.setRequestEntity(
            new StringRequestEntity("tuv=wxyz&abcd=", "application/x-www-form-urlencoded", "UTF-8"));
    try {
        client.executeMethod(postMethod);

        assertEquals(200, postMethod.getStatusCode());
        InputStream is = postMethod.getResponseBodyAsStream();

        InputStreamReader isr = new InputStreamReader(is);
        char[] buffer = new char[1];
        int read = 0;
        int offset = 0;
        while ((read = isr.read(buffer, offset, buffer.length - offset)) != -1) {
            offset += read;
            if (offset >= buffer.length) {
                buffer = ArrayUtils.copyOf(buffer, buffer.length * 2);
            }
        }
        char[] carr = ArrayUtils.copyOf(buffer, offset);

        int checkEOF = is.read();
        assertEquals(-1, checkEOF);
        String str = new String(carr);

        assertTrue(str, "abcd=&tuv=wxyz".equals(str) || "tuv=wxyz&abcd=".equals(str));
        assertEquals("application/x-www-form-urlencoded",
                postMethod.getResponseHeader("Content-Type").getValue());
        Header contentLengthHeader = postMethod.getResponseHeader("Content-Length");
        if (contentLengthHeader != null) {
            // some of the containers can be "smarter" and set the
            // content-length for us if the payload is small
            assertEquals("14", contentLengthHeader.getValue());
        }
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:org.apache.wink.itest.standard.JAXRSMultivaluedMapTest.java

/**
 * Tests putting and then getting a /multivaluedmap.
 * //w ww.j a  v a  2s.c o  m
 * @throws HttpException
 * @throws IOException
 */
public void testPutReader() throws HttpException, IOException {
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(getBaseURI() + "/providers/standard/multivaluedmap");
    putMethod.setRequestEntity(new StringRequestEntity("username=user1&password=user1password",
            "application/x-www-form-urlencoded", "UTF-8"));
    try {
        client.executeMethod(putMethod);
        assertEquals(204, putMethod.getStatusCode());
    } finally {
        putMethod.releaseConnection();
    }

    GetMethod getMethod = new GetMethod(getBaseURI() + "/providers/standard/multivaluedmap");
    getMethod.addRequestHeader("Accept", "application/x-www-form-urlencoded");
    try {
        client.executeMethod(getMethod);
        assertEquals(200, getMethod.getStatusCode());
        InputStream is = getMethod.getResponseBodyAsStream();

        InputStreamReader isr = new InputStreamReader(is);
        char[] buffer = new char[1];
        int read = 0;
        int offset = 0;
        while ((read = isr.read(buffer, offset, buffer.length - offset)) != -1) {
            offset += read;
            if (offset >= buffer.length) {
                buffer = ArrayUtils.copyOf(buffer, buffer.length * 2);
            }
        }
        char[] carr = ArrayUtils.copyOf(buffer, offset);

        int checkEOF = is.read();
        assertEquals(-1, checkEOF);
        String str = new String(carr);

        assertTrue(str, "username=user1&password=user1password".equals(str)
                || "password=user1password&username=user1".equals(str));
        assertEquals("application/x-www-form-urlencoded",
                getMethod.getResponseHeader("Content-Type").getValue());
        Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");
        if (contentLengthHeader != null) {
            // some of the containers can be "smarter" and set the
            // content-length for us if the payload is small
            assertEquals("37", contentLengthHeader.getValue());
        }
    } finally {
        getMethod.releaseConnection();
    }
}

From source file:com.samknows.measurement.net.Connection.java

/**
 * Retrieve the input stream from the HTTP connection.
 * //from  ww w .  j  a  v a  2s  . co m
 * @param httpEntity
 * @return String
 */
private String retrieveInputStream(HttpEntity httpEntity) {
    int length = (int) httpEntity.getContentLength();
    boolean chunked = (boolean) httpEntity.isChunked();

    Log.i(TAG, "Chunked: " + Boolean.toString(chunked) + " - Length: " + Integer.toString(length));
    StringBuffer stringBuffer = new StringBuffer(length);
    try {
        InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);
        char buffer[] = new char[length];
        int count;
        while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {
            stringBuffer.append(buffer, 0, count);
        }
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, e.toString());
    } catch (IllegalStateException e) {
        Log.e(TAG, e.toString());
    } catch (IOException e) {
        Log.e(TAG, e.toString());
    }
    return stringBuffer.toString();
}

From source file:com.temenos.interaction.example.odata.notes.CreateReadUpdateDeleteITCase.java

/**
 * Tests create with application/x-www-form-urlencoded request Content-Type.
 * /* w  w w.  j av a2s .  c o m*/
 * @throws HttpException
 * @throws IOException
 */
@Test
public void testCreateUrlEncodedForm() throws HttpException, IOException {
    ODataConsumer consumer = ODataJerseyConsumer.newBuilder(Configuration.TEST_ENDPOINT_URI).build();
    EdmDataServices metadata = consumer.getMetadata();

    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(Configuration.TEST_ENDPOINT_URI + PERSONS_RESOURCE);
    postMethod.setRequestEntity(
            new StringRequestEntity("name=RonOnForm&abcd=", "application/x-www-form-urlencoded", "UTF-8"));
    postMethod.addRequestHeader("Content-Type", PostMethod.FORM_URL_ENCODED_CONTENT_TYPE);
    postMethod.addRequestHeader("Accept", "application/atom+xml");

    String personId = null;
    try {
        client.executeMethod(postMethod);

        assertEquals(201, postMethod.getStatusCode());
        InputStream is = postMethod.getResponseBodyAsStream();

        InputStreamReader isr = new InputStreamReader(is);
        char[] buffer = new char[1];
        int read = 0;
        int offset = 0;
        while ((read = isr.read(buffer, offset, buffer.length - offset)) != -1) {
            offset += read;
            if (offset >= buffer.length) {
                buffer = Arrays.copyOf(buffer, buffer.length * 2);
            }
        }
        char[] carr = Arrays.copyOf(buffer, offset);

        int checkEOF = is.read();
        assertEquals(-1, checkEOF);
        String str = new String(carr);

        assertEquals("application/atom+xml", postMethod.getResponseHeader("Content-Type").getValue());
        FormatParser<Entry> parser = FormatParserFactory.getParser(Entry.class, FormatType.ATOM,
                new Settings(ODataConstants.DATA_SERVICE_VERSION, metadata, PERSON_ENTITYSET_NAME, null, null));
        Entry entry = parser.parse(new StringReader(str));
        personId = entry.getEntity().getProperty("id").getValue().toString();
        assertEquals("RonOnForm", entry.getEntity().getProperty("name").getValue().toString());
    } finally {
        postMethod.releaseConnection();
    }
    assertNotNull(personId);

    // read the person to check it was created ok
    OEntity person = consumer.getEntity(PERSON_ENTITYSET_NAME, Integer.valueOf(personId)).execute();
    assertTrue(person != null);
    assertEquals("RonOnForm", person.getProperty("name").getValue());
}