Example usage for org.apache.http.entity InputStreamEntity InputStreamEntity

List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity

Introduction

In this page you can find the example usage for org.apache.http.entity InputStreamEntity InputStreamEntity.

Prototype

public InputStreamEntity(InputStream inputStream, ContentType contentType) 

Source Link

Usage

From source file:org.peterbaldwin.vlcremote.sweep.Worker.java

@Override
public void run() {
    // Note: InetAddress#isReachable(int) always returns false for Windows
    // hosts because applications do not have permission to perform ICMP
    // echo requests.
    for (;;) {//from   w w  w  .  j  av  a2s  .  co  m
        byte[] ipAddress = mManager.pollIpAddress();
        if (ipAddress == null) {
            break;
        }
        try {
            InetAddress address = InetAddress.getByAddress(ipAddress);
            String hostAddress = address.getHostAddress();
            URL url = createUrl("http", hostAddress, mPort, mPath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(1000);
            try {
                int responseCode = connection.getResponseCode();
                String responseMessage = connection.getResponseMessage();
                InputStream inputStream = (responseCode == HttpURLConnection.HTTP_OK)
                        ? connection.getInputStream()
                        : connection.getErrorStream();
                if (inputStream != null) {
                    try {
                        int length = connection.getContentLength();
                        InputStreamEntity entity = new InputStreamEntity(inputStream, length);
                        entity.setContentType(connection.getContentType());

                        // Copy the entire response body into memory
                        // before the HTTP connection is closed:
                        String body = EntityUtils.toString(entity);

                        ProtocolVersion version = new ProtocolVersion("HTTP", 1, 1);
                        String hostname = address.getHostName();
                        StatusLine statusLine = new BasicStatusLine(version, responseCode, responseMessage);
                        HttpResponse response = new BasicHttpResponse(statusLine);
                        response.setHeader(HTTP.TARGET_HOST, hostname + ":" + mPort);
                        response.setEntity(new StringEntity(body));
                        mCallback.onReachable(ipAddress, response);
                    } finally {
                        inputStream.close();
                    }
                } else {
                    Log.w(TAG, "InputStream is null");
                }
            } finally {
                connection.disconnect();
            }
        } catch (IOException e) {
            mCallback.onUnreachable(ipAddress, e);
        }
    }
}

From source file:org.chaplib.TestHttpResource.java

@Test
public void closesConnectionAfterParsingGet() throws Exception {
    response.setEntity(new InputStreamEntity(mockInputStream, -1));
    when(mockHttpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
    when(mockParser.parse(entity)).thenReturn(parsed);
    impl.value(mockParser);/*from w  w  w  .  j  ava  2 s  .  c o m*/
    verify(mockInputStream, atLeastOnce()).close();
}

From source file:com.sinacloud.scs.http.RepeatableInputStreamRequestEntity.java

/**
 * Creates a new RepeatableInputStreamRequestEntity using the information
 * from the specified request. If the input stream containing the request's
 * contents is repeatable, then this RequestEntity will report as being
 * repeatable.//from www .jav  a  2  s .c  o m
 *
 * @param request
 *            The details of the request being written out (content type,
 *            content length, and content).
 */
RepeatableInputStreamRequestEntity(final Request<?> request) {
    setChunked(false);

    /*
     * If we don't specify a content length when we instantiate our
     * InputStreamRequestEntity, then HttpClient will attempt to
     * buffer the entire stream contents into memory to determine
     * the content length.
     *
     * TODO: It'd be nice to have easier access to content length and
     *       content type from the request, instead of having to look
     *       directly into the headers.
     */
    long contentLength = -1;
    try {
        String contentLengthString = request.getHeaders().get("Content-Length");
        if (contentLengthString != null) {
            contentLength = Long.parseLong(contentLengthString);
        }
    } catch (NumberFormatException nfe) {
        log.warn("Unable to parse content length from request.  " + "Buffering contents in memory.");
    }

    String contentType = request.getHeaders().get("Content-Type");
    //        ThroughputMetricType type = ServiceMetricTypeGuesser
    //                .guessThroughputMetricType(request,
    //                        ServiceMetricType.UPLOAD_THROUGHPUT_NAME_SUFFIX,
    //                        ServiceMetricType.UPLOAD_BYTE_COUNT_NAME_SUFFIX);
    //        if (type == null) {
    inputStreamRequestEntity = new InputStreamEntity(request.getContent(), contentLength);
    //        } else {
    //            inputStreamRequestEntity = 
    //                new MetricInputStreamEntity(type, request.getContent(), contentLength);
    //        }
    inputStreamRequestEntity.setContentType(contentType);
    content = request.getContent();

    setContent(content);
    setContentType(contentType);
    setContentLength(contentLength);
}

From source file:com.amazonaws.http.RepeatableInputStreamRequestEntity.java

/**
 * Creates a new RepeatableInputStreamRequestEntity using the information
 * from the specified request. If the input stream containing the request's
 * contents is repeatable, then this RequestEntity will report as being
 * repeatable.//w w  w . ja va 2  s.  c o m
 *
 * @param request
 *            The details of the request being written out (content type,
 *            content length, and content).
 */
RepeatableInputStreamRequestEntity(final Request<?> request) {
    setChunked(false);

    /*
     * If we don't specify a content length when we instantiate our
     * InputStreamRequestEntity, then HttpClient will attempt to
     * buffer the entire stream contents into memory to determine
     * the content length.
     *
     * TODO: It'd be nice to have easier access to content length and
     *       content type from the request, instead of having to look
     *       directly into the headers.
     */
    long contentLength = -1;
    try {
        String contentLengthString = request.getHeaders().get("Content-Length");
        if (contentLengthString != null) {
            contentLength = Long.parseLong(contentLengthString);
        }
    } catch (NumberFormatException nfe) {
        log.warn("Unable to parse content length from request.  " + "Buffering contents in memory.");
    }

    String contentType = request.getHeaders().get("Content-Type");
    ThroughputMetricType type = ServiceMetricTypeGuesser.guessThroughputMetricType(request,
            ServiceMetricType.UPLOAD_THROUGHPUT_NAME_SUFFIX, ServiceMetricType.UPLOAD_BYTE_COUNT_NAME_SUFFIX);
    if (type == null) {
        inputStreamRequestEntity = new InputStreamEntity(request.getContent(), contentLength);
    } else {
        inputStreamRequestEntity = new MetricInputStreamEntity(type, request.getContent(), contentLength);
    }
    inputStreamRequestEntity.setContentType(contentType);
    content = request.getContent();

    setContent(content);
    setContentType(contentType);
    setContentLength(contentLength);
}

From source file:com.ksc.http.RepeatableInputStreamRequestEntity.java

/**
 * Creates a new RepeatableInputStreamRequestEntity using the information
 * from the specified request. If the input stream containing the request's
 * contents is repeatable, then this RequestEntity will report as being
 * repeatable.//from w ww .j av a 2s  . c  o m
 *
 * @param request
 *            The details of the request being written out (content type,
 *            content length, and content).
 */
public RepeatableInputStreamRequestEntity(final Request<?> request) {
    setChunked(false);

    /*
     * If we don't specify a content length when we instantiate our
     * InputStreamRequestEntity, then HttpClient will attempt to
     * buffer the entire stream contents into memory to determine
     * the content length.
     *
     * TODO: It'd be nice to have easier access to content length and
     *       content type from the request, instead of having to look
     *       directly into the headers.
     */
    long contentLength = -1;
    try {
        String contentLengthString = request.getHeaders().get("Content-Length");
        if (contentLengthString != null) {
            contentLength = Long.parseLong(contentLengthString);
        }
    } catch (NumberFormatException nfe) {
        log.warn("Unable to parse content length from request.  " + "Buffering contents in memory.");
    }

    String contentType = request.getHeaders().get("Content-Type");
    ThroughputMetricType type = ServiceMetricTypeGuesser.guessThroughputMetricType(request,
            ServiceMetricType.UPLOAD_THROUGHPUT_NAME_SUFFIX, ServiceMetricType.UPLOAD_BYTE_COUNT_NAME_SUFFIX);

    content = getContent(request);
    inputStreamRequestEntity = (type == null) ? new InputStreamEntity(content, contentLength)
            : new MetricInputStreamEntity(type, content, contentLength);
    inputStreamRequestEntity.setContentType(contentType);

    setContent(content);
    setContentType(contentType);
    setContentLength(contentLength);
}

From source file:eu.scape_project.fcrepo.integration.ReferencedContentIntellectualEntitiesIT.java

@Test
public void testIngestIntellectualEntitiesAsync() throws Exception {
    List<String> entityIds = new ArrayList(
            Arrays.asList("ref-async-1", "ref-async-2", "ref-async-3", "ref-async-4", "ref-async-5"));
    List<String> queueId = new ArrayList<>();
    for (String id : entityIds) {
        IntellectualEntity ie = TestUtil.createTestEntityWithMultipleRepresentations(id);
        HttpPost post = new HttpPost(SCAPE_URL + "/entity-async");
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        this.marshaller.serialize(ie, sink);
        post.setEntity(new InputStreamEntity(new ByteArrayInputStream(sink.toByteArray()), sink.size()));
        HttpResponse resp = this.client.execute(post);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        post.releaseConnection();//from  ww w. j a v a 2s. co m
    }

    Iterator<String> ids = entityIds.iterator();
    while (ids.hasNext()) {
        String id = ids.next();
        HttpGet get = new HttpGet(SCAPE_URL + "/lifecycle/" + id);
        HttpResponse resp = this.client.execute(get);
        assertEquals(200, resp.getStatusLine().getStatusCode());
        get.releaseConnection();
        LifecycleState state = (LifecycleState) this.marshaller.deserialize(resp.getEntity().getContent());
        if (state.getState().equals(LifecycleState.State.INGESTED)) {
            //                System.out.println(id + " was ingested");
            ids.remove();
        } else if (state.getState().equals(LifecycleState.State.INGESTING)) {
            //                System.out.println(id + " is currently ingesting");
        } else {
            throw new Exception("this should not happen!");
        }
        if (!ids.hasNext()) {
            ids = entityIds.iterator();
        }
    }
}

From source file:com.ettrema.httpclient.TransferService.java

public HttpResult put(String encodedUrl, InputStream content, Long contentLength, String contentType,
        ProgressListener listener) {//from  w w  w  .  j a va2  s . c  o m
    LogUtils.trace(log, "put: ", encodedUrl);
    notifyStartRequest();
    String s = encodedUrl;
    HttpPut p = new HttpPut(s);

    NotifyingFileInputStream notifyingIn = null;
    try {
        notifyingIn = new NotifyingFileInputStream(content, contentLength, s, listener);
        HttpEntity requestEntity;
        if (contentLength == null) {
            throw new RuntimeException("Content length for input stream is null, you must provide a length");
        } else {
            requestEntity = new InputStreamEntity(notifyingIn, contentLength);
        }
        p.setEntity(requestEntity);
        return Utils.executeHttpWithResult(client, p, null);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeQuietly(notifyingIn);
        notifyFinishRequest();
    }
}

From source file:com.autonomy.aci.client.services.impl.DocumentProcessorTest.java

@Test
public void testConvertACIResponseToDOMSAXException() throws AciErrorException, IOException {
    try {//ww w .  j  a  v a 2  s  .  c o m
        // Setup with a proper XML response file...
        final BasicHttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
        response.setEntity(
                new InputStreamEntity(getClass().getResourceAsStream("/MalformedAciException.xml"), -1));

        // Set the AciResponseInputStream...
        final AciResponseInputStream stream = new AciResponseInputStreamImpl(response);

        // Process...
        processor.process(stream);
        fail("Should have raised an ProcessorException.");
    } catch (final ProcessorException pe) {
        // Check for the correct causes...
        assertThat("Cause not correct.", pe.getCause(), is(instanceOf(SAXException.class)));
    }
}

From source file:edu.wisc.cypress.dao.taxstmt.RestTaxStatementDaoTest.java

protected HttpResponse setupHttpClient(InputStream taxStatementsStream, String contentType)
        throws IOException, ClientProtocolException {
    final HttpResponse httpResponse = mock(HttpResponse.class);
    when(httpClient.execute(any(HttpUriRequest.class), any(HttpContext.class))).thenReturn(httpResponse);
    when(httpResponse.getStatusLine()).thenReturn(
            new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase()));
    when(httpResponse.getAllHeaders())/*from w w  w  .  j a  va 2s . c om*/
            .thenReturn(new Header[] { new BasicHeader("Content-Type", contentType) });
    when(httpResponse.getEntity()).thenReturn(new InputStreamEntity(taxStatementsStream, -1));

    return httpResponse;
}