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.apache.hadoop.gateway.dispatch.HttpClientDispatch.java

protected HttpEntity createRequestEntity(HttpServletRequest request) throws IOException {

    String contentType = request.getContentType();
    int contentLength = request.getContentLength();
    InputStream contentStream = request.getInputStream();

    HttpEntity entity;//from  w w w.  j av a 2  s.  co  m
    if (contentType == null) {
        entity = new InputStreamEntity(contentStream, contentLength);
    } else {
        entity = new InputStreamEntity(contentStream, contentLength, ContentType.parse(contentType));
    }

    if ("true".equals(System.getProperty(GatewayConfig.HADOOP_KERBEROS_SECURED))) {

        //Check if delegation token is supplied in the request
        boolean delegationTokenPresent = false;
        String queryString = request.getQueryString();
        if (queryString != null) {
            delegationTokenPresent = queryString.startsWith("delegation=")
                    || queryString.contains("&delegation=");
        }
        if (!delegationTokenPresent && getReplayBufferSize() > 0) {
            entity = new CappedBufferHttpEntity(entity, getReplayBufferSize() * 1024);
        }
    }

    return entity;
}

From source file:de.derschimi.proxyservlet.TestServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    //initialize request attributes from caches if unset by a subclass by this point
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }//  w  w w.  ja  va 2  s  . c om
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;

    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        //  note: we don't bother ensuring we close the servletInputStream since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //the response is already "committed" now without any body to send
            //TODO copy response headers?
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
        //  reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException)
            throw (RuntimeException) e;
        if (e instanceof ServletException)
            throw (ServletException) e;
        //noinspection ConstantConditions
        if (e instanceof IOException)
            throw (IOException) e;
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is released
        if (proxyResponse != null)
            consumeQuietly(proxyResponse.getEntity());
        //Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
    }
}

From source file:org.dataconservancy.access.connector.HttpDcsConnector.java

@Override
public String uploadFile(InputStream is, long length) throws DcsClientFault {
    HttpPost post;/*from w  ww.  j  av a  2  s  . c o m*/

    try {
        post = new HttpPost(config.getUploadFileUrl().toURI());
    } catch (URISyntaxException e) {
        final String msg = "Malformed upload file endpoint URL " + config.getUploadFileUrl() + ": "
                + e.getMessage();
        log.debug(msg, e);
        throw new DcsClientFault(msg, e);
    }

    InputStreamEntity data = new InputStreamEntity(is, length);
    data.setContentType("binary/octet-stream");
    data.setChunked(true);
    post.setEntity(data);

    HttpResponse resp = execute(post, HttpStatus.SC_ACCEPTED);

    try {
        resp.getEntity().consumeContent();
    } catch (IOException e) {
        throw new DcsClientFault("Problem releasing resources", e);
    }

    Header header = resp.getFirstHeader("X-dcs-src");

    if (header == null) {
        throw new DcsClientFault(
                "Server response missing required header X-dcs-src for post to " + config.getUploadFileUrl());
    }

    return header.getValue();
}

From source file:com.hp.octane.integrations.services.rest.OctaneRestClientImpl.java

/**
 * This method should be the ONLY mean that creates Http Request objects
 *
 * @param octaneRequest Request data as it is maintained in Octane related flavor
 * @return pre-configured HttpUriRequest
 *///from   ww  w .ja v a 2 s .  c  o  m
private HttpUriRequest createHttpRequest(OctaneRequest octaneRequest) {
    HttpUriRequest request;
    RequestBuilder requestBuilder;

    //  create base request by METHOD
    if (octaneRequest.getMethod().equals(HttpMethod.GET)) {
        requestBuilder = RequestBuilder.get(octaneRequest.getUrl());
    } else if (octaneRequest.getMethod().equals(HttpMethod.DELETE)) {
        requestBuilder = RequestBuilder.delete(octaneRequest.getUrl());
    } else if (octaneRequest.getMethod().equals(HttpMethod.POST)) {
        requestBuilder = RequestBuilder.post(octaneRequest.getUrl());
        requestBuilder
                .addHeader(new BasicHeader(RestService.CONTENT_ENCODING_HEADER, RestService.GZIP_ENCODING));
        requestBuilder.setEntity(new GzipCompressingEntity(
                new InputStreamEntity(octaneRequest.getBody(), ContentType.APPLICATION_JSON)));
    } else if (octaneRequest.getMethod().equals(HttpMethod.PUT)) {
        requestBuilder = RequestBuilder.put(octaneRequest.getUrl());
        requestBuilder
                .addHeader(new BasicHeader(RestService.CONTENT_ENCODING_HEADER, RestService.GZIP_ENCODING));
        requestBuilder.setEntity(new GzipCompressingEntity(
                new InputStreamEntity(octaneRequest.getBody(), ContentType.APPLICATION_JSON)));
    } else {
        throw new RuntimeException("HTTP method " + octaneRequest.getMethod() + " not supported");
    }

    //  set custom headers
    if (octaneRequest.getHeaders() != null) {
        for (Map.Entry<String, String> e : octaneRequest.getHeaders().entrySet()) {
            requestBuilder.setHeader(e.getKey(), e.getValue());
        }
    }

    //  set system headers
    requestBuilder.setHeader(CLIENT_TYPE_HEADER, CLIENT_TYPE_VALUE);

    request = requestBuilder.build();
    return request;
}

From source file:com.reachcall.pretty.http.ProxyServlet.java

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Match match = (Match) req.getAttribute("match");
    HttpPut method = new HttpPut(match.toURL());
    copyHeaders(req, method);/*  www  .j  av  a  2  s .co m*/

    method.setEntity(new InputStreamEntity(req.getInputStream(), req.getContentLength()));

    this.execute(match, method, req, resp);
}

From source file:httpmultiplexer.httpproxy.ProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    // duplicate request before processing it
    HttpServletRequest duplicatedServletRequest;
    duplicatedServletRequest = servletRequest;

    // send another request to second target host
    duplicateRequest(duplicatedServletRequest);

    //initialize request attributes from caches if unset by a subclass by this point
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }// w  w  w.  j  a  va2s.co m
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    //note: we won't transfer the protocol version because I'm not sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;
    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        //  note: we don't bother ensuring we close the servletInputStream since the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        if (doLog) {
            _logger.info("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //the response is already "committed" now without any body to send
            //TODO copy response headers?
            return;
        }

        // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the
        //  reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is released
        if (proxyResponse != null) {
            consumeQuietly(proxyResponse.getEntity());
        }
        //Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
    }

}

From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    //initialize request attributes from caches if unset by a subclass by this point
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }/*from  ww  w .  j a v a  2  s.  c  om*/
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    // note: we won't transfer the protocol version because I'm not 
    // sure it would truly be compatible
    String method = servletRequest.getMethod();
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);
    HttpRequest proxyRequest;
    //spec: RFC 2616, sec 4.3: either of these two headers signal that there is
    //a message body.
    if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null
            || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) {
        HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri);
        // Add the input entity (streamed)
        // note: we don't bother ensuring we close the servletInputStream since 
        // the container handles it
        eProxyRequest.setEntity(
                new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength()));
        proxyRequest = eProxyRequest;
    } else {
        proxyRequest = new BasicHttpRequest(method, proxyRequestUri);
    }

    copyRequestHeaders(servletRequest, proxyRequest);

    setXForwardedForHeader(servletRequest, proxyRequest);

    HttpResponse proxyResponse = null;
    try {
        // Execute the request
        if (doLog) {
            log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- "
                    + proxyRequest.getRequestLine().getUri());
        }
        HttpHost httpHost = getTargetHost(servletRequest);
        proxyResponse = proxyClient.execute(httpHost, proxyRequest);

        // Process the response
        int statusCode = proxyResponse.getStatusLine().getStatusCode();

        if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) {
            //the response is already "committed" now without any body to send
            //TODO copy response headers?
            return;
        }

        // Pass the response code. This method with the "reason phrase" is 
        //deprecated but it's the only way to pass the reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase());

        copyResponseHeaders(proxyResponse, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(proxyResponse, servletResponse);

    } catch (Exception e) {
        //abort request, according to best practice with HttpClient
        if (proxyRequest instanceof AbortableHttpRequest) {
            AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest;
            abortableHttpRequest.abort();
        }
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    } finally {
        // make sure the entire entity was consumed, so the connection is released
        if (proxyResponse != null) {
            consumeQuietly(proxyResponse.getEntity());
        }
        //Note: Don't need to close servlet outputStream:
        // http://stackoverflow.com/questions/1159168/should-one-call-close-on
        //-httpservletresponse-getoutputstream-getwriter
    }
}

From source file:org.commonjava.web.json.test.WebFixture.java

public HttpResponse put(final String url, final int status, final InputStream stream, final String contentType,
        final int contentLength) throws Exception {
    final HttpPut request = new HttpPut(url);
    request.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
    request.setEntity(new InputStreamEntity(stream, contentLength));

    try {/*from  w w w .  j  av  a2  s .  c  o  m*/
        final HttpResponse response = http.execute(request);

        assertThat(response.getStatusLine().getStatusCode(), equalTo(status));

        return response;
    } finally {
        request.abort();
    }
}

From source file:com.fujitsu.dc.test.jersey.DcRestAdapter.java

/**
 * PUT??.//from   w  w w  . j  a  va 2s.  co  m
 * @param url ?URL
 * @param contentType 
 * @param is PUT?
 * @return HttpPut
 * @throws DcException DAO
 */
protected final HttpPut makePutRequestByStream(final String url, final String contentType, final InputStream is)
        throws DcException {
    HttpPut request = new HttpPut(url);
    InputStreamEntity body;
    body = new InputStreamEntity(is, -1);
    Boolean chunked = true;
    if (chunked != null) {
        body.setChunked(chunked);
    }
    request.setEntity(body);
    return request;
}